From c3c4b5b7fc956ef60c087661436a5d70a065f20e Mon Sep 17 00:00:00 2001 From: Jacob Wilkins Date: Fri, 24 Jan 2025 17:20:00 +0000 Subject: [PATCH] Run ruff format --- .github/workflows/lint.yml | 7 +- MDANSE/Src/MDANSE/Chemistry/ChemicalSystem.py | 13 +- MDANSE/Src/MDANSE/Chemistry/Databases.py | 29 +--- MDANSE/Src/MDANSE/Core/Platform.py | 8 +- MDANSE/Src/MDANSE/Core/Singleton.py | 4 +- MDANSE/Src/MDANSE/Core/SubclassFactory.py | 7 +- .../Framework/AtomMapping/atom_mapping.py | 9 +- .../Framework/AtomSelector/all_selector.py | 12 +- .../Framework/AtomSelector/atom_selectors.py | 18 +-- .../Framework/AtomSelector/group_selectors.py | 20 +-- .../AtomSelector/molecule_selectors.py | 4 +- .../MDANSE/Framework/AtomSelector/selector.py | 30 +++-- MDANSE/Src/MDANSE/Framework/Configurable.py | 8 +- .../Configurators/ASEFileConfigurator.py | 1 - .../AtomSelectionConfigurator.py | 3 +- .../AtomTransmutationConfigurator.py | 9 +- .../Configurators/AtomsListConfigurator.py | 8 +- .../AxisSelectionConfigurator.py | 4 +- .../BasisSelectionConfigurator.py | 4 +- .../Configurators/ConfigFileConfigurator.py | 14 +- .../CorrelationFramesConfigurator.py | 4 +- .../DerivativeOrderConfigurator.py | 4 +- .../DistHistCutoffConfigurator.py | 10 +- .../Configurators/FieldFileConfigurator.py | 16 +-- .../FileWithAtomDataConfigurator.py | 1 - .../Configurators/FramesConfigurator.py | 17 ++- .../GroupingLevelConfigurator.py | 14 +- .../Configurators/HDFInputFileConfigurator.py | 4 +- .../Framework/Configurators/IConfigurator.py | 4 +- .../InstrumentResolutionConfigurator.py | 12 +- .../Configurators/IntegerConfigurator.py | 8 +- .../InterpolationOrderConfigurator.py | 8 +- .../MDAnalysisCoordinateFileConfigurator.py | 1 - .../MDAnalysisTimeStepConfigurator.py | 9 +- .../MDAnalysisTopologyFileConfigurator.py | 5 +- .../Configurators/MDFileConfigurator.py | 36 ++--- .../MDMCTrajectoryConfigurator.py | 3 +- .../MDTrajTimeStepConfigurator.py | 5 +- .../MDTrajTopologyFileConfigurator.py | 17 +-- .../MDTrajTrajectoryFileConfigurator.py | 1 - .../McStasParametersConfigurator.py | 8 +- .../MockTrajectoryConfigurator.py | 3 +- .../MoleculeSelectionConfigurator.py | 8 +- .../MultiInputFileConfigurator.py | 5 +- .../Configurators/OutputFilesConfigurator.py | 16 +-- .../PartialChargeConfigurator.py | 12 +- .../Configurators/QVectorsConfigurator.py | 8 +- .../Configurators/RangeConfigurator.py | 1 - .../SingleOutputFileConfigurator.py | 12 +- .../Configurators/StringConfigurator.py | 4 +- .../Configurators/UnitCellConfigurator.py | 12 +- .../Configurators/VectorConfigurator.py | 4 +- .../Configurators/WeightsConfigurator.py | 20 +-- .../Configurators/XDATCARFileConfigurator.py | 14 +- .../Configurators/XTDFileConfigurator.py | 17 +-- .../Configurators/XYZFileConfigurator.py | 16 +-- MDANSE/Src/MDANSE/Framework/Converters/ASE.py | 16 +-- .../Src/MDANSE/Framework/Converters/CP2K.py | 26 +--- .../MDANSE/Framework/Converters/Converter.py | 4 +- MDANSE/Src/MDANSE/Framework/Converters/DCD.py | 20 +-- .../MDANSE/Framework/Converters/DL_POLY.py | 13 +- .../MDANSE/Framework/Converters/Discover.py | 7 +- .../MDANSE/Framework/Converters/Forcite.py | 28 +--- .../MDANSE/Framework/Converters/Gromacs.py | 15 +-- .../Framework/Converters/ImprovedASE.py | 8 +- .../Src/MDANSE/Framework/Converters/LAMMPS.py | 52 ++------ .../MDANSE/Framework/Converters/MDAnalysis.py | 7 +- .../Src/MDANSE/Framework/Converters/MDTraj.py | 14 +- .../Src/MDANSE/Framework/Converters/VASP.py | 8 +- .../MDANSE/Framework/Formats/TextFormat.py | 9 +- .../Handlers/ColorizingStreamHandler.py | 4 +- .../InputData/HDFTrajectoryInputData.py | 4 +- .../InstrumentResolutions/PseudoVoigt.py | 4 +- .../Framework/InstrumentResolutions/Square.py | 4 +- .../InstrumentResolutions/__init__.py | 4 +- .../Framework/Jobs/AngularCorrelation.py | 18 +-- .../MDANSE/Framework/Jobs/AreaPerMolecule.py | 11 +- .../MDANSE/Framework/Jobs/AverageStructure.py | 16 +-- .../Jobs/CenterOfMassesTrajectory.py | 8 +- .../Framework/Jobs/CoordinationNumber.py | 24 +--- .../Framework/Jobs/CroppedTrajectory.py | 13 +- .../Jobs/CurrentCorrelationFunction.py | 20 ++- MDANSE/Src/MDANSE/Framework/Jobs/Density.py | 12 +- .../MDANSE/Framework/Jobs/DensityOfStates.py | 8 +- .../MDANSE/Framework/Jobs/DensityProfile.py | 8 +- .../Jobs/DipoleAutoCorrelationFunction.py | 21 +-- .../Framework/Jobs/DistanceHistogram.py | 8 +- .../Jobs/DynamicCoherentStructureFactor.py | 10 +- .../Jobs/DynamicIncoherentStructureFactor.py | 12 +- .../Src/MDANSE/Framework/Jobs/Eccentricity.py | 16 +-- .../Jobs/ElasticIncoherentStructureFactor.py | 4 +- ...aussianDynamicIncoherentStructureFactor.py | 8 +- .../Jobs/GeneralAutoCorrelationFunction.py | 4 +- .../Jobs/GlobalMotionFilteredTrajectory.py | 8 +- MDANSE/Src/MDANSE/Framework/Jobs/IJob.py | 13 +- MDANSE/Src/MDANSE/Framework/Jobs/Infrared.py | 21 +-- .../Framework/Jobs/McStasVirtualInstrument.py | 58 +++----- .../Framework/Jobs/MeanSquareDisplacement.py | 12 +- .../MDANSE/Framework/Jobs/MolecularTrace.py | 11 +- .../NeutronDynamicTotalStructureFactor.py | 124 +++++------------- .../MDANSE/Framework/Jobs/OrderParameter.py | 10 +- .../Jobs/PairDistributionFunction.py | 16 +-- .../Jobs/PositionAutoCorrelationFunction.py | 8 +- .../Framework/Jobs/PositionPowerSpectrum.py | 8 +- .../MDANSE/Framework/Jobs/RadiusOfGyration.py | 10 +- .../Framework/Jobs/RigidBodyTrajectory.py | 31 ++--- .../Framework/Jobs/RootMeanSquareDeviation.py | 8 +- .../Jobs/RootMeanSquareFluctuation.py | 10 +- .../Jobs/SolventAccessibleSurface.py | 35 ++--- .../Framework/Jobs/StaticStructureFactor.py | 16 +-- .../StructureFactorFromScatteringFunction.py | 12 +- .../Src/MDANSE/Framework/Jobs/Temperature.py | 8 +- .../MDANSE/Framework/Jobs/TrajectoryEditor.py | 14 +- .../Framework/Jobs/UnfoldedTrajectory.py | 9 +- .../Framework/Jobs/VanHoveFunctionDistinct.py | 25 +--- .../Framework/Jobs/VanHoveFunctionSelf.py | 4 +- .../Jobs/VelocityAutoCorrelationFunction.py | 12 +- MDANSE/Src/MDANSE/Framework/Jobs/Voronoi.py | 9 +- .../Jobs/XRayStaticStructureFactor.py | 20 +-- .../OutputVariables/IOutputVariable.py | 3 +- .../Framework/OutputVariables/__init__.py | 4 +- .../Framework/Projectors/AxialProjector.py | 4 +- .../Framework/Projectors/PlanarProjector.py | 4 +- .../QVectors/ApproximateDispersionQVectors.py | 12 +- .../QVectors/CircularLatticeQVectors.py | 5 +- .../Framework/QVectors/CircularQVectors.py | 6 +- .../QVectors/DispersionLatticeQVectors.py | 8 +- .../MDANSE/Framework/QVectors/GridQVectors.py | 4 +- .../MDANSE/Framework/QVectors/IQVectors.py | 4 +- .../QVectors/LinearLatticeQVectors.py | 5 +- .../Framework/QVectors/LinearQVectors.py | 10 +- .../QVectors/SphericalLatticeQVectors.py | 9 +- .../Framework/QVectors/SphericalQVectors.py | 6 +- MDANSE/Src/MDANSE/Framework/Units.py | 96 ++++---------- MDANSE/Src/MDANSE/IO/FortranFormat.py | 1 + MDANSE/Src/MDANSE/IO/MinimalPDBReader.py | 6 +- .../Src/MDANSE/Mathematics/LinearAlgebra.py | 11 +- .../Src/MDANSE/Mathematics/Transformation.py | 30 +---- .../Src/MDANSE/MolecularDynamics/Analysis.py | 4 +- .../MDANSE/MolecularDynamics/Configuration.py | 40 ++---- .../MDANSE/MolecularDynamics/Connectivity.py | 4 +- .../MolecularDynamics/MockTrajectory.py | 52 ++------ .../MDANSE/MolecularDynamics/Trajectory.py | 39 ++---- .../MolecularDynamics/TrajectoryUtils.py | 1 - .../NeutronInstruments/Coverage/__init__.py | 4 +- .../NeutronInstruments/Method/__init__.py | 5 +- .../NeutronInstruments/Resolution/__init__.py | 4 +- .../NeutronInstruments/Spectrum/__init__.py | 4 +- MDANSE/Src/MDANSE/Scripts/mdanse.py | 61 +++------ .../Src/MDANSE/Trajectory/H5MDTrajectory.py | 58 +++----- .../Src/MDANSE/Trajectory/MdanseTrajectory.py | 61 +++------ 151 files changed, 564 insertions(+), 1532 deletions(-) diff --git a/.github/workflows/lint.yml b/.github/workflows/lint.yml index e3fa86c035..b08a29eab6 100644 --- a/.github/workflows/lint.yml +++ b/.github/workflows/lint.yml @@ -11,10 +11,11 @@ jobs: runs-on: ubuntu-latest steps: - uses: actions/checkout@v4 - - uses: psf/black@stable + - uses: astral-sh/ruff-action@v3 with: - options: "--check --verbose" - src: "MDANSE_GUI/Src" + src: "./MDANSE/Src" + args: "format --check" + lint_check_ruff: runs-on: ubuntu-latest diff --git a/MDANSE/Src/MDANSE/Chemistry/ChemicalSystem.py b/MDANSE/Src/MDANSE/Chemistry/ChemicalSystem.py index d411393640..fc07f64a3e 100644 --- a/MDANSE/Src/MDANSE/Chemistry/ChemicalSystem.py +++ b/MDANSE/Src/MDANSE/Chemistry/ChemicalSystem.py @@ -28,7 +28,6 @@ class ChemicalSystem: - def __init__(self, name: str = "", trajectory=None): """ @@ -80,9 +79,7 @@ def add_atom(self, atm_num: int) -> int: def add_bonds(self, pair_list: List[Tuple[int]]): self._bonds += list(pair_list) for pair in pair_list: - self.rdkit_mol.AddBond( - int(pair[0]), int(pair[1]), Chem.rdchem.BondType.UNSPECIFIED - ) + self.rdkit_mol.AddBond(int(pair[0]), int(pair[1]), Chem.rdchem.BondType.UNSPECIFIED) def add_labels(self, label_dict: Dict[str, List[int]]): for key, item in label_dict.items(): @@ -98,9 +95,7 @@ def add_clusters(self, group_list: List[List[int]]): continue atom_list = [self._atom_types[index] for index in group] unique_atoms, counts = np.unique(atom_list, return_counts=True) - name = "_".join( - [str(unique_atoms[n]) + str(counts[n]) for n in range(len(counts))] - ) + name = "_".join([str(unique_atoms[n]) + str(counts[n]) for n in range(len(counts))]) if name not in self._clusters: self._clusters[name] = [sorted_group] else: @@ -122,9 +117,7 @@ def has_substructure_match(self, smarts: str) -> bool: """ return self.rdkit_mol.HasSubstructMatch(Chem.MolFromSmarts(smarts)) - def get_substructure_matches( - self, smarts: str, maxmatches: int = 1000000 - ) -> set[int]: + def get_substructure_matches(self, smarts: str, maxmatches: int = 1000000) -> set[int]: """Get the indices which match the smarts string. Note that the default bond type in MDANSE is Chem.rdchem.BondType.UNSPECIFIED. diff --git a/MDANSE/Src/MDANSE/Chemistry/Databases.py b/MDANSE/Src/MDANSE/Chemistry/Databases.py index df6f51204c..5458e7ae91 100644 --- a/MDANSE/Src/MDANSE/Chemistry/Databases.py +++ b/MDANSE/Src/MDANSE/Chemistry/Databases.py @@ -244,9 +244,7 @@ def add_atom(self, atom: str) -> None: """ if atom in self._data: - raise AtomsDatabaseError( - "The atom {} is already stored in the database".format(atom) - ) + raise AtomsDatabaseError("The atom {} is already stored in the database".format(atom)) self._data[atom] = {} @@ -304,9 +302,7 @@ def get_isotopes(self, atom: str) -> list[str]: # The isotopes are searched according to |symbol| property symbol = self._data[atom]["symbol"] - return [ - iname for iname, props in self._data.items() if props["symbol"] == symbol - ] + return [iname for iname, props in self._data.items() if props["symbol"] == symbol] @property def properties(self) -> list[str]: @@ -338,8 +334,7 @@ def get_property(self, pname: str) -> dict[str, Union[str, int, float, list]]: ptype = AtomsDatabase._TYPES[self._properties[pname]] return { - element: properties.get(pname, ptype()) - for element, properties in self._data.items() + element: properties.get(pname, ptype()) for element, properties in self._data.items() } def get_value(self, atom: str, pname: str) -> Union[str, int, float, list]: @@ -400,9 +395,7 @@ def get_values_for_multiple_atoms( values = {name: self._data[name][prop] for name in unique_atoms} return [values[atom] for atom in atoms] - def set_value( - self, atom: str, pname: str, value: Union[str, int, float, list] - ) -> None: + def set_value(self, atom: str, pname: str, value: Union[str, int, float, list]) -> None: """ Set the given property of the given atom to the given value. @@ -425,9 +418,7 @@ def set_value( ) try: - self._data[atom][pname] = AtomsDatabase._TYPES[self._properties[pname]]( - value - ) + self._data[atom][pname] = AtomsDatabase._TYPES[self._properties[pname]](value) except ValueError: raise AtomsDatabaseError( "Can not coerce {} to {} type".format(value, self._properties[pname]) @@ -482,9 +473,7 @@ def info(self, atom: str) -> str: # The values for all element's properties for pname in sorted(self._properties): - info.append( - " {0:<20}{1:>50}".format(pname, str(self._data[atom].get(pname, None))) - ) + info.append(" {0:<20}{1:>50}".format(pname, str(self._data[atom].get(pname, None)))) info.append(delimiter) info = "\n".join(info) @@ -564,11 +553,7 @@ def numeric_properties(self) -> list[str]: :return: the name of the numeric properties stored in the atoms database :rtype: list """ - return [ - pname - for pname, prop in self._properties.items() - if prop in ["int", "float"] - ] + return [pname for pname, prop in self._properties.items() if prop in ["int", "float"]] def _reset(self) -> None: """ diff --git a/MDANSE/Src/MDANSE/Core/Platform.py b/MDANSE/Src/MDANSE/Core/Platform.py index 8b3f0b771e..9fd9f091c7 100644 --- a/MDANSE/Src/MDANSE/Core/Platform.py +++ b/MDANSE/Src/MDANSE/Core/Platform.py @@ -433,9 +433,7 @@ def etime_to_ctime(self, etime): days, hours, minutes, seconds = etime[-4:] - etime = datetime.timedelta( - days=days, hours=hours, minutes=minutes, seconds=seconds - ) + etime = datetime.timedelta(days=days, hours=hours, minutes=minutes, seconds=seconds) return (datetime.datetime.today() - etime).strftime("%d-%m-%Y %H:%M:%S") @@ -457,9 +455,7 @@ def get_processes_info(self): procs = [p.split() for p in procs if p] # A mapping between the active processes pid and their corresponding exectuable. - procs = dict( - [(int(p[0].strip()), self.etime_to_ctime(p[1].strip())) for p in procs] - ) + procs = dict([(int(p[0].strip()), self.etime_to_ctime(p[1].strip())) for p in procs]) return procs diff --git a/MDANSE/Src/MDANSE/Core/Singleton.py b/MDANSE/Src/MDANSE/Core/Singleton.py index 01154c5a51..1dd8bcb4e9 100644 --- a/MDANSE/Src/MDANSE/Core/Singleton.py +++ b/MDANSE/Src/MDANSE/Core/Singleton.py @@ -28,8 +28,6 @@ def __call__(self, *args, **kwargs): """ if self.__name__ not in self.__instances: - self.__instances[self.__name__] = super(Singleton, self).__call__( - *args, **kwargs - ) + self.__instances[self.__name__] = super(Singleton, self).__call__(*args, **kwargs) return self.__instances[self.__name__] diff --git a/MDANSE/Src/MDANSE/Core/SubclassFactory.py b/MDANSE/Src/MDANSE/Core/SubclassFactory.py index 2a2bdb0721..9190453196 100644 --- a/MDANSE/Src/MDANSE/Core/SubclassFactory.py +++ b/MDANSE/Src/MDANSE/Core/SubclassFactory.py @@ -70,9 +70,7 @@ def recursive_search(parent_class: type, name: str): return return_type else: for child in parent_class._registered_subclasses.keys(): - return_type = recursive_search( - parent_class._registered_subclasses[child], name - ) + return_type = recursive_search(parent_class._registered_subclasses[child], name) if return_type is not None: return return_type @@ -114,8 +112,7 @@ def recursive_dict(parent_class: type) -> dict: """ try: results = { - ckey: parent_class._registered_subclasses[ckey] - for ckey in parent_class.subclasses() + ckey: parent_class._registered_subclasses[ckey] for ckey in parent_class.subclasses() } except Exception: return {} diff --git a/MDANSE/Src/MDANSE/Framework/AtomMapping/atom_mapping.py b/MDANSE/Src/MDANSE/Framework/AtomMapping/atom_mapping.py index b2ee2ca975..955e54756d 100644 --- a/MDANSE/Src/MDANSE/Framework/AtomMapping/atom_mapping.py +++ b/MDANSE/Src/MDANSE/Framework/AtomMapping/atom_mapping.py @@ -21,7 +21,6 @@ class AtomLabel: - def __init__(self, atm_label: str, **kwargs): """Creates an atom label object which is used for atom mapping and atom type guessing. @@ -171,9 +170,7 @@ def guess_element(atm_label: str, mass: Union[float, int, None] = None) -> str: raise AttributeError(f"Unable to guess: {atm_label}") -def get_element_from_mapping( - mapping: dict[str, dict[str, str]], label: str, **kwargs -) -> str: +def get_element_from_mapping(mapping: dict[str, dict[str, str]], label: str, **kwargs) -> str: """Determine the symbol of the element from the atom label and the information from the kwargs. @@ -202,9 +199,7 @@ def get_element_from_mapping( return element -def fill_remaining_labels( - mapping: dict[str, dict[str, str]], labels: list[AtomLabel] -) -> None: +def fill_remaining_labels(mapping: dict[str, dict[str, str]], labels: list[AtomLabel]) -> None: """Given a list of labels fill the remaining labels in the mapping dictionary. diff --git a/MDANSE/Src/MDANSE/Framework/AtomSelector/all_selector.py b/MDANSE/Src/MDANSE/Framework/AtomSelector/all_selector.py index 8b1813e10c..cf1a452c88 100644 --- a/MDANSE/Src/MDANSE/Framework/AtomSelector/all_selector.py +++ b/MDANSE/Src/MDANSE/Framework/AtomSelector/all_selector.py @@ -17,9 +17,7 @@ from MDANSE.MolecularDynamics.Trajectory import Trajectory -def select_all( - trajectory: Trajectory, check_exists: bool = False -) -> Union[set[int], bool]: +def select_all(trajectory: Trajectory, check_exists: bool = False) -> Union[set[int], bool]: """Selects all atoms in the chemical system except for the dummy atoms. @@ -45,10 +43,4 @@ def select_all( for atm in system._unique_elements: if trajectory.get_atom_property(atm, "dummy"): dummy_list.append(atm) - return set( - [ - index - for index in system._atom_indices - if atom_list[index] not in dummy_list - ] - ) + return set([index for index in system._atom_indices if atom_list[index] not in dummy_list]) diff --git a/MDANSE/Src/MDANSE/Framework/AtomSelector/atom_selectors.py b/MDANSE/Src/MDANSE/Framework/AtomSelector/atom_selectors.py index 1b7a054818..1b0ba6211a 100644 --- a/MDANSE/Src/MDANSE/Framework/AtomSelector/atom_selectors.py +++ b/MDANSE/Src/MDANSE/Framework/AtomSelector/atom_selectors.py @@ -55,9 +55,7 @@ def select_element( return system.get_substructure_matches(pattern) -def select_dummy( - trajectory: Trajectory, check_exists: bool = False -) -> Union[set[int], bool]: +def select_dummy(trajectory: Trajectory, check_exists: bool = False) -> Union[set[int], bool]: """Selects all dummy atoms in the chemical system. Parameters @@ -86,11 +84,7 @@ def select_dummy( if trajectory.get_atom_property(atm, "dummy"): dummy_list.append(atm) return set( - [ - index - for index, element in enumerate(system.atom_list) - if element in dummy_list - ] + [index for index, element in enumerate(system.atom_list) if element in dummy_list] ) @@ -119,9 +113,7 @@ def select_atom_name( return True return False else: - return set( - [index for index, element in enumerate(system.atom_list) if element == name] - ) + return set([index for index, element in enumerate(system.atom_list) if element == name]) def select_atom_fullname( @@ -149,9 +141,7 @@ def select_atom_fullname( return True return False else: - return set( - [index for index, name in enumerate(system.name_list) if name == fullname] - ) + return set([index for index, name in enumerate(system.name_list) if name == fullname]) def select_hs_on_element( diff --git a/MDANSE/Src/MDANSE/Framework/AtomSelector/group_selectors.py b/MDANSE/Src/MDANSE/Framework/AtomSelector/group_selectors.py index 0bc1e85672..3f6c330cac 100644 --- a/MDANSE/Src/MDANSE/Framework/AtomSelector/group_selectors.py +++ b/MDANSE/Src/MDANSE/Framework/AtomSelector/group_selectors.py @@ -52,9 +52,7 @@ def select_primary_amine( return system.get_substructure_matches(pattern) -def select_hydroxy( - trajectory: Trajectory, check_exists: bool = False -) -> Union[set[int], bool]: +def select_hydroxy(trajectory: Trajectory, check_exists: bool = False) -> Union[set[int], bool]: """Selects the O and H atoms of all hydroxy groups including water. Parameters @@ -77,9 +75,7 @@ def select_hydroxy( return system.get_substructure_matches(pattern) -def select_methyl( - trajectory: Trajectory, check_exists: bool = False -) -> Union[set[int], bool]: +def select_methyl(trajectory: Trajectory, check_exists: bool = False) -> Union[set[int], bool]: """Selects the C and H atoms of all methyl groups. Parameters @@ -102,9 +98,7 @@ def select_methyl( return system.get_substructure_matches(pattern) -def select_phosphate( - trajectory: Trajectory, check_exists: bool = False -) -> Union[set[int], bool]: +def select_phosphate(trajectory: Trajectory, check_exists: bool = False) -> Union[set[int], bool]: """Selects the P and O atoms of all phosphate groups. Parameters @@ -127,9 +121,7 @@ def select_phosphate( return system.get_substructure_matches(pattern) -def select_sulphate( - trajectory: Trajectory, check_exists: bool = False -) -> Union[set[int], bool]: +def select_sulphate(trajectory: Trajectory, check_exists: bool = False) -> Union[set[int], bool]: """Selects the S and O atoms of all sulphate groups. Parameters @@ -152,9 +144,7 @@ def select_sulphate( return system.get_substructure_matches(pattern) -def select_thiol( - trajectory: Trajectory, check_exists: bool = False -) -> Union[set[int], bool]: +def select_thiol(trajectory: Trajectory, check_exists: bool = False) -> Union[set[int], bool]: """Selects the S and H atoms of all thiol groups. Parameters diff --git a/MDANSE/Src/MDANSE/Framework/AtomSelector/molecule_selectors.py b/MDANSE/Src/MDANSE/Framework/AtomSelector/molecule_selectors.py index 366f599833..d793fe35a1 100644 --- a/MDANSE/Src/MDANSE/Framework/AtomSelector/molecule_selectors.py +++ b/MDANSE/Src/MDANSE/Framework/AtomSelector/molecule_selectors.py @@ -22,9 +22,7 @@ ] -def select_water( - trajectory: Trajectory, check_exists: bool = False -) -> Union[set[int], bool]: +def select_water(trajectory: Trajectory, check_exists: bool = False) -> Union[set[int], bool]: """Selects the O and H atoms of all water molecules. Parameters diff --git a/MDANSE/Src/MDANSE/Framework/AtomSelector/selector.py b/MDANSE/Src/MDANSE/Framework/AtomSelector/selector.py index 4b9db97c55..a4415b1025 100644 --- a/MDANSE/Src/MDANSE/Framework/AtomSelector/selector.py +++ b/MDANSE/Src/MDANSE/Framework/AtomSelector/selector.py @@ -21,11 +21,22 @@ from MDANSE.MolecularDynamics.Trajectory import Trajectory from MDANSE.Framework.AtomSelector.all_selector import select_all from MDANSE.Framework.AtomSelector.atom_selectors import ( - select_atom_fullname, select_atom_name, select_dummy, select_element, - select_hs_on_element, select_hs_on_heteroatom, select_index) + select_atom_fullname, + select_atom_name, + select_dummy, + select_element, + select_hs_on_element, + select_hs_on_heteroatom, + select_index, +) from MDANSE.Framework.AtomSelector.group_selectors import ( - select_hydroxy, select_methyl, select_phosphate, select_primary_amine, - select_sulphate, select_thiol) + select_hydroxy, + select_methyl, + select_phosphate, + select_primary_amine, + select_sulphate, + select_thiol, +) from MDANSE.Framework.AtomSelector.molecule_selectors import select_water @@ -124,9 +135,7 @@ def __init__(self, trajectory: Trajectory) -> None: for k1 in v0.keys(): self.match_exists[k0][k1] = True else: - self.match_exists[k0] = self._funcs[k0]( - self.trajectory, check_exists=True - ) + self.match_exists[k0] = self._funcs[k0](self.trajectory, check_exists=True) self.settings = self.create_default_settings() @@ -166,9 +175,7 @@ def update_settings( Raises a ValueError if the inputted settings are not valid. """ if not self.check_valid_setting(settings): - raise ValueError( - f"Settings are not valid for the given chemical system - {settings}." - ) + raise ValueError(f"Settings are not valid for the given chemical system - {settings}.") if reset_first: self.reset_settings() @@ -191,7 +198,6 @@ def get_idxs(self) -> set[int]: idxs = set([]) for k, v in self.settings.items(): - if isinstance(v, dict): args = [{self._kwarg_keys[k]: i} for i in v.keys()] switches = v.values() @@ -223,7 +229,6 @@ def update_with_idxs(self, idxs: set[int]) -> None: added = set([]) for k, v in self.settings.items(): - if k == "index": continue @@ -327,7 +332,6 @@ def check_valid_setting(self, settings: dict[str, Union[bool, dict]]) -> bool: setting_keys = self._default.keys() dict_setting_keys = self._kwarg_keys.keys() for k0, v0 in settings.items(): - if k0 not in setting_keys: return False diff --git a/MDANSE/Src/MDANSE/Framework/Configurable.py b/MDANSE/Src/MDANSE/Framework/Configurable.py index d4343d4958..f8c1c8cdce 100644 --- a/MDANSE/Src/MDANSE/Framework/Configurable.py +++ b/MDANSE/Src/MDANSE/Framework/Configurable.py @@ -347,9 +347,7 @@ def build_doc(cls, use_html_table=False): settings = getattr(cls, "settings", {}) if not isinstance(settings, dict): - raise ConfigurationError( - "Invalid type for settings: must be a mapping-like object" - ) + raise ConfigurationError("Invalid type for settings: must be a mapping-like object") doclist = [] @@ -390,9 +388,7 @@ def get_default_parameters(cls): settings = getattr(cls, "settings", {}) if not isinstance(settings, dict): - raise ConfigurationError( - "Invalid type for settings: must be a mapping-like object" - ) + raise ConfigurationError("Invalid type for settings: must be a mapping-like object") params = collections.OrderedDict() for name, (typ, kwds) in list(settings.items()): diff --git a/MDANSE/Src/MDANSE/Framework/Configurators/ASEFileConfigurator.py b/MDANSE/Src/MDANSE/Framework/Configurators/ASEFileConfigurator.py index 8f57aa1e20..e3fdab1532 100644 --- a/MDANSE/Src/MDANSE/Framework/Configurators/ASEFileConfigurator.py +++ b/MDANSE/Src/MDANSE/Framework/Configurators/ASEFileConfigurator.py @@ -28,7 +28,6 @@ class ASEFileConfigurator(FileWithAtomDataConfigurator): """ def parse(self): - try: self._input = ASETrajectory(self["filename"]) except Exception: diff --git a/MDANSE/Src/MDANSE/Framework/Configurators/AtomSelectionConfigurator.py b/MDANSE/Src/MDANSE/Framework/Configurators/AtomSelectionConfigurator.py index 5d7be86ca9..8e65afbe70 100644 --- a/MDANSE/Src/MDANSE/Framework/Configurators/AtomSelectionConfigurator.py +++ b/MDANSE/Src/MDANSE/Framework/Configurators/AtomSelectionConfigurator.py @@ -72,8 +72,7 @@ def configure(self, value: str) -> None: self["names"] = [at for at in selectedAtoms] self["unique_names"] = sorted(set(self["names"])) self["masses"] = [ - [trajConfig["instance"].get_atom_property(n, "atomic_weight")] - for n in self["names"] + [trajConfig["instance"].get_atom_property(n, "atomic_weight")] for n in self["names"] ] if self["selection_length"] == 0: self.error_status = "The atom selection is empty." diff --git a/MDANSE/Src/MDANSE/Framework/Configurators/AtomTransmutationConfigurator.py b/MDANSE/Src/MDANSE/Framework/Configurators/AtomTransmutationConfigurator.py index 6ec3f36fee..c69be1a49e 100644 --- a/MDANSE/Src/MDANSE/Framework/Configurators/AtomTransmutationConfigurator.py +++ b/MDANSE/Src/MDANSE/Framework/Configurators/AtomTransmutationConfigurator.py @@ -142,7 +142,6 @@ def configure(self, value: str): self._nTransmutedAtoms = 0 for idx, element in value.items(): - try: idx = int(idx) except ValueError: @@ -150,13 +149,13 @@ def configure(self, value: str): return if idx not in idxs: - self.error_status = "Inputted setting not valid - atom index not found in the current system." + self.error_status = ( + "Inputted setting not valid - atom index not found in the current system." + ) return if element not in traj_config["instance"].atoms_in_database: - self.error_status = ( - f"the element {element} is not registered in the database" - ) + self.error_status = f"the element {element} is not registered in the database" return self.transmute(idx, element) diff --git a/MDANSE/Src/MDANSE/Framework/Configurators/AtomsListConfigurator.py b/MDANSE/Src/MDANSE/Framework/Configurators/AtomsListConfigurator.py index d465ef6dd5..8fdfb515fa 100644 --- a/MDANSE/Src/MDANSE/Framework/Configurators/AtomsListConfigurator.py +++ b/MDANSE/Src/MDANSE/Framework/Configurators/AtomsListConfigurator.py @@ -69,9 +69,7 @@ def configure(self, value): molecule, atoms = UD_STORE.get_definition( traj_configurator["basename"], "%d_atoms_list" % self._nAtoms, value ) - elif UD_STORE.has_definition( - traj_configurator["basename"], "AtomsListConfigurator", value - ): + elif UD_STORE.has_definition(traj_configurator["basename"], "AtomsListConfigurator", value): tempdict = UD_STORE.get_definition( traj_configurator["basename"], "AtomsListConfigurator", value ) @@ -112,8 +110,6 @@ def get_information(self): return "No configured yet" info = [] - info.append( - "Number of selected %d-tuplets:%d" % (self._nAtoms, self["n_values"]) - ) + info.append("Number of selected %d-tuplets:%d" % (self._nAtoms, self["n_values"])) return "\n".join(info) + "\n" diff --git a/MDANSE/Src/MDANSE/Framework/Configurators/AxisSelectionConfigurator.py b/MDANSE/Src/MDANSE/Framework/Configurators/AxisSelectionConfigurator.py index c49ee605a5..f5429f1dfb 100644 --- a/MDANSE/Src/MDANSE/Framework/Configurators/AxisSelectionConfigurator.py +++ b/MDANSE/Src/MDANSE/Framework/Configurators/AxisSelectionConfigurator.py @@ -52,9 +52,7 @@ def configure(self, value): trajConfig = self._configurable[self._dependencies["trajectory"]] if UD_STORE.has_definition(trajConfig["basename"], "axis_selection", value): - ud = UD_STORE.get_definition( - trajConfig["basename"], "axis_selection", value - ) + ud = UD_STORE.get_definition(trajConfig["basename"], "axis_selection", value) self.update(ud) else: self.update(value) diff --git a/MDANSE/Src/MDANSE/Framework/Configurators/BasisSelectionConfigurator.py b/MDANSE/Src/MDANSE/Framework/Configurators/BasisSelectionConfigurator.py index c11e70a786..dfaa8735b9 100644 --- a/MDANSE/Src/MDANSE/Framework/Configurators/BasisSelectionConfigurator.py +++ b/MDANSE/Src/MDANSE/Framework/Configurators/BasisSelectionConfigurator.py @@ -52,9 +52,7 @@ def configure(self, value): trajConfig = self._configurable[self._dependencies["trajectory"]] if UD_STORE.has_definition(trajConfig["basename"], "basis_selection", value): - ud = UD_STORE.get_definition( - trajConfig["basename"], "basis_selection", value - ) + ud = UD_STORE.get_definition(trajConfig["basename"], "basis_selection", value) self.update(ud) else: self.update(value) diff --git a/MDANSE/Src/MDANSE/Framework/Configurators/ConfigFileConfigurator.py b/MDANSE/Src/MDANSE/Framework/Configurators/ConfigFileConfigurator.py index 1af42d6711..d4933854c9 100644 --- a/MDANSE/Src/MDANSE/Framework/Configurators/ConfigFileConfigurator.py +++ b/MDANSE/Src/MDANSE/Framework/Configurators/ConfigFileConfigurator.py @@ -29,7 +29,6 @@ class LAMMPSConfigFileError(Error): def parse_unit_cell(inputs): - unit_cell = np.zeros(9) xlo, xhi, xy = inputs[0], inputs[1], inputs[2] @@ -53,7 +52,6 @@ def parse_unit_cell(inputs): class ConfigFileConfigurator(FileWithAtomDataConfigurator): - def parse(self): self._filename = self["filename"] @@ -119,14 +117,10 @@ def parse(self): if re.match("^\s*masses\s*$", line, re.I): if self["n_atom_types"] is None: - raise LAMMPSConfigFileError( - "Did not find the number of atom types." - ) + raise LAMMPSConfigFileError("Did not find the number of atom types.") for j in range(1, self["n_atom_types"] + 1): - data_line = ( - lines[i + j].strip().split("#")[0] - ) # Remove comments, if present + data_line = lines[i + j].strip().split("#")[0] # Remove comments, if present idx, mass = data_line.split()[0:2] idx = int(idx) mass = float(mass) @@ -181,9 +175,7 @@ def parse(self): if np.trace(np.abs(self["unit_cell"])) < 1e-8: # print(f"Concatenated: {np.concatenate([x_inputs, y_inputs, z_inputs])}") try: - self["unit_cell"] = parse_unit_cell( - np.concatenate([x_inputs, y_inputs, z_inputs]) - ) + self["unit_cell"] = parse_unit_cell(np.concatenate([x_inputs, y_inputs, z_inputs])) except Exception: LOG.error("LAMMPS ConfigFileConfigurator failed to find a unit cell") diff --git a/MDANSE/Src/MDANSE/Framework/Configurators/CorrelationFramesConfigurator.py b/MDANSE/Src/MDANSE/Framework/Configurators/CorrelationFramesConfigurator.py index 4de5aa93c3..bc341933d1 100644 --- a/MDANSE/Src/MDANSE/Framework/Configurators/CorrelationFramesConfigurator.py +++ b/MDANSE/Src/MDANSE/Framework/Configurators/CorrelationFramesConfigurator.py @@ -19,7 +19,6 @@ class CorrelationFramesConfigurator(FramesConfigurator): - def configure(self, value: tuple[int, int, int, int]): """Configure the correlation and set the number of correlation frames to use. @@ -50,8 +49,7 @@ def configure(self, value: tuple[int, int, int, int]): if c_frames < 2: self.error_status = ( - "Number of frames used for the correlation " - "should be greater then zero." + "Number of frames used for the correlation should be greater then zero." ) return diff --git a/MDANSE/Src/MDANSE/Framework/Configurators/DerivativeOrderConfigurator.py b/MDANSE/Src/MDANSE/Framework/Configurators/DerivativeOrderConfigurator.py index 71436b9641..2acd2defc2 100644 --- a/MDANSE/Src/MDANSE/Framework/Configurators/DerivativeOrderConfigurator.py +++ b/MDANSE/Src/MDANSE/Framework/Configurators/DerivativeOrderConfigurator.py @@ -61,9 +61,7 @@ def configure(self, value: Optional[int]) -> None: number = frames_configurator["number"] if number < value + 1: - self.error_status = ( - f"Not enough MD frames to apply derivatives of order {value}" - ) + self.error_status = f"Not enough MD frames to apply derivatives of order {value}" return self.error_status = "OK" diff --git a/MDANSE/Src/MDANSE/Framework/Configurators/DistHistCutoffConfigurator.py b/MDANSE/Src/MDANSE/Framework/Configurators/DistHistCutoffConfigurator.py index dee9d13c9d..cc8b13e3a9 100644 --- a/MDANSE/Src/MDANSE/Framework/Configurators/DistHistCutoffConfigurator.py +++ b/MDANSE/Src/MDANSE/Framework/Configurators/DistHistCutoffConfigurator.py @@ -6,7 +6,6 @@ class DistHistCutoffConfigurator(RangeConfigurator): - def __init__(self, name, **kwargs): super().__init__(name, **kwargs) self._max_value = kwargs.get("max_value", True) @@ -20,9 +19,7 @@ def configure(self, value): A tuple of the range parameters. """ if self._max_value and value[1] > floor(self.get_largest_cutoff() * 100) / 100: - self.error_status = ( - "The cutoff distance goes into the simulation box periodic images." - ) + self.error_status = "The cutoff distance goes into the simulation box periodic images." return super().configure(value) @@ -39,10 +36,7 @@ def get_largest_cutoff(self) -> float: traj_config = self._configurable[self._dependencies["trajectory"]]["instance"] try: trajectory_array = np.array( - [ - traj_config.unit_cell(frame)._unit_cell - for frame in range(len(traj_config)) - ] + [traj_config.unit_cell(frame)._unit_cell for frame in range(len(traj_config))] ) except Exception: return np.linalg.norm(traj_config.min_span) diff --git a/MDANSE/Src/MDANSE/Framework/Configurators/FieldFileConfigurator.py b/MDANSE/Src/MDANSE/Framework/Configurators/FieldFileConfigurator.py index 233660a5dd..d2195498b1 100644 --- a/MDANSE/Src/MDANSE/Framework/Configurators/FieldFileConfigurator.py +++ b/MDANSE/Src/MDANSE/Framework/Configurators/FieldFileConfigurator.py @@ -51,9 +51,7 @@ def parse(self): self["n_molecular_types"] = int(self["n_molecular_types"]) - molBlocks = [ - i for i, line in enumerate(lines) if re.match("finish", line, re.IGNORECASE) - ] + molBlocks = [i for i, line in enumerate(lines) if re.match("finish", line, re.IGNORECASE)] if self["n_molecular_types"] != len(molBlocks): raise FieldFileError("Error in the definition of the molecular types") @@ -66,9 +64,7 @@ def parse(self): moleculeName = lines[first] # Extract the number of molecular types - nMolecules = re.match( - "nummols\s+(\d+)", lines[first + 1], re.IGNORECASE - ).groups()[0] + nMolecules = re.match("nummols\s+(\d+)", lines[first + 1], re.IGNORECASE).groups()[0] nMolecules = int(nMolecules) for i in range(first + 2, last): @@ -102,9 +98,7 @@ def parse(self): comp += 1 - self["molecules"].append( - [moleculeName, nMolecules, atoms, masses, charges] - ) + self["molecules"].append([moleculeName, nMolecules, atoms, masses, charges]) break @@ -148,9 +142,7 @@ def build_chemical_system(self, chemical_system, aliases): cluster = [] for _, (name, mass) in enumerate(zip(atomic_contents, masses)): # The atom is created. - element = get_element_from_mapping( - aliases, name, molecule=db_name, mass=mass - ) + element = get_element_from_mapping(aliases, name, molecule=db_name, mass=mass) element_list.append(element) name_list.append(name) cluster.append(index) diff --git a/MDANSE/Src/MDANSE/Framework/Configurators/FileWithAtomDataConfigurator.py b/MDANSE/Src/MDANSE/Framework/Configurators/FileWithAtomDataConfigurator.py index 8f3c8d5407..1858f379c4 100644 --- a/MDANSE/Src/MDANSE/Framework/Configurators/FileWithAtomDataConfigurator.py +++ b/MDANSE/Src/MDANSE/Framework/Configurators/FileWithAtomDataConfigurator.py @@ -22,7 +22,6 @@ class FileWithAtomDataConfigurator(InputFileConfigurator): - def configure(self, filepath: str) -> None: """ Parameters diff --git a/MDANSE/Src/MDANSE/Framework/Configurators/FramesConfigurator.py b/MDANSE/Src/MDANSE/Framework/Configurators/FramesConfigurator.py index 21233a23b5..e9e0f9f0a1 100644 --- a/MDANSE/Src/MDANSE/Framework/Configurators/FramesConfigurator.py +++ b/MDANSE/Src/MDANSE/Framework/Configurators/FramesConfigurator.py @@ -79,7 +79,9 @@ def configure(self, value): # check last setting if last <= 0 or last > n_steps or last <= first: - self.error_status = f"Last frame needs to be between 1 and {n_steps} and greater than the first frame" + self.error_status = ( + f"Last frame needs to be between 1 and {n_steps} and greater than the first frame" + ) return # check step setting @@ -122,14 +124,11 @@ def get_information(self): """ try: - result = ( - "%d frames selected (first=%.3f ; last = %.3f ; time step = %.3f)\n" - % ( - self["n_frames"], - self["time"][0], - self["time"][-1], - self["time_step"], - ) + result = "%d frames selected (first=%.3f ; last = %.3f ; time step = %.3f)\n" % ( + self["n_frames"], + self["time"][0], + self["time"][-1], + self["time_step"], ) except KeyError: result = "FramesConfigurator could not be configured!" diff --git a/MDANSE/Src/MDANSE/Framework/Configurators/GroupingLevelConfigurator.py b/MDANSE/Src/MDANSE/Framework/Configurators/GroupingLevelConfigurator.py index a9144d5a0d..ddd72cdcc7 100644 --- a/MDANSE/Src/MDANSE/Framework/Configurators/GroupingLevelConfigurator.py +++ b/MDANSE/Src/MDANSE/Framework/Configurators/GroupingLevelConfigurator.py @@ -85,12 +85,10 @@ def configure(self, value): if value == "molecule": for mol_name in chemical_system._clusters.keys(): - for mol_number, cluster in enumerate( - chemical_system._clusters[mol_name] - ): + for mol_number, cluster in enumerate(chemical_system._clusters[mol_name]): indices.append(cluster) elements.append([chemical_system.atom_list[x] for x in cluster]) - names.append(f"{mol_name}_mol{mol_number+1}") + names.append(f"{mol_name}_mol{mol_number + 1}") masses.append([mass_lookup[x] for x in cluster]) elif value == "group": for group_name, group_indices in chemical_system._labels.items(): @@ -101,9 +99,7 @@ def configure(self, value): molecule = set(cluster) if molecule.issubset(residue) or residue.issubset(molecule): indices.append(list(molecule.intersection(residue))) - elements.append( - [chemical_system.atom_list[x] for x in cluster] - ) + elements.append([chemical_system.atom_list[x] for x in cluster]) names.append(f"{group_name}_num{counter}_in_{clustername}") masses.append([mass_lookup[x] for x in cluster]) counter += 1 @@ -118,7 +114,9 @@ def configure(self, value): self["level"] = value self["group_indices"] = list(range(len(names))) if atomSelectionConfig["selection_length"] == 0: - self.error_status = "This option resulted in nothing being selected in the current trajectory" + self.error_status = ( + "This option resulted in nothing being selected in the current trajectory" + ) @staticmethod def find_parent(atom, level): diff --git a/MDANSE/Src/MDANSE/Framework/Configurators/HDFInputFileConfigurator.py b/MDANSE/Src/MDANSE/Framework/Configurators/HDFInputFileConfigurator.py index 7557a7d57a..b6af6c13bb 100644 --- a/MDANSE/Src/MDANSE/Framework/Configurators/HDFInputFileConfigurator.py +++ b/MDANSE/Src/MDANSE/Framework/Configurators/HDFInputFileConfigurator.py @@ -79,9 +79,7 @@ def configure(self, value): except Exception: self._units[v] = "unitless" else: - self.error_status = ( - f"the variable {v} was not found in {value} HDF file" - ) + self.error_status = f"the variable {v} was not found in {value} HDF file" return self.error_status = "OK" diff --git a/MDANSE/Src/MDANSE/Framework/Configurators/IConfigurator.py b/MDANSE/Src/MDANSE/Framework/Configurators/IConfigurator.py index 185b060008..528d797142 100644 --- a/MDANSE/Src/MDANSE/Framework/Configurators/IConfigurator.py +++ b/MDANSE/Src/MDANSE/Framework/Configurators/IConfigurator.py @@ -288,9 +288,7 @@ def check_dependencies(self, configured=None): if configured is None: names = [str(key) for key in self._configurable._configuration.keys()] configured = [ - name - for name in names - if self._configurable._configuration[name].is_configured() + name for name in names if self._configurable._configuration[name].is_configured() ] for c in list(self._dependencies.values()): diff --git a/MDANSE/Src/MDANSE/Framework/Configurators/InstrumentResolutionConfigurator.py b/MDANSE/Src/MDANSE/Framework/Configurators/InstrumentResolutionConfigurator.py index 1fdf6768d8..69b4941e42 100644 --- a/MDANSE/Src/MDANSE/Framework/Configurators/InstrumentResolutionConfigurator.py +++ b/MDANSE/Src/MDANSE/Framework/Configurators/InstrumentResolutionConfigurator.py @@ -76,16 +76,12 @@ def configure(self, value): self["omega"] = ( 2.0 * np.pi - * np.fft.fftshift( - np.fft.fftfreq(2 * self["n_frames"] - 1, self["time_step"]) - ) + * np.fft.fftshift(np.fft.fftfreq(2 * self["n_frames"] - 1, self["time_step"])) ) self["n_omegas"] = len(self["omega"]) # generate the rfftfreq for the positive frequency only results - self["romega"] = ( - 2.0 * np.pi * np.fft.rfftfreq(2 * self["n_frames"] - 1, self["time_step"]) - ) + self["romega"] = 2.0 * np.pi * np.fft.rfftfreq(2 * self["n_frames"] - 1, self["time_step"]) self["n_romegas"] = len(self["romega"]) kernel, parameters = value @@ -97,9 +93,7 @@ def configure(self, value): resolution.set_kernel(self["omega"], self["time_step"]) self["omega_window"] = resolution.omegaWindow self["time_window"] = resolution.timeWindow.real - self["time_window_positive"] = np.fft.ifftshift(self["time_window"])[ - : len(time) - ] + self["time_window_positive"] = np.fft.ifftshift(self["time_window"])[: len(time)] def preview_output_axis(self): if not self.is_configured(): diff --git a/MDANSE/Src/MDANSE/Framework/Configurators/IntegerConfigurator.py b/MDANSE/Src/MDANSE/Framework/Configurators/IntegerConfigurator.py index e9d18b307f..1bc9799a0e 100644 --- a/MDANSE/Src/MDANSE/Framework/Configurators/IntegerConfigurator.py +++ b/MDANSE/Src/MDANSE/Framework/Configurators/IntegerConfigurator.py @@ -27,9 +27,7 @@ class IntegerConfigurator(IConfigurator): _default = 0 - def __init__( - self, name, mini=None, maxi=None, choices=None, exclude=None, **kwargs - ): + def __init__(self, name, mini=None, maxi=None, choices=None, exclude=None, **kwargs): """ Initializes the configurator. @@ -87,7 +85,9 @@ def configure(self, value): if self._exclude: if value in self._exclude: - self.error_status = f"the input value is forbidden; forbidden values are {self._exclude}" + self.error_status = ( + f"the input value is forbidden; forbidden values are {self._exclude}" + ) return self["value"] = value diff --git a/MDANSE/Src/MDANSE/Framework/Configurators/InterpolationOrderConfigurator.py b/MDANSE/Src/MDANSE/Framework/Configurators/InterpolationOrderConfigurator.py index f42ed27e48..3ba8d0f00d 100644 --- a/MDANSE/Src/MDANSE/Framework/Configurators/InterpolationOrderConfigurator.py +++ b/MDANSE/Src/MDANSE/Framework/Configurators/InterpolationOrderConfigurator.py @@ -69,17 +69,13 @@ def configure(self, value): self["variable"] = "velocities" elif value > 5: - self.error_status = ( - "Use an interpolation order greater than 5 is not implemented." - ) + self.error_status = "Use an interpolation order greater than 5 is not implemented." return else: number = frames_configurator["number"] if number < value + 1: - self.error_status = ( - f"Not enough MD frames to apply derivatives of order {value}" - ) + self.error_status = f"Not enough MD frames to apply derivatives of order {value}" return self["variable"] = "coordinates" diff --git a/MDANSE/Src/MDANSE/Framework/Configurators/MDAnalysisCoordinateFileConfigurator.py b/MDANSE/Src/MDANSE/Framework/Configurators/MDAnalysisCoordinateFileConfigurator.py index ce9d17c174..6b4f907283 100644 --- a/MDANSE/Src/MDANSE/Framework/Configurators/MDAnalysisCoordinateFileConfigurator.py +++ b/MDANSE/Src/MDANSE/Framework/Configurators/MDAnalysisCoordinateFileConfigurator.py @@ -22,7 +22,6 @@ class MDAnalysisCoordinateFileConfigurator(MultiInputFileConfigurator): - _default = ("", "AUTO") def __init__(self, name, wildcard="All files (*)", **kwargs): diff --git a/MDANSE/Src/MDANSE/Framework/Configurators/MDAnalysisTimeStepConfigurator.py b/MDANSE/Src/MDANSE/Framework/Configurators/MDAnalysisTimeStepConfigurator.py index eab8d125a1..2a1a6e335d 100644 --- a/MDANSE/Src/MDANSE/Framework/Configurators/MDAnalysisTimeStepConfigurator.py +++ b/MDANSE/Src/MDANSE/Framework/Configurators/MDAnalysisTimeStepConfigurator.py @@ -19,7 +19,6 @@ class MDAnalysisTimeStepConfigurator(FloatConfigurator): - _default = 0.0 def configure(self, value): @@ -33,9 +32,7 @@ def configure(self, value): if value is None or value == "" or value == 0.0: file_configurator = self._configurable[self._dependencies["topology_file"]] - files_configurator = self._configurable[ - self._dependencies["coordinate_files"] - ] + files_configurator = self._configurable[self._dependencies["coordinate_files"]] if file_configurator._valid and files_configurator._valid: try: coord_format = files_configurator["format"] @@ -55,9 +52,7 @@ def configure(self, value): topology_format=file_configurator["format"], ).trajectory.ts.dt except Exception as e: - self.error_status = ( - f"Unable to determine a time step from MDAnalysis: {e}" - ) + self.error_status = f"Unable to determine a time step from MDAnalysis: {e}" return else: self.error_status = "Unable to determine a time step from MDAnalysis" diff --git a/MDANSE/Src/MDANSE/Framework/Configurators/MDAnalysisTopologyFileConfigurator.py b/MDANSE/Src/MDANSE/Framework/Configurators/MDAnalysisTopologyFileConfigurator.py index 50b0c4e9ab..2446bcf377 100644 --- a/MDANSE/Src/MDANSE/Framework/Configurators/MDAnalysisTopologyFileConfigurator.py +++ b/MDANSE/Src/MDANSE/Framework/Configurators/MDAnalysisTopologyFileConfigurator.py @@ -22,7 +22,6 @@ class MDAnalysisTopologyFileConfigurator(FileWithAtomDataConfigurator): - _default = ("", "AUTO") def configure(self, setting: str) -> None: @@ -49,9 +48,7 @@ def parse(self) -> None: # which will give us more control over what is guessed. We may # want to change the MDAnalysis guessing options in the future # so that it works better with the MDANSE atom mapping. - self.atoms = mda.Universe( - self["filename"], topology_format=self["format"] - ).atoms + self.atoms = mda.Universe(self["filename"], topology_format=self["format"]).atoms def atom_labels(self) -> Iterable[AtomLabel]: """ diff --git a/MDANSE/Src/MDANSE/Framework/Configurators/MDFileConfigurator.py b/MDANSE/Src/MDANSE/Framework/Configurators/MDFileConfigurator.py index 8e29acb50a..7279a6a8ea 100644 --- a/MDANSE/Src/MDANSE/Framework/Configurators/MDFileConfigurator.py +++ b/MDANSE/Src/MDANSE/Framework/Configurators/MDFileConfigurator.py @@ -81,9 +81,7 @@ def parse(self): self["instance"].readline() # Save the length of the cell data self._frameInfo["cell_data"].append( - self["instance"].tell() - - self._frameInfo["cell_data"][0] - - self._headerSize + self["instance"].tell() - self._frameInfo["cell_data"][0] - self._headerSize ) # If the properties of the positional data have not been stored yet and the line stores this data @@ -103,29 +101,18 @@ def parse(self): # Read the whole ionic data block (positions, velocities, and forces) of the first frame self["instance"].seek(self._headerSize + self._frameInfo["data"][0]) - frame = ( - self["instance"] - .read(self._frameInfo["data"][1]) - .decode("UTF-8") - .splitlines() - ) - self["n_atoms"] = ( - len(frame) // 3 - ) # Save the number of atoms (length of positional data) + frame = self["instance"].read(self._frameInfo["data"][1]).decode("UTF-8").splitlines() + self["n_atoms"] = len(frame) // 3 # Save the number of atoms (length of positional data) # Create a list storing the chemical symbol of the element described on each line of positional data tmp = [f.split()[0] for f in frame[: self["n_atoms"]]] # Save a list of tuples where each tuple consists of the symbol on the amount of those atoms in the simulation - self["atoms"] = [ - (element, len(list(group))) for element, group in itertools.groupby(tmp) - ] + self["atoms"] = [(element, len(list(group))) for element, group in itertools.groupby(tmp)] # Move file handle to the end of the file self["instance"].seek(0, 2) # Save the number of frames - self["n_frames"] = ( - self["instance"].tell() - self._headerSize - ) // self._frameSize + self["n_frames"] = (self["instance"].tell() - self._headerSize) // self._frameSize self["instance"].seek(0) # Move file handle to the beginning of the file def read_step(self, step): @@ -147,9 +134,7 @@ def read_step(self, step): self["instance"].seek(start + self._frameInfo["time_step"][0]) # Read the time stored in the line and convert its units - timeStep = float( - self["instance"].read(self._frameInfo["time_step"][1]).decode("UTF-8") - ) + timeStep = float(self["instance"].read(self._frameInfo["time_step"][1]).decode("UTF-8")) timeStep *= HBAR / HARTREE # Read and process the cell data @@ -157,15 +142,10 @@ def read_step(self, step): start + self._frameInfo["cell_data"][0] ) # Move to the start of cell data unitCell = ( - self["instance"] - .read(self._frameInfo["cell_data"][1]) - .decode("UTF-8") - .splitlines() + self["instance"].read(self._frameInfo["cell_data"][1]).decode("UTF-8").splitlines() ) # Read the cell data by line # Generate an array of three vectors where each vector is constructed from its components stored in each line - unitCell = np.array( - [[float(bb) for bb in b.strip().split()[:3]] for b in unitCell] - ) + unitCell = np.array([[float(bb) for bb in b.strip().split()[:3]] for b in unitCell]) unitCell *= BOHR unitCell = UnitCell(unitCell) diff --git a/MDANSE/Src/MDANSE/Framework/Configurators/MDMCTrajectoryConfigurator.py b/MDANSE/Src/MDANSE/Framework/Configurators/MDMCTrajectoryConfigurator.py index a0c503be1d..4a73a1b4d3 100644 --- a/MDANSE/Src/MDANSE/Framework/Configurators/MDMCTrajectoryConfigurator.py +++ b/MDANSE/Src/MDANSE/Framework/Configurators/MDMCTrajectoryConfigurator.py @@ -74,8 +74,7 @@ def get_information(self): info = ["MDMC trajectory used as input"] info.append("Number of steps: %d\n" % self["length"]) info.append( - "Size of the chemical system: %d\n" - % self["instance"].chemical_system.number_of_atoms + "Size of the chemical system: %d\n" % self["instance"].chemical_system.number_of_atoms ) if self["has_velocities"]: info.append("The trajectory contains atomic velocities\n") diff --git a/MDANSE/Src/MDANSE/Framework/Configurators/MDTrajTimeStepConfigurator.py b/MDANSE/Src/MDANSE/Framework/Configurators/MDTrajTimeStepConfigurator.py index dea06a4d9b..84b5a7ec03 100644 --- a/MDANSE/Src/MDANSE/Framework/Configurators/MDTrajTimeStepConfigurator.py +++ b/MDANSE/Src/MDANSE/Framework/Configurators/MDTrajTimeStepConfigurator.py @@ -19,7 +19,6 @@ class MDTrajTimeStepConfigurator(FloatConfigurator): - _default = 0.0 def configure(self, value): @@ -47,9 +46,7 @@ def configure(self, value): else: value = float(traj.timestep) except Exception as e: - self.error_status = ( - f"Unable to determine a time step from MDTraj: {e}" - ) + self.error_status = f"Unable to determine a time step from MDTraj: {e}" return else: self.error_status = "Unable to determine a time step from MDTraj" diff --git a/MDANSE/Src/MDANSE/Framework/Configurators/MDTrajTopologyFileConfigurator.py b/MDANSE/Src/MDANSE/Framework/Configurators/MDTrajTopologyFileConfigurator.py index ee3e6fe221..7f350b972c 100644 --- a/MDANSE/Src/MDANSE/Framework/Configurators/MDTrajTopologyFileConfigurator.py +++ b/MDANSE/Src/MDANSE/Framework/Configurators/MDTrajTopologyFileConfigurator.py @@ -25,7 +25,6 @@ class MDTrajTopologyFileConfigurator(FileWithAtomDataConfigurator): - def configure(self, value: Optional[str]): """ Parameters @@ -42,9 +41,7 @@ def configure(self, value: Optional[str]): self.error_status = "OK" self["filename"] = value - extension = self._configurable[ - self._dependencies["coordinate_files"] - ].extension + extension = self._configurable[self._dependencies["coordinate_files"]].extension supported = list(i[1:] for i in _TOPOLOGY_EXTS) if extension not in supported: @@ -68,18 +65,16 @@ def configure(self, value: Optional[str]): extension = "".join(Path(value).suffixes)[1:] supported = list(i[1:] for i in _TOPOLOGY_EXTS) if extension not in supported: - self.error_status = f"File '{extension}' not supported. Should be one of the following: {supported}" + self.error_status = ( + f"File '{extension}' not supported. Should be one of the following: {supported}" + ) return super().configure(value) def parse(self) -> None: - coord_files = self._configurable[self._dependencies["coordinate_files"]][ - "filenames" - ] + coord_files = self._configurable[self._dependencies["coordinate_files"]]["filenames"] if self["filename"]: - self.atoms = [ - at for at in md.load(coord_files, top=self["filename"]).topology.atoms - ] + self.atoms = [at for at in md.load(coord_files, top=self["filename"]).topology.atoms] else: self.atoms = [at for at in md.load(coord_files).topology.atoms] diff --git a/MDANSE/Src/MDANSE/Framework/Configurators/MDTrajTrajectoryFileConfigurator.py b/MDANSE/Src/MDANSE/Framework/Configurators/MDTrajTrajectoryFileConfigurator.py index 41df11c7ad..367a429c54 100644 --- a/MDANSE/Src/MDANSE/Framework/Configurators/MDTrajTrajectoryFileConfigurator.py +++ b/MDANSE/Src/MDANSE/Framework/Configurators/MDTrajTrajectoryFileConfigurator.py @@ -21,7 +21,6 @@ class MDTrajTrajectoryFileConfigurator(MultiInputFileConfigurator): - def configure(self, value): super().configure(value) diff --git a/MDANSE/Src/MDANSE/Framework/Configurators/McStasParametersConfigurator.py b/MDANSE/Src/MDANSE/Framework/Configurators/McStasParametersConfigurator.py index 18b556728a..76494977c0 100644 --- a/MDANSE/Src/MDANSE/Framework/Configurators/McStasParametersConfigurator.py +++ b/MDANSE/Src/MDANSE/Framework/Configurators/McStasParametersConfigurator.py @@ -74,9 +74,7 @@ def configure(self, value): exePath = instrConfig["value"] - s = subprocess.Popen( - [exePath, "-h"], stdout=subprocess.PIPE, stderr=subprocess.STDOUT - ) + s = subprocess.Popen([exePath, "-h"], stdout=subprocess.PIPE, stderr=subprocess.STDOUT) parameters_bytes = s.communicate()[0] parameters_string = parameters_bytes.decode(encoding="utf-8") @@ -84,9 +82,7 @@ def configure(self, value): instrParameters = dict( [ (v[0], [v[1], v[2]]) - for v in re.findall( - "\s*(\w+)\s*\((\w+)\)\s*\[default='(\S+)'\]", parameters_string - ) + for v in re.findall("\s*(\w+)\s*\((\w+)\)\s*\[default='(\S+)'\]", parameters_string) if v[0] not in self._exclude ] ) diff --git a/MDANSE/Src/MDANSE/Framework/Configurators/MockTrajectoryConfigurator.py b/MDANSE/Src/MDANSE/Framework/Configurators/MockTrajectoryConfigurator.py index 85da7def71..6f0ca68732 100644 --- a/MDANSE/Src/MDANSE/Framework/Configurators/MockTrajectoryConfigurator.py +++ b/MDANSE/Src/MDANSE/Framework/Configurators/MockTrajectoryConfigurator.py @@ -77,8 +77,7 @@ def get_information(self): info = ["Mock trajectory used as input"] info.append("Number of steps: %d\n" % self["length"]) info.append( - "Size of the chemical system: %d\n" - % self["instance"].chemical_system.number_of_atoms + "Size of the chemical system: %d\n" % self["instance"].chemical_system.number_of_atoms ) if self["has_velocities"]: info.append("The trajectory contains atomic velocities\n") diff --git a/MDANSE/Src/MDANSE/Framework/Configurators/MoleculeSelectionConfigurator.py b/MDANSE/Src/MDANSE/Framework/Configurators/MoleculeSelectionConfigurator.py index 145f0a7840..d877eb62a2 100644 --- a/MDANSE/Src/MDANSE/Framework/Configurators/MoleculeSelectionConfigurator.py +++ b/MDANSE/Src/MDANSE/Framework/Configurators/MoleculeSelectionConfigurator.py @@ -65,15 +65,11 @@ def configure(self, value) -> None: self.error_status = "Input file not selected." return - self._choices = trajectory_configurator[ - "instance" - ].chemical_system.unique_molecules() + self._choices = trajectory_configurator["instance"].chemical_system.unique_molecules() if value in self._choices: self.error_status = "OK" self["value"] = value else: - self.error_status = ( - "The specified molecule name is not present in the trajectory." - ) + self.error_status = "The specified molecule name is not present in the trajectory." self["value"] = self._default diff --git a/MDANSE/Src/MDANSE/Framework/Configurators/MultiInputFileConfigurator.py b/MDANSE/Src/MDANSE/Framework/Configurators/MultiInputFileConfigurator.py index ae1054d47f..9510b49a61 100644 --- a/MDANSE/Src/MDANSE/Framework/Configurators/MultiInputFileConfigurator.py +++ b/MDANSE/Src/MDANSE/Framework/Configurators/MultiInputFileConfigurator.py @@ -22,7 +22,6 @@ class MultiInputFileConfigurator(IConfigurator): - _default = "" def __init__(self, name, wildcard="All files (*)", **kwargs): @@ -54,9 +53,7 @@ def configure(self, setting: Union[str, list]): self.error_status = f"Unable to evaluate string: {e}" return if type(values) is not list: - self.error_status = ( - "Input values should be able to be evaluated as a list" - ) + self.error_status = "Input values should be able to be evaluated as a list" return else: values = [] diff --git a/MDANSE/Src/MDANSE/Framework/Configurators/OutputFilesConfigurator.py b/MDANSE/Src/MDANSE/Framework/Configurators/OutputFilesConfigurator.py index bb0b1c6bfc..fb8e8e98c1 100644 --- a/MDANSE/Src/MDANSE/Framework/Configurators/OutputFilesConfigurator.py +++ b/MDANSE/Src/MDANSE/Framework/Configurators/OutputFilesConfigurator.py @@ -50,9 +50,7 @@ def __init__(self, name, formats=None, **kwargs): IConfigurator.__init__(self, name, **kwargs) - self._formats = ( - formats if formats is not None else OutputFilesConfigurator._default[-1] - ) + self._formats = formats if formats is not None else OutputFilesConfigurator._default[-1] self._forbidden_files = [] def configure(self, value): @@ -85,13 +83,13 @@ def configure(self, value): for fmt in formats: if fmt not in self._formats: - self.error_status = ( - f"the output file format {fmt} is not a valid output format" - ) + self.error_status = f"the output file format {fmt} is not a valid output format" return if fmt not in IFormat.subclasses(): - self.error_status = f"the output file format {fmt} is not registered as a valid file format." + self.error_status = ( + f"the output file format {fmt} is not registered as a valid file format." + ) return self["root"] = root @@ -104,7 +102,9 @@ def configure(self, value): self["files"].append(root + extension) for file in self["files"]: if PurePath(os.path.abspath(file)) in self._forbidden_files: - self.error_status = f"File {file} is either open or being written into. Please pick another name." + self.error_status = ( + f"File {file} is either open or being written into. Please pick another name." + ) return self["value"] = self["files"] diff --git a/MDANSE/Src/MDANSE/Framework/Configurators/PartialChargeConfigurator.py b/MDANSE/Src/MDANSE/Framework/Configurators/PartialChargeConfigurator.py index a85bd46a9e..9c552a7b16 100644 --- a/MDANSE/Src/MDANSE/Framework/Configurators/PartialChargeConfigurator.py +++ b/MDANSE/Src/MDANSE/Framework/Configurators/PartialChargeConfigurator.py @@ -44,9 +44,7 @@ def __init__(self, trajectory: Trajectory) -> None: self._original_map[at_num] = 0.0 self._new_map = {} - def update_charges( - self, selection_dict: dict[str, Union[bool, dict]], charge: float - ) -> None: + def update_charges(self, selection_dict: dict[str, Union[bool, dict]], charge: float) -> None: """With the selection dictionary update the selector and then update the partial charge map. @@ -138,9 +136,7 @@ def configure(self, value): try: int(k) except ValueError: - self.error_status = ( - "Setting not valid - keys should be castable to an int." - ) + self.error_status = "Setting not valid - keys should be castable to an int." return traj_config = self._configurable[self._dependencies["trajectory"]] @@ -148,7 +144,9 @@ def configure(self, value): idxs = system._atom_indices if any([int(i) not in idxs for i in value.keys()]): - self.error_status = "Inputted setting not valid - atom index not found in the current system." + self.error_status = ( + "Inputted setting not valid - atom index not found in the current system." + ) return for idx in idxs: diff --git a/MDANSE/Src/MDANSE/Framework/Configurators/QVectorsConfigurator.py b/MDANSE/Src/MDANSE/Framework/Configurators/QVectorsConfigurator.py index 66a5306570..7610474717 100644 --- a/MDANSE/Src/MDANSE/Framework/Configurators/QVectorsConfigurator.py +++ b/MDANSE/Src/MDANSE/Framework/Configurators/QVectorsConfigurator.py @@ -62,9 +62,7 @@ def configure(self, value): except ValueError: self.error_status = f"Invalid q vectors settings {value}" return - generator = IQVectors.create( - generator, trajConfig["instance"].configuration(0) - ) + generator = IQVectors.create(generator, trajConfig["instance"].configuration(0)) try: generator.setup(parameters) except Exception: @@ -122,8 +120,6 @@ def get_information(self): return "QVectors could not be configured correctly" else: for qValue, qVectors in list(self["q_vectors"].items()): - info.append( - "Shell %s: %d Q vectors generated\n" % (qValue, len(qVectors)) - ) + info.append("Shell %s: %d Q vectors generated\n" % (qValue, len(qVectors))) return "".join(info) diff --git a/MDANSE/Src/MDANSE/Framework/Configurators/RangeConfigurator.py b/MDANSE/Src/MDANSE/Framework/Configurators/RangeConfigurator.py index ceb5f4b8f5..b0d36c9de7 100644 --- a/MDANSE/Src/MDANSE/Framework/Configurators/RangeConfigurator.py +++ b/MDANSE/Src/MDANSE/Framework/Configurators/RangeConfigurator.py @@ -211,7 +211,6 @@ def get_information(self): """ if self._valid: - info = "%d values from %s to %s" % ( self["number"], self["first"], diff --git a/MDANSE/Src/MDANSE/Framework/Configurators/SingleOutputFileConfigurator.py b/MDANSE/Src/MDANSE/Framework/Configurators/SingleOutputFileConfigurator.py index 85cb56fe71..63b1720bc0 100644 --- a/MDANSE/Src/MDANSE/Framework/Configurators/SingleOutputFileConfigurator.py +++ b/MDANSE/Src/MDANSE/Framework/Configurators/SingleOutputFileConfigurator.py @@ -45,9 +45,7 @@ def __init__(self, name, format=None, **kwargs): IConfigurator.__init__(self, name, **kwargs) - self._format = ( - format if format is not None else SingleOutputFileConfigurator._default[-1] - ) + self._format = format if format is not None else SingleOutputFileConfigurator._default[-1] def configure(self, value): """ @@ -78,13 +76,13 @@ def configure(self, value): return if format != self._format: - self.error_status = ( - f"the output file format {format} is not a valid output format" - ) + self.error_status = f"the output file format {format} is not a valid output format" return if format not in IFormat.subclasses(): - self.error_status = f"the output file format {format} is not registered as a valid file format." + self.error_status = ( + f"the output file format {format} is not registered as a valid file format." + ) return self["root"] = root diff --git a/MDANSE/Src/MDANSE/Framework/Configurators/StringConfigurator.py b/MDANSE/Src/MDANSE/Framework/Configurators/StringConfigurator.py index 31559c5a20..8f9cb8e1f8 100644 --- a/MDANSE/Src/MDANSE/Framework/Configurators/StringConfigurator.py +++ b/MDANSE/Src/MDANSE/Framework/Configurators/StringConfigurator.py @@ -64,9 +64,7 @@ def configure(self, value): if self._evalType is not None: value = ast.literal_eval(value) if not isinstance(value, self._evalType): - self.error_status = ( - f"the string can not be eval to {self._evalType.__name__} type" - ) + self.error_status = f"the string can not be eval to {self._evalType.__name__} type" return self["value"] = value diff --git a/MDANSE/Src/MDANSE/Framework/Configurators/UnitCellConfigurator.py b/MDANSE/Src/MDANSE/Framework/Configurators/UnitCellConfigurator.py index 6d65cb3571..6bd1df04a6 100644 --- a/MDANSE/Src/MDANSE/Framework/Configurators/UnitCellConfigurator.py +++ b/MDANSE/Src/MDANSE/Framework/Configurators/UnitCellConfigurator.py @@ -71,12 +71,8 @@ def update_trajectory_information(self): ) if not has_valid_cell: - traj_config = self._configurable[self._dependencies["trajectory"]][ - "instance" - ] - self._recommended_cell = ( - 2.0 * np.eye(3) * np.linalg.norm(traj_config.max_span) - ) + traj_config = self._configurable[self._dependencies["trajectory"]]["instance"] + self._recommended_cell = 2.0 * np.eye(3) * np.linalg.norm(traj_config.max_span) LOG.info( "Setting recommended cell to twice the maximum distance found in the trajectory." ) @@ -98,9 +94,7 @@ def configure(self, value): try: input_array = np.array(value[0], dtype=float) except Exception: - self.error_status = ( - "Could not convert the inputs into a floating point array" - ) + self.error_status = "Could not convert the inputs into a floating point array" return else: if input_array.shape != (3, 3): diff --git a/MDANSE/Src/MDANSE/Framework/Configurators/VectorConfigurator.py b/MDANSE/Src/MDANSE/Framework/Configurators/VectorConfigurator.py index 5881a77121..e38ee1cc14 100644 --- a/MDANSE/Src/MDANSE/Framework/Configurators/VectorConfigurator.py +++ b/MDANSE/Src/MDANSE/Framework/Configurators/VectorConfigurator.py @@ -28,9 +28,7 @@ class VectorConfigurator(IConfigurator): _default = [1.0, 0.0, 0.0] - def __init__( - self, name, valueType=int, normalize=False, notNull=False, dimension=3, **kwargs - ): + def __init__(self, name, valueType=int, normalize=False, notNull=False, dimension=3, **kwargs): """ Initializes the configurator. diff --git a/MDANSE/Src/MDANSE/Framework/Configurators/WeightsConfigurator.py b/MDANSE/Src/MDANSE/Framework/Configurators/WeightsConfigurator.py index ffa7853fb7..af04b8aba2 100644 --- a/MDANSE/Src/MDANSE/Framework/Configurators/WeightsConfigurator.py +++ b/MDANSE/Src/MDANSE/Framework/Configurators/WeightsConfigurator.py @@ -43,9 +43,7 @@ def __init__(self, name, **kwargs): self._aliases = {"mass": "atomic_weight"} filtered_choices = self.filter_choices() - SingleChoiceConfigurator.__init__( - self, name, choices=filtered_choices, **kwargs - ) + SingleChoiceConfigurator.__init__(self, name, choices=filtered_choices, **kwargs) def filter_choices(self): full_choices = ATOMS_DATABASE.numeric_properties + list(self._aliases.keys()) @@ -64,12 +62,8 @@ def filter_choices(self): "state", ] limited_choices = [x for x in full_choices if x not in to_discard] - self._optional_grouping["xray_group"] = [ - x for x in limited_choices if "xray" in x - ] - self._optional_grouping["neutron_group"] = [ - x for x in limited_choices if "b_" in x - ] + self._optional_grouping["xray_group"] = [x for x in limited_choices if "xray" in x] + self._optional_grouping["neutron_group"] = [x for x in limited_choices if "b_" in x] self._optional_grouping["atomic_group"] = [ "mass", "nucleon", @@ -86,9 +80,7 @@ def configure(self, value): :type value: one of the numeric properties of MDANSE.Data.ElementsDatabase.ElementsDatabase """ self._original_input = value - self._trajectory = self._configurable[self._dependencies["trajectory"]][ - "instance" - ] + self._trajectory = self._configurable[self._dependencies["trajectory"]]["instance"] if not isinstance(value, str): self.error_status = "Invalid type for weight. Must be a string." @@ -100,9 +92,7 @@ def configure(self, value): value = self._aliases[value] if value not in self._trajectory.properties_in_database: - self.error_status = ( - f"weight {value} is not registered as a valid numeric property." - ) + self.error_status = f"weight {value} is not registered as a valid numeric property." return self["property"] = value diff --git a/MDANSE/Src/MDANSE/Framework/Configurators/XDATCARFileConfigurator.py b/MDANSE/Src/MDANSE/Framework/Configurators/XDATCARFileConfigurator.py index 85d889e3e3..7aca0cdc50 100644 --- a/MDANSE/Src/MDANSE/Framework/Configurators/XDATCARFileConfigurator.py +++ b/MDANSE/Src/MDANSE/Framework/Configurators/XDATCARFileConfigurator.py @@ -66,15 +66,12 @@ def check_trajectory(filename: str): frame_numbers = False if direct_configuration_found > 0: if not frame_numbers: - raise ValueError( - "File contains both 'direct configuration' and empty lines" - ) + raise ValueError("File contains both 'direct configuration' and empty lines") frame_numbers = True return fixed_cell, frame_numbers class XDATCARFileConfigurator(FileWithAtomDataConfigurator): - def parse(self): filename = self["filename"] with open(filename, "r") as source: @@ -107,11 +104,8 @@ def parse(self): self._coordinates = np.empty((self["n_atoms"], 3)) def read_step(self, step): - if step > 0 and not self._has_fixed_cell: - unit_cell, atoms, atom_numbers, system_name = read_modern_header( - self["instance"] - ) + unit_cell, atoms, atom_numbers, system_name = read_modern_header(self["instance"]) else: unit_cell = self._init_cell @@ -126,9 +120,7 @@ def read_step(self, step): self["step_number"] = step_number for atom_number in range(self["n_atoms"]): - self._coordinates[atom_number] = [ - float(x) for x in self["instance"].readline().split() - ] + self._coordinates[atom_number] = [float(x) for x in self["instance"].readline().split()] return self._coordinates diff --git a/MDANSE/Src/MDANSE/Framework/Configurators/XTDFileConfigurator.py b/MDANSE/Src/MDANSE/Framework/Configurators/XTDFileConfigurator.py index eb46ff7ab9..9d909b2c13 100644 --- a/MDANSE/Src/MDANSE/Framework/Configurators/XTDFileConfigurator.py +++ b/MDANSE/Src/MDANSE/Framework/Configurators/XTDFileConfigurator.py @@ -33,7 +33,6 @@ class XTDFileConfigurator(FileWithAtomDataConfigurator): - def __init__(self, name, **kwargs): super().__init__(name, **kwargs) self._atoms = None @@ -141,18 +140,14 @@ def parse(self): atomsMapping[int(v)] for v in node.attrib["Connects"].split(",") ] idx1, idx2 = bondsMapping[idx] - self._bonds.append( - (self._atoms[idx1]["index"], self._atoms[idx2]["index"]) - ) + self._bonds.append((self._atoms[idx1]["index"], self._atoms[idx2]["index"])) self._atoms[idx1]["bonded_to"].add(idx2) self._atoms[idx2]["bonded_to"].add(idx1) def build_chemical_system(self, aliases): self._chemical_system = ChemicalSystem() - coordinates = np.array( - [atom["xyz"] for atom in self._atoms.values()], dtype=np.float64 - ) + coordinates = np.array([atom["xyz"] for atom in self._atoms.values()], dtype=np.float64) element_list = [atom["element"] for atom in self._atoms.values()] name_list = [atom["atom_name"] for atom in self._atoms.values()] unique_labels = set(name_list) @@ -166,15 +161,11 @@ def build_chemical_system(self, aliases): self._chemical_system.find_clusters_from_bonds() if self._pbc: - boxConf = PeriodicBoxConfiguration( - self._chemical_system, coordinates, self._cell - ) + boxConf = PeriodicBoxConfiguration(self._chemical_system, coordinates, self._cell) real_conf = boxConf.to_real_configuration() else: coordinates *= measure(1.0, "ang").toval("nm") - real_conf = RealConfiguration( - self._chemical_system, coordinates, self._cell - ) + real_conf = RealConfiguration(self._chemical_system, coordinates, self._cell) real_conf.fold_coordinates() self._configuration = real_conf diff --git a/MDANSE/Src/MDANSE/Framework/Configurators/XYZFileConfigurator.py b/MDANSE/Src/MDANSE/Framework/Configurators/XYZFileConfigurator.py index 62bc1a5676..dd4c1c12a2 100644 --- a/MDANSE/Src/MDANSE/Framework/Configurators/XYZFileConfigurator.py +++ b/MDANSE/Src/MDANSE/Framework/Configurators/XYZFileConfigurator.py @@ -47,9 +47,7 @@ def parse(self): try: self["n_atoms"] = int(self["instance"].readline().strip()) except ValueError: - raise XYZFileError( - "Could not read the number of atoms in %s file" % filename - ) + raise XYZFileError("Could not read the number of atoms in %s file" % filename) self._nAtomsLineSize = self["instance"].tell() self["instance"].readline() @@ -101,9 +99,7 @@ def fetch_time_step(self, step: int): try: timeStep = float(matches[0]) except ValueError: - raise XYZFileError( - "Could not cast the timestep to a floating point number." - ) + raise XYZFileError("Could not cast the timestep to a floating point number.") else: return timeStep @@ -118,9 +114,7 @@ def read_step(self, step: int): ndarray -- an (N,3) array containing the coordinates of N atoms at the requested simulation step. """ - starting_line = ( - step * (self._frame_lines + self._header_lines) + self._header_lines - ) + starting_line = step * (self._frame_lines + self._header_lines) + self._header_lines lines_to_skip = starting_line - self._lastline if lines_to_skip < 0: self["instance"].seek(0) @@ -131,9 +125,7 @@ def read_step(self, step: int): templines = [] for _ in range(self._frame_lines): - templines.append( - [float(x) for x in self["instance"].readline().split()[1:]] - ) + templines.append([float(x) for x in self["instance"].readline().split()[1:]]) self._lastline += 1 config = np.array(templines, dtype=np.float64) diff --git a/MDANSE/Src/MDANSE/Framework/Converters/ASE.py b/MDANSE/Src/MDANSE/Framework/Converters/ASE.py index b0aa8dd408..929ccaa316 100644 --- a/MDANSE/Src/MDANSE/Framework/Converters/ASE.py +++ b/MDANSE/Src/MDANSE/Framework/Converters/ASE.py @@ -188,22 +188,16 @@ def run_step(self, index): ) except ValueError: self._keep_running = False - LOG.warning( - f"Could not create configuration for frame {index}. Will skip the rest" - ) + LOG.warning(f"Could not create configuration for frame {index}. Will skip the rest") return index, None if self._configuration["fold"]["value"]: real_conf.fold_coordinates() else: try: - real_conf = RealConfiguration( - self._trajectory.chemical_system, coords, **variables - ) + real_conf = RealConfiguration(self._trajectory.chemical_system, coords, **variables) except ValueError: self._keep_running = False - LOG.warning( - f"Could not create configuration for frame {index}. Will skip the rest" - ) + LOG.warning(f"Could not create configuration for frame {index}. Will skip the rest") return index, None # A snapshot is created out of the current configuration. @@ -269,9 +263,7 @@ def parse_first_step(self, mapping): else: first_frame = self._input[0] self._total_number_of_steps = len(self._input) - LOG.debug( - f"Length found using len(self._input)={self._total_number_of_steps}" - ) + LOG.debug(f"Length found using len(self._input)={self._total_number_of_steps}") self._timeaxis = self._timestep * np.arange(self._total_number_of_steps) diff --git a/MDANSE/Src/MDANSE/Framework/Converters/CP2K.py b/MDANSE/Src/MDANSE/Framework/Converters/CP2K.py index b334f7407f..87916db041 100644 --- a/MDANSE/Src/MDANSE/Framework/Converters/CP2K.py +++ b/MDANSE/Src/MDANSE/Framework/Converters/CP2K.py @@ -59,9 +59,7 @@ def __init__(self, filename): try: time_steps.append(float(words[1])) except ValueError: - raise CellFileError( - f"Cannot cast time step {words[1]} to a floating point number" - ) + raise CellFileError(f"Cannot cast time step {words[1]} to a floating point number") try: cell = np.array(words[2:11], dtype=np.float64).reshape((3, 3)) @@ -172,27 +170,19 @@ def initialize(self): if self.configuration["vel_file"]: self._velFile = self.configuration["vel_file"] if abs(self._xyzFile["time_step"] - self._velFile["time_step"]) > 1.0e-09: - raise CP2KConverterError( - "Inconsistent time step between pos and vel files" - ) + raise CP2KConverterError("Inconsistent time step between pos and vel files") if self._xyzFile["n_frames"] != self._velFile["n_frames"]: - raise CP2KConverterError( - "Inconsistent number of frames between pos and vel files" - ) + raise CP2KConverterError("Inconsistent number of frames between pos and vel files") self._cellFile = CellFile(self.configuration["cell_file"]["filename"]) if abs(self._cellFile["time_step"] - self._xyzFile["time_step"]) > 1.0e-09: - LOG.error(f'{self._cellFile["time_step"]}, {self._xyzFile["time_step"]}') - raise CP2KConverterError( - "Inconsistent time step between pos and cell files" - ) + LOG.error(f"{self._cellFile['time_step']}, {self._xyzFile['time_step']}") + raise CP2KConverterError("Inconsistent time step between pos and cell files") if self._cellFile["n_frames"] != self._xyzFile["n_frames"]: - raise CP2KConverterError( - "Inconsistent number of frames between pos and cell files" - ) + raise CP2KConverterError("Inconsistent number of frames between pos and cell files") # The number of steps of the analysis. self.numberOfSteps = self._xyzFile["n_frames"] @@ -231,9 +221,7 @@ def run_step(self, index): # Read the current coordinates in the XYZ file. coords = self._xyzFile.read_step(index) * measure(1.0, iunit="ang").toval("nm") - unitcell = UnitCell( - self._cellFile.read_step(index) * measure(1.0, iunit="ang").toval("nm") - ) + unitcell = UnitCell(self._cellFile.read_step(index) * measure(1.0, iunit="ang").toval("nm")) variables = {} if self.configuration["vel_file"]: diff --git a/MDANSE/Src/MDANSE/Framework/Converters/Converter.py b/MDANSE/Src/MDANSE/Framework/Converters/Converter.py index ba728b2e12..8b7ef51f9a 100644 --- a/MDANSE/Src/MDANSE/Framework/Converters/Converter.py +++ b/MDANSE/Src/MDANSE/Framework/Converters/Converter.py @@ -35,9 +35,7 @@ def run_step(self, index): def write_metadata(self, output_file): string_dt = h5py.special_dtype(vlen=str) meta = output_file.create_group("metadata") - meta.create_dataset( - "task_name", (1,), data=str(self.__class__.__name__), dtype=string_dt - ) + meta.create_dataset("task_name", (1,), data=str(self.__class__.__name__), dtype=string_dt) meta.create_dataset( "MDANSE_version", (1,), diff --git a/MDANSE/Src/MDANSE/Framework/Converters/DCD.py b/MDANSE/Src/MDANSE/Framework/Converters/DCD.py index ce42b8d620..ef86d7c4de 100644 --- a/MDANSE/Src/MDANSE/Framework/Converters/DCD.py +++ b/MDANSE/Src/MDANSE/Framework/Converters/DCD.py @@ -69,9 +69,7 @@ def get_byte_order(filename): break if byteOrder is None: - raise ByteOrderError( - "Invalid byte order. %s is not a valid DCD file" % filename - ) + raise ByteOrderError("Invalid byte order. %s is not a valid DCD file" % filename) return byteOrder @@ -103,9 +101,7 @@ def next_record(self): raise StopIteration reclen = struct.unpack(self.byteOrder + "i", data)[0] data = self.file.read(reclen) - reclen2 = struct.unpack( - self.byteOrder + "i", self.file.read(struct.calcsize("i")) - )[0] + reclen2 = struct.unpack(self.byteOrder + "i", self.file.read(struct.calcsize("i")))[0] if reclen != reclen2: FortranBinaryFileError("Invalid block") @@ -185,9 +181,7 @@ def read_header(self): self["delta"] = temp[9] # The time step is in AKMA time - self["time_step"] = ( - self["nsavc"] * self["delta"] * measure(1.0, "akma_time").toval("ps") - ) + self["time_step"] = self["nsavc"] * self["delta"] * measure(1.0, "akma_time").toval("ps") self["has_pbc_data"] = temp[10] @@ -200,9 +194,7 @@ def read_header(self): self["title"] = [] for i in range(nLines): - temp = struct.unpack( - self.byteOrder + "80c", data[4 + 80 * i : 4 + 80 * (i + 1)] - ) + temp = struct.unpack(self.byteOrder + "80c", data[4 + 80 * i : 4 + 80 * (i + 1)]) self["title"].append(b"".join(temp).strip()) self["title"] = b"\n".join(self["title"]) @@ -352,9 +344,7 @@ def run_step(self, index): unit_cell = get_basis_vectors_from_cell_parameters(unit_cell) unit_cell = UnitCell(unit_cell) - conf = PeriodicRealConfiguration( - self._trajectory._chemical_system, config, unit_cell - ) + conf = PeriodicRealConfiguration(self._trajectory._chemical_system, config, unit_cell) if self.configuration["fold"]["value"]: conf.fold_coordinates() diff --git a/MDANSE/Src/MDANSE/Framework/Converters/DL_POLY.py b/MDANSE/Src/MDANSE/Framework/Converters/DL_POLY.py index ed643e4162..e6c2e37c5e 100644 --- a/MDANSE/Src/MDANSE/Framework/Converters/DL_POLY.py +++ b/MDANSE/Src/MDANSE/Framework/Converters/DL_POLY.py @@ -37,7 +37,6 @@ class DL_POLYConverterError(Error): class HistoryFile(dict): - def __init__(self, filename): super().__init__() self._dist_conversion = measure(1.0, "ang").toval("nm") @@ -70,9 +69,7 @@ def read_step(self, step): if self["imcon"] > 0: cell_nums = [] for _ in range(3): - cell_nums.append( - [float(x) for x in self["instance"].readline().split()] - ) + cell_nums.append([float(x) for x in self["instance"].readline().split()]) cell = np.array(cell_nums, dtype=np.float64) cell = np.reshape(cell, (3, 3)).T cell *= self._dist_conversion @@ -182,9 +179,7 @@ def initialize(self): self._chemical_system = ChemicalSystem() - self._fieldFile.build_chemical_system( - self._chemical_system, self._atomicAliases - ) + self._fieldFile.build_chemical_system(self._chemical_system, self._atomicAliases) self._trajectory = TrajectoryWriter( self.configuration["output_files"]["file"], @@ -219,9 +214,7 @@ def run_step(self, index): unitCell = UnitCell(unitCell) if self._historyFile["imcon"] > 0: - conf = PeriodicRealConfiguration( - self._trajectory.chemical_system, config[0], unitCell - ) + conf = PeriodicRealConfiguration(self._trajectory.chemical_system, config[0], unitCell) else: conf = RealConfiguration(self._trajectory.chemical_system, config[0]) diff --git a/MDANSE/Src/MDANSE/Framework/Converters/Discover.py b/MDANSE/Src/MDANSE/Framework/Converters/Discover.py index 7906087c95..6a951029a3 100644 --- a/MDANSE/Src/MDANSE/Framework/Converters/Discover.py +++ b/MDANSE/Src/MDANSE/Framework/Converters/Discover.py @@ -210,12 +210,7 @@ def read_step(self, index): time = index * self["time_step"] - hisfile.seek( - self._headerSize - + index * self._frameSize - + self._rec1Size - + self._rec14Size - ) + hisfile.seek(self._headerSize + index * self._frameSize + self._rec1Size + self._rec14Size) cell = np.reshape( np.array(struct.unpack(self._recN2, hisfile.read(self._recN2Size))[6:]), diff --git a/MDANSE/Src/MDANSE/Framework/Converters/Forcite.py b/MDANSE/Src/MDANSE/Framework/Converters/Forcite.py index 49296abf17..c2ff8660ac 100644 --- a/MDANSE/Src/MDANSE/Framework/Converters/Forcite.py +++ b/MDANSE/Src/MDANSE/Framework/Converters/Forcite.py @@ -23,9 +23,7 @@ from MDANSE.MolecularDynamics.Trajectory import TrajectoryWriter -FORCE_FACTOR = measure(1.0, "kcal_per_mole/ang", equivalent=True).toval( - "uma nm/ps2 mol" -) +FORCE_FACTOR = measure(1.0, "kcal_per_mole/ang", equivalent=True).toval("uma nm/ps2 mol") class TrjFile(dict): @@ -92,9 +90,7 @@ def parse_header(self): rec = "!%di8x" % self["totmov"] recSize = struct.calcsize(rec) - self["mvofst"] = ( - np.array(struct.unpack(rec, trjfile.read(recSize)), dtype=np.int32) - 1 - ) + self["mvofst"] = np.array(struct.unpack(rec, trjfile.read(recSize)), dtype=np.int32) - 1 # Record 4a rec = "!i" @@ -173,25 +169,17 @@ def parse_header(self): if self["velocities_written"]: if self["gradients_written"]: # Frame record 8,9,10,11,12,13,14,15,16 - self._configRec = "!" + ("%d%s8x" * 9) % ( - (self["totmov"], self._fp) * 9 - ) + self._configRec = "!" + ("%d%s8x" * 9) % ((self["totmov"], self._fp) * 9) else: # Frame record 8,9,10,11,12,13 - self._configRec = "!" + ("%d%s8x" * 6) % ( - (self["totmov"], self._fp) * 6 - ) + self._configRec = "!" + ("%d%s8x" * 6) % ((self["totmov"], self._fp) * 6) else: if self["gradients_written"]: # Frame record 8,9,10,14,15,16 - self._configRec = "!" + ("%d%s8x" * 6) % ( - (self["totmov"], self._fp) * 6 - ) + self._configRec = "!" + ("%d%s8x" * 6) % ((self["totmov"], self._fp) * 6) else: # Frame record 8,9,10 - self._configRec = "!" + ("%d%s8x" * 3) % ( - (self["totmov"], self._fp) * 3 - ) + self._configRec = "!" + ("%d%s8x" * 3) % ((self["totmov"], self._fp) * 3) self._configRecSize = struct.calcsize(self._configRec) trjfile.read(self._configRecSize) @@ -340,9 +328,7 @@ def initialize(self): self._velocities = None if self._trjfile["gradients_written"]: - self._gradients = np.zeros( - (self._chemical_system.number_of_atoms, 3), dtype=np.float64 - ) + self._gradients = np.zeros((self._chemical_system.number_of_atoms, 3), dtype=np.float64) else: self._gradients = None diff --git a/MDANSE/Src/MDANSE/Framework/Converters/Gromacs.py b/MDANSE/Src/MDANSE/Framework/Converters/Gromacs.py index 800b8d7dec..e224aebf33 100644 --- a/MDANSE/Src/MDANSE/Framework/Converters/Gromacs.py +++ b/MDANSE/Src/MDANSE/Framework/Converters/Gromacs.py @@ -79,14 +79,10 @@ def initialize(self): # Create XTC or TRR object depending on which kind of trajectory was loaded if self.configuration["xtc_file"]["filename"][-4:] == ".xtc": - self._xdr_file = XTCTrajectoryFile( - self.configuration["xtc_file"]["filename"], "r" - ) + self._xdr_file = XTCTrajectoryFile(self.configuration["xtc_file"]["filename"], "r") self._xtc = True elif self.configuration["xtc_file"]["filename"][-4:] == ".trr": - self._xdr_file = TRRTrajectoryFile( - self.configuration["xtc_file"]["filename"], "r" - ) + self._xdr_file = TRRTrajectoryFile(self.configuration["xtc_file"]["filename"], "r") self._xtc = False # Extract information about whether velocities and forces are present in the TRR file @@ -104,9 +100,10 @@ def initialize(self): ) # The TRRTrajectoryFile object returns ints for these values, so turn them into bools - self._read_velocities, self._read_forces = bool( - self._read_velocities - ), bool(self._read_forces) + self._read_velocities, self._read_forces = ( + bool(self._read_velocities), + bool(self._read_forces), + ) if self._read_velocities: data_to_be_written.append("velocities") diff --git a/MDANSE/Src/MDANSE/Framework/Converters/ImprovedASE.py b/MDANSE/Src/MDANSE/Framework/Converters/ImprovedASE.py index 2f1d1678b3..d60ab31163 100644 --- a/MDANSE/Src/MDANSE/Framework/Converters/ImprovedASE.py +++ b/MDANSE/Src/MDANSE/Framework/Converters/ImprovedASE.py @@ -168,9 +168,7 @@ def run_step(self, index): coords *= measure(1.0, "ang").toval("nm") if self._fractionalCoordinates: - conf = PeriodicBoxConfiguration( - self._trajectory.chemical_system, coords, unitCell - ) + conf = PeriodicBoxConfiguration(self._trajectory.chemical_system, coords, unitCell) real_conf = conf.to_real_configuration() else: real_conf = PeriodicRealConfiguration( @@ -257,9 +255,7 @@ def parse_optional_config(self): except FileNotFoundError: return except Exception: - for file_format in self.configuration[ - "configuration_file" - ]._allowed_formats: + for file_format in self.configuration["configuration_file"]._allowed_formats: try: self._extra_input = read( self.configuration["configuration_file"]["value"], diff --git a/MDANSE/Src/MDANSE/Framework/Converters/LAMMPS.py b/MDANSE/Src/MDANSE/Framework/Converters/LAMMPS.py index b50addc1dc..375f380170 100644 --- a/MDANSE/Src/MDANSE/Framework/Converters/LAMMPS.py +++ b/MDANSE/Src/MDANSE/Framework/Converters/LAMMPS.py @@ -40,7 +40,6 @@ class LAMMPSTrajectoryFileError(Error): class LAMMPSReader: - def __init__(self, *args, **kwargs): self._units = kwargs.get("lammps_units", "real") self._timestep = kwargs.get("timestep", 1.0) @@ -116,7 +115,6 @@ def set_units(self, lammps_units): class LAMMPScustom(LAMMPSReader): - def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) @@ -135,7 +133,6 @@ def open_file(self, filename: str): self._start = 0 def parse_first_step(self, aliases, config): - self._itemsPosition = collections.OrderedDict() comp = -1 @@ -275,9 +272,7 @@ def run_step(self, index): * measure(1.0, self._time_unit).toval("ps") ) - for _ in range( - self._itemsPosition["TIMESTEP"][1], self._itemsPosition["BOX BOUNDS"][0] - ): + for _ in range(self._itemsPosition["TIMESTEP"][1], self._itemsPosition["BOX BOUNDS"][0]): self._file.readline() unitCell = np.zeros((9), dtype=np.float64) @@ -325,19 +320,13 @@ def run_step(self, index): unitCell *= measure(1.0, self._length_unit).toval("nm") unitCell = UnitCell(unitCell) - for _ in range( - self._itemsPosition["BOX BOUNDS"][1], self._itemsPosition["ATOMS"][0] - ): + for _ in range(self._itemsPosition["BOX BOUNDS"][1], self._itemsPosition["ATOMS"][0]): self._file.readline() - coords = np.empty( - (self._trajectory.chemical_system.number_of_atoms, 3), dtype=np.float64 - ) + coords = np.empty((self._trajectory.chemical_system.number_of_atoms, 3), dtype=np.float64) if self._charge is not None: - charges = np.empty( - self._trajectory.chemical_system.number_of_atoms, dtype=np.float64 - ) + charges = np.empty(self._trajectory.chemical_system.number_of_atoms, dtype=np.float64) for i, _ in enumerate( range(self._itemsPosition["ATOMS"][0], self._itemsPosition["ATOMS"][1]) @@ -356,9 +345,7 @@ def run_step(self, index): charges[idx] = float(temp[self._charge]) if self._fractionalCoordinates: - conf = PeriodicBoxConfiguration( - self._trajectory.chemical_system, coords, unitCell - ) + conf = PeriodicBoxConfiguration(self._trajectory.chemical_system, coords, unitCell) real_conf = conf.to_real_configuration() else: coords *= measure(1.0, self._length_unit).toval("nm") @@ -377,9 +364,7 @@ def run_step(self, index): units={"time": "ps", "unit_cell": "nm", "coordinates": "nm"}, ) if self._charge is not None: - self._trajectory.write_charges( - charges * self._charge_conversion_factor, index - ) + self._trajectory.write_charges(charges * self._charge_conversion_factor, index) self._start += self._last @@ -387,7 +372,6 @@ def run_step(self, index): class LAMMPSxyz(LAMMPSReader): - def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self._full_cell = None @@ -406,7 +390,6 @@ def open_file(self, filename: str): self._file = open(filename, "r") def read_any_step(self): - line = self._file.readline() number_of_atoms = int(line) line = self._file.readline() @@ -416,7 +399,6 @@ def read_any_step(self): atom_types = np.empty(number_of_atoms, dtype=int) for at_num in range(number_of_atoms): - line = self._file.readline() if not line: @@ -433,7 +415,6 @@ def read_any_step(self): return timestep, atom_types, positions def parse_first_step(self, aliases, config): - _, atom_types, positions = self.read_any_step() self._nAtoms = len(atom_types) @@ -502,9 +483,7 @@ def run_step(self, index): time = timestep * self._timestep * measure(1.0, self._time_unit).toval("ps") if self._fractionalCoordinates: - conf = PeriodicBoxConfiguration( - self._trajectory.chemical_system, positions, unitCell - ) + conf = PeriodicBoxConfiguration(self._trajectory.chemical_system, positions, unitCell) real_conf = conf.to_real_configuration() else: positions *= measure(1.0, self._length_unit).toval("nm") @@ -527,7 +506,6 @@ def run_step(self, index): class LAMMPSh5md(LAMMPSReader): - def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self._charges_fixed = None @@ -544,7 +522,6 @@ def open_file(self, filename: str): self._file = h5py.File(filename, "r") def parse_first_step(self, aliases, config): - try: atom_types = self._file["/particles/all/species/value"][0] except KeyError: @@ -557,9 +534,7 @@ def parse_first_step(self, aliases, config): self._fractionalCoordinates = False cell_edges = self._file["/particles/all/box/edges/value"][0] - full_cell = np.array( - [[cell_edges[0], 0, 0], [0, cell_edges[1], 0], [0, 0, cell_edges[2]]] - ) + full_cell = np.array([[cell_edges[0], 0, 0], [0, cell_edges[1], 0], [0, 0, cell_edges[2]]]) try: self._charges_fixed = self._file["/particles/all/charge"][:] except Exception: @@ -609,9 +584,7 @@ def run_step(self, index): time = timestep * self._timestep * measure(1.0, self._time_unit).toval("ps") if self._fractionalCoordinates: - conf = PeriodicBoxConfiguration( - self._trajectory.chemical_system, positions, unitCell - ) + conf = PeriodicBoxConfiguration(self._trajectory.chemical_system, positions, unitCell) real_conf = conf.to_real_configuration() else: positions *= measure(1.0, self._length_unit).toval("nm") @@ -635,9 +608,7 @@ def run_step(self, index): except Exception: pass else: - self._trajectory.write_charges( - charge * self._charge_conversion_factor, index - ) + self._trajectory.write_charges(charge * self._charge_conversion_factor, index) return index, 0 @@ -747,8 +718,7 @@ def initialize(self): ) charges_single_cell = ( - np.array(self._lammpsConfig["charges"]) - * self._reader._charge_conversion_factor + np.array(self._lammpsConfig["charges"]) * self._reader._charge_conversion_factor ) if len(charges_single_cell) < self._chemical_system.number_of_atoms: charges = list(charges_single_cell) * int( diff --git a/MDANSE/Src/MDANSE/Framework/Converters/MDAnalysis.py b/MDANSE/Src/MDANSE/Framework/Converters/MDAnalysis.py index 6a567fc46e..135fd2bc65 100644 --- a/MDANSE/Src/MDANSE/Framework/Converters/MDAnalysis.py +++ b/MDANSE/Src/MDANSE/Framework/Converters/MDAnalysis.py @@ -108,7 +108,7 @@ def initialize(self): *coord_files, continuous=self.configuration["continuous"]["value"], format=coord_format, - topology_format=self.configuration["topology_file"]["format"] + topology_format=self.configuration["topology_file"]["format"], ) else: coord_files = [(i, coord_format) for i in coord_files] @@ -176,7 +176,7 @@ def initialize(self): self.configuration["output_files"]["file"], self._chemical_system, self.numberOfSteps, - **kwargs + **kwargs, ) super().initialize() @@ -209,8 +209,7 @@ def run_step(self, index: int): self._trajectory._chemical_system, self.u.trajectory.ts.positions * measure(1.0, "ang").toval("nm"), UnitCell( - self.u.trajectory.ts.triclinic_dimensions - * measure(1.0, "ang").toval("nm") + self.u.trajectory.ts.triclinic_dimensions * measure(1.0, "ang").toval("nm") ), ) diff --git a/MDANSE/Src/MDANSE/Framework/Converters/MDTraj.py b/MDANSE/Src/MDANSE/Framework/Converters/MDTraj.py index 4d838454a4..680a627919 100644 --- a/MDANSE/Src/MDANSE/Framework/Converters/MDTraj.py +++ b/MDANSE/Src/MDANSE/Framework/Converters/MDTraj.py @@ -103,16 +103,16 @@ def initialize(self): self.traj = md.load( coord_files, top=top_file, - discard_overlapping_frames=self.configuration[ - "discard_overlapping_frames" - ]["value"], + discard_overlapping_frames=self.configuration["discard_overlapping_frames"][ + "value" + ], ) else: self.traj = md.load( coord_files, - discard_overlapping_frames=self.configuration[ - "discard_overlapping_frames" - ]["value"], + discard_overlapping_frames=self.configuration["discard_overlapping_frames"][ + "value" + ], ) self.numberOfSteps = self.traj.n_frames @@ -156,7 +156,7 @@ def initialize(self): self.configuration["output_files"]["file"], self._chemical_system, self.numberOfSteps, - **kwargs + **kwargs, ) super().initialize() diff --git a/MDANSE/Src/MDANSE/Framework/Converters/VASP.py b/MDANSE/Src/MDANSE/Framework/Converters/VASP.py index 8ae0ec257d..fe93ddabd3 100644 --- a/MDANSE/Src/MDANSE/Framework/Converters/VASP.py +++ b/MDANSE/Src/MDANSE/Framework/Converters/VASP.py @@ -101,9 +101,7 @@ def initialize(self): self._chemical_system = ChemicalSystem() element_list = [] - for symbol, number in zip( - self._xdatcarFile["atoms"], self._xdatcarFile["atom_numbers"] - ): + 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) @@ -133,9 +131,7 @@ def run_step(self, index): unitCell = UnitCell(self._xdatcarFile["cell_shape"]) - conf = PeriodicBoxConfiguration( - self._trajectory.chemical_system, coords, unitCell - ) + conf = PeriodicBoxConfiguration(self._trajectory.chemical_system, coords, unitCell) # The coordinates in VASP are in box format. Convert them into real coordinates. real_conf = conf.to_real_configuration() diff --git a/MDANSE/Src/MDANSE/Framework/Formats/TextFormat.py b/MDANSE/Src/MDANSE/Framework/Formats/TextFormat.py index 8a62a82751..2bd9f04581 100644 --- a/MDANSE/Src/MDANSE/Framework/Formats/TextFormat.py +++ b/MDANSE/Src/MDANSE/Framework/Formats/TextFormat.py @@ -136,8 +136,7 @@ def write_data(cls, fileobject, data, allData): else: xValues = allData[xData] fileobject.write( - "# 1st column: %s (%s)\n" - % (allData[xData].varname, allData[xData].units) + "# 1st column: %s (%s)\n" % (allData[xData].varname, allData[xData].units) ) if yData == "index": @@ -146,8 +145,7 @@ def write_data(cls, fileobject, data, allData): else: yValues = allData[yData] fileobject.write( - "# 1st row: %s (%s)\n\n" - % (allData[yData].varname, allData[yData].units) + "# 1st row: %s (%s)\n\n" % (allData[yData].varname, allData[yData].units) ) zData = np.zeros((data.shape[0] + 1, data.shape[1] + 1), dtype=np.float64) @@ -167,8 +165,7 @@ def write_data(cls, fileobject, data, allData): else: xValues = allData[xData] fileobject.write( - "# 1st column: %s (%s)\n" - % (allData[xData].varname, allData[xData].units) + "# 1st column: %s (%s)\n" % (allData[xData].varname, allData[xData].units) ) fileobject.write("# 2nd column: %s (%s)\n\n" % (data.varname, data.units)) diff --git a/MDANSE/Src/MDANSE/Framework/Handlers/ColorizingStreamHandler.py b/MDANSE/Src/MDANSE/Framework/Handlers/ColorizingStreamHandler.py index ab3459ed7a..da75eb86ec 100644 --- a/MDANSE/Src/MDANSE/Framework/Handlers/ColorizingStreamHandler.py +++ b/MDANSE/Src/MDANSE/Framework/Handlers/ColorizingStreamHandler.py @@ -206,9 +206,7 @@ def colorize(self, message, record): if bold: params.append("1") if params: - message = "".join( - (self.csi, ";".join(params), "m", message, self.reset) - ) + message = "".join((self.csi, ";".join(params), "m", message, self.reset)) return message def format(self, record): diff --git a/MDANSE/Src/MDANSE/Framework/InputData/HDFTrajectoryInputData.py b/MDANSE/Src/MDANSE/Framework/InputData/HDFTrajectoryInputData.py index 62cf3fef03..34eaf4966a 100644 --- a/MDANSE/Src/MDANSE/Framework/InputData/HDFTrajectoryInputData.py +++ b/MDANSE/Src/MDANSE/Framework/InputData/HDFTrajectoryInputData.py @@ -63,9 +63,7 @@ def info(self): val.append("Configuration:") val.append("\tIs periodic: {}\n".format("unit_cell" in self._data.file)) try: - val.append( - "First unit cell (nm):\n{}\n".format(self._data.unit_cell(0)._unit_cell) - ) + val.append("First unit cell (nm):\n{}\n".format(self._data.unit_cell(0)._unit_cell)) except Exception: val.append("No unit cell information\n") val.append("Frame times (1st, 2nd, ..., last) in ps:") diff --git a/MDANSE/Src/MDANSE/Framework/InstrumentResolutions/PseudoVoigt.py b/MDANSE/Src/MDANSE/Framework/InstrumentResolutions/PseudoVoigt.py index 6c2b99800b..2ac5b261ef 100644 --- a/MDANSE/Src/MDANSE/Framework/InstrumentResolutions/PseudoVoigt.py +++ b/MDANSE/Src/MDANSE/Framework/InstrumentResolutions/PseudoVoigt.py @@ -41,9 +41,7 @@ def set_kernel(self, omegas, dt): muG = self._configuration["mu_gaussian"]["value"] sigmaG = self._configuration["sigma_gaussian"]["value"] - gaussian = (np.sqrt(2.0 * np.pi) / sigmaG) * np.exp( - -0.5 * ((omegas - muG) / sigmaG) ** 2 - ) + gaussian = (np.sqrt(2.0 * np.pi) / sigmaG) * np.exp(-0.5 * ((omegas - muG) / sigmaG) ** 2) lorentzian = (2.0 * sigmaL) / ((omegas - muL) ** 2 + sigmaL**2) diff --git a/MDANSE/Src/MDANSE/Framework/InstrumentResolutions/Square.py b/MDANSE/Src/MDANSE/Framework/InstrumentResolutions/Square.py index 3d617ead9d..0821b37af2 100644 --- a/MDANSE/Src/MDANSE/Framework/InstrumentResolutions/Square.py +++ b/MDANSE/Src/MDANSE/Framework/InstrumentResolutions/Square.py @@ -36,9 +36,7 @@ def set_kernel(self, omegas, dt): sigma = self._configuration["sigma"]["value"] self._omegaWindow = ( - 2.0 - * np.pi - * np.where((np.abs(omegas - mu) - sigma) > 0, 0.0, 1.0 / (2.0 * sigma)) + 2.0 * np.pi * np.where((np.abs(omegas - mu) - sigma) > 0, 0.0, 1.0 / (2.0 * sigma)) ) self._timeWindow = self.apply_fft(self._omegaWindow, dt) diff --git a/MDANSE/Src/MDANSE/Framework/InstrumentResolutions/__init__.py b/MDANSE/Src/MDANSE/Framework/InstrumentResolutions/__init__.py index 0003dbb3b2..ab2e542733 100644 --- a/MDANSE/Src/MDANSE/Framework/InstrumentResolutions/__init__.py +++ b/MDANSE/Src/MDANSE/Framework/InstrumentResolutions/__init__.py @@ -31,9 +31,7 @@ if name in ["__init__"]: continue try: - tempmod = importlib.import_module( - "." + name, "MDANSE.Framework.InstrumentResolutions" - ) + tempmod = importlib.import_module("." + name, "MDANSE.Framework.InstrumentResolutions") except ModuleNotFoundError: continue tempobject = getattr(tempmod, name) diff --git a/MDANSE/Src/MDANSE/Framework/Jobs/AngularCorrelation.py b/MDANSE/Src/MDANSE/Framework/Jobs/AngularCorrelation.py index 3ca179ecc1..b21c25c55b 100644 --- a/MDANSE/Src/MDANSE/Framework/Jobs/AngularCorrelation.py +++ b/MDANSE/Src/MDANSE/Framework/Jobs/AngularCorrelation.py @@ -85,9 +85,9 @@ def initialize(self): """ super().initialize() - self.molecules = self.configuration["trajectory"][ - "instance" - ].chemical_system._clusters[self.configuration["molecule_name"]["value"]] + self.molecules = self.configuration["trajectory"]["instance"].chemical_system._clusters[ + self.configuration["molecule_name"]["value"] + ] self.numberOfSteps = len(self.molecules) @@ -108,9 +108,7 @@ def initialize(self): "axis_index", "LineOutputVariable", np.arange( - self.configuration["trajectory"][ - "instance" - ].chemical_system.number_of_molecules( + self.configuration["trajectory"]["instance"].chemical_system.number_of_molecules( self.configuration["molecule_name"]["value"] ) ), @@ -168,9 +166,7 @@ def run_step(self, index): self.configuration["frames"]["step"], ) ): - configuration = self.configuration["trajectory"]["instance"].configuration( - frame_index - ) + configuration = self.configuration["trajectory"]["instance"].configuration(frame_index) coordinates = configuration.contiguous_configuration().coordinates centre_coordinates = center_of_mass(coordinates[molecule], masses) at1_traj[i] = centre_coordinates @@ -206,9 +202,7 @@ def finalize(self): self._outputData["ac"] /= self.configuration["trajectory"][ "instance" - ].chemical_system.number_of_molecules( - self.configuration["molecule_name"]["value"] - ) + ].chemical_system.number_of_molecules(self.configuration["molecule_name"]["value"]) self._outputData.write( self.configuration["output_files"]["root"], diff --git a/MDANSE/Src/MDANSE/Framework/Jobs/AreaPerMolecule.py b/MDANSE/Src/MDANSE/Framework/Jobs/AreaPerMolecule.py index 0a0c85c002..68e4c931d6 100644 --- a/MDANSE/Src/MDANSE/Framework/Jobs/AreaPerMolecule.py +++ b/MDANSE/Src/MDANSE/Framework/Jobs/AreaPerMolecule.py @@ -98,8 +98,7 @@ def initialize(self): ) if self._nMolecules == 0: raise AreaPerMoleculeError( - "No molecule matches %r name." - % self.configuration["molecule_name"]["value"] + "No molecule matches %r name." % self.configuration["molecule_name"]["value"] ) self._outputData.add( @@ -132,15 +131,11 @@ def run_step(self, index): # Get the frame index frame_index = self.configuration["frames"]["value"][index] - configuration = self.configuration["trajectory"]["instance"].configuration( - frame_index - ) + configuration = self.configuration["trajectory"]["instance"].configuration(frame_index) try: unit_cell = configuration.unit_cell._unit_cell - normalVect = np.cross( - unit_cell[self._axisIndexes[0]], unit_cell[self._axisIndexes[1]] - ) + normalVect = np.cross(unit_cell[self._axisIndexes[0]], unit_cell[self._axisIndexes[1]]) except Exception: raise AreaPerMoleculeError( "The unit cell must be defined for AreaPerMolecule. " diff --git a/MDANSE/Src/MDANSE/Framework/Jobs/AverageStructure.py b/MDANSE/Src/MDANSE/Framework/Jobs/AverageStructure.py index 5bf43c6479..c4d1f82995 100644 --- a/MDANSE/Src/MDANSE/Framework/Jobs/AverageStructure.py +++ b/MDANSE/Src/MDANSE/Framework/Jobs/AverageStructure.py @@ -85,9 +85,7 @@ def initialize(self): self.numberOfSteps = self.configuration["atom_selection"]["selection_length"] - self._atoms = self.configuration["trajectory"][ - "instance" - ].chemical_system.atom_list + self._atoms = self.configuration["trajectory"]["instance"].chemical_system.atom_list target_unit = self.configuration["output_units"]["value"] if target_unit == "Angstrom": @@ -106,9 +104,7 @@ def initialize(self): ) try: - unit_cells = [ - trajectory.unit_cell(frame)._unit_cell for frame in frame_range - ] + unit_cells = [trajectory.unit_cell(frame)._unit_cell for frame in frame_range] except Exception: raise ValueError( "Unit cell needs to be defined for the AverageStructure analysis. " @@ -131,9 +127,7 @@ def run_step(self, index): # get selected atom indices sublist indices = self.configuration["atom_selection"]["indices"][index] if len(indices) == 1: - series = self.configuration["trajectory"][ - "instance" - ].read_atomic_trajectory( + series = self.configuration["trajectory"]["instance"].read_atomic_trajectory( indices[0], first=self.configuration["frames"]["first"], last=self.configuration["frames"]["last"] + 1, @@ -183,9 +177,7 @@ def finalize(self): correction = np.floor(temp) self._ase_atoms.set_scaled_positions(temp - correction) - PLATFORM.create_directory( - os.path.dirname(self.configuration["output_files"]["file"]) - ) + PLATFORM.create_directory(os.path.dirname(self.configuration["output_files"]["file"])) ase_write( self.configuration["output_files"]["file"], self._ase_atoms, diff --git a/MDANSE/Src/MDANSE/Framework/Jobs/CenterOfMassesTrajectory.py b/MDANSE/Src/MDANSE/Framework/Jobs/CenterOfMassesTrajectory.py index 9f0d9b9e76..bd9caf59cc 100644 --- a/MDANSE/Src/MDANSE/Framework/Jobs/CenterOfMassesTrajectory.py +++ b/MDANSE/Src/MDANSE/Framework/Jobs/CenterOfMassesTrajectory.py @@ -128,9 +128,7 @@ def run_step(self, index): conf = self.configuration["trajectory"]["instance"].configuration(frameIndex) conf = conf.contiguous_configuration() - temp_radii = { - cluster_name: [] for cluster_name in chemical_system._clusters.keys() - } + temp_radii = {cluster_name: [] for cluster_name in chemical_system._clusters.keys()} com_coords = np.empty((n_coms, 3), dtype=np.float64) mol_index = 0 @@ -160,9 +158,7 @@ def run_step(self, index): self._output_trajectory.chemical_system, com_coords, conf.unit_cell ) else: - com_conf = RealConfiguration( - self._output_trajectory.chemical_system, com_coords - ) + com_conf = RealConfiguration(self._output_trajectory.chemical_system, com_coords) if self.configuration["fold"]["value"]: com_conf.fold_coordinates() diff --git a/MDANSE/Src/MDANSE/Framework/Jobs/CoordinationNumber.py b/MDANSE/Src/MDANSE/Framework/Jobs/CoordinationNumber.py index 04a5a7f079..b858f9ed78 100644 --- a/MDANSE/Src/MDANSE/Framework/Jobs/CoordinationNumber.py +++ b/MDANSE/Src/MDANSE/Framework/Jobs/CoordinationNumber.py @@ -179,24 +179,12 @@ def finalize(self): invPair = pair[::-1] - self._outputData["cn_intra_%s%s" % pair][:] = ( - self.averageDensity * cBeta * cnIntra - ) - self._outputData["cn_inter_%s%s" % pair][:] = ( - self.averageDensity * cBeta * cnInter - ) - self._outputData["cn_total_%s%s" % pair][:] = ( - self.averageDensity * cBeta * cnTotal - ) - self._outputData["cn_intra_%s%s" % invPair][:] = ( - self.averageDensity * cAlpha * cnIntra - ) - self._outputData["cn_inter_%s%s" % invPair][:] = ( - self.averageDensity * cAlpha * cnInter - ) - self._outputData["cn_total_%s%s" % invPair][:] = ( - self.averageDensity * cAlpha * cnTotal - ) + self._outputData["cn_intra_%s%s" % pair][:] = self.averageDensity * cBeta * cnIntra + self._outputData["cn_inter_%s%s" % pair][:] = self.averageDensity * cBeta * cnInter + self._outputData["cn_total_%s%s" % pair][:] = self.averageDensity * cBeta * cnTotal + self._outputData["cn_intra_%s%s" % invPair][:] = self.averageDensity * cAlpha * cnIntra + self._outputData["cn_inter_%s%s" % invPair][:] = self.averageDensity * cAlpha * cnInter + self._outputData["cn_total_%s%s" % invPair][:] = self.averageDensity * cAlpha * cnTotal self._outputData.write( self.configuration["output_files"]["root"], diff --git a/MDANSE/Src/MDANSE/Framework/Jobs/CroppedTrajectory.py b/MDANSE/Src/MDANSE/Framework/Jobs/CroppedTrajectory.py index 71f9b11b09..81d93b3a09 100644 --- a/MDANSE/Src/MDANSE/Framework/Jobs/CroppedTrajectory.py +++ b/MDANSE/Src/MDANSE/Framework/Jobs/CroppedTrajectory.py @@ -61,11 +61,7 @@ def initialize(self): atoms = self.configuration["trajectory"]["instance"].chemical_system.atom_list # The collection of atoms corresponding to the atoms selected for output. - indices = [ - idx - for idxs in self.configuration["atom_selection"]["indices"] - for idx in idxs - ] + indices = [idx for idxs in self.configuration["atom_selection"]["indices"] for idx in idxs] self._selectedAtoms = [atoms[ind] for ind in indices] self._selected_indices = indices @@ -79,8 +75,7 @@ def initialize(self): chunking_limit=self.configuration["output_files"]["chunk_size"], compression=self.configuration["output_files"]["compression"], initial_charges=[ - self.configuration["trajectory"]["instance"].charges(0)[ind] - for ind in indices + self.configuration["trajectory"]["instance"].charges(0)[ind] for ind in indices ], ) @@ -104,9 +99,7 @@ def run_step(self, index): time = self.configuration["frames"]["time"][index] - charge = self.configuration["trajectory"]["instance"].charges(index)[ - self._selected_indices - ] + charge = self.configuration["trajectory"]["instance"].charges(index)[self._selected_indices] self._output_trajectory.dump_configuration(cloned_conf, time) diff --git a/MDANSE/Src/MDANSE/Framework/Jobs/CurrentCorrelationFunction.py b/MDANSE/Src/MDANSE/Framework/Jobs/CurrentCorrelationFunction.py index 87aca2d6bd..b9f7894e6a 100644 --- a/MDANSE/Src/MDANSE/Framework/Jobs/CurrentCorrelationFunction.py +++ b/MDANSE/Src/MDANSE/Framework/Jobs/CurrentCorrelationFunction.py @@ -164,9 +164,7 @@ def initialize(self): self._nFrames = self.configuration["frames"]["n_frames"] self._elements = self.configuration["atom_selection"]["unique_names"] - self._elementsPairs = sorted( - itertools.combinations_with_replacement(self._elements, 2) - ) + self._elementsPairs = sorted(itertools.combinations_with_replacement(self._elements, 2)) self._indicesPerElement = self.configuration["atom_selection"].get_indices() @@ -315,9 +313,7 @@ def run_step(self, index: int): dt=self.configuration["frames"]["time_step"], ) - curr = np.einsum( - "ik,ij->ikj", veloc, np.exp(1j * np.dot(coords, qVectors)) - ) + curr = np.einsum("ik,ij->ikj", veloc, np.exp(1j * np.dot(coords, qVectors))) long = np.einsum( "lj,kj,ikj->ilj", qVectors, @@ -355,13 +351,13 @@ def combine(self, index: int, x: Optional[tuple[np.ndarray, np.ndarray]]): rho_l, rho_t = x n_configs = self.configuration["frames"]["n_configs"] for at1, at2 in self._elementsPairs: - corr_l = correlate(rho_l[at1], rho_l[at2][:n_configs], mode="valid")[ - :, 0, 0 - ] / (3 * n_configs * rho_l[at1].shape[2]) + corr_l = correlate(rho_l[at1], rho_l[at2][:n_configs], mode="valid")[:, 0, 0] / ( + 3 * n_configs * rho_l[at1].shape[2] + ) self._outputData["j(q,t)_long_%s%s" % (at1, at2)][index, :] += corr_l.real - corr_t = correlate(rho_t[at1], rho_t[at2][:n_configs], mode="valid")[ - :, 0, 0 - ] / (3 * n_configs * rho_t[at1].shape[2]) + corr_t = correlate(rho_t[at1], rho_t[at2][:n_configs], mode="valid")[:, 0, 0] / ( + 3 * n_configs * rho_t[at1].shape[2] + ) self._outputData["j(q,t)_trans_%s%s" % (at1, at2)][index, :] += corr_t.real def finalize(self): diff --git a/MDANSE/Src/MDANSE/Framework/Jobs/Density.py b/MDANSE/Src/MDANSE/Framework/Jobs/Density.py index e092d911d9..d00a385554 100644 --- a/MDANSE/Src/MDANSE/Framework/Jobs/Density.py +++ b/MDANSE/Src/MDANSE/Framework/Jobs/Density.py @@ -61,13 +61,9 @@ def initialize(self): self._n_frames = self.numberOfSteps - self._n_atoms = self.configuration["trajectory"][ - "instance" - ].chemical_system.number_of_atoms + self._n_atoms = self.configuration["trajectory"]["instance"].chemical_system.number_of_atoms - self._symbols = self.configuration["trajectory"][ - "instance" - ].chemical_system.atom_list + self._symbols = self.configuration["trajectory"]["instance"].chemical_system.atom_list # Will store the time. self._outputData.add( @@ -174,9 +170,7 @@ def finalize(self): self._outputData["avg_atomic_density"][:] = ( np.cumsum(self._outputData["atomic_density"]) / norm ) - self._outputData["avg_mass_density"][:] = ( - np.cumsum(self._outputData["mass_density"]) / norm - ) + self._outputData["avg_mass_density"][:] = np.cumsum(self._outputData["mass_density"]) / norm self._outputData.write( self.configuration["output_files"]["root"], diff --git a/MDANSE/Src/MDANSE/Framework/Jobs/DensityOfStates.py b/MDANSE/Src/MDANSE/Framework/Jobs/DensityOfStates.py index 9fc07955c7..ce92b965fc 100644 --- a/MDANSE/Src/MDANSE/Framework/Jobs/DensityOfStates.py +++ b/MDANSE/Src/MDANSE/Framework/Jobs/DensityOfStates.py @@ -161,9 +161,7 @@ def initialize(self): main_result=True, ) - self._atoms = self.configuration["trajectory"][ - "instance" - ].chemical_system.atom_list + self._atoms = self.configuration["trajectory"]["instance"].chemical_system.atom_list def run_step(self, index): """ @@ -209,9 +207,7 @@ def run_step(self, index): series = self.configuration["projection"]["projector"](series) n_configs = self.configuration["frames"]["n_configs"] - atomicVACF = correlate(series, series[:n_configs], mode="valid") / ( - 3 * n_configs - ) + atomicVACF = correlate(series, series[:n_configs], mode="valid") / (3 * n_configs) return index, atomicVACF.T[0] def combine(self, index, x): diff --git a/MDANSE/Src/MDANSE/Framework/Jobs/DensityProfile.py b/MDANSE/Src/MDANSE/Framework/Jobs/DensityProfile.py index 4c823fb9e4..e7ac5ad9be 100644 --- a/MDANSE/Src/MDANSE/Framework/Jobs/DensityProfile.py +++ b/MDANSE/Src/MDANSE/Framework/Jobs/DensityProfile.py @@ -149,9 +149,7 @@ def run_step(self, index): dp_per_frame = {} for k, v in self._indices_per_element.items(): - h = np.histogram( - box_coords[v, axis_index], bins=self._n_bins, range=[0.0, 1.0] - ) + h = np.histogram(box_coords[v, axis_index], bins=self._n_bins, range=[0.0, 1.0]) dp_per_frame[k] = h[0] return index, (axis_length, dp_per_frame) @@ -187,9 +185,7 @@ def finalize(self): "dp_%s", ) - self._outputData.add( - "dp_total", "LineOutputVariable", dp_total, axis="r", units="au" - ) + self._outputData.add("dp_total", "LineOutputVariable", dp_total, axis="r", units="au") self._extent /= self.numberOfSteps diff --git a/MDANSE/Src/MDANSE/Framework/Jobs/DipoleAutoCorrelationFunction.py b/MDANSE/Src/MDANSE/Framework/Jobs/DipoleAutoCorrelationFunction.py index b48d0e99e5..7dba4c82b7 100644 --- a/MDANSE/Src/MDANSE/Framework/Jobs/DipoleAutoCorrelationFunction.py +++ b/MDANSE/Src/MDANSE/Framework/Jobs/DipoleAutoCorrelationFunction.py @@ -23,7 +23,6 @@ class DipoleAutoCorrelationFunction(IJob): - enabled = True label = "Dipole AutoCorrelation Function" @@ -66,9 +65,7 @@ def initialize(self): """Initialize the input parameters and analysis self variables.""" super().initialize() - self.chemical_system = self.configuration["trajectory"][ - "instance" - ].chemical_system + self.chemical_system = self.configuration["trajectory"]["instance"].chemical_system self.molecules = self.chemical_system._clusters[ self.configuration["molecule_name"]["value"] @@ -107,9 +104,7 @@ def run_step(self, index) -> tuple[int, np.ndarray]: auto-correlation function for a molecule. """ molecule = self.molecules[index] - dipoles = np.zeros( - (self.configuration["frames"]["number"], 3), dtype=np.float64 - ) + dipoles = np.zeros((self.configuration["frames"]["number"], 3), dtype=np.float64) for i, frame_index in enumerate( range( self.configuration["frames"]["first"], @@ -117,9 +112,7 @@ def run_step(self, index) -> tuple[int, np.ndarray]: self.configuration["frames"]["step"], ) ): - configuration = self.configuration["trajectory"]["instance"].configuration( - frame_index - ) + configuration = self.configuration["trajectory"]["instance"].configuration(frame_index) masses = [ self.configuration["trajectory"]["instance"].get_atom_property( self.chemical_system.atom_list[index], "atomic_weight" @@ -136,14 +129,10 @@ def run_step(self, index) -> tuple[int, np.ndarray]: q = self.configuration["atom_charges"]["charges"][idx] except KeyError: q = charges[idx] - dipoles[i] += q * ( - contiguous_configuration["coordinates"][idx, :] - com - ) + dipoles[i] += q * (contiguous_configuration["coordinates"][idx, :] - com) n_configs = self.configuration["frames"]["n_configs"] - mol_dacf = correlate(dipoles, dipoles[:n_configs], mode="valid") / ( - 3 * n_configs - ) + mol_dacf = correlate(dipoles, dipoles[:n_configs], mode="valid") / (3 * n_configs) return index, mol_dacf.T[0] def combine(self, index, x): diff --git a/MDANSE/Src/MDANSE/Framework/Jobs/DistanceHistogram.py b/MDANSE/Src/MDANSE/Framework/Jobs/DistanceHistogram.py index 462be1c99d..66f132a3b6 100644 --- a/MDANSE/Src/MDANSE/Framework/Jobs/DistanceHistogram.py +++ b/MDANSE/Src/MDANSE/Framework/Jobs/DistanceHistogram.py @@ -94,9 +94,7 @@ def initialize(self): self.numberOfSteps = self.configuration["frames"]["number"] self._indices = [ - idx - for idxs in self.configuration["atom_selection"]["indices"] - for idx in idxs + idx for idxs in self.configuration["atom_selection"]["indices"] for idx in idxs ] self._indices = np.array(self._indices, dtype=np.int32) @@ -215,9 +213,7 @@ def combine(self, index, x): #. x (any): The returned result(s) of run_step """ - nAtoms = self.configuration["trajectory"][ - "instance" - ].chemical_system.number_of_atoms + nAtoms = self.configuration["trajectory"]["instance"].chemical_system.number_of_atoms self.averageDensity += nAtoms / x[0] diff --git a/MDANSE/Src/MDANSE/Framework/Jobs/DynamicCoherentStructureFactor.py b/MDANSE/Src/MDANSE/Framework/Jobs/DynamicCoherentStructureFactor.py index c9287fd041..0e4881a1ec 100644 --- a/MDANSE/Src/MDANSE/Framework/Jobs/DynamicCoherentStructureFactor.py +++ b/MDANSE/Src/MDANSE/Framework/Jobs/DynamicCoherentStructureFactor.py @@ -200,9 +200,7 @@ def run_step(self, index): else: traj = self.configuration["trajectory"]["instance"] - nQVectors = self.configuration["q_vectors"]["value"][shell][ - "q_vectors" - ].shape[1] + nQVectors = self.configuration["q_vectors"]["value"][shell]["q_vectors"].shape[1] rho = {} for element in self.configuration["atom_selection"]["unique_names"]: @@ -238,9 +236,9 @@ def combine(self, index, x): for pair in self._elementsPairs: # F_ab(Q,t) = F_ba(Q,t) this is valid as long as # n_configs is sufficiently large - corr = correlate(x[pair[0]], x[pair[1]][:n_configs], mode="valid").T[ - 0 - ] / (n_configs * x[pair[0]].shape[1]) + corr = correlate(x[pair[0]], x[pair[1]][:n_configs], mode="valid").T[0] / ( + n_configs * x[pair[0]].shape[1] + ) self._outputData["f(q,t)_%s%s" % pair][index, :] += corr.real def finalize(self): diff --git a/MDANSE/Src/MDANSE/Framework/Jobs/DynamicIncoherentStructureFactor.py b/MDANSE/Src/MDANSE/Framework/Jobs/DynamicIncoherentStructureFactor.py index ef6d2ceb7a..fa1fd0a91d 100644 --- a/MDANSE/Src/MDANSE/Framework/Jobs/DynamicIncoherentStructureFactor.py +++ b/MDANSE/Src/MDANSE/Framework/Jobs/DynamicIncoherentStructureFactor.py @@ -111,9 +111,7 @@ def initialize(self): self._instrResolution = self.configuration["instrument_resolution"] - self._atoms = self.configuration["trajectory"][ - "instance" - ].chemical_system.atom_list + self._atoms = self.configuration["trajectory"]["instance"].chemical_system.atom_list self._nOmegas = self._instrResolution["n_omegas"] @@ -199,9 +197,7 @@ def run_step(self, index): indices = self.configuration["atom_selection"]["indices"][index] if len(indices) == 1: - series = self.configuration["trajectory"][ - "instance" - ].read_atomic_trajectory( + series = self.configuration["trajectory"]["instance"].read_atomic_trajectory( indices[0], first=self.configuration["frames"]["first"], last=self.configuration["frames"]["last"] + 1, @@ -227,9 +223,7 @@ def run_step(self, index): qVectors = self.configuration["q_vectors"]["value"][q]["q_vectors"] rho = np.exp(1j * np.dot(series, qVectors)) - res = correlate(rho, rho[:n_configs], mode="valid").T[0] / ( - n_configs * rho.shape[1] - ) + res = correlate(rho, rho[:n_configs], mode="valid").T[0] / (n_configs * rho.shape[1]) disf_per_q_shell[q] += res.real diff --git a/MDANSE/Src/MDANSE/Framework/Jobs/Eccentricity.py b/MDANSE/Src/MDANSE/Framework/Jobs/Eccentricity.py index 39b568f780..cddd77612a 100644 --- a/MDANSE/Src/MDANSE/Framework/Jobs/Eccentricity.py +++ b/MDANSE/Src/MDANSE/Framework/Jobs/Eccentricity.py @@ -75,22 +75,12 @@ def initialize(self): main_result=True, ) - self._atoms = self.configuration["trajectory"][ - "instance" - ].chemical_system.atom_list + self._atoms = self.configuration["trajectory"]["instance"].chemical_system.atom_list self._indices = np.array( - [ - idx - for idxs in self._configuration["atom_selection"]["indices"] - for idx in idxs - ] + [idx for idxs in self._configuration["atom_selection"]["indices"] for idx in idxs] ) self._selectionMasses = np.array( - [ - m - for masses in self._configuration["atom_selection"]["masses"] - for m in masses - ] + [m for masses in self._configuration["atom_selection"]["masses"] for m in masses] ) def run_step(self, index: int): diff --git a/MDANSE/Src/MDANSE/Framework/Jobs/ElasticIncoherentStructureFactor.py b/MDANSE/Src/MDANSE/Framework/Jobs/ElasticIncoherentStructureFactor.py index 49365e622b..9ba3d4eee6 100644 --- a/MDANSE/Src/MDANSE/Framework/Jobs/ElasticIncoherentStructureFactor.py +++ b/MDANSE/Src/MDANSE/Framework/Jobs/ElasticIncoherentStructureFactor.py @@ -134,9 +134,7 @@ def initialize(self): main_result=True, ) - self._atoms = self.configuration["trajectory"][ - "instance" - ].chemical_system.atom_list + self._atoms = self.configuration["trajectory"]["instance"].chemical_system.atom_list def run_step(self, index): """ diff --git a/MDANSE/Src/MDANSE/Framework/Jobs/GaussianDynamicIncoherentStructureFactor.py b/MDANSE/Src/MDANSE/Framework/Jobs/GaussianDynamicIncoherentStructureFactor.py index 5e8ce62d09..203bce1d0e 100644 --- a/MDANSE/Src/MDANSE/Framework/Jobs/GaussianDynamicIncoherentStructureFactor.py +++ b/MDANSE/Src/MDANSE/Framework/Jobs/GaussianDynamicIncoherentStructureFactor.py @@ -183,9 +183,7 @@ def initialize(self): main_result=True, ) - self._atoms = self.configuration["trajectory"][ - "instance" - ].chemical_system.atom_list + self._atoms = self.configuration["trajectory"]["instance"].chemical_system.atom_list def run_step(self, index): """ @@ -212,9 +210,7 @@ def run_step(self, index): atomicSF = np.zeros((self._nQShells, self._nFrames), dtype=np.float64) - msd = mean_square_displacement( - series, self.configuration["frames"]["n_configs"] - ) + msd = mean_square_displacement(series, self.configuration["frames"]["n_configs"]) for i, q2 in enumerate(self._kSquare): gaussian = np.exp(-msd * q2 / 6.0) diff --git a/MDANSE/Src/MDANSE/Framework/Jobs/GeneralAutoCorrelationFunction.py b/MDANSE/Src/MDANSE/Framework/Jobs/GeneralAutoCorrelationFunction.py index 319bd21fcc..0a127ce0d5 100644 --- a/MDANSE/Src/MDANSE/Framework/Jobs/GeneralAutoCorrelationFunction.py +++ b/MDANSE/Src/MDANSE/Framework/Jobs/GeneralAutoCorrelationFunction.py @@ -126,9 +126,7 @@ def run_step(self, index): indices = self.configuration["atom_selection"]["indices"][index] - series = self.configuration["trajectory"][ - "instance" - ].read_configuration_trajectory( + series = self.configuration["trajectory"]["instance"].read_configuration_trajectory( indices[0], first=self.configuration["frames"]["first"], last=self.configuration["frames"]["last"] + 1, diff --git a/MDANSE/Src/MDANSE/Framework/Jobs/GlobalMotionFilteredTrajectory.py b/MDANSE/Src/MDANSE/Framework/Jobs/GlobalMotionFilteredTrajectory.py index 579b3834ed..1e3a7a4c47 100644 --- a/MDANSE/Src/MDANSE/Framework/Jobs/GlobalMotionFilteredTrajectory.py +++ b/MDANSE/Src/MDANSE/Framework/Jobs/GlobalMotionFilteredTrajectory.py @@ -132,17 +132,13 @@ def run_step(self, index): current_configuration = current_configuration.continuous_configuration() variables = copy.deepcopy(current_configuration.variables) coords = variables.pop("coordinates") - current_configuration = RealConfiguration( - trajectory.chemical_system, coords, **variables - ) + current_configuration = RealConfiguration(trajectory.chemical_system, coords, **variables) # Case of the first frame. if frameIndex == self.configuration["frames"]["first"]: # A a linear transformation that shifts the center of mass of the reference atoms to the coordinate origin # and makes its principal axes of inertia parallel to the three coordinate axes is computed. - transfo = self._reference_atoms.normalizing_transformation( - current_configuration - ) + transfo = self._reference_atoms.normalizing_transformation(current_configuration) # The first rms is set to zero by construction. rms = 0.0 diff --git a/MDANSE/Src/MDANSE/Framework/Jobs/IJob.py b/MDANSE/Src/MDANSE/Framework/Jobs/IJob.py index 6427a36985..b2d0f91b69 100644 --- a/MDANSE/Src/MDANSE/Framework/Jobs/IJob.py +++ b/MDANSE/Src/MDANSE/Framework/Jobs/IJob.py @@ -258,7 +258,6 @@ def _run_singlecore(self): LOG.info("Single-core job completed all the steps") def process_tasks_queue(self, tasks, outputs, log_queues): - queue_handlers = [] for log_queue in log_queues: queue_handler = QueueHandler(log_queue) @@ -351,9 +350,7 @@ def _run_multicore_check_terminate(self, listener) -> None: listener : QueueListener The log listener that we need to stop. """ - if not ( - hasattr(self._status, "_queue_0") and hasattr(self._status, "_queue_1") - ): + if not (hasattr(self._status, "_queue_0") and hasattr(self._status, "_queue_1")): return if not self._status._queue_1.empty(): if self._status._queue_1.get() == "terminate": @@ -371,9 +368,7 @@ def _run_multicore_check_terminate(self, listener) -> None: time.sleep(10) def _run_remote(self): - raise NotImplementedError( - "Currently there is no replacement for the old Pyro remote runs." - ) + raise NotImplementedError("Currently there is no replacement for the old Pyro remote runs.") _runner = { "single-core": _run_singlecore, @@ -426,9 +421,7 @@ def info(self): @classmethod def save_template(cls, shortname, classname): if shortname in IJob.subclasses(): - raise KeyError( - "A job with %r name is already stored in the registry" % shortname - ) + raise KeyError("A job with %r name is already stored in the registry" % shortname) templateFile = os.path.join(PLATFORM.macros_directory(), "%s.py" % classname) diff --git a/MDANSE/Src/MDANSE/Framework/Jobs/Infrared.py b/MDANSE/Src/MDANSE/Framework/Jobs/Infrared.py index 81e11d3558..c85aab60fc 100644 --- a/MDANSE/Src/MDANSE/Framework/Jobs/Infrared.py +++ b/MDANSE/Src/MDANSE/Framework/Jobs/Infrared.py @@ -24,7 +24,6 @@ class Infrared(IJob): - enabled = True label = "Infrared Spectrum" @@ -77,9 +76,7 @@ class Infrared(IJob): def initialize(self): super().initialize() - self.chemical_system = self.configuration["trajectory"][ - "instance" - ].chemical_system + self.chemical_system = self.configuration["trajectory"]["instance"].chemical_system self.molecules = self.chemical_system._clusters[ self.configuration["molecule_name"]["value"] @@ -145,9 +142,7 @@ def run_step(self, index: int) -> tuple[int, np.ndarray]: auto-correlation function for a molecule. """ molecule = self.molecules[index] - ddipole = np.zeros( - (self.configuration["frames"]["number"], 3), dtype=np.float64 - ) + ddipole = np.zeros((self.configuration["frames"]["number"], 3), dtype=np.float64) for i, frame_index in enumerate( range( self.configuration["frames"]["first"], @@ -155,9 +150,7 @@ def run_step(self, index: int) -> tuple[int, np.ndarray]: self.configuration["frames"]["step"], ) ): - configuration = self.configuration["trajectory"]["instance"].configuration( - frame_index - ) + configuration = self.configuration["trajectory"]["instance"].configuration(frame_index) masses = [ self.configuration["trajectory"]["instance"].get_atom_property( self.chemical_system.atom_list[index], "atomic_weight" @@ -174,9 +167,7 @@ def run_step(self, index: int) -> tuple[int, np.ndarray]: q = self.configuration["atom_charges"]["charges"][idx] except KeyError: q = charges[idx] - ddipole[i] += q * ( - contiguous_configuration["coordinates"][idx, :] - com - ) + ddipole[i] += q * (contiguous_configuration["coordinates"][idx, :] - com) for axis in range(3): ddipole[:, axis] = differentiate( @@ -186,9 +177,7 @@ def run_step(self, index: int) -> tuple[int, np.ndarray]: ) n_configs = self.configuration["frames"]["n_configs"] - mol_ddacf = correlate(ddipole, ddipole[:n_configs], mode="valid") / ( - 3 * n_configs - ) + mol_ddacf = correlate(ddipole, ddipole[:n_configs], mode="valid") / (3 * n_configs) return index, mol_ddacf.T[0] def combine(self, index: int, x: np.ndarray): diff --git a/MDANSE/Src/MDANSE/Framework/Jobs/McStasVirtualInstrument.py b/MDANSE/Src/MDANSE/Framework/Jobs/McStasVirtualInstrument.py index f5d8a096b4..a5a181e0e4 100644 --- a/MDANSE/Src/MDANSE/Framework/Jobs/McStasVirtualInstrument.py +++ b/MDANSE/Src/MDANSE/Framework/Jobs/McStasVirtualInstrument.py @@ -39,9 +39,11 @@ NAVOGADRO = 6.02214129e23 + def _startswith(key: str, line: str) -> bool: return line.strip().startswith(key) + class McStasError(Error): pass @@ -136,9 +138,7 @@ def initialize(self): self._mcStasPhysicalParameters["V_rho"] = 0.0 self._mcStasPhysicalParameters["weight"] = sum( [ - self.configuration["trajectory"]["instance"].get_atom_property( - s, "atomic_weight" - ) + self.configuration["trajectory"]["instance"].get_atom_property(s, "atomic_weight") for s in symbols ] ) @@ -156,9 +156,7 @@ def initialize(self): self._mcStasPhysicalParameters["sigma_coh"] = ( np.mean( [ - self.configuration["trajectory"]["instance"].get_atom_property( - s, "xs_coherent" - ) + self.configuration["trajectory"]["instance"].get_atom_property(s, "xs_coherent") for s in symbols ] ) @@ -176,29 +174,19 @@ def initialize(self): * MCSTAS_UNITS_LUT["nm2"] ) for frameIndex in self.configuration["frames"]["value"]: - configuration = self.configuration["trajectory"]["instance"].configuration( - frameIndex - ) + configuration = self.configuration["trajectory"]["instance"].configuration(frameIndex) cellVolume = configuration._unit_cell.volume self._mcStasPhysicalParameters["density"] += ( self._mcStasPhysicalParameters["weight"] / cellVolume ) self._mcStasPhysicalParameters["V_rho"] += ( - self.configuration["trajectory"][ - "instance" - ].chemical_system.number_of_atoms + self.configuration["trajectory"]["instance"].chemical_system.number_of_atoms / cellVolume ) - self._mcStasPhysicalParameters["density"] /= self.configuration["frames"][ - "n_frames" - ] - self._mcStasPhysicalParameters["V_rho"] /= self.configuration["frames"][ - "n_frames" - ] + self._mcStasPhysicalParameters["density"] /= self.configuration["frames"]["n_frames"] + self._mcStasPhysicalParameters["V_rho"] /= self.configuration["frames"]["n_frames"] # The density is converty in g/cm3 - self._mcStasPhysicalParameters["density"] /= NAVOGADRO / measure( - 1.0, "cm3" - ).toval("nm3") + self._mcStasPhysicalParameters["density"] /= NAVOGADRO / measure(1.0, "cm3").toval("nm3") self._mcStasPhysicalParameters["V_rho"] *= measure(1.0, "1/nm3").toval("1/ang3") def run_step(self, index): @@ -228,9 +216,7 @@ def run_step(self, index): for k, v in list(self._mcStasPhysicalParameters.items()): fout.write("# %s %s \n" % (k, v)) - fout.write( - "# Temperature %s \n" % self.configuration["temperature"]["value"] - ) + fout.write("# Temperature %s \n" % self.configuration["temperature"]["value"]) fout.write("#\n") for var in self.configuration[typ].variables: @@ -243,9 +229,7 @@ def run_step(self, index): try: data *= MCSTAS_UNITS_LUT[data_unit] except KeyError: - LOG.error( - f"Could not find the physical unit {data_unit} in the lookup table." - ) + LOG.error(f"Could not find the physical unit {data_unit} in the lookup table.") np.savetxt(fout, np.atleast_2d(data), delimiter=" ", newline="\n") @@ -426,12 +410,8 @@ def save_single(self, FileStruct): x = FileStruct["data"][:, 0] y = FileStruct["data"][:, 1] - Title = self.unique( - self.treat_str_var(FileStruct["component"]), self._outputData - ) - xlabel = self.unique( - self.treat_str_var(FileStruct["xlabel"]), self._outputData, x - ) + Title = self.unique(self.treat_str_var(FileStruct["component"]), self._outputData) + xlabel = self.unique(self.treat_str_var(FileStruct["xlabel"]), self._outputData, x) self._outputData[xlabel] = IOutputVariable.create( "LineOutputVariable", x, xlabel, units="au" @@ -456,15 +436,9 @@ def save_single(self, FileStruct): x = np.linspace(Xmin, Xmax, mysize[1]) y = np.linspace(Ymin, Ymax, mysize[0]) - title = self.unique( - self.treat_str_var(FileStruct["component"]), self._outputData - ) - xlabel = self.unique( - self.treat_str_var(FileStruct["xlabel"]), self._outputData, x - ) - ylabel = self.unique( - self.treat_str_var(FileStruct["ylabel"]), self._outputData, y - ) + title = self.unique(self.treat_str_var(FileStruct["component"]), self._outputData) + xlabel = self.unique(self.treat_str_var(FileStruct["xlabel"]), self._outputData, x) + ylabel = self.unique(self.treat_str_var(FileStruct["ylabel"]), self._outputData, y) self._outputData.add(xlabel, "LineOutputVariable", x, units="au") self._outputData.add(ylabel, "LineOutputVariable", y, units="au") diff --git a/MDANSE/Src/MDANSE/Framework/Jobs/MeanSquareDisplacement.py b/MDANSE/Src/MDANSE/Framework/Jobs/MeanSquareDisplacement.py index b59d04729d..81021d90c3 100644 --- a/MDANSE/Src/MDANSE/Framework/Jobs/MeanSquareDisplacement.py +++ b/MDANSE/Src/MDANSE/Framework/Jobs/MeanSquareDisplacement.py @@ -132,9 +132,7 @@ def initialize(self): partial_result=True, ) - self._atoms = self.configuration["trajectory"][ - "instance" - ].chemical_system.atom_list + self._atoms = self.configuration["trajectory"]["instance"].chemical_system.atom_list def run_step(self, index): """ @@ -150,9 +148,7 @@ def run_step(self, index): # get selected atom indices sublist indices = self.configuration["atom_selection"]["indices"][index] if len(indices) == 1: - series = self.configuration["trajectory"][ - "instance" - ].read_atomic_trajectory( + series = self.configuration["trajectory"]["instance"].read_atomic_trajectory( indices[0], first=self.configuration["frames"]["first"], last=self.configuration["frames"]["last"] + 1, @@ -169,9 +165,7 @@ def run_step(self, index): series = self.configuration["projection"]["projector"](series) - msd = mean_square_displacement( - series, self.configuration["frames"]["n_configs"] - ) + msd = mean_square_displacement(series, self.configuration["frames"]["n_configs"]) return index, msd diff --git a/MDANSE/Src/MDANSE/Framework/Jobs/MolecularTrace.py b/MDANSE/Src/MDANSE/Framework/Jobs/MolecularTrace.py index cae1ed2420..db0d0eba15 100644 --- a/MDANSE/Src/MDANSE/Framework/Jobs/MolecularTrace.py +++ b/MDANSE/Src/MDANSE/Framework/Jobs/MolecularTrace.py @@ -77,9 +77,7 @@ def initialize(self): minx, miny, minz = 10**9, 10**9, 10**9 for i in range(self.numberOfSteps): frameIndex = self.configuration["frames"]["value"][i] - conf = self.configuration["trajectory"]["instance"].configuration( - frameIndex - ) + conf = self.configuration["trajectory"]["instance"].configuration(frameIndex) conf = conf.continuous_configuration() coords = conf["coordinates"] @@ -134,9 +132,7 @@ def initialize(self): ) self._indices = [ - idx - for idxs in self.configuration["atom_selection"]["indices"] - for idx in idxs + idx for idxs in self.configuration["atom_selection"]["indices"] for idx in idxs ] def run_step(self, index): @@ -158,8 +154,7 @@ def run_step(self, index): resolution = self.configuration["spatial_resolution"]["value"] indices = np.floor( - (conf["coordinates"][self._indices, :] - self.min.reshape((1, 3))) - / resolution + (conf["coordinates"][self._indices, :] - self.min.reshape((1, 3))) / resolution ).astype(int) unique_indices, counts = np.unique(indices, return_counts=True, axis=0) grid[tuple(unique_indices.T)] += counts diff --git a/MDANSE/Src/MDANSE/Framework/Jobs/NeutronDynamicTotalStructureFactor.py b/MDANSE/Src/MDANSE/Framework/Jobs/NeutronDynamicTotalStructureFactor.py index cb827cde9e..ea6914547b 100644 --- a/MDANSE/Src/MDANSE/Framework/Jobs/NeutronDynamicTotalStructureFactor.py +++ b/MDANSE/Src/MDANSE/Framework/Jobs/NeutronDynamicTotalStructureFactor.py @@ -81,13 +81,9 @@ def initialize(self): # Check time consistency if "time" not in self.configuration["dcsf_input_file"]["instance"]: - raise NeutronDynamicTotalStructureFactorError( - "No time found in dcsf input file" - ) + raise NeutronDynamicTotalStructureFactorError("No time found in dcsf input file") if "time" not in self.configuration["disf_input_file"]["instance"]: - raise NeutronDynamicTotalStructureFactorError( - "No time found in disf input file" - ) + raise NeutronDynamicTotalStructureFactorError("No time found in disf input file") dcsf_time = self.configuration["dcsf_input_file"]["instance"]["time"][:] disf_time = self.configuration["disf_input_file"]["instance"]["time"][:] @@ -101,39 +97,25 @@ def initialize(self): # Check time window consistency if "time_window" not in self.configuration["dcsf_input_file"]["instance"]: - raise NeutronDynamicTotalStructureFactorError( - "No time window found in dcsf input file" - ) + raise NeutronDynamicTotalStructureFactorError("No time window found in dcsf input file") if "time_window" not in self.configuration["disf_input_file"]["instance"]: - raise NeutronDynamicTotalStructureFactorError( - "No time window found in disf input file" - ) + raise NeutronDynamicTotalStructureFactorError("No time window found in disf input file") - dcsf_time_window = self.configuration["dcsf_input_file"]["instance"][ - "time_window" - ][:] - disf_time_window = self.configuration["disf_input_file"]["instance"][ - "time_window" - ][:] + dcsf_time_window = self.configuration["dcsf_input_file"]["instance"]["time_window"][:] + disf_time_window = self.configuration["disf_input_file"]["instance"]["time_window"][:] if not np.all(dcsf_time_window == disf_time_window): raise NeutronDynamicTotalStructureFactorError( "Inconsistent time windows between dcsf and disf input files" ) - self._outputData.add( - "time_window", "LineOutputVariable", dcsf_time_window, units="au" - ) + self._outputData.add("time_window", "LineOutputVariable", dcsf_time_window, units="au") # Check q values consistency if "q" not in self.configuration["dcsf_input_file"]["instance"]: - raise NeutronDynamicTotalStructureFactorError( - "No q values found in dcsf input file" - ) + raise NeutronDynamicTotalStructureFactorError("No q values found in dcsf input file") if "q" not in self.configuration["disf_input_file"]["instance"]: - raise NeutronDynamicTotalStructureFactorError( - "No q values found in disf input file" - ) + raise NeutronDynamicTotalStructureFactorError("No q values found in disf input file") dcsf_q = self.configuration["dcsf_input_file"]["instance"]["q"][:] disf_q = self.configuration["disf_input_file"]["instance"]["q"][:] @@ -147,13 +129,9 @@ def initialize(self): # Check omega consistency if "omega" not in self.configuration["dcsf_input_file"]["instance"]: - raise NeutronDynamicTotalStructureFactorError( - "No omega found in dcsf input file" - ) + raise NeutronDynamicTotalStructureFactorError("No omega found in dcsf input file") if "omega" not in self.configuration["disf_input_file"]["instance"]: - raise NeutronDynamicTotalStructureFactorError( - "No omega found in disf input file" - ) + raise NeutronDynamicTotalStructureFactorError("No omega found in disf input file") dcsf_omegas = self.configuration["dcsf_input_file"]["instance"]["omega"][:] disf_omegas = self.configuration["disf_input_file"]["instance"]["omega"][:] @@ -175,21 +153,15 @@ def initialize(self): "No omega window found in disf input file" ) - dcsf_omega_window = self.configuration["dcsf_input_file"]["instance"][ - "omega_window" - ][:] - disf_omega_window = self.configuration["disf_input_file"]["instance"][ - "omega_window" - ][:] + dcsf_omega_window = self.configuration["dcsf_input_file"]["instance"]["omega_window"][:] + disf_omega_window = self.configuration["disf_input_file"]["instance"]["omega_window"][:] if not np.all(dcsf_omega_window == disf_omega_window): raise NeutronDynamicTotalStructureFactorError( "Inconsistent omega windows between dcsf and disf input files" ) - self._outputData.add( - "omega_window", "LineOutputVariable", dcsf_omegas, units="au" - ) + self._outputData.add("omega_window", "LineOutputVariable", dcsf_omegas, units="au") # Check f(q,t) and s(q,f) for dcsf self._elementsPairs = sorted( @@ -198,44 +170,20 @@ def initialize(self): ) ) for pair in self._elementsPairs: - if ( - "f(q,t)_{}{}".format(*pair) - not in self.configuration["dcsf_input_file"]["instance"] - ): - raise NeutronDynamicTotalStructureFactorError( - "Missing f(q,t) in dcsf input file" - ) - if ( - "s(q,f)_{}{}".format(*pair) - not in self.configuration["dcsf_input_file"]["instance"] - ): - raise NeutronDynamicTotalStructureFactorError( - "Missing s(q,f) in dcsf input file" - ) + if "f(q,t)_{}{}".format(*pair) not in self.configuration["dcsf_input_file"]["instance"]: + raise NeutronDynamicTotalStructureFactorError("Missing f(q,t) in dcsf input file") + if "s(q,f)_{}{}".format(*pair) not in self.configuration["dcsf_input_file"]["instance"]: + raise NeutronDynamicTotalStructureFactorError("Missing s(q,f) in dcsf input file") for element in self.configuration["atom_selection"]["unique_names"]: - if ( - "f(q,t)_{}".format(element) - not in self.configuration["disf_input_file"]["instance"] - ): - raise NeutronDynamicTotalStructureFactorError( - "Missing f(q,t) in disf input file" - ) - if ( - "s(q,f)_{}".format(element) - not in self.configuration["disf_input_file"]["instance"] - ): - raise NeutronDynamicTotalStructureFactorError( - "Missing s(q,f) in disf input file" - ) + if "f(q,t)_{}".format(element) not in self.configuration["disf_input_file"]["instance"]: + raise NeutronDynamicTotalStructureFactorError("Missing f(q,t) in disf input file") + if "s(q,f)_{}".format(element) not in self.configuration["disf_input_file"]["instance"]: + raise NeutronDynamicTotalStructureFactorError("Missing s(q,f) in disf input file") for element in self.configuration["atom_selection"]["unique_names"]: - fqt = self.configuration["disf_input_file"]["instance"][ - "f(q,t)_{}".format(element) - ] - sqf = self.configuration["disf_input_file"]["instance"][ - "s(q,f)_{}".format(element) - ] + fqt = self.configuration["disf_input_file"]["instance"]["f(q,t)_{}".format(element)] + sqf = self.configuration["disf_input_file"]["instance"]["s(q,f)_{}".format(element)] self._outputData.add( "f(q,t)_inc_%s" % element, "SurfaceOutputVariable", @@ -266,12 +214,8 @@ def initialize(self): ) for pair in self._elementsPairs: - fqt = self.configuration["dcsf_input_file"]["instance"][ - "f(q,t)_{}{}".format(*pair) - ] - sqf = self.configuration["dcsf_input_file"]["instance"][ - "s(q,f)_{}{}".format(*pair) - ] + fqt = self.configuration["dcsf_input_file"]["instance"]["f(q,t)_{}{}".format(*pair)] + sqf = self.configuration["dcsf_input_file"]["instance"]["s(q,f)_{}{}".format(*pair)] self._outputData.add( "f(q,t)_coh_%s%s" % pair, "SurfaceOutputVariable", @@ -401,16 +345,10 @@ def finalize(self): cj = nj / nTotalAtoms self._outputData["f(q,t)_coh_weighted_%s%s" % pair][:] = ( - self._outputData["f(q,t)_coh_%s%s" % pair][:] - * np.sqrt(ci * cj) - * bi - * bj + self._outputData["f(q,t)_coh_%s%s" % pair][:] * np.sqrt(ci * cj) * bi * bj ) self._outputData["s(q,f)_coh_weighted_%s%s" % pair][:] = ( - self._outputData["s(q,f)_coh_%s%s" % pair][:] - * np.sqrt(ci * cj) - * bi - * bj + self._outputData["s(q,f)_coh_%s%s" % pair][:] * np.sqrt(ci * cj) * bi * bj ) if pair[0] == pair[1]: # Add a factor 2 if the two elements are different self._outputData["f(q,t)_coh_total"][:] += self._outputData[ @@ -451,12 +389,10 @@ def finalize(self): # Compute total F(Q,t) = inc + coh self._outputData["f(q,t)_total"][:] = ( - self._outputData["f(q,t)_coh_total"][:] - + self._outputData["f(q,t)_inc_total"][:] + self._outputData["f(q,t)_coh_total"][:] + self._outputData["f(q,t)_inc_total"][:] ) self._outputData["s(q,f)_total"][:] = ( - self._outputData["s(q,f)_coh_total"][:] - + self._outputData["s(q,f)_inc_total"][:] + self._outputData["s(q,f)_coh_total"][:] + self._outputData["s(q,f)_inc_total"][:] ) self._outputData.write( diff --git a/MDANSE/Src/MDANSE/Framework/Jobs/OrderParameter.py b/MDANSE/Src/MDANSE/Framework/Jobs/OrderParameter.py index 80222fc001..0e3058a3a0 100644 --- a/MDANSE/Src/MDANSE/Framework/Jobs/OrderParameter.py +++ b/MDANSE/Src/MDANSE/Framework/Jobs/OrderParameter.py @@ -158,9 +158,7 @@ def initialize(self): units="au", main_result=True, ) - self._outputData.add( - "s2", "LineOutputVariable", (self._nAxis,), axis="time", units="au" - ) + self._outputData.add("s2", "LineOutputVariable", (self._nAxis,), axis="time", units="au") if self.configuration["per_axis"]["value"]: self._outputData.add( @@ -246,10 +244,8 @@ def run_step(self, index): # s2 calculation (s2 = lim (t->+inf) p2) s2 = ( - 0.75 - * (np.sum(cos2phi * sintheta_sq) ** 2 + np.sum(sin2phi * sintheta_sq) ** 2) - + 3.00 - * (np.sum(cosphi * cossintheta) ** 2 + np.sum(sinphi * cossintheta) ** 2) + 0.75 * (np.sum(cos2phi * sintheta_sq) ** 2 + np.sum(sin2phi * sintheta_sq) ** 2) + + 3.00 * (np.sum(cosphi * cossintheta) ** 2 + np.sum(sinphi * cossintheta) ** 2) + 0.25 * np.sum(tr2) ** 2 ) / self._nFrames**2 diff --git a/MDANSE/Src/MDANSE/Framework/Jobs/PairDistributionFunction.py b/MDANSE/Src/MDANSE/Framework/Jobs/PairDistributionFunction.py index 5a78dfeba7..95765a6b5c 100644 --- a/MDANSE/Src/MDANSE/Framework/Jobs/PairDistributionFunction.py +++ b/MDANSE/Src/MDANSE/Framework/Jobs/PairDistributionFunction.py @@ -135,17 +135,13 @@ def finalize(self): pdf_inter = self.hInter[idi, idj, :] / fact pdf_total = pdf_intra + pdf_inter - for i, pdf in zip( - ["intra", "inter", "total"], [pdf_intra, pdf_inter, pdf_total] - ): + for i, pdf in zip(["intra", "inter", "total"], [pdf_intra, pdf_inter, pdf_total]): self._outputData["pdf_%s_%s%s" % (i, pair[0], pair[1])][:] = pdf self._outputData["rdf_%s_%s%s" % (i, pair[0], pair[1])][:] = ( shellSurfaces * self.averageDensity * pdf ) self._outputData["tcf_%s_%s%s" % (i, pair[0], pair[1])][:] = ( - densityFactor - * self.averageDensity - * (pdf if i == "intra" else pdf - 1) + densityFactor * self.averageDensity * (pdf if i == "intra" else pdf - 1) ) weights = self.configuration["weights"].get_weights() @@ -159,13 +155,9 @@ def finalize(self): "pdf{}_%s%s".format(i if i else "_total"), ) self._outputData["pdf%s_total" % i][:] = pdf - self._outputData["rdf%s_total" % i][:] = ( - shellSurfaces * self.averageDensity * pdf - ) + self._outputData["rdf%s_total" % i][:] = shellSurfaces * self.averageDensity * pdf self._outputData["tcf%s_total" % i][:] = ( - densityFactor - * self.averageDensity - * (pdf if i == "_intra" else pdf - 1) + densityFactor * self.averageDensity * (pdf if i == "_intra" else pdf - 1) ) self._outputData.write( diff --git a/MDANSE/Src/MDANSE/Framework/Jobs/PositionAutoCorrelationFunction.py b/MDANSE/Src/MDANSE/Framework/Jobs/PositionAutoCorrelationFunction.py index 1143f0f3ff..9dec16214f 100644 --- a/MDANSE/Src/MDANSE/Framework/Jobs/PositionAutoCorrelationFunction.py +++ b/MDANSE/Src/MDANSE/Framework/Jobs/PositionAutoCorrelationFunction.py @@ -114,9 +114,7 @@ def initialize(self): partial_result=True, ) - self._atoms = self.configuration["trajectory"][ - "instance" - ].chemical_system.atom_list + self._atoms = self.configuration["trajectory"]["instance"].chemical_system.atom_list def run_step(self, index): """ @@ -143,9 +141,7 @@ def run_step(self, index): series = self.configuration["projection"]["projector"](series) n_configs = self.configuration["frames"]["n_configs"] - atomicPACF = correlate(series, series[:n_configs], mode="valid") / ( - 3 * n_configs - ) + atomicPACF = correlate(series, series[:n_configs], mode="valid") / (3 * n_configs) return index, atomicPACF.T[0] def combine(self, index, x): diff --git a/MDANSE/Src/MDANSE/Framework/Jobs/PositionPowerSpectrum.py b/MDANSE/Src/MDANSE/Framework/Jobs/PositionPowerSpectrum.py index aa848f9f8d..8c524ca219 100644 --- a/MDANSE/Src/MDANSE/Framework/Jobs/PositionPowerSpectrum.py +++ b/MDANSE/Src/MDANSE/Framework/Jobs/PositionPowerSpectrum.py @@ -154,9 +154,7 @@ def initialize(self): main_result=True, ) - self._atoms = self.configuration["trajectory"][ - "instance" - ].chemical_system.atom_list + self._atoms = self.configuration["trajectory"]["instance"].chemical_system.atom_list def run_step(self, index): """ @@ -187,9 +185,7 @@ def run_step(self, index): series = self.configuration["projection"]["projector"](series) n_configs = self.configuration["frames"]["n_configs"] - atomicPACF = correlate(series, series[:n_configs], mode="valid") / ( - 3 * n_configs - ) + atomicPACF = correlate(series, series[:n_configs], mode="valid") / (3 * n_configs) return index, atomicPACF.T[0] def combine(self, index, x): diff --git a/MDANSE/Src/MDANSE/Framework/Jobs/RadiusOfGyration.py b/MDANSE/Src/MDANSE/Framework/Jobs/RadiusOfGyration.py index 82a0333bab..d88a960029 100644 --- a/MDANSE/Src/MDANSE/Framework/Jobs/RadiusOfGyration.py +++ b/MDANSE/Src/MDANSE/Framework/Jobs/RadiusOfGyration.py @@ -82,17 +82,11 @@ def initialize(self): ) self._indices = [ - idx - for idxs in self.configuration["atom_selection"]["indices"] - for idx in idxs + idx for idxs in self.configuration["atom_selection"]["indices"] for idx in idxs ] self._masses = np.array( - [ - m - for masses in self._configuration["atom_selection"]["masses"] - for m in masses - ], + [m for masses in self._configuration["atom_selection"]["masses"] for m in masses], dtype=np.float64, ) diff --git a/MDANSE/Src/MDANSE/Framework/Jobs/RigidBodyTrajectory.py b/MDANSE/Src/MDANSE/Framework/Jobs/RigidBodyTrajectory.py index 012b7f1e7e..d427b0a9f2 100644 --- a/MDANSE/Src/MDANSE/Framework/Jobs/RigidBodyTrajectory.py +++ b/MDANSE/Src/MDANSE/Framework/Jobs/RigidBodyTrajectory.py @@ -84,10 +84,7 @@ def initialize(self): """ """ super().initialize() - if ( - self.configuration["reference"]["value"] - >= self.configuration["trajectory"]["length"] - ): + if self.configuration["reference"]["value"] >= self.configuration["trajectory"]["length"]: raise JobError( self, "Invalid reference frame. Must be an integer in [%d,%d[" @@ -124,9 +121,7 @@ def initialize(self): for i in range(self.configuration["atom_selection"]["selection_length"]): indices = self.configuration["atom_selection"]["indices"][i] - self._groups.append( - AtomCluster("", [atoms[idx] for idx in indices], parentless=True) - ) + self._groups.append(AtomCluster("", [atoms[idx] for idx in indices], parentless=True)) self.numberOfSteps = len(self._groups) @@ -155,9 +150,7 @@ def initialize(self): self._group_atoms = [group.atom_list for group in self._groups] - conf = RealConfiguration( - self._output_trajectory.chemical_system, coords, unitCell - ) + conf = RealConfiguration(self._output_trajectory.chemical_system, coords, unitCell) self._reference_configuration = conf.continuous_configuration() @@ -190,8 +183,7 @@ def finalize(self): """ """ group_coms = [ - center_of_mass(self._reference_configuration[group]) - for group in self._groups + center_of_mass(self._reference_configuration[group]) for group in self._groups ] trajectory = self.configuration["trajectory"]["instance"] @@ -223,13 +215,10 @@ def finalize(self): for atom in self._group_atoms[group_id]: # The coordinates of the atoms are centered around the center of mass of the group. xyz = ( - self._reference_configuration["coordinates"][atom.index, :] - - center_of_mass + self._reference_configuration["coordinates"][atom.index, :] - center_of_mass ) - real_configuration["coordinates"][atom.index, :] = transfo( - Vector(*xyz) - ) + real_configuration["coordinates"][atom.index, :] = transfo(Vector(*xyz)) self._output_trajectory.dump_configuration( real_configuration, @@ -246,13 +235,9 @@ def finalize(self): "quaternions", shape=(n_groups, n_frames, 4), dtype=np.float64 ) - coms = outputFile.create_dataset( - "coms", shape=(n_groups, n_frames, 3), dtype=np.float64 - ) + coms = outputFile.create_dataset("coms", shape=(n_groups, n_frames, 3), dtype=np.float64) - fits = outputFile.create_dataset( - "fits", shape=(n_groups, n_frames), dtype=np.float64 - ) + fits = outputFile.create_dataset("fits", shape=(n_groups, n_frames), dtype=np.float64) outputFile.attrs["info"] = str(self) diff --git a/MDANSE/Src/MDANSE/Framework/Jobs/RootMeanSquareDeviation.py b/MDANSE/Src/MDANSE/Framework/Jobs/RootMeanSquareDeviation.py index 1ceeb2001f..7e6fc868b0 100644 --- a/MDANSE/Src/MDANSE/Framework/Jobs/RootMeanSquareDeviation.py +++ b/MDANSE/Src/MDANSE/Framework/Jobs/RootMeanSquareDeviation.py @@ -110,9 +110,7 @@ def initialize(self): main_result=True, ) - self._atoms = self.configuration["trajectory"][ - "instance" - ].chemical_system.atom_list + self._atoms = self.configuration["trajectory"]["instance"].chemical_system.atom_list def run_step(self, index): """ @@ -163,9 +161,7 @@ def finalize(self): self._outputData["rmsd_{}".format(element)] ) - self._outputData["rmsd_all"] /= self.configuration[ - "atom_selection" - ].get_total_natoms() + self._outputData["rmsd_all"] /= self.configuration["atom_selection"].get_total_natoms() self._outputData["rmsd_all"] = np.sqrt(self._outputData["rmsd_all"]) self._outputData.write( diff --git a/MDANSE/Src/MDANSE/Framework/Jobs/RootMeanSquareFluctuation.py b/MDANSE/Src/MDANSE/Framework/Jobs/RootMeanSquareFluctuation.py index 5b8f3f190f..6d1e1a2679 100644 --- a/MDANSE/Src/MDANSE/Framework/Jobs/RootMeanSquareFluctuation.py +++ b/MDANSE/Src/MDANSE/Framework/Jobs/RootMeanSquareFluctuation.py @@ -71,11 +71,7 @@ def initialize(self): self.numberOfSteps = self.configuration["atom_selection"]["selection_length"] # Will store the indices. - indices = [ - idx - for idxs in self.configuration["atom_selection"]["indices"] - for idx in idxs - ] + indices = [idx for idxs in self.configuration["atom_selection"]["indices"] for idx in idxs] if self.configuration["grouping_level"]["value"] == "atom": self._outputData.add("indices", "LineOutputVariable", indices) else: @@ -95,9 +91,7 @@ def initialize(self): main_result=True, ) - self._atoms = self.configuration["trajectory"][ - "instance" - ].chemical_system.atom_list + self._atoms = self.configuration["trajectory"]["instance"].chemical_system.atom_list def run_step(self, index): """ diff --git a/MDANSE/Src/MDANSE/Framework/Jobs/SolventAccessibleSurface.py b/MDANSE/Src/MDANSE/Framework/Jobs/SolventAccessibleSurface.py index 79e1b22859..93fe54170e 100644 --- a/MDANSE/Src/MDANSE/Framework/Jobs/SolventAccessibleSurface.py +++ b/MDANSE/Src/MDANSE/Framework/Jobs/SolventAccessibleSurface.py @@ -32,7 +32,6 @@ def solvent_accessible_surface( sphere_points: np.ndarray, probe_radius_value: float, ): - # Computes the Solvent Accessible Surface Based on the algorithm published by Shrake, A., and J. A. Rupley. JMB (1973) 79:351-371. sas = 0.0 @@ -41,33 +40,23 @@ def solvent_accessible_surface( min_dist = np.min(vdwRadii) + probe_radius_value sphere_indices = set(range(len(sphere_points))) for idx in indexes: - sphere_tree = KDTree( - coords[idx] + sphere_points * (vdwRadii[idx] + probe_radius_value) - ) + sphere_tree = KDTree(coords[idx] + sphere_points * (vdwRadii[idx] + probe_radius_value)) distance_dict = sphere_tree.sparse_distance_matrix(tree, max_distance=max_dist) pair_array = np.array([pair for pair in distance_dict.keys()]) value_array = np.array([value for value in distance_dict.values()]) - combined_array = np.hstack( - [pair_array, value_array.reshape((len(value_array), 1))] - )[np.where(pair_array[:, 1] != idx)] - blocked_for_sure = set( - combined_array[:, 0][np.where(combined_array[:, 2] <= min_dist)] - ) + combined_array = np.hstack([pair_array, value_array.reshape((len(value_array), 1))])[ + np.where(pair_array[:, 1] != idx) + ] + blocked_for_sure = set(combined_array[:, 0][np.where(combined_array[:, 2] <= min_dist)]) free_for_sure = sphere_indices - set(combined_array[:, 0]) uncertain = sphere_indices - free_for_sure - blocked_for_sure confirmed = set() if len(uncertain) > 0: - uncertain_lines = np.array( - [line for line in combined_array if line[0] in uncertain] - ) - neighbour_radii = np.array( - [vdwRadii[int(line[1])] for line in uncertain_lines] - ) + uncertain_lines = np.array([line for line in combined_array if line[0] in uncertain]) + neighbour_radii = np.array([vdwRadii[int(line[1])] for line in uncertain_lines]) confirmed = set( uncertain_lines[:, 0][ - np.where( - uncertain_lines[:, 2] < neighbour_radii + probe_radius_value - ) + np.where(uncertain_lines[:, 2] < neighbour_radii + probe_radius_value) ] ) free_for_sure.update(uncertain - confirmed) @@ -159,16 +148,12 @@ def initialize(self): ) # A mapping between the atom indices and covalent_radius radius for the whole universe. - self.vdwRadii = self.configuration["trajectory"][ - "instance" - ].chemical_system.atom_property( + self.vdwRadii = self.configuration["trajectory"]["instance"].chemical_system.atom_property( "vdw_radius" ) # should it be covalent? self._indices = [ - idx - for idxs in self.configuration["atom_selection"]["indices"] - for idx in idxs + idx for idxs in self.configuration["atom_selection"]["indices"] for idx in idxs ] def run_step(self, index): diff --git a/MDANSE/Src/MDANSE/Framework/Jobs/StaticStructureFactor.py b/MDANSE/Src/MDANSE/Framework/Jobs/StaticStructureFactor.py index 5616e060dd..c306123340 100644 --- a/MDANSE/Src/MDANSE/Framework/Jobs/StaticStructureFactor.py +++ b/MDANSE/Src/MDANSE/Framework/Jobs/StaticStructureFactor.py @@ -193,9 +193,7 @@ def finalize(self): + self._outputData["ssf_inter_%s%s" % pair][:] ) - self._outputData.add( - "ssf_intra", "LineOutputVariable", (nq,), axis="q", units="au" - ) + self._outputData.add("ssf_intra", "LineOutputVariable", (nq,), axis="q", units="au") self._outputData.add( "ssf_inter", "LineOutputVariable", @@ -203,20 +201,14 @@ def finalize(self): axis="q", units="au", ) - self._outputData.add( - "ssf_total", "LineOutputVariable", (nq,), axis="q", units="au" - ) + self._outputData.add("ssf_total", "LineOutputVariable", (nq,), axis="q", units="au") weights = self.configuration["weights"].get_weights() - ssfIntra = weight( - weights, self._outputData, nAtomsPerElement, 2, "ssf_intra_%s%s" - ) + ssfIntra = weight(weights, self._outputData, nAtomsPerElement, 2, "ssf_intra_%s%s") self._outputData["ssf_intra"][:] = ssfIntra - ssfInter = weight( - weights, self._outputData, nAtomsPerElement, 2, "ssf_inter_%s%s" - ) + ssfInter = weight(weights, self._outputData, nAtomsPerElement, 2, "ssf_inter_%s%s") self._outputData["ssf_inter"][:] = ssfInter diff --git a/MDANSE/Src/MDANSE/Framework/Jobs/StructureFactorFromScatteringFunction.py b/MDANSE/Src/MDANSE/Framework/Jobs/StructureFactorFromScatteringFunction.py index f8b706c79c..079d070405 100644 --- a/MDANSE/Src/MDANSE/Framework/Jobs/StructureFactorFromScatteringFunction.py +++ b/MDANSE/Src/MDANSE/Framework/Jobs/StructureFactorFromScatteringFunction.py @@ -64,9 +64,7 @@ def initialize(self): resolution = self.configuration["instrument_resolution"] - self._outputData.add( - "time", "LineOutputVariable", inputFile["time"][:], units="ps" - ) + self._outputData.add("time", "LineOutputVariable", inputFile["time"][:], units="ps") self._outputData.add( "time_window", @@ -78,9 +76,7 @@ def initialize(self): self._outputData.add("q", "LineOutputVariable", inputFile["q"][:], units="1/nm") - self._outputData.add( - "omega", "LineOutputVariable", resolution["omega"], units="rad/ps" - ) + self._outputData.add("omega", "LineOutputVariable", resolution["omega"], units="rad/ps") self._outputData.add( "omega_window", @@ -95,9 +91,7 @@ def initialize(self): for k, v in list(inputFile.items()): if k.startswith("f(q,t)_"): - self._outputData.add( - k, "SurfaceOutputVariable", v[:], axis="q|time", units="au" - ) + self._outputData.add(k, "SurfaceOutputVariable", v[:], axis="q|time", units="au") suffix = k[7:] self._outputData.add( "s(q,f)_%s" % suffix, diff --git a/MDANSE/Src/MDANSE/Framework/Jobs/Temperature.py b/MDANSE/Src/MDANSE/Framework/Jobs/Temperature.py index 1f052989a4..d01b2373d2 100644 --- a/MDANSE/Src/MDANSE/Framework/Jobs/Temperature.py +++ b/MDANSE/Src/MDANSE/Framework/Jobs/Temperature.py @@ -111,9 +111,7 @@ def initialize(self): units="K", ) - self._atoms = self.configuration["trajectory"][ - "instance" - ].chemical_system.atom_list + self._atoms = self.configuration["trajectory"]["instance"].chemical_system.atom_list def run_step(self, index): """ @@ -185,9 +183,7 @@ def finalize(self): np.cumsum(self._outputData["kinetic_energy"]) / norm ) - self._outputData["temperature"][:] = ( - 2.0 * self._outputData["kinetic_energy"] / (3.0 * KB) - ) + self._outputData["temperature"][:] = 2.0 * self._outputData["kinetic_energy"] / (3.0 * KB) self._outputData["avg_temperature"][:] = ( 2.0 * self._outputData["avg_kinetic_energy"] / (3.0 * KB) ) diff --git a/MDANSE/Src/MDANSE/Framework/Jobs/TrajectoryEditor.py b/MDANSE/Src/MDANSE/Framework/Jobs/TrajectoryEditor.py index 407af90dbf..b97c7c17c6 100644 --- a/MDANSE/Src/MDANSE/Framework/Jobs/TrajectoryEditor.py +++ b/MDANSE/Src/MDANSE/Framework/Jobs/TrajectoryEditor.py @@ -95,9 +95,7 @@ def initialize(self): self.numberOfSteps = self.configuration["frames"]["number"] self._input_trajectory = self.configuration["trajectory"]["instance"] - self._input_chemical_system = self.configuration["trajectory"][ - "instance" - ].chemical_system + self._input_chemical_system = self.configuration["trajectory"]["instance"].chemical_system if self.configuration["unit_cell"]["apply"]: self._new_unit_cell = UnitCell(self.configuration["unit_cell"]["value"]) @@ -106,11 +104,7 @@ def initialize(self): ] # The collection of atoms corresponding to the atoms selected for output. - indices = [ - idx - for idxs in self.configuration["atom_selection"]["indices"] - for idx in idxs - ] + indices = [idx for idxs in self.configuration["atom_selection"]["indices"] for idx in idxs] self._indices = indices temp_copy = list(self._input_chemical_system.atom_list) indices_per_element = self.configuration["atom_selection"].get_indices() @@ -146,9 +140,7 @@ def initialize(self): else: new_chemical_system.add_bonds(self._input_chemical_system._bonds) for key in self._input_chemical_system._clusters.keys(): - new_chemical_system.add_clusters( - self._input_chemical_system._clusters[key] - ) + new_chemical_system.add_clusters(self._input_chemical_system._clusters[key]) # The output trajectory is opened for writing. self._output_trajectory = TrajectoryWriter( diff --git a/MDANSE/Src/MDANSE/Framework/Jobs/UnfoldedTrajectory.py b/MDANSE/Src/MDANSE/Framework/Jobs/UnfoldedTrajectory.py index 845188cd9e..7232b652f7 100644 --- a/MDANSE/Src/MDANSE/Framework/Jobs/UnfoldedTrajectory.py +++ b/MDANSE/Src/MDANSE/Framework/Jobs/UnfoldedTrajectory.py @@ -64,11 +64,7 @@ def initialize(self): atoms = self.configuration["trajectory"]["instance"].chemical_system.atom_list # The collection of atoms corresponding to the atoms selected for output. - indices = [ - idx - for idxs in self.configuration["atom_selection"]["indices"] - for idx in idxs - ] + indices = [idx for idxs in self.configuration["atom_selection"]["indices"] for idx in idxs] self._selectedAtoms = [atoms[ind] for ind in indices] self._selection_indices = indices @@ -82,8 +78,7 @@ def initialize(self): chunking_limit=self.configuration["output_files"]["chunk_size"], compression=self.configuration["output_files"]["compression"], initial_charges=[ - self.configuration["trajectory"]["instance"].charges(0)[ind] - for ind in indices + self.configuration["trajectory"]["instance"].charges(0)[ind] for ind in indices ], ) diff --git a/MDANSE/Src/MDANSE/Framework/Jobs/VanHoveFunctionDistinct.py b/MDANSE/Src/MDANSE/Framework/Jobs/VanHoveFunctionDistinct.py index 0b38211e56..4142322f46 100644 --- a/MDANSE/Src/MDANSE/Framework/Jobs/VanHoveFunctionDistinct.py +++ b/MDANSE/Src/MDANSE/Framework/Jobs/VanHoveFunctionDistinct.py @@ -24,9 +24,8 @@ from MDANSE.MolecularDynamics.TrajectoryUtils import atom_index_to_molecule_index from MDANSE.Mathematics.Arithmetic import weight -def distance_array_2D( - ref_atoms: np.ndarray, other_atoms: np.ndarray, cell_array: np.ndarray -): + +def distance_array_2D(ref_atoms: np.ndarray, other_atoms: np.ndarray, cell_array: np.ndarray): """Given two input arrays of atomic positions sized (N,3) and (M,3), returns an (M, N) array of distances between the atoms. @@ -262,9 +261,7 @@ def initialize(self): self._nAtomsPerElement = self.configuration["atom_selection"].get_natoms() self.selectedElements = self.configuration["atom_selection"]["unique_names"] self.nElements = len(self.selectedElements) - self._elementsPairs = sorted( - it.combinations_with_replacement(self.selectedElements, 2) - ) + self._elementsPairs = sorted(it.combinations_with_replacement(self.selectedElements, 2)) self.n_mid_points = len(self.configuration["r_values"]["mid_points"]) @@ -339,9 +336,7 @@ def initialize(self): self.configuration["trajectory"]["instance"].chemical_system ) self._indices = [ - idx - for idxs in self.configuration["atom_selection"]["indices"] - for idx in idxs + idx for idxs in self.configuration["atom_selection"]["indices"] for idx in idxs ] self.indexToMolecule = np.array([lut[i] for i in self._indices], dtype=np.int32) self.indexToSymbol = np.array( @@ -400,15 +395,11 @@ def run_step(self, time: int) -> tuple[int, tuple[np.ndarray, np.ndarray]]: # difference over a number of configuration for i in range(self.n_configs): frame_index_t0 = self.configuration["frames"]["value"][i] - conf_t0 = self.configuration["trajectory"]["instance"].configuration( - frame_index_t0 - ) + conf_t0 = self.configuration["trajectory"]["instance"].configuration(frame_index_t0) coords_t0 = conf_t0["coordinates"][self._indices] frame_index_t1 = self.configuration["frames"]["value"][i + time] - conf_t1 = self.configuration["trajectory"]["instance"].configuration( - frame_index_t1 - ) + conf_t1 = self.configuration["trajectory"]["instance"].configuration(frame_index_t1) coords_t1 = conf_t1["coordinates"][self._indices] direct_cell = conf_t1.unit_cell.transposed_direct inverse_cell = conf_t1.unit_cell.transposed_inverse @@ -483,9 +474,7 @@ def finalize(self): ["intra", "inter", "total"], [van_hove_intra, van_hove_inter, van_hove_total], ): - self._outputData[f"g(r,t)_{i}_{''.join(pair)}"][ - ... - ] = van_h + self._outputData[f"g(r,t)_{i}_{''.join(pair)}"][...] = van_h weights = self.configuration["weights"].get_weights() for i in ["_intra", "_inter", ""]: diff --git a/MDANSE/Src/MDANSE/Framework/Jobs/VanHoveFunctionSelf.py b/MDANSE/Src/MDANSE/Framework/Jobs/VanHoveFunctionSelf.py index 59c6c23850..a099dfffa9 100644 --- a/MDANSE/Src/MDANSE/Framework/Jobs/VanHoveFunctionSelf.py +++ b/MDANSE/Src/MDANSE/Framework/Jobs/VanHoveFunctionSelf.py @@ -242,9 +242,7 @@ def run_step(self, atm_index: int) -> tuple[int, tuple[np.ndarray, np.ndarray]]: ) cell_vols = np.array( [ - self.configuration["trajectory"]["instance"] - .configuration(i) - .unit_cell.volume + self.configuration["trajectory"]["instance"].configuration(i).unit_cell.volume for i in range(first, last, step) ] ) diff --git a/MDANSE/Src/MDANSE/Framework/Jobs/VelocityAutoCorrelationFunction.py b/MDANSE/Src/MDANSE/Framework/Jobs/VelocityAutoCorrelationFunction.py index dbe8c64dbb..5852d52c59 100644 --- a/MDANSE/Src/MDANSE/Framework/Jobs/VelocityAutoCorrelationFunction.py +++ b/MDANSE/Src/MDANSE/Framework/Jobs/VelocityAutoCorrelationFunction.py @@ -141,9 +141,7 @@ def initialize(self): main_result=True, ) - self._atoms = self.configuration["trajectory"][ - "instance" - ].chemical_system.atom_list + self._atoms = self.configuration["trajectory"]["instance"].chemical_system.atom_list def run_step(self, index): """ @@ -189,9 +187,7 @@ def run_step(self, index): series = self.configuration["projection"]["projector"](series) n_configs = self.configuration["frames"]["n_configs"] - atomicVACF = correlate(series, series[:n_configs], mode="valid") / ( - 3 * n_configs - ) + atomicVACF = correlate(series, series[:n_configs], mode="valid") / (3 * n_configs) return index, atomicVACF.T[0] def combine(self, index, x): @@ -226,9 +222,7 @@ def finalize(self): self._outputData["vacf_%s" % element] = normalize( self._outputData["vacf_%s" % element], axis=0 ) - self._outputData["vacf_total"] = normalize( - self._outputData["vacf_total"], axis=0 - ) + self._outputData["vacf_total"] = normalize(self._outputData["vacf_total"], axis=0) self._outputData.write( self.configuration["output_files"]["root"], diff --git a/MDANSE/Src/MDANSE/Framework/Jobs/Voronoi.py b/MDANSE/Src/MDANSE/Framework/Jobs/Voronoi.py index 2368be80e9..29dd744cfb 100644 --- a/MDANSE/Src/MDANSE/Framework/Jobs/Voronoi.py +++ b/MDANSE/Src/MDANSE/Framework/Jobs/Voronoi.py @@ -34,6 +34,7 @@ def no_exc_min(numbers: List[float]): except TypeError: return -2 + class VoronoiError(Exception): pass @@ -106,9 +107,7 @@ def initialize(self): try: cell = first_conf.unit_cell.direct - self.cell_param = np.array( - [cell[0, 0], cell[1, 1], cell[2, 2]], dtype=np.float64 - ) + self.cell_param = np.array([cell[0, 0], cell[1, 1], cell[2, 2]], dtype=np.float64) except Exception: raise VoronoiError( "Voronoi analysis cannot be computed if simulation box is not defined. " @@ -195,9 +194,7 @@ def run_step(self, index): # Volume Computation global_volumes = {} - for vrid, regions in list( - delaunay_regions_for_each_valid_voronoi_region.items() - ): + for vrid, regions in list(delaunay_regions_for_each_valid_voronoi_region.items()): regions_volumes = [] for vidx in regions: coords = vertices_coords[vidx] diff --git a/MDANSE/Src/MDANSE/Framework/Jobs/XRayStaticStructureFactor.py b/MDANSE/Src/MDANSE/Framework/Jobs/XRayStaticStructureFactor.py index 5da649cec0..e3c23597ff 100644 --- a/MDANSE/Src/MDANSE/Framework/Jobs/XRayStaticStructureFactor.py +++ b/MDANSE/Src/MDANSE/Framework/Jobs/XRayStaticStructureFactor.py @@ -186,15 +186,9 @@ def finalize(self): + self._outputData["xssf_inter_%s%s" % pair][:] ) - self._outputData.add( - "xssf_intra", "LineOutputVariable", (nq,), axis="q", units="au" - ) - self._outputData.add( - "xssf_inter", "LineOutputVariable", (nq,), axis="q", units="au" - ) - self._outputData.add( - "xssf_total", "LineOutputVariable", (nq,), axis="q", units="au" - ) + self._outputData.add("xssf_intra", "LineOutputVariable", (nq,), axis="q", units="au") + self._outputData.add("xssf_inter", "LineOutputVariable", (nq,), axis="q", units="au") + self._outputData.add("xssf_total", "LineOutputVariable", (nq,), axis="q", units="au") asf = dict( ( @@ -208,14 +202,10 @@ def finalize(self): for k in list(nAtomsPerElement.keys()) ) - xssfIntra = weight( - asf, self._outputData, nAtomsPerElement, 2, "xssf_intra_%s%s" - ) + xssfIntra = weight(asf, self._outputData, nAtomsPerElement, 2, "xssf_intra_%s%s") self._outputData["xssf_intra"][:] = xssfIntra - xssfInter = weight( - asf, self._outputData, nAtomsPerElement, 2, "xssf_inter_%s%s" - ) + xssfInter = weight(asf, self._outputData, nAtomsPerElement, 2, "xssf_inter_%s%s") self._outputData["xssf_inter"][:] = xssfInter self._outputData["xssf_total"][:] = xssfIntra + xssfInter diff --git a/MDANSE/Src/MDANSE/Framework/OutputVariables/IOutputVariable.py b/MDANSE/Src/MDANSE/Framework/OutputVariables/IOutputVariable.py index 35508e6e03..88a0f7e10e 100644 --- a/MDANSE/Src/MDANSE/Framework/OutputVariables/IOutputVariable.py +++ b/MDANSE/Src/MDANSE/Framework/OutputVariables/IOutputVariable.py @@ -82,8 +82,7 @@ def __new__( if value.ndim != cls._nDimensions: raise OutputVariableError( - "Invalid number of dimensions for an output variable of type %r" - % cls.name + "Invalid number of dimensions for an output variable of type %r" % cls.name ) # Input array is an already formed ndarray instance diff --git a/MDANSE/Src/MDANSE/Framework/OutputVariables/__init__.py b/MDANSE/Src/MDANSE/Framework/OutputVariables/__init__.py index c0eab43316..b14466ec44 100644 --- a/MDANSE/Src/MDANSE/Framework/OutputVariables/__init__.py +++ b/MDANSE/Src/MDANSE/Framework/OutputVariables/__init__.py @@ -31,9 +31,7 @@ if name in ["__init__"]: continue try: - tempmod = importlib.import_module( - "." + name, "MDANSE.Framework.OutputVariables" - ) + tempmod = importlib.import_module("." + name, "MDANSE.Framework.OutputVariables") except ModuleNotFoundError: continue tempobject = getattr(tempmod, name) diff --git a/MDANSE/Src/MDANSE/Framework/Projectors/AxialProjector.py b/MDANSE/Src/MDANSE/Framework/Projectors/AxialProjector.py index c355d07569..562b82f51d 100644 --- a/MDANSE/Src/MDANSE/Framework/Projectors/AxialProjector.py +++ b/MDANSE/Src/MDANSE/Framework/Projectors/AxialProjector.py @@ -26,9 +26,7 @@ def set_axis(self, axis): try: self._axis = Vector(axis) except (TypeError, ValueError): - raise ProjectorError( - "Wrong axis definition: must be a sequence of 3 floats" - ) + raise ProjectorError("Wrong axis definition: must be a sequence of 3 floats") try: self._axis = self._axis.normal() diff --git a/MDANSE/Src/MDANSE/Framework/Projectors/PlanarProjector.py b/MDANSE/Src/MDANSE/Framework/Projectors/PlanarProjector.py index ff032be388..6f6d8063e3 100644 --- a/MDANSE/Src/MDANSE/Framework/Projectors/PlanarProjector.py +++ b/MDANSE/Src/MDANSE/Framework/Projectors/PlanarProjector.py @@ -26,9 +26,7 @@ def set_axis(self, axis): try: self._axis = Vector(axis) except (TypeError, ValueError): - raise ProjectorError( - "Wrong axis definition: must be a sequence of 3 floats" - ) + raise ProjectorError("Wrong axis definition: must be a sequence of 3 floats") try: self._axis = self._axis.normal() diff --git a/MDANSE/Src/MDANSE/Framework/QVectors/ApproximateDispersionQVectors.py b/MDANSE/Src/MDANSE/Framework/QVectors/ApproximateDispersionQVectors.py index cdb223921f..9e01e64b0b 100644 --- a/MDANSE/Src/MDANSE/Framework/QVectors/ApproximateDispersionQVectors.py +++ b/MDANSE/Src/MDANSE/Framework/QVectors/ApproximateDispersionQVectors.py @@ -59,15 +59,11 @@ def _generate(self): try: n = (qEnd - qStart).normal() except ZeroDivisionError: - self._configuration["q_end"].error_status = ( - "Zero-length vector cannot be used here" - ) + self._configuration["q_end"].error_status = "Zero-length vector cannot be used here" return nSteps = int(d / qStep) + 1 - vects = ( - np.array(qStart)[:, np.newaxis] + np.outer(n, np.arange(0, nSteps)) * qStep - ) + vects = np.array(qStart)[:, np.newaxis] + np.outer(n, np.arange(0, nSteps)) * qStep hkls = np.rint(np.dot(self._directUnitCell, vects)) @@ -75,9 +71,7 @@ def _generate(self): dists = list(zip(range(len(dists)), dists)) dists.sort(key=operator.itemgetter(1)) qGroups = itertools.groupby(dists, key=operator.itemgetter(1)) - qGroups = collections.OrderedDict( - [(k, [item[0] for item in v]) for k, v in qGroups] - ) + qGroups = collections.OrderedDict([(k, [item[0] for item in v]) for k, v in qGroups]) if self._status is not None: self._status.start(len(qGroups)) diff --git a/MDANSE/Src/MDANSE/Framework/QVectors/CircularLatticeQVectors.py b/MDANSE/Src/MDANSE/Framework/QVectors/CircularLatticeQVectors.py index 01175ad326..2965701083 100644 --- a/MDANSE/Src/MDANSE/Framework/QVectors/CircularLatticeQVectors.py +++ b/MDANSE/Src/MDANSE/Framework/QVectors/CircularLatticeQVectors.py @@ -63,10 +63,7 @@ def _generate(self): qVects = np.dot(self._inverseUnitCell, hkls) - qMax = ( - self._configuration["shells"]["last"] - + 0.5 * self._configuration["width"]["value"] - ) + qMax = self._configuration["shells"]["last"] + 0.5 * self._configuration["width"]["value"] uvMax = np.ceil([qMax / Vector(v).length() for v in qVects.T]) + 1 # Enforce integers in uvMax diff --git a/MDANSE/Src/MDANSE/Framework/QVectors/CircularQVectors.py b/MDANSE/Src/MDANSE/Framework/QVectors/CircularQVectors.py index b8a2b25a7e..1ee4b1bc37 100644 --- a/MDANSE/Src/MDANSE/Framework/QVectors/CircularQVectors.py +++ b/MDANSE/Src/MDANSE/Framework/QVectors/CircularQVectors.py @@ -70,9 +70,9 @@ def _generate(self): self._configuration["q_vectors"] = collections.OrderedDict() for q in self._configuration["shells"]["value"]: - fact = q * np.sign( - np.random.uniform(-0.5, 0.5, nVectors) - ) + width * np.random.uniform(-0.5, 0.5, nVectors) + fact = q * np.sign(np.random.uniform(-0.5, 0.5, nVectors)) + width * np.random.uniform( + -0.5, 0.5, nVectors + ) v = random_points_on_circle(axis, radius=1.0, nPoints=nVectors) self._configuration["q_vectors"][q] = {} diff --git a/MDANSE/Src/MDANSE/Framework/QVectors/DispersionLatticeQVectors.py b/MDANSE/Src/MDANSE/Framework/QVectors/DispersionLatticeQVectors.py index ef4cc82071..729affbd47 100644 --- a/MDANSE/Src/MDANSE/Framework/QVectors/DispersionLatticeQVectors.py +++ b/MDANSE/Src/MDANSE/Framework/QVectors/DispersionLatticeQVectors.py @@ -43,9 +43,7 @@ def _generate(self): direction = self._configuration["direction"]["value"] n_steps = self._configuration["n_steps"]["value"] - hkls = np.array(start)[:, np.newaxis] + np.outer( - direction, np.arange(0, n_steps) - ) + hkls = np.array(start)[:, np.newaxis] + np.outer(direction, np.arange(0, n_steps)) # The k matrix (3,n_hkls) vects = np.dot(self._inverseUnitCell, hkls) @@ -59,9 +57,7 @@ def _generate(self): for i, v in enumerate(dists): self._configuration["q_vectors"][v] = {} - self._configuration["q_vectors"][v]["q_vectors"] = vects[:, i][ - :, np.newaxis - ] + self._configuration["q_vectors"][v]["q_vectors"] = vects[:, i][:, np.newaxis] self._configuration["q_vectors"][v]["n_q_vectors"] = 1 self._configuration["q_vectors"][v]["q"] = v self._configuration["q_vectors"][v]["hkls"] = hkls[:, i][:, np.newaxis] diff --git a/MDANSE/Src/MDANSE/Framework/QVectors/GridQVectors.py b/MDANSE/Src/MDANSE/Framework/QVectors/GridQVectors.py index 940cf2deec..2121503634 100644 --- a/MDANSE/Src/MDANSE/Framework/QVectors/GridQVectors.py +++ b/MDANSE/Src/MDANSE/Framework/QVectors/GridQVectors.py @@ -74,9 +74,7 @@ def _generate(self): dists = list(zip(range(len(dists)), dists)) dists.sort(key=operator.itemgetter(1)) qGroups = itertools.groupby(dists, key=operator.itemgetter(1)) - qGroups = collections.OrderedDict( - [(k, [item[0] for item in v]) for k, v in qGroups] - ) + qGroups = collections.OrderedDict([(k, [item[0] for item in v]) for k, v in qGroups]) if self._status is not None: self._status.start(len(qGroups)) diff --git a/MDANSE/Src/MDANSE/Framework/QVectors/IQVectors.py b/MDANSE/Src/MDANSE/Framework/QVectors/IQVectors.py index b3fadad0ee..5251cd6224 100644 --- a/MDANSE/Src/MDANSE/Framework/QVectors/IQVectors.py +++ b/MDANSE/Src/MDANSE/Framework/QVectors/IQVectors.py @@ -47,9 +47,7 @@ def generate(self) -> bool: self._status.finish() return True else: - LOG.error( - "Cannot generate vectors: q vector generator is not configured correctly." - ) + LOG.error("Cannot generate vectors: q vector generator is not configured correctly.") return False def setStatus(self, status): diff --git a/MDANSE/Src/MDANSE/Framework/QVectors/LinearLatticeQVectors.py b/MDANSE/Src/MDANSE/Framework/QVectors/LinearLatticeQVectors.py index fefabc3aa3..2783e22505 100644 --- a/MDANSE/Src/MDANSE/Framework/QVectors/LinearLatticeQVectors.py +++ b/MDANSE/Src/MDANSE/Framework/QVectors/LinearLatticeQVectors.py @@ -53,10 +53,7 @@ def _generate(self): # The Q vector corresponding to the input hkl. qVect = np.dot(self._inverseUnitCell, self._configuration["axis"]["vector"]) - qMax = ( - self._configuration["shells"]["last"] - + 0.5 * self._configuration["width"]["value"] - ) + qMax = self._configuration["shells"]["last"] + 0.5 * self._configuration["width"]["value"] uMax = np.ceil(qMax / Vector(qVect).length()) + 1 diff --git a/MDANSE/Src/MDANSE/Framework/QVectors/LinearQVectors.py b/MDANSE/Src/MDANSE/Framework/QVectors/LinearQVectors.py index 26c55932a1..fd609f310c 100644 --- a/MDANSE/Src/MDANSE/Framework/QVectors/LinearQVectors.py +++ b/MDANSE/Src/MDANSE/Framework/QVectors/LinearQVectors.py @@ -58,14 +58,12 @@ def _generate(self): self._configuration["q_vectors"] = collections.OrderedDict() for q in self._configuration["shells"]["value"]: - fact = q * np.sign( - np.random.uniform(-0.5, 0.5, nVectors) - ) + width * np.random.uniform(-0.5, 0.5, nVectors) + fact = q * np.sign(np.random.uniform(-0.5, 0.5, nVectors)) + width * np.random.uniform( + -0.5, 0.5, nVectors + ) self._configuration["q_vectors"][q] = {} - self._configuration["q_vectors"][q]["q_vectors"] = ( - axis.array[:, np.newaxis] * fact - ) + self._configuration["q_vectors"][q]["q_vectors"] = axis.array[:, np.newaxis] * fact self._configuration["q_vectors"][q]["n_q_vectors"] = nVectors self._configuration["q_vectors"][q]["q"] = q self._configuration["q_vectors"][q]["hkls"] = None diff --git a/MDANSE/Src/MDANSE/Framework/QVectors/SphericalLatticeQVectors.py b/MDANSE/Src/MDANSE/Framework/QVectors/SphericalLatticeQVectors.py index 566170635a..17296629b1 100644 --- a/MDANSE/Src/MDANSE/Framework/QVectors/SphericalLatticeQVectors.py +++ b/MDANSE/Src/MDANSE/Framework/QVectors/SphericalLatticeQVectors.py @@ -44,14 +44,9 @@ def _generate(self): np.random.seed(self._configuration["seed"]["value"]) random.seed(self._configuration["seed"]["value"]) - qMax = ( - self._configuration["shells"]["last"] - + 0.5 * self._configuration["width"]["value"] - ) + qMax = self._configuration["shells"]["last"] + 0.5 * self._configuration["width"]["value"] - hklMax = ( - np.ceil([qMax / np.sqrt(np.sum(v**2)) for v in self._inverseUnitCell.T]) + 1 - ) + hklMax = np.ceil([qMax / np.sqrt(np.sum(v**2)) for v in self._inverseUnitCell.T]) + 1 vects = np.mgrid[ -hklMax[0] : hklMax[0] + 1, diff --git a/MDANSE/Src/MDANSE/Framework/QVectors/SphericalQVectors.py b/MDANSE/Src/MDANSE/Framework/QVectors/SphericalQVectors.py index d111e4072a..6b3d5ce536 100644 --- a/MDANSE/Src/MDANSE/Framework/QVectors/SphericalQVectors.py +++ b/MDANSE/Src/MDANSE/Framework/QVectors/SphericalQVectors.py @@ -53,9 +53,9 @@ def _generate(self): self._status.start(len(self._configuration["shells"]["value"])) for q in self._configuration["shells"]["value"]: - fact = q * np.sign( - np.random.uniform(-0.5, 0.5, nVectors) - ) + width * np.random.uniform(-0.5, 0.5, nVectors) + fact = q * np.sign(np.random.uniform(-0.5, 0.5, nVectors)) + width * np.random.uniform( + -0.5, 0.5, nVectors + ) v = random_points_on_sphere(radius=1.0, nPoints=nVectors) diff --git a/MDANSE/Src/MDANSE/Framework/Units.py b/MDANSE/Src/MDANSE/Framework/Units.py index 55accca7c8..4b15f9a60c 100644 --- a/MDANSE/Src/MDANSE/Framework/Units.py +++ b/MDANSE/Src/MDANSE/Framework/Units.py @@ -155,9 +155,7 @@ def _str_to_unit(s): class _Unit(object): - def __init__( - self, uname, factor, kg=0, m=0, s=0, K=0, mol=0, A=0, cd=0, rad=0, sr=0 - ): + def __init__(self, uname, factor, kg=0, m=0, s=0, K=0, mol=0, A=0, cd=0, rad=0, sr=0): self._factor = factor self._dimension = [kg, m, s, K, mol, A, cd, rad, sr] @@ -694,21 +692,15 @@ def default(self, obj): class UnitsManager(metaclass=Singleton): _UNITS = {} - _DEFAULT_DATABASE = os.path.join( - PLATFORM.base_directory(), "MDANSE", "Framework", "units.json" - ) + _DEFAULT_DATABASE = os.path.join(PLATFORM.base_directory(), "MDANSE", "Framework", "units.json") _USER_DATABASE = os.path.join(PLATFORM.application_directory(), "units.json") def __init__(self): self.load() - def add_unit( - self, uname, factor, kg=0, m=0, s=0, K=0, mol=0, A=0, cd=0, rad=0, sr=0 - ): - UnitsManager._UNITS[uname] = _Unit( - uname, factor, kg, m, s, K, mol, A, cd, rad, sr - ) + def add_unit(self, uname, factor, kg=0, m=0, s=0, K=0, mol=0, A=0, cd=0, rad=0, sr=0): + UnitsManager._UNITS[uname] = _Unit(uname, factor, kg, m, s, K, mol, A, cd, rad, sr) def delete_unit(self, uname): if uname in UnitsManager._UNITS: @@ -779,87 +771,47 @@ def measure(val, iunit="au", ounit="", equivalent=False): # au --> au add_equivalence((0, 0, 0, 0, 0, 0, 0, 0, 0), (0, 0, 0, 0, 0, 0, 0, 0, 0), 1.0) # 1J --> 1Hz -add_equivalence( - (1, 2, -2, 0, 0, 0, 0, 0, 0), (0, 0, -1, 0, 0, 0, 0, 0, 0), 1.50919031167677e33 -) +add_equivalence((1, 2, -2, 0, 0, 0, 0, 0, 0), (0, 0, -1, 0, 0, 0, 0, 0, 0), 1.50919031167677e33) # 1J --> 1K -add_equivalence( - (1, 2, -2, 0, 0, 0, 0, 0, 0), (0, 0, 0, 1, 0, 0, 0, 0, 0), 7.242971666663e22 -) +add_equivalence((1, 2, -2, 0, 0, 0, 0, 0, 0), (0, 0, 0, 1, 0, 0, 0, 0, 0), 7.242971666663e22) # 1J --> 1kg -add_equivalence( - (1, 2, -2, 0, 0, 0, 0, 0, 0), (1, 0, 0, 0, 0, 0, 0, 0, 0), 1.112650055999e-17 -) +add_equivalence((1, 2, -2, 0, 0, 0, 0, 0, 0), (1, 0, 0, 0, 0, 0, 0, 0, 0), 1.112650055999e-17) # 1J --> 1/m -add_equivalence( - (1, 2, -2, 0, 0, 0, 0, 0, 0), (0, -1, 0, 0, 0, 0, 0, 0, 0), 5.034117012218e24 -) +add_equivalence((1, 2, -2, 0, 0, 0, 0, 0, 0), (0, -1, 0, 0, 0, 0, 0, 0, 0), 5.034117012218e24) # 1J --> 1J/mol -add_equivalence( - (1, 2, -2, 0, 0, 0, 0, 0, 0), (1, 2, -2, 0, -1, 0, 0, 0, 0), 6.02214076e23 -) +add_equivalence((1, 2, -2, 0, 0, 0, 0, 0, 0), (1, 2, -2, 0, -1, 0, 0, 0, 0), 6.02214076e23) # 1J --> 1rad/s -add_equivalence( - (1, 2, -2, 0, 0, 0, 0, 0, 0), (0, 0, -1, 0, 0, 0, 0, 1, 0), 9.482522392065263e33 -) +add_equivalence((1, 2, -2, 0, 0, 0, 0, 0, 0), (0, 0, -1, 0, 0, 0, 0, 1, 0), 9.482522392065263e33) # 1Hz --> 1K -add_equivalence( - (0, 0, -1, 0, 0, 0, 0, 0, 0), (0, 0, 0, 1, 0, 0, 0, 0, 0), 4.79924341590788e-11 -) +add_equivalence((0, 0, -1, 0, 0, 0, 0, 0, 0), (0, 0, 0, 1, 0, 0, 0, 0, 0), 4.79924341590788e-11) # 1Hz --> 1kg -add_equivalence( - (0, 0, -1, 0, 0, 0, 0, 0, 0), (1, 0, 0, 0, 0, 0, 0, 0, 0), 7.37249667845648e-51 -) +add_equivalence((0, 0, -1, 0, 0, 0, 0, 0, 0), (1, 0, 0, 0, 0, 0, 0, 0, 0), 7.37249667845648e-51) # 1Hz --> 1/m -add_equivalence( - (0, 0, -1, 0, 0, 0, 0, 0, 0), (0, -1, 0, 0, 0, 0, 0, 0, 0), 3.33564095480276e-09 -) +add_equivalence((0, 0, -1, 0, 0, 0, 0, 0, 0), (0, -1, 0, 0, 0, 0, 0, 0, 0), 3.33564095480276e-09) # 1Hz --> 1J/mol -add_equivalence( - (0, 0, -1, 0, 0, 0, 0, 0, 0), (1, 2, -2, 0, -1, 0, 0, 0, 0), 3.9903124e-10 -) +add_equivalence((0, 0, -1, 0, 0, 0, 0, 0, 0), (1, 2, -2, 0, -1, 0, 0, 0, 0), 3.9903124e-10) # 1Hz --> 1rad/s -add_equivalence( - (0, 0, -1, 0, 0, 0, 0, 0, 0), (0, 0, -1, 0, 0, 0, 0, 1, 0), 6.283185307179586 -) +add_equivalence((0, 0, -1, 0, 0, 0, 0, 0, 0), (0, 0, -1, 0, 0, 0, 0, 1, 0), 6.283185307179586) # 1K --> 1kg -add_equivalence( - (0, 0, 0, 1, 0, 0, 0, 0, 0), (1, 0, 0, 0, 0, 0, 0, 0, 0), 1.53617894312656e-40 -) +add_equivalence((0, 0, 0, 1, 0, 0, 0, 0, 0), (1, 0, 0, 0, 0, 0, 0, 0, 0), 1.53617894312656e-40) # 1K --> 1/m -add_equivalence( - (0, 0, 0, 1, 0, 0, 0, 0, 0), (0, -1, 0, 0, 0, 0, 0, 0, 0), 6.95034751466497e01 -) +add_equivalence((0, 0, 0, 1, 0, 0, 0, 0, 0), (0, -1, 0, 0, 0, 0, 0, 0, 0), 6.95034751466497e01) # 1K --> 1J/mol add_equivalence((0, 0, 0, 1, 0, 0, 0, 0, 0), (1, 2, -2, 0, -1, 0, 0, 0, 0), 8.31435) # 1K --> 1rad/s -add_equivalence( - (0, 0, 0, 1, 0, 0, 0, 0, 0), (0, 0, -1, 0, 0, 0, 0, 1, 0), 130920329782.73508 -) +add_equivalence((0, 0, 0, 1, 0, 0, 0, 0, 0), (0, 0, -1, 0, 0, 0, 0, 1, 0), 130920329782.73508) # 1kg --> 1/m -add_equivalence( - (1, 0, 0, 0, 0, 0, 0, 0, 0), (0, -1, 0, 0, 0, 0, 0, 0, 0), 4.52443873532014e41 -) +add_equivalence((1, 0, 0, 0, 0, 0, 0, 0, 0), (0, -1, 0, 0, 0, 0, 0, 0, 0), 4.52443873532014e41) # 1kg --> 1J/mol -add_equivalence( - (1, 0, 0, 0, 0, 0, 0, 0, 0), (0, -1, 0, 0, 0, 0, 0, 0, 0), 5.412430195397762e40 -) +add_equivalence((1, 0, 0, 0, 0, 0, 0, 0, 0), (0, -1, 0, 0, 0, 0, 0, 0, 0), 5.412430195397762e40) # 1kg --> 1rad/s -add_equivalence( - (1, 0, 0, 0, 0, 0, 0, 0, 0), (0, 0, -1, 0, 0, 0, 0, 1, 0), 8.522466107774846e50 -) +add_equivalence((1, 0, 0, 0, 0, 0, 0, 0, 0), (0, 0, -1, 0, 0, 0, 0, 1, 0), 8.522466107774846e50) # 1/m --> 1J/mol -add_equivalence( - (0, -1, 0, 0, 0, 0, 0, 0, 0), (1, 2, -2, 0, -1, 0, 0, 0, 0), 0.000119627 -) +add_equivalence((0, -1, 0, 0, 0, 0, 0, 0, 0), (1, 2, -2, 0, -1, 0, 0, 0, 0), 0.000119627) # 1/m --> 1rad/s -add_equivalence( - (0, -1, 0, 0, 0, 0, 0, 0, 0), (0, 0, -1, 0, 0, 0, 0, 1, 0), 1883651565.7166505 -) +add_equivalence((0, -1, 0, 0, 0, 0, 0, 0, 0), (0, 0, -1, 0, 0, 0, 0, 1, 0), 1883651565.7166505) # 1J/mol --> 1rad/s -add_equivalence( - (1, 2, -2, 0, -1, 0, 0, 0, 0), (0, 0, -1, 0, 0, 0, 0, 1, 0), 15746098887.375164 -) +add_equivalence((1, 2, -2, 0, -1, 0, 0, 0, 0), (0, 0, -1, 0, 0, 0, 0, 1, 0), 15746098887.375164) if __name__ == "__main__": m = measure(1.0, "m") diff --git a/MDANSE/Src/MDANSE/IO/FortranFormat.py b/MDANSE/Src/MDANSE/IO/FortranFormat.py index 5ef241ab1c..b25687621c 100644 --- a/MDANSE/Src/MDANSE/IO/FortranFormat.py +++ b/MDANSE/Src/MDANSE/IO/FortranFormat.py @@ -46,6 +46,7 @@ '3.14159D+00 2.71828D+00' """ + import string from MDANSE.MLogging import LOG diff --git a/MDANSE/Src/MDANSE/IO/MinimalPDBReader.py b/MDANSE/Src/MDANSE/IO/MinimalPDBReader.py index 0baab13af8..2f262e34f9 100644 --- a/MDANSE/Src/MDANSE/IO/MinimalPDBReader.py +++ b/MDANSE/Src/MDANSE/IO/MinimalPDBReader.py @@ -58,9 +58,7 @@ def atom_line_slice(keyword: str) -> slice: class MinimalPDBReader: - def __init__(self, filename: str): - self._unit_cell = None cell_params = self.find_unit_cell(filename) if len(cell_params) == 0: @@ -148,9 +146,7 @@ def build_chemical_system(self, atom_lines: List[str]): processed_atom_name[0].upper() + processed_atom_name[1].lower() ) if len(chemical_element) == 2: - chemical_element = ( - chemical_element[0].upper() + chemical_element[1].lower() - ) + chemical_element = chemical_element[0].upper() + chemical_element[1].lower() backup_element = atom_line.rstrip().split()[-1] backup_element2 = atom_line.split()[-2].strip() if atom_name[-2:].isnumeric(): diff --git a/MDANSE/Src/MDANSE/Mathematics/LinearAlgebra.py b/MDANSE/Src/MDANSE/Mathematics/LinearAlgebra.py index 955ffb6169..76550a9228 100644 --- a/MDANSE/Src/MDANSE/Mathematics/LinearAlgebra.py +++ b/MDANSE/Src/MDANSE/Mathematics/LinearAlgebra.py @@ -234,8 +234,7 @@ def angle(self, other): if not is_vector(other): raise TypeError("Angle between vector and non-vector") cosa = np.add.reduce(self.array * other.array) / np.sqrt( - np.add.reduce(self.array * self.array) - * np.add.reduce(other.array * other.array) + np.add.reduce(self.array * self.array) * np.add.reduce(other.array * other.array) ) cosa = max(-1.0, min(1.0, cosa)) return np.arccos(cosa) @@ -559,9 +558,7 @@ def symmetricalPart(self): @raises ValueError: if rank !=2 """ if self.rank == 2: - return Tensor( - 0.5 * (self.array + np.transpose(self.array, np.array([1, 0]))), 1 - ) + return Tensor(0.5 * (self.array + np.transpose(self.array, np.array([1, 0]))), 1) else: raise ValueError("Not yet implemented") @@ -572,9 +569,7 @@ def asymmetricalPart(self): @raises ValueError: if rank !=2 """ if self.rank == 2: - return Tensor( - 0.5 * (self.array - np.transpose(self.array, np.array([1, 0]))), 1 - ) + return Tensor(0.5 * (self.array - np.transpose(self.array, np.array([1, 0]))), 1) else: raise ValueError("Not yet implemented") diff --git a/MDANSE/Src/MDANSE/Mathematics/Transformation.py b/MDANSE/Src/MDANSE/Mathematics/Transformation.py index 2b799819d8..e0bab90a19 100644 --- a/MDANSE/Src/MDANSE/Mathematics/Transformation.py +++ b/MDANSE/Src/MDANSE/Mathematics/Transformation.py @@ -213,9 +213,7 @@ def __mul__(self, other): elif hasattr(other, "is_translation"): return RotationTranslation(self.tensor, self.tensor * other.vector) elif hasattr(other, "is_rotation_translation"): - return RotationTranslation( - self.tensor.dot(other.tensor), self.tensor * other.vector - ) + return RotationTranslation(self.tensor.dot(other.tensor), self.tensor * other.vector) else: return self.asLinearTransformation() * other.asLinearTransformation() @@ -309,8 +307,7 @@ def threeAngles(self, e1, e2, e3, tolerance=1e-7): raise ValueError("FAILURE 1, norm = 0") if abs(_c / _norm) > 1 + tolerance: raise ValueError( - "FAILURE 2" - + "malformed rotation Tensor (non orthogonal?) %.8f" % (_c / _norm) + "FAILURE 2" + "malformed rotation Tensor (non orthogonal?) %.8f" % (_c / _norm) ) # if _c/_norm > 1: raise ValueError('Step1: No solution') _th = angleFromSineAndCosine(_b / _norm, _a / _norm) @@ -407,9 +404,7 @@ def __mul__(self, other): if hasattr(other, "is_rotation"): return RotationTranslation(self.tensor.dot(other.tensor), self.vector) elif hasattr(other, "is_translation"): - return RotationTranslation( - self.tensor, self.tensor * other.vector + self.vector - ) + return RotationTranslation(self.tensor, self.tensor * other.vector + self.vector) elif hasattr(other, "is_rotation_translation"): return RotationTranslation( self.tensor.dot(other.tensor), self.tensor * other.vector + self.vector @@ -441,9 +436,7 @@ def screwMotion(self): angle = 0.0 else: x = d * axis - self.vector - r0 = -0.5 * ( - (np.cos(0.5 * angle) / np.sin(0.5 * angle)) * axis.cross(x) + x - ) + r0 = -0.5 * ((np.cos(0.5 * angle) / np.sin(0.5 * angle)) * axis.cross(x) + x) return r0, axis, angle % (2.0 * np.pi), d @@ -499,15 +492,8 @@ def __init__(self, *args): else: self.tensor = Tensor(args[0]) assert self.tensor.rank == 2 - elif ( - len(args) == 3 - and is_vector(args[0]) - and is_vector(args[1]) - and is_vector(args[2]) - ): - self.tensor = Tensor( - [args[0].array, args[1].array, args[2].array] - ).transpose() + elif len(args) == 3 and is_vector(args[0]) and is_vector(args[1]) and is_vector(args[2]): + self.tensor = Tensor([args[0].array, args[1].array, args[2].array]).transpose() def asLinearTransformation(self): return LinearTransformation(self.tensor, nullVector) @@ -570,9 +556,7 @@ def mod_angle(angle, mod): t = Translation(Vector(1.0, -2.0, 0)) r = Rotation(Vector(0.1, -2.0, 0.5), 1.0e-10) q = r.asQuaternion() - angles = r.threeAngles( - Vector(1.0, 0.0, 0.0), Vector(0.0, 1.0, 0.0), Vector(0.0, 0.0, 1.0) - ) + angles = r.threeAngles(Vector(1.0, 0.0, 0.0), Vector(0.0, 1.0, 0.0), Vector(0.0, 0.0, 1.0)) c = t * r print(c.screwMotion()) s = Scaling(2.0) diff --git a/MDANSE/Src/MDANSE/MolecularDynamics/Analysis.py b/MDANSE/Src/MDANSE/MolecularDynamics/Analysis.py index 668d228c3b..a9c423bb8b 100644 --- a/MDANSE/Src/MDANSE/MolecularDynamics/Analysis.py +++ b/MDANSE/Src/MDANSE/MolecularDynamics/Analysis.py @@ -117,9 +117,7 @@ def mean_square_fluctuation(coords: np.ndarray, root: bool = False) -> float: return msf -def radius_of_gyration( - coords: np.ndarray, masses: np.ndarray = None, root: bool = False -) -> float: +def radius_of_gyration(coords: np.ndarray, masses: np.ndarray = None, root: bool = False) -> float: """ Computes the radius of gyration for a set of coordinates and their corresponding masses. If no masses are provided, all masses are set to 1, in which case the ROG is equivalent to the centre of gravity. The following equation is diff --git a/MDANSE/Src/MDANSE/MolecularDynamics/Configuration.py b/MDANSE/Src/MDANSE/MolecularDynamics/Configuration.py index f34c2f21f0..48857ec6a0 100644 --- a/MDANSE/Src/MDANSE/MolecularDynamics/Configuration.py +++ b/MDANSE/Src/MDANSE/MolecularDynamics/Configuration.py @@ -95,7 +95,6 @@ def contiguous_coordinates_real( scaleconfig = np.matmul(coords, rcell) for idxs in indices: - if len(idxs) < 2: continue if bring_to_centre: @@ -146,7 +145,6 @@ def contiguous_coordinates_box( contiguous_coords = frac_coords.copy() for tupleidxs in indices: - if len(tupleidxs) < 2: continue @@ -460,9 +458,7 @@ def __init__( :param variables: keyword arguments for any other variables that should be saved to this configuration """ - super(_PeriodicConfiguration, self).__init__( - chemical_system, coords, **variables - ) + super(_PeriodicConfiguration, self).__init__(chemical_system, coords, **variables) if unit_cell.direct.shape != (3, 3): raise ValueError("Invalid unit cell dimensions") @@ -479,10 +475,7 @@ def clone(self, chemical_system: Union[ChemicalSystem, None] = None): if chemical_system is None: chemical_system = self._chemical_system else: - if ( - chemical_system.total_number_of_atoms - != self.chemical_system.total_number_of_atoms - ): + if chemical_system.total_number_of_atoms != self.chemical_system.total_number_of_atoms: raise ConfigurationError( "Mismatch between the chemical systems; the provided chemical system, " f"{chemical_system.name}, has {chemical_system.total_number_of_atoms} atoms " @@ -580,9 +573,7 @@ def to_real_configuration(self) -> PeriodicRealConfiguration: return real_conf - def contiguous_configuration( - self, bring_to_centre: bool = False - ) -> PeriodicBoxConfiguration: + def contiguous_configuration(self, bring_to_centre: bool = False) -> PeriodicBoxConfiguration: """ Return a configuration with chemical entities made contiguous. @@ -590,9 +581,7 @@ def contiguous_configuration( :rtype: :class: `MDANSE.MolecularDynamics.Configuration.PeriodicBoxConfiguration` """ - indices_grouped = reduce( - list.__add__, self._chemical_system._clusters.values(), [] - ) + indices_grouped = reduce(list.__add__, self._chemical_system._clusters.values(), []) contiguous_coords = contiguous_coordinates_box( self._variables["coordinates"], @@ -647,9 +636,7 @@ def to_real_coordinates(self) -> np.ndarray: """ return self._variables["coordinates"] - def contiguous_configuration( - self, bring_to_centre: bool = False - ) -> PeriodicRealConfiguration: + def contiguous_configuration(self, bring_to_centre: bool = False) -> PeriodicRealConfiguration: """ Return a configuration with chemical entities made contiguous. @@ -657,9 +644,7 @@ def contiguous_configuration( :rtype: :class: `MDANSE.MolecularDynamics.Configuration.PeriodicBoxConfiguration` """ - indices_grouped = reduce( - list.__add__, self._chemical_system._clusters.values(), [] - ) + indices_grouped = reduce(list.__add__, self._chemical_system._clusters.values(), []) contiguous_coords = contiguous_coordinates_real( self._variables["coordinates"], @@ -696,9 +681,7 @@ def continuous_configuration(self) -> PeriodicRealConfiguration: class RealConfiguration(_Configuration): is_periodic = False - def clone( - self, chemical_system: Union[None, ChemicalSystem] = None - ) -> RealConfiguration: + def clone(self, chemical_system: Union[None, ChemicalSystem] = None) -> RealConfiguration: """ Creates a deep copy of this configuration, using the provided chemical system. @@ -712,10 +695,7 @@ def clone( if chemical_system is None: chemical_system = self._chemical_system else: - if ( - chemical_system.total_number_of_atoms - != self.chemical_system.total_number_of_atoms - ): + if chemical_system.total_number_of_atoms != self.chemical_system.total_number_of_atoms: raise ConfigurationError("Mismatch between the chemical systems") variables = copy.deepcopy(self.variables) @@ -737,9 +717,7 @@ def to_real_coordinates(self) -> np.ndarray: """ return self._variables["coordinates"] - def contiguous_configuration( - self, bring_to_centre: bool = False - ) -> RealConfiguration: + def contiguous_configuration(self, bring_to_centre: bool = False) -> RealConfiguration: """ Return a configuration with chemical entities made contiguous, which is always itself. diff --git a/MDANSE/Src/MDANSE/MolecularDynamics/Connectivity.py b/MDANSE/Src/MDANSE/MolecularDynamics/Connectivity.py index a4f2b0841b..8c2a7812f5 100644 --- a/MDANSE/Src/MDANSE/MolecularDynamics/Connectivity.py +++ b/MDANSE/Src/MDANSE/MolecularDynamics/Connectivity.py @@ -58,9 +58,7 @@ def check_composition(self, chemical: ChemicalSystem): chemical -- ChemicalSystem instance connected to the trajectory. """ if self._selection is not None: - atom_elements = [ - self._chemical_system.atom_list[index] for index in self._selection - ] + atom_elements = [self._chemical_system.atom_list[index] for index in self._selection] else: atom_elements = self._chemical_system.atom_list unique_elements = np.unique(atom_elements) diff --git a/MDANSE/Src/MDANSE/MolecularDynamics/MockTrajectory.py b/MDANSE/Src/MDANSE/MolecularDynamics/MockTrajectory.py index 91c8185939..ba77b894ab 100644 --- a/MDANSE/Src/MDANSE/MolecularDynamics/MockTrajectory.py +++ b/MDANSE/Src/MDANSE/MolecularDynamics/MockTrajectory.py @@ -61,9 +61,7 @@ def __init__( self._multiplier = multiplier self._pbc = pbc self._time_step = time_step * measure(1.0, "fs").toval("ps") - self._time_axis = np.arange( - 0.0, number_of_frames * self._time_step, self._time_step - ) + self._time_axis = np.arange(0.0, number_of_frames * self._time_step, self._time_step) self._box_size = box_size * measure(1.0, "ang").toval("nm") self._real_length = 0 self._num_atoms_in_box = len(atoms_in_box) @@ -162,9 +160,7 @@ def modulate_structure( if current_steps < period: step = math.gcd([current_steps, period]) while len(self._coordinates) < period: - self._coordinates = np.vstack( - [self._coordinates, self._coordinates[-step:]] - ) + self._coordinates = np.vstack([self._coordinates, self._coordinates[-step:]]) nm_amp = amplitude * measure(1.0, "ang").toval("nm") unit_cell = UnitCell(self._full_box_size) inverse_cell = unit_cell._inverse_unit_cell @@ -334,9 +330,7 @@ def __len__(self) -> int: return self._number_of_frames - def read_com_trajectory( - self, indices, first=0, last=None, step=1, box_coordinates=False - ): + def read_com_trajectory(self, indices, first=0, last=None, step=1, box_coordinates=False): """Build the trajectory of the center of mass of a set of atoms. :param atoms: the atoms for which the center of mass should be computed @@ -358,10 +352,7 @@ def read_com_trajectory( last = len(self) masses = np.array( - [ - self.chemical_system.atom_property("atomic_weight")[index] - for index in indices - ] + [self.chemical_system.atom_property("atomic_weight")[index] for index in indices] ) frames = np.array([self.coordinates(fnum) for fnum in range(first, last, step)]) @@ -385,18 +376,13 @@ def read_com_trajectory( bring_to_centre=True, ) com_coords = np.vstack( - [ - center_of_mass(temp_coords[tstep], masses) - for tstep in range(len(temp_coords)) - ] + [center_of_mass(temp_coords[tstep], masses) for tstep in range(len(temp_coords))] ) com_traj = atomic_trajectory(com_coords, direct_cells, inverse_cells) else: - com_traj = np.sum( - coords[:, indices, :] * masses[np.newaxis, :, np.newaxis], axis=1 - ) + com_traj = np.sum(coords[:, indices, :] * masses[np.newaxis, :, np.newaxis], axis=1) com_traj /= np.sum(masses) return com_traj @@ -422,17 +408,13 @@ def to_real_coordinates(self, box_coordinates, first, last, step): comp = 0 for i in range(first, last, step): direct_cell = self.unit_cell(i).transposed_direct - real_coordinates[comp, :] = np.matmul( - direct_cell, box_coordinates[comp, :] - ) + real_coordinates[comp, :] = np.matmul(direct_cell, box_coordinates[comp, :]) comp += 1 return real_coordinates else: return box_coordinates - def read_atomic_trajectory( - self, index, first=0, last=None, step=1, box_coordinates=False - ): + def read_atomic_trajectory(self, index, first=0, last=None, step=1, box_coordinates=False): """Read an atomic trajectory. The trajectory is corrected from box jumps. :param index: the index of the atom @@ -458,20 +440,12 @@ def read_atomic_trajectory( if self._pbc: direct_cells = np.array( - [ - self.unit_cell(fnum).transposed_direct - for fnum in range(first, last, step) - ] + [self.unit_cell(fnum).transposed_direct for fnum in range(first, last, step)] ) inverse_cells = np.array( - [ - self.unit_cell(fnum).transposed_inverse - for fnum in range(first, last, step) - ] - ) - atomic_traj = atomic_trajectory( - coords, direct_cells, inverse_cells, box_coordinates + [self.unit_cell(fnum).transposed_inverse for fnum in range(first, last, step)] ) + atomic_traj = atomic_trajectory(coords, direct_cells, inverse_cells, box_coordinates) return atomic_traj else: return coords @@ -502,9 +476,7 @@ def read_configuration_trajectory( grp = self._variables if variable not in grp: - raise KeyError( - "The variable {} is not stored in the trajectory".format(variable) - ) + raise KeyError("The variable {} is not stored in the trajectory".format(variable)) variable = grp[variable][first:last:step, index, :].astype(np.float64) diff --git a/MDANSE/Src/MDANSE/MolecularDynamics/Trajectory.py b/MDANSE/Src/MDANSE/MolecularDynamics/Trajectory.py index 8be6f992c3..e76817a445 100644 --- a/MDANSE/Src/MDANSE/MolecularDynamics/Trajectory.py +++ b/MDANSE/Src/MDANSE/MolecularDynamics/Trajectory.py @@ -176,9 +176,7 @@ def min_span(self): self.calculate_coordinate_span() return self._min_span - def read_com_trajectory( - self, atom_indices, first=0, last=None, step=1, box_coordinates=False - ): + def read_com_trajectory(self, atom_indices, first=0, last=None, step=1, box_coordinates=False): """Build the trajectory of the center of mass of a set of atoms. :param atoms: the atoms for which the center of mass should be computed @@ -220,9 +218,7 @@ def to_real_coordinates(self, box_coordinates, first, last, step): """ return self._trajectory.to_real_coordinates(box_coordinates, first, last, step) - def read_atomic_trajectory( - self, index, first=0, last=None, step=1, box_coordinates=False - ): + def read_atomic_trajectory(self, index, first=0, last=None, step=1, box_coordinates=False): """Read an atomic trajectory. The trajectory is corrected for box jumps. :param index: the index of the atom @@ -285,8 +281,8 @@ def has_variable(self, variable: str) -> bool: def get_atom_property(self, atom_symbol: str, property: str): if (atom_symbol, property) not in self._atom_cache.keys(): - self._atom_cache[(atom_symbol, property)] = ( - self._trajectory.get_atom_property(atom_symbol, property) + self._atom_cache[(atom_symbol, property)] = self._trajectory.get_atom_property( + atom_symbol, property ) return self._atom_cache[(atom_symbol, property)] @@ -417,9 +413,7 @@ def create_average_atom( temp = [] total = 0 for element_name, element_count in atom_dictionary.items(): - temp.append( - [database.get_atom_property(element_name, property), element_count] - ) + temp.append([database.get_atom_property(element_name, property), element_count]) if property in additive_atom_properties: total = np.sum([float(x[0]) * int(x[1]) for x in temp]) elif property in averaged_atom_properties: @@ -430,8 +424,7 @@ def create_average_atom( total = constant_atom_properties[property] elif property in atom_radii: total = ( - np.sum([float(x[0]) * int(x[1]) for x in temp]) - / np.sum([int(x[1]) for x in temp]) + np.sum([float(x[0]) * int(x[1]) for x in temp]) / np.sum([int(x[1]) for x in temp]) + radius_padding ) else: @@ -516,9 +509,7 @@ def __init__( self._chunking_limit = self._n_atoms else: self._chunk_tuple = (1, chunking_limit, 3) - self._padded_size = ( - math.ceil(self._n_atoms / chunking_limit) * chunking_limit - ) + self._padded_size = math.ceil(self._n_atoms / chunking_limit) * chunking_limit self._chunking_limit = chunking_limit self._compression = compression @@ -543,9 +534,7 @@ def write_atom_properties( else: label_dataset = self._h5_file["/atom_database/property_labels"] if "property_types" not in group: - type_dataset = group.create_dataset( - "property_types", data=200 * [""], dtype=string_dt - ) + type_dataset = group.create_dataset("property_types", data=200 * [""], dtype=string_dt) else: type_dataset = self._h5_file["/atom_database/property_types"] next_index = 0 @@ -587,9 +576,7 @@ def write_atom_properties( colour = [int(x) for x in properties["color"].split(";")] except AttributeError: colour = [int(x) for x in properties["color"][0].split(";")] - atom_dataset[mapping["color"]] = ( - 0x10000 * colour[0] + 0x100 * colour[1] + colour[2] - ) + atom_dataset[mapping["color"]] = 0x10000 * colour[0] + 0x100 * colour[1] + colour[2] def write_atom_database( self, @@ -623,9 +610,7 @@ def write_atom_database( atom_dict, database, radius_padding=molecule_radius ) if hasattr(database, "_properties"): - self.write_atom_properties( - atom_symbol, property_dict, database._properties - ) + self.write_atom_properties(atom_symbol, property_dict, database._properties) else: self.write_atom_properties(atom_symbol, property_dict) @@ -858,9 +843,7 @@ def __init__( possq = np.zeros((n_steps,), np.float64) cross = np.zeros((n_steps, 3, 3), np.float64) - rcms = self._trajectory.read_com_trajectory( - atoms, first, last, step, box_coordinates=True - ) + rcms = self._trajectory.read_com_trajectory(atoms, first, last, step, box_coordinates=True) # relative coords of the CONTIGUOUS reference r_ref = np.zeros((len(atoms), 3), np.float64) diff --git a/MDANSE/Src/MDANSE/MolecularDynamics/TrajectoryUtils.py b/MDANSE/Src/MDANSE/MolecularDynamics/TrajectoryUtils.py index 3f27c1519b..b0e82d7e5b 100644 --- a/MDANSE/Src/MDANSE/MolecularDynamics/TrajectoryUtils.py +++ b/MDANSE/Src/MDANSE/MolecularDynamics/TrajectoryUtils.py @@ -77,7 +77,6 @@ def find_atoms_in_molecule( atom_names: list[str], indices: bool = False, ) -> list[list[int]]: - if entity_name not in chemical_system._clusters: return [] diff --git a/MDANSE/Src/MDANSE/NeutronInstruments/Coverage/__init__.py b/MDANSE/Src/MDANSE/NeutronInstruments/Coverage/__init__.py index 4caf3ac941..41575c1fb8 100644 --- a/MDANSE/Src/MDANSE/NeutronInstruments/Coverage/__init__.py +++ b/MDANSE/Src/MDANSE/NeutronInstruments/Coverage/__init__.py @@ -38,9 +38,7 @@ if name in ["__init__"]: continue try: - tempmod = importlib.import_module( - "." + name, "MDANSE.NeutronInstruments.Coverage" - ) + tempmod = importlib.import_module("." + name, "MDANSE.NeutronInstruments.Coverage") except ModuleNotFoundError: continue tempobject = getattr(tempmod, name) diff --git a/MDANSE/Src/MDANSE/NeutronInstruments/Method/__init__.py b/MDANSE/Src/MDANSE/NeutronInstruments/Method/__init__.py index b326884607..7210472471 100644 --- a/MDANSE/Src/MDANSE/NeutronInstruments/Method/__init__.py +++ b/MDANSE/Src/MDANSE/NeutronInstruments/Method/__init__.py @@ -25,7 +25,6 @@ performed. Initially, the plan is to start with time-of-flight diffraction, direct and indirect spectrometry.""" - import glob import importlib import os @@ -44,9 +43,7 @@ if name in ["__init__"]: continue try: - tempmod = importlib.import_module( - "." + name, "MDANSE.NeutronInstruments.Method" - ) + tempmod = importlib.import_module("." + name, "MDANSE.NeutronInstruments.Method") except ModuleNotFoundError: continue tempobject = getattr(tempmod, name) diff --git a/MDANSE/Src/MDANSE/NeutronInstruments/Resolution/__init__.py b/MDANSE/Src/MDANSE/NeutronInstruments/Resolution/__init__.py index b7b0c32c4a..99e5e4b86e 100644 --- a/MDANSE/Src/MDANSE/NeutronInstruments/Resolution/__init__.py +++ b/MDANSE/Src/MDANSE/NeutronInstruments/Resolution/__init__.py @@ -41,9 +41,7 @@ if name in ["__init__"]: continue try: - tempmod = importlib.import_module( - "." + name, "MDANSE.NeutronInstruments.Resolution" - ) + tempmod = importlib.import_module("." + name, "MDANSE.NeutronInstruments.Resolution") except ModuleNotFoundError: continue tempobject = getattr(tempmod, name) diff --git a/MDANSE/Src/MDANSE/NeutronInstruments/Spectrum/__init__.py b/MDANSE/Src/MDANSE/NeutronInstruments/Spectrum/__init__.py index a80b96f6a0..f2ef73a0cd 100644 --- a/MDANSE/Src/MDANSE/NeutronInstruments/Spectrum/__init__.py +++ b/MDANSE/Src/MDANSE/NeutronInstruments/Spectrum/__init__.py @@ -40,9 +40,7 @@ if name in ["__init__"]: continue try: - tempmod = importlib.import_module( - "." + name, "MDANSE.NeutronInstruments.Spectrum" - ) + tempmod = importlib.import_module("." + name, "MDANSE.NeutronInstruments.Spectrum") except ModuleNotFoundError: continue tempobject = getattr(tempmod, name) diff --git a/MDANSE/Src/MDANSE/Scripts/mdanse.py b/MDANSE/Src/MDANSE/Scripts/mdanse.py index 4d5db5afac..742a55f12f 100644 --- a/MDANSE/Src/MDANSE/Scripts/mdanse.py +++ b/MDANSE/Src/MDANSE/Scripts/mdanse.py @@ -45,9 +45,7 @@ def format_description(self, description): indent = " " * self.current_indent bits = description.split("\n") formatted_bits = [ - textwrap.fill( - bit, desc_width, initial_indent=indent, subsequent_indent=indent - ) + textwrap.fill(bit, desc_width, initial_indent=indent, subsequent_indent=indent) for bit in bits ] result = "\n".join(formatted_bits) + "\n" @@ -73,9 +71,7 @@ def format_option(self, option): help_lines.extend(textwrap.wrap(para, self.help_width)) # Everything is the same after here result.append("%*s%s\n" % (indent_first, "", help_lines[0])) - result.extend( - ["%*s%s\n" % (self.help_position, "", line) for line in help_lines[1:]] - ) + result.extend(["%*s%s\n" % (self.help_position, "", line) for line in help_lines[1:]]) elif opts[-1] != "\n": result.append("\n") @@ -112,9 +108,7 @@ def check_job(self, option, opt_str, value, parser): """ if len(parser.rargs) != 1: - raise CommandLineParserError( - "Invalid number of arguments for %r option" % opt_str - ) + raise CommandLineParserError("Invalid number of arguments for %r option" % opt_str) basename = parser.rargs[0] @@ -131,9 +125,7 @@ def check_job(self, option, opt_str, value, parser): # If the file could not be opened/unpickled for whatever reason, try at the next checkpoint except Exception: - raise CommandLineParserError( - "The job %r could not be opened properly." % basename - ) + raise CommandLineParserError("The job %r could not be opened properly." % basename) # The job file could be opened and unpickled properly else: @@ -147,9 +139,7 @@ def check_job(self, option, opt_str, value, parser): def display_element_info(self, option, opt_str, value, parser): if len(parser.rargs) != 1: - raise CommandLineParserError( - "Invalid number of arguments for %r option" % opt_str - ) + raise CommandLineParserError("Invalid number of arguments for %r option" % opt_str) element = parser.rargs[0] @@ -158,9 +148,7 @@ def display_element_info(self, option, opt_str, value, parser): try: LOG.info(ATOMS_DATABASE.info(element)) except ValueError: - raise CommandLineParserError( - "The entry %r is not registered in the database" % element - ) + raise CommandLineParserError("The entry %r is not registered in the database" % element) def display_jobs_list(self, option, opt_str, value, parser): """Display the jobs list @@ -179,14 +167,9 @@ def display_jobs_list(self, option, opt_str, value, parser): """ if len(parser.rargs) != 0: - raise CommandLineParserError( - "Invalid number of arguments for %r option" % opt_str - ) + raise CommandLineParserError("Invalid number of arguments for %r option" % opt_str) - jobs = [ - f - for f in glob.glob(os.path.join(PLATFORM.temporary_files_directory(), "*")) - ] + jobs = [f for f in glob.glob(os.path.join(PLATFORM.temporary_files_directory(), "*"))] for j in jobs: # Open the job temporary file @@ -258,9 +241,7 @@ def query_classes_registry(self, option, opt_str, value, parser): val = parser.rargs[0] LOG.info(IJob.create(val).info()) else: - raise CommandLineParserError( - "Invalid number of arguments for %r option" % opt_str - ) + raise CommandLineParserError("Invalid number of arguments for %r option" % opt_str) def run_job(self, option, opt_str, value, parser): """Run job file(s). @@ -279,16 +260,12 @@ def run_job(self, option, opt_str, value, parser): """ if len(parser.rargs) != 1: - raise CommandLineParserError( - "Invalid number of arguments for %r option" % opt_str - ) + raise CommandLineParserError("Invalid number of arguments for %r option" % opt_str) filename = parser.rargs[0] if not os.path.exists(filename): - raise CommandLineParserError( - "The job file %r could not be executed" % filename - ) + raise CommandLineParserError("The job file %r could not be executed" % filename) subprocess.Popen([sys.executable, filename]) @@ -310,9 +287,7 @@ def save_job(self, option, opt_str, value, parser): """ if len(parser.rargs) != 1: - raise CommandLineParserError( - "Invalid number of arguments for %r option" % opt_str - ) + raise CommandLineParserError("Invalid number of arguments for %r option" % opt_str) jobs = IJob @@ -326,9 +301,7 @@ def save_job(self, option, opt_str, value, parser): jobs.create(name).save(filename) # Case where an error occured when writing the template. except IOError: - raise CommandLineParserError( - "Could not write the job template as %r" % filename - ) + raise CommandLineParserError("Could not write the job template as %r" % filename) # If the job class has no save method, thisis not a valid MDANSE job. except KeyError: raise CommandLineParserError("The job %r is not a valid MDANSE job" % name) @@ -375,9 +348,7 @@ def main(): import MDANSE # Creates the option parser. - parser = CommandLineParser( - formatter=IndentedHelp(), version="MDANSE %s " % MDANSE.__version__ - ) + parser = CommandLineParser(formatter=IndentedHelp(), version="MDANSE %s " % MDANSE.__version__) # Creates a first the group of general options. group = optparse.OptionGroup(parser, "General options") @@ -424,9 +395,7 @@ def main(): callback=parser.display_jobs_list, help="Display the jobs list.", ) - group.add_option( - "--jr", action="callback", callback=parser.run_job, help="Run MDANSE job(s)." - ) + group.add_option("--jr", action="callback", callback=parser.run_job, help="Run MDANSE job(s).") group.add_option( "--js", action="callback", diff --git a/MDANSE/Src/MDANSE/Trajectory/H5MDTrajectory.py b/MDANSE/Src/MDANSE/Trajectory/H5MDTrajectory.py index 32dd79aca7..29190686ae 100644 --- a/MDANSE/Src/MDANSE/Trajectory/H5MDTrajectory.py +++ b/MDANSE/Src/MDANSE/Trajectory/H5MDTrajectory.py @@ -127,9 +127,9 @@ def __getitem__(self, frame): vel_unit = self._h5_file["/particles/all/velocity/value"].attrs["unit"] except Exception: vel_unit = "ang/fs" - configuration["velocities"] = self._h5_file[ - "/particles/all/velocity/value" - ][frame, :, :] * measure(1.0, vel_unit).toval("nm/ps") + configuration["velocities"] = self._h5_file["/particles/all/velocity/value"][ + frame, :, : + ] * measure(1.0, vel_unit).toval("nm/ps") except Exception: pass @@ -313,9 +313,7 @@ def __len__(self): return grp.shape[0] - def read_com_trajectory( - self, atom_indices, first=0, last=None, step=1, box_coordinates=False - ): + def read_com_trajectory(self, atom_indices, first=0, last=None, step=1, box_coordinates=False): """Build the trajectory of the center of mass of a set of atoms. :param atoms: the atoms for which the center of mass should be computed @@ -348,20 +346,13 @@ def read_com_trajectory( atoms = self.chemical_system.atom_list try: - masses = self._h5_file["/particles/all/mass/value"][atom_indices].astype( - np.float64 - ) + masses = self._h5_file["/particles/all/mass/value"][atom_indices].astype(np.float64) except KeyError: try: - masses = self._h5_file["/particles/all/mass"][atom_indices].astype( - np.float64 - ) + masses = self._h5_file["/particles/all/mass"][atom_indices].astype(np.float64) except KeyError: masses = np.array( - [ - ATOMS_DATABASE.get_atom_property(at, "atomic_weight") - for at in atoms - ] + [ATOMS_DATABASE.get_atom_property(at, "atomic_weight") for at in atoms] )[atom_indices] grp = self._h5_file["/particles/all/position/value"] try: @@ -379,9 +370,7 @@ def read_com_trajectory( coords = coords[np.newaxis, :, :] if self._unit_cells is not None: - direct_cells = np.array( - [self.unit_cell(nf).direct for nf in range(first, last, step)] - ) + direct_cells = np.array([self.unit_cell(nf).direct for nf in range(first, last, step)]) inverse_cells = np.array( [self.unit_cell(nf).inverse for nf in range(first, last, step)] ) @@ -393,10 +382,7 @@ def read_com_trajectory( bring_to_centre=True, ) com_coords = np.vstack( - [ - center_of_mass(temp_coords[tstep], masses) - for tstep in range(len(temp_coords)) - ] + [center_of_mass(temp_coords[tstep], masses) for tstep in range(len(temp_coords))] ) com_traj = atomic_trajectory(com_coords, direct_cells, inverse_cells) @@ -430,17 +416,13 @@ def to_real_coordinates(self, box_coordinates, first, last, step): comp = 0 for i in range(first, last, step): direct_cell = self.unit_cell(i).transposed_direct - real_coordinates[comp, :] = np.matmul( - direct_cell, box_coordinates[comp, :] - ) + real_coordinates[comp, :] = np.matmul(direct_cell, box_coordinates[comp, :]) comp += 1 return real_coordinates else: return box_coordinates - def read_atomic_trajectory( - self, index, first=0, last=None, step=1, box_coordinates=False - ): + def read_atomic_trajectory(self, index, first=0, last=None, step=1, box_coordinates=False): """Read an atomic trajectory. The trajectory is corrected from box jumps. :param index: the index of the atom @@ -474,20 +456,12 @@ def read_atomic_trajectory( if self._unit_cells is not None: direct_cells = np.array( - [ - self.unit_cell(nf).transposed_direct - for nf in range(first, last, step) - ] + [self.unit_cell(nf).transposed_direct for nf in range(first, last, step)] ) inverse_cells = np.array( - [ - self.unit_cell(nf).transposed_inverse - for nf in range(first, last, step) - ] - ) - atomic_traj = atomic_trajectory( - coords, direct_cells, inverse_cells, box_coordinates + [self.unit_cell(nf).transposed_inverse for nf in range(first, last, step)] ) + atomic_traj = atomic_trajectory(coords, direct_cells, inverse_cells, box_coordinates) return atomic_traj else: return coords @@ -516,9 +490,7 @@ def read_configuration_trajectory( last = len(self) if not self.has_variable(variable): - raise KeyError( - "The variable {} is not stored in the trajectory".format(variable) - ) + raise KeyError("The variable {} is not stored in the trajectory".format(variable)) grp = self._h5_file["/particles/all"] variable = grp[variable]["value"][first:last:step, index, :].astype(np.float64) diff --git a/MDANSE/Src/MDANSE/Trajectory/MdanseTrajectory.py b/MDANSE/Src/MDANSE/Trajectory/MdanseTrajectory.py index c9387179f4..66bd1fb164 100644 --- a/MDANSE/Src/MDANSE/Trajectory/MdanseTrajectory.py +++ b/MDANSE/Src/MDANSE/Trajectory/MdanseTrajectory.py @@ -70,9 +70,7 @@ def file_is_right(self, filename): result = False else: try: - temp_cs = ChemicalSystem( - os.path.splitext(os.path.basename(filename))[0] - ) + temp_cs = ChemicalSystem(os.path.splitext(os.path.basename(filename))[0]) temp_cs.load(file_object) except Exception: LOG.warning( @@ -234,9 +232,7 @@ def __len__(self): return grp["coordinates"].shape[0] - def read_com_trajectory( - self, atom_indices, first=0, last=None, step=1, box_coordinates=False - ): + def read_com_trajectory(self, atom_indices, first=0, last=None, step=1, box_coordinates=False): """Build the trajectory of the center of mass of a set of atoms. :param atoms: the atoms for which the center of mass should be computed @@ -284,12 +280,8 @@ def read_com_trajectory( coords = coords[np.newaxis, :, :] if self._unit_cells is not None: - direct_cells = np.array( - [uc.direct for uc in self._unit_cells[first:last:step]] - ) - inverse_cells = np.array( - [uc.inverse for uc in self._unit_cells[first:last:step]] - ) + direct_cells = np.array([uc.direct for uc in self._unit_cells[first:last:step]]) + inverse_cells = np.array([uc.inverse for uc in self._unit_cells[first:last:step]]) temp_coords = contiguous_coordinates_real( coords, direct_cells, @@ -298,10 +290,7 @@ def read_com_trajectory( bring_to_centre=True, ) com_coords = np.vstack( - [ - center_of_mass(temp_coords[tstep], masses) - for tstep in range(len(temp_coords)) - ] + [center_of_mass(temp_coords[tstep], masses) for tstep in range(len(temp_coords))] ) com_traj = atomic_trajectory(com_coords, direct_cells, inverse_cells) @@ -335,17 +324,13 @@ def to_real_coordinates(self, box_coordinates, first, last, step): comp = 0 for i in range(first, last, step): direct_cell = self._unit_cells[i].transposed_direct - real_coordinates[comp, :] = np.matmul( - direct_cell, box_coordinates[comp, :] - ) + real_coordinates[comp, :] = np.matmul(direct_cell, box_coordinates[comp, :]) comp += 1 return real_coordinates else: return box_coordinates - def read_atomic_trajectory( - self, index, first=0, last=None, step=1, box_coordinates=False - ): + def read_atomic_trajectory(self, index, first=0, last=None, step=1, box_coordinates=False): """Read an atomic trajectory. The trajectory is corrected from box jumps. :param index: the index of the atom @@ -371,20 +356,12 @@ def read_atomic_trajectory( if self._unit_cells is not None: direct_cells = np.array( - [ - self._unit_cells[nf].transposed_direct - for nf in range(first, last, step) - ] + [self._unit_cells[nf].transposed_direct for nf in range(first, last, step)] ) inverse_cells = np.array( - [ - self._unit_cells[nf].transposed_inverse - for nf in range(first, last, step) - ] - ) - atomic_traj = atomic_trajectory( - coords, direct_cells, inverse_cells, box_coordinates + [self._unit_cells[nf].transposed_inverse for nf in range(first, last, step)] ) + atomic_traj = atomic_trajectory(coords, direct_cells, inverse_cells, box_coordinates) return atomic_traj else: return coords @@ -413,9 +390,7 @@ def read_configuration_trajectory( last = len(self) if not self.has_variable(variable): - raise KeyError( - "The variable {} is not stored in the trajectory".format(variable) - ) + raise KeyError("The variable {} is not stored in the trajectory".format(variable)) grp = self._h5_file["/configuration"] variable = grp[variable][first:last:step, index, :].astype(np.float64) @@ -447,22 +422,17 @@ def get_atom_property(self, symbol: str, property: str): elif symbol not in self._h5_file["/atom_database"]: return ATOMS_DATABASE.get_atom_property(symbol, property) temp = np.where( - self._h5_file["/atom_database/property_labels"][:] - == property.encode("utf-8") + self._h5_file["/atom_database/property_labels"][:] == property.encode("utf-8") )[0] if len(temp) == 0: if property == "dummy": try: return ATOMS_DATABASE.get_atom_property(symbol, property) except KeyError: - if ( - "_" in symbol - ): # this is most likely an artificial atom from a molecule + if "_" in symbol: # this is most likely an artificial atom from a molecule return 0 # the molecule atoms are not dummy else: - raise KeyError( - f"Property {property} is not in the trajectory's internal database." - ) + raise KeyError(f"Property {property} is not in the trajectory's internal database.") index = temp.flatten()[0] data_type = self._h5_file["/atom_database/property_types"][index] value = self._h5_file[f"/atom_database/{symbol}"][index] @@ -486,8 +456,7 @@ def properties_in_database(self) -> List[str]: return ATOMS_DATABASE.properties else: return list( - label.decode("utf-8") - for label in self._h5_file["/atom_database/property_labels"] + label.decode("utf-8") for label in self._h5_file["/atom_database/property_labels"] ) @property