diff --git a/.github/workflows/CI.yaml b/.github/workflows/CI.yaml index d2ce820de..1e799443c 100644 --- a/.github/workflows/CI.yaml +++ b/.github/workflows/CI.yaml @@ -13,16 +13,13 @@ on: jobs: test: if: github.event.pull_request.draft == false - name: mBuild Tests + name: mBuild Tests (python) runs-on: ${{ matrix.os }} strategy: fail-fast: false matrix: - os: [macOS-latest, macOS-13, ubuntu-latest] + os: [ubuntu-latest] python-version: ["3.9", "3.10", "3.11", "3.12"] - include: - - os: windows-latest - python-version: "3.12" defaults: run: @@ -60,6 +57,45 @@ jobs: name: mBuild-Coverage verbose: true files: ./coverage.xml + arch-test: + if: github.event.pull_request.draft == false + name: mBuild Tests (arch) + runs-on: ${{ matrix.os }} + strategy: + fail-fast: false + matrix: + os: [macOS-latest, macOS-13, ubuntu-latest, windows-latest] + python-version: ["3.12"] + + defaults: + run: + shell: bash -l {0} + + steps: + - uses: actions/checkout@v4 + name: Checkout Branch / Pull Request + + - name: Install Mamba (Linux) + uses: mamba-org/setup-micromamba@v1 + with: + environment-file: environment-dev.yml + create-args: >- + python=${{ matrix.python-version }} + if: runner.os != 'Windows' + + - name: Install Mamba (Windows) + uses: mamba-org/setup-micromamba@v1 + with: + environment-file: environment-dev-win.yml + create-args: >- + python=${{ matrix.python-version }} + if: runner.os == 'Windows' + + - name: Install Package + run: python -m pip install -e . + + - name: Test (OS -> ${{ matrix.os }} / Python -> ${{ matrix.python-version }}) + run: python -m pytest -v --cov=mbuild --cov-report=xml --cov-append --cov-config=setup.cfg --color yes --pyargs mbuild bleeding-edge-test: if: github.event.pull_request.draft == false @@ -77,7 +113,7 @@ jobs: uses: mamba-org/setup-micromamba@v1 with: environment-file: environment-dev.yml - create-args: python=3.11 + create-args: python=3.12 - name: Clone Foyer and GMSO run: | diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml index a59e69a3e..1c637c6c5 100644 --- a/.pre-commit-config.yaml +++ b/.pre-commit-config.yaml @@ -1,7 +1,6 @@ ci: autofix_commit_msg: | [pre-commit.ci] auto fixes from pre-commit.com hooks - for more information, see https://pre-commit.ci autofix_prs: true autoupdate_commit_msg: '[pre-commit.ci] pre-commit autoupdate' @@ -9,27 +8,25 @@ ci: skip: [] submodules: false repos: +- repo: https://github.com/astral-sh/ruff-pre-commit + # Ruff version. + rev: v0.7.0 + hooks: + # Run the linter. + - id: ruff + args: [--line-length=80, --fix] + # Run the formatter. + - id: ruff-format - repo: https://github.com/pre-commit/pre-commit-hooks rev: v5.0.0 hooks: - id: check-yaml - id: end-of-file-fixer - id: trailing-whitespace - exclude: setup.cfg -- repo: https://github.com/psf/black - rev: 24.10.0 - hooks: - - id: black - args: [--line-length=80] + - repo: https://github.com/pycqa/isort rev: 5.13.2 hooks: - id: isort name: isort (python) args: [--profile=black, --line-length=80] -- repo: https://github.com/pycqa/pydocstyle - rev: '6.3.0' - hooks: - - id: pydocstyle - exclude: ^(mbuild/tests/|docs/|devtools/|setup.py|setup.cfg|mbuild/formats/charmm_writer.py|mbuild/formats/gomc_conf_writer.py|mbuild/utils/specific_ff_to_residue.py) - args: [--convention=numpy] diff --git a/docs/conf.py b/docs/conf.py index 3b4f22dd6..4a777e90a 100755 --- a/docs/conf.py +++ b/docs/conf.py @@ -16,6 +16,7 @@ import sys import mock +import sphinx_rtd_theme # If extensions (or modules to document with autodoc) are in another directory, # add these directories to sys.path here. If the directory is relative to the @@ -205,7 +206,6 @@ # The theme to use for HTML and HTML Help pages. See the documentation for # a list of builtin themes. # html_theme = 'default' -import sphinx_rtd_theme html_theme = "sphinx_rtd_theme" hhtml_theme_path = [sphinx_rtd_theme.get_html_theme_path()] diff --git a/docs/sphinxext/notebook_sphinxext.py b/docs/sphinxext/notebook_sphinxext.py index 4c0d591a7..7fe3e8477 100644 --- a/docs/sphinxext/notebook_sphinxext.py +++ b/docs/sphinxext/notebook_sphinxext.py @@ -130,8 +130,6 @@ def setup(app): setup.config = app.config setup.confdir = app.confdir - app.add_node( - notebook_node, html=(visit_notebook_node, depart_notebook_node) - ) + app.add_node(notebook_node, html=(visit_notebook_node, depart_notebook_node)) app.add_directive("notebook", NotebookDirective) diff --git a/mbuild/__init__.py b/mbuild/__init__.py index 33dfcd2a1..f1e9084fc 100644 --- a/mbuild/__init__.py +++ b/mbuild/__init__.py @@ -1,3 +1,5 @@ +# ruff: noqa: F401 +# ruff: noqa: F403 """mBuild: a hierarchical, component based molecule builder.""" from mbuild.box import Box diff --git a/mbuild/bond_graph.py b/mbuild/bond_graph.py index 6cb32d4c9..3a470d5b0 100644 --- a/mbuild/bond_graph.py +++ b/mbuild/bond_graph.py @@ -39,8 +39,6 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. """ -from collections import defaultdict - import networkx as nx diff --git a/mbuild/box.py b/mbuild/box.py index 8a739db62..87f980eab 100644 --- a/mbuild/box.py +++ b/mbuild/box.py @@ -98,9 +98,7 @@ def from_uvec_lengths(cls, uvec, lengths, precision=None): scaled_vec = (uvec.T * lengths).T (alpha, beta, gamma) = _calc_angles(scaled_vec) - return cls( - lengths=lengths, angles=(alpha, beta, gamma), precision=precision - ) + return cls(lengths=lengths, angles=(alpha, beta, gamma), precision=precision) @classmethod def from_mins_maxs_angles(cls, mins, maxs, angles, precision=None): @@ -123,14 +121,10 @@ def from_vectors(cls, vectors, precision=None): Ly = np.linalg.norm(v2) Lz = np.linalg.norm(v3) lengths = (Lx, Ly, Lz) - return cls( - lengths=lengths, angles=(alpha, beta, gamma), precision=precision - ) + return cls(lengths=lengths, angles=(alpha, beta, gamma), precision=precision) @classmethod - def from_lengths_tilt_factors( - cls, lengths, tilt_factors=None, precision=None - ): + def from_lengths_tilt_factors(cls, lengths, tilt_factors=None, precision=None): """Generate a box from box lengths and tilt factors.""" (Lx, Ly, Lz) = lengths if tilt_factors is None: @@ -138,13 +132,9 @@ def from_lengths_tilt_factors( else: (xy, xz, yz) = tilt_factors - vecs = np.asarray( - [[Lx, 0.0, 0.0], [Ly * xy, Ly, 0.0], [Lz * xz, Lz * yz, Lz]] - ) + vecs = np.asarray([[Lx, 0.0, 0.0], [Ly * xy, Ly, 0.0], [Lz * xz, Lz * yz, Lz]]) (alpha, beta, gamma) = _calc_angles(vecs) - return cls( - lengths=lengths, angles=[alpha, beta, gamma], precision=precision - ) + return cls(lengths=lengths, angles=[alpha, beta, gamma], precision=precision) @classmethod def from_lo_hi_tilt_factors(cls, lo, hi, tilt_factors, precision=None): @@ -159,9 +149,7 @@ def from_lo_hi_tilt_factors(cls, lo, hi, tilt_factors, precision=None): yhi_bound = yhi + max([0.0, yz]) lengths = [xhi_bound - xlo_bound, yhi_bound - ylo_bound, zhi - zlo] - return cls.from_lengths_tilt_factors( - lengths=lengths, tilt_factors=tilt_factors - ) + return cls.from_lengths_tilt_factors(lengths=lengths, tilt_factors=tilt_factors) @property def vectors(self): @@ -327,8 +315,6 @@ def _lengths_angles_to_vectors(lengths, angles, precision): cos_b = np.clip(np.cos(beta), -1.0, 1.0) cos_g = np.clip(np.cos(gamma), -1.0, 1.0) - sin_a = np.clip(np.sin(alpha), -1.0, 1.0) - sin_b = np.clip(np.sin(beta), -1.0, 1.0) sin_g = np.clip(np.sin(gamma), -1.0, 1.0) a_vec = np.asarray([a, 0.0, 0.0]) @@ -376,9 +362,7 @@ def _normalize_box(vectors): sign = np.linalg.det(Q) R = R * sign - signs = np.diag( - np.diag(np.where(R < 0, -np.ones(R.shape), np.ones(R.shape))) - ) + signs = np.diag(np.diag(np.where(R < 0, -np.ones(R.shape), np.ones(R.shape)))) transformed_vecs = R.dot(signs) return _reduced_form_vectors(transformed_vecs.T) diff --git a/mbuild/coarse_graining.py b/mbuild/coarse_graining.py index 2e619afbf..e1eafceaa 100644 --- a/mbuild/coarse_graining.py +++ b/mbuild/coarse_graining.py @@ -113,9 +113,7 @@ def _clone(self, clone_of=None, root_container=None): if self.labels: for label, compound in self.labels.items(): if not isinstance(compound, list): - newone.labels[label] = compound._clone( - clone_of, root_container - ) + newone.labels[label] = compound._clone(clone_of, root_container) compound.referrers.add(clone_of[compound]) else: # compound is a list of compounds, so we create an empty @@ -150,13 +148,11 @@ def _create_proxy_compounds(real_thing, memo, particle_classes): proxy = Proxy(real_thing) memo[real_thing] = proxy - if not type(real_thing) in particle_classes: + if type(real_thing) not in particle_classes: if not is_leaf(real_thing): # Recurse only if it has parts. # Recursively create proxies for parts. for part in real_thing.children: - part_proxy = _create_proxy_compounds( - part, memo, particle_classes - ) + part_proxy = _create_proxy_compounds(part, memo, particle_classes) proxy.add(part_proxy) return proxy diff --git a/mbuild/compound.py b/mbuild/compound.py index 70f15fa42..e8966f46b 100644 --- a/mbuild/compound.py +++ b/mbuild/compound.py @@ -26,7 +26,6 @@ from mbuild.exceptions import MBuildError from mbuild.periodic_kdtree import PeriodicKDTree from mbuild.utils.decorators import experimental_feature -from mbuild.utils.exceptions import RemovedFuncError from mbuild.utils.io import import_, run_from_ipython from mbuild.utils.jsutils import overwrite_nglview_default @@ -48,9 +47,7 @@ def clone(existing_compound, clone_of=None, root_container=None): if clone_of is None: clone_of = dict() - newone = existing_compound._clone( - clone_of=clone_of, root_container=root_container - ) + newone = existing_compound._clone(clone_of=clone_of, root_container=root_container) existing_compound._clone_bonds(clone_of=clone_of) return newone @@ -317,7 +314,7 @@ def print_hierarchy(self, print_full=False, index=None, show_tree=True): ) # if index is specified, ensure we are not selecting an index out of range - if not index is None: + if index is not None: if index >= len(self.children): raise MBuildError( f"Index {index} out of range. The number of first level nodes in the tree is {len(self.children)}." @@ -391,7 +388,7 @@ def _get_hierarchy_nodup(self, level=0): identifier = f"{child.name}_{len(child.children)}_{child_string}_{child.n_particles}_{part_string}_{n_bonds}" - if not identifier in duplicates: + if identifier not in duplicates: duplicates[identifier] = [1, True] else: duplicates[identifier][0] += 1 @@ -507,9 +504,7 @@ def mass(self): f"Some particle of {self} does not have mass." "They will not be accounted for during this calculation." ) - filtered_masses = [ - mass for mass in particle_masses if mass is not None - ] + filtered_masses = [mass for mass in particle_masses if mass is not None] return sum(filtered_masses) if filtered_masses else None @staticmethod @@ -526,8 +521,7 @@ def _particle_mass(particle): def mass(self, value): if self._contains_only_ports() is False: raise MBuildError( - "Cannot set the mass of a Compound containing " - "children compounds" + "Cannot set the mass of a Compound containing " "children compounds" ) value = float(value) @@ -751,8 +745,7 @@ def add( # Check that bounding box is within box after adding compound if self.box and check_box_size: if ( - np.array(self.box.lengths) - < np.array(self.get_boundingbox().lengths) + np.array(self.box.lengths) < np.array(self.get_boundingbox().lengths) ).any(): warn( "After adding new Compound, Compound.box.lengths < " @@ -858,9 +851,7 @@ def reset_labels(self): if label is None: if "Port" in child.name: label = [ - key - for key, x in self.labels.items() - if id(x) == id(child) + key for key, x in self.labels.items() if id(x) == id(child) ][0] if "port" in label: label = "port[$]" @@ -892,9 +883,7 @@ def _prune_ghost_ports(self): def _remove(self, removed_part): """Worker for remove(). Removes bonds.""" if self.root.bond_graph.has_node(removed_part): - for neighbor in nx.neighbors( - self.root.bond_graph.copy(), removed_part - ): + for neighbor in nx.neighbors(self.root.bond_graph.copy(), removed_part): self.root.remove_bond((removed_part, neighbor)) self.root.bond_graph.remove_node(removed_part) @@ -963,11 +952,7 @@ def available_ports(self): """ from mbuild.port import Port - return [ - p - for p in self.labels.values() - if isinstance(p, Port) and not p.used - ] + return [p for p in self.labels.values() if isinstance(p, Port) and not p.used] def direct_bonds(self): """Return a list of particles that this particle bonds to. @@ -1081,8 +1066,7 @@ def add_bond(self, particle_pair, bond_order=None): "unspecified", ]: raise ValueError( - "Invalid bond_order given. Available bond orders are: " - "single", + "Invalid bond_order given. Available bond orders are: " "single", "double", "triple", "aromatic", @@ -1108,9 +1092,7 @@ def generate_bonds(self, name_a, name_b, dmin, dmax): """ if self.box is None: self.box = self.get_boundingbox() - particle_kdtree = PeriodicKDTree.from_compound( - compound=self, leafsize=10 - ) + particle_kdtree = PeriodicKDTree.from_compound(compound=self, leafsize=10) particle_array = np.array(list(self.particles())) added_bonds = list() for p1 in self.particles_by_name(name_a): @@ -1163,9 +1145,7 @@ def freud_generate_bonds( box = self.get_boundingbox() else: box = self.box - moved_positions = self.xyz - np.array( - [box.Lx / 2, box.Ly / 2, box.Lz / 2] - ) + moved_positions = self.xyz - np.array([box.Lx / 2, box.Ly / 2, box.Lz / 2]) # quadruple box lengths for non-periodic dimensions # since freud boxes are centered at the origin, extend box @@ -1176,16 +1156,14 @@ def freud_generate_bonds( freud_box = freud.box.Box.from_matrix(box.vectors.T) # not periodic in some dimensions, lets make them pseudo-periodic else: - tmp_lengths = [l for l in box.lengths] + tmp_lengths = [length for length in box.lengths] max_tmp_length = max(tmp_lengths) for i, is_periodic in enumerate(self.periodicity): if is_periodic: continue else: tmp_lengths[i] = tmp_lengths[i] + 4 * max_tmp_length - tmp_box = Box.from_lengths_angles( - lengths=tmp_lengths, angles=box.angles - ) + tmp_box = Box.from_lengths_angles(lengths=tmp_lengths, angles=box.angles) freud_box = freud.box.Box.from_matrix(tmp_box.vectors.T) freud_box.periodic = (True, True, True) @@ -1246,8 +1224,9 @@ def remove_bond(self, particle_pair): bond_vector = particle_pair[0].pos - particle_pair[1].pos if np.allclose(bond_vector, np.zeros(3)): warn( - "Particles {} and {} overlap! Ports will not be added." - "".format(*particle_pair) + "Particles {} and {} overlap! Ports will not be added." "".format( + *particle_pair + ) ) return distance = np.linalg.norm(bond_vector) @@ -1314,7 +1293,7 @@ def box(self): @box.setter def box(self, box): - if box is not None and type(box) != Box: + if box and not isinstance(box, Box): raise TypeError("box must be specified as an mbuild.Box") if self.port_particle and box is not None: raise ValueError("Ports cannot have a box") @@ -1402,9 +1381,7 @@ def xyz(self, arrnx3): ) self.pos = np.squeeze(arrnx3) else: - for atom, coords in zip( - self._particles(include_ports=False), arrnx3 - ): + for atom, coords in zip(self._particles(include_ports=False), arrnx3): atom.pos = coords @xyz_with_ports.setter @@ -1424,9 +1401,7 @@ def xyz_with_ports(self, arrnx3): ) self.pos = np.squeeze(arrnx3) else: - for atom, coords in zip( - self._particles(include_ports=True), arrnx3 - ): + for atom, coords in zip(self._particles(include_ports=True), arrnx3): atom.pos = coords @property @@ -1550,9 +1525,7 @@ def get_boundingbox(self, pad_box=None): for dim, val in enumerate(padding): vecs[dim][dim] = vecs[dim][dim] + val - bounding_box = Box.from_vectors( - vectors=np.asarray([vecs]).reshape(3, 3) - ) + bounding_box = Box.from_vectors(vectors=np.asarray([vecs]).reshape(3, 3)) return bounding_box def min_periodic_distance(self, xyz0, xyz1): @@ -1591,9 +1564,7 @@ def min_periodic_distance(self, xyz0, xyz1): raise MBuildError(f'Cannot calculate minimum periodic distance. ' f'No Box set for {self}') """ - warn( - f"No Box object set for {self}, using rectangular bounding box" - ) + warn(f"No Box object set for {self}, using rectangular bounding box") self.box = self.get_boundingbox() if np.allclose(self.box.angles, 90.0): d = np.where( @@ -1699,13 +1670,9 @@ def visualize( ) else: - raise RuntimeError( - "Visualization is only supported in Jupyter Notebooks." - ) + raise RuntimeError("Visualization is only supported in Jupyter Notebooks.") - def _visualize_py3dmol( - self, show_ports=False, color_scheme={}, bead_size=0.3 - ): + def _visualize_py3dmol(self, show_ports=False, color_scheme={}, bead_size=0.3): """Visualize the Compound using py3Dmol. Allows for visualization of a Compound within a Jupyter Notebook. @@ -1765,9 +1732,7 @@ def _visualize_py3dmol( return view - def _visualize_nglview( - self, show_ports=False, color_scheme={}, bead_size=0.3 - ): + def _visualize_nglview(self, show_ports=False, color_scheme={}, bead_size=0.3): """Visualize the Compound using nglview. Allows for visualization of a Compound within a Jupyter Notebook. @@ -1778,7 +1743,7 @@ def _visualize_nglview( Visualize Ports in addition to Particles """ nglview = import_("nglview") - mdtraj = import_("mdtraj") + mdtraj = import_("mdtraj") # noqa: F841 from mdtraj.geometry.sasa import _ATOMIC_RADII def remove_digits(x): @@ -1858,9 +1823,7 @@ def condense(self, inplace=True): # ancestor of the first particle is used as reference. # Hence, this called will return the lowest-level Compound # that is a molecule - ancestors = ancestors.intersection( - IndexedSet(particle.ancestors()) - ) + ancestors = ancestors.intersection(IndexedSet(particle.ancestors())) """Parse molecule information""" molecule_tag = ancestors[0] @@ -2177,12 +2140,11 @@ def energy_minimize( anchor_in_compound = True anchor_pos_old = anchor.pos - if anchor_in_compound == False: + if not anchor_in_compound: raise MBuildError( f"Anchor: {anchor} is not part of the Compound: {self}" "that you are trying to energy minimize." ) - original = clone(self) self._kick() extension = os.path.splitext(forcefield)[-1] openbabel_ffs = ["MMFF94", "MMFF94s", "UFF", "GAFF", "Ghemical"] @@ -2216,7 +2178,7 @@ def energy_minimize( if shift_com: self.translate_to(com) - if anchor_in_compound == True: + if anchor_in_compound: anchor_pos_new = anchor.pos delta = anchor_pos_old - anchor_pos_new self.translate(delta) @@ -2272,9 +2234,7 @@ def _energy_minimize_openmm( foyer = import_("foyer") to_parmed = self.to_parmed() - ff = foyer.Forcefield( - forcefield_files=forcefield_files, name=forcefield_name - ) + ff = foyer.Forcefield(forcefield_files=forcefield_files, name=forcefield_name) to_parmed = ff.apply(to_parmed) import openmm.unit as u @@ -2319,9 +2279,7 @@ def _energy_minimize_openmm( elif type(force).__name__ == "HarmonicAngleForce": for angle_index in range(force.getNumAngles()): - atom1, atom2, atom3, r0, k = force.getAngleParameters( - angle_index - ) + atom1, atom2, atom3, r0, k = force.getAngleParameters(angle_index) force.setAngleParameters( angle_index, atom1, atom2, atom3, r0, k * scale_angles ) @@ -2358,9 +2316,7 @@ def _energy_minimize_openmm( elif type(force).__name__ == "NonbondedForce": for nb_index in range(force.getNumParticles()): - charge, sigma, epsilon = force.getParticleParameters( - nb_index - ) + charge, sigma, epsilon = force.getParticleParameters(nb_index) force.setParticleParameters( nb_index, charge, sigma, epsilon * scale_nonbonded ) @@ -2380,9 +2336,7 @@ def _energy_minimize_openmm( # Run energy minimization through OpenMM simulation.minimizeEnergy(maxIterations=steps) reporter = PDBReporter(os.path.join(tmp_dir, "minimized.pdb"), 1) - reporter.report( - simulation, simulation.context.getState(getPositions=True) - ) + reporter.report(simulation, simulation.context.getState(getPositions=True)) def _check_openbabel_constraints( self, @@ -2604,18 +2558,16 @@ def _energy_minimize_openbabel( self._check_openbabel_constraints([p1], successors_list) if len(p1.children) == 0: - pid = ( - particle_idx[id(p1)] + 1 - ) # openbabel indices start at 1 + pid = particle_idx[id(p1)] + 1 # openbabel indices start at 1 - if all_true == True: + if all_true: ob_constraints.AddAtomConstraint(pid) else: - if dims[0] == True: + if dims[0]: ob_constraints.AddAtomXConstraint(pid) - if dims[1] == True: + if dims[1]: ob_constraints.AddAtomYConstraint(pid) - if dims[2] == True: + if dims[2]: ob_constraints.AddAtomZConstraint(pid) else: for particle in p1.particles(): @@ -2623,14 +2575,14 @@ def _energy_minimize_openbabel( particle_idx[id(particle)] + 1 ) # openbabel indices start at 1 - if all_true == True: + if all_true: ob_constraints.AddAtomConstraint(pid) else: - if dims[0] == True: + if dims[0]: ob_constraints.AddAtomXConstraint(pid) - if dims[1] == True: + if dims[1]: ob_constraints.AddAtomYConstraint(pid) - if dims[2] == True: + if dims[2]: ob_constraints.AddAtomZConstraint(pid) if ignore_compounds is not None: @@ -2645,9 +2597,7 @@ def _energy_minimize_openbabel( for ignore in ignore_compounds: p1 = ignore if len(p1.children) == 0: - pid = ( - particle_idx[id(p1)] + 1 - ) # openbabel indices start at 1 + pid = particle_idx[id(p1)] + 1 # openbabel indices start at 1 ob_constraints.AddIgnore(pid) else: @@ -2954,9 +2904,7 @@ def to_hoomdsnapshot(self, **kwargs): # Interface to Trajectory for reading/writing .pdb and .mol2 files. # ----------------------------------------------------------------- - def from_trajectory( - self, traj, frame=-1, coords_only=False, infer_hierarchy=True - ): + def from_trajectory(self, traj, frame=-1, coords_only=False, infer_hierarchy=True): """Extract atoms and bonds from a md.Trajectory. Will create sub-compounds for every chain if there is more than one @@ -2985,9 +2933,7 @@ def from_trajectory( infer_hierarchy=True, ) - def to_trajectory( - self, include_ports=False, chains=None, residues=None, box=None - ): + def to_trajectory(self, include_ports=False, chains=None, residues=None, box=None): """Convert to an md.Trajectory and flatten the compound. Parameters @@ -3263,9 +3209,7 @@ def to_intermol(self, molecule_types=None): # pragma: no cover -------- mbuild.conversion.to_intermol """ - return conversion.to_intermol( - compound=self, molecule_types=molecule_types - ) + return conversion.to_intermol(compound=self, molecule_types=molecule_types) def get_smiles(self): """Get SMILES string for compound. @@ -3366,9 +3310,7 @@ def _clone(self, clone_of=None, root_container=None): if self.labels: for label, compound in self.labels.items(): if not isinstance(compound, list): - newone.labels[label] = compound._clone( - clone_of, root_container - ) + newone.labels[label] = compound._clone(clone_of, root_container) compound.referrers.add(clone_of[compound]) else: # compound is a list of compounds, so we create an empty diff --git a/mbuild/conversion.py b/mbuild/conversion.py index 7cb168017..b056ce3ec 100644 --- a/mbuild/conversion.py +++ b/mbuild/conversion.py @@ -21,14 +21,7 @@ from mbuild.box import Box from mbuild.exceptions import MBuildError from mbuild.formats.json_formats import compound_from_json, compound_to_json -from mbuild.utils.io import ( - has_gmso, - has_mdtraj, - has_networkx, - has_openbabel, - has_rdkit, - import_, -) +from mbuild.utils.io import has_mdtraj, has_openbabel, import_ def load( @@ -241,9 +234,8 @@ def load_smiles( backend = "rdkit" if backend == "rdkit": - rdkit = import_("rdkit") + rdkit = import_("rdkit") # noqa: F841 from rdkit import Chem - from rdkit.Chem import AllChem if test_path.exists(): # assuming this is a smi file now @@ -365,9 +357,7 @@ def load_file( # in its own folder. E.g., you build a system from ~/foo.py and it imports # from ~/bar/baz.py where baz.py loads ~/bar/baz.pdb. if relative_to_module: - filename = str( - Path(sys.modules[relative_to_module].__file__).parent / filename - ) + filename = str(Path(sys.modules[relative_to_module].__file__).parent / filename) extension = Path(filename).suffix if not backend: @@ -486,9 +476,7 @@ def from_parmed( for pmd_atom, particle in zip( structure.atoms, compound.particles(include_ports=False) ): - particle.pos = ( - np.array([pmd_atom.xx, pmd_atom.xy, pmd_atom.xz]) / 10 - ) + particle.pos = np.array([pmd_atom.xx, pmd_atom.xy, pmd_atom.xz]) / 10 return compound elif not compound and coords_only: raise MBuildError("coords_only=True but host compound is not provided") @@ -499,7 +487,6 @@ def from_parmed( # Convert parmed structure to mbuild compound atom_mapping = dict() - chain_id = None chains = defaultdict(list) # Build up chains dict @@ -532,9 +519,7 @@ def from_parmed( element = element_from_atomic_number(atom.atomic_number) except ElementError: element = None - new_atom = mb.Particle( - name=str(atom.name), pos=pos, element=element - ) + new_atom = mb.Particle(name=str(atom.name), pos=pos, element=element) atom_list.append(new_atom) atom_label_list.append(f"{atom.name}[$]") atom_mapping[atom] = new_atom @@ -593,9 +578,7 @@ def from_trajectory( if compound and coords_only: if traj.n_atoms != compound.n_particles: raise ValueError( - "Number of atoms in {traj} does not match {compound}".format( - **locals() - ) + "Number of atoms in {traj} does not match {compound}".format(**locals()) ) if None in compound._particles(include_ports=False): raise ValueError("Some particles are None") @@ -639,9 +622,7 @@ def from_trajectory( atom_label_list = [] for atom in res.atoms: try: - element = element_from_atomic_number( - atom.element.atomic_number - ) + element = element_from_atomic_number(atom.element.atomic_number) except ElementError: element = None new_atom = mb.Particle( @@ -980,16 +961,12 @@ def save( raise IOError(f"{filename} exists; not overwriting") if compound.charge: if round(compound.charge, 4) != 0.0: - warn( - f"System is not charge neutral. Total charge is {compound.charge}." - ) + warn(f"System is not charge neutral. Total charge is {compound.charge}.") extension = os.path.splitext(filename)[-1] # Keep json stuff with internal mbuild method if extension == ".json": - compound_to_json( - compound, file_path=filename, include_ports=include_ports - ) + compound_to_json(compound, file_path=filename, include_ports=include_ports) return # Savers supported by mbuild.formats @@ -1089,9 +1066,7 @@ def catalog_bondgraph_type(compound, bond_graph=None): return "multiple_graphs" -def pull_residues( - compound, segment_level=0, include_base_level=False, bond_graph=None -): +def pull_residues(compound, segment_level=0, include_base_level=False, bond_graph=None): """Pull residues from a Compound object. Search class instance for completed compounds based on the number of @@ -1140,9 +1115,7 @@ def pull_residues( elif segment_level == 0 and compound_graphtype == "one_graph": # At top level and a single molecule is here residuesList.append(id(compound)) - elif ( - compound_graphtype == "particle_graph" - ): # Currently at the particle level + elif compound_graphtype == "particle_graph": # Currently at the particle level if include_base_level: # only consider adding particles if specified residuesList.append(id(compound)) @@ -1323,9 +1296,7 @@ def to_parmed( if residues and tmp_check in residues: if parent not in compound_residue_map: current_residue = pmd.Residue( - parent.name - if parent.name - else default_residue.name + parent.name if parent.name else default_residue.name ) compound_residue_map[parent] = current_residue atom_residue_map[atom] = current_residue @@ -1396,9 +1367,7 @@ def to_parmed( return structure -def to_trajectory( - compound, include_ports=False, chains=None, residues=None, box=None -): +def to_trajectory(compound, include_ports=False, chains=None, residues=None, box=None): """Convert to an md.Trajectory and flatten the compound. Parameters @@ -1475,7 +1444,7 @@ def _to_topology(compound, atom_list, chains=None, residues=None): -------- mdtraj.Topology : Details on the mdtraj Topology object """ - md = import_("mdtraj") + md = import_("mdtraj") # noqa: F841 from mdtraj.core.element import get_by_symbol from mdtraj.core.topology import Topology @@ -1511,9 +1480,7 @@ def _to_topology(compound, atom_list, chains=None, residues=None): if parent not in compound_chain_map: current_chain = top.add_chain() compound_chain_map[parent] = current_chain - current_residue = top.add_residue( - "RES", current_chain - ) + current_residue = top.add_residue("RES", current_chain) break else: current_chain = default_chain @@ -1715,9 +1682,8 @@ def to_rdkit(compound): ------- rdkit.Chem.RWmol """ - rdkit = import_("rdkit") + rdkit = import_("rdkit") # noqa: F841 from rdkit import Chem - from rdkit.Chem import AllChem for particle in compound.particles(): if particle.element is None: @@ -1750,9 +1716,7 @@ def to_rdkit(compound): temp_atom = Chem.Atom(particle.element.atomic_number) # this next line is necessary to prevent rdkit from adding hydrogens # this will also set the label to be the element with particle index - temp_atom.SetProp( - "atomLabel", f"{temp_atom.GetSymbol()}:{p_dict[particle]}" - ) + temp_atom.SetProp("atomLabel", f"{temp_atom.GetSymbol()}:{p_dict[particle]}") temp_mol.AddAtom(temp_atom) @@ -1783,8 +1747,7 @@ def to_smiles(compound, backend="pybel"): mol = to_pybel(compound) warn( - "The bond orders will be guessed using pybel" - "OBMol.PerceviedBondOrders()" + "The bond orders will be guessed using pybel" "OBMol.PerceviedBondOrders()" ) mol.OBMol.PerceiveBondOrders() smiles_string = mol.write("smi").replace("\t", " ").split(" ")[0] @@ -1826,9 +1789,7 @@ def to_networkx(compound, names_only=False): nodes.append(compound.name + "_" + str(id(compound))) else: nodes.append(compound) - nodes, edges = _iterate_children( - compound, nodes, edges, names_only=names_only - ) + nodes, edges = _iterate_children(compound, nodes, edges, names_only=names_only) graph = nx.DiGraph() graph.add_nodes_from(nodes) @@ -1846,17 +1807,13 @@ def _iterate_children(compound, nodes, edges, names_only=False): for child in compound.children: if names_only: unique_name = child.name + "_" + str(id(child)) - unique_name_parent = ( - child.parent.name + "_" + str((id(child.parent))) - ) + unique_name_parent = child.parent.name + "_" + str((id(child.parent))) nodes.append(unique_name) edges.append([unique_name_parent, unique_name]) else: nodes.append(child) edges.append([child.parent, child]) - nodes, edges = _iterate_children( - child, nodes, edges, names_only=names_only - ) + nodes, edges = _iterate_children(child, nodes, edges, names_only=names_only) return nodes, edges diff --git a/mbuild/coordinate_transform.py b/mbuild/coordinate_transform.py index 533f45859..b9130d590 100644 --- a/mbuild/coordinate_transform.py +++ b/mbuild/coordinate_transform.py @@ -2,11 +2,11 @@ from warnings import simplefilter, warn -simplefilter("always", DeprecationWarning) - import numpy as np from numpy.linalg import inv, norm, svd +simplefilter("always", DeprecationWarning) + __all__ = [ "force_overlap", "x_axis_transform", @@ -46,9 +46,7 @@ def force_overlap( ): equivalence_pairs = zip(from_positions, to_positions) elif isinstance(from_positions, Port) and isinstance(to_positions, Port): - equivalence_pairs, T = _choose_correct_port( - from_positions, to_positions - ) + equivalence_pairs, T = _choose_correct_port(from_positions, to_positions) from_positions.used = True to_positions.used = True else: @@ -195,9 +193,7 @@ def __init__(self, basis, origin=None): class AxisTransform(CoordinateTransform): """Axis transform.""" - def __init__( - self, new_origin=None, point_on_x_axis=None, point_on_xy_plane=None - ): + def __init__(self, new_origin=None, point_on_x_axis=None, point_on_xy_plane=None): if new_origin is None: new_origin = np.array([0.0, 0.0, 0.0]) if point_on_x_axis is None: @@ -255,9 +251,7 @@ def __init__(self, A, B): H = np.zeros((3, 3), dtype=float) for i in range(rows): - H = H + np.transpose(A[i, :] - centroid_A).dot( - (B[i, :] - centroid_B) - ) + H = H + np.transpose(A[i, :] - centroid_A).dot((B[i, :] - centroid_B)) U, _, V = svd(H) V = np.transpose(V) @@ -325,9 +319,7 @@ def _create_equivalence_transform(equiv): for pair in equiv: if not isinstance(pair, tuple) or len(pair) != 2: raise ValueError("Equivalence pair not a 2-tuple") - if not ( - isinstance(pair[0], Compound) and isinstance(pair[1], Compound) - ): + if not (isinstance(pair[0], Compound) and isinstance(pair[1], Compound)): raise ValueError( f"Equivalence pair type mismatch: pair[0] is a {pair[0]} " f"and pair[1] is a {pair[1]}" @@ -345,9 +337,7 @@ def _create_equivalence_transform(equiv): return T -def equivalence_transform( - compound, from_positions, to_positions, add_bond=True -): +def equivalence_transform(compound, from_positions, to_positions, add_bond=True): """Compute an affine transformation. Maps the from_positions to the respective to_positions, and applies this @@ -375,9 +365,7 @@ def equivalence_transform( ): equivalence_pairs = zip(from_positions, to_positions) elif isinstance(from_positions, Port) and isinstance(to_positions, Port): - equivalence_pairs, T = _choose_correct_port( - from_positions, to_positions - ) + equivalence_pairs, T = _choose_correct_port(from_positions, to_positions) from_positions.used = True to_positions.used = True else: diff --git a/mbuild/formats/cassandramcf.py b/mbuild/formats/cassandramcf.py index 14d92cb1f..024849749 100644 --- a/mbuild/formats/cassandramcf.py +++ b/mbuild/formats/cassandramcf.py @@ -14,9 +14,7 @@ __all__ = ["write_mcf"] -def write_mcf( - structure, filename, angle_style, dihedral_style, lj14=None, coul14=None -): +def write_mcf(structure, filename, angle_style, dihedral_style, lj14=None, coul14=None): """Output a Cassandra molecular connectivity file (MCF). Outputs a Cassandra MCF from a Parmed structure object. @@ -45,9 +43,7 @@ def write_mcf( if not isinstance(structure, pmd.Structure): raise ValueError("MCF writer requires parmed structure.") if not all([a.type for a in structure.atoms]): - raise ValueError( - "MCF writing not supported without parameterized forcefield." - ) + raise ValueError("MCF writing not supported without parameterized forcefield.") # Conversion factors IG_CONSTANT_KCAL = 0.00198720425864083 # kcal/mol*K @@ -55,13 +51,9 @@ def write_mcf( # Check some things before we start writing the MCF # Only will write MCF for Cassandra-supported options - if ( - angle_style.casefold() != "fixed" - and angle_style.casefold() != "harmonic" - ): + if angle_style.casefold() != "fixed" and angle_style.casefold() != "harmonic": raise ValueError( - "Invalid selection for angle_style. Please choose 'fixed' or " - "'harmonic'" + "Invalid selection for angle_style. Please choose 'fixed' or " "'harmonic'" ) if len(structure.urey_bradleys) > 0: @@ -81,19 +73,14 @@ def write_mcf( ) if dihedral_style.casefold() != "none": - if ( - len(structure.rb_torsions) > 0 - and dihedral_style.casefold() != "opls" - ): + if len(structure.rb_torsions) > 0 and dihedral_style.casefold() != "opls": raise ValueError( - "Dihedral style declared as {} but RB torsions " - "found.".format(dihedral_style) + "Dihedral style declared as {} but RB torsions " "found.".format( + dihedral_style + ) ) - if ( - len(structure.dihedrals) > 0 - and dihedral_style.casefold() != "charmm" - ): + if len(structure.dihedrals) > 0 and dihedral_style.casefold() != "charmm": raise ValueError( "Dihedral style declared as {} but charmm-style dihedrals " "found.".format(dihedral_style) @@ -136,9 +123,7 @@ def write_mcf( "{:.1f}".format(lj14) ) else: - scaled_eps_list = [ - adj.type.epsilon for adj in structure.adjusts - ] + scaled_eps_list = [adj.type.epsilon for adj in structure.adjusts] for i_adj, combined_eps in enumerate(combined_eps_list): if combined_eps != 0: lj14 = scaled_eps_list[i_adj] / combined_eps @@ -158,9 +143,7 @@ def write_mcf( ) if coul14 < 0.0 or coul14 > 1.0: - raise ValueError( - "Unreasonable value {} for coul14 scaling.".format(coul14) - ) + raise ValueError("Unreasonable value {} for coul14 scaling.".format(coul14)) if lj14 < 0.0 or lj14 > 1.0: raise ValueError("Unreasonable value {} for lj14 scaling.".format(lj14)) @@ -178,12 +161,8 @@ def write_mcf( mcf_file.write(header) _write_atom_information(mcf_file, structure, in_ring, IG_CONSTANT_KCAL) _write_bond_information(mcf_file, structure) - _write_angle_information( - mcf_file, structure, angle_style, IG_CONSTANT_KCAL - ) - _write_dihedral_information( - mcf_file, structure, dihedral_style, KCAL_TO_KJ - ) + _write_angle_information(mcf_file, structure, angle_style, IG_CONSTANT_KCAL) + _write_dihedral_information(mcf_file, structure, dihedral_style, KCAL_TO_KJ) _write_improper_information(mcf_file, structure, KCAL_TO_KJ) _write_fragment_information(mcf_file, structure, frag_list, frag_conn) _write_intrascaling_information(mcf_file, lj14, coul14) @@ -216,16 +195,14 @@ def _id_rings_fragments(structure): ) if len(structure.bonds) == 0: - warnings.warn( - "No bonds found. Cassandra will interpet this as a rigid species" - ) + warnings.warn("No bonds found. Cassandra will interpet this as a rigid species") in_ring = [False] * len(structure.atoms) frag_list = [] frag_conn = [] return in_ring, frag_list, frag_conn # Check if entire molecule is connected. Warn if not. - if nx.is_connected(bond_graph) == False: + if nx.is_connected(bond_graph) is False: raise ValueError( "Not all components of the molecule are connected. MCF files are " "for a single molecule and thus everything should be connected " @@ -246,8 +223,7 @@ def _id_rings_fragments(structure): # First create a neighbor list for each atom neigh_dict = { - i: list(bond_graph.neighbors(i)) - for i in range(bond_graph.number_of_nodes()) + i: list(bond_graph.neighbors(i)) for i in range(bond_graph.number_of_nodes()) } # Handle fused/adjoining rings @@ -281,7 +257,7 @@ def _id_rings_fragments(structure): # Now ID the other fragments for idx in neigh_dict: if len(neigh_dict[idx]) > 1: - if in_ring[idx] == True: + if in_ring[idx] is True: continue else: frag_list.append([idx] + neigh_dict[idx]) @@ -389,7 +365,7 @@ def _write_atom_information(mcf_file, structure, in_ring, IG_CONSTANT_KCAL): sigmas[i], ) ) - if in_ring[i] == True: + if in_ring[i] is True: mcf_file.write(" ring") mcf_file.write("\n") @@ -407,9 +383,7 @@ def _write_bond_information(mcf_file, structure): bond_parms = [f"{bond.type.req:8.3f}" for bond in structure.bonds] mcf_file.write("\n!Bond Format\n") - mcf_file.write( - "!index i j type parameters\n" + '!type="fixed", parms=bondLength\n' - ) + mcf_file.write("!index i j type parameters\n" + '!type="fixed", parms=bondLength\n') mcf_file.write("\n# Bond_Info\n") mcf_file.write("{:d}\n".format(len(structure.bonds))) for i, bond in enumerate(structure.bonds): @@ -424,9 +398,7 @@ def _write_bond_information(mcf_file, structure): ) -def _write_angle_information( - mcf_file, structure, angle_style, IG_CONSTANT_KCAL -): +def _write_angle_information(mcf_file, structure, angle_style, IG_CONSTANT_KCAL): """Write the angles in the system. Parameters @@ -450,8 +422,7 @@ def _write_angle_information( ] else: raise ValueError( - "Only 'fixed' and 'harmonic' angle styles are supported by " - "Cassandra" + "Only 'fixed' and 'harmonic' angle styles are supported by " "Cassandra" ) header = ( @@ -478,9 +449,7 @@ def _write_angle_information( ) -def _write_dihedral_information( - mcf_file, structure, dihedral_style, KCAL_TO_KJ -): +def _write_dihedral_information(mcf_file, structure, dihedral_style, KCAL_TO_KJ): """Write the dihedrals in the system. Parameters @@ -560,8 +529,7 @@ def _write_dihedral_information( dihedral_parms = ["" for dihedral in dihedrals] else: raise ValueError( - "Only 'OPLS', 'CHARMM', and 'none' dihedral styles are " - "supported." + "Only 'OPLS', 'CHARMM', and 'none' dihedral styles are " "supported." ) mcf_file.write("{:d}\n".format(len(dihedrals))) @@ -571,8 +539,7 @@ def _write_dihedral_information( # The atom order provided in the parmed.Structure # is written to the MCF file. mcf_file.write( - "{:<4d} {:<4d} {:<4d} {:<4d} {:<4d}" - " {:s} {:s}\n".format( + "{:<4d} {:<4d} {:<4d} {:<4d} {:<4d}" " {:s} {:s}\n".format( i + 1, dihedral.atom1.idx + 1, dihedral.atom2.idx + 1, @@ -656,9 +623,7 @@ def _write_fragment_information(mcf_file, structure, frag_list, frag_conn): mcf_file.write("1\n") mcf_file.write("1 2 1 2\n") else: - warnings.warn( - "More than two atoms present but no fragments identified." - ) + warnings.warn("More than two atoms present but no fragments identified.") mcf_file.write("0\n") else: mcf_file.write("{:d}\n".format(len(frag_list))) @@ -671,9 +636,7 @@ def _write_fragment_information(mcf_file, structure, frag_list, frag_conn): mcf_file.write("\n\n# Fragment_Connectivity\n") mcf_file.write("{:d}\n".format(len(frag_conn))) for i, conn in enumerate(frag_conn): - mcf_file.write( - "{:d} {:d} {:d}\n".format(i + 1, conn[0] + 1, conn[1] + 1) - ) + mcf_file.write("{:d} {:d} {:d}\n".format(i + 1, conn[0] + 1, conn[1] + 1)) def _write_intrascaling_information(mcf_file, lj14, coul14): diff --git a/mbuild/formats/json_formats.py b/mbuild/formats/json_formats.py index 33bbb53de..be1a2da28 100644 --- a/mbuild/formats/json_formats.py +++ b/mbuild/formats/json_formats.py @@ -69,9 +69,7 @@ def compound_from_json(json_file): parent_compound.add(sub_cmpd, check_box_size=False, label=label_str) parent.bond_graph = BondGraph() - parent.bond_graph.add_nodes_from( - [particle for particle in parent.particles()] - ) + parent.bond_graph.add_nodes_from([particle for particle in parent.particles()]) _add_ports(compound_dict, converted_dict) _add_bonds(compound_dict, parent, converted_dict) @@ -114,12 +112,8 @@ def compound_to_json(cmpd, file_path, include_ports=False): if val == sub_compound: sub_compound_dict["label"] = key if isinstance(val, list): - if not cmpd_info[sub_compound.parent].get( - "label_list", None - ): - cmpd_info[sub_compound.parent][ - "label_list" - ] = OrderedDict() + if not cmpd_info[sub_compound.parent].get("label_list", None): + cmpd_info[sub_compound.parent]["label_list"] = OrderedDict() cmpd_info[sub_compound.parent]["label_list"][key] = [ id(x) for x in val ] @@ -230,9 +224,7 @@ def _dict_successors(compound_dict): else: for sub_compund in compound_dict["children"]: yield sub_compund, compound_dict - for sub_sub_compound, parent_compound in _dict_successors( - sub_compund - ): + for sub_sub_compound, parent_compound in _dict_successors(sub_compund): yield (sub_sub_compound, parent_compound) @@ -274,22 +266,16 @@ def _perform_sanity_check(json_dict): """Perform Sanity Check on the JSON File.""" from warnings import warn - warning_msg = ( - "This Json was written using {0}, current mbuild version is {1}." - ) + warning_msg = "This Json was written using {0}, current mbuild version is {1}." this_version = mb.__version__ json_mbuild_version = json_dict.get("mbuild-version", None) if not json_mbuild_version: - raise MBuildError( - "The uploaded JSON file doesn't isn't correctly formatted" - ) + raise MBuildError("The uploaded JSON file doesn't isn't correctly formatted") json_mb_type = json_dict.get("type", None) if (not json_mb_type) or (json_mb_type != "Compound"): - raise MBuildError( - "Error. Cannot convert JSON of type: {}".format(json_mb_type) - ) + raise MBuildError("Error. Cannot convert JSON of type: {}".format(json_mb_type)) [major, minor, patch] = json_mbuild_version.split(".") [this_major, this_minor, this_patch] = this_version.split(".") @@ -299,7 +285,4 @@ def _perform_sanity_check(json_dict): + " Cannot Convert JSON to compound" ) if minor != this_minor: - warn( - warning_msg.format(json_mbuild_version, this_version) - + " Will Proceed." - ) + warn(warning_msg.format(json_mbuild_version, this_version) + " Will Proceed.") diff --git a/mbuild/formats/vasp.py b/mbuild/formats/vasp.py index 2d2b1d7c0..507c54e4f 100644 --- a/mbuild/formats/vasp.py +++ b/mbuild/formats/vasp.py @@ -12,9 +12,7 @@ __all__ = ["write_poscar", "read_poscar"] -def write_poscar( - compound, filename, lattice_constant=1.0, coord_style="cartesian" -): +def write_poscar(compound, filename, lattice_constant=1.0, coord_style="cartesian"): """Write a VASP POSCAR file from a Compound. See //https://www.vasp.at formore information. @@ -36,9 +34,7 @@ def write_poscar( try: atoms = [p.element.symbol for p in compound.particles()] except AttributeError: - atoms = [ - element_from_symbol(p.name).symbol for p in compound.particles() - ] + atoms = [element_from_symbol(p.name).symbol for p in compound.particles()] # This automatically sorts element names alphabetically unique_atoms = np.unique(atoms) @@ -147,10 +143,7 @@ def read_poscar(filename, conversion=0.1): # Slice is necessary to handle files using selective dynamics coords = np.stack( - [ - np.fromiter(line.split()[:3], dtype="float64") - for line in data[:total_atoms] - ] + [np.fromiter(line.split()[:3], dtype="float64") for line in data[:total_atoms]] ) if cartesian: diff --git a/mbuild/lattice.py b/mbuild/lattice.py index b2a85fbe1..893469bd1 100644 --- a/mbuild/lattice.py +++ b/mbuild/lattice.py @@ -41,15 +41,12 @@ def load_cif(file_or_path=None, wrap_coords=False): # convert angstroms to nanometers lattice_spacing = ( - np.linalg.norm(np.asarray(frame.box.get_box_matrix()).T, axis=1) - / 10 + np.linalg.norm(np.asarray(frame.box.get_box_matrix()).T, axis=1) / 10 ) # create lattice_points dictionary position_dict = defaultdict(list) - for elem_id, coords in zip( - frame.typeid, frame.cif_coordinates.tolist() - ): + for elem_id, coords in zip(frame.typeid, frame.cif_coordinates.tolist()): if wrap_coords: for i, pos in enumerate(coords): if 0 > pos > -1: @@ -636,9 +633,7 @@ def populate(self, compound_dict=None, x=1, y=1, z=1): break except ElementError: element = None - particle = mb.Compound( - name=key_id, pos=[0, 0, 0], element=element - ) + particle = mb.Compound(name=key_id, pos=[0, 0, 0], element=element) for pos in all_pos: particle_to_add = mb.clone(particle) particle_to_add.translate_to(list(pos)) @@ -664,14 +659,10 @@ def populate(self, compound_dict=None, x=1, y=1, z=1): ) ret_lattice.add(compoundsList) # Create mbuild.box - ret_lattice.box = mb.Box( - lengths=[a * x, b * y, c * z], angles=self.angles - ) + ret_lattice.box = mb.Box(lengths=[a * x, b * y, c * z], angles=self.angles) # if coordinates are below a certain threshold, set to 0 tolerance = 1e-12 - ret_lattice.xyz_with_ports[ret_lattice.xyz_with_ports <= tolerance] = ( - 0.0 - ) + ret_lattice.xyz_with_ports[ret_lattice.xyz_with_ports <= tolerance] = 0.0 return ret_lattice diff --git a/mbuild/lib/atoms/__init__.py b/mbuild/lib/atoms/__init__.py index fb9d8cbc1..819cffc95 100644 --- a/mbuild/lib/atoms/__init__.py +++ b/mbuild/lib/atoms/__init__.py @@ -1,3 +1,4 @@ +# ruff: noqa: F401 """mBuild library of atoms.""" from mbuild.lib.atoms.c3 import C3 diff --git a/mbuild/lib/atoms/n4.py b/mbuild/lib/atoms/n4.py index 7f4103400..a6b21d8f2 100644 --- a/mbuild/lib/atoms/n4.py +++ b/mbuild/lib/atoms/n4.py @@ -10,9 +10,7 @@ class N4(mb.Compound): def __init__(self): super(N4, self).__init__() - self.add( - mb.Particle(name="N", pos=[0, 0, 0], element="N"), label="N[$]" - ) + self.add(mb.Particle(name="N", pos=[0, 0, 0], element="N"), label="N[$]") self.add(mb.Port(anchor=self[0]), label="port_0") self.add(mb.Port(anchor=self[0]), label="port_1") self.add(mb.Port(anchor=self[0]), label="port_2") diff --git a/mbuild/lib/bulk_materials/__init__.py b/mbuild/lib/bulk_materials/__init__.py index 9417b96a3..4f9e7fac3 100644 --- a/mbuild/lib/bulk_materials/__init__.py +++ b/mbuild/lib/bulk_materials/__init__.py @@ -1,3 +1,4 @@ +# ruff: noqa: F401 """mBuild bulk materials library.""" from mbuild.lib.bulk_materials.amorphous_silica_bulk import AmorphousSilicaBulk diff --git a/mbuild/lib/moieties/__init__.py b/mbuild/lib/moieties/__init__.py index a1978ef0b..9b76338bb 100644 --- a/mbuild/lib/moieties/__init__.py +++ b/mbuild/lib/moieties/__init__.py @@ -1,3 +1,4 @@ +# ruff: noqa: F401 """mBuild library of common chemical moieties.""" from mbuild.lib.moieties.ch2 import CH2 diff --git a/mbuild/lib/moieties/h2o.py b/mbuild/lib/moieties/h2o.py index 337fd7532..77e50edf4 100644 --- a/mbuild/lib/moieties/h2o.py +++ b/mbuild/lib/moieties/h2o.py @@ -9,15 +9,9 @@ class H2O(mb.Compound): def __init__(self): super(H2O, self).__init__() - self.add( - mb.Particle(name="O", pos=[1.0203, 0.7604, 1.2673], element="O") - ) - self.add( - mb.Particle(name="H", pos=[0.9626, 0.8420, 1.2673], element="H") - ) - self.add( - mb.Particle(name="H", pos=[0.9626, 0.6787, 1.2673], element="H") - ) + self.add(mb.Particle(name="O", pos=[1.0203, 0.7604, 1.2673], element="O")) + self.add(mb.Particle(name="H", pos=[0.9626, 0.8420, 1.2673], element="H")) + self.add(mb.Particle(name="H", pos=[0.9626, 0.6787, 1.2673], element="H")) self.add_bond((self[0], self[1])) self.add_bond((self[0], self[2])) diff --git a/mbuild/lib/molecules/__init__.py b/mbuild/lib/molecules/__init__.py index f39893047..85c103d38 100644 --- a/mbuild/lib/molecules/__init__.py +++ b/mbuild/lib/molecules/__init__.py @@ -1,3 +1,4 @@ +# ruff: noqa: F401 """Library of molecules for mBuild.""" from mbuild.lib.molecules.ethane import Ethane diff --git a/mbuild/lib/molecules/ethane.py b/mbuild/lib/molecules/ethane.py index 0722208d2..7095da927 100644 --- a/mbuild/lib/molecules/ethane.py +++ b/mbuild/lib/molecules/ethane.py @@ -15,6 +15,4 @@ def __init__(self): self.add(CH3(), "methyl1") self.add(CH3(), "methyl2") - mb.force_overlap( - self["methyl1"], self["methyl1"]["up"], self["methyl2"]["up"] - ) + mb.force_overlap(self["methyl1"], self["methyl1"]["up"], self["methyl2"]["up"]) diff --git a/mbuild/lib/molecules/water.py b/mbuild/lib/molecules/water.py index 071c0e4bb..7b6661b3d 100644 --- a/mbuild/lib/molecules/water.py +++ b/mbuild/lib/molecules/water.py @@ -12,9 +12,7 @@ def __init__(self, oh_bond_length, hoh_angle): super().__init__() o1 = mb.Compound(name="OW", element="O", pos=[0.0, 0.0, 0.0]) - h1 = mb.Compound( - name="HW1", element="H", pos=[oh_bond_length, 0.0, 0.0] - ) + h1 = mb.Compound(name="HW1", element="H", pos=[oh_bond_length, 0.0, 0.0]) h2 = mb.Compound( name="HW2", element="H", @@ -63,9 +61,7 @@ def __init__(self, oh_bond_length, hoh_angle, om_bond_length): super().__init__() o1 = mb.Compound(name="OW", element="O", pos=[0.0, 0.0, 0.0]) - h1 = mb.Compound( - name="HW1", element="H", pos=[oh_bond_length, 0.0, 0.0] - ) + h1 = mb.Compound(name="HW1", element="H", pos=[oh_bond_length, 0.0, 0.0]) h2 = mb.Compound( name="HW2", element="H", diff --git a/mbuild/lib/recipes/__init__.py b/mbuild/lib/recipes/__init__.py index 9d4fc9b3a..16f148718 100644 --- a/mbuild/lib/recipes/__init__.py +++ b/mbuild/lib/recipes/__init__.py @@ -1,3 +1,4 @@ +# ruff: noqa: F401 """Library of recipes for mBuild.""" from mbuild.lib.recipes.alkane import Alkane diff --git a/mbuild/lib/recipes/monolayer.py b/mbuild/lib/recipes/monolayer.py index 25ab4a7f3..97dfa7d23 100644 --- a/mbuild/lib/recipes/monolayer.py +++ b/mbuild/lib/recipes/monolayer.py @@ -43,7 +43,7 @@ def __init__( pattern=None, tile_x=1, tile_y=1, - **kwargs + **kwargs, ): from mbuild.lib.recipes import TiledCompound @@ -93,10 +93,7 @@ def __init__( # Attach chains to the surface attached_chains, _ = subpattern.apply_to_compound( - guest=chain, - host=self["tiled_surface"], - backfill=None, - **kwargs + guest=chain, host=self["tiled_surface"], backfill=None, **kwargs ) self.add(attached_chains) @@ -106,10 +103,7 @@ def __init__( # Attach final chain type. Remaining sites get a backfill. warn("\n Adding {} of chain {}".format(len(pattern), chains[-1])) attached_chains, backfills = pattern.apply_to_compound( - guest=chains[-1], - host=self["tiled_surface"], - backfill=backfill, - **kwargs + guest=chains[-1], host=self["tiled_surface"], backfill=backfill, **kwargs ) self.add(attached_chains) self.add(backfills) diff --git a/mbuild/lib/recipes/polymer.py b/mbuild/lib/recipes/polymer.py index 9209a532d..c908003e1 100644 --- a/mbuild/lib/recipes/polymer.py +++ b/mbuild/lib/recipes/polymer.py @@ -193,9 +193,7 @@ def build(self, n, sequence="A", add_hydrogens=True): break self.head_port = first_part["up"] if not first_part["up"].used else None - self.tail_port = ( - last_part["down"] if not last_part["down"].used else None - ) + self.tail_port = last_part["down"] if not last_part["down"].used else None head_tail = [self.head_port, self.tail_port] for i, compound in enumerate(self._end_groups): @@ -374,9 +372,7 @@ def add_end_groups( `add_end_groups()` a second time to add another end group. """ comp = clone(compound) - separation = _add_port( - comp, "up", index, separation, orientation, replace - ) + separation = _add_port(comp, "up", index, separation, orientation, replace) if replace: comp.remove(comp[index]) if duplicate: diff --git a/mbuild/lib/recipes/silica_interface.py b/mbuild/lib/recipes/silica_interface.py index 4f0149563..857d48e2f 100644 --- a/mbuild/lib/recipes/silica_interface.py +++ b/mbuild/lib/recipes/silica_interface.py @@ -39,9 +39,7 @@ class SilicaInterface(Compound): Zhuravlev model." (2000) Colloids Surf., A. 10, 1-38 """ - def __init__( - self, bulk_silica, tile_x=1, tile_y=1, thickness=1.0, seed=12345 - ): + def __init__(self, bulk_silica, tile_x=1, tile_y=1, thickness=1.0, seed=12345): super(SilicaInterface, self).__init__() random.seed(seed) @@ -74,15 +72,10 @@ def _cleave_interface(self, bulk_silica, tile_x, tile_y, thickness): particle.name == "Si" and O_buffer < particle.pos[2] < (thickness + O_buffer) ) or ( - particle.name == "O" - and particle.pos[2] < (thickness + 2 * O_buffer) + particle.name == "O" and particle.pos[2] < (thickness + 2 * O_buffer) ): - interface_particle = Compound( - name=particle.name, pos=particle.pos - ) - interface.add( - interface_particle, particle.name + "_{}".format(i) - ) + interface_particle = Compound(name=particle.name, pos=particle.pos) + interface.add(interface_particle, particle.name + "_{}".format(i)) self.add(interface, inherit_box=True, inherit_periodicity=True) def _strip_stray_atoms(self): @@ -175,7 +168,5 @@ def _adjust_stoichiometry(self): if __name__ == "__main__": from mbuild.lib.bulk_materials import AmorphousSilicaBulk - silica_interface = SilicaInterface( - bulk_silica=AmorphousSilicaBulk(), thickness=1.2 - ) + silica_interface = SilicaInterface(bulk_silica=AmorphousSilicaBulk(), thickness=1.2) silica_interface.save("silica_interface.mol2", show_ports=True) diff --git a/mbuild/lib/recipes/tiled_compound.py b/mbuild/lib/recipes/tiled_compound.py index 4c228ca69..3d3f4e3fb 100644 --- a/mbuild/lib/recipes/tiled_compound.py +++ b/mbuild/lib/recipes/tiled_compound.py @@ -47,9 +47,7 @@ def __init__(self, tile, n_tiles, name=None, **kwargs): name = tile.name + "-".join(str(d) for d in n_tiles) self.name = name self.periodicity = tile.periodicity - self.box = Box( - np.array(tile.box.lengths) * n_tiles, angles=tile.box.angles - ) + self.box = Box(np.array(tile.box.lengths) * n_tiles, angles=tile.box.angles) if all(n_tiles == 1): self._add_tile(tile, (0, 0, 0)) diff --git a/mbuild/lib/recipes/water_box.py b/mbuild/lib/recipes/water_box.py index 6e15b4940..8e4be86f8 100644 --- a/mbuild/lib/recipes/water_box.py +++ b/mbuild/lib/recipes/water_box.py @@ -80,7 +80,7 @@ def __init__( radii_dict = {} else: if not isinstance(radii_dict, dict): - raise ValueError(f"radii_dict should be dictionary.") + raise ValueError("radii_dict should be dictionary.") # check if we are given a list or single value if isinstance(edge, (list, tuple)): @@ -98,7 +98,7 @@ def __init__( if model is not None: if not isinstance(model, Compound): - raise MBuildError(f"Model must be a compound.") + raise MBuildError("Model must be a compound.") particles = [p for p in model.particles()] if particles[0].element.symbol != "O": raise MBuildError( @@ -185,22 +185,14 @@ def __init__( if p1.name in radii_dict: c1 = radii_scaling * radii_dict[p1.name] elif p1.element is not None: - c1 = ( - radii_scaling - * p1.element.radius_alvarez - / 10.0 - ) + c1 = radii_scaling * p1.element.radius_alvarez / 10.0 else: c1 = radii_scaling * radii_overlap if p2.name in radii_dict: c2 = radii_scaling * radii_dict[p2.name] elif p2.element is not None: - c2 = ( - radii_scaling - * p2.element.radius_alvarez - / 10.0 - ) + c2 = radii_scaling * p2.element.radius_alvarez / 10.0 else: c2 = radii_scaling * radii_overlap diff --git a/mbuild/lib/surfaces/__init__.py b/mbuild/lib/surfaces/__init__.py index b7e40474b..0be2e9eba 100644 --- a/mbuild/lib/surfaces/__init__.py +++ b/mbuild/lib/surfaces/__init__.py @@ -1,3 +1,4 @@ +# ruff: noqa: F401 """mBuild surface library.""" from mbuild.lib.surfaces.amorphous_silica_surface import AmorphousSilicaSurface diff --git a/mbuild/lib/surfaces/amorphous_silica_surface.py b/mbuild/lib/surfaces/amorphous_silica_surface.py index 646229f3c..2b1950b3c 100644 --- a/mbuild/lib/surfaces/amorphous_silica_surface.py +++ b/mbuild/lib/surfaces/amorphous_silica_surface.py @@ -28,9 +28,7 @@ def __init__(self, surface_roughness=1.0): for particle in list(self.particles()): if particle.name == "OB": count += 1 - port = mb.Port( - anchor=particle, orientation=[0, 0, 1], separation=0.1 - ) + port = mb.Port(anchor=particle, orientation=[0, 0, 1], separation=0.1) self.add(port, "port_{}".format(count)) diff --git a/mbuild/lib/surfaces/betacristobalite.py b/mbuild/lib/surfaces/betacristobalite.py index d78c7246b..5510a106e 100644 --- a/mbuild/lib/surfaces/betacristobalite.py +++ b/mbuild/lib/surfaces/betacristobalite.py @@ -37,9 +37,7 @@ def __init__(self): for particle in list(self.particles()): if particle.name.startswith("O") and particle.pos[2] > 1.0: count += 1 - port = mb.Port( - anchor=particle, orientation=[0, 0, 1], separation=0.1 - ) + port = mb.Port(anchor=particle, orientation=[0, 0, 1], separation=0.1) self.add(port, "port_{}".format(count)) particle.name = "O" # Strip numbers required in .mol2 files. elif particle.name.startswith("Si"): diff --git a/mbuild/packing.py b/mbuild/packing.py index 7a1742c78..47c45d555 100644 --- a/mbuild/packing.py +++ b/mbuild/packing.py @@ -238,9 +238,7 @@ def fill_box( if compound is not None and n_compounds is not None: if len(compound) != len(n_compounds): - raise ValueError( - "`compound` and `n_compounds` must be of equal length." - ) + raise ValueError("`compound` and `n_compounds` must be of equal length.") if compound is not None: if len(compound) != len(fix_orientation): @@ -283,8 +281,7 @@ def fill_box( ) if len(compound) != len(compound_ratio): raise ValueError( - "Length of `compound_ratio` must equal length of " - "`compound`" + "Length of `compound_ratio` must equal length of " "`compound`" ) prototype_mass = 0 for c, r in zip(compound, compound_ratio): @@ -327,9 +324,7 @@ def fill_box( input_text = PACKMOL_HEADER.format( overlap, filled_xyz.name, seed, sidemax * 10, packmol_commands ) - for comp, m_compounds, rotate in zip( - compound, n_compounds, fix_orientation - ): + for comp, m_compounds, rotate in zip(compound, n_compounds, fix_orientation): m_compounds = int(m_compounds) compound_xyz = _new_xyz_file() @@ -476,9 +471,7 @@ def fill_region( if compound is not None and n_compounds is not None: if len(compound) != len(n_compounds): - raise ValueError( - "`compound` and `n_compounds` must be of equal length." - ) + raise ValueError("`compound` and `n_compounds` must be of equal length.") if compound is not None: if len(compound) != len(fix_orientation): raise ValueError( @@ -721,9 +714,7 @@ def fill_sphere( if compound is not None and n_compounds is not None: if len(compound) != len(n_compounds): - raise ValueError( - "`compound` and `n_compounds` must be of equal length." - ) + raise ValueError("`compound` and `n_compounds` must be of equal length.") if compound is not None: if len(compound) != len(fix_orientation): @@ -734,9 +725,7 @@ def fill_sphere( for coord in sphere[:3]: if coord < sphere[3]: - raise ValueError( - "`sphere` center coordinates must be greater than radius." - ) + raise ValueError("`sphere` center coordinates must be greater than radius.") # Apply edge buffer radius = sphere[3] - edge @@ -747,12 +736,7 @@ def fill_sphere( if len(compound) == 1: # Conversion from kg/m^3 / amu * nm^3 to dimensionless units n_compounds = [ - int( - density - / total_mass - * (4 / 3 * np.pi * radius**3) - * 0.60224 - ) + int(density / total_mass * (4 / 3 * np.pi * radius**3) * 0.60224) ] else: if compound_ratio is None: @@ -763,18 +747,14 @@ def fill_sphere( ) if len(compound) != len(compound_ratio): raise ValueError( - "Length of `compound_ratio` must equal length of " - "`compound`" + "Length of `compound_ratio` must equal length of " "`compound`" ) prototype_mass = 0 for c, r in zip(compound, compound_ratio): prototype_mass += r * c.mass # Conversion from kg/m^3 / amu * nm^3 to dimensionless units n_prototypes = int( - density - / prototype_mass - * (4 / 3 * np.pi * radius**3) - * 0.60224 + density / prototype_mass * (4 / 3 * np.pi * radius**3) * 0.60224 ) n_compounds = list() for c in compound_ratio: @@ -801,9 +781,7 @@ def fill_sphere( input_text = PACKMOL_HEADER.format( overlap, filled_xyz.name, seed, sidemax * 10, packmol_commands ) - for comp, m_compounds, rotate in zip( - compound, n_compounds, fix_orientation - ): + for comp, m_compounds, rotate in zip(compound, n_compounds, fix_orientation): m_compounds = int(m_compounds) compound_xyz = _new_xyz_file() @@ -1026,7 +1004,7 @@ def _validate_mass(compound, n_compounds): comp_masses = np.array([c._particle_mass(p) for p in c.particles()]) if 0.0 in comp_masses or None in comp_masses: found_zero_mass = True - comp_masses[comp_masses == None] = 0.0 + comp_masses[comp_masses is None] = 0.0 total_mass += np.sum(comp_masses) * n if total_mass == 0: diff --git a/mbuild/pattern.py b/mbuild/pattern.py index 8173c0e1a..38d96a940 100644 --- a/mbuild/pattern.py +++ b/mbuild/pattern.py @@ -163,16 +163,12 @@ def apply_to_compound( # Attach the guest to the closest port. new_guest = clone(guest) - force_overlap( - new_guest, new_guest.labels[guest_port_name], closest_port - ) + force_overlap(new_guest, new_guest.labels[guest_port_name], closest_port) guests.append(new_guest) # Move the port as far away as possible (simpler than removing it). # There may well be a more elegant/efficient way of doing this. - port_positions[closest_point_idx, :] = np.array( - [np.inf, np.inf, np.inf] - ) + port_positions[closest_point_idx, :] = np.array([np.inf, np.inf, np.inf]) backfills = [] if backfill: assert_port_exists(backfill_port_name, backfill) @@ -267,7 +263,7 @@ class Grid3DPattern(Pattern): Number of grid aisles """ - def __init__(self, n, m, l, **kwargs): + def __init__(self, n, m, l, **kwargs): # noqa: E741 points = np.zeros(shape=(n * m * l, 3), dtype=float) for i, j, k in product(range(n), range(m), range(l)): points[i * m * l + j * l + k, 0] = i / n diff --git a/mbuild/periodic_kdtree.py b/mbuild/periodic_kdtree.py index 94281e218..0e7a0c098 100644 --- a/mbuild/periodic_kdtree.py +++ b/mbuild/periodic_kdtree.py @@ -58,9 +58,7 @@ def _gen_relevant_images(x, bounds, distance_upper_bound): disp[i] = bounds[i] if distance_upper_bound == np.inf: - xs = list( - chain.from_iterable((_ + disp, _, _ - disp) for _ in xs) - ) + xs = list(chain.from_iterable((_ + disp, _, _ - disp) for _ in xs)) else: extra_xs = [] @@ -209,9 +207,7 @@ def __query(self, x, k=1, eps=0, p=2, distance_upper_bound=np.inf): # Run queries over all relevant images of x hits_list = [] - for real_x in _gen_relevant_images( - x, self.bounds, distance_upper_bound - ): + for real_x in _gen_relevant_images(x, self.bounds, distance_upper_bound): d, i = super(PeriodicKDTree, self).query( real_x, k, eps, p, distance_upper_bound ) diff --git a/mbuild/port.py b/mbuild/port.py index b1c337309..65326967b 100644 --- a/mbuild/port.py +++ b/mbuild/port.py @@ -167,9 +167,7 @@ def access_labels(self): referrer_labels = [ key for key, val in self.root.labels.items() if val == referrer ] - port_labels = [ - key for key, val in referrer.labels.items() if val == self - ] + port_labels = [key for key, val in referrer.labels.items() if val == self] if referrer is self.root: for label in port_labels: access_labels.add(f"['{label}']") diff --git a/mbuild/recipes/__init__.py b/mbuild/recipes/__init__.py index e5caecc5e..44b87fdc9 100644 --- a/mbuild/recipes/__init__.py +++ b/mbuild/recipes/__init__.py @@ -1,6 +1,7 @@ """Entrypoints for mBuild recipe plugins.""" import sys +from importlib import metadata class Recipes(object): @@ -10,7 +11,6 @@ class Recipes(object): recipes = Recipes() -from importlib import metadata if sys.version_info.minor >= 10: entry_points = metadata.entry_points().select(group="mbuild.plugins") diff --git a/mbuild/tests/base_test.py b/mbuild/tests/base_test.py index 2bcfd4697..40e6a5cbd 100644 --- a/mbuild/tests/base_test.py +++ b/mbuild/tests/base_test.py @@ -161,9 +161,7 @@ def benzene_from_parts(self): def box_of_benzenes(self, benzene): n_benzenes = 10 benzene.name = "Benzene" - filled = mb.fill_box( - benzene, n_compounds=n_benzenes, box=[0, 0, 0, 4, 4, 4] - ) + filled = mb.fill_box(benzene, n_compounds=n_benzenes, box=[0, 0, 0, 4, 4, 4]) return filled @pytest.fixture @@ -192,15 +190,11 @@ def _connect_and_reconnect(chf, bond_vector): first = mb.clone(chf) second = mb.clone(chf) first.add( - mb.Port( - anchor=first[0], orientation=bond_vector, separation=0.075 - ), + mb.Port(anchor=first[0], orientation=bond_vector, separation=0.075), label="up", ) second.add( - mb.Port( - anchor=second[0], orientation=-bond_vector, separation=0.075 - ), + mb.Port(anchor=second[0], orientation=-bond_vector, separation=0.075), label="down", ) c2h2f2 = mb.Compound(subcompounds=(first, second)) @@ -252,9 +246,7 @@ def graphene(self): lattice_points=basis, ) carbon_dict = {"C": carbon} - graphene_cell = graphene.populate( - compound_dict=carbon_dict, x=3, y=3, z=1 - ) + graphene_cell = graphene.populate(compound_dict=carbon_dict, x=3, y=3, z=1) return graphene_cell @pytest.fixture @@ -266,9 +258,7 @@ def cscl_crystal(self): cscl_lattice = mb.Lattice(spacing, lattice_points=basis) cscl_dict = {"Cs": cesium, "Cl": chlorine} - cscl_compound = cscl_lattice.populate( - x=3, y=3, z=1, compound_dict=cscl_dict - ) + cscl_compound = cscl_lattice.populate(x=3, y=3, z=1, compound_dict=cscl_dict) return cscl_compound @pytest.fixture @@ -285,38 +275,16 @@ def gilmerite(self): angles=[114.94999695, 93.05000305, 91.91999817], ) gilmerite.add( - mb.Particle( - name="As", pos=[5.43783569e-01, 1.54457900e-04, 4.61488000e-05] - ) - ) - gilmerite.add( - mb.Particle(name="Cu", pos=[0.00615697, 0.28454988, 0.14878373]) - ) - gilmerite.add( - mb.Particle(name="Cu", pos=[0.28204174, 0.13594167, 0.16465892]) - ) - gilmerite.add( - mb.Particle(name="Cu", pos=[0.28377297, 0.43348074, 0.17854972]) - ) - gilmerite.add( - mb.Particle(name="O", pos=[0.08094841, 0.14370937, 0.03276565]) - ) - gilmerite.add( - mb.Particle(name="O", pos=[0.08451646, 0.45650253, 0.03415011]) - ) - gilmerite.add( - mb.Particle(name="O", pos=[0.36793642, 0.28482277, 0.07106915]) - ) - gilmerite.add( - mb.Particle(name="O", pos=[0.39833167, -0.00501952, 0.08583677]) - ) - gilmerite.add( - mb.Particle(name="O", pos=[0.17415644, 0.27864442, 0.24828055]) - ) - gilmerite.add( - mb.Particle(name="O", pos=[0.24149659, -0.00539473, 0.29073744]) - ) - gilmerite.add( - mb.Particle(name="O", pos=[0.45795937, 0.36822546, 0.30135167]) + mb.Particle(name="As", pos=[5.43783569e-01, 1.54457900e-04, 4.61488000e-05]) ) + gilmerite.add(mb.Particle(name="Cu", pos=[0.00615697, 0.28454988, 0.14878373])) + gilmerite.add(mb.Particle(name="Cu", pos=[0.28204174, 0.13594167, 0.16465892])) + gilmerite.add(mb.Particle(name="Cu", pos=[0.28377297, 0.43348074, 0.17854972])) + gilmerite.add(mb.Particle(name="O", pos=[0.08094841, 0.14370937, 0.03276565])) + gilmerite.add(mb.Particle(name="O", pos=[0.08451646, 0.45650253, 0.03415011])) + gilmerite.add(mb.Particle(name="O", pos=[0.36793642, 0.28482277, 0.07106915])) + gilmerite.add(mb.Particle(name="O", pos=[0.39833167, -0.00501952, 0.08583677])) + gilmerite.add(mb.Particle(name="O", pos=[0.17415644, 0.27864442, 0.24828055])) + gilmerite.add(mb.Particle(name="O", pos=[0.24149659, -0.00539473, 0.29073744])) + gilmerite.add(mb.Particle(name="O", pos=[0.45795937, 0.36822546, 0.30135167])) return gilmerite diff --git a/mbuild/tests/test_box.py b/mbuild/tests/test_box.py index bbcfa342a..2f8b7b763 100644 --- a/mbuild/tests/test_box.py +++ b/mbuild/tests/test_box.py @@ -42,13 +42,7 @@ def test_from_lengths_angles(self, lengths, angles): ], ) def test_left_handed_matrix(self, lh_matrix): - msg = ( - "Box vectors provided for a left-handed basis, these will " - "be transformed into a right-handed basis automatically." - ) - with pytest.warns( - UserWarning, match=r"provided for a left\-handed basis" - ): + with pytest.warns(UserWarning, match=r"provided for a left\-handed basis"): mb.Box.from_vectors(vectors=lh_matrix) @pytest.mark.parametrize( @@ -136,9 +130,7 @@ def test_lo_hi_tilt_factors(self, lo, hi, tilt_factors, angles): (xy, xz, yz) = tilt_factors lengths = [xhi - (xlo + xy), yhi - ylo, zhi - zlo] - box = mb.Box.from_lo_hi_tilt_factors( - lo=lo, hi=hi, tilt_factors=tilt_factors - ) + box = mb.Box.from_lo_hi_tilt_factors(lo=lo, hi=hi, tilt_factors=tilt_factors) assert np.all(np.isclose(box.lengths, lengths)) assert np.all(np.isclose(box.tilt_factors, tilt_factors)) assert np.all(np.isclose(box.angles, angles)) @@ -150,7 +142,5 @@ def test_lo_hi_tilt_factors(self, lo, hi, tilt_factors, angles): def test_bravais_parameters(self, a, b, c, alpha, beta, gamma): box = mb.Box(lengths=[a, b, c], angles=[alpha, beta, gamma]) assert np.all( - np.isclose( - list(box.bravais_parameters), [a, b, c, alpha, beta, gamma] - ) + np.isclose(list(box.bravais_parameters), [a, b, c, alpha, beta, gamma]) ) diff --git a/mbuild/tests/test_cif.py b/mbuild/tests/test_cif.py index e1cd7e124..ea36f4c7b 100644 --- a/mbuild/tests/test_cif.py +++ b/mbuild/tests/test_cif.py @@ -1,5 +1,4 @@ from collections import OrderedDict -from operator import itemgetter import numpy as np import pytest @@ -61,9 +60,7 @@ def test_cif_vs_manual(self): lattice_cif = load_cif(file_or_path=get_fn("LaCl3.cif")) assert np.all( - np.isclose( - lattice_manual.lattice_spacing, lattice_cif.lattice_spacing - ) + np.isclose(lattice_manual.lattice_spacing, lattice_cif.lattice_spacing) ) assert np.all(np.isclose(lattice_manual.angles, lattice_cif.angles)) @@ -117,9 +114,7 @@ def test_cif_vs_manual_triclinic(self): lattice_cif = load_cif(file_or_path=get_fn("ReS2.cif")) assert np.all( - np.isclose( - lattice_manual.lattice_spacing, lattice_cif.lattice_spacing - ) + np.isclose(lattice_manual.lattice_spacing, lattice_cif.lattice_spacing) ) assert np.all(np.isclose(lattice_manual.angles, lattice_cif.angles)) @@ -180,4 +175,4 @@ def test_cif_raise_warnings(self): match=r"Element assumed from cif file to be Element: silicon, symbol: Si, atomic number: 14, mass: 28.085.", ): lattice_cif = load_cif(file_or_path=get_fn("ETV_triclinic.cif")) - periodic_boxed_molecule = lattice_cif.populate(x=1, y=1, z=1) + lattice_cif.populate(x=1, y=1, z=1) diff --git a/mbuild/tests/test_coarse_graining.py b/mbuild/tests/test_coarse_graining.py index 14ad6a785..6d4cd4e7c 100644 --- a/mbuild/tests/test_coarse_graining.py +++ b/mbuild/tests/test_coarse_graining.py @@ -13,8 +13,6 @@ def test_hexane(self, hexane, propyl): cg_clone = mb.clone(cg) assert cg_clone.n_particles == 2 assert cg_clone.n_bonds == 1 - assert all( - child.name.startswith(propyl.name) for child in cg_clone.children - ) + assert all(child.name.startswith(propyl.name) for child in cg_clone.children) assert cg_clone.wrapped.n_particles == 20 assert cg_clone.wrapped.n_bonds == 19 diff --git a/mbuild/tests/test_compound.py b/mbuild/tests/test_compound.py index aee4490db..bb8761187 100644 --- a/mbuild/tests/test_compound.py +++ b/mbuild/tests/test_compound.py @@ -1,6 +1,5 @@ import os import sys -import time import numpy as np import parmed as pmd @@ -10,8 +9,6 @@ from mbuild import Box, Compound, Particle, Port from mbuild.exceptions import MBuildError from mbuild.tests.base_test import BaseTest -from mbuild.utils.exceptions import RemovedFuncError -from mbuild.utils.geometry import calc_dihedral from mbuild.utils.io import ( get_fn, has_foyer, @@ -49,18 +46,9 @@ def test_load_conversion(self, ethane, h2o): topo_converted = mb.load(topo) assert isinstance(topo_converted, Compound) assert topo_converted.n_particles == 11 - assert ( - len([at for at in topo_converted.particles() if at.name == "C"]) - == 2 - ) - assert ( - len([at for at in topo_converted.particles() if at.name == "H"]) - == 8 - ) - assert ( - len([at for at in topo_converted.particles() if at.name == "O"]) - == 1 - ) + assert len([at for at in topo_converted.particles() if at.name == "C"]) == 2 + assert len([at for at in topo_converted.particles() if at.name == "H"]) == 8 + assert len([at for at in topo_converted.particles() if at.name == "O"]) == 1 for topo in [parm, traj]: new_topo = mb.load(compound) @@ -82,9 +70,7 @@ def test_load_conversion(self, ethane, h2o): assert test_converted2.n_bonds == test_converted2.n_bonds test_converted1.xyz = np.random.random(test_converted1.xyz.shape) - test_converted1 = mb.load( - test, compound=test_converted1, coords_only=True - ) + test_converted1 = mb.load(test, compound=test_converted1, coords_only=True) test_converted2.xyz = np.random.random(test_converted2.xyz.shape) test_converted2.from_parmed(test, coords_only=True) assert np.allclose(test_converted1.xyz, test_converted2.xyz) @@ -106,7 +92,7 @@ def test_n_bonds_particle(self): def test_direct_bonds_parent(self, methane): with pytest.raises(MBuildError): - bond_particles = [i for i in methane.direct_bonds()] + [i for i in methane.direct_bonds()] def test_direct_bonds(self, methane): bond_particles = [i for i in methane[0].direct_bonds()] @@ -296,9 +282,7 @@ def test_hierarchy(self, ethane): == '{"Ethane, 8 particles, 7 bonds, 2 children": {"children": [{"[CH3]: 4 particles, 3 bonds, 4 children": {"children": ["[C]: 1 particles, 4 bonds, 0 children", "[H]: 1 particles, 1 bonds, 0 children", "[H]: 1 particles, 1 bonds, 0 children", "[H]: 1 particles, 1 bonds, 0 children"]}}, {"[CH3]: 4 particles, 3 bonds, 4 children": {"children": ["[C]: 1 particles, 4 bonds, 0 children", "[H]: 1 particles, 1 bonds, 0 children", "[H]: 1 particles, 1 bonds, 0 children", "[H]: 1 particles, 1 bonds, 0 children"]}}]}}' ) - ethane_tree_full_index = ethane.print_hierarchy( - print_full=True, index=0 - ) + ethane_tree_full_index = ethane.print_hierarchy(print_full=True, index=0) assert ethane_tree_full_index.depth() == 2 tree_json_full_index = ethane_tree_full_index.to_json(with_data=False) assert ( @@ -497,13 +481,13 @@ def test_init_mass(self): assert bead_overwrite.mass == 1.0 bead_no_mass = mb.Compound(name="A") - assert bead_no_mass.mass == None + assert bead_no_mass.mass is None def test_init_with_bad_mass(self): with pytest.raises(MBuildError): a = mb.Compound(name="A") b = mb.Compound(name="B") - compound = mb.Compound(subcompounds=[a, b], mass=2.0) + mb.Compound(subcompounds=[a, b], mass=2.0) with pytest.raises(ValueError): mb.Compound(name="A", mass=-1.0) @@ -567,12 +551,12 @@ def test_mass_add_port(self): def test_none_mass(self): A = mb.Compound() - assert A.mass == None + assert A.mass is None container = mb.Compound(subcompounds=[A]) with pytest.warns(UserWarning): container_mass = container.mass - assert container_mass == None + assert container_mass is None A.mass = 1 B = mb.Compound() @@ -722,9 +706,7 @@ def test_freud_generate_bonds_mixed(self): child.name = "O" child.element = "O" - co_system.freud_generate_bonds( - name_a="C", name_b="O", dmin=0.0, dmax=0.16 - ) + co_system.freud_generate_bonds(name_a="C", name_b="O", dmin=0.0, dmax=0.16) assert co_system.n_bonds == 4 def test_remove_from_box(self, ethane): @@ -889,23 +871,17 @@ def test_center(self, methane): for orientation in np.identity(3): separation = 0.2 port = Port(anchor=methane[0], orientation=orientation) - assert np.allclose( - port.center, np.array([0.0, 0.0, 0.0]), atol=1e-15 - ) + assert np.allclose(port.center, np.array([0.0, 0.0, 0.0]), atol=1e-15) port = Port( anchor=methane[0], orientation=orientation, separation=separation, ) - assert np.allclose( - port.center, separation * orientation, atol=1e-15 - ) + assert np.allclose(port.center, separation * orientation, atol=1e-15) np.random.seed(0) for orientation in np.random.rand(5, 3): port = Port(anchor=methane[0], orientation=orientation) - assert np.allclose( - port.center, np.array([0.0, 0.0, 0.0]), atol=1e-15 - ) + assert np.allclose(port.center, np.array([0.0, 0.0, 0.0]), atol=1e-15) port = Port( anchor=methane[0], orientation=orientation, @@ -1091,9 +1067,7 @@ def test_reload(self): assert p3ht1.n_particles == 33 assert p3ht1.n_bonds == 33 - @pytest.mark.skipif( - not has_openbabel, reason="Open Bable package not installed" - ) + @pytest.mark.skipif(not has_openbabel, reason="Open Bable package not installed") def test_to_smiles(self, ethane, benzene): # Test predefined molecule eth_smiles = "CC" @@ -1107,9 +1081,7 @@ def test_to_smiles(self, ethane, benzene): compound = mb.load(smiles, smiles=True) assert compound.to_smiles() == smiles - @pytest.mark.parametrize( - "extension", [(".xyz"), (".pdb"), (".mol2"), (".gro")] - ) + @pytest.mark.parametrize("extension", [(".xyz"), (".pdb"), (".mol2"), (".gro")]) def test_update_coordinates(self, ethane, extension): ethane_clone = mb.clone(ethane) ethane_clone.xyz += [1, 1, 1] @@ -1250,9 +1222,7 @@ def test_mdtraj_box(self, h2o): tilted_box = Box(lengths=[2.0, 2.0, 2.0], angles=[60.0, 80.0, 100.0]) trajectory = compound.to_trajectory(box=tilted_box) assert np.all(np.isclose(trajectory.unitcell_lengths, [2.0, 2.0, 2.0])) - assert np.all( - np.isclose(trajectory.unitcell_angles, [60.0, 80.0, 100.0]) - ) + assert np.all(np.isclose(trajectory.unitcell_angles, [60.0, 80.0, 100.0])) @pytest.mark.skipif(not has_intermol, reason="InterMol is not installed") def test_intermol_conversion1(self, ethane, h2o): @@ -1305,9 +1275,7 @@ def test_parmed_conversion(self, ethane, h2o): assert len(structure.bonds) == 9 - assert sum(len(res.atoms) for res in structure.residues) == len( - structure.atoms - ) + assert sum(len(res.atoms) for res in structure.residues) == len(structure.atoms) compound2 = Compound() compound2.from_parmed(structure) @@ -1368,8 +1336,7 @@ def test_fillbox_then_parmed(self): assert isinstance(bead_box_in_pmd, pmd.Structure) assert len(bead_box_in_pmd.atoms) == 100 assert ( - bead_box_in_pmd.box - == np.array([10.0, 10.0, 10.0, 90.0, 90.0, 90.0]) + bead_box_in_pmd.box == np.array([10.0, 10.0, 10.0, 90.0, 90.0, 90.0]) ).all() def test_resnames_parmed(self, h2o, ethane): @@ -1382,35 +1349,27 @@ def test_resnames_parmed(self, h2o, ethane): assert struct.residues[0].name == "H2O" assert struct.residues[1].name == "H2O" assert struct.residues[2].name == "Ethane" - assert sum(len(res.atoms) for res in struct.residues) == len( - struct.atoms - ) + assert sum(len(res.atoms) for res in struct.residues) == len(struct.atoms) struct = system.to_parmed(residues="Ethane", infer_residues=True) assert len(struct.residues) == 2 assert struct.residues[0].name == "RES" assert struct.residues[1].name == "Ethane" - assert sum(len(res.atoms) for res in struct.residues) == len( - struct.atoms - ) + assert sum(len(res.atoms) for res in struct.residues) == len(struct.atoms) struct = system.to_parmed( infer_residues=False, ) assert len(struct.residues) == 1 assert struct.residues[0].name == "RES" - assert sum(len(res.atoms) for res in struct.residues) == len( - struct.atoms - ) + assert sum(len(res.atoms) for res in struct.residues) == len(struct.atoms) struct = system.to_parmed(infer_residues=True) assert len(struct.residues) == 3 assert struct.residues[0].name == "H2O" assert struct.residues[1].name == "H2O" assert struct.residues[2].name == "Ethane" - assert sum(len(res.atoms) for res in struct.residues) == len( - struct.atoms - ) + assert sum(len(res.atoms) for res in struct.residues) == len(struct.atoms) struct = system.to_parmed( infer_residues=True, @@ -1421,9 +1380,7 @@ def test_resnames_parmed(self, h2o, ethane): assert struct.residues[1].name == "H2O" assert struct.residues[2].name == "CH3" assert struct.residues[3].name == "CH3" - assert sum(len(res.atoms) for res in struct.residues) == len( - struct.atoms - ) + assert sum(len(res.atoms) for res in struct.residues) == len(struct.atoms) errmsg = "`segment_level` must be greater than zero." with pytest.raises(ValueError, match=errmsg): @@ -1448,9 +1405,7 @@ def test_resnames_parmed(self, h2o, ethane): assert struct.residues[5].name == "H" assert struct.residues[6].name == "CH3" assert struct.residues[7].name == "CH3" - assert sum(len(res.atoms) for res in struct.residues) == len( - struct.atoms - ) + assert sum(len(res.atoms) for res in struct.residues) == len(struct.atoms) def test_resnames_parmed_cg(self, benzene_from_SMILES, hexane, propyl): particles = [propyl.__class__] @@ -1469,9 +1424,7 @@ def test_resnames_parmed_cg(self, benzene_from_SMILES, hexane, propyl): two_beads = mb.Compound([mb.clone(cg), mb.clone(cg)]) two_beads.add_bond((two_beads.children[0][0], two_beads.children[1][0])) bonded_beads = two_beads - two_bonded_beads = mb.Compound( - [mb.clone(bonded_beads), mb.clone(bonded_beads)] - ) + two_bonded_beads = mb.Compound([mb.clone(bonded_beads), mb.clone(bonded_beads)]) struct = two_bonded_beads.to_parmed( infer_residues=True, infer_residues_kwargs={"segment_level": 1}, @@ -1553,10 +1506,11 @@ def test_resnames_parmed_cg(self, benzene_from_SMILES, hexane, propyl): # two_bonded beads should generate 8 residues (gets down to particle level) (16 total) # benzene gets down to particle levels (24 total) # hexane is goes from polymer down to monomer level. Made from two propyl groups which gives two monomers (4 total) - assert len( - struct.residues - ) == 2 * two_bonded_beads.n_particles + 2 * benzene_from_SMILES.n_particles + 2 * len( - hexane.children + assert ( + len(struct.residues) + == 2 * two_bonded_beads.n_particles + + 2 * benzene_from_SMILES.n_particles + + 2 * len(hexane.children) ) def test_parmed_element_guess(self): @@ -1573,39 +1527,28 @@ def test_parmed_box(self, h2o): compound.add(h2o) tilted_box = Box(lengths=[2.0, 2.0, 2.0], angles=[90.0, 90.0, 120.0]) structure = compound.to_parmed(box=tilted_box) - assert np.all( - np.isclose(structure.box, [20, 20, 20, 90.0, 90.0, 120.0]) - ) + assert np.all(np.isclose(structure.box, [20, 20, 20, 90.0, 90.0, 120.0])) def test_parmed_box_with_periodicity(self, h2o): compound = Compound() compound.add(h2o) compound.box = Box(lengths=[2.0, 2.0, 2.0], angles=[90.0, 90.0, 120.0]) structure = compound.to_parmed() - assert np.all( - np.isclose(structure.box, [20, 20, 20, 90.0, 90.0, 120.0]) - ) + assert np.all(np.isclose(structure.box, [20, 20, 20, 90.0, 90.0, 120.0])) def test_min_periodic_dist(self, ethane): compound = Compound(ethane) - C_pos = np.array( - [atom.pos for atom in list(compound.particles_by_name("C"))] - ) - assert ( - round(compound.min_periodic_distance(C_pos[0], C_pos[1]), 2) == 0.14 - ) + C_pos = np.array([atom.pos for atom in list(compound.particles_by_name("C"))]) + assert round(compound.min_periodic_distance(C_pos[0], C_pos[1]), 2) == 0.14 compound.box = Box(lengths=[0.2, 0.2, 0.2], angles=[90, 90, 90]) - assert ( - round(compound.min_periodic_distance(C_pos[0], C_pos[1]), 2) == 0.06 - ) + assert round(compound.min_periodic_distance(C_pos[0], C_pos[1]), 2) == 0.06 def test_bond_graph(self, ch3): compound = Compound() compound.add(ch3) assert compound.n_bonds == 3 assert all( - compound.bond_graph.has_node(particle) - for particle in ch3.particles() + compound.bond_graph.has_node(particle) for particle in ch3.particles() ) ch3_nobonds = mb.clone(ch3) @@ -1619,17 +1562,14 @@ def test_bond_graph(self, ch3): for particle in ch3_nobonds.particles() ) assert not any( - compound.bond_graph.has_edge(bond[0], bond[1]) - for bond in bonds_list + compound.bond_graph.has_edge(bond[0], bond[1]) for bond in bonds_list ) assert compound.bond_graph.has_edge carbons = list(compound.particles_by_name("C")) compound.add_bond((carbons[0], carbons[1])) assert compound.n_bonds == 4 - assert all( - compound.bond_graph.has_node(particle) for particle in carbons - ) + assert all(compound.bond_graph.has_node(particle) for particle in carbons) assert any( compound.bond_graph.has_node(particle) for particle in ch3_nobonds.particles() @@ -1680,9 +1620,7 @@ def test_is_independent_progression(self): assert ch3_1.is_independent() assert ch3_2.is_independent() - mb.force_overlap( - eth["methyl1"], eth["methyl1"]["up"], eth["methyl2"]["up"] - ) + mb.force_overlap(eth["methyl1"], eth["methyl1"]["up"], eth["methyl2"]["up"]) assert not ch3_1.is_independent() assert not ch3_2.is_independent() @@ -1725,7 +1663,7 @@ def test_charge(self, ch2, ch3): compound = Compound(charge=2.0) assert compound.charge == 2.0 compound2 = Compound() - assert compound2.charge == None + assert compound2.charge is None ch2[0].charge = 0.5 ch2[1].charge = -0.25 @@ -1819,22 +1757,12 @@ def test_energy_minimize_fix_compounds(self, octane): octane.energy_minimize(fixed_compounds=carbon_end) octane.energy_minimize(fixed_compounds=methyl_end0) octane.energy_minimize(fixed_compounds=[methyl_end0]) - octane.energy_minimize( - fixed_compounds=[methyl_end0, (True, True, True)] - ) + octane.energy_minimize(fixed_compounds=[methyl_end0, (True, True, True)]) - octane.energy_minimize( - fixed_compounds=[methyl_end0, (True, True, False)] - ) - octane.energy_minimize( - fixed_compounds=[methyl_end0, [True, True, False]] - ) - octane.energy_minimize( - fixed_compounds=[methyl_end0, (True, False, False)] - ) - octane.energy_minimize( - fixed_compounds=[methyl_end0, (False, False, False)] - ) + octane.energy_minimize(fixed_compounds=[methyl_end0, (True, True, False)]) + octane.energy_minimize(fixed_compounds=[methyl_end0, [True, True, False]]) + octane.energy_minimize(fixed_compounds=[methyl_end0, (True, False, False)]) + octane.energy_minimize(fixed_compounds=[methyl_end0, (False, False, False)]) octane.energy_minimize(fixed_compounds=[methyl_end0, methyl_end1]) octane.energy_minimize(fixed_compounds=[[methyl_end0], [methyl_end1]]) @@ -1850,17 +1778,13 @@ def test_energy_minimize_fix_compounds(self, octane): with pytest.raises(MBuildError): octane.energy_minimize(fixed_compounds=[not_in_compound]) with pytest.raises(MBuildError): - octane.energy_minimize( - fixed_compounds=[12323.3, (True, False, False)] - ) + octane.energy_minimize(fixed_compounds=[12323.3, (True, False, False)]) with pytest.raises(Exception): octane.energy_minimize( fixed_compounds=[methyl_end0, (True, False, False, False)] ) with pytest.raises(Exception): - octane.energy_minimize( - fixed_compounds=[methyl_end0, True, False, False] - ) + octane.energy_minimize(fixed_compounds=[methyl_end0, True, False, False]) with pytest.raises(Exception): octane.energy_minimize(fixed_compounds=[methyl_end0, True]) with pytest.raises(Exception): @@ -1874,17 +1798,11 @@ def test_energy_minimize_fix_compounds(self, octane): octane.energy_minimize(fixed_compounds=[methyl_end0, (True)]) with pytest.raises(Exception): - octane.energy_minimize( - fixed_compounds=[methyl_end0, ("True", True, True)] - ) + octane.energy_minimize(fixed_compounds=[methyl_end0, ("True", True, True)]) with pytest.raises(Exception): - octane.energy_minimize( - fixed_compounds=[methyl_end0, (True, "True", True)] - ) + octane.energy_minimize(fixed_compounds=[methyl_end0, (True, "True", True)]) with pytest.raises(Exception): - octane.energy_minimize( - fixed_compounds=[methyl_end0, (True, True, "True")] - ) + octane.energy_minimize(fixed_compounds=[methyl_end0, (True, True, "True")]) with pytest.raises(Exception): octane.energy_minimize( fixed_compounds=[methyl_end0, ("True", True, "True")] @@ -1902,9 +1820,7 @@ def test_energy_minimize_fix_compounds(self, octane): fixed_compounds=[methyl_end0, ("True", "True", "True")] ) with pytest.raises(Exception): - octane.energy_minimize( - fixed_compounds=[methyl_end0, (123.0, 231, "True")] - ) + octane.energy_minimize(fixed_compounds=[methyl_end0, (123.0, 231, "True")]) @pytest.mark.skipif(not has_openbabel, reason="Open Babel not installed") @pytest.mark.skipif( @@ -1965,9 +1881,7 @@ def test_energy_minimize_distance_constraints(self, octane): atol=1e-2, ) - octane.energy_minimize( - distance_constraints=[[(carbon_end0, carbon_end1), 0.7]] - ) + octane.energy_minimize(distance_constraints=[[(carbon_end0, carbon_end1), 0.7]]) octane.energy_minimize( distance_constraints=[ [(carbon_end0, carbon_end1), 0.7], @@ -2074,9 +1988,7 @@ def test_energy_minimize_openmm(self, octane): octane.energy_minimize(forcefield="oplsaa") @pytest.mark.skipif(not has_foyer, reason="Foyer is not installed") - @pytest.mark.parametrize( - "constraints", ["AllBonds", "HBonds", "HAngles", None] - ) + @pytest.mark.parametrize("constraints", ["AllBonds", "HBonds", "HAngles", None]) def test_energy_minimize_openmm_constraints(self, octane, constraints): octane.energy_minimize(forcefield="oplsaa", constraints=constraints) @@ -2093,7 +2005,7 @@ def test_clone_outside_containment(self, ch2, ch3): compound.add(ch2) mb.force_overlap(ch3, ch3["up"], ch2["up"]) with pytest.raises(MBuildError): - ch3_clone = mb.clone(ch3) + mb.clone(ch3) def test_load_nonelement_mol2(self): mb.load(get_fn("benzene-nonelement.mol2"), backend="mdtraj") @@ -2336,9 +2248,7 @@ def test_from_pybel_residues(self): def test_from_pybel_molecule(self, extension): pybel = import_("pybel") chol = list( - pybel.readfile( - extension, get_fn("cholesterol.{}".format(extension)) - ) + pybel.readfile(extension, get_fn("cholesterol.{}".format(extension))) )[0] cmpd = mb.Compound() cmpd.from_pybel(chol) @@ -2363,9 +2273,7 @@ def test_from_rdkit_smiles(self, test_smiles): for _ in range(3): cmpd = mb.load(test_smiles, smiles=True, backend="rdkit", seed=29) pos.append(cmpd.xyz) - assert ( - np.diff(np.vstack(pos).reshape(len(pos), -1), axis=0) == 0 - ).all() + assert (np.diff(np.vstack(pos).reshape(len(pos), -1), axis=0) == 0).all() @pytest.mark.skipif(not has_openbabel, reason="Pybel is not installed") def test_get_smiles(self): @@ -2376,10 +2284,7 @@ def test_get_smiles(self): try: assert my_cmp.get_smiles() == test_string except AssertionError: - assert ( - my_cmp.get_smiles() - == "CC(=O)OC1=C([CH][CH][CH][CH]1)C(=O)O" - ) + assert my_cmp.get_smiles() == "CC(=O)OC1=C([CH][CH][CH][CH]1)C(=O)O" else: assert my_cmp.get_smiles() == test_string @@ -2391,7 +2296,7 @@ def test_sdf(self, methane): def test_load_multiple_sdf(self, methane): filled = mb.fill_box(methane, n_compounds=10, box=Box([4, 4, 4])) filled.save("methane.sdf") - sdf_string = mb.load("methane.sdf") + mb.load("methane.sdf") def test_save_multiple_sdf(self, methane): filled = mb.fill_box(methane, n_compounds=10, box=[0, 0, 0, 4, 4, 4]) @@ -2403,7 +2308,7 @@ def test_box(self): angles = [90.0, 90.0, 90.0] lengths = [3.0, 3.0, 3.0] compound = Compound() - assert compound.box == None + assert compound.box is None compound.box = Box([3.0, 3.0, 3.0]) assert np.allclose(compound.box.lengths, lengths) assert np.allclose(compound.box.angles, angles) @@ -2412,7 +2317,7 @@ def test_box(self): with pytest.raises(TypeError, match=r"specified as an mbuild.Box"): compound.box = [3.0, 3.0, 3.0] port = Port() - assert port.box == None + assert port.box is None with pytest.raises(ValueError, match=r"cannot have"): port.box = Box(lengths=lengths, angles=angles) @@ -2428,9 +2333,7 @@ def test_box(self): assert np.allclose(compound.box.lengths, [3.0, 3.0, 3.0]) assert np.allclose(compound.box.angles, [90.0, 90.0, 90.0]) compound = Compound(box=Box(lengths=lengths, angles=angles)) - subcomp = Compound( - box=Box(lengths=[6.0, 6.0, 6.0], angles=[90.0, 90.0, 120.0]) - ) + subcomp = Compound(box=Box(lengths=[6.0, 6.0, 6.0], angles=[90.0, 90.0, 120.0])) compound.add(subcomp, inherit_box=True) assert np.allclose(compound.box.lengths, [6.0, 6.0, 6.0]) assert np.allclose(compound.box.angles, [90.0, 90.0, 120.0]) @@ -2485,9 +2388,7 @@ def test_get_boundingbox_extrema(self): decimal=6, ) - @pytest.mark.parametrize( - "bad_value", [[1.0, 2.0], set([1, 2, 3]), {"x": 1.0}] - ) + @pytest.mark.parametrize("bad_value", [[1.0, 2.0], set([1, 2, 3]), {"x": 1.0}]) def test_get_boundingbox_error(self, bad_value): with pytest.raises(TypeError): meth = mb.load(get_fn("methyl.pdb")) @@ -2503,9 +2404,7 @@ def test_visualize_py3dmol(self, ethane): def test_visualize_nglview(self, ethane): nglview = import_("nglview") vis_object = ethane._visualize_nglview() - assert isinstance( - vis_object.component_0, nglview.component.ComponentViewer - ) + assert isinstance(vis_object.component_0, nglview.component.ComponentViewer) def test_element(self): from ele import Elements @@ -2535,9 +2434,9 @@ def test_invalid_element(self): from ele.exceptions import ElementError with pytest.raises(ElementError, match=r"No element with symbol"): - na_compound = Compound(element="sodium") + Compound(element="sodium") with pytest.raises(ElementError, match=r"No element with symbol"): - na_compound = Compound(element="") + Compound(element="") def test_get_by_element(self): from ele import Elements @@ -2554,9 +2453,7 @@ def test_get_by_element(self): assert item == Elements.Na with pytest.raises(ElementError, match=r"No element with symbol"): - element_list = [ - c.element for c in container.particles_by_element("sod") - ] + element_list = [c.element for c in container.particles_by_element("sod")] @pytest.mark.parametrize("backend", ["pybel", "rdkit"]) def test_elements_from_smiles(self, backend): @@ -2621,10 +2518,7 @@ def test_residues_from_hierarchy(self, benzene, h2o): n_waters = 4 # box of multiple waters compound = mb.fill_box(h2o, n_waters, mb.Box([10, 10, 10])) - assert ( - len(pull_residues(compound, bond_graph=compound.bond_graph)) - == n_waters - ) + assert len(pull_residues(compound, bond_graph=compound.bond_graph)) == n_waters def test_catalog_bondgraph_types(self, benzene): from mbuild.conversion import catalog_bondgraph_type diff --git a/mbuild/tests/test_coordinate_transform.py b/mbuild/tests/test_coordinate_transform.py index 1dadedccc..b11d4515d 100644 --- a/mbuild/tests/test_coordinate_transform.py +++ b/mbuild/tests/test_coordinate_transform.py @@ -29,15 +29,13 @@ def test_apply_to(self): double = CoordinateTransform(T=np.eye(4) * 2) A = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]]) assert ( - double.apply_to(A) - == np.array([[2, 4, 6], [8, 10, 12], [14, 16, 18]]) + double.apply_to(A) == np.array([[2, 4, 6], [8, 10, 12], [14, 16, 18]]) ).all() def test_translation(self): translation = Translation((10, 10, 10)) assert ( - translation.apply_to(np.array([[1, 1, 1]])) - == np.array([11, 11, 11]) + translation.apply_to(np.array([[1, 1, 1]])) == np.array([11, 11, 11]) ).all() def test_rotation_around_z(self): @@ -65,9 +63,7 @@ def test_rotation(self): assert np.allclose(a, b, atol=1.0e-16) def test_change_of_basis(self): - change_basis = ChangeOfBasis( - np.array([[-2, 0, 0], [0, -2, 0], [0, 0, -2]]) - ) + change_basis = ChangeOfBasis(np.array([[-2, 0, 0], [0, -2, 0], [0, 0, -2]])) assert ( change_basis.apply_to(np.array([[2, 3, 4]])) == np.array([[-1.0, -1.5, -2.0]]) @@ -76,8 +72,7 @@ def test_change_of_basis(self): def test_axis_transform(self): origin_transform = AxisTransform(new_origin=np.array([1, 1, 1])) assert ( - origin_transform.apply_to(np.array([[1, 1, 1]])) - == np.array([[0, 0, 0]]) + origin_transform.apply_to(np.array([[1, 1, 1]])) == np.array([[0, 0, 0]]) ).all() orientation_transform = AxisTransform( point_on_x_axis=np.array([0, 0, 1]), @@ -91,8 +86,7 @@ def test_axis_transform(self): np.array([1, 1, 1]), np.array([1, 1, 2]), np.array([1, 2, 1]) ) assert ( - axis_transform.apply_to(np.array([[2, 3, 4]])) - == np.array([3, 2, -1]) + axis_transform.apply_to(np.array([[2, 3, 4]])) == np.array([3, 2, -1]) ).all() def test_rigid_transform(self): @@ -204,18 +198,14 @@ def test_spin_x(self, sixpoints): sixpoints.spin(np.pi, np.asarray([1, 0, 0])) assert np.allclose( sixpoints["up"].xyz, before["down"].xyz, atol=1e-16 - ) and np.allclose( - sixpoints["front"].xyz, before["back"].xyz, atol=1e-16 - ) + ) and np.allclose(sixpoints["front"].xyz, before["back"].xyz, atol=1e-16) def test_spin_y(self, sixpoints): before = mb.clone(sixpoints) sixpoints.spin(np.pi, np.asarray([0, 1, 0])) assert np.allclose( sixpoints["left"].xyz, before["right"].xyz, atol=1e-16 - ) and np.allclose( - sixpoints["front"].xyz, before["back"].xyz, atol=1e-16 - ) + ) and np.allclose(sixpoints["front"].xyz, before["back"].xyz, atol=1e-16) def test_spin_z(self, sixpoints): before = mb.clone(sixpoints) @@ -275,49 +265,49 @@ def test_rotate_around_x(self, methane): before = methane.xyz_with_ports methane.rotate(np.pi, around=np.asarray([1, 0, 0])) after = methane.xyz_with_ports - assert np.allclose( - before[:, 1], -1 * after[:, 1], atol=1e-16 - ) and np.allclose(before[:, 2], -1 * after[:, 2], atol=1e-16) + assert np.allclose(before[:, 1], -1 * after[:, 1], atol=1e-16) and np.allclose( + before[:, 2], -1 * after[:, 2], atol=1e-16 + ) def test_rotate_around_y(self, ch2): before = ch2.xyz_with_ports ch2.rotate(np.pi, around=np.asarray([0, 1, 0])) after = ch2.xyz_with_ports - assert np.allclose( - before[:, 0], -1 * after[:, 0], atol=1e-16 - ) and np.allclose(before[:, 2], -1 * after[:, 2], atol=1e-16) + assert np.allclose(before[:, 0], -1 * after[:, 0], atol=1e-16) and np.allclose( + before[:, 2], -1 * after[:, 2], atol=1e-16 + ) def test_rotate_around_z(self, ch2): before = ch2.xyz_with_ports ch2.rotate(np.pi, around=np.asarray([0, 0, 1])) after = ch2.xyz_with_ports - assert np.allclose( - before[:, 0], -1 * after[:, 0], atol=1e-16 - ) and np.allclose(before[:, 1], -1 * after[:, 1], atol=1e-16) + assert np.allclose(before[:, 0], -1 * after[:, 0], atol=1e-16) and np.allclose( + before[:, 1], -1 * after[:, 1], atol=1e-16 + ) def test_rotate_around_x_away_from_origin(self, sixpoints): before = sixpoints.xyz_with_ports sixpoints.rotate(np.pi, around=np.asarray([1, 0, 0])) after = sixpoints.xyz_with_ports - assert np.allclose( - before[:, 1], -1 * after[:, 1], atol=1e-16 - ) and np.allclose(before[:, 2], -1 * after[:, 2], atol=1e-16) + assert np.allclose(before[:, 1], -1 * after[:, 1], atol=1e-16) and np.allclose( + before[:, 2], -1 * after[:, 2], atol=1e-16 + ) def test_rotate_around_y_away_from_origin(self, sixpoints): before = sixpoints.xyz_with_ports sixpoints.rotate(np.pi, around=np.asarray([0, 1, 0])) after = sixpoints.xyz_with_ports - assert np.allclose( - before[:, 0], -1 * after[:, 0], atol=1e-16 - ) and np.allclose(before[:, 2], -1 * after[:, 2], atol=1e-16) + assert np.allclose(before[:, 0], -1 * after[:, 0], atol=1e-16) and np.allclose( + before[:, 2], -1 * after[:, 2], atol=1e-16 + ) def test_rotate_around_z_away_from_origin(self, sixpoints): before = sixpoints.xyz_with_ports sixpoints.rotate(np.pi, around=np.asarray([0, 0, 1])) after = sixpoints.xyz_with_ports - assert np.allclose( - before[:, 1], -1 * after[:, 1], atol=1e-16 - ) and np.allclose(before[:, 0], -1 * after[:, 0], atol=1e-16) + assert np.allclose(before[:, 1], -1 * after[:, 1], atol=1e-16) and np.allclose( + before[:, 0], -1 * after[:, 0], atol=1e-16 + ) def test_rotate_dihedral(self, ethane): bond = (ethane[0], ethane[4]) diff --git a/mbuild/tests/test_gmso.py b/mbuild/tests/test_gmso.py index 520ad944d..3b09fc103 100644 --- a/mbuild/tests/test_gmso.py +++ b/mbuild/tests/test_gmso.py @@ -2,7 +2,7 @@ import pytest import mbuild as mb -from mbuild.conversion import from_gmso, to_gmso +from mbuild.conversion import from_gmso from mbuild.tests.base_test import BaseTest from mbuild.utils.io import has_gmso, import_ @@ -19,9 +19,7 @@ def test_to_gmso(self, ethane): assert len(gmso_eth.bonds) == ethane.n_bonds for i in range(ethane.n_particles): assert ethane[i].name == gmso_eth.sites[i].name - assert np.isclose( - ethane[i].xyz, gmso_eth.sites[i].position.value - ).all() + assert np.isclose(ethane[i].xyz, gmso_eth.sites[i].position.value).all() def test_full_conversion(self, ethane): # Note: at this point, the full conversion may lose some information regarding the hierarchical, diff --git a/mbuild/tests/test_json_formats.py b/mbuild/tests/test_json_formats.py index 90a8dce8f..edcfe9604 100644 --- a/mbuild/tests/test_json_formats.py +++ b/mbuild/tests/test_json_formats.py @@ -27,11 +27,7 @@ def test_box(self): meth.box = mb.Box(lengths=(3, 3, 3), angles=(45, 45, 45)) meth.save("meth_with_box.json") meth_with_box = mb.load("meth_with_box.json") - assert ( - meth.n_particles - == meth_with_box.n_particles - == meth_no_box.n_particles - ) + assert meth.n_particles == meth_with_box.n_particles == meth_no_box.n_particles assert meth.n_bonds == meth_with_box.n_bonds == meth_no_box.n_bonds assert meth.box.lengths == meth_with_box.box.lengths == (3, 3, 3) assert meth.box.angles == meth_with_box.box.angles @@ -53,9 +49,7 @@ def test_loop_with_ports(self): assert ethane_copy.n_particles == ethane_without_overlap.n_particles assert ethane_copy.n_bonds == ethane_without_overlap.n_bonds assert len(ethane_copy.children) == len(ethane_without_overlap.children) - assert len(ethane_copy.all_ports()) == len( - ethane_without_overlap.all_ports() - ) + assert len(ethane_copy.all_ports()) == len(ethane_without_overlap.all_ports()) assert ethane_copy.labels.keys() == ethane_without_overlap.labels.keys() assert ( ethane_without_overlap["methyl2"].labels.keys() @@ -83,9 +77,7 @@ def test_nested_compound(self): port1 = mb.Port(anchor=this_child) this_child.add(port1, label="port{}".format(j + 1)) for k in range(num_grand_children): - this_grand_child = mb.Compound( - name="GrandChild{}".format(k + 1) - ) + this_grand_child = mb.Compound(name="GrandChild{}".format(k + 1)) this_child.add( this_grand_child, label="Child{0}GrandChild{1}".format(i + 1, k + 1), @@ -109,9 +101,7 @@ def test_label_consistency(self): parent_copy = compound_from_json("parent.json") assert len(parent_copy["CH2"]) == len(parent["CH2"]) assert parent_copy.labels.keys() == parent.labels.keys() - for child, child_copy in zip( - parent.successors(), parent_copy.successors() - ): + for child, child_copy in zip(parent.successors(), parent_copy.successors()): assert child.labels.keys() == child_copy.labels.keys() assert parent_copy.available_ports() == parent.available_ports() diff --git a/mbuild/tests/test_lattice.py b/mbuild/tests/test_lattice.py index d3e9acde5..4df70a7e5 100644 --- a/mbuild/tests/test_lattice.py +++ b/mbuild/tests/test_lattice.py @@ -98,12 +98,10 @@ def test_overdefinied_inputs(self): vectors = [[1, 0, 0], [0, 1, 0], [0, 0, 1]] angles = [90, 90, 90] with pytest.raises(ValueError): - mb.Lattice( - lattice_spacing=space, lattice_vectors=vectors, angles=angles - ) + mb.Lattice(lattice_spacing=space, lattice_vectors=vectors, angles=angles) @pytest.mark.parametrize("the_type", [(list()), (tuple()), (str()), ([])]) - def test_lattice_points_input_type(self, the_type): + def test_lattice_points_input_empty_type(self, the_type): with pytest.raises(TypeError): mb.Lattice(lattice_spacing=[1, 1, 1], lattice_points=the_type) @@ -156,9 +154,7 @@ def test_improper_angles(self, angles): ], ) def test_proper_angles(self, vectors, angles): - testlattice = mb.Lattice( - lattice_spacing=[1, 1, 1], lattice_vectors=vectors - ) + testlattice = mb.Lattice(lattice_spacing=[1, 1, 1], lattice_vectors=vectors) np.testing.assert_allclose( testlattice.angles, np.asarray(angles, dtype=np.float64), @@ -182,9 +178,7 @@ def test_proper_angles(self, vectors, angles): def test_incorrect_populate_inputs(self, x, y, z): with pytest.raises(ValueError): test_lattice = mb.Lattice(lattice_spacing=[1, 1, 1]) - test_lattice.populate( - compound_dict={"id": mb.Compound()}, x=x, y=y, z=z - ) + test_lattice.populate(compound_dict={"id": mb.Compound()}, x=x, y=y, z=z) @pytest.mark.parametrize("my_type", [([]), (()), (np.array), (np.ndarray)]) def test_populate_basis_type_incorrect(self, my_type): @@ -217,9 +211,7 @@ def test_proper_populate(self): [1, 0, 1], [1, 1, 1], ] - test_lattice = mb.Lattice( - lattice_spacing=[1, 1, 1], angles=[90, 90, 90] - ) + test_lattice = mb.Lattice(lattice_spacing=[1, 1, 1], angles=[90, 90, 90]) new_compound = test_lattice.populate(x=2, y=2, z=2) @@ -247,9 +239,7 @@ def test_box(self): replication = [2, 5, 9] np.testing.assert_allclose( compound_test.box.lengths, - np.asarray( - [x * y for x, y in zip(replication, lattice.lattice_spacing)] - ), + np.asarray([x * y for x, y in zip(replication, lattice.lattice_spacing)]), ) np.testing.assert_allclose( compound_test.box.angles, np.asarray([90.0, 90.0, 90.0]) @@ -267,9 +257,7 @@ def test_box_non_rectangular(self): replication = [2, 2, 1] np.testing.assert_allclose( compound_test.box.lengths, - np.asarray( - [x * y for x, y in zip(replication, lattice.lattice_spacing)] - ), + np.asarray([x * y for x, y in zip(replication, lattice.lattice_spacing)]), ) np.testing.assert_allclose( compound_test.box.angles, np.asarray([90.0, 90.0, 120.0]) @@ -283,9 +271,7 @@ def test_get_box(self): ) replication = [5, 4, 3] - expected_lengths = [ - x * y for x, y in zip(replication, lattice.lattice_spacing) - ] + expected_lengths = [x * y for x, y in zip(replication, lattice.lattice_spacing)] mylat = lattice.populate(x=5, y=4, z=3) @@ -301,9 +287,7 @@ def test_get_box_non_rectangular(self): ) replication = [2, 2, 1] - expected_lengths = [ - x * y for x, y in zip(replication, lattice.lattice_spacing) - ] + expected_lengths = [x * y for x, y in zip(replication, lattice.lattice_spacing)] mylat = lattice.populate(x=2, y=2, z=1) diff --git a/mbuild/tests/test_lib_molecule.py b/mbuild/tests/test_lib_molecule.py index c71274a0e..0e2b44c07 100644 --- a/mbuild/tests/test_lib_molecule.py +++ b/mbuild/tests/test_lib_molecule.py @@ -33,9 +33,7 @@ def test_water_3site(self, model, bond_length, angle): assert np.allclose(np.linalg.norm(v2), bond_length) assert np.allclose( np.degrees( - np.arccos( - np.dot(v1, v2) / (np.linalg.norm(v1) * np.linalg.norm(v2)) - ) + np.arccos(np.dot(v1, v2) / (np.linalg.norm(v1) * np.linalg.norm(v2))) ), angle, ) @@ -70,9 +68,7 @@ def test_water_4site(self, model, bond_length, vsite_length, angle): assert np.allclose(np.linalg.norm(v3), vsite_length) assert np.allclose( np.degrees( - np.arccos( - np.dot(v1, v2) / (np.linalg.norm(v1) * np.linalg.norm(v2)) - ) + np.arccos(np.dot(v1, v2) / (np.linalg.norm(v1) * np.linalg.norm(v2))) ), angle, ) diff --git a/mbuild/tests/test_monolayer.py b/mbuild/tests/test_monolayer.py index c27845508..0e04c0ea7 100644 --- a/mbuild/tests/test_monolayer.py +++ b/mbuild/tests/test_monolayer.py @@ -2,7 +2,7 @@ import mbuild as mb from mbuild.lib.atoms import H -from mbuild.lib.recipes import Monolayer, Polymer +from mbuild.lib.recipes import Monolayer from mbuild.lib.surfaces import Betacristobalite from mbuild.tests.base_test import BaseTest @@ -55,9 +55,7 @@ def test_periodic_pattern(self, ch2): chain.create_periodic_bond(axis=axis) assert not chain.all_ports() - bonded_atoms = [ - x.name for x in list(chain["monomer[0]"][0].direct_bonds()) - ] + bonded_atoms = [x.name for x in list(chain["monomer[0]"][0].direct_bonds())] assert bonded_atoms.count("H") == 2 assert bonded_atoms.count("C") == 2 diff --git a/mbuild/tests/test_packing.py b/mbuild/tests/test_packing.py index a364772b4..eba091b6b 100644 --- a/mbuild/tests/test_packing.py +++ b/mbuild/tests/test_packing.py @@ -20,9 +20,7 @@ def test_fill_box(self, h2o): def test_fill_box_density_box(self, h2o): filled = mb.fill_box(h2o, n_compounds=100, density=100) - assert np.all( - np.isclose(filled.box.lengths, np.ones(3) * 3.104281669169261) - ) + assert np.all(np.isclose(filled.box.lengths, np.ones(3) * 3.104281669169261)) def test_fill_box_aspect_ratio(self, h2o): filled = mb.fill_box( @@ -85,9 +83,7 @@ def test_fill_sphere_bad_args(self, h2o, ethane): compound=[h2o, ethane], n_compounds=1000, sphere=[1, 1, 1, 4] ) with pytest.raises(ValueError): - mb.fill_sphere( - compound=h2o, n_compounds=[10, 10], sphere=[1, 1, 1, 4] - ) + mb.fill_sphere(compound=h2o, n_compounds=[10, 10], sphere=[1, 1, 1, 4]) with pytest.raises(ValueError): mb.fill_sphere(compound=h2o, n_compounds=100, sphere=[1, 1, 1, 4]) @@ -134,16 +130,12 @@ def test_fill_region_multiple(self, ethane, h2o): def test_fill_region_incorrect_type(self, ethane): box1 = {"a": 1} with pytest.raises(ValueError, match=r"expected a list of type:"): - mb.fill_region( - compound=[ethane], n_compounds=[2], region=box1, bounds=None - ) + mb.fill_region(compound=[ethane], n_compounds=[2], region=box1, bounds=None) def test_fill_region_bounds_not_list(self, ethane): box1 = Box(lengths=[2, 2, 2], angles=[90.0, 90.0, 90.0]) with pytest.raises(TypeError): - mb.fill_region( - compound=[ethane], n_compounds=[2], region=box1, bounds=box1 - ) + mb.fill_region(compound=[ethane], n_compounds=[2], region=box1, bounds=box1) def test_fill_region_incorrect_bounds_amount(self, ethane, h2o): box1 = Box(lengths=[2, 2, 2], angles=[90.0, 90.0, 90.0]) @@ -167,9 +159,7 @@ def test_fill_region_incorrect_bounds_types(self, ethane, h2o): def test_box_no_bound(self, ethane): box1 = Box(lengths=[2, 2, 2], angles=[90.0, 90.0, 90.0]) - mb.fill_region( - compound=[ethane], n_compounds=[2], region=box1, bounds=None - ) + mb.fill_region(compound=[ethane], n_compounds=[2], region=box1, bounds=None) def test_fill_region_multiple_bounds(self, ethane, h2o): box1 = Box.from_mins_maxs_angles( @@ -222,17 +212,12 @@ def test_solvate(self, ethane, h2o): ethane, h2o, n_solvent=n_solvent, box=[4, 4, 4], center_solute=False ) - print(ethane.xyz) - print(solvated2.children[0].xyz) - - assert ( - solvated1.n_particles == solvated2.n_particles == 8 + n_solvent * 3 - ) + assert solvated1.n_particles == solvated2.n_particles == 8 + n_solvent * 3 assert solvated1.n_bonds == solvated2.n_bonds == 7 + n_solvent * 2 assert not np.isclose(solvated1.children[0].pos, ethane_pos).all() assert np.isclose(solvated2.children[0].pos, ethane_pos).all() - assert ethane.parent == None + assert ethane.parent is None def test_solvate_multiple(self, methane, ethane, h2o): init_box = mb.fill_box(methane, 2, box=[4, 4, 4]) @@ -249,9 +234,9 @@ def test_fill_box_seed(self, ethane): def test_wrong_box(self, h2o): with pytest.raises(MBuildError): - filled = mb.fill_box(h2o, n_compounds=50, box=[2, 2]) + mb.fill_box(h2o, n_compounds=50, box=[2, 2]) with pytest.raises(MBuildError): - filled = mb.fill_box(h2o, n_compounds=50, box=[2, 2, 2, 2]) + mb.fill_box(h2o, n_compounds=50, box=[2, 2, 2, 2]) def test_bad_args(self, h2o): with pytest.raises(ValueError): @@ -265,9 +250,7 @@ def test_bad_args(self, h2o): with pytest.raises(ValueError): mb.fill_box(compound=[h2o, h2o], n_compounds=[10], density=1000) with pytest.raises(ValueError): - mb.solvate( - solute=h2o, solvent=[h2o], n_solvent=[10, 10], box=[2, 2, 2] - ) + mb.solvate(solute=h2o, solvent=[h2o], n_solvent=[10, 10], box=[2, 2, 2]) with pytest.raises(ValueError): mb.fill_region(h2o, n_compounds=[10, 10], region=[2, 2, 2, 4, 4, 4]) with pytest.raises(ValueError): @@ -283,16 +266,14 @@ def test_write_temp_file(self, h2o): filled = mb.fill_box( h2o, n_compounds=10, box=Box([4, 4, 4]), temp_file="temp_file1.pdb" ) - region = mb.fill_region( + mb.fill_region( h2o, 10, [[2, 2, 2, 4, 4, 4]], temp_file="temp_file2.pdb", bounds=[[2, 2, 2, 4, 4, 4]], ) - solvated = mb.solvate( - filled, h2o, 10, box=[4, 4, 4], temp_file="temp_file3.pdb" - ) + mb.solvate(filled, h2o, 10, box=[4, 4, 4], temp_file="temp_file3.pdb") assert os.path.isfile(os.path.join(cwd, "temp_file1.pdb")) assert os.path.isfile(os.path.join(cwd, "temp_file2.pdb")) assert os.path.isfile(os.path.join(cwd, "temp_file3.pdb")) @@ -447,26 +428,22 @@ def test_remove_port(self): butane = Alkane(n=4) butane.remove(butane[-1]) - box = mb.fill_box(butane, n_compounds=10, density=1) + mb.fill_box(butane, n_compounds=10, density=1) def test_sidemax(self): from mbuild.lib.molecules import Methane ch4 = Methane() # With default sidemax - box_of_methane = mb.fill_box( - ch4, box=[1000, 1000, 1000], n_compounds=500 - ) + box_of_methane = mb.fill_box(ch4, box=[1000, 1000, 1000], n_compounds=500) sphere_of_methane = mb.fill_sphere( ch4, sphere=[1000, 1000, 1000, 1000], n_compounds=500 ) assert all( - np.asarray(box_of_methane.get_boundingbox().lengths) - < [110, 110, 110] + np.asarray(box_of_methane.get_boundingbox().lengths) < [110, 110, 110] ) assert all( - np.asarray(sphere_of_methane.get_boundingbox().lengths) - < [210, 210, 210] + np.asarray(sphere_of_methane.get_boundingbox().lengths) < [210, 210, 210] ) # With adjusted sidemax @@ -481,8 +458,7 @@ def test_sidemax(self): ) assert all( - np.asarray(big_box_of_methane.get_boundingbox().lengths) - > [900, 900, 900] + np.asarray(big_box_of_methane.get_boundingbox().lengths) > [900, 900, 900] ) assert all( np.asarray(big_sphere_of_methane.get_boundingbox().lengths) @@ -491,31 +467,23 @@ def test_sidemax(self): def test_box_edge(self, h2o, methane): system_box = mb.Box(lengths=(1.8, 1.8, 1.8)) - packed = mb.fill_box( - compound=h2o, n_compounds=100, box=system_box, edge=0.2 - ) - edge_sizes = np.subtract( - system_box.lengths, packed.get_boundingbox().lengths - ) + packed = mb.fill_box(compound=h2o, n_compounds=100, box=system_box, edge=0.2) + edge_sizes = np.subtract(system_box.lengths, packed.get_boundingbox().lengths) assert np.allclose(edge_sizes, np.array([0.4] * 3), atol=0.1) - region = mb.fill_region( + mb.fill_region( compound=h2o, n_compounds=100, region=system_box, edge=0.2, bounds=[system_box], ) - edge_sizes = np.subtract( - system_box.lengths, packed.get_boundingbox().lengths - ) + edge_sizes = np.subtract(system_box.lengths, packed.get_boundingbox().lengths) assert np.allclose(edge_sizes, np.array([0.4] * 3), atol=0.1) edge = 0.2 bounds = [2, 2, 2, 1] - sphere = mb.fill_sphere( - compound=h2o, n_compounds=120, sphere=bounds, edge=edge - ) + sphere = mb.fill_sphere(compound=h2o, n_compounds=120, sphere=bounds, edge=edge) target_diameter = (bounds[3] - edge) * 2 assert np.allclose( sphere.maxs - sphere.mins, np.array([target_diameter] * 3), atol=0.1 @@ -528,9 +496,7 @@ def test_box_edge(self, h2o, methane): box=system_box, overlap=0.2, ) - edge_sizes = np.subtract( - system_box.lengths, solvated.get_boundingbox().lengths - ) + edge_sizes = np.subtract(system_box.lengths, solvated.get_boundingbox().lengths) assert np.allclose(edge_sizes, np.array([0.4] * 3), atol=0.1) def test_validate_mass(self, methane): diff --git a/mbuild/tests/test_pattern.py b/mbuild/tests/test_pattern.py index b2c583863..7b0cbe1de 100644 --- a/mbuild/tests/test_pattern.py +++ b/mbuild/tests/test_pattern.py @@ -162,16 +162,8 @@ def test_scaling(self): def test_scaling_error_string(self): with pytest.raises(TypeError): - pattern = mb.Random3DPattern(10, scale="tim") + mb.Random3DPattern(10, scale="tim") def test_scaling_error_dict(self): with pytest.raises(TypeError): - pattern = mb.Random3DPattern(10, scale={"name": "tim"}) - - def test_scaling_error_dict(self): - with pytest.raises(TypeError): - pattern = mb.Random3DPattern(10, scale={"name": "tim"}) - - def test_scaling_error_dict(self): - with pytest.raises(TypeError): - pattern = mb.Random3DPattern(10, scale={"name": "tim"}) + mb.Random3DPattern(10, scale={"name": "tim"}) diff --git a/mbuild/tests/test_plugins.py b/mbuild/tests/test_plugins.py index 6dad8e82c..4b9c17471 100644 --- a/mbuild/tests/test_plugins.py +++ b/mbuild/tests/test_plugins.py @@ -5,7 +5,7 @@ class TestPlugins(BaseTest): def test_basic_import(self): - import mbuild.recipes + pass @pytest.mark.parametrize( "recipe_name", diff --git a/mbuild/tests/test_polymer.py b/mbuild/tests/test_polymer.py index 0bf67161d..b04b708e7 100644 --- a/mbuild/tests/test_polymer.py +++ b/mbuild/tests/test_polymer.py @@ -11,9 +11,7 @@ class TestPolymer(BaseTest): def test_polymer_from_smiles(self): chain = mb.recipes.Polymer() ethane = mb.load("CC", smiles=True) - chain.add_monomer( - ethane, indices=[2, -2], separation=0.15, replace=True - ) + chain.add_monomer(ethane, indices=[2, -2], separation=0.15, replace=True) chain.build(n=5, add_hydrogens=True) assert len([p for p in chain.particles() if p.name == "C"]) == 10 assert len([p for p in chain.particles() if p.name == "H"]) == 22 @@ -57,9 +55,7 @@ def test_errors(self, ch2, ester): def test_no_end_groups(self): chain = mb.recipes.Polymer() ethane = mb.load("CC", smiles=True) - chain.add_monomer( - ethane, indices=[2, -2], separation=0.15, replace=True - ) + chain.add_monomer(ethane, indices=[2, -2], separation=0.15, replace=True) chain.build(n=5, add_hydrogens=False) assert len([p for p in chain.particles() if p.name == "H"]) == 20 assert len(chain.available_ports()) == 2 diff --git a/mbuild/tests/test_port.py b/mbuild/tests/test_port.py index 9c5ee441a..6415d7bae 100644 --- a/mbuild/tests/test_port.py +++ b/mbuild/tests/test_port.py @@ -13,16 +13,12 @@ def test_port_center(self): def test_port_shift(self, ethane): ethane.translate_to(np.ones(3)) port = mb.Port(anchor=ethane) - assert [ - ethane.center[i] == coord for i, coord in enumerate(port.center) - ] + assert [ethane.center[i] == coord for i, coord in enumerate(port.center)] def test_port_init_shift_0(self, ethane): ethane.translate_to(np.ones(3)) port = mb.Port(anchor=ethane, separation=0) - assert [ - ethane.center[i] == coord for i, coord in enumerate(port.center) - ] + assert [ethane.center[i] == coord for i, coord in enumerate(port.center)] def test_port_init_shift(self, ethane): ethane.translate_to(np.ones(3)) @@ -36,23 +32,17 @@ def test_port_init_shift(self, ethane): def test_port_init_rotate_0(self, ethane): port1 = mb.Port(anchor=ethane, orientation=[0, 1, 0]) port2 = mb.Port(anchor=ethane) - assert np.allclose( - port1.xyz_with_ports, port2.xyz_with_ports, atol=1e-15 - ) + assert np.allclose(port1.xyz_with_ports, port2.xyz_with_ports, atol=1e-15) def test_port_init_rotate(self, ethane): port1 = mb.Port(anchor=ethane, orientation=[1, 1, 1]) port2 = mb.Port(anchor=ethane) - assert not np.allclose( - port1.xyz_with_ports, port2.xyz_with_ports, atol=1e-15 - ) + assert not np.allclose(port1.xyz_with_ports, port2.xyz_with_ports, atol=1e-15) def test_port_init_rotate_180(self, ethane): port1 = mb.Port(anchor=ethane, orientation=[0, -1, 0]) port2 = mb.Port(anchor=ethane) - assert not np.allclose( - port1.xyz_with_ports, port2.xyz_with_ports, atol=1e-15 - ) + assert not np.allclose(port1.xyz_with_ports, port2.xyz_with_ports, atol=1e-15) def test_port_direction(self): port = mb.Port() @@ -101,12 +91,8 @@ def test_up_down_reverse_orientation_axes(self): for vector in [[1, 0, 0], [0, 1, 0], [0, 0, 1]]: port1 = mb.Port(orientation=vector) port2 = mb.Port(orientation=-np.array(vector)) - assert np.allclose( - port1["up"].xyz_with_ports, port2["down"].xyz_with_ports - ) - assert np.allclose( - port1["down"].xyz_with_ports, port2["up"].xyz_with_ports - ) + assert np.allclose(port1["up"].xyz_with_ports, port2["down"].xyz_with_ports) + assert np.allclose(port1["down"].xyz_with_ports, port2["up"].xyz_with_ports) def test_up_down_reverse_orientation_random(self): np.random.seed(84) @@ -114,12 +100,8 @@ def test_up_down_reverse_orientation_random(self): vector = np.random.random(3) - 0.5 port1 = mb.Port(orientation=vector) port2 = mb.Port(orientation=-vector) - assert np.allclose( - port1["up"].xyz_with_ports, port2["down"].xyz_with_ports - ) - assert np.allclose( - port1["down"].xyz_with_ports, port2["up"].xyz_with_ports - ) + assert np.allclose(port1["up"].xyz_with_ports, port2["down"].xyz_with_ports) + assert np.allclose(port1["down"].xyz_with_ports, port2["up"].xyz_with_ports) def test_port_access_labels(self, ethane): ethane.remove(ethane[2]) diff --git a/mbuild/tests/test_silica_interface.py b/mbuild/tests/test_silica_interface.py index 32b7878aa..4eb562a19 100644 --- a/mbuild/tests/test_silica_interface.py +++ b/mbuild/tests/test_silica_interface.py @@ -1,10 +1,3 @@ -import numpy as np - -import mbuild as mb -from mbuild.lib.bulk_materials import AmorphousSilicaBulk -from mbuild.lib.recipes import SilicaInterface -from mbuild.tests.base_test import BaseTest - """ class TestSilicaInterface(BaseTest): def test_silica_interface(self): diff --git a/mbuild/tests/test_silica_surface.py b/mbuild/tests/test_silica_surface.py index 1df0a8fd6..d7545a1b3 100644 --- a/mbuild/tests/test_silica_surface.py +++ b/mbuild/tests/test_silica_surface.py @@ -18,4 +18,4 @@ def test_create_amorphous_silica_surface(self): def test_amorphous_silica_surface_error(self): with pytest.raises(ValueError): - surface = AmorphousSilicaSurface(surface_roughness=2) + AmorphousSilicaSurface(surface_roughness=2) diff --git a/mbuild/tests/test_utils.py b/mbuild/tests/test_utils.py index 07277d982..ab61a4894 100644 --- a/mbuild/tests/test_utils.py +++ b/mbuild/tests/test_utils.py @@ -1,5 +1,4 @@ import difflib -from warnings import warn import numpy as np import pytest @@ -76,7 +75,9 @@ def test_structure_reproducibility(self): with open(get_fn("decane.xyz")) as file1: with open(filename) as file2: diff = difflib.ndiff(file1.readlines(), file2.readlines()) - changes = [l for l in diff if l.startswith("+ ") or l.startswith("- ")] + changes = [ + line for line in diff if line.startswith("+ ") or line.startswith("- ") + ] assert not changes def test_fn(self): @@ -183,7 +184,7 @@ def test_coord_wrap_box(self): assert (new_xyz[1, :] == xyz[1, :]).all() def test_has_ipython(self): - __IPYTHON__ = None + __IPYTHON__ = None # noqa: F841 assert run_from_ipython() is False def test_removed_func_error(self): @@ -237,7 +238,7 @@ def test_RB_to_OPLS_f0_not_0_within_tolerance_error(self): ) with pytest.raises( - TypeError, + ValueError, match=f"{text_for_error_tolerance}", ): c0 = 0.4 @@ -248,7 +249,7 @@ def test_RB_to_OPLS_f0_not_0_within_tolerance_error(self): c5 = 0 RB_to_OPLS(c0, c1, c2, c3, c4, c5) - def test_RB_to_OPLS_f0_not_0_within_tolerance_error(self): + def test_RB_to_OPLS_f0_not_0_within_tolerance_error_s(self): with pytest.raises( TypeError, match=f"The error_tolerance variable must be a float, is type {type('s')}.", @@ -319,34 +320,22 @@ def test_RB_to_OPLS_and_back_random_values(self, c0, c1, c2, c3, c4, c5): ) assert np.all( - np.isclose( - c0, reversed_RB_coeffs[0], atol=test_error_tolerance, rtol=0 - ) + np.isclose(c0, reversed_RB_coeffs[0], atol=test_error_tolerance, rtol=0) ) assert np.all( - np.isclose( - c1, reversed_RB_coeffs[1], atol=test_error_tolerance, rtol=0 - ) + np.isclose(c1, reversed_RB_coeffs[1], atol=test_error_tolerance, rtol=0) ) assert np.all( - np.isclose( - c2, reversed_RB_coeffs[2], atol=test_error_tolerance, rtol=0 - ) + np.isclose(c2, reversed_RB_coeffs[2], atol=test_error_tolerance, rtol=0) ) assert np.all( - np.isclose( - c3, reversed_RB_coeffs[3], atol=test_error_tolerance, rtol=0 - ) + np.isclose(c3, reversed_RB_coeffs[3], atol=test_error_tolerance, rtol=0) ) assert np.all( - np.isclose( - c4, reversed_RB_coeffs[4], atol=test_error_tolerance, rtol=0 - ) + np.isclose(c4, reversed_RB_coeffs[4], atol=test_error_tolerance, rtol=0) ) assert np.all( - np.isclose( - c5, reversed_RB_coeffs[5], atol=test_error_tolerance, rtol=0 - ) + np.isclose(c5, reversed_RB_coeffs[5], atol=test_error_tolerance, rtol=0) ) def test_OPLS_to_RB_error_tolerance_not_float(self): diff --git a/mbuild/tests/test_vasp.py b/mbuild/tests/test_vasp.py index db7e53905..383a070c4 100644 --- a/mbuild/tests/test_vasp.py +++ b/mbuild/tests/test_vasp.py @@ -1,7 +1,6 @@ import numpy as np import pytest -import mbuild as mb from mbuild.formats.vasp import read_poscar, write_poscar from mbuild.tests.base_test import BaseTest @@ -42,9 +41,7 @@ def test_bravais(self, copper_cell): with open("test.poscar", "r") as f: lines = f.readlines() - bravais = np.stack( - [np.fromstring(line, sep=" ") for line in lines[2:5]] - ) + bravais = np.stack([np.fromstring(line, sep=" ") for line in lines[2:5]]) # zero the diagonal for i in range(3): diff --git a/mbuild/tests/test_water_box.py b/mbuild/tests/test_water_box.py index 6b450c14f..eefa38332 100644 --- a/mbuild/tests/test_water_box.py +++ b/mbuild/tests/test_water_box.py @@ -50,8 +50,6 @@ def test_replicate(self): assert wb.n_particles == 13227 def test_mask(self, ethane): - box_temp = mb.Box([2.0, 2.0, 1.0]) - grid_pattern = mb.Grid3DPattern(6, 6, 4) grid_pattern.scale([2, 2, 1]) ethane_system_list = grid_pattern.apply(ethane) @@ -117,9 +115,7 @@ def test_mask(self, ethane): assert wb.n_particles == 291 def test_model(self): - wb = Water3SiteBox( - box=mb.Box([2.0, 2.0, 2.0]), model=water_models.WaterSPC() - ) + wb = Water3SiteBox(box=mb.Box([2.0, 2.0, 2.0]), model=water_models.WaterSPC()) assert wb.children[0].name == "WaterSPC" parts = [p for p in wb.children[0].particles()] @@ -133,9 +129,7 @@ def test_model(self): v1_u = v1 / np.linalg.norm(v1) v2_u = v2 / np.linalg.norm(v2) - angle = ( - np.arccos(np.clip(np.dot(v1_u, v2_u), -1.0, 1.0)) * 180.0 / np.pi - ) + angle = np.arccos(np.clip(np.dot(v1_u, v2_u), -1.0, 1.0)) * 180.0 / np.pi assert np.isclose(angle, 109.47) @@ -159,9 +153,7 @@ def test_bad_model(self): bad_model = mb.Compound() oxygen = mb.Compound(name="O", element="O") hydrogen = mb.Compound(name="H", element="H") - bad_model.add( - [mb.clone(hydrogen), mb.clone(oxygen), mb.clone(hydrogen)] - ) + bad_model.add([mb.clone(hydrogen), mb.clone(oxygen), mb.clone(hydrogen)]) with pytest.raises(MBuildError): Water3SiteBox(box=mb.Box([2.0, 2.0, 2.0]), model=bad_model) @@ -170,9 +162,7 @@ def test_bad_model2(self): bad_model = mb.Compound() oxygen = mb.Compound(name="O", element="O") hydrogen = mb.Compound(name="H", element="H") - bad_model.add( - [mb.clone(hydrogen), mb.clone(oxygen), mb.clone(hydrogen)] - ) + bad_model.add([mb.clone(hydrogen), mb.clone(oxygen), mb.clone(hydrogen)]) with pytest.raises(MBuildError): Water3SiteBox(box=mb.Box([2.0, 2.0, 2.0]), model=[bad_model]) @@ -181,9 +171,7 @@ def test_bad_dict(self): bad_model = mb.Compound() oxygen = mb.Compound(name="O", element="O") hydrogen = mb.Compound(name="H", element="H") - bad_model.add( - [mb.clone(hydrogen), mb.clone(oxygen), mb.clone(hydrogen)] - ) + bad_model.add([mb.clone(hydrogen), mb.clone(oxygen), mb.clone(hydrogen)]) with pytest.raises(ValueError): Water3SiteBox( diff --git a/mbuild/utils/conversion.py b/mbuild/utils/conversion.py index bd3c47a97..0703ffa11 100644 --- a/mbuild/utils/conversion.py +++ b/mbuild/utils/conversion.py @@ -76,9 +76,7 @@ def RB_to_OPLS( ) if not np.all(np.isclose(c5, 0, atol=1e-10, rtol=0)): - raise ValueError( - "c5 must equal zero, so this conversion is not possible." - ) + raise ValueError("c5 must equal zero, so this conversion is not possible.") f0 = 2.0 * (c0 + c1 + c2 + c3 + c4 + c5) if not np.all(np.isclose(f0 / 2, 0, atol=error_tolerance, rtol=0)): diff --git a/mbuild/utils/decorators.py b/mbuild/utils/decorators.py index 4a6a08960..ddf26b6ee 100644 --- a/mbuild/utils/decorators.py +++ b/mbuild/utils/decorators.py @@ -114,9 +114,7 @@ def breaking_change(warning_string=""): def old_function(fcn): def wrapper(*args, **kwargs): - warn( - f"{fcn.__name__} has breaking change. {warning_string}", Warning - ) + warn(f"{fcn.__name__} has breaking change. {warning_string}", Warning) fcn(*args, **kwargs) return wrapper diff --git a/mbuild/utils/exceptions.py b/mbuild/utils/exceptions.py index 7beca5878..d2c545da3 100644 --- a/mbuild/utils/exceptions.py +++ b/mbuild/utils/exceptions.py @@ -4,9 +4,7 @@ class RemovedFuncError(Exception): """Exception for mBuild functions that have been deprecated and removed.""" - def __init__( - self, deprecated_func, new_func, version_deprecated, version_removed - ): + def __init__(self, deprecated_func, new_func, version_deprecated, version_removed): self.deprecated_func = deprecated_func self.new_func = new_func self.version_deprecated = version_deprecated diff --git a/mbuild/utils/geometry.py b/mbuild/utils/geometry.py index 972fd1e3b..fad27db2d 100644 --- a/mbuild/utils/geometry.py +++ b/mbuild/utils/geometry.py @@ -92,10 +92,7 @@ def wrap_coords(xyz, box, mins=None): xyz = xyz - mins wrap_xyz = ( xyz - - ( - np.floor_divide(xyz, np.asarray(box.lengths)) - * np.asarray(box.lengths) - ) + - (np.floor_divide(xyz, np.asarray(box.lengths)) * np.asarray(box.lengths)) + mins ) diff --git a/mbuild/utils/io.py b/mbuild/utils/io.py index 7c2f2e0f0..2faa37e81 100644 --- a/mbuild/utils/io.py +++ b/mbuild/utils/io.py @@ -1,3 +1,4 @@ +# ruff: noqa: F401 """Module for working with external libraries. Portions of this code are adapted from MDTraj and are released under the @@ -37,9 +38,7 @@ class DelayImportError(ImportError, SkipTest): MESSAGES = dict() -MESSAGES[ - "gsd" -] = """ +MESSAGES["gsd"] = """ The code at {filename}:{line_number} requires the "gsd" package gsd can be installed with conda using: @@ -47,9 +46,7 @@ class DelayImportError(ImportError, SkipTest): # conda install -c conda-forge gsd """ -MESSAGES[ - "nglview" -] = """ +MESSAGES["nglview"] = """ The code at {filename}:{line_number} requires the "nglview" package nglview can be installed using: @@ -61,9 +58,7 @@ class DelayImportError(ImportError, SkipTest): # pip install nglview """ -MESSAGES[ - "py3Dmol" -] = """ +MESSAGES["py3Dmol"] = """ The code at {filename}:{line_number} requires the "py3Dmol" package py3Dmol can be installed using: @@ -75,9 +70,7 @@ class DelayImportError(ImportError, SkipTest): # pip install py3Dmol """ -MESSAGES[ - "rdkit" -] = """ +MESSAGES["rdkit"] = """ The code at {filename}:{line_number} requires the "rdkit" package rdkit can be installed with conda using: @@ -89,9 +82,7 @@ class DelayImportError(ImportError, SkipTest): https://www.rdkit.org/docs/Install.html#installation-from-source """ -MESSAGES[ - "openbabel" -] = """ +MESSAGES["openbabel"] = """ The code at {filename}:{line_number} requires the "openbabel" package openbabel can be installed with conda using: @@ -105,9 +96,7 @@ class DelayImportError(ImportError, SkipTest): MESSAGES["pybel"] = MESSAGES["openbabel"] -MESSAGES[ - "mdtraj" -] = """ +MESSAGES["mdtraj"] = """ The code at {filename}:{line_number} requires the "mdtraj" package mdtraj can be installed using: # conda install -c conda-forge mdtraj @@ -115,9 +104,7 @@ class DelayImportError(ImportError, SkipTest): # pip install mdtraj """ -MESSAGES[ - "foyer" -] = """ +MESSAGES["foyer"] = """ The code at {filename}:{line_number} requires the "foyer" package foyer can be installed using: @@ -129,9 +116,7 @@ class DelayImportError(ImportError, SkipTest): # pip install foyer """ -MESSAGES[ - "garnett" -] = """ +MESSAGES["garnett"] = """ The code at {filename}:{line_number} requires the "garnett" package garnett can be installed with conda using: @@ -139,9 +124,7 @@ class DelayImportError(ImportError, SkipTest): # conda install -c conda-forge garnett """ -MESSAGES[ - "pycifrw" -] = """ +MESSAGES["pycifrw"] = """ The code at {filename}:{line_number} requires the "pycifrw" package pycifrw can be installed with conda using: @@ -149,9 +132,7 @@ class DelayImportError(ImportError, SkipTest): # conda install -c conda-forge pycifrw """ -MESSAGES[ - "freud" -] = """ +MESSAGES["freud"] = """ The code at {filename}:{line_number} requires the "freud" package freud can be installed with conda using: @@ -222,15 +203,14 @@ def import_(module): pass try: return importlib.import_module(module) - except ImportError as e: + except ImportError: try: message = MESSAGES[module] except KeyError: message = ( - "The code at {filename}:{line_number} requires the " - f"{module} package" + "The code at {filename}:{line_number} requires the " f"{module} package" ) - e = ImportError(f"No module named {module}") + raise ImportError(f"No module named {module}") ( frame, @@ -241,9 +221,7 @@ def import_(module): index, ) = inspect.getouterframes(inspect.currentframe())[1] - m = message.format( - filename=os.path.basename(filename), line_number=line_number - ) + m = message.format(filename=os.path.basename(filename), line_number=line_number) m = textwrap.dedent(m) bar = ( diff --git a/mbuild/utils/orderedset.py b/mbuild/utils/orderedset.py index 6ca17aab4..fc4fa3f3b 100644 --- a/mbuild/utils/orderedset.py +++ b/mbuild/utils/orderedset.py @@ -21,13 +21,6 @@ class OrderedSet(MutableSet): def __init__(self, *args): self._data = {value: None for value in args} - def __contains__(self, key): - """Determine whether the set contains a key.""" - return key in self._data - - def __getitem__(self, value): - """Get an item.""" - def __repr__(self): """Return the OrderedSet representation.""" data = ", ".join(str(i) for i in self._data) diff --git a/mbuild/utils/validation.py b/mbuild/utils/validation.py index 39f8f349e..d9b36c681 100644 --- a/mbuild/utils/validation.py +++ b/mbuild/utils/validation.py @@ -9,9 +9,7 @@ def assert_port_exists(port_name, compound): from mbuild.port import Port available_ports = [ - name - for name in compound.labels - if isinstance(compound.labels[name], Port) + name for name in compound.labels if isinstance(compound.labels[name], Port) ] compound_name = compound.__class__.__name__ raise ValueError( diff --git a/setup.cfg b/setup.cfg index 6d9773317..fe4db44eb 100644 --- a/setup.cfg +++ b/setup.cfg @@ -6,19 +6,19 @@ message = Bump to version {new_version} tag_name = {new_version} [coverage:run] -omit = +omit = mbuild/examples/* mbuild/tests/* [coverage:report] -exclude_lines = +exclude_lines = pragma: no cover - + if 0: if __name__ == .__main__.: def __repr__ except ImportError -omit = +omit = mbuild/examples/* mbuild/tests/* diff --git a/setup.py b/setup.py index 1cb7d12f3..12defd00b 100644 --- a/setup.py +++ b/setup.py @@ -74,9 +74,7 @@ def compile_proto(protoc): __version__ ), packages=find_packages(), - package_data={ - "mbuild": ["utils/reference/*.{pdb,mol2}", "lib/*.{pdb,mol2}"] - }, + package_data={"mbuild": ["utils/reference/*.{pdb,mol2}", "lib/*.{pdb,mol2}"]}, entry_points={ "mbuild.plugins": [ "Alkane = mbuild.lib.recipes.alkane:Alkane",