diff --git a/mdgo/__init__.py b/mdgo/__init__.py index ba1bf5d2..689a18ae 100644 --- a/mdgo/__init__.py +++ b/mdgo/__init__.py @@ -1,9 +1,7 @@ # Copyright (c) Tingzheng Hou. # Distributed under the terms of the MIT License. -""" -This package contains core modules and classes molecular dynamics simulation setup and analysis. -""" +"""This package contains core modules and classes molecular dynamics simulation setup and analysis.""" from __future__ import annotations diff --git a/mdgo/core/analysis.py b/mdgo/core/analysis.py index fbc4db3a..3c64012f 100644 --- a/mdgo/core/analysis.py +++ b/mdgo/core/analysis.py @@ -201,9 +201,7 @@ def from_lammps( ) def get_init_dimension(self) -> np.ndarray: - """ - Returns the initial box dimension. - """ + """Returns the initial box dimension.""" return self.wrapped_run.trajectory[0].dimensions def get_equilibrium_dimension(self, npt_range: int, period: int = 200) -> np.ndarray: @@ -234,9 +232,7 @@ def get_equilibrium_dimension(self, npt_range: int, period: int = 200) -> np.nda return np.mean(np.array(d), axis=0) def get_nvt_dimension(self) -> np.ndarray: - """ - Returns the box dimension at the last frame. - """ + """Returns the box dimension at the last frame.""" return self.wrapped_run.trajectory[-1].dimensions def get_cond_array(self) -> np.ndarray: @@ -249,7 +245,7 @@ def get_cond_array(self) -> np.ndarray: nvt_run = self.unwrapped_run cations = nvt_run.select_atoms(self.select_dict.get("cation")) anions = nvt_run.select_atoms(self.select_dict.get("anion")) - cond_array = calc_cond_msd( + return calc_cond_msd( nvt_run, anions, cations, @@ -257,7 +253,6 @@ def get_cond_array(self) -> np.ndarray: self.cation_charge, self.anion_charge, ) - return cond_array def choose_cond_fit_region(self) -> tuple: """ @@ -358,10 +353,9 @@ def get_conductivity(self, start: int = -1, end: int = -1) -> float: print(f"Start of linear fitting regime: {start} ({self.time_array[start]} {time_units})") print(f"End of linear fitting regime: {end} ({self.time_array[end]} {time_units})") print(f"Beta value (fit to MSD = t^\u03B2): {beta} (\u03B2 = 1 in the diffusive regime)") - cond = conductivity_calculator( + return conductivity_calculator( self.time_array, self.cond_array, self.nvt_v, self.name, start, end, self.temp, self.units ) - return cond def coord_num_array_single_species( self, @@ -386,7 +380,7 @@ def coord_num_array_single_species( nvt_run = self.wrapped_run distance_dict = {species: distance} center_atoms = nvt_run.select_atoms(self.select_dict.get(center_atom)) - num_array = concat_coord_array( + return concat_coord_array( nvt_run, num_of_neighbor, center_atoms, @@ -395,7 +389,6 @@ def coord_num_array_single_species( run_start, run_end, )["total"] - return num_array def coord_num_array_multi_species( self, @@ -418,7 +411,7 @@ def coord_num_array_multi_species( """ nvt_run = self.wrapped_run center_atoms = nvt_run.select_atoms(self.select_dict.get(center_atom)) - num_array_dict = concat_coord_array( + return concat_coord_array( nvt_run, num_of_neighbor, center_atoms, @@ -427,7 +420,6 @@ def coord_num_array_multi_species( run_start, run_end, ) - return num_array_dict def coord_num_array_specific( self, @@ -453,7 +445,7 @@ def coord_num_array_specific( """ nvt_run = self.wrapped_run center_atoms = nvt_run.select_atoms(self.select_dict.get(center_atom)) - num_array_dict = concat_coord_array( + return concat_coord_array( nvt_run, num_of_neighbor_specific, center_atoms, @@ -463,7 +455,6 @@ def coord_num_array_specific( run_end, counter_atom=counter_atom, ) - return num_array_dict def write_solvation_structure( self, @@ -475,7 +466,7 @@ def write_solvation_structure( write_path: str, center_atom: str = "cation", ): - """Writes out a series of desired solvation structures as ``*.xyz`` files + """Writes out a series of desired solvation structures as ``*.xyz`` files. Args: distance_dict: A dict of coordination cutoff distance of the neighbor species. @@ -528,7 +519,7 @@ def coord_type_array( nvt_run = self.wrapped_run distance_dict = {counter_atom: distance} center_atoms = nvt_run.select_atoms(self.select_dict.get(center_atom)) - num_array = concat_coord_array( + return concat_coord_array( nvt_run, num_of_neighbor_simple, center_atoms, @@ -537,7 +528,6 @@ def coord_type_array( run_start, run_end, )["total"] - return num_array def angle_array( self, @@ -567,8 +557,8 @@ def angle_array( nvt_run = self.wrapped_run center_atoms = nvt_run.select_atoms(self.select_dict.get(center_atom)) assert len(distance_dict) == 2, "Only distance a->c, b->c shoud be specified in the distance_dict." - distance_dict[center_atom] = list(distance_dict.values())[0] - ang_array = concat_coord_array( + distance_dict[center_atom] = next(iter(distance_dict.values())) + return concat_coord_array( nvt_run, angular_dist_of_neighbor, center_atoms, @@ -578,7 +568,6 @@ def angle_array( run_end, cip=cip, )["total"] - return ang_array def coordination( self, @@ -612,8 +601,7 @@ def coordination( item_list.append(str(int(combined[i, 0]))) percent_list.append(f"{(combined[i, 1] / combined[:, 1].sum() * 100):.4f}%") df_dict = {item_name: item_list, "Percentage": percent_list} - df = pd.DataFrame(df_dict) - return df + return pd.DataFrame(df_dict) def rdf_integral( self, @@ -644,8 +632,7 @@ def rdf_integral( item_list.append(kw) cn_list.append(cn) df_dict = {item_name: item_list, "CN": cn_list} - df = pd.DataFrame(df_dict) - return df + return pd.DataFrame(df_dict) def coordination_type( self, @@ -655,7 +642,7 @@ def coordination_type( center_atom: str = "cation", counter_atom: str = "anion", ) -> pd.DataFrame: - """Tabulates the percentage of each solvation structures (CIP/SSIP/AGG) + """Tabulates the percentage of each solvation structures (CIP/SSIP/AGG). Args: distance: The coordination cutoff distance. @@ -683,8 +670,7 @@ def coordination_type( item_list.append(item_dict.get(item)) percent_list.append(f"{(combined[i, 1] / combined[:, 1].sum() * 100):.4f}%") df_dict = {item_name: item_list, "Percentage": percent_list} - df = pd.DataFrame(df_dict) - return df + return pd.DataFrame(df_dict) def coordination_specific( self, @@ -695,7 +681,7 @@ def coordination_specific( counter_atom: str = "anion", ) -> pd.DataFrame: """Calculates the integral of the coordiantion number of selected species - in each type of solvation structures (CIP/SSIP/AGG) + in each type of solvation structures (CIP/SSIP/AGG). Args: distance_dict: A dict of coordination cutoff distance of the neighbor species. @@ -727,8 +713,7 @@ def coordination_specific( else: agg_list.append(cn) df_dict = {item_name: item_list, "CN in SSIP": ssip_list, "CN in CIP": cip_list, "CN in AGG": agg_list} - df = pd.DataFrame(df_dict) - return df + return pd.DataFrame(df_dict) def get_msd_all( self, @@ -758,7 +743,7 @@ def get_msd_all( """ selection = self.select_dict.get(species) assert selection is not None - msd_array = total_msd( + return total_msd( self.unwrapped_run, start=start, end=end, @@ -768,7 +753,6 @@ def get_msd_all( built_in=built_in, center_of_mass=center_of_mass, ) - return msd_array def get_msd_partial( self, @@ -861,7 +845,7 @@ def get_neighbor_corr( def get_residence_time( self, times: np.ndarray, acf_avg_dict: dict[str, np.ndarray], cutoff_time: int ) -> dict[str, np.floating]: - """Calculates the residence time of selected species around cation + """Calculates the residence time of selected species around cation. Args: times: The time series. @@ -882,7 +866,7 @@ def get_neighbor_trj( center_atom: str = "cation", index: int = 0, ) -> dict[str, np.ndarray]: - """Returns the distance between one center atom and neighbors as a function of time + """Returns the distance between one center atom and neighbors as a function of time. Args: run_start: Start frame of analysis. @@ -1063,12 +1047,12 @@ def get_heat_map( hopping_cutoff: float, floating_atom: str = "cation", cartesian_by_ref: np.ndarray = None, - sym_dict: dict[str, list[np.ndarray]] = None, + sym_dict: dict[str, list[np.ndarray]] | None = None, sample: int | None = None, smooth: int = 51, dim: str = "xyz", ) -> np.ndarray: - """Calculates the heatmap matrix of floating ion around a cluster + """Calculates the heatmap matrix of floating ion around a cluster. Args: run_start: Start frame of analysis. @@ -1133,7 +1117,7 @@ def get_heat_map( def get_cluster_distance( self, run_start: int, run_end: int, neighbor_cutoff: float, cluster_center: str = "center" ) -> np.floating: - """Calculates the average distance of the center of clusters/molecules + """Calculates the average distance of the center of clusters/molecules. Args: run_start: Start frame of analysis. diff --git a/mdgo/core/run.py b/mdgo/core/run.py index cc30ae6c..9de5e172 100644 --- a/mdgo/core/run.py +++ b/mdgo/core/run.py @@ -1,21 +1,15 @@ # Copyright (c) Tingzheng Hou. # Distributed under the terms of the MIT License. -""" -This module implements a core class MdRun for molecular dynamics job setup. -""" +"""This module implements a core class MdRun for molecular dynamics job setup.""" from __future__ import annotations class MdJob: - """ - A core class for MD results analysis. - """ + """A core class for MD results analysis.""" def __init__(self, name): - """ - Base constructor - """ + """Base constructor.""" self.name = name @classmethod diff --git a/mdgo/forcefield/aqueous.py b/mdgo/forcefield/aqueous.py index c071d4db..44f34615 100644 --- a/mdgo/forcefield/aqueous.py +++ b/mdgo/forcefield/aqueous.py @@ -1,9 +1,7 @@ # Copyright (c) Tingzheng Hou. # Distributed under the terms of the MIT License. -""" -A class for retrieving water and ion force field parameters. -""" +"""A class for retrieving water and ion force field parameters.""" from __future__ import annotations @@ -227,10 +225,7 @@ def get_ion( parameter_set = alias.get(parameter_set, parameter_set) # Make the Ion object to get mass and charge - if isinstance(ion, Ion): - ion_obj = ion - else: - ion_obj = Ion.from_formula(ion.capitalize()) + ion_obj = ion if isinstance(ion, Ion) else Ion.from_formula(ion.capitalize()) # load ion data as a list of IonLJData objects ion_data = loadfn(os.path.join(DATA_DIR, "ion_lj_params.json")) diff --git a/mdgo/forcefield/charge.py b/mdgo/forcefield/charge.py index cc26a250..ae3b30d9 100644 --- a/mdgo/forcefield/charge.py +++ b/mdgo/forcefield/charge.py @@ -1,9 +1,7 @@ # Copyright (c) Tingzheng Hou. # Distributed under the terms of the MIT License. -""" -A class for writing, overwriting, scaling charges of a LammpsData object. -""" +"""A class for writing, overwriting, scaling charges of a LammpsData object.""" from __future__ import annotations @@ -16,7 +14,7 @@ class ChargeWriter: A class for write, overwrite, scale charges of a LammpsData object. TODO: Auto determine number of significant figures of charges TODO: write to obj or write separate charge file - TODO: Read LammpsData or path + TODO: Read LammpsData or path. Args: data: The provided LammpsData obj. @@ -30,7 +28,7 @@ def __init__(self, data: LammpsData, precision: int = 10): def scale(self, factor: float) -> LammpsData: """ - Scales the charge in of the in self.data and returns a new one. TODO: check if non-destructive + Scales the charge in of the in self.data and returns a new one. TODO: check if non-destructive. Args: factor: The charge scaling factor diff --git a/mdgo/forcefield/crawler.py b/mdgo/forcefield/crawler.py index 27596f7d..a50b66ca 100644 --- a/mdgo/forcefield/crawler.py +++ b/mdgo/forcefield/crawler.py @@ -91,10 +91,7 @@ def __init__( print("LigParGen server connected.") def quit(self): - """ - Method for quiting ChromeDriver. - - """ + """Method for quiting ChromeDriver.""" self.web.quit() def data_from_pdb(self, pdb_dir: str): diff --git a/mdgo/forcefield/maestro.py b/mdgo/forcefield/maestro.py index c1a61d09..8b35eb6a 100644 --- a/mdgo/forcefield/maestro.py +++ b/mdgo/forcefield/maestro.py @@ -146,8 +146,7 @@ def get_ff(self): FFLD.format(self.mae + ".mae", self.ff), check=True, shell=True, - stdout=subprocess.PIPE, - stderr=subprocess.PIPE, + capture_output=True, ) except subprocess.CalledProcessError as e: raise ValueError(f"Maestro failed with errorcode {e.returncode} and stderr: {e.stderr}") from e diff --git a/mdgo/forcefield/pubchem.py b/mdgo/forcefield/pubchem.py index da8617f5..e35fcc74 100644 --- a/mdgo/forcefield/pubchem.py +++ b/mdgo/forcefield/pubchem.py @@ -84,10 +84,7 @@ def __init__( print("PubChem server connected.") def quit(self): - """ - Method for quiting ChromeDriver. - - """ + """Method for quiting ChromeDriver.""" if not self.api: self.web.quit() diff --git a/mdgo/msd.py b/mdgo/msd.py index 035ac157..04e3c442 100644 --- a/mdgo/msd.py +++ b/mdgo/msd.py @@ -11,7 +11,7 @@ from __future__ import annotations -from typing import Literal +from typing import TYPE_CHECKING, Literal try: import MDAnalysis.analysis.msd as mda_msd @@ -23,10 +23,12 @@ td = None import numpy as np -from MDAnalysis import AtomGroup, Universe -from MDAnalysis.core.groups import Atom from tqdm.auto import trange +if TYPE_CHECKING: + from MDAnalysis import AtomGroup, Universe + from MDAnalysis.core.groups import Atom + __author__ = "Tingzheng Hou" __version__ = "0.3.0" __maintainer__ = "Tingzheng Hou" @@ -169,11 +171,11 @@ def create_position_arrays( atom_group = nvt_run.select_atoms(select) atom_positions = np.zeros((end - start, len(atom_group), 3)) if center_of_mass: - for ts in nvt_run.trajectory[start:end]: + for _ts in nvt_run.trajectory[start:end]: atom_positions[time, :, :] = atom_group.positions - nvt_run.atoms.center_of_mass() time += 1 else: - for ts in nvt_run.trajectory[start:end]: + for _ts in nvt_run.trajectory[start:end]: atom_positions[time, :, :] = atom_group.positions time += 1 return atom_positions @@ -223,8 +225,7 @@ def onsager_ii_self( r = atom_positions[:, atom_num, dim[0] : dim[1] : dim[2]] msd_temp = msd_straight_forward(np.array(r)) # [start:end] ii_self += msd_temp - msd = np.array(ii_self) / n_atoms - return msd + return np.array(ii_self) / n_atoms def mda_msd_wrapper( @@ -311,8 +312,7 @@ def _total_msd(nvt_run: Universe, run_start: int, run_end: int, select: str = "a current_coord = ts[li_atom.id - 1] coords.append(current_coord) all_list.append(np.array(coords)) - total_array = msd_from_frags(all_list, run_end - run_start - 1) - return total_array + return msd_from_frags(all_list, run_end - run_start - 1) def msd_from_frags(coord_list: list[np.ndarray], largest: int) -> np.ndarray: @@ -345,8 +345,7 @@ def msd_from_frags(coord_list: list[np.ndarray], largest: int) -> np.ndarray: assert msds is not None msds_by_state[kw] = msds.mean() timeseries.append(msds_by_state[kw]) - timeseries = np.array(timeseries) - return timeseries + return np.array(timeseries) def states_coord_array( @@ -361,7 +360,7 @@ def states_coord_array( """Cuts the trajectory of an atom into fragments. Each fragment contains consecutive timesteps of coordinates of the atom in either attached or free state. The Attached state is when the atom coordinates with the ``binding_site`` species (distance < ``distance``), and vice versa for the free state. - TODO: check if need wrapped trj + TODO: check if need wrapped trj. Args: nvt_run: An MDAnalysis ``Universe`` containing unwrapped trajectory. diff --git a/mdgo/residence_time.py b/mdgo/residence_time.py index ce26678e..c3a6a843 100644 --- a/mdgo/residence_time.py +++ b/mdgo/residence_time.py @@ -1,22 +1,23 @@ # Copyright (c) Tingzheng Hou. # Distributed under the terms of the MIT License. -""" -This module calculates species correlation lifetime (residence time). -""" +"""This module calculates species correlation lifetime (residence time).""" from __future__ import annotations import os +from typing import TYPE_CHECKING import matplotlib.pyplot as plt import numpy as np -from MDAnalysis import Universe -from MDAnalysis.core.groups import Atom from scipy.optimize import curve_fit from statsmodels.tsa.stattools import acovf from tqdm.auto import tqdm +if TYPE_CHECKING: + from MDAnalysis import Universe + from MDAnalysis.core.groups import Atom + __author__ = "Kara Fong, Tingzheng Hou" __version__ = "0.3.0" __maintainer__ = "Tingzheng Hou" @@ -51,7 +52,7 @@ def neighbors_one_atom( """ bool_values = {} time_count = 0 - for ts in nvt_run.trajectory[run_start:run_end:]: + for _ts in nvt_run.trajectory[run_start:run_end:]: if species in select_dict: selection = ( "(" @@ -75,7 +76,7 @@ def neighbors_one_atom( def calc_acf(a_values: dict[str, np.ndarray]) -> list[np.ndarray]: """ - Calculate auto-correlation function (ACF) + Calculate auto-correlation function (ACF). Args: a_values: A dict of adjacency matrix with neighbor atom id as keys and arrays @@ -98,7 +99,7 @@ def exponential_func( c: float | np.floating | np.ndarray, ) -> np.floating | np.ndarray: """ - An exponential decay function + An exponential decay function. Args: x: Independent variable. @@ -140,7 +141,7 @@ def calc_neigh_corr( times = [] step = 0 center_atoms = nvt_run.select_atoms(select_dict[center_atom]) - for ts in nvt_run.trajectory[run_start:run_end]: + for _ts in nvt_run.trajectory[run_start:run_end]: times.append(step * time_step) step += 1 times = np.array(times) @@ -176,7 +177,7 @@ def fit_residence_time( ) -> dict[str, np.floating]: """ Use the ACF to fit the residence time (Exponential decay constant). - TODO: allow defining the residence time according to a threshold value of the decay + TODO: allow defining the residence time according to a threshold value of the decay. Args: times: A time series. diff --git a/mdgo/util/__init__.py b/mdgo/util/__init__.py index 46ca2dd3..05c04b5a 100644 --- a/mdgo/util/__init__.py +++ b/mdgo/util/__init__.py @@ -13,7 +13,7 @@ from typing import Dict, Final -MM_of_Elements: Final[Dict[str, float]] = { +MM_of_Elements: Final[dict[str, float]] = { "H": 1.00794, "He": 4.002602, "Li": 6.941, diff --git a/mdgo/util/coord.py b/mdgo/util/coord.py index 1db0b6a8..32570f0b 100644 --- a/mdgo/util/coord.py +++ b/mdgo/util/coord.py @@ -5,8 +5,12 @@ from __future__ import annotations +from typing import TYPE_CHECKING + import numpy as np -from MDAnalysis.core.groups import Atom + +if TYPE_CHECKING: + from MDAnalysis.core.groups import Atom def atom_vec(atom1: Atom, atom2: Atom, dimension: np.ndarray) -> np.ndarray: diff --git a/mdgo/util/dict_utils.py b/mdgo/util/dict_utils.py index d5eb8f79..bcc80195 100644 --- a/mdgo/util/dict_utils.py +++ b/mdgo/util/dict_utils.py @@ -8,15 +8,18 @@ import math import re import string +from typing import TYPE_CHECKING import numpy as np -import pandas as pd -from MDAnalysis import Universe -from MDAnalysis.core.groups import AtomGroup, Residue from pymatgen.io.lammps.data import CombinedData from . import MM_of_Elements +if TYPE_CHECKING: + import pandas as pd + from MDAnalysis import Universe + from MDAnalysis.core.groups import AtomGroup, Residue + def mass_to_name(masses: np.ndarray) -> np.ndarray: """ @@ -247,10 +250,7 @@ def extract_atom_from_ion(positive: bool, ion: Residue | AtomGroup, select_dict: number: The serial number of the ion. """ if positive: - if number == 0: - cation_name = "cation" - else: - cation_name = "cation_" + str(number) + cation_name = "cation" if number == 0 else "cation_" + str(number) if len(ion.atoms.types) == 1: select_dict[cation_name] = "type " + ion.atoms.types[0] else: @@ -265,10 +265,7 @@ def extract_atom_from_ion(positive: bool, ion: Residue | AtomGroup, select_dict: select_dict[cation_name + "_" + pos_center.name + pos_center.type] = "type " + pos_center.type select_dict[cation_name] = "type " + uni_center else: - if number == 0: - anion_name = "anion" - else: - anion_name = "anion_" + str(number) + anion_name = "anion" if number == 0 else "anion_" + str(number) if len(ion.atoms.types) == 1: select_dict[anion_name] = "type " + ion.atoms.types[0] else: @@ -288,7 +285,7 @@ def extract_atom_from_molecule( resname: str, molecule: Residue | AtomGroup, select_dict: dict[str, str], number: int = 0 ): """ - Assign the most negatively charged atom in the molecule into select_dict + Assign the most negatively charged atom in the molecule into select_dict. Args: resname: The name of the molecule diff --git a/mdgo/util/packmol.py b/mdgo/util/packmol.py index d0f8fb36..9d7fa175 100644 --- a/mdgo/util/packmol.py +++ b/mdgo/util/packmol.py @@ -119,8 +119,7 @@ def run_packmol(self, timeout=30): check=True, shell=True, timeout=timeout, - stdout=subprocess.PIPE, - stderr=subprocess.PIPE, + capture_output=True, ) # this workaround is needed because packmol can fail to find # a solution but still return a zero exit code @@ -150,11 +149,8 @@ def make_packmol_input(self): else: # estimate the total volume of all molecules net_volume = 0.0 - for idx, d in enumerate(self.molecules): - if not isinstance(d["coords"], Molecule): - mol = Molecule.from_file(d["coords"]) - else: - mol = d["coords"] + for _idx, d in enumerate(self.molecules): + mol = Molecule.from_file(d["coords"]) if not isinstance(d["coords"], Molecule) else d["coords"] # molecular volume in cubic Å vol = molecular_volume(mol, radii_type="pymatgen", molar_volume=False) # pad the calculated length by an amount related to the tolerance parameter @@ -183,7 +179,7 @@ def make_packmol_input(self): else: out.write(f"output {self.output}\n\n") - for i, d in enumerate(self.molecules): + for _i, d in enumerate(self.molecules): if isinstance(d["coords"], str): if " " in d["coords"]: out.write(f'structure "{d["coords"]}"\n') diff --git a/mdgo/util/reformat.py b/mdgo/util/reformat.py index 2a78f03c..5583306b 100644 --- a/mdgo/util/reformat.py +++ b/mdgo/util/reformat.py @@ -1,9 +1,7 @@ # Copyright (c) Tingzheng Hou. # Distributed under the terms of the MIT License. -""" -Utilities for converting data file formats. -""" +"""Utilities for converting data file formats.""" from __future__ import annotations @@ -120,7 +118,7 @@ def ff_parser(ff_dir: str, xyz_dir: str) -> str: counts = {} counts["atoms"] = len(dfs["atoms"].index) mass_list = [] - for index, row in dfs["atoms"].iterrows(): + for _index, row in dfs["atoms"].iterrows(): mass_list.append(MM_of_Elements.get(re.split(r"(\d+)", row["atom"])[0])) mass_df = pd.DataFrame(mass_list) mass_df.index += 1 @@ -175,15 +173,14 @@ def ff_parser(ff_dir: str, xyz_dir: str) -> str: stats_template = "{:>" + str(max_stats) + "} {}" count_lines = [stats_template.format(v, k) for k, v in counts.items()] type_lines = [stats_template.format(v, k[:-1] + " types") for k, v in counts.items()] - stats = "\n".join(count_lines + [""] + type_lines) + stats = "\n".join([*count_lines, "", *type_lines]) header = [ f"LAMMPS data file created by mdgo (by {__author__})\n" "# OPLS force field: harmonic, harmonic, opls, cvff", stats, BOX.format(lo, hi), ] - data_string = "\n\n".join(header + masses + ff + topo) + "\n" - return data_string + return "\n\n".join(header + masses + ff + topo) + "\n" def sdf_to_pdb( @@ -209,10 +206,7 @@ def sdf_to_pdb( with open(sdf_file) as inp: sdf_lines = inp.readlines() sdf = list(map(str.strip, sdf_lines)) - if pubchem: - title = "cid_" - else: - title = "" + title = "cid_" if pubchem else "" pdb_atoms: list[dict[str, Any]] = [] # create pdb list of dictionaries atoms = 0 diff --git a/mdgo/util/volume.py b/mdgo/util/volume.py index d6cef08f..645dce3c 100644 --- a/mdgo/util/volume.py +++ b/mdgo/util/volume.py @@ -285,7 +285,7 @@ def parse_command_line(): def get_max_dimensions(mol: Molecule) -> tuple[float, float, float, float, float, float]: """ - Calculates the dimension of a Molecule + Calculates the dimension of a Molecule. Args: mol: A Molecule object. @@ -373,7 +373,7 @@ def round_dimensions( def dsq(a1: float, a2: float, a3: float, b1: float, b2: float, b3: float) -> float: """ - Squared distance between a and b + Squared distance between a and b. Args: a1: x coordinate of a @@ -386,8 +386,7 @@ def dsq(a1: float, a2: float, a3: float, b1: float, b2: float, b3: float) -> flo Returns: squared distance """ - d2 = (b1 - a1) ** 2 + (b2 - a2) ** 2 + (b3 - a3) ** 2 - return d2 + return (b1 - a1) ** 2 + (b2 - a2) ** 2 + (b3 - a3) ** 2 def get_dimensions( @@ -431,8 +430,7 @@ def make_matrix(x_num: int, y_num: int, z_num: int) -> np.ndarray: Returns: matrix """ - matrix = np.array([[[None for _ in range(z_num)] for _ in range(y_num)] for _ in range(x_num)]) - return matrix + return np.array([[[None for _ in range(z_num)] for _ in range(y_num)] for _ in range(x_num)]) def get_radii(radii_type: str = "Bondi") -> dict[str, float]: @@ -530,9 +528,8 @@ def fill_volume_matrix( for a in mol.sites: element = str(a.species.elements[0]) - if exclude_h: - if element == "H": - continue + if exclude_h and element == "H": + continue radius = radii.get(element, DEFAULT_VDW) for i in range(xsteps): if abs(a.x - (x0 + 0.5 * res + i * res)) < radius: @@ -615,7 +612,7 @@ def molecular_volume( z_size: float = 10.0, ) -> float: """ - Estimate the molar volume in cm^3/mol or volume in Å^3 + Estimate the molar volume in cm^3/mol or volume in Å^3. Args: mol: Molecule object or path to .xyz or other file that can be read @@ -644,10 +641,7 @@ def molecular_volume( Returns: The molar volume in cm^3/mol or volume in Å^3. """ - if isinstance(mol, str): - molecule = Molecule.from_file(mol) - else: - molecule = mol + molecule = Molecule.from_file(mol) if isinstance(mol, str) else mol if mode == "lig": print("Calculating occupied volume...") x_min, x_max, y_min, y_max, z_min, z_max = get_max_dimensions(molecule) @@ -682,7 +676,7 @@ def concentration_matcher( Estimate the number of molecules of each species in a box, given the salt concentration, salt type, solvent molecular weight, solvent density, solvent ratio and total number of salt. - TODO: Auto box size according to Debye screening length + TODO: Auto box size according to Debye screening length. Args: concentration: Salt concentration in mol/L. diff --git a/tasks.py b/tasks.py index c0d226e2..d3f563d8 100644 --- a/tasks.py +++ b/tasks.py @@ -191,7 +191,7 @@ def update_changelog(ctx, version, sim=False): ll = ll.strip() if ll in ["", "## Summary"]: continue - elif ll.startswith("## Checklist") or ll.startswith("## TODO"): + elif ll.startswith(("## Checklist", "## TODO")): break lines.append(f" {ll}") misc.append(l) diff --git a/tests/test_coordination.py b/tests/test_coordination.py index 20c90463..cf1cc95f 100644 --- a/tests/test_coordination.py +++ b/tests/test_coordination.py @@ -5,7 +5,7 @@ class MyTestCase(unittest.TestCase): def test_something(self): - self.assertEqual(True, True) + assert True is True if __name__ == "__main__": diff --git a/tests/test_core.py b/tests/test_core.py index 20c90463..cf1cc95f 100644 --- a/tests/test_core.py +++ b/tests/test_core.py @@ -5,7 +5,7 @@ class MyTestCase(unittest.TestCase): def test_something(self): - self.assertEqual(True, True) + assert True is True if __name__ == "__main__": diff --git a/tests/test_util.py b/tests/test_util.py index 20c90463..cf1cc95f 100644 --- a/tests/test_util.py +++ b/tests/test_util.py @@ -5,7 +5,7 @@ class MyTestCase(unittest.TestCase): def test_something(self): - self.assertEqual(True, True) + assert True is True if __name__ == "__main__":