Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion .github/workflows/lint.yml
Original file line number Diff line number Diff line change
Expand Up @@ -60,4 +60,4 @@ jobs:
run: python -m pip install vermin

- name: Run Vermin
run: vermin -t=3.9 --lint --quiet --no-parse-comments MDANSE/ MDANSE_GUI/
run: vermin -t=3.10 --lint --quiet --no-parse-comments MDANSE/ MDANSE_GUI/
3 changes: 2 additions & 1 deletion MDANSE/Src/MDANSE/Chemistry/ChemicalSystem.py
Original file line number Diff line number Diff line change
Expand Up @@ -127,7 +127,8 @@ def add_clusters(self, group_list: list[list[int]]):
unique_atoms, counts = np.unique(atom_list, return_counts=True)
unique_atoms = map(self._rename_isotopes, unique_atoms)
name = "_".join(
f"{atom}{count}" for atom, count in zip(unique_atoms, counts)
f"{atom}{count}"
for atom, count in zip(unique_atoms, counts, strict=True)
)

if name not in self._clusters:
Expand Down
2 changes: 1 addition & 1 deletion MDANSE/Src/MDANSE/Chemistry/Databases.py
Original file line number Diff line number Diff line change
Expand Up @@ -759,7 +759,7 @@ def remove_property(self, label: str):
try:
del self._properties[label]
except KeyError:
raise AtomsDatabaseError(f"Atom property {label} does not exist.")
raise AtomsDatabaseError(f"Atom property {label} does not exist.") from None

for atm in self.atoms:
del self._data[atm][label]
Expand Down
6 changes: 4 additions & 2 deletions MDANSE/Src/MDANSE/Framework/Configurable.py
Original file line number Diff line number Diff line change
Expand Up @@ -90,8 +90,10 @@ def build_configuration(self):
class_name, name, configurable=self, **kwds
)
# Any kind of error has to be caught
except Exception:
raise ConfigurationError(f"Could not set {name!r} configuration item")
except Exception as err:
raise ConfigurationError(
f"Could not set {name!r} configuration item"
) from err

def set_settings(self, settings):
self.settings = settings
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -730,7 +730,7 @@ def parse(self, filename: Path | str | None = None) -> None:

elem_range = range(1, self["n_atom_types"] + 1)

self.setdefault("elements", dict(zip(elem_range, map(str, elem_range))))
self.setdefault("elements", {elem: str(elem) for elem in elem_range})
self.setdefault("charges", np.zeros(self["n_atoms"]))

def atom_labels(self) -> Iterable[AtomLabel]:
Expand All @@ -742,7 +742,7 @@ def atom_labels(self) -> Iterable[AtomLabel]:
"""
conts = sorted(self.keys() & {"elements", "mass"})
if conts == ["elements", "mass"]:
for elem, mass in zip(self["elements"].values(), self["mass"]):
for elem, mass in zip(self["elements"].values(), self["mass"], strict=True):
yield AtomLabel(elem, mass=mass)
elif conts == ["elements"]:
for elem in self["elements"].values():
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -162,7 +162,7 @@ def atom_labels(self) -> Iterable[AtomLabel]:
An atom label.
"""
for molecule in self["molecules"]:
for atm_label, mass in zip(molecule.species, molecule.masses):
for atm_label, mass in zip(molecule.species, molecule.masses, strict=True):
yield AtomLabel(atm_label, molecule=molecule.name, mass=mass)

def get_atom_charges(self) -> np.ndarray:
Expand Down Expand Up @@ -208,15 +208,15 @@ def build_chemical_system(
get_element_from_mapping(
aliases, name, molecule=molecule.name, mass=mass
)
for name, mass in zip(molecule.species, molecule.masses)
for name, mass in zip(molecule.species, molecule.masses, strict=True)
]
curr_name_list = molecule.species
curr_cluster = np.arange(molecule.n_atoms, dtype=int)

# Bonds 0-indexed in RDKit
curr_bonds = np.array(molecule.bonds, dtype=int) - 1

for i in range(1, molecule.n_mols + 1):
for _ in range(molecule.n_mols):
element_list.extend(curr_element_list)
name_list.extend(curr_name_list)
bonds.extend(map(tuple, curr_bonds + curr_n))
Expand Down
2 changes: 1 addition & 1 deletion MDANSE/Src/MDANSE/Framework/Configurators/IConfigurator.py
Original file line number Diff line number Diff line change
Expand Up @@ -207,7 +207,7 @@ def warning_status(self, warning_text: str):
self._warning_status = warning_text
if warning_text:
LOG.warning(warning_text)
warn(warning_text, ConfiguratorWarning)
warn(warning_text, ConfiguratorWarning, stacklevel=1)

@abc.abstractmethod
def configure(self, value: str):
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -62,15 +62,15 @@ def configure(self, setting: tuple[str | list[str], str]):

try:
if len(self["filenames"]) <= 1 or self["format"] is None:
mda.Universe(
_ = mda.Universe(
topology_configurator["filename"],
*self["filenames"],
format=self["format"],
topology_format=topology_configurator["format"],
).trajectory
else:
coord_files = [(i, self["format"]) for i in self["filenames"]]
mda.Universe(
_ = mda.Universe(
topology_configurator["filename"],
coord_files,
topology_format=topology_configurator["format"],
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,7 @@ def __init__(self, trajectory: Trajectory) -> None:
self._traj_charges = trajectory.charges(0)[:]
self._current_trajectory = trajectory
self._original_map = {}
for at_num, at in enumerate(system.atom_list):
for at_num, _ in enumerate(system.atom_list):
try:
self._original_map[at_num] = self._traj_charges[at_num]
except Exception:
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -57,33 +57,33 @@ def configure(self, value: tuple[str, Sequence[SupportsFloat]]):
try:
try:
mode, axis = value
except (TypeError, ValueError) as e:
raise Exception("Failed to unpack input" + str(e))
except (TypeError, ValueError) as err:
raise Exception("Failed to unpack input") from err

if not isinstance(mode, str):
raise Exception("invalid type for projection mode: must be a string")

try:
self["projector"] = IProjector.create(mode)
except KeyError:
raise Exception(f"the projector {mode} is unknown")
except KeyError as err:
raise Exception(f"the projector {mode} is unknown") from err

if mode == "NullProjector":
self.error_status = "OK"
return

try:
vector = [float(x) for x in axis]
except ValueError:
raise Exception(f"Could not convert {axis} to numbers")
except ValueError as err:
raise Exception(f"Could not convert {axis} to numbers") from err

if np.allclose(vector, 0):
raise Exception("Vector of 0 length does not define projection")

try:
self["projector"].set_axis(vector)
except ProjectorError:
raise Exception(f"Axis {vector} is wrong for this projector")
except ProjectorError as err:
raise Exception(f"Axis {vector} is wrong for this projector") from err

self["axis"] = self["projector"].axis

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -66,24 +66,26 @@ def configure(self, value: tuple[str, dict[str, Any]]):

try:
generator_name, parameters = value
except ValueError:
raise Exception(f"Invalid q vectors settings {value}")
except ValueError as err:
raise Exception(f"Invalid q vectors settings {value}") from err

generator = IQVectors.create(
generator_name,
trajConfig["instance"].configuration(0),
)
try:
generator.setup(parameters)
except Exception:
raise Exception(f"Could not configure q vectors using {parameters}")
except Exception as err:
raise Exception(
f"Could not configure q vectors using {parameters}"
) from err

try:
generator_success = generator.generate()
except Exception:
except Exception as err:
raise Exception(
"Q Vector parameters were parsed correctly, but caused an error. Invalid values?"
)
) from err

if not generator_success:
raise Exception(
Expand Down
10 changes: 6 additions & 4 deletions MDANSE/Src/MDANSE/Framework/Configurators/XYZFileConfigurator.py
Original file line number Diff line number Diff line change
Expand Up @@ -53,8 +53,10 @@ def parse(self):

try:
self["n_atoms"] = int(self["instance"].readline().strip())
except ValueError:
raise XYZFileError(f"Could not read the number of atoms in {filename} file")
except ValueError as err:
raise XYZFileError(
f"Could not read the number of atoms in {filename} file"
) from err

self._nAtomsLineSize = self["instance"].tell()
self["instance"].readline()
Expand Down Expand Up @@ -105,10 +107,10 @@ def fetch_time_step(self, step: int):
raise XYZFileError("Could not fetch the time step from XYZ file")
try:
timeStep = float(matches[0])
except ValueError:
except ValueError as err:
raise XYZFileError(
"Could not cast the timestep to a floating point number."
)
) from err
else:
return timeStep

Expand Down
4 changes: 2 additions & 2 deletions MDANSE/Src/MDANSE/Framework/Converters/DCD.py
Original file line number Diff line number Diff line change
Expand Up @@ -132,7 +132,7 @@ def get_record(self, fmt, repeat=False):
try:
data = self.next_record()
except StopIteration:
raise EndOfFile()
raise EndOfFile() from None
if repeat:
unit = struct.calcsize(self.byteOrder + fmt)
assert len(data) % unit == 0
Expand Down Expand Up @@ -267,7 +267,7 @@ def next_step(self):
try:
return self.read_step()
except EndOfFile:
raise StopIteration
raise StopIteration from None


class DCD(Converter):
Expand Down
2 changes: 1 addition & 1 deletion MDANSE/Src/MDANSE/Framework/Converters/DL_POLY.py
Original file line number Diff line number Diff line change
Expand Up @@ -101,7 +101,7 @@ def read_step(self, step: int):
mass = float(mass)
charge = float(charge)
charges[ind] = float(charge)
for arr, val in zip(data.values(), atom):
for arr, val in zip(data.values(), atom, strict=True):
arr[ind] = np.array(val.split(), dtype=np.float64)

data["positions"] *= self._dist_conversion
Expand Down
2 changes: 1 addition & 1 deletion MDANSE/Src/MDANSE/Framework/Converters/Gromacs.py
Original file line number Diff line number Diff line change
Expand Up @@ -98,7 +98,7 @@ def initialize(self):
if self._read_velocities < 0 or self._read_forces < 0:
raise RuntimeError(
"Could not determine whether velocities or forces are present!"
)
) from None

# The TRRTrajectoryFile object returns ints for these values, so turn them into bools
self._read_velocities, self._read_forces = (
Expand Down
8 changes: 6 additions & 2 deletions MDANSE/Src/MDANSE/Framework/Converters/LAMMPS.py
Original file line number Diff line number Diff line change
Expand Up @@ -438,7 +438,11 @@ def parse_first_step(
for i, (_, atom_line) in enumerate(take(self._nAtoms, file)):
temp = {
key: self._type_map[key](val)
for key, val in zip(self.keywords, atom_line.split())
for key, val in zip(
self.keywords,
atom_line.split(),
strict=False,
)
}
idx = temp.get("id", 1)

Expand Down Expand Up @@ -545,7 +549,7 @@ def run_step(self, index: int) -> tuple[int, int | None]:
for i, line in enumerate(take(self._nAtoms, file), 1):
temp = {
key: self._type_map[key](val)
for key, val in zip(self.keywords, line.split())
for key, val in zip(self.keywords, line.split(), strict=False)
}
idx = temp.get("id", i) - 1 # MDANSE 0-indexed
coords[idx, :] = np.array(
Expand Down
22 changes: 14 additions & 8 deletions MDANSE/Src/MDANSE/Framework/Converters/VASP.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,9 @@
from __future__ import annotations

import collections
from functools import partial

from more_itertools import run_length

from MDANSE.Chemistry.ChemicalSystem import ChemicalSystem
from MDANSE.Core.Error import Error
Expand Down Expand Up @@ -106,14 +109,17 @@ def initialize(self):
self.numberOfSteps = int(self._xdatcarFile["n_frames"])

self._chemical_system = ChemicalSystem()
element_list = []

for symbol, number in zip(
self._xdatcarFile["atoms"], self._xdatcarFile["atom_numbers"]
):
for i in range(number):
element = get_element_from_mapping(self._atomicAliases, symbol)
element_list.append(element)

atoms = (
get_element_from_mapping(self._atomicAliases, atom)
for atom in self._xdatcarFile["atoms"]
)

element_list = list(
run_length.decode(
zip(atoms, self._xdatcarFile["atom_numbers"], strict=True)
)
)
self._chemical_system.initialise_atoms(element_list)

# A trajectory is opened for writing.
Expand Down
2 changes: 1 addition & 1 deletion MDANSE/Src/MDANSE/Framework/Jobs/AreaPerMolecule.py
Original file line number Diff line number Diff line change
Expand Up @@ -142,7 +142,7 @@ def run_step(self, index):
raise AreaPerMoleculeError(
"The unit cell must be defined for AreaPerMolecule. "
"You can add a box using TrajectoryEditor."
)
) from None

apm = np.sqrt(np.sum(normalVect**2)) / self._nMolecules

Expand Down
2 changes: 1 addition & 1 deletion MDANSE/Src/MDANSE/Framework/Jobs/AverageStructure.py
Original file line number Diff line number Diff line change
Expand Up @@ -109,7 +109,7 @@ def initialize(self):
raise ValueError(
"Unit cell needs to be defined for the AverageStructure analysis. "
"You can add a unit cell using TrajectoryEditor."
)
) from None
else:
self._unit_cells = unit_cells

Expand Down
2 changes: 1 addition & 1 deletion MDANSE/Src/MDANSE/Framework/Jobs/Density.py
Original file line number Diff line number Diff line change
Expand Up @@ -127,7 +127,7 @@ def run_step(self, index):
raise DensityError(
"Density cannot be computed for chemical system without a defined simulation box. "
"You can add a box using TrajectoryEditor."
)
) from None
if abs(cell_volume) < 1e-31:
raise DensityError(
f"Non-physical cell volume: {cell_volume}. Density will not be calculated."
Expand Down
2 changes: 1 addition & 1 deletion MDANSE/Src/MDANSE/Framework/Jobs/IJob.py
Original file line number Diff line number Diff line change
Expand Up @@ -391,7 +391,7 @@ def _run_multicore(self, *, prog: bool = False):
for i in range(self.numberOfSteps):
inputQueue.put(i)

for i in range(self.configuration["running_mode"]["slots"]):
for _ in range(self.configuration["running_mode"]["slots"]):
self._run_multicore_check_terminate(listener)
p = multiprocessing.Process(
target=self.process_tasks_queue,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -90,15 +90,15 @@ class NeutronDynamicTotalStructureFactor(IJob):

def _get_data_from_files(self, props: str):
out = {}
for file, prop in zip(("dcsf", "disf"), self._expand(props)):
for file, prop in zip(("dcsf", "disf"), self._expand(props), strict=True):
try:
out[file] = self.configuration[f"{file}_input_file"]["instance"][prop][
:
]
except KeyError:
raise NeutronDynamicTotalStructureFactorError(
f"No `{prop}` found in {file} input file"
)
) from None
return tuple(out.values())

@staticmethod
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -176,6 +176,7 @@ def calc_func(
else None,
pdf_total - pdf_intra if self.intra else None,
),
strict=True,
):
yield f"pdf{i}", i == "/intra", pdf
yield (
Expand Down
4 changes: 2 additions & 2 deletions MDANSE/Src/MDANSE/Framework/Jobs/RotationAutocorrelation.py
Original file line number Diff line number Diff line change
Expand Up @@ -191,14 +191,14 @@ def combine(self, index: int, x: np.ndarray):
array of the correlation results

"""
for ax_ind, axis in enumerate(["x", "y", "z"]):
for ax_ind, axis in "xyz":
self._outputData[f"{axis}_rotation_ac"] += x[0][ax_ind]
self._outputData[f"rotation_around_{axis}"] += x[1][:, ax_ind]

def finalize(self):
"""Normalise and write out the results."""

for ax_ind, axis in enumerate(["x", "y", "z"]):
for axis in "xyz":
self._outputData[f"{axis}_rotation_ac"] /= self.numberOfSteps
self._outputData[f"rotation_around_{axis}"] /= self.numberOfSteps

Expand Down
Loading
Loading