Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix deprecation warnig in packing.py and replace .format() with f-strings where possible. #1192

Merged
merged 16 commits into from
Aug 19, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
52 changes: 22 additions & 30 deletions mbuild/compound.py
Original file line number Diff line number Diff line change
Expand Up @@ -750,8 +750,8 @@ def label_rigid_bodies(self, discrete_bodies=None, rigid_particles=None):
if self.root.max_rigid_id is not None:
rigid_id = self.root.max_rigid_id + 1
warn(
"{} rigid bodies already exist. Incrementing 'rigid_id'"
"starting from {}.".format(rigid_id, rigid_id)
f"{rigid_id} rigid bodies already exist. Incrementing 'rigid_id'"
f"starting from {rigid_id}."
)
else:
rigid_id = 0
Expand Down Expand Up @@ -935,9 +935,7 @@ def add(
if containment:
if new_child.parent is not None:
raise MBuildError(
"Part {} already has a parent: {}".format(
new_child, new_child.parent
)
f"Part {new_child} already has a parent: {new_child.parent}"
)
self.children.append(new_child)
new_child.parent = self
Expand All @@ -956,7 +954,7 @@ def add(

# Add new_part to labels. Does not currently support batch add.
if label is None:
label = "{0}[$]".format(new_child.name)
label = f"{new_child.name}[$]"

if label.endswith("[$]"):
label = label[:-3]
Expand Down Expand Up @@ -1121,7 +1119,7 @@ def _check_if_empty(child):
if "port" in label:
label = "port[$]"
else:
label = "{0}[$]".format(child.name)
label = f"{child.name}[$]"

if label.endswith("[$]"):
label = label[:-3]
Expand Down Expand Up @@ -1656,8 +1654,8 @@ def xyz(self, arrnx3):
if not self.children:
if not arrnx3.shape[0] == 1:
raise ValueError(
"Trying to set position of {} with more than one"
"coordinate: {}".format(self, arrnx3)
f"Trying to set position of {self} with more than one"
f"coordinate: {arrnx3}"
)
self.pos = np.squeeze(arrnx3)
else:
Expand All @@ -1678,8 +1676,8 @@ def xyz_with_ports(self, arrnx3):
if not self.children:
if not arrnx3.shape[0] == 1:
raise ValueError(
"Trying to set position of {} with more than one"
"coordinate: {}".format(self, arrnx3)
f"Trying to set position of {self} with more than one"
f"coordinate: {arrnx3}"
)
self.pos = np.squeeze(arrnx3)
else:
Expand Down Expand Up @@ -2631,11 +2629,9 @@ def _energy_minimize_openmm(

else:
warn(
"OpenMM Force {} is "
f"OpenMM Force {type(force).__name__} is "
"not currently supported in _energy_minimize_openmm. "
"This Force will not be updated!".format(
type(force).__name__
)
"This Force will not be updated!"
)

simulation.context.setPositions(to_parmed.positions)
Expand Down Expand Up @@ -2766,11 +2762,9 @@ def _energy_minimize_openbabel(
particle._element = element_from_name(particle.name)
except ElementError:
raise MBuildError(
"No element assigned to {}; element could not be"
"inferred from particle name {}. Cannot perform"
"an energy minimization.".format(
particle, particle.name
)
f"No element assigned to {particle}; element could not be"
f"inferred from particle name {particle.name}. Cannot perform"
"an energy minimization."
)
# Create a dict containing particle id and associated index to speed up looping
particle_idx = {
Expand Down Expand Up @@ -2930,10 +2924,10 @@ def _energy_minimize_openbabel(
ff = openbabel.OBForceField.FindForceField(forcefield)
if ff is None:
raise MBuildError(
"Force field '{}' not supported for energy "
f"Force field '{forcefield}' not supported for energy "
"minimization. Valid force fields are 'MMFF94', "
"'MMFF94s', 'UFF', 'GAFF', and 'Ghemical'."
"".format(forcefield)
""
)
warn(
"Performing energy minimization using the Open Babel package. "
Expand Down Expand Up @@ -3594,19 +3588,17 @@ def __repr__(self):
descr.append(self.name + " ")

if self.children:
descr.append("{:d} particles, ".format(self.n_particles))
descr.append("{:d} bonds, ".format(self.n_bonds))
descr.append(f"{self.n_particles} particles, ")
descr.append(f"{self.n_bonds} bonds, ")
if self.box is not None:
descr.append("System box: {}, ".format(self.box))
descr.append(f"System box: {self.box}, ")
else:
descr.append("non-periodic, ")
else:
descr.append(
"pos=({}), ".format(np.array2string(self.pos, precision=4))
)
descr.append("{:d} bonds, ".format(self.n_direct_bonds))
descr.append(f"pos=({np.array2string(self.pos, precision=4)}), ")
descr.append(f"{self.n_direct_bonds} bonds, ")

descr.append("id: {}>".format(id(self)))
descr.append(f"id: {id(self)}>")
return "".join(descr)

def _clone(self, clone_of=None, root_container=None):
Expand Down
10 changes: 5 additions & 5 deletions mbuild/conversion.py
Original file line number Diff line number Diff line change
Expand Up @@ -411,8 +411,8 @@ def load_file(
tmp = read_xyz(filename)
if tmp.n_particles != compound.n_particles:
raise ValueError(
"Number of atoms in {filename}"
"does not match {compound}".format(**locals())
f"Number of atoms in {filename}"
f"does not match {compound}"
)
ref_and_compound = zip(
tmp._particles(include_ports=False),
Expand Down Expand Up @@ -583,7 +583,7 @@ def from_parmed(
name=str(atom.name), pos=pos, element=element
)
atom_list.append(new_atom)
atom_label_list.append("{0}[$]".format(atom.name))
atom_label_list.append(f"{atom.name}[$]")
atom_mapping[atom] = new_atom
parent_compound.add(atom_list, label=atom_label_list)
if infer_hierarchy:
Expand Down Expand Up @@ -697,7 +697,7 @@ def from_trajectory(
element=element,
)
atom_list.append(new_atom)
atom_label_list.append("{0}[$]".format(atom.name))
atom_label_list.append(f"{atom.name}[$]")
atom_mapping[atom] = new_atom

parent_cmpd.add(atom_list, label=atom_label_list)
Expand Down Expand Up @@ -1093,7 +1093,7 @@ def save(
saver = None

if os.path.exists(filename) and not overwrite:
raise IOError("{0} exists; not overwriting".format(filename))
raise IOError(f"{filename} exists; not overwriting")

if not parmed_kwargs:
parmed_kwargs = {}
Expand Down
8 changes: 4 additions & 4 deletions mbuild/coordinate_transform.py
Original file line number Diff line number Diff line change
Expand Up @@ -321,8 +321,8 @@ def _create_equivalence_transform(equiv):
isinstance(pair[0], Compound) and isinstance(pair[1], Compound)
):
raise ValueError(
"Equivalence pair type mismatch: pair[0] is a {0} "
"and pair[1] is a {1}".format(type(pair[0]), type(pair[1]))
f"Equivalence pair type mismatch: pair[0] is a {pair[0]} "
f"and pair[1] is a {pair[1]}"
)

if not pair[0].children:
Expand Down Expand Up @@ -546,7 +546,7 @@ def x_axis_transform(
"x_axis_transform, y_axis_transform, and z_axis_transform only "
"accept mb.Compounds, list-like of size 3, or None for the "
"point_on_x_axis parameter. User passed type: "
"{}.".format(type(point_on_x_axis))
f"{point_on_x_axis}."
)
if point_on_xy_plane is None:
point_on_xy_plane = np.array([1.0, 1.0, 0.0])
Expand All @@ -559,7 +559,7 @@ def x_axis_transform(
"x_axis_transform, y_axis_transform, and z_axis_transform only "
"accept mb.Compounds, list-like of size 3, or None for the "
"point_on_xy_plane parameter. User passed type: "
"{}.".format(type(point_on_xy_plane))
f"{point_on_xy_plane}."
)

atom_positions = compound.xyz_with_ports
Expand Down
69 changes: 29 additions & 40 deletions mbuild/lattice.py
Original file line number Diff line number Diff line change
Expand Up @@ -273,25 +273,25 @@ def _validate_lattice_spacing(self, lattice_spacing):
lattice_spacing = lattice_spacing.reshape((3,))
if np.shape(lattice_spacing) != (self.dimension,):
raise ValueError(
"Lattice spacing should be a vector of size:({},). Please "
f"Lattice spacing should be a vector of size:({self.dimension},). Please "
"include lattice spacing of size >= 0 depending on desired "
"dimensionality.".format(self.dimension)
"dimensionality."
)
else:
raise ValueError(
"No lattice_spacing provided. Please provide lattice spacing's "
"that are >= 0. with size ({},)".format((self.dimension))
f"that are >= 0. with size ({self.dimension},)"
)

if np.any(np.isnan(lattice_spacing)):
raise ValueError(
"None type or NaN type values present in lattice_spacing: "
"{}.".format(lattice_spacing)
f"{lattice_spacing}."
)
elif np.any(lattice_spacing < 0.0):
raise ValueError(
"Negative lattice spacing value. One of the spacing: {} is "
"negative.".format(lattice_spacing)
f"Negative lattice spacing value. One of the spacing: {lattice_spacing} is "
"negative."
)

self.lattice_spacing = lattice_spacing
Expand Down Expand Up @@ -320,20 +320,20 @@ def _validate_angles(self, angles):
raise ValueError("Angles cannot be 180.0 or 0.0")
else:
raise ValueError(
"Angles sum: {} is either greater than 360.0 or less than "
"-360.0".format(np.sum(tempAngles))
f"Angles sum: {np.sum(tempAngles)} is either greater than 360.0 or less than "
"-360.0"
)

for subset in it.permutations(tempAngles, r=self.dimension):
if not subset[0] < np.sum(tempAngles) - subset[0]:
raise ValueError(
"Each angle provided must be less than the sum of the "
"other angles. {} is greater.".format(subset[0])
f"other angles. {subset[0]} is greater."
)
else:
raise ValueError(
"Incorrect array size. When converted to a Numpy array, the "
"shape is: {}, expected {}.".format(np.shape(tempAngles), (3,))
"shape is: {np.shape(tempAngles)}, expected {(3,)}."
)
self.angles = tempAngles

Expand All @@ -358,24 +358,21 @@ def _validate_lattice_vectors(self, lattice_vectors):

if (self.dimension, self.dimension) != np.shape(lattice_vectors):
raise ValueError(
"Dimensionality of lattice_vectors is of shape {} not "
"{}.".format(
np.shape(lattice_vectors),
(self.dimension, self.dimension),
)
f"Dimensionality of lattice_vectors is of shape {np.shape(lattice_vectors)} not "
f"{(self.dimension, self.dimension)}."
)

det = np.linalg.det(lattice_vectors)
if abs(det) == 0.0:
raise ValueError(
"Co-linear vectors: {} have a determinant of 0.0. Does not "
"define a unit cell.".format(lattice_vectors)
f"Co-linear vectors: {lattice_vectors} have a determinant of 0.0. Does not "
"define a unit cell."
)

if det <= 0.0:
raise ValueError(
"Negative Determinant: the determinant of {} is negative, "
"indicating a left-handed system.".format(det)
f"Negative Determinant: the determinant of {det} is negative, "
"indicating a left-handed system."
)
self.lattice_vectors = lattice_vectors

Expand All @@ -398,29 +395,29 @@ def _validate_lattice_points(self, lattice_points):
pass
else:
raise TypeError(
"Incorrect type, lattice_points is of type {}, Expected "
"dict.".format(type(lattice_points))
f"Incorrect type, lattice_points is of type {type(lattice_points)}, Expected "
"dict."
)

for name, positions in lattice_points.items():
for pos in positions:
if len(pos) != self.dimension:
raise ValueError(
"Incorrect lattice point position size. lattice point "
"{} has location {}, which is inconsistent with the "
"dimension {}.".format(name, pos, self.dimension)
f"{name} has location {pos}, which is inconsistent with the "
"dimension {self.dimension}."
)
if pos is None:
raise ValueError(
"NoneType passed, expected float. None was passed in "
"as position for {}.".format(name)
f"as position for {name}."
)
for coord in pos:
if (coord is None) or (0 > coord) or (coord >= 1):
raise ValueError(
"Incorrect lattice point fractional coordinates. "
"Coordinates cannot be None, greater than or equal "
"to one, or negative. You passed {}.".format(coord)
f"to one, or negative. You passed {coord}."
)

self.lattice_points = self._check_for_overlap(lattice_points)
Expand Down Expand Up @@ -451,10 +448,8 @@ def _check_for_overlap(self, lattice_points):
if len(val) > 1:
raise ValueError(
"Overlapping lattice points: Lattice points overlap when "
"the unit cell is expanded to {}. This is an incorrect "
"perfect lattice. The offending points are: {}".format(
key, val
)
f"the unit cell is expanded to {key}. This is an incorrect "
f"perfect lattice. The offending points are: {val}"
)
return lattice_points

Expand Down Expand Up @@ -540,16 +535,14 @@ def _sanitize_populate_args(self, x, y, z):
z = int(z)
except (ValueError, TypeError):
raise ValueError(
"Cannot convert replication amounts into integers. x= {}, "
"y= {}, z= {} needs to be an int.".format(x, y, z)
f"Cannot convert replication amounts into integers. x= {x}, "
f"y= {y}, z= {z} needs to be an int."
)

for replication_amount, index in zip([x, y, z], range(3)):
if replication_amount < 1:
raise ValueError(
"Incorrect populate value: {} : {} is < 1. ".format(
error_dict[index], replication_amount
)
f"Incorrect populate value: {error_dict[index]} : {replication_amount} is < 1. "
)

return x, y, z
Expand Down Expand Up @@ -592,9 +585,7 @@ def populate(self, compound_dict=None, x=1, y=1, z=1):
pass
else:
raise TypeError(
"Compound dictionary is not a dict. {} was passed.".format(
type(compound_dict)
)
f"Compound dictionary is not a dict. {type(compound_dict)} was passed."
)

cell = defaultdict(list)
Expand Down Expand Up @@ -663,9 +654,7 @@ def populate(self, compound_dict=None, x=1, y=1, z=1):
err_type = type(compound_dict.get(key_id))
raise TypeError(
"Invalid type in provided Compound dictionary. For key "
"{}, type: {} was provided, not Compound.".format(
key_id, err_type
)
f"{key_id}, type: {err_type} was provided, not Compound."
)
# Raise warnings about assumed elements
for element in elementsSet:
Expand Down
Loading
Loading