Skip to content

Commit

Permalink
Update line length, formatting etc. to pass linting checks, add defin…
Browse files Browse the repository at this point in the history
…ition for ruff to pyproject.toml
  • Loading branch information
peterspackman committed Nov 22, 2024
1 parent bd7d6b9 commit 3c951be
Show file tree
Hide file tree
Showing 66 changed files with 406 additions and 393 deletions.
4 changes: 4 additions & 0 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -38,3 +38,7 @@ where = ["src"]

[tool.cibuildwheel]
skip = "pp*"

[tool.ruff.lint]
select = ["E", "F"]
ignore = ["E741"]
11 changes: 10 additions & 1 deletion src/chmpy/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,4 +3,13 @@
from . import surface
from .interpolate import PromoleculeDensity, StockholderWeight

__all__ = ["surface", "Crystal", "Molecule", "SpaceGroup", "UnitCell"]
__all__ = [
"Crystal",
"Element",
"Molecule",
"PromoleculeDensity",
"SpaceGroup",
"StockholderWeight",
"UnitCell",
"surface",
]
6 changes: 3 additions & 3 deletions src/chmpy/cmd/convert.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,8 +18,8 @@ def main():
args = parser.parse_args()
logging.basicConfig(level=args.log_level)

inpath = Path(args.input)
outpath = Path(args.output)
Path(args.input)
Path(args.output)

in_kwargs = {}
if args.input_format != "file_ext":
Expand All @@ -33,7 +33,7 @@ def main():
try:
x = cls.load(args.input, **in_kwargs)
break
except KeyError as e:
except KeyError:
pass
else:
LOG.error("Could not delegate parser for '%s'", args.input)
Expand Down
16 changes: 9 additions & 7 deletions src/chmpy/core/dimer.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,13 +15,14 @@ class Dimer:
Args:
mol_a (Molecule):
one of the molecules in the pair (symmetry unique)
mol_b (Molecule): the neighbouring molecule (may be symmetry related to mol_a)
separation (float, optional): set the separation of the molecules (otherwise it
will be calculated)
transform_ab (np.ndarray, optional): specify the transform from mol_a to mol_b
mol_b (Molecule): the neighbouring molecule (may be symmetry
related to mol_a)
separation (float, optional): set the separation of the molecules
(otherwise it will be calculated)
frac_shift (np.ndarray, optional): specify the offset in fractions of a unit cell,
which combined with transform_ab will yield mol_b
transform_ab (np.ndarray, optional): specify the transform from mol_a
to mol_b (otherwise it will be calculated)
frac_shift (np.ndarray, optional): specify the offset in fractions
of a unit cell, which combined with transform_ab will yield mol_b
"""

seitz_b = None
Expand Down Expand Up @@ -110,7 +111,8 @@ def scale_separation(self, scale_factor):

@property
def separations(self):
"""The closest atom, centroid-centroid, and center of mass - center of mass separations of mol_a and mol_b."""
"The closest atom, centroid-centroid, and center of mass -"
"center of mass separations of mol_a and mol_b."
return np.array(
(self.closest_separation, self.centroid_separation, self.com_separation)
)
Expand Down
15 changes: 10 additions & 5 deletions src/chmpy/core/element.py
Original file line number Diff line number Diff line change
Expand Up @@ -284,7 +284,8 @@ def from_string(s: str) -> "Element":
s (str): a string representation of an element in the periodic table
Returns:
Element: an Element object if the conversion was successful, otherwise an exception is raised
Element: an Element object if the conversion was successful,
otherwise an exception is raised
Examples:
>>> Element.from_string("h")
Expand Down Expand Up @@ -315,7 +316,8 @@ def from_label(label: str) -> "Element":
l (str): a string representation of an element in the periodic table
Returns:
Element: an Element object if the conversion was successful, otherwise an exception is raised
Element: an Element object if the conversion was successful,
otherwise an exception is raised
Examples:
>>> Element.from_label("C1")
Expand Down Expand Up @@ -345,7 +347,8 @@ def from_atomic_number(n: int) -> "Element":
n (int): the atomic number of the element
Returns:
Element: an Element object if atomic number was valid, otherwise an exception is raised
Element: an Element object if atomic number was valid,
otherwise an exception is raised
Examples:
>>> Element.from_atomic_number(2)
Expand Down Expand Up @@ -395,7 +398,8 @@ def __eq__(self, other):
return self.atomic_number == other.atomic_number

def __lt__(self, other):
"""Check which element comes before the other in chemical formulae (C first, then order of atomic number)."""
"Check which element comes before the other in chemical formulae "
"(C first, then order of atomic number)."
if not self._is_valid_operand(other):
raise NotImplementedError
n1, n2 = self.atomic_number, other.atomic_number
Expand All @@ -422,7 +426,8 @@ def chemical_formula(elements, subscript=False):
elements (List[Element or str]): a list of elements or element symbols.
Note that if a list of strings are provided the order of chemical
symbols may not match convention.
subscript (bool, optoinal): toggle to use unicode subscripts for the chemical formula string
subscript (bool, optional): toggle to use unicode subscripts for the
chemical formula string
Returns:
str: the chemical formula
Expand Down
115 changes: 71 additions & 44 deletions src/chmpy/core/molecule.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,13 +24,15 @@ class Molecule:
Attributes:
elements: list of element information for each atom in this molecule
positions: (N, 3) array of Cartesian coordinates for each atom in this molecule (Angstroms)
positions: (N, 3) array of Cartesian coordinates for each atom in this
molecule (Angstroms)
bonds: (N, N) adjacency matrix of bond lengths for connected atoms, 0 otherwise.
If not provided this will be calculated.
labels: (N,) vector of string labels for each atom in this molecule
If not provided this will assigned default labels i.e. numbered in order.
proerties: Additional keyword arguments will be stored in the `properties` member, and
some may be utilized in methods, raising an exception if they are not set.
proerties: Additional keyword arguments will be stored in the `properties`
member, and some may be utilized in methods, raising an exception if they
are not set.
"""

positions: np.ndarray
Expand All @@ -44,11 +46,16 @@ def __init__(self, elements, positions, bonds=None, labels=None, **kwargs):
Initialize a new molecule.
Arguments:
elements (List[Element]): N length list of elements associated with the sites
positions (array_like): (N, 3) array of site positions in Cartesian coordinates
bonds (dok_matrix, optional): if bonds are already calculated provide them here
labels (array_like, optional): labels (array_like): N length array of string labels for each site
**kwargs: Additional properties (will populate the properties member) to store in this molecule
elements (List[Element]): N length list of elements associated with
the sites
positions (array_like): (N, 3) array of site positions in Cartesian
coordinates
bonds (dok_matrix, optional): if bonds are already calculated provide
them here
labels (array_like, optional): labels (array_like): N length array of
string labels for each site
**kwargs: Additional properties (will populate the properties member)
to store in this molecule
"""
self.positions = positions
self.elements = elements
Expand Down Expand Up @@ -108,7 +115,8 @@ def guess_bonds(self, tolerance=0.40):
Args:
tolerance (float, optional): Additional tolerance for attributing two sites as 'bonded'.
tolerance (float, optional): Additional tolerance for attributing
two sites as 'bonded'.
The default is 0.4 angstroms, which is recommended by the CCDC
"""
tree = KDTree(self.positions)
Expand Down Expand Up @@ -159,7 +167,8 @@ def connected_fragments(self) -> List:
return molecules

def assign_default_labels(self):
"Assign the default labels to atom sites in this molecule (number them by element)"
"Assign the default labels to atom sites in this molecule"
"(number them by element)"
counts = defaultdict(int)
labels = []
for el, _ in self:
Expand Down Expand Up @@ -240,12 +249,12 @@ def electrostatic_potential(self, positions) -> np.ndarray:
in atomic units.
Args:
positions (np.ndarray): (N, 3) array of locations where the molecular ESP should
be calculated. Assumed to be in Angstroms.
positions (np.ndarray): (N, 3) array of locations where the
molecular ESP should be calculated. Assumed to be in Angstroms.
Returns:
np.ndarray: (N,) array of electrostatic potential values (atomic units) at the given
positions.
np.ndarray: (N,) array of electrostatic potential values (atomic units)
at the given positions.
"""
if "esp_cube" in self.properties:
return self.electrostatic_potential_from_cube(
Expand Down Expand Up @@ -696,12 +705,13 @@ def atomic_shape_descriptors(
in :obj:`chmpy.crystal.Crystal`.
Args:
l_max (int, optional): maximum level of angular momenta to include in the spherical harmonic
transform of the shape function. (default=5)
radius (float, optional): Maximum distance in Angstroms between any atom in the molecule
and the resulting neighbouring atoms (default=6.0)
background (float, optional): 'background' density to ensure closed surfaces for isolated atoms
(default=1e-5)
l_max (int, optional): maximum level of angular momenta to include
in the spherical harmonic transform of the shape function. (default=5)
radius (float, optional): Maximum distance in Angstroms between
any atom in the molecule and the resulting neighbouring
atoms (default=6.0)
background (float, optional): 'background' density to ensure closed
surfaces for isolated atoms (default=1e-5)
Returns:
shape description vector
Expand Down Expand Up @@ -767,7 +777,8 @@ def atomic_stockholder_weight_isosurfaces(self, **kwargs):
use the midpoint norm (as is used in CrystalExplorer)
Returns:
List[trimesh.Trimesh]: A list of meshes representing the stockholder weight isosurfaces
List[trimesh.Trimesh]: A list of meshes representing the stockholder
weight isosurfaces
"""

from chmpy import StockholderWeight
Expand Down Expand Up @@ -827,13 +838,15 @@ def shape_descriptors(self, l_max=5, **kwargs) -> np.ndarray:
this molecule using the promolecule density.
Args:
l_max (int, optional): maximum level of angular momenta to include in the spherical harmonic
transform of the molecular shape function.
l_max (int, optional): maximum level of angular momenta to include in
the spherical harmonic transform of the molecular shape function.
Keyword Args:
with_property (str, optional): describe the combination of the radial shape function and a surface
property in the real, imaginary channels of a complex function
isovalue (float, optional): the isovalue for the promolecule density surface (default 0.0002 au)
with_property (str, optional): describe the combination of the radial
shape function and a surface property in the real, imaginary channels
of a complex function
isovalue (float, optional): the isovalue for the promolecule density
surface (default 0.0002 au)
Returns:
shape description vector
Expand Down Expand Up @@ -914,7 +927,8 @@ def to_mesh(self, **kwargs):

@property
def name(self):
"The name of this molecule, checks 'GENERIC_NAME' and 'name' keys in `self.properties`"
"The name of this molecule, checks 'GENERIC_NAME' and 'name'"
"keys in `self.properties`"
return self.properties.get(
"GENERIC_NAME", self.properties.get("name", self.__class__.__name__)
)
Expand All @@ -930,7 +944,8 @@ def molecular_dipole_moment(self):
net_charge = np.sum(self.partial_charges)
if np.abs(net_charge) > 1e-3:
LOG.warn(
"Molecular dipole will be origin dependent: molecule has a net charge (%f)",
"Molecular dipole will be origin dependent: molecule "
"has a net charge (%f)",
net_charge,
)
r = ANGSTROM_TO_BOHR * (self.positions - self.center_of_mass)
Expand All @@ -939,7 +954,8 @@ def molecular_dipole_moment(self):

@property
def asym_symops(self):
"the symmetry operations which generate this molecule (default x,y,z if not set)"
"the symmetry operations which generate this molecule"
"(default x,y,z if not set)"
return self.properties.get("generator_symop", [16484] * len(self))

@classmethod
Expand All @@ -949,8 +965,10 @@ def from_arrays(cls, elements, positions, **kwargs):
will be passed through to the Molecule constructor.
Args:
elements (np.ndarray): (N,) array of atomic numbers for each atom in this molecule
positions (np.ndarray): (N, 3) array of Cartesian coordinates for each atom in this molecule (Angstroms)
elements (np.ndarray): (N,) array of atomic numbers for each
atom in this molecule
positions (np.ndarray): (N, 3) array of Cartesian coordinates
for each atom in this molecule (Angstroms)
Returns:
Molecule: a new molecule object
Expand All @@ -959,11 +977,12 @@ def from_arrays(cls, elements, positions, **kwargs):

def mask(self, mask, **kwargs):
"""
Convenience method to construct a new molecule from this molecule with the given mask
array.
Convenience method to construct a new molecule from this molecule
with the given mask array.
Args:
mask (np.ndarray): a numpy mask array used to filter which atoms to keep in the new molecule.
mask (np.ndarray): a numpy mask array used to filter which
atoms to keep in the new molecule.
Returns:
Molecule: a new `Molecule`, with atoms filtered by the mask.
Expand Down Expand Up @@ -1006,7 +1025,7 @@ def inertia_tensor(self):
masses = np.asarray([x.mass for x in self.elements])
d = self.positions - self.center_of_mass
d2 = d**2
r2 = (d2).sum(axis=1)
(d2).sum(axis=1)
tensor = np.empty((3, 3))
tensor[0, 0] = np.sum(masses * (d2[:, 1] + d2[:, 2]))
tensor[1, 1] = np.sum(masses * (d2[:, 0] + d2[:, 2]))
Expand All @@ -1025,7 +1044,6 @@ def principle_moments_of_inertia(self, units="amu angstrom^2"):

def rotational_constants(self, unit="MHz"):
from scipy.constants import Planck, speed_of_light, Avogadro
from chmpy.util.unit import BOHR_TO_ANGSTROM

# convert amu angstrom^2 to g cm^2
moments = self.principle_moments_of_inertia() / Avogadro / 1e16
Expand Down Expand Up @@ -1057,7 +1075,8 @@ def rotated(self, rotation, origin=(0, 0, 0)):
rotation (np.ndarray): A (3, 3) rotation matrix
Returns:
Molecule: a new copy of this `Molecule` rotated by the given rotation matrix.
Molecule: a new copy of this `Molecule` rotated by the
given rotation matrix.
"""
from copy import deepcopy

Expand All @@ -1071,7 +1090,8 @@ def translate(self, translation):
translation vector
Args:
translation (np.ndarray): A (3,) vector of x, y, z coordinates of the translation
translation (np.ndarray): A (3,) vector of x, y, z coordinates
of the translation
"""
self.positions += translation

Expand All @@ -1081,10 +1101,12 @@ def translated(self, translation):
translated by a given translation vector
Args:
translation (np.ndarray): A (3,) vector of x, y, z coordinates of the translation
translation (np.ndarray): A (3,) vector of x, y, z coordinates
of the translation
Returns:
Molecule: a new copy of this `Molecule` translated by the given vector.
Molecule: a new copy of this `Molecule` translated by the
given vector.
"""
import copy

Expand All @@ -1099,7 +1121,8 @@ def transform(self, rotation=None, translation=None):
Args:
rotation (np.ndarray): A (3,3) rotation matrix
translation (np.ndarray): A (3,) vector of x, y, z coordinates of the translation
translation (np.ndarray): A (3,) vector of x, y, z
coordinates of the translation
"""

if rotation is not None:
Expand All @@ -1114,10 +1137,12 @@ def transformed(self, rotation=None, translation=None):
Args:
rotation (np.ndarray): A (3,3) rotation matrix
translation (np.ndarray): A (3,) vector of x, y, z coordinates of the translation
translation (np.ndarray): A (3,) vector of x, y, z
coordinates of the translation
Returns:
Molecule: a new copy of this `Molecule` transformed by the provided matrix and vector.
Molecule: a new copy of this `Molecule` transformed by the
provided matrix and vector.
"""

from copy import deepcopy
Expand Down Expand Up @@ -1170,7 +1195,9 @@ def from_sdf_file(cls, filename, **kwargs):

sdf_data = parse_sdf_file(filename, **kwargs)
progress = kwargs.get("progress", False)
update = lambda x: None

def update(x):
return None

if progress:
from tqdm import tqdm
Expand Down
Loading

0 comments on commit 3c951be

Please sign in to comment.