From 3691d09ab71efcebfe3ee3675e1c521bfc7b6679 Mon Sep 17 00:00:00 2001 From: Jacob Wilkins Date: Mon, 27 Jan 2025 11:08:34 +0000 Subject: [PATCH 1/2] First stage of string modernisation --- MDANSE/Src/MDANSE/Chemistry/Databases.py | 7 +- MDANSE/Src/MDANSE/Framework/Configurable.py | 66 ++++---------- .../Configurators/AseInputFileConfigurator.py | 2 +- .../AtomSelectionConfigurator.py | 4 +- .../AtomTransmutationConfigurator.py | 2 +- .../Configurators/AtomsListConfigurator.py | 16 ++-- .../AxisSelectionConfigurator.py | 14 +-- .../BasisSelectionConfigurator.py | 14 +-- .../Configurators/BooleanConfigurator.py | 2 +- .../Configurators/FloatConfigurator.py | 2 +- .../Configurators/FramesConfigurator.py | 13 +-- .../GroupingLevelConfigurator.py | 2 +- .../Configurators/HDFInputFileConfigurator.py | 4 +- .../HDFTrajectoryConfigurator.py | 7 +- .../Framework/Configurators/IConfigurator.py | 5 +- .../InputDirectoryConfigurator.py | 2 +- .../InstrumentResolutionConfigurator.py | 8 +- .../Configurators/IntegerConfigurator.py | 2 +- .../MDMCTrajectoryConfigurator.py | 5 +- .../McStasOptionsConfigurator.py | 4 +- .../McStasParametersConfigurator.py | 4 +- .../MockTrajectoryConfigurator.py | 5 +- .../MultipleChoicesConfigurator.py | 2 +- .../OptionalFloatConfigurator.py | 2 +- .../OutputDirectoryConfigurator.py | 2 +- .../OutputTrajectoryConfigurator.py | 2 +- .../Configurators/ProjectionConfigurator.py | 6 +- .../Configurators/PythonObjectConfigurator.py | 2 +- .../Configurators/QVectorsConfigurator.py | 10 +-- .../Configurators/RangeConfigurator.py | 6 +- .../Configurators/RunningModeConfigurator.py | 4 +- .../Configurators/SingleChoiceConfigurator.py | 2 +- .../SingleOutputFileConfigurator.py | 2 +- .../Configurators/StringConfigurator.py | 2 +- .../TrajectoryVariableConfigurator.py | 2 +- .../Configurators/UnitCellConfigurator.py | 2 +- .../Configurators/VectorConfigurator.py | 2 +- .../Configurators/WeightsConfigurator.py | 2 +- .../Configurators/XYZFileConfigurator.py | 2 +- MDANSE/Src/MDANSE/Framework/Converters/DCD.py | 4 +- .../MDANSE/Framework/Converters/Discover.py | 36 +++----- .../MDANSE/Framework/Converters/Forcite.py | 48 +++++------ .../MDANSE/Framework/Converters/Gromacs.py | 2 +- .../Src/MDANSE/Framework/Formats/SVGFormat.py | 6 +- .../MDANSE/Framework/Formats/TextFormat.py | 19 ++--- .../InputData/HDFTrajectoryInputData.py | 14 +-- .../InputData/MockTrajectoryInputData.py | 7 +- .../MDANSE/Framework/Jobs/AreaPerMolecule.py | 4 +- .../Framework/Jobs/CoordinationNumber.py | 26 +++--- .../Jobs/CurrentCorrelationFunction.py | 30 ++++--- .../MDANSE/Framework/Jobs/DensityOfStates.py | 12 +-- .../MDANSE/Framework/Jobs/DensityProfile.py | 6 +- .../Jobs/DynamicCoherentStructureFactor.py | 15 ++-- .../Jobs/DynamicIncoherentStructureFactor.py | 10 +-- .../Jobs/ElasticIncoherentStructureFactor.py | 6 +- ...aussianDynamicIncoherentStructureFactor.py | 12 +-- .../Jobs/GeneralAutoCorrelationFunction.py | 4 +- MDANSE/Src/MDANSE/Framework/Jobs/IJob.py | 41 ++++----- .../Framework/Jobs/McStasVirtualInstrument.py | 16 ++-- .../Framework/Jobs/MeanSquareDisplacement.py | 6 +- .../NeutronDynamicTotalStructureFactor.py | 49 +++++------ .../Jobs/PairDistributionFunction.py | 26 +++--- .../Jobs/PositionAutoCorrelationFunction.py | 12 +-- .../Framework/Jobs/PositionPowerSpectrum.py | 12 +-- .../Framework/Jobs/RigidBodyTrajectory.py | 9 +- .../Framework/Jobs/RootMeanSquareDeviation.py | 2 +- .../Framework/Jobs/StaticStructureFactor.py | 17 ++-- .../StructureFactorFromScatteringFunction.py | 4 +- .../Framework/Jobs/VanHoveFunctionDistinct.py | 12 +-- .../Framework/Jobs/VanHoveFunctionSelf.py | 8 +- .../Jobs/VelocityAutoCorrelationFunction.py | 10 +-- .../Jobs/XRayStaticStructureFactor.py | 21 ++--- .../OutputVariables/IOutputVariable.py | 18 ++-- MDANSE/Src/MDANSE/Framework/Units.py | 42 +++------ .../MDANSE/Framework/UserDefinitionStore.py | 4 +- MDANSE/Src/MDANSE/IO/FortranFormat.py | 8 +- MDANSE/Src/MDANSE/Mathematics/Arithmetic.py | 2 +- .../Src/MDANSE/Mathematics/LinearAlgebra.py | 6 +- .../Src/MDANSE/Mathematics/Transformation.py | 3 +- MDANSE/Src/MDANSE/Scripts/mdanse.py | 85 +++++++------------ 80 files changed, 398 insertions(+), 518 deletions(-) diff --git a/MDANSE/Src/MDANSE/Chemistry/Databases.py b/MDANSE/Src/MDANSE/Chemistry/Databases.py index e7b52792d4..9448344bf1 100644 --- a/MDANSE/Src/MDANSE/Chemistry/Databases.py +++ b/MDANSE/Src/MDANSE/Chemistry/Databases.py @@ -480,18 +480,19 @@ def info(self, atom: str) -> str: # A delimiter line. delimiter = "-" * 70 + tab_fmt = "{:<20}{:>50}" info = [ delimiter, - "%s" % atom.center(70), - "%s" % " {0:<20}{1:>50}".format("property", "value"), + f"{atom:^70}", + tab_fmt.format("property", "value"), delimiter, ] # 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))) + tab_fmt.format(pname, self._data[atom].get(pname, None)) ) info.append(delimiter) diff --git a/MDANSE/Src/MDANSE/Framework/Configurable.py b/MDANSE/Src/MDANSE/Framework/Configurable.py index bedb732b5d..2d68c083a0 100644 --- a/MDANSE/Src/MDANSE/Framework/Configurable.py +++ b/MDANSE/Src/MDANSE/Framework/Configurable.py @@ -31,14 +31,14 @@ class ConfigurationError(Error): class Configurable(object): """ This class allows any object that derives from it to be configurable within the MDANSE framework. - + Within that framework, to be configurable, a class must: #. derive from this class #. implement the "configurators" class attribute as a list of 3-tuple whose: #.. 0-value is the type of the configurator that will be used to fetch the corresponding \ MDANSE.Framework.Configurators.IConfigurator.IConfigurator derived class from the configurators registry #.. 1-value is the name of the configurator that will be used as the key of the _configuration attribute. - #.. 2-value is the dictionary of the keywords used when initializing the configurator. + #.. 2-value is the dictionary of the keywords used when initializing the configurator. """ enabled = True @@ -94,7 +94,7 @@ def build_configuration(self): ) # Any kind of error has to be caught except: - raise ConfigurationError("Could not set %r configuration item" % name) + raise ConfigurationError(f"Could not set {name!r} configuration item") def set_settings(self, settings): self.settings = settings @@ -228,10 +228,10 @@ def build_doc_example(cls): docstring += ">>> \n" docstring += ">>> \n" docstring += ">>> parameters = {}\n" - for k, v in list(cls.get_default_parameters().items()): - docstring += ">>> parameters[%r]=%r\n" % (k, v) + for k, v in cls.get_default_parameters().items(): + docstring += f">>> parameters[{k!r}]={v!r}\n" docstring += ">>> \n" - docstring += ">>> job = IJob.create(%r)\n" % cls.__name__ + docstring += f">>> job = IJob.create({cls.__name__!r})\n" docstring += ">>> job.setup(parameters)\n" docstring += ">>> job.run()\n" return docstring @@ -249,53 +249,23 @@ def build_doc_texttable(cls, doclist): sizes[1] = max(sizes[1], len(v["Default value"])) # Case of Description field: has to be splitted and parsed for inserting sphinx "|" keyword for multiline v["Description"] = v["Description"].strip() - v["Description"] = v["Description"].split("\n") + v["Description"] = v["Description"].splitlines() v["Description"] = ["| " + vv.strip() for vv in v["Description"]] - sizes[2] = max(sizes[2], max([len(d) for d in v["Description"]])) - - docstring += "+%s+%s+%s+\n" % ( - "-" * (sizes[0] + 1), - "-" * (sizes[1] + 1), - "-" * (sizes[2] + 1), - ) - docstring += "| %-*s| %-*s| %-*s|\n" % ( - sizes[0], - columns[0], - sizes[1], - columns[1], - sizes[2], - columns[2], - ) - docstring += "+%s+%s+%s+\n" % ( - "=" * (sizes[0] + 1), - "=" * (sizes[1] + 1), - "=" * (sizes[2] + 1), - ) + sizes[2] = max(sizes[2], max(v["Description"], key=len)) + + data_line = "| " + "| ".join(f"{{}}:<{size}" for size in sizes) + "|\n" + sep_line = "+" + "+".join("-" * (size+1) for size in sizes) + "+\n" + + docstring += sep_line + docstring += data_line.format(*columns) + docstring += sep_line.replace("-", "=") for v in doclist: - docstring += "| %-*s| %-*s| %-*s|\n" % ( - sizes[0], - v["Configurator"], - sizes[1], - v["Default value"], - sizes[2], - v["Description"][0], - ) + docstring += data_line.format(v["Configurator"], v["Default value"], v["Description"][0]) if len(v["Description"]) > 1: for descr in v["Description"][1:]: - docstring += "| %-*s| %-*s| %-*s|\n" % ( - sizes[0], - "", - sizes[1], - "", - sizes[2], - descr, - ) - docstring += "+%s+%s+%s+\n" % ( - "-" * (sizes[0] + 1), - "-" * (sizes[1] + 1), - "-" * (sizes[2] + 1), - ) + data_line.format("", "", descr) + docstring += sep_line docstring += "\n" return docstring diff --git a/MDANSE/Src/MDANSE/Framework/Configurators/AseInputFileConfigurator.py b/MDANSE/Src/MDANSE/Framework/Configurators/AseInputFileConfigurator.py index d69e05bbfe..0654a47b3f 100644 --- a/MDANSE/Src/MDANSE/Framework/Configurators/AseInputFileConfigurator.py +++ b/MDANSE/Src/MDANSE/Framework/Configurators/AseInputFileConfigurator.py @@ -105,4 +105,4 @@ def get_information(self): LOG.error(result) return result else: - return "Input file: %r\n" % self["value"] + return f"Input file: {self['value']!r}\n" diff --git a/MDANSE/Src/MDANSE/Framework/Configurators/AtomSelectionConfigurator.py b/MDANSE/Src/MDANSE/Framework/Configurators/AtomSelectionConfigurator.py index 5d7be86ca9..5ed11f7e87 100644 --- a/MDANSE/Src/MDANSE/Framework/Configurators/AtomSelectionConfigurator.py +++ b/MDANSE/Src/MDANSE/Framework/Configurators/AtomSelectionConfigurator.py @@ -127,8 +127,8 @@ def get_information(self) -> str: return "Not configured yet\n" info = [] - info.append("Number of selected atoms:%d" % self["selection_length"]) - info.append("Selected elements:%s" % self["unique_names"]) + info.append(f"Number of selected atoms:{self['selection_length']:d}") + info.append(f"Selected elements:{self['unique_names']}") return "\n".join(info) + "\n" diff --git a/MDANSE/Src/MDANSE/Framework/Configurators/AtomTransmutationConfigurator.py b/MDANSE/Src/MDANSE/Framework/Configurators/AtomTransmutationConfigurator.py index 6ec3f36fee..ddd2ce27d2 100644 --- a/MDANSE/Src/MDANSE/Framework/Configurators/AtomTransmutationConfigurator.py +++ b/MDANSE/Src/MDANSE/Framework/Configurators/AtomTransmutationConfigurator.py @@ -203,7 +203,7 @@ def get_information(self) -> str: if self["value"] is None: return "No atoms selected for transmutation\n" - return "Number of transmuted atoms:%d\n" % self._nTransmutedAtoms + return f"Number of transmuted atoms:{self._nTransmutedAtoms:d}\n" def get_transmuter(self) -> AtomTransmuter: """ diff --git a/MDANSE/Src/MDANSE/Framework/Configurators/AtomsListConfigurator.py b/MDANSE/Src/MDANSE/Framework/Configurators/AtomsListConfigurator.py index d465ef6dd5..6699704b31 100644 --- a/MDANSE/Src/MDANSE/Framework/Configurators/AtomsListConfigurator.py +++ b/MDANSE/Src/MDANSE/Framework/Configurators/AtomsListConfigurator.py @@ -64,10 +64,10 @@ def configure(self, value): traj_configurator = self._configurable[self._dependencies["trajectory"]] if UD_STORE.has_definition( - traj_configurator["basename"], "%d_atoms_list" % self._nAtoms, value + traj_configurator["basename"], f"{self._nAtoms:d}_atoms_list", value ): molecule, atoms = UD_STORE.get_definition( - traj_configurator["basename"], "%d_atoms_list" % self._nAtoms, value + traj_configurator["basename"], f"{self._nAtoms:d}_atoms_list", value ) elif UD_STORE.has_definition( traj_configurator["basename"], "AtomsListConfigurator", value @@ -78,11 +78,8 @@ def configure(self, value): natoms = tempdict["natoms"] if not natoms == self._nAtoms: raise ValueError( - "The atom list must have " - + str(self._nAtoms) - + " atoms per molecule, but " - + str(natoms) - + " were found." + f"The atom list must have {self._nAtoms} " + f"atoms per molecule, but {natoms} were found." ) atoms = tempdict["indices"] self["value"] = value @@ -111,9 +108,6 @@ def get_information(self): if "atoms" not in self: return "No configured yet" - info = [] - info.append( - "Number of selected %d-tuplets:%d" % (self._nAtoms, self["n_values"]) - ) + info = [f"Number of selected {self._nAtoms:d}-tuplets:{self['n_values']:d}"] 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..7c67eb26da 100644 --- a/MDANSE/Src/MDANSE/Framework/Configurators/AxisSelectionConfigurator.py +++ b/MDANSE/Src/MDANSE/Framework/Configurators/AxisSelectionConfigurator.py @@ -33,19 +33,19 @@ class AxisSelectionConfigurator(IConfigurator): def configure(self, value): """ - Configure an input value. - + Configure an input value. + The value can be: - + #. a dict with *'molecule'*, *'endpoint1'* and *'endpoint2'* keys. *'molecule'* key \ is the name of the molecule for which the axis selection will be performed and *'endpoint1'* \ - and *'endpoint2'* keys are the names of two atoms of the molecule along which the axis will be defined + and *'endpoint2'* keys are the names of two atoms of the molecule along which the axis will be defined #. str: the axis selection will be performed by reading the corresponding user definition. - + :param configuration: the current configuration :type configuration: MDANSE.Framework.Configurable.Configurable :param value: the input value - :type value: tuple or str + :type value: tuple or str """ self._original_input = value @@ -88,4 +88,4 @@ def get_information(self): if "value" not in self: return "Not configured yet\n" - return "Axis vector:%s\n" % self["value"] + return f"Axis vector:{self['value']}\n" diff --git a/MDANSE/Src/MDANSE/Framework/Configurators/BasisSelectionConfigurator.py b/MDANSE/Src/MDANSE/Framework/Configurators/BasisSelectionConfigurator.py index c11e70a786..ed9e3da797 100644 --- a/MDANSE/Src/MDANSE/Framework/Configurators/BasisSelectionConfigurator.py +++ b/MDANSE/Src/MDANSE/Framework/Configurators/BasisSelectionConfigurator.py @@ -33,17 +33,17 @@ class BasisSelectionConfigurator(IConfigurator): def configure(self, value): """ - Configure an input value. - + Configure an input value. + The value can be: - + #. a dict with *'molecule'*, *'origin'*, *'x_axis'* and *'y_axis'* keys. *'molecule'* key is \ the name of the molecule for which the axis selection will be performed and *'origin'*, *'x_axis'* and *'y_axis'* \ - keys are the names of three atoms of the molecule that will be used to define respectively the origin, the X and Y axis of the basis + keys are the names of three atoms of the molecule that will be used to define respectively the origin, the X and Y axis of the basis #. str: the axis selection will be performed by reading the corresponding user definition. - + :param value: the input value - :type value: tuple or str + :type value: tuple or str :note: this configurator depends on 'trajectory' configurator to be configured """ @@ -85,4 +85,4 @@ def get_information(self): if "value" not in self: return "Not configured yet\n" - return "Basis vector:%s\n" % self["value"] + return f"Basis vector:{self['value']}\n" diff --git a/MDANSE/Src/MDANSE/Framework/Configurators/BooleanConfigurator.py b/MDANSE/Src/MDANSE/Framework/Configurators/BooleanConfigurator.py index 6cbe4ce046..e51ada3771 100644 --- a/MDANSE/Src/MDANSE/Framework/Configurators/BooleanConfigurator.py +++ b/MDANSE/Src/MDANSE/Framework/Configurators/BooleanConfigurator.py @@ -70,4 +70,4 @@ def get_information(self): if "value" not in self: return "Not configured yet\n" - return "Value: %r\n" % self["value"] + return f"Value: {self['value']!r}\n" diff --git a/MDANSE/Src/MDANSE/Framework/Configurators/FloatConfigurator.py b/MDANSE/Src/MDANSE/Framework/Configurators/FloatConfigurator.py index 8a0b8eed2a..3234e06f45 100644 --- a/MDANSE/Src/MDANSE/Framework/Configurators/FloatConfigurator.py +++ b/MDANSE/Src/MDANSE/Framework/Configurators/FloatConfigurator.py @@ -125,4 +125,4 @@ def get_information(self): if "value" not in self: return "Not configured yet\n" - return "Value: %r\n" % self["value"] + return f"Value: {self['value']!r}\n" diff --git a/MDANSE/Src/MDANSE/Framework/Configurators/FramesConfigurator.py b/MDANSE/Src/MDANSE/Framework/Configurators/FramesConfigurator.py index 21233a23b5..12905cfcb9 100644 --- a/MDANSE/Src/MDANSE/Framework/Configurators/FramesConfigurator.py +++ b/MDANSE/Src/MDANSE/Framework/Configurators/FramesConfigurator.py @@ -19,9 +19,9 @@ class FramesConfigurator(RangeConfigurator): """ This configurator allows to input a frame selection for the analysis. - + The frame selection can be input as: - + #. a 3-tuple where the 1st, 2nd will correspond respectively to the indices of the first and \ last (excluded) frames to be selected while the 3rd element will correspond to the step number between two frames. For example (1,11,3) will give 1,4,7,10 #. *'all'* keyword, in such case, all the frames of the trajectory are selected @@ -123,13 +123,8 @@ 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"], - ) + f"{self['n_frames']} frames selected " + f"(first={self['time'][0]:.3f} ; last = {self['time'][-1]:.3f} ; time step = {self['time_step']:.3f})\n" ) 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..1b635682bd 100644 --- a/MDANSE/Src/MDANSE/Framework/Configurators/GroupingLevelConfigurator.py +++ b/MDANSE/Src/MDANSE/Framework/Configurators/GroupingLevelConfigurator.py @@ -149,4 +149,4 @@ def get_information(self): if "value" not in self: return "Not configured yet\n" - return "Grouping level: %r\n" % self["value"] + return f"Grouping level: {self['value']!r}\n" diff --git a/MDANSE/Src/MDANSE/Framework/Configurators/HDFInputFileConfigurator.py b/MDANSE/Src/MDANSE/Framework/Configurators/HDFInputFileConfigurator.py index 5582ea5ade..6efce61cc5 100644 --- a/MDANSE/Src/MDANSE/Framework/Configurators/HDFInputFileConfigurator.py +++ b/MDANSE/Src/MDANSE/Framework/Configurators/HDFInputFileConfigurator.py @@ -117,7 +117,7 @@ def get_information(self): if "value" not in self: return "Not configured yet\n" - info = ["HDF input file: %r" % self["value"]] + info = [f"HDF input file: {self['value']!r}"] if "instance" in self: info.append("Contains the following variables:") @@ -125,6 +125,6 @@ def get_information(self): find_numeric_variables(variables, self["instance"]) for v in variables: - info.append("\t-{}".format(v)) + info.append(f"\t-{v}") return "\n".join(info) + "\n" diff --git a/MDANSE/Src/MDANSE/Framework/Configurators/HDFTrajectoryConfigurator.py b/MDANSE/Src/MDANSE/Framework/Configurators/HDFTrajectoryConfigurator.py index be357df2de..ce18ef7004 100644 --- a/MDANSE/Src/MDANSE/Framework/Configurators/HDFTrajectoryConfigurator.py +++ b/MDANSE/Src/MDANSE/Framework/Configurators/HDFTrajectoryConfigurator.py @@ -80,14 +80,13 @@ def get_information(self): :rtype: str """ try: - info = ["HDF input trajectory: %r\n" % self["filename"]] - info.append("Number of steps: %d\n" % self["length"]) + info = [f"HDF input trajectory: {self['filename']!r}\n"] + info.append(f"Number of steps: {self['length']:d}\n") except KeyError: info = "Input trajectory has not been configured" else: info.append( - "Size of the chemical system: %d\n" - % self["instance"].chemical_system.number_of_atoms + f"Size of the chemical system: {self['instance'].chemical_system.number_of_atoms:d}\n" ) if self["has_velocities"]: diff --git a/MDANSE/Src/MDANSE/Framework/Configurators/IConfigurator.py b/MDANSE/Src/MDANSE/Framework/Configurators/IConfigurator.py index 9372e7be0f..17c93689d4 100644 --- a/MDANSE/Src/MDANSE/Framework/Configurators/IConfigurator.py +++ b/MDANSE/Src/MDANSE/Framework/Configurators/IConfigurator.py @@ -59,10 +59,7 @@ def __str__(self): """ if self._configurator is not None: - self._message = "Configurator: %r --> %s" % ( - self._configurator.name, - self._message, - ) + self._message = f"Configurator: {self._configurator.name!r} --> {self._message}" return self._message diff --git a/MDANSE/Src/MDANSE/Framework/Configurators/InputDirectoryConfigurator.py b/MDANSE/Src/MDANSE/Framework/Configurators/InputDirectoryConfigurator.py index 8313b41d5f..b745bb13f7 100644 --- a/MDANSE/Src/MDANSE/Framework/Configurators/InputDirectoryConfigurator.py +++ b/MDANSE/Src/MDANSE/Framework/Configurators/InputDirectoryConfigurator.py @@ -56,4 +56,4 @@ def get_information(self): if "value" not in self: return "Not configured yet\n" - return "Input directory: %r\n" % self["value"] + return f"Input directory: {self['value']!r}\n" diff --git a/MDANSE/Src/MDANSE/Framework/Configurators/InstrumentResolutionConfigurator.py b/MDANSE/Src/MDANSE/Framework/Configurators/InstrumentResolutionConfigurator.py index 1fdf6768d8..40ad8e4e42 100644 --- a/MDANSE/Src/MDANSE/Framework/Configurators/InstrumentResolutionConfigurator.py +++ b/MDANSE/Src/MDANSE/Framework/Configurators/InstrumentResolutionConfigurator.py @@ -53,7 +53,7 @@ class InstrumentResolutionConfigurator(IConfigurator): def configure(self, value): """ Configure the instrument resolution. - + :param value: the instrument resolution. It must a 2-tuple where the 1st element is the \ is a string representing one of the supported instrument resolution and the 2nd element \ is a dictionary that stores the parameters for this kernel. @@ -122,11 +122,11 @@ def get_information(self): if "kernel" not in self: return "No configured yet" - info = ["Instrument resolution kernel: %s" % self["kernel"]] + info = [f"Instrument resolution kernel: {self['kernel']}"] if self["parameters"]: info.append("Parameters:") - for k, v in list(self["parameters"].items()): - info.append("%s = %s" % (k, v)) + for k, v in self["parameters"].items(): + info.append(f"{k} = {v}") info = "\n".join(info) diff --git a/MDANSE/Src/MDANSE/Framework/Configurators/IntegerConfigurator.py b/MDANSE/Src/MDANSE/Framework/Configurators/IntegerConfigurator.py index d8ded23b8a..73307c54f5 100644 --- a/MDANSE/Src/MDANSE/Framework/Configurators/IntegerConfigurator.py +++ b/MDANSE/Src/MDANSE/Framework/Configurators/IntegerConfigurator.py @@ -137,4 +137,4 @@ def get_information(self): if "value" not in self: return "Not configured yet\n" - return "Value: %r\n" % self["value"] + return f"Value: {self['value']!r}\n" diff --git a/MDANSE/Src/MDANSE/Framework/Configurators/MDMCTrajectoryConfigurator.py b/MDANSE/Src/MDANSE/Framework/Configurators/MDMCTrajectoryConfigurator.py index a0c503be1d..ffc25444bc 100644 --- a/MDANSE/Src/MDANSE/Framework/Configurators/MDMCTrajectoryConfigurator.py +++ b/MDANSE/Src/MDANSE/Framework/Configurators/MDMCTrajectoryConfigurator.py @@ -72,10 +72,9 @@ def get_information(self): """ info = ["MDMC trajectory used as input"] - info.append("Number of steps: %d\n" % self["length"]) + info.append(f"Number of steps: {self['length']:d}\n") info.append( - "Size of the chemical system: %d\n" - % self["instance"].chemical_system.number_of_atoms + f"Size of the chemical system: {self['instance'].chemical_system.number_of_atoms:d}\n" ) if self["has_velocities"]: info.append("The trajectory contains atomic velocities\n") diff --git a/MDANSE/Src/MDANSE/Framework/Configurators/McStasOptionsConfigurator.py b/MDANSE/Src/MDANSE/Framework/Configurators/McStasOptionsConfigurator.py index c9cf35aaa9..1bfa4170ca 100644 --- a/MDANSE/Src/MDANSE/Framework/Configurators/McStasOptionsConfigurator.py +++ b/MDANSE/Src/MDANSE/Framework/Configurators/McStasOptionsConfigurator.py @@ -84,7 +84,7 @@ def configure(self, value): if Path(v).exists(): v = self._default["dir"] self["mcstas_output_directory"] = Path(v) - tmp.append("--%s=%s" % (k, v)) + tmp.append(f"--{k}={v}") dirname = self["mcstas_output_directory"].parent @@ -107,4 +107,4 @@ def get_information(self): if "value" not in self: return "Not configured yet\n" - return "McStas command line options: %s\n" % self["value"] + return f"McStas command line options: {self['value']}\n" diff --git a/MDANSE/Src/MDANSE/Framework/Configurators/McStasParametersConfigurator.py b/MDANSE/Src/MDANSE/Framework/Configurators/McStasParametersConfigurator.py index 18b556728a..99daff6f42 100644 --- a/MDANSE/Src/MDANSE/Framework/Configurators/McStasParametersConfigurator.py +++ b/MDANSE/Src/MDANSE/Framework/Configurators/McStasParametersConfigurator.py @@ -101,7 +101,7 @@ def configure(self, value): continue val[k] = self._mcStasTypes[instrParameters[k][0]](v) - self["value"] = ["%s=%s" % (k, v) for k, v in list(val.items())] + self["value"] = [f"{k}={v}" for k, v in val.items()] @property def exclude(self): @@ -124,4 +124,4 @@ def get_information(self): if "value" not in self: return "Not configured yet\n" - return "McStas command line parameters:%s\n" % self["value"] + return f"McStas command line parameters:{self['value']}\n" diff --git a/MDANSE/Src/MDANSE/Framework/Configurators/MockTrajectoryConfigurator.py b/MDANSE/Src/MDANSE/Framework/Configurators/MockTrajectoryConfigurator.py index 85da7def71..14f0969114 100644 --- a/MDANSE/Src/MDANSE/Framework/Configurators/MockTrajectoryConfigurator.py +++ b/MDANSE/Src/MDANSE/Framework/Configurators/MockTrajectoryConfigurator.py @@ -75,10 +75,9 @@ def get_information(self): """ info = ["Mock trajectory used as input"] - info.append("Number of steps: %d\n" % self["length"]) + info.append(f"Number of steps: {self['length']:d}\n") info.append( - "Size of the chemical system: %d\n" - % self["instance"].chemical_system.number_of_atoms + f"Size of the chemical system: {self['instance'].chemical_system.number_of_atoms}\n" ) if self["has_velocities"]: info.append("The trajectory contains atomic velocities\n") diff --git a/MDANSE/Src/MDANSE/Framework/Configurators/MultipleChoicesConfigurator.py b/MDANSE/Src/MDANSE/Framework/Configurators/MultipleChoicesConfigurator.py index 640a9479b3..2550678660 100644 --- a/MDANSE/Src/MDANSE/Framework/Configurators/MultipleChoicesConfigurator.py +++ b/MDANSE/Src/MDANSE/Framework/Configurators/MultipleChoicesConfigurator.py @@ -102,7 +102,7 @@ def nChoices(self): def get_information(self): try: - info = "Selected items: %r\n" % self["choices"] + info = f"Selected items: {self['choices']!r}\n" except KeyError: info = "MultipleChoicesConfigurator could not be set up" return info diff --git a/MDANSE/Src/MDANSE/Framework/Configurators/OptionalFloatConfigurator.py b/MDANSE/Src/MDANSE/Framework/Configurators/OptionalFloatConfigurator.py index 2fb3066f0e..8ab4439ed8 100644 --- a/MDANSE/Src/MDANSE/Framework/Configurators/OptionalFloatConfigurator.py +++ b/MDANSE/Src/MDANSE/Framework/Configurators/OptionalFloatConfigurator.py @@ -132,4 +132,4 @@ def get_information(self): if "value" not in self: return "Not configured yet\n" - return "Value: %r\n" % self["value"] + return f"Value: {self['value']!r}\n" diff --git a/MDANSE/Src/MDANSE/Framework/Configurators/OutputDirectoryConfigurator.py b/MDANSE/Src/MDANSE/Framework/Configurators/OutputDirectoryConfigurator.py index 00bb8b7e91..39f0a7512a 100644 --- a/MDANSE/Src/MDANSE/Framework/Configurators/OutputDirectoryConfigurator.py +++ b/MDANSE/Src/MDANSE/Framework/Configurators/OutputDirectoryConfigurator.py @@ -72,4 +72,4 @@ def get_information(self): if "value" not in self: return "Not configured yet\n" - return "Output directory: %r\n" % self["value"] + return f"Output directory: {self['value']!r}\n" diff --git a/MDANSE/Src/MDANSE/Framework/Configurators/OutputTrajectoryConfigurator.py b/MDANSE/Src/MDANSE/Framework/Configurators/OutputTrajectoryConfigurator.py index e92988de9e..4488affba2 100644 --- a/MDANSE/Src/MDANSE/Framework/Configurators/OutputTrajectoryConfigurator.py +++ b/MDANSE/Src/MDANSE/Framework/Configurators/OutputTrajectoryConfigurator.py @@ -126,7 +126,7 @@ def get_information(self): :rtype: str """ try: - info = "Output file: %s\n" % self["file"] + info = f"Output file: {self['file']}\n" except KeyError: info = "Output Trajectory has not been defined" diff --git a/MDANSE/Src/MDANSE/Framework/Configurators/ProjectionConfigurator.py b/MDANSE/Src/MDANSE/Framework/Configurators/ProjectionConfigurator.py index 1c9aa15747..2c43de6d86 100644 --- a/MDANSE/Src/MDANSE/Framework/Configurators/ProjectionConfigurator.py +++ b/MDANSE/Src/MDANSE/Framework/Configurators/ProjectionConfigurator.py @@ -33,8 +33,8 @@ class ProjectionConfigurator(IConfigurator): def configure(self, value): """ - Configure a projector. - + Configure a projector. + :param value: the input projector definition. It can be a 2-tuple whose 1st element if the name \ of the projector (one of *'null'*,*'axial'* or *'planar'*) and the 2nd element the parameters for the selected \ projector (None for *'null'*, a Scientific.Vector for *'axial'* and a list of two Scientific.Vector for *'planar'*) \ @@ -96,4 +96,4 @@ def get_information(self): if self["axis"] is not None: return "No projection performed\n" else: - return "Projection along %r axis\n" % self["axis"] + return f"Projection along {self['axis']!r} axis\n" diff --git a/MDANSE/Src/MDANSE/Framework/Configurators/PythonObjectConfigurator.py b/MDANSE/Src/MDANSE/Framework/Configurators/PythonObjectConfigurator.py index 5fc91cc11c..f3c3053a03 100644 --- a/MDANSE/Src/MDANSE/Framework/Configurators/PythonObjectConfigurator.py +++ b/MDANSE/Src/MDANSE/Framework/Configurators/PythonObjectConfigurator.py @@ -59,4 +59,4 @@ def get_information(self): if "value" not in self: return "Not configured yet\n" - return "Python object: %r\n" % self["value"] + return f"Python object: {self['value']}\n" diff --git a/MDANSE/Src/MDANSE/Framework/Configurators/QVectorsConfigurator.py b/MDANSE/Src/MDANSE/Framework/Configurators/QVectorsConfigurator.py index cd8a7c8ef0..42c8033d5c 100644 --- a/MDANSE/Src/MDANSE/Framework/Configurators/QVectorsConfigurator.py +++ b/MDANSE/Src/MDANSE/Framework/Configurators/QVectorsConfigurator.py @@ -45,8 +45,8 @@ class QVectorsConfigurator(IConfigurator): def configure(self, value): """ - Configure a Q vectors generator. - + Configure a Q vectors generator. + :param configuration: the current configuration. :type configuration: a MDANSE.Framework.Configurable.Configurable object :param value: the Q vectors generator definition. It can be a 2-tuple, whose 1st element is the name of the Q vector generator \ @@ -117,13 +117,13 @@ def get_information(self): """ try: - info = ["%d Q shells generated\n" % self["n_shells"]] + info = [f"{self['n_shells']} Q shells generated\n"] except KeyError: return "QVectors could not be configured correctly" else: - for qValue, qVectors in list(self["q_vectors"].items()): + for qValue, qVectors in self["q_vectors"].items(): info.append( - "Shell %s: %d Q vectors generated\n" % (qValue, len(qVectors)) + f"Shell {qValue}: {len(qVectors)} Q vectors generated\n" ) return "".join(info) diff --git a/MDANSE/Src/MDANSE/Framework/Configurators/RangeConfigurator.py b/MDANSE/Src/MDANSE/Framework/Configurators/RangeConfigurator.py index 2edad306eb..84508d850a 100644 --- a/MDANSE/Src/MDANSE/Framework/Configurators/RangeConfigurator.py +++ b/MDANSE/Src/MDANSE/Framework/Configurators/RangeConfigurator.py @@ -213,11 +213,7 @@ def get_information(self): if self._valid: - info = "%d values from %s to %s" % ( - self["number"], - self["first"], - self["last"], - ) + info = f"{self['number']} values from {self['first']} to {self['last']}" if self._includeLast: info += " last value included" diff --git a/MDANSE/Src/MDANSE/Framework/Configurators/RunningModeConfigurator.py b/MDANSE/Src/MDANSE/Framework/Configurators/RunningModeConfigurator.py index 56fcc870ad..068bec5632 100644 --- a/MDANSE/Src/MDANSE/Framework/Configurators/RunningModeConfigurator.py +++ b/MDANSE/Src/MDANSE/Framework/Configurators/RunningModeConfigurator.py @@ -33,7 +33,7 @@ class RunningModeConfigurator(IConfigurator): def configure(self, value): """ Configure the running mode. - + :param value: the running mode specification. It can be *'single-core'* or a 2-tuple whose first element \ must be *'multicore'* and 2nd element the number of slots allocated for running the analysis. :type value: *'single-core'* or 2-tuple @@ -81,7 +81,7 @@ def get_information(self): :rtype: str """ try: - info = "Run in %s mode (%d slots)\n" % (self["mode"], self["slots"]) + info = f"Run in {self['mode']} mode ({self['slots']:d} slots)\n" except KeyError: info = "Running mode has not been configured" diff --git a/MDANSE/Src/MDANSE/Framework/Configurators/SingleChoiceConfigurator.py b/MDANSE/Src/MDANSE/Framework/Configurators/SingleChoiceConfigurator.py index e8264551fa..d651d3f6a1 100644 --- a/MDANSE/Src/MDANSE/Framework/Configurators/SingleChoiceConfigurator.py +++ b/MDANSE/Src/MDANSE/Framework/Configurators/SingleChoiceConfigurator.py @@ -81,4 +81,4 @@ def get_information(self): if "value" not in self: return "Not configured yet\n" - return "Selected item: %r\n" % self["value"] + return f"Selected item: {self['value']!r}\n" diff --git a/MDANSE/Src/MDANSE/Framework/Configurators/SingleOutputFileConfigurator.py b/MDANSE/Src/MDANSE/Framework/Configurators/SingleOutputFileConfigurator.py index 7e26065e36..adf63c6fc7 100644 --- a/MDANSE/Src/MDANSE/Framework/Configurators/SingleOutputFileConfigurator.py +++ b/MDANSE/Src/MDANSE/Framework/Configurators/SingleOutputFileConfigurator.py @@ -119,7 +119,7 @@ def get_information(self): :rtype: str """ try: - info = "Output file: %s\n" % self["file"] + info = f"Output file: {self['file']}\n" except KeyError: info = "Output file has not been configured" diff --git a/MDANSE/Src/MDANSE/Framework/Configurators/StringConfigurator.py b/MDANSE/Src/MDANSE/Framework/Configurators/StringConfigurator.py index 31559c5a20..5312a1431f 100644 --- a/MDANSE/Src/MDANSE/Framework/Configurators/StringConfigurator.py +++ b/MDANSE/Src/MDANSE/Framework/Configurators/StringConfigurator.py @@ -104,4 +104,4 @@ def get_information(self): if "value" not in self: return "Not configured yet\n" - return "Value: %r\n" % self["value"] + return f"Value: {self['value']!r}\n" diff --git a/MDANSE/Src/MDANSE/Framework/Configurators/TrajectoryVariableConfigurator.py b/MDANSE/Src/MDANSE/Framework/Configurators/TrajectoryVariableConfigurator.py index 78f17da577..6d70a5c359 100644 --- a/MDANSE/Src/MDANSE/Framework/Configurators/TrajectoryVariableConfigurator.py +++ b/MDANSE/Src/MDANSE/Framework/Configurators/TrajectoryVariableConfigurator.py @@ -57,4 +57,4 @@ def get_information(self): if "value" not in self: return "Not configured yet\n" - return "Selected variable: %r\n" % self["value"] + return f"Selected variable: {self['value']!r}\n" diff --git a/MDANSE/Src/MDANSE/Framework/Configurators/UnitCellConfigurator.py b/MDANSE/Src/MDANSE/Framework/Configurators/UnitCellConfigurator.py index 99b4ed13c2..d2be900d67 100644 --- a/MDANSE/Src/MDANSE/Framework/Configurators/UnitCellConfigurator.py +++ b/MDANSE/Src/MDANSE/Framework/Configurators/UnitCellConfigurator.py @@ -123,4 +123,4 @@ def get_information(self): if "value" not in self: return "Not configured yet\n" - return "Value: %r\n" % self["value"] + return f"Value: {self['value']!r}\n" diff --git a/MDANSE/Src/MDANSE/Framework/Configurators/VectorConfigurator.py b/MDANSE/Src/MDANSE/Framework/Configurators/VectorConfigurator.py index 5881a77121..79bb6131f2 100644 --- a/MDANSE/Src/MDANSE/Framework/Configurators/VectorConfigurator.py +++ b/MDANSE/Src/MDANSE/Framework/Configurators/VectorConfigurator.py @@ -142,4 +142,4 @@ def get_information(self): if "value" not in self: return "Not configured yet\n" - return "Value: %r\n" % self["value"] + return f"Value: {self['value']!r}\n" diff --git a/MDANSE/Src/MDANSE/Framework/Configurators/WeightsConfigurator.py b/MDANSE/Src/MDANSE/Framework/Configurators/WeightsConfigurator.py index ffa7853fb7..eb64b7040d 100644 --- a/MDANSE/Src/MDANSE/Framework/Configurators/WeightsConfigurator.py +++ b/MDANSE/Src/MDANSE/Framework/Configurators/WeightsConfigurator.py @@ -134,7 +134,7 @@ def get_information(self): :rtype: str """ try: - info = "selected weight: %s\n" % self["property"] + info = f"selected weight: {self['property']}\n" except KeyError: info = "Weights have not been configured" diff --git a/MDANSE/Src/MDANSE/Framework/Configurators/XYZFileConfigurator.py b/MDANSE/Src/MDANSE/Framework/Configurators/XYZFileConfigurator.py index 62bc1a5676..72d69119cd 100644 --- a/MDANSE/Src/MDANSE/Framework/Configurators/XYZFileConfigurator.py +++ b/MDANSE/Src/MDANSE/Framework/Configurators/XYZFileConfigurator.py @@ -48,7 +48,7 @@ def parse(self): self["n_atoms"] = int(self["instance"].readline().strip()) except ValueError: raise XYZFileError( - "Could not read the number of atoms in %s file" % filename + f"Could not read the number of atoms in {filename} file" ) self._nAtomsLineSize = self["instance"].tell() diff --git a/MDANSE/Src/MDANSE/Framework/Converters/DCD.py b/MDANSE/Src/MDANSE/Framework/Converters/DCD.py index ded2bddb43..3e4510eb71 100644 --- a/MDANSE/Src/MDANSE/Framework/Converters/DCD.py +++ b/MDANSE/Src/MDANSE/Framework/Converters/DCD.py @@ -70,7 +70,7 @@ def get_byte_order(filename): if byteOrder is None: raise ByteOrderError( - "Invalid byte order. %s is not a valid DCD file" % filename + f"Invalid byte order. {filename} not a valid DCD file" ) return byteOrder @@ -237,7 +237,7 @@ def read_step(self): else: unitCell = None - fmt = "%df" % self["natoms"] + fmt = f"{self['natoms']}f" config = np.empty((self["natoms"], 3), dtype=np.float64) config[:, 0] = np.array(self.get_record(fmt), dtype=np.float64) config[:, 1] = np.array(self.get_record(fmt), dtype=np.float64) diff --git a/MDANSE/Src/MDANSE/Framework/Converters/Discover.py b/MDANSE/Src/MDANSE/Framework/Converters/Discover.py index 7906087c95..c5468182f2 100644 --- a/MDANSE/Src/MDANSE/Framework/Converters/Discover.py +++ b/MDANSE/Src/MDANSE/Framework/Converters/Discover.py @@ -61,7 +61,7 @@ def parse_header(self): rec = "!i" recSize = struct.calcsize(rec) N_ATTYP = struct.unpack(rec, hisfile.read(recSize))[0] - rec = "!" + "%ds" % (4 * N_ATTYP) + "%dd" % N_ATTYP + "8x" + rec = f"!{4 * N_ATTYP}s{N_ATTYP}d8x" recSize = struct.calcsize(rec) hisfile.read(recSize) @@ -69,7 +69,7 @@ def parse_header(self): rec = "!i" recSize = struct.calcsize(rec) N_NMRES = struct.unpack(rec, hisfile.read(recSize))[0] - rec = "!" + "%ds" % (4 * N_NMRES) + "8x" + rec = f"!{4 * N_NMRES}s8x" recSize = struct.calcsize(rec) hisfile.read(recSize) @@ -77,12 +77,7 @@ def parse_header(self): rec = "!i" recSize = struct.calcsize(rec) self["n_atoms"] = N_ATOMS = struct.unpack(rec, hisfile.read(recSize))[0] - rec = "!" + "%di" % N_ATOMS - if VERSION < 2.9: - rec += "%ds" % (4 * N_ATOMS) - else: - rec += "%ds" % (5 * N_ATOMS) - rec += "8x" + rec = f"!{N_ATOMS}i{N_ATOMS * (4 if VERSION < 2.9 else 5)}s8x" recSize = struct.calcsize(rec) hisfile.read(recSize) @@ -91,7 +86,7 @@ def parse_header(self): recSize = struct.calcsize(rec) _, N_MOVAT = struct.unpack(rec, hisfile.read(recSize)) if VERSION >= 2.6: - rec = "!" + "%di" % N_MOVAT + rec = f"!{N_MOVAT}i" recSize = struct.calcsize(rec) self["movable_atoms"] = ( np.array(struct.unpack(rec, hisfile.read(recSize)), dtype=np.int32) - 1 @@ -106,7 +101,7 @@ def parse_header(self): rec = "!i" recSize = struct.calcsize(rec) N_MOL = struct.unpack(rec, hisfile.read(recSize))[0] - rec = "!" + "%di" % N_MOL + "%di" % N_MOL + "8x" + rec = f"!{N_MOL}i{N_MOL}i8x" recSize = struct.calcsize(rec) hisfile.read(recSize) @@ -114,7 +109,7 @@ def parse_header(self): rec = "!i" recSize = struct.calcsize(rec) N_RES = struct.unpack(rec, hisfile.read(recSize))[0] - rec = "!" + "%di" % (2 * N_RES) + "%di" % N_RES + "8x" + rec = f"!{2 * N_RES}i{N_RES}i8x" recSize = struct.calcsize(rec) hisfile.read(recSize) @@ -123,7 +118,7 @@ def parse_header(self): recSize = struct.calcsize(rec) N_BONDS = struct.unpack(rec, hisfile.read(recSize))[0] if N_BONDS > 0: - rec = "!" + "%di" % (2 * N_BONDS) + rec = f"!{2 * N_BONDS}i" recSize = struct.calcsize(rec) _ = struct.unpack(rec, hisfile.read(recSize)) rec = "!8x" @@ -152,19 +147,12 @@ def parse_header(self): self["time_step"] = TIME_STEP * measure(1.0, "fs").toval("ps") # Record 14 - rec = ( - "!3d" - + "%dd" % N_ENER - + "%dd" % N_MOL - + "%dd" % (N_MOL * N_ENER) - + "%dd" % (4 * N_MOL + 2 + 54) - + "8x" - ) + rec = f"!3d{N_ENER}d{N_MOL}d{N_MOL * N_ENER}d{4 * N_MOL + 2 + 54}d8x" self._rec14Size = struct.calcsize(rec) hisfile.read(self._rec14Size) # Record 15 - rec = "!" + "%df" % (3 * N_ATOMS) + "8x" + rec = f"!{3 * N_ATOMS}f8x" recSize = struct.calcsize(rec) self["initial_coordinates"] = np.reshape( struct.unpack(rec, hisfile.read(recSize)), (N_ATOMS, 3) @@ -172,7 +160,7 @@ def parse_header(self): self["initial_coordinates"] *= measure(1.0, "ang").toval("nm") # Record 16 - rec = "!" + "%df" % (3 * N_ATOMS) + "8x" + rec = f"!{3 * N_ATOMS}f8x" recSize = struct.calcsize(rec) self["initial_velocities"] = np.reshape( struct.unpack(rec, hisfile.read(recSize)), (N_ATOMS, 3) @@ -188,9 +176,9 @@ def parse_header(self): self["n_movable_atoms"] = N_ATOMS else: self["n_movable_atoms"] = N_MOVAT - self._recCoord = "!" + "%df" % (3 * self["n_movable_atoms"]) + "8x" + self._recCoord = f"!{3 * self['n_movable_atoms']}f8x" self._recCoordSize = struct.calcsize(self._recCoord) - self._recVel = "!" + "%df" % (3 * self["n_movable_atoms"]) + "8x" + self._recVel = f"!{3 * self['n_movable_atoms']}f8x" self._recVelSize = struct.calcsize(self._recVel) self._frameSize = ( diff --git a/MDANSE/Src/MDANSE/Framework/Converters/Forcite.py b/MDANSE/Src/MDANSE/Framework/Converters/Forcite.py index 49296abf17..ad177b57d6 100644 --- a/MDANSE/Src/MDANSE/Framework/Converters/Forcite.py +++ b/MDANSE/Src/MDANSE/Framework/Converters/Forcite.py @@ -55,7 +55,7 @@ def parse_header(self): rec = "!i" recSize = struct.calcsize(rec) (NTRJTI,) = struct.unpack(rec, trjfile.read(recSize)) - rec = "!%ds8x" % (80 * NTRJTI) + rec = f"!{80*NTRJTI}s8x" recSize = struct.calcsize(rec) self["title"] = struct.unpack(rec, trjfile.read(recSize)) self["title"] = "\n".join([t.decode("utf-8") for t in self["title"]]) @@ -64,7 +64,7 @@ def parse_header(self): rec = "!i" recSize = struct.calcsize(rec) NEEXTI = struct.unpack(rec, trjfile.read(recSize))[0] - rec = "!" + "%ds" % (80 * NEEXTI) + "8x" + rec = f"!{80 * NEEXTI}s8x" recSize = struct.calcsize(rec) trjfile.read(recSize) @@ -82,7 +82,7 @@ def parse_header(self): recSize = struct.calcsize(rec) NFLUSD = struct.unpack(rec, trjfile.read(recSize))[0] - rec = "!%di%di%ds8x" % (NFLUSD, NFLUSD, 8 * NFLUSD) + rec = f"!{NFLUSD}i{NFLUSD}i{8*NFLUSD}s8x" recSize = struct.calcsize(rec) trjfile.read(recSize) @@ -90,7 +90,7 @@ def parse_header(self): recSize = struct.calcsize(rec) self["totmov"] = struct.unpack(rec, trjfile.read(recSize))[0] - rec = "!%di8x" % self["totmov"] + rec = f"!{self['totmov']}i8x" recSize = struct.calcsize(rec) self["mvofst"] = ( np.array(struct.unpack(rec, trjfile.read(recSize)), dtype=np.int32) - 1 @@ -100,7 +100,7 @@ def parse_header(self): rec = "!i" recSize = struct.calcsize(rec) (LEEXTI,) = struct.unpack(rec, trjfile.read(recSize)) - rec = "!%ds8x" % LEEXTI + rec = f"!{LEEXTI}s8x" recSize = struct.calcsize(rec) trjfile.read(recSize) @@ -108,7 +108,7 @@ def parse_header(self): rec = "!i" recSize = struct.calcsize(rec) (LPARTI,) = struct.unpack(rec, trjfile.read(recSize)) - rec = "!%ds8x" % LPARTI + rec = f"!{LPARTI}s8x" recSize = struct.calcsize(rec) trjfile.read(recSize) @@ -116,11 +116,11 @@ def parse_header(self): # Frame record 1 if VERSION == 2000: - rec1 = "!%si33%s5i8x" % (self._fp, self._fp) + rec1 = f"!{self._fp}i33{self.fp}5i8x" elif VERSION == 2010: - rec1 = "!%si57%s6i8x" % (self._fp, self._fp) + rec1 = f"!{self._fp}i57{self._fp}6i8x" else: - rec1 = "!%si58%s6i8x" % (self._fp, self._fp) + rec1 = f"!{self._fp}i58{self._fp}6i8x" recSize = struct.calcsize(rec1) DATA = struct.unpack(rec1, trjfile.read(recSize)) @@ -133,38 +133,38 @@ def parse_header(self): self["gradients_written"] = DATA[-3] # Frame record 2 - rec = "!12%s8x" % self._fp + rec = f"!12{self._fp}8x" recSize = struct.calcsize(rec) trjfile.read(recSize) # Frame record 3 if LCANON: - rec = "!4%s8x" % self._fp + rec = f"!4{self._fp}8x" recSize = struct.calcsize(rec) trjfile.read(recSize) if PERTYPE > 0: # Frame record 4 self._defCellRecPos = trjfile.tell() - self._headerSize - self._defCellRec = "!22%s8x" % self._fp + self._defCellRec = f"!22{self._fp}8x" self._defCellRecSize = struct.calcsize(self._defCellRec) trjfile.read(self._defCellRecSize) if PERTYPE > 0: # Frame record 5 - rec = "!i14%s8x" % self._fp + rec = f"!i14{self._fp}8x" recSize = struct.calcsize(rec) trjfile.read(recSize) if LNPECAN: # Frame record 6 - rec = "!3%s8x" % self._fp + rec = f"!3{self._fp}8x" recSize = struct.calcsize(rec) trjfile.read(recSize) if LTMPDAMP: # Frame record 7 - rec = "!%s8x" % self._fp + rec = f"!{self._fp}8x" recSize = struct.calcsize(rec) trjfile.read(recSize) @@ -173,25 +173,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 = "!" + (f"{self['totmov']}{self._fp}8x" * 9) else: # Frame record 8,9,10,11,12,13 - self._configRec = "!" + ("%d%s8x" * 6) % ( - (self["totmov"], self._fp) * 6 - ) + self._configRec = "!" + (f"{self['totmov']}{self._fp}8x" * 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 = "!" + (f"{self['totmov']}{self._fp}8x" * 6) else: # Frame record 8,9,10 - self._configRec = "!" + ("%d%s8x" * 3) % ( - (self["totmov"], self._fp) * 3 - ) + self._configRec = "!" + (f"{self['totmov']}{self._fp}8x" * 3) self._configRecSize = struct.calcsize(self._configRec) trjfile.read(self._configRecSize) @@ -211,7 +203,7 @@ def read_step(self, index): trjfile.seek(pos, 0) - rec = "!%s" % self._fp + rec = f"!{self._fp}" recSize = struct.calcsize(rec) (timeStep,) = struct.unpack(rec, trjfile.read(recSize)) diff --git a/MDANSE/Src/MDANSE/Framework/Converters/Gromacs.py b/MDANSE/Src/MDANSE/Framework/Converters/Gromacs.py index a01cac5320..bf956d3a86 100644 --- a/MDANSE/Src/MDANSE/Framework/Converters/Gromacs.py +++ b/MDANSE/Src/MDANSE/Framework/Converters/Gromacs.py @@ -113,7 +113,7 @@ def initialize(self): else: raise GromacsConverterError( "Invalid file format: Gromacs converter can only convert XTC and TRR files, " - "but %s was provided." % self.configuration["xtc_file"]["filename"][-4:] + f"but {self.configuration['xtc_file']['filename'][-4:]} was provided." ) # The number of steps of the analysis. diff --git a/MDANSE/Src/MDANSE/Framework/Formats/SVGFormat.py b/MDANSE/Src/MDANSE/Framework/Formats/SVGFormat.py index e7acd8170c..3f6ae31275 100644 --- a/MDANSE/Src/MDANSE/Framework/Formats/SVGFormat.py +++ b/MDANSE/Src/MDANSE/Framework/Formats/SVGFormat.py @@ -70,12 +70,12 @@ def write(cls, filename: Union[Path, str], data, header=""): if var.axis in data: axis = data[var.axis] - xtitle = "%s (%s)" % (axis.name, format_unit_string(axis.units)) + xtitle = f"{axis.name} ({format_unit_string(axis.units)})" else: axis = np.arange(len(var)) xtitle = "index" - ytitle = "%s (%s)" % (var.varname, format_unit_string(var.units)) + ytitle = f"{var.varname} ({format_unit_string(var.units)})" pl = Poly(list(zip(axis, var)), stroke="blue") @@ -91,7 +91,7 @@ def write(cls, filename: Union[Path, str], data, header=""): ytitle=ytitle, ).SVG().save(svgfilename) - tf.add(svgfilename, arcname="%s%s" % (var.varname, cls.extensions[0])) + tf.add(svgfilename, arcname=f"{var.varname}{cls.extensions[0]}") svgfilename.unlink() diff --git a/MDANSE/Src/MDANSE/Framework/Formats/TextFormat.py b/MDANSE/Src/MDANSE/Framework/Formats/TextFormat.py index e355f733c5..fdcab8c1d9 100644 --- a/MDANSE/Src/MDANSE/Framework/Formats/TextFormat.py +++ b/MDANSE/Src/MDANSE/Framework/Formats/TextFormat.py @@ -108,7 +108,7 @@ def write( cls.write_data(tempStr, var, data) real_buffer.seek(0) - info = tarfile.TarInfo(name="%s%s" % (var.varname, cls.extensions[0])) + info = tarfile.TarInfo(name=f"{var.varname}{cls.extensions[0]}") info.size = length_stringio(real_buffer) info.mtime = time.time() tf.addfile(tarinfo=info, fileobj=real_buffer) @@ -138,22 +138,20 @@ def write_data(cls, fileobject, data, allData): if xData == "index": xValues = np.arange(data.shape[0]) - fileobject.write("# 1st column: %s (%s)\n" % (xData, "au")) + fileobject.write(f"# 1st column: {xData} (au)\n") else: xValues = allData[xData] fileobject.write( - "# 1st column: %s (%s)\n" - % (allData[xData].varname, allData[xData].units) + f"# 1st column: {xValues.varname} ({xValues.units})\n" ) if yData == "index": yValues = np.arange(data.shape[1]) - fileobject.write("# 1st row: %s (%s)\n\n" % (yData, "au")) + fileobject.write(f"# 1st row: {yData} (au)\n\n") else: yValues = allData[yData] fileobject.write( - "# 1st row: %s (%s)\n\n" - % (allData[yData].varname, allData[yData].units) + f"# 1st row: {yValues.varname} ({yValues.units})\n\n" ) zData = np.zeros((data.shape[0] + 1, data.shape[1] + 1), dtype=np.float64) @@ -169,15 +167,14 @@ def write_data(cls, fileobject, data, allData): if xData == "index": xValues = np.arange(data.size) - fileobject.write("# 1st column: %s (%s)\n" % (xData, "au")) + fileobject.write(f"# 1st column: {xData} (au)\n") else: xValues = allData[xData] fileobject.write( - "# 1st column: %s (%s)\n" - % (allData[xData].varname, allData[xData].units) + f"# 1st column: {xValues.varname} ({xValues.units})\n" ) - fileobject.write("# 2nd column: %s (%s)\n\n" % (data.varname, data.units)) + fileobject.write(f"# 2nd column: {data.varname} ({data.units})\n\n") np.savetxt(fileobject, np.column_stack([xValues, data])) fileobject.write("\n") diff --git a/MDANSE/Src/MDANSE/Framework/InputData/HDFTrajectoryInputData.py b/MDANSE/Src/MDANSE/Framework/InputData/HDFTrajectoryInputData.py index 715213aa36..1f773a1081 100644 --- a/MDANSE/Src/MDANSE/Framework/InputData/HDFTrajectoryInputData.py +++ b/MDANSE/Src/MDANSE/Framework/InputData/HDFTrajectoryInputData.py @@ -57,14 +57,14 @@ def info(self): timeline = f"[{time_axis[0]}, {time_axis[1]}, ..., {time_axis[-1]}]\n" val.append("Path:") - val.append("%s\n" % self._name) + val.append(f"{self._name}\n") val.append("Number of steps:") - val.append("%s\n" % len(self._data)) + val.append(f"{self._data}\n") val.append("Configuration:") - val.append("\tIs periodic: {}\n".format("unit_cell" in self._data.file)) + val.append(f"\tIs periodic: {"unit_cell" in self._data.file}\n") try: val.append( - "First unit cell (nm):\n{}\n".format(self._data.unit_cell(0)._unit_cell) + f"First unit cell (nm):\n{self._data.unit_cell(0)._unit_cell}\n" ) except: val.append("No unit cell information\n") @@ -74,10 +74,10 @@ def info(self): for k in self._data.variables(): v = self._data.variable(k) try: - val.append("\t- {}: {}".format(k, v.shape)) + val.append(f"\t- {k}: {v.shape}") except AttributeError: try: - val.append("\t- {}: {}".format(k, v["value"].shape)) + val.append(f"\t- {k}: {v['value'].shape}") except KeyError: continue @@ -91,7 +91,7 @@ def info(self): val.append(f"Molecule: {molname}; Count: {len(mollist)}") for k, v in mol_types.items(): - val.append("\t- {:d} {}".format(v, k)) + val.append(f"\t- {v:d} {k}") val = "\n".join(val) diff --git a/MDANSE/Src/MDANSE/Framework/InputData/MockTrajectoryInputData.py b/MDANSE/Src/MDANSE/Framework/InputData/MockTrajectoryInputData.py index b1f2621945..997f166910 100644 --- a/MDANSE/Src/MDANSE/Framework/InputData/MockTrajectoryInputData.py +++ b/MDANSE/Src/MDANSE/Framework/InputData/MockTrajectoryInputData.py @@ -43,16 +43,17 @@ def info(self): val = [] val.append("Path:") - val.append("%s\n" % self._name) + val.append(f"{self._name}\n") val.append("Number of steps:") - val.append("%s\n" % len(self._data)) + val.append(f"{self._data}\n") + mol_types = {} val.append("\nMolecular types found:") for name, list in self._data.chemical_system._clusters.items(): mol_types[name] = len(list) for k, v in mol_types.items(): - val.append("\t- {:d} {}".format(v, k)) + val.append(f"\t- {v:d} {k}") val = "\n".join(val) diff --git a/MDANSE/Src/MDANSE/Framework/Jobs/AreaPerMolecule.py b/MDANSE/Src/MDANSE/Framework/Jobs/AreaPerMolecule.py index dece49de23..2c19d0ba58 100644 --- a/MDANSE/Src/MDANSE/Framework/Jobs/AreaPerMolecule.py +++ b/MDANSE/Src/MDANSE/Framework/Jobs/AreaPerMolecule.py @@ -98,8 +98,8 @@ def initialize(self): ) if self._nMolecules == 0: raise AreaPerMoleculeError( - "No molecule matches %r name." - % self.configuration["molecule_name"]["value"] + "No molecule matches " + f"{self.configuration['molecule_name']['value']!r} name." ) self._outputData.add( diff --git a/MDANSE/Src/MDANSE/Framework/Jobs/CoordinationNumber.py b/MDANSE/Src/MDANSE/Framework/Jobs/CoordinationNumber.py index 04a5a7f079..fc725617fe 100644 --- a/MDANSE/Src/MDANSE/Framework/Jobs/CoordinationNumber.py +++ b/MDANSE/Src/MDANSE/Framework/Jobs/CoordinationNumber.py @@ -90,43 +90,45 @@ def finalize(self): for pair in self._elementsPairs: invPair = pair[::-1] + pair_str = "".join(map(str, pair)) + inv_pair_str = "".join(map(str, invPair)) self._outputData.add( - "cn_intra_%s%s" % pair, + f"cn_intra_{pair_str}", "LineOutputVariable", (npoints,), axis="r", units="au", ) self._outputData.add( - "cn_inter_%s%s" % pair, + f"cn_inter_{pair_str}", "LineOutputVariable", (npoints,), axis="r", units="au", ) self._outputData.add( - "cn_total_%s%s" % pair, + f"cn_total_{pair_str}", "LineOutputVariable", (npoints,), axis="r", units="au", ) self._outputData.add( - "cn_intra_%s%s" % invPair, + f"cn_intra_{inv_pair_str}", "LineOutputVariable", (npoints,), axis="r", units="au", ) self._outputData.add( - "cn_inter_%s%s" % invPair, + f"cn_inter_{inv_pair_str}", "LineOutputVariable", (npoints,), axis="r", units="au", ) self._outputData.add( - "cn_total_%s%s" % invPair, + f"cn_total_{inv_pair_str}", "LineOutputVariable", (npoints,), axis="r", @@ -179,22 +181,22 @@ def finalize(self): invPair = pair[::-1] - self._outputData["cn_intra_%s%s" % pair][:] = ( + self._outputData[f"cn_intra_{pair_str}"][:] = ( self.averageDensity * cBeta * cnIntra ) - self._outputData["cn_inter_%s%s" % pair][:] = ( + self._outputData[f"cn_inter_{pair_str}"][:] = ( self.averageDensity * cBeta * cnInter ) - self._outputData["cn_total_%s%s" % pair][:] = ( + self._outputData[f"cn_total_{pair_str}"][:] = ( self.averageDensity * cBeta * cnTotal ) - self._outputData["cn_intra_%s%s" % invPair][:] = ( + self._outputData[f"cn_intra_{inv_pair_str}"][:] = ( self.averageDensity * cAlpha * cnIntra ) - self._outputData["cn_inter_%s%s" % invPair][:] = ( + self._outputData[f"cn_inter_{inv_pair_str}"][:] = ( self.averageDensity * cAlpha * cnInter ) - self._outputData["cn_total_%s%s" % invPair][:] = ( + self._outputData[f"cn_total_{inv_pair_str}"][:] = ( self.averageDensity * cAlpha * cnTotal ) diff --git a/MDANSE/Src/MDANSE/Framework/Jobs/CurrentCorrelationFunction.py b/MDANSE/Src/MDANSE/Framework/Jobs/CurrentCorrelationFunction.py index 87aca2d6bd..3fe6154ae5 100644 --- a/MDANSE/Src/MDANSE/Framework/Jobs/CurrentCorrelationFunction.py +++ b/MDANSE/Src/MDANSE/Framework/Jobs/CurrentCorrelationFunction.py @@ -171,22 +171,23 @@ def initialize(self): self._indicesPerElement = self.configuration["atom_selection"].get_indices() for pair in self._elementsPairs: + pair_str = "".join(map(str, pair)) self._outputData.add( - "j(q,t)_long_%s%s" % pair, + f"j(q,t)_long_{pair_str}", "SurfaceOutputVariable", (nQShells, self._nFrames), axis="q|time", units="au", ) self._outputData.add( - "j(q,t)_trans_%s%s" % pair, + f"j(q,t)_trans_{pair_str}", "SurfaceOutputVariable", (nQShells, self._nFrames), axis="q|time", units="au", ) self._outputData.add( - "J(q,f)_long_%s%s" % pair, + f"J(q,f)_long_{pair_str}", "SurfaceOutputVariable", (nQShells, self._nOmegas), axis="q|romega", @@ -195,7 +196,7 @@ def initialize(self): partial_result=True, ) self._outputData.add( - "J(q,f)_trans_%s%s" % pair, + f"J(q,f)_trans_{pair_str}", "SurfaceOutputVariable", (nQShells, self._nOmegas), axis="q|romega", @@ -344,10 +345,10 @@ def combine(self, index: int, x: Optional[tuple[np.ndarray, np.ndarray]]): """ if x is None: for at1, at2 in self._elementsPairs: - self._outputData["j(q,t)_long_%s%s" % (at1, at2)][index, :] = np.zeros( + self._outputData[f"j(q,t)_long_{at1}{at2}"][index, :] = np.zeros( self._nFrames ) - self._outputData["j(q,t)_trans_%s%s" % (at1, at2)][index, :] = np.zeros( + self._outputData[f"j(q,t)_trans_{at1}{at2}"][index, :] = np.zeros( self._nFrames ) return @@ -358,11 +359,11 @@ def combine(self, index: int, x: Optional[tuple[np.ndarray, np.ndarray]]): 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 + self._outputData[f"j(q,t)_long_{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]) - self._outputData["j(q,t)_trans_%s%s" % (at1, at2)][index, :] += corr_t.real + self._outputData[f"j(q,t)_trans_{at1}{at2}"][index, :] += corr_t.real def finalize(self): """Normalize, Fourier transform and write the results out to @@ -370,20 +371,21 @@ def finalize(self): """ nAtomsPerElement = self.configuration["atom_selection"].get_natoms() for pair in self._elementsPairs: + pair_str = "".join(map(str, pair)) at1, at2 = pair ni = nAtomsPerElement[at1] nj = nAtomsPerElement[at2] - self._outputData["j(q,t)_long_%s%s" % pair][:] /= ni * nj - self._outputData["j(q,t)_trans_%s%s" % pair][:] /= ni * nj - self._outputData["J(q,f)_long_%s%s" % pair][:] = get_spectrum( - self._outputData["j(q,t)_long_%s%s" % pair], + self._outputData[f"j(q,t)_long_{pair_str}"][:] /= ni * nj + self._outputData[f"j(q,t)_trans_{pair_str}"][:] /= ni * nj + self._outputData[f"J(q,f)_long_{pair_str}"][:] = get_spectrum( + self._outputData["j(q,t)_long_{pair_str}"], self.configuration["instrument_resolution"]["time_window"], self.configuration["instrument_resolution"]["time_step"], axis=1, fft="rfft", ) - self._outputData["J(q,f)_trans_%s%s" % pair][:] = get_spectrum( - self._outputData["j(q,t)_trans_%s%s" % pair], + self._outputData[f"J(q,f)_trans_{pair_str}"][:] = get_spectrum( + self._outputData[f"j(q,t)_trans_{pair_str}"], self.configuration["instrument_resolution"]["time_window"], self.configuration["instrument_resolution"]["time_step"], axis=1, diff --git a/MDANSE/Src/MDANSE/Framework/Jobs/DensityOfStates.py b/MDANSE/Src/MDANSE/Framework/Jobs/DensityOfStates.py index 9fc07955c7..a9a02470ec 100644 --- a/MDANSE/Src/MDANSE/Framework/Jobs/DensityOfStates.py +++ b/MDANSE/Src/MDANSE/Framework/Jobs/DensityOfStates.py @@ -130,14 +130,14 @@ def initialize(self): for element in self.configuration["atom_selection"]["unique_names"]: self._outputData.add( - "vacf_%s" % element, + f"vacf_{element}", "LineOutputVariable", (self.configuration["frames"]["n_frames"],), axis="time", units="nm2/ps2", ) self._outputData.add( - "dos_%s" % element, + f"dos_{element}", "LineOutputVariable", (instrResolution["n_romegas"],), axis="romega", @@ -225,7 +225,7 @@ def combine(self, index, x): # The symbol of the atom. element = self.configuration["atom_selection"]["names"][index] - self._outputData["vacf_%s" % element] += x + self._outputData[f"vacf_{element}"] += x def finalize(self): """ @@ -234,9 +234,9 @@ def finalize(self): nAtomsPerElement = self.configuration["atom_selection"].get_natoms() for element, number in nAtomsPerElement.items(): - self._outputData["vacf_%s" % element][:] /= number - self._outputData["dos_%s" % element][:] = get_spectrum( - self._outputData["vacf_%s" % element], + self._outputData[f"vacf_{element}"][:] /= number + self._outputData[f"dos_{element}"][:] = get_spectrum( + self._outputData[f"vacf_{element}"], self.configuration["instrument_resolution"]["time_window"], self.configuration["instrument_resolution"]["time_step"], fft="rfft", diff --git a/MDANSE/Src/MDANSE/Framework/Jobs/DensityProfile.py b/MDANSE/Src/MDANSE/Framework/Jobs/DensityProfile.py index 5dae1d5302..fa7332aa86 100644 --- a/MDANSE/Src/MDANSE/Framework/Jobs/DensityProfile.py +++ b/MDANSE/Src/MDANSE/Framework/Jobs/DensityProfile.py @@ -115,7 +115,7 @@ def initialize(self): for element in self._indices_per_element.keys(): self._outputData.add( - "dp_%s" % element, + f"dp_{element}", "LineOutputVariable", (self._n_bins,), axis="r", @@ -168,7 +168,7 @@ def combine(self, index, x): self._extent += x[0] for element, hist in list(x[1].items()): - self._outputData["dp_%s" % element] += hist + self._outputData[f"dp_{element}"] += hist def finalize(self): """ @@ -177,7 +177,7 @@ def finalize(self): n_atoms_per_element = self.configuration["atom_selection"].get_natoms() for element in n_atoms_per_element.keys(): - self._outputData["dp_%s" % element] += self.numberOfSteps + self._outputData[f"dp_{element}"] += self.numberOfSteps dp_total = weight( self.configuration["weights"].get_weights(), diff --git a/MDANSE/Src/MDANSE/Framework/Jobs/DynamicCoherentStructureFactor.py b/MDANSE/Src/MDANSE/Framework/Jobs/DynamicCoherentStructureFactor.py index 3482ee4ff4..1feeadcf97 100644 --- a/MDANSE/Src/MDANSE/Framework/Jobs/DynamicCoherentStructureFactor.py +++ b/MDANSE/Src/MDANSE/Framework/Jobs/DynamicCoherentStructureFactor.py @@ -148,15 +148,16 @@ def initialize(self): self._indicesPerElement = self.configuration["atom_selection"].get_indices() for pair in self._elementsPairs: + pair_str = "".join(map(str, pair)) self._outputData.add( - "f(q,t)_%s%s" % pair, + f"f(q,t)_{pair_str}", "SurfaceOutputVariable", (nQShells, self._nFrames), axis="q|time", units="au", ) self._outputData.add( - "s(q,f)_%s%s" % pair, + f"s(q,f)_{pair_str}", "SurfaceOutputVariable", (nQShells, self._nOmegas), axis="q|omega", @@ -236,12 +237,13 @@ def combine(self, index, x): if x is not None: n_configs = self.configuration["frames"]["n_configs"] for pair in self._elementsPairs: + pair_str = "".join(map(str, pair)) # 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]) - self._outputData["f(q,t)_%s%s" % pair][index, :] += corr.real + self._outputData[f"f(q,t)_{pair_str}"][index, :] += corr.real def finalize(self): """ @@ -250,11 +252,12 @@ def finalize(self): nAtomsPerElement = self.configuration["atom_selection"].get_natoms() for pair in self._elementsPairs: + pair_str = "".join(map(str, pair)) ni = nAtomsPerElement[pair[0]] nj = nAtomsPerElement[pair[1]] - self._outputData["f(q,t)_%s%s" % pair][:] /= np.sqrt(ni * nj) - self._outputData["s(q,f)_%s%s" % pair][:] = get_spectrum( - self._outputData["f(q,t)_%s%s" % pair], + self._outputData[f"f(q,t)_{pair_str}"][:] /= np.sqrt(ni * nj) + self._outputData[f"s(q,f)_{pair_str}"][:] = get_spectrum( + self._outputData[f"f(q,t)_{pair_str}"], self.configuration["instrument_resolution"]["time_window"], self.configuration["instrument_resolution"]["time_step"], axis=1, diff --git a/MDANSE/Src/MDANSE/Framework/Jobs/DynamicIncoherentStructureFactor.py b/MDANSE/Src/MDANSE/Framework/Jobs/DynamicIncoherentStructureFactor.py index ef6d2ceb7a..1c20b0af50 100644 --- a/MDANSE/Src/MDANSE/Framework/Jobs/DynamicIncoherentStructureFactor.py +++ b/MDANSE/Src/MDANSE/Framework/Jobs/DynamicIncoherentStructureFactor.py @@ -153,14 +153,14 @@ def initialize(self): for element in self.configuration["atom_selection"]["unique_names"]: self._outputData.add( - "f(q,t)_%s" % element, + f"f(q,t)_{element}", "SurfaceOutputVariable", (self._nQShells, self._nFrames), axis="q|time", units="au", ) self._outputData.add( - "s(q,f)_%s" % element, + f"s(q,f)_{element}", "SurfaceOutputVariable", (self._nQShells, self._nOmegas), axis="q|omega", @@ -254,9 +254,9 @@ def finalize(self): nAtomsPerElement = self.configuration["atom_selection"].get_natoms() for element, number in list(nAtomsPerElement.items()): - self._outputData["f(q,t)_%s" % element][:] /= number - self._outputData["s(q,f)_%s" % element][:] = get_spectrum( - self._outputData["f(q,t)_%s" % element], + self._outputData[f"f(q,t)_{element}"][:] /= number + self._outputData[f"s(q,f)_{element}"][:] = get_spectrum( + self._outputData[f"f(q,t)_{element}"], self.configuration["instrument_resolution"]["time_window"], self.configuration["instrument_resolution"]["time_step"], axis=1, diff --git a/MDANSE/Src/MDANSE/Framework/Jobs/ElasticIncoherentStructureFactor.py b/MDANSE/Src/MDANSE/Framework/Jobs/ElasticIncoherentStructureFactor.py index 755c1a55b4..face85b9aa 100644 --- a/MDANSE/Src/MDANSE/Framework/Jobs/ElasticIncoherentStructureFactor.py +++ b/MDANSE/Src/MDANSE/Framework/Jobs/ElasticIncoherentStructureFactor.py @@ -116,7 +116,7 @@ def initialize(self): for element in self.configuration["atom_selection"]["unique_names"]: self._outputData.add( - "eisf_%s" % element, + f"eisf_{element}", "LineOutputVariable", (self._nQShells,), axis="q", @@ -187,7 +187,7 @@ def combine(self, index, x): # The symbol of the atom. element = self.configuration["atom_selection"]["names"][index] - self._outputData["eisf_%s" % element] += x + self._outputData[f"eisf_{element}"] += x def finalize(self): """ @@ -196,7 +196,7 @@ def finalize(self): nAtomsPerElement = self.configuration["atom_selection"].get_natoms() for element, number in list(nAtomsPerElement.items()): - self._outputData["eisf_%s" % element][:] /= number + self._outputData[f"eisf_{element}"][:] /= number weights = self.configuration["weights"].get_weights() self._outputData["eisf_total"][:] = weight( diff --git a/MDANSE/Src/MDANSE/Framework/Jobs/GaussianDynamicIncoherentStructureFactor.py b/MDANSE/Src/MDANSE/Framework/Jobs/GaussianDynamicIncoherentStructureFactor.py index 5e8ce62d09..dc67d8caaf 100644 --- a/MDANSE/Src/MDANSE/Framework/Jobs/GaussianDynamicIncoherentStructureFactor.py +++ b/MDANSE/Src/MDANSE/Framework/Jobs/GaussianDynamicIncoherentStructureFactor.py @@ -151,14 +151,14 @@ def initialize(self): for element in self.configuration["atom_selection"]["unique_names"]: self._outputData.add( - "f(q,t)_%s" % element, + f"f(q,t)_{element}", "SurfaceOutputVariable", (self._nQShells, self._nFrames), axis="q|time", units="au", ) self._outputData.add( - "s(q,f)_%s" % element, + f"s(q,f)_{element}", "SurfaceOutputVariable", (self._nQShells, self._nOmegas), axis="q|omega", @@ -234,7 +234,7 @@ def combine(self, index, x): # The symbol of the atom. element = self.configuration["atom_selection"]["names"][index] - self._outputData["f(q,t)_%s" % element] += x + self._outputData[f"f(q,t)_{element}"] += x def finalize(self): """ @@ -243,9 +243,9 @@ def finalize(self): nAtomsPerElement = self.configuration["atom_selection"].get_natoms() for element, number in nAtomsPerElement.items(): - self._outputData["f(q,t)_%s" % element][:] /= number - self._outputData["s(q,f)_%s" % element][:] = get_spectrum( - self._outputData["f(q,t)_%s" % element], + self._outputData[f"f(q,t)_{element}"][:] /= number + self._outputData[f"s(q,f)_{element}"][:] = get_spectrum( + self._outputData[f"f(q,t)_{element}"], self.configuration["instrument_resolution"]["time_window"], self.configuration["instrument_resolution"]["time_step"], axis=1, diff --git a/MDANSE/Src/MDANSE/Framework/Jobs/GeneralAutoCorrelationFunction.py b/MDANSE/Src/MDANSE/Framework/Jobs/GeneralAutoCorrelationFunction.py index cddda4c8d7..2e3e36ab1c 100644 --- a/MDANSE/Src/MDANSE/Framework/Jobs/GeneralAutoCorrelationFunction.py +++ b/MDANSE/Src/MDANSE/Framework/Jobs/GeneralAutoCorrelationFunction.py @@ -150,7 +150,7 @@ def combine(self, index, x): element = self.configuration["atom_selection"]["names"][index] - self._outputData["gacf_%s" % element] += x + self._outputData[f"gacf_{element}"] += x def finalize(self): """ @@ -169,7 +169,7 @@ def finalize(self): raise ValueError("The normalization factor is equal to zero") else: self._outputData["gacf_{}".format(element)] = normalize( - self._outputData["gacf_%s" % element], axis=0 + self._outputData[f"gacf_{element}"], axis=0 ) weights = self.configuration["weights"].get_weights() diff --git a/MDANSE/Src/MDANSE/Framework/Jobs/IJob.py b/MDANSE/Src/MDANSE/Framework/Jobs/IJob.py index f41191ce24..60aee6b948 100644 --- a/MDANSE/Src/MDANSE/Framework/Jobs/IJob.py +++ b/MDANSE/Src/MDANSE/Framework/Jobs/IJob.py @@ -63,7 +63,7 @@ def __init__(self, job, message=None): self._message = str(message) - trace.append("\n%s" % self._message) + trace.append(f"\n{self._message}") trace = "\n".join(trace) @@ -83,7 +83,7 @@ def key_generator(keySize, chars=None, prefix=""): key = "".join(random.choice(chars) for _ in range(keySize)) if prefix: - key = "%s_%s" % (prefix, key) + key = f"{prefix}_{key}" return key @@ -103,7 +103,7 @@ def define_unique_name(): Sets a name for the job that is not already in use by another running job. """ - prefix = "%s_%d" % (PLATFORM.username()[:4], PLATFORM.pid()) + prefix = f"{PLATFORM.username()[:4]}_{PLATFORM.pid():d}" # The list of the registered jobs. registeredJobs = [ @@ -197,7 +197,7 @@ def save(cls, jobFile, parameters=None): # The first line contains the call to the python executable. This is necessary for the file to # be autostartable. - f.write("#!%s\n\n" % sys.executable) + f.write(f"#!{sys.executable}\n\n") # Writes the input file header. f.write("########################################################\n") @@ -230,8 +230,8 @@ def save(cls, jobFile, parameters=None): f.write("\n") f.write('if __name__ == "__main__":\n') - f.write(" %s = IJob.create(%r)\n" % (cls.__name__.lower(), cls.__name__)) - f.write(" %s.run(parameters, status=True)\n" % (cls.__name__.lower())) + f.write(f" {cls.__name__.lower()} = IJob.create({cls.__name__!r})\n") + f.write(f" {cls.__name__.lower()}.run(parameters, status=True)\n") f.close() @@ -386,7 +386,7 @@ def run(self, parameters, status=False): """ try: - self._name = "%s_%s" % (self.__class__.__name__, IJob.define_unique_name()) + self._name = f"{self.__class__.__name__}_{IJob.define_unique_name()}" if status and self._status is None: self._status = self._status_constructor(self) @@ -400,7 +400,7 @@ def run(self, parameters, status=False): self._status.state["info"] = str(self) if getattr(self, "numberOfSteps", 0) <= 0: - raise JobError(self, "Invalid number of steps for job %s" % self._name) + raise JobError(self, f"Invalid number of steps for job {self._name}") if "running_mode" in self.configuration: mode = self.configuration["running_mode"]["mode"] @@ -426,26 +426,26 @@ def info(self): 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 + f"A job with {shortname!r} name is already stored in the registry" ) templateFile = PLATFORM.macros_directory() / f"{classname}.py" try: + label = "label of the class" with templateFile.open("w") as f: - f.write( - '''import collections + f'''import collections from MDANSE.Framework.Jobs.IJob import IJob -class %(classname)s(IJob): +class {classname}s(IJob): """ You should enter the description of your job here ... """ # You should enter the label under which your job will be viewed from the gui. - label = %(label)r + label = {label!r} # You should enter the category under which your job will be references. category = ('My jobs',) @@ -455,9 +455,9 @@ class %(classname)s(IJob): # You should enter the configuration of your job here # Here a basic example of a job that will use a HDF trajectory, a frame selection and an output file in HDF5 and Text file formats settings = collections.OrderedDict() - settings['trajectory']=('hdf_trajectory',{}) - settings['frames']=('frames', {"dependencies":{'trajectory':'trajectory'}}) - settings['output_files']=('output_files', {"formats":["HDFFormat","netcdf","TextFormat"]}) + settings['trajectory']=('hdf_trajectory',{{}}) + settings['frames']=('frames', {{"dependencies":{{'trajectory':'trajectory'}}}}) + settings['output_files']=('output_files', {{"formats":["HDFFormat","netcdf","TextFormat"]}}) def initialize(self): """ @@ -497,13 +497,8 @@ def finalize(self): # The trajectory is closed self.configuration['trajectory']['instance'].close() - ''' - % { - "classname": classname, - "label": "label of the class", - "shortname": shortname, - } - ) +''' + ) except IOError: return None diff --git a/MDANSE/Src/MDANSE/Framework/Jobs/McStasVirtualInstrument.py b/MDANSE/Src/MDANSE/Framework/Jobs/McStasVirtualInstrument.py index 89fdf873d4..e14bc0bd22 100644 --- a/MDANSE/Src/MDANSE/Framework/Jobs/McStasVirtualInstrument.py +++ b/MDANSE/Src/MDANSE/Framework/Jobs/McStasVirtualInstrument.py @@ -231,15 +231,15 @@ def run_step(self, index): fout.write("# Physical parameters:\n") for k, v in list(self._mcStasPhysicalParameters.items()): - fout.write("# %s %s \n" % (k, v)) + fout.write(f"# {k} {v} \n") fout.write( - "# Temperature %s \n" % self.configuration["temperature"]["value"] + f"# Temperature {self.configuration['temperature']['value']} \n" ) fout.write("#\n") for var in self.configuration[typ].variables: - fout.write("# %s\n" % var) + fout.write(f"# {var}\n") data = self.configuration[typ][var][:] LOG.info(f"In {typ} the variable {var} has shape {data.shape}") @@ -261,7 +261,7 @@ def run_step(self, index): # + typ # + ".sqw" # ) - sqwInput += "%s=%s " % (typ, fout.name) + sqwInput += f"{typ}={fout.name} " # sys.exit(0) @@ -290,7 +290,7 @@ def run_step(self, index): for line in out.splitlines(): if "ERROR" in line.decode(encoding="utf-8"): - raise McStasError("An error occured during McStas run: %s" % out) + raise McStasError(f"An error occured during McStas run: {out}") out_file = self.mcstas_output_dir / "mcstas_mdanse.mvi" with out_file.open("w") as f: @@ -340,7 +340,7 @@ def unique(self, key, d, value=None): if np.allclose(v, value): return k while key in d: - key = skey + "_%d" % i + key = f"{skey}_{i:d}" i += 1 return key @@ -432,7 +432,7 @@ def save_single(self, FileStruct): "LineOutputVariable", x, xlabel, units="au" ) self._outputData[Title] = IOutputVariable.create( - "LineOutputVariable", y, Title, axis="%s" % xlabel, units="au" + "LineOutputVariable", y, Title, axis=str(xlabel), units="au" ) elif typ == "array_2d": @@ -467,7 +467,7 @@ def save_single(self, FileStruct): title, "SurfaceOutputVariable", I, - axis="%s|%s" % (xlabel, ylabel), + axis=f"{xlabel}|{ylabel}", units="au", main_result=True, partial_result=True, diff --git a/MDANSE/Src/MDANSE/Framework/Jobs/MeanSquareDisplacement.py b/MDANSE/Src/MDANSE/Framework/Jobs/MeanSquareDisplacement.py index b59d04729d..320351c6bd 100644 --- a/MDANSE/Src/MDANSE/Framework/Jobs/MeanSquareDisplacement.py +++ b/MDANSE/Src/MDANSE/Framework/Jobs/MeanSquareDisplacement.py @@ -123,7 +123,7 @@ def initialize(self): # Will store the mean square displacement evolution. for element in self.configuration["atom_selection"]["unique_names"]: self._outputData.add( - "msd_%s" % element, + f"msd_{element}", "LineOutputVariable", (self.configuration["frames"]["n_frames"],), axis="time", @@ -186,7 +186,7 @@ def combine(self, index, result): # The symbol of the atom. element = self.configuration["atom_selection"]["names"][index] - self._outputData["msd_%s" % element] += result + self._outputData[f"msd_{element}"] += result def finalize(self): """ @@ -196,7 +196,7 @@ def finalize(self): # The MSDs per element are averaged. nAtomsPerElement = self.configuration["atom_selection"].get_natoms() for element, number in list(nAtomsPerElement.items()): - self._outputData["msd_%s" % element] /= number + self._outputData[f"msd_{element}"] /= number weights = self.configuration["weights"].get_weights() msdTotal = weight(weights, self._outputData, nAtomsPerElement, 1, "msd_%s") diff --git a/MDANSE/Src/MDANSE/Framework/Jobs/NeutronDynamicTotalStructureFactor.py b/MDANSE/Src/MDANSE/Framework/Jobs/NeutronDynamicTotalStructureFactor.py index cb827cde9e..0538309edd 100644 --- a/MDANSE/Src/MDANSE/Framework/Jobs/NeutronDynamicTotalStructureFactor.py +++ b/MDANSE/Src/MDANSE/Framework/Jobs/NeutronDynamicTotalStructureFactor.py @@ -237,28 +237,28 @@ def initialize(self): "s(q,f)_{}".format(element) ] self._outputData.add( - "f(q,t)_inc_%s" % element, + f"f(q,t)_inc_{element}", "SurfaceOutputVariable", fqt, axis="q|time", units="au", ) self._outputData.add( - "s(q,f)_inc_%s" % element, + f"s(q,f)_inc_{element}", "SurfaceOutputVariable", sqf, axis="q|omega", units="nm2/ps", ) self._outputData.add( - "f(q,t)_inc_weighted_%s" % element, + f"f(q,t)_inc_weighted_{element}", "SurfaceOutputVariable", fqt.shape, axis="q|time", units="au", ) self._outputData.add( - "s(q,f)_inc_weighted_%s" % element, + f"s(q,f)_inc_weighted_{element}", "SurfaceOutputVariable", sqf.shape, axis="q|omega", @@ -266,35 +266,36 @@ def initialize(self): ) for pair in self._elementsPairs: + pair_str = ''.join(map(str, pair)) fqt = self.configuration["dcsf_input_file"]["instance"][ - "f(q,t)_{}{}".format(*pair) + f"f(q,t)_{pair_str}" ] sqf = self.configuration["dcsf_input_file"]["instance"][ - "s(q,f)_{}{}".format(*pair) + f"s(q,f)_{pair_str}" ] self._outputData.add( - "f(q,t)_coh_%s%s" % pair, + f"f(q,t)_coh_{pair_str}", "SurfaceOutputVariable", fqt, axis="q|time", units="au", ) self._outputData.add( - "s(q,f)_coh_%s%s" % pair, + f"s(q,f)_coh_{pair_str}", "SurfaceOutputVariable", sqf, axis="q|omega", units="nm2/ps", ) self._outputData.add( - "f(q,t)_coh_weighted_%s%s" % pair, + f"f(q,t)_coh_weighted_{pair_str}", "SurfaceOutputVariable", fqt.shape, axis="q|time", units="au", ) self._outputData.add( - "s(q,f)_coh_weighted_%s%s" % pair, + f"s(q,f)_coh_weighted_{pair_str}", "SurfaceOutputVariable", sqf.shape, axis="q|omega", @@ -400,31 +401,31 @@ def finalize(self): ci = ni / nTotalAtoms cj = nj / nTotalAtoms - self._outputData["f(q,t)_coh_weighted_%s%s" % pair][:] = ( - self._outputData["f(q,t)_coh_%s%s" % pair][:] + self._outputData[f"f(q,t)_coh_weighted_{pair_str}"][:] = ( + self._outputData[f"f(q,t)_coh_{pair_str}"][:] * 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][:] + self._outputData[f"s(q,f)_coh_weighted_{pair_str}"][:] = ( + self._outputData[f"s(q,f)_coh_{pair_str}"][:] * 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[ - "f(q,t)_coh_weighted_%s%s" % pair + f"f(q,t)_coh_weighted_{pair_str}" ][:] self._outputData["s(q,f)_coh_total"][:] += self._outputData[ - "s(q,f)_coh_weighted_%s%s" % pair + f"s(q,f)_coh_weighted_{pair_str}" ][:] else: self._outputData["f(q,t)_coh_total"][:] += ( - 2 * self._outputData["f(q,t)_coh_weighted_%s%s" % pair][:] + 2 * self._outputData[f"f(q,t)_coh_weighted_{pair_str}"][:] ) self._outputData["s(q,f)_coh_total"][:] += ( - 2 * self._outputData["s(q,f)_coh_weighted_%s%s" % pair][:] + 2 * self._outputData[f"s(q,f)_coh_weighted_{pair_str}"][:] ) # Compute incoherent functions and structure factor @@ -435,18 +436,18 @@ def finalize(self): ni = nAtomsPerElement[element] ci = ni / nTotalAtoms - self._outputData["f(q,t)_inc_weighted_%s" % element][:] = ( - self._outputData["f(q,t)_inc_%s" % element][:] * ci * bi + self._outputData[f"f(q,t)_inc_weighted_{element}"][:] = ( + self._outputData[f"f(q,t)_inc_{element}"][:] * ci * bi ) - self._outputData["s(q,f)_inc_weighted_%s" % element][:] = ( - self._outputData["s(q,f)_inc_%s" % element][:] * ci * bi + self._outputData[f"s(q,f)_inc_weighted_{element}"][:] = ( + self._outputData[f"s(q,f)_inc_{element}"][:] * ci * bi ) self._outputData["f(q,t)_inc_total"][:] += self._outputData[ - "f(q,t)_inc_weighted_%s" % element + f"f(q,t)_inc_weighted_{element}" ][:] self._outputData["s(q,f)_inc_total"][:] += self._outputData[ - "s(q,f)_inc_weighted_%s" % element + f"s(q,f)_inc_weighted_{element}" ][:] # Compute total F(Q,t) = inc + coh diff --git a/MDANSE/Src/MDANSE/Framework/Jobs/PairDistributionFunction.py b/MDANSE/Src/MDANSE/Framework/Jobs/PairDistributionFunction.py index 5a78dfeba7..a5e8a7dc61 100644 --- a/MDANSE/Src/MDANSE/Framework/Jobs/PairDistributionFunction.py +++ b/MDANSE/Src/MDANSE/Framework/Jobs/PairDistributionFunction.py @@ -63,21 +63,21 @@ def finalize(self): for x, y in self._elementsPairs: for i in ["pdf", "rdf", "tcf"]: self._outputData.add( - "%s_intra_%s%s" % (i, x, y), + f"{i}_intra_{x}{y}", "LineOutputVariable", (npoints,), axis="r", units="au", ) self._outputData.add( - "%s_inter_%s%s" % (i, x, y), + f"{i}_inter_{x}{y}", "LineOutputVariable", (npoints,), axis="r", units="au", ) self._outputData.add( - "%s_total_%s%s" % (i, x, y), + f"{i}_total_{x}{y}", "LineOutputVariable", (npoints,), axis="r", @@ -86,21 +86,21 @@ def finalize(self): for i in ["pdf", "rdf", "tcf"]: self._outputData.add( - "%s_intra_total" % i, + f"{i}_intra_total", "LineOutputVariable", (npoints,), axis="r", units="au", ) self._outputData.add( - "%s_inter_total" % i, + f"{i}_inter_total", "LineOutputVariable", (npoints,), axis="r", units="au", ) self._outputData.add( - "%s_total" % i, "LineOutputVariable", (npoints,), axis="r", units="au" + f"{i}_total", "LineOutputVariable", (npoints,), axis="r", units="au" ) nFrames = self.configuration["frames"]["number"] @@ -138,11 +138,11 @@ def finalize(self): 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])][:] = ( + self._outputData[f"pdf_{i}_{pair[0]}{pair[1]}")][:] = pdf + self._outputData[f"rdf_{i}_{pair[0]}{pair[1]}")][:] = ( shellSurfaces * self.averageDensity * pdf ) - self._outputData["tcf_%s_%s%s" % (i, pair[0], pair[1])][:] = ( + self._outputData[f"tcf_{i}_{pair[0]}{pair[1]}")][:] = ( densityFactor * self.averageDensity * (pdf if i == "intra" else pdf - 1) @@ -156,13 +156,13 @@ def finalize(self): self._outputData, nAtomsPerElement, 2, - "pdf{}_%s%s".format(i if i else "_total"), + f"pdf{i if i else "_total"}_%s%s", ) - self._outputData["pdf%s_total" % i][:] = pdf - self._outputData["rdf%s_total" % i][:] = ( + self._outputData[f"pdf{i}_total"][:] = pdf + self._outputData[f"rdf{i}_total"][:] = ( shellSurfaces * self.averageDensity * pdf ) - self._outputData["tcf%s_total" % i][:] = ( + self._outputData[f"tcf{i}_total"][:] = ( densityFactor * self.averageDensity * (pdf if i == "_intra" else pdf - 1) diff --git a/MDANSE/Src/MDANSE/Framework/Jobs/PositionAutoCorrelationFunction.py b/MDANSE/Src/MDANSE/Framework/Jobs/PositionAutoCorrelationFunction.py index 1143f0f3ff..ec2cb62eaf 100644 --- a/MDANSE/Src/MDANSE/Framework/Jobs/PositionAutoCorrelationFunction.py +++ b/MDANSE/Src/MDANSE/Framework/Jobs/PositionAutoCorrelationFunction.py @@ -105,7 +105,7 @@ def initialize(self): # Will store the mean square displacement evolution. for element in self.configuration["atom_selection"]["unique_names"]: self._outputData.add( - "pacf_%s" % element, + f"pacf_{element}", "LineOutputVariable", (self.configuration["frames"]["n_frames"],), axis="time", @@ -160,7 +160,7 @@ def combine(self, index, x): element = self.configuration["atom_selection"]["names"][index] # The MSD for element |symbol| is updated. - self._outputData["pacf_%s" % element] += x + self._outputData[f"pacf_{element}"] += x def finalize(self): """ @@ -171,15 +171,15 @@ def finalize(self): self.configuration["atom_selection"]["n_atoms_per_element"] = nAtomsPerElement for element, number in list(nAtomsPerElement.items()): - self._outputData["pacf_%s" % element] /= number + self._outputData[f"pacf_{element}"] /= number if self.configuration["normalize"]["value"]: for element in list(nAtomsPerElement.keys()): - if self._outputData["pacf_%s" % element][0] == 0: + if self._outputData[f"pacf_{element}"][0] == 0: raise ValueError("The normalization factor is equal to zero !!!") else: - self._outputData["pacf_%s" % element] = normalize( - self._outputData["pacf_%s" % element], axis=0 + self._outputData[f"pacf_{element}"] = normalize( + self._outputData[f"pacf_{element}"], axis=0 ) weights = self.configuration["weights"].get_weights() diff --git a/MDANSE/Src/MDANSE/Framework/Jobs/PositionPowerSpectrum.py b/MDANSE/Src/MDANSE/Framework/Jobs/PositionPowerSpectrum.py index 28989ade79..181871998d 100644 --- a/MDANSE/Src/MDANSE/Framework/Jobs/PositionPowerSpectrum.py +++ b/MDANSE/Src/MDANSE/Framework/Jobs/PositionPowerSpectrum.py @@ -122,14 +122,14 @@ def initialize(self): for element in self.configuration["atom_selection"]["unique_names"]: self._outputData.add( - "pacf_%s" % element, + f"pacf_{element}", "LineOutputVariable", (self.configuration["frames"]["n_frames"],), axis="time", units="nm2", ) self._outputData.add( - "pps_%s" % element, + f"pps_{element}", "LineOutputVariable", (instrResolution["n_romegas"],), axis="romega", @@ -202,7 +202,7 @@ def combine(self, index, x): # The symbol of the atom. element = self.configuration["atom_selection"]["names"][index] - self._outputData["pacf_%s" % element] += x + self._outputData[f"pacf_{element}"] += x def finalize(self): """ @@ -211,9 +211,9 @@ def finalize(self): nAtomsPerElement = self.configuration["atom_selection"].get_natoms() for element, number in nAtomsPerElement.items(): - self._outputData["pacf_%s" % element][:] /= number - self._outputData["pps_%s" % element][:] = get_spectrum( - self._outputData["pacf_%s" % element], + self._outputData[f"pacf_{element}"][:] /= number + self._outputData[f"pps_{element}"][:] = get_spectrum( + self._outputData[f"pacf_{element}"], self.configuration["instrument_resolution"]["time_window"], self.configuration["instrument_resolution"]["time_step"], fft="rfft", diff --git a/MDANSE/Src/MDANSE/Framework/Jobs/RigidBodyTrajectory.py b/MDANSE/Src/MDANSE/Framework/Jobs/RigidBodyTrajectory.py index 1aa6682aed..1cb5f0c487 100644 --- a/MDANSE/Src/MDANSE/Framework/Jobs/RigidBodyTrajectory.py +++ b/MDANSE/Src/MDANSE/Framework/Jobs/RigidBodyTrajectory.py @@ -90,8 +90,8 @@ def initialize(self): ): raise JobError( self, - "Invalid reference frame. Must be an integer in [%d,%d[" - % (0, self.configuration["trajectory"]["length"]), + "Invalid reference frame. Must be an integer in " + f"[{0},{self.configuration['trajectory']['length']}[" ) self._quaternions = np.zeros( @@ -260,10 +260,7 @@ def finalize(self): for comp in range(self.configuration["atom_selection"]["selection_length"]): aIndexes = self.configuration["atom_selection"]["indices"][comp] - outputFile.attrs["info"] += "Group %s: %s\n" % ( - comp, - [index for index in aIndexes], - ) + outputFile.attrs["info"] += f"Group {comp}: {list(aIndexes)}\n" quaternions[comp, :, :] = self._quaternions[comp, :, :] coms[comp, :, :] = self._coms[comp, :, :] diff --git a/MDANSE/Src/MDANSE/Framework/Jobs/RootMeanSquareDeviation.py b/MDANSE/Src/MDANSE/Framework/Jobs/RootMeanSquareDeviation.py index 1ceeb2001f..74d34d9698 100644 --- a/MDANSE/Src/MDANSE/Framework/Jobs/RootMeanSquareDeviation.py +++ b/MDANSE/Src/MDANSE/Framework/Jobs/RootMeanSquareDeviation.py @@ -146,7 +146,7 @@ def combine(self, index, x): element = self.configuration["atom_selection"]["names"][index] - self._outputData["rmsd_%s" % element] += x + self._outputData[f"rmsd_{element}"] += x self._outputData["rmsd_all"] += x def finalize(self): diff --git a/MDANSE/Src/MDANSE/Framework/Jobs/StaticStructureFactor.py b/MDANSE/Src/MDANSE/Framework/Jobs/StaticStructureFactor.py index 2c9445f0a1..3392e686ce 100644 --- a/MDANSE/Src/MDANSE/Framework/Jobs/StaticStructureFactor.py +++ b/MDANSE/Src/MDANSE/Framework/Jobs/StaticStructureFactor.py @@ -142,22 +142,23 @@ def finalize(self): nAtomsPerElement = self.configuration["atom_selection"].get_natoms() for pair in self._elementsPairs: + pair_str = ''.join(map(str, pair)) self._outputData.add( - "ssf_intra_%s%s" % pair, + f"ssf_intra_{pair_str}", "LineOutputVariable", (nq,), axis="q", units="au", ) self._outputData.add( - "ssf_inter_%s%s" % pair, + f"ssf_inter_{pair_str}", "LineOutputVariable", (nq,), axis="q", units="au", ) self._outputData.add( - "ssf_total_%s%s" % pair, + f"ssf_total_{pair_str}", "LineOutputVariable", (nq,), axis="q", @@ -182,15 +183,15 @@ def finalize(self): pdfIntra = self.hIntra[idi, idj, :] / fact pdfInter = self.hInter[idi, idj, :] / fact - self._outputData["ssf_intra_%s%s" % pair][:] = ( + self._outputData[f"ssf_intra_{pair_str}"][:] = ( fact1 * np.sum((r**2) * pdfIntra * sincqr, axis=1) * dr ) - self._outputData["ssf_inter_%s%s" % pair][:] = ( + self._outputData[f"ssf_inter_{pair_str}"][:] = ( 1.0 + fact1 * np.sum((r**2) * (pdfInter - 1.0) * sincqr, axis=1) * dr ) - self._outputData["ssf_total_%s%s" % pair][:] = ( - self._outputData["ssf_intra_%s%s" % pair][:] - + self._outputData["ssf_inter_%s%s" % pair][:] + self._outputData[f"ssf_total_{pair_str}"][:] = ( + self._outputData[f"ssf_intra_{pair_str}"][:] + + self._outputData[f"ssf_inter_{pair_str}"][:] ) self._outputData.add( diff --git a/MDANSE/Src/MDANSE/Framework/Jobs/StructureFactorFromScatteringFunction.py b/MDANSE/Src/MDANSE/Framework/Jobs/StructureFactorFromScatteringFunction.py index f8b706c79c..dfbb18cf9c 100644 --- a/MDANSE/Src/MDANSE/Framework/Jobs/StructureFactorFromScatteringFunction.py +++ b/MDANSE/Src/MDANSE/Framework/Jobs/StructureFactorFromScatteringFunction.py @@ -100,7 +100,7 @@ def initialize(self): ) suffix = k[7:] self._outputData.add( - "s(q,f)_%s" % suffix, + f"s(q,f)_{suffix}", "SurfaceOutputVariable", (nQVectors, nOmegas), axis="q|omega", @@ -108,7 +108,7 @@ def initialize(self): main_result=True, partial_result=True, ) - self._outputData["s(q,f)_%s" % suffix][:] = get_spectrum( + self._outputData[f"s(q,f)_{suffix}"][:] = get_spectrum( v[:], self.configuration["instrument_resolution"]["time_window"], self.configuration["instrument_resolution"]["time_step"], diff --git a/MDANSE/Src/MDANSE/Framework/Jobs/VanHoveFunctionDistinct.py b/MDANSE/Src/MDANSE/Framework/Jobs/VanHoveFunctionDistinct.py index 7dfd561780..953971b88b 100644 --- a/MDANSE/Src/MDANSE/Framework/Jobs/VanHoveFunctionDistinct.py +++ b/MDANSE/Src/MDANSE/Framework/Jobs/VanHoveFunctionDistinct.py @@ -315,21 +315,21 @@ def initialize(self): ) for x, y in self._elementsPairs: self._outputData.add( - "g(r,t)_intra_%s%s" % (x, y), + f"g(r,t)_intra_{x}{y}", "SurfaceOutputVariable", (self.n_mid_points, self.numberOfSteps), axis="r|time", units="au", ) self._outputData.add( - "g(r,t)_inter_%s%s" % (x, y), + f"g(r,t)_inter_{x}{y}", "SurfaceOutputVariable", (self.n_mid_points, self.numberOfSteps), axis="r|time", units="au", ) self._outputData.add( - "g(r,t)_total_%s%s" % (x, y), + f"g(r,t)_total_{x}{y}", "SurfaceOutputVariable", (self.n_mid_points, self.numberOfSteps), axis="r|time", @@ -484,7 +484,7 @@ def finalize(self): ["intra", "inter", "total"], [van_hove_intra, van_hove_inter, van_hove_total], ): - self._outputData["g(r,t)_%s_%s%s" % (i, pair[0], pair[1])][ + self._outputData[f"g(r,t)_{i}_{pair[0]}{pair[1]}"][ ... ] = van_hove @@ -495,9 +495,9 @@ def finalize(self): self._outputData, nAtomsPerElement, 2, - "g(r,t){}_%s%s".format(i if i else "_total"), + f"g(r,t){i if i else '_total'}_%s%s", ) - self._outputData["g(r,t)%s_total" % i][...] = pdf + self._outputData[f"g(r,t){i}_total"][...] = pdf self._outputData.write( self.configuration["output_files"]["root"], diff --git a/MDANSE/Src/MDANSE/Framework/Jobs/VanHoveFunctionSelf.py b/MDANSE/Src/MDANSE/Framework/Jobs/VanHoveFunctionSelf.py index 16bceccbf1..738610c13e 100644 --- a/MDANSE/Src/MDANSE/Framework/Jobs/VanHoveFunctionSelf.py +++ b/MDANSE/Src/MDANSE/Framework/Jobs/VanHoveFunctionSelf.py @@ -182,14 +182,14 @@ def initialize(self): ) for element in self.selectedElements: self._outputData.add( - "g(r,t)_%s" % element, + f"g(r,t)_{element}", "SurfaceOutputVariable", (self.n_mid_points, self.n_frames), axis="r|time", units="au", ) self._outputData.add( - "4_pi_r2_g(r,t)_%s" % element, + f"4_pi_r2_g(r,t)_{element}", "SurfaceOutputVariable", (self.n_mid_points, self.n_frames), axis="r|time", @@ -284,10 +284,10 @@ def finalize(self): nAtomsPerElement = self.configuration["atom_selection"].get_natoms() for element, number in list(nAtomsPerElement.items()): - self._outputData["g(r,t)_%s" % element][:] /= ( + self._outputData[f"g(r,t)_{element}"][:] /= ( self.shell_volumes[:, np.newaxis] * number**2 * self.n_configs ) - self._outputData["4_pi_r2_g(r,t)_%s" % element][:] /= ( + self._outputData[f"4_pi_r2_g(r,t)_{element}"][:] /= ( number**2 * self.n_configs * self.configuration["r_values"]["step"] ) diff --git a/MDANSE/Src/MDANSE/Framework/Jobs/VelocityAutoCorrelationFunction.py b/MDANSE/Src/MDANSE/Framework/Jobs/VelocityAutoCorrelationFunction.py index dbe8c64dbb..272a5df1d4 100644 --- a/MDANSE/Src/MDANSE/Framework/Jobs/VelocityAutoCorrelationFunction.py +++ b/MDANSE/Src/MDANSE/Framework/Jobs/VelocityAutoCorrelationFunction.py @@ -123,7 +123,7 @@ def initialize(self): for element in self.configuration["atom_selection"]["unique_names"]: self._outputData.add( - "vacf_%s" % element, + f"vacf_{element}", "LineOutputVariable", (self.configuration["frames"]["n_frames"],), axis="time", @@ -205,7 +205,7 @@ def combine(self, index, x): # The symbol of the atom. element = self.configuration["atom_selection"]["names"][index] - self._outputData["vacf_%s" % element] += x + self._outputData[f"vacf_{element}"] += x def finalize(self): """ @@ -214,7 +214,7 @@ def finalize(self): nAtomsPerElement = self.configuration["atom_selection"].get_natoms() for element, number in nAtomsPerElement.items(): - self._outputData["vacf_%s" % element] /= number + self._outputData[f"vacf_{element}"] /= number weights = self.configuration["weights"].get_weights() @@ -223,8 +223,8 @@ def finalize(self): if self.configuration["normalize"]["value"]: for element in nAtomsPerElement.keys(): - self._outputData["vacf_%s" % element] = normalize( - self._outputData["vacf_%s" % element], axis=0 + self._outputData[f"vacf_{element}"] = normalize( + self._outputData[f"vacf_{element}"], axis=0 ) self._outputData["vacf_total"] = normalize( self._outputData["vacf_total"], axis=0 diff --git a/MDANSE/Src/MDANSE/Framework/Jobs/XRayStaticStructureFactor.py b/MDANSE/Src/MDANSE/Framework/Jobs/XRayStaticStructureFactor.py index 5da649cec0..1b15b10fae 100644 --- a/MDANSE/Src/MDANSE/Framework/Jobs/XRayStaticStructureFactor.py +++ b/MDANSE/Src/MDANSE/Framework/Jobs/XRayStaticStructureFactor.py @@ -135,22 +135,23 @@ def finalize(self): nAtomsPerElement = self.configuration["atom_selection"].get_natoms() for pair in self._elementsPairs: + pair_str = ''.join(map(str, pair)) self._outputData.add( - "xssf_intra_%s%s" % pair, + f"xssf_intra_{pair_str}", "LineOutputVariable", (nq,), axis="q", units="au", ) self._outputData.add( - "xssf_inter_%s%s" % pair, + f"xssf_inter_{pair_str}", "LineOutputVariable", (nq,), axis="q", units="au", ) self._outputData.add( - "xssf_total_%s%s" % pair, + f"xssf_total_{pair_str}", "LineOutputVariable", (nq,), axis="q", @@ -175,15 +176,15 @@ def finalize(self): pdfIntra = self.hIntra[idi, idj, :] / fact pdfInter = self.hInter[idi, idj, :] / fact - self._outputData["xssf_intra_%s%s" % pair][:] = ( + self._outputData[f"xssf_intra_{pair_str}"][:] = ( fact1 * np.sum((r**2) * pdfIntra * sincqr, axis=1) * dr ) - self._outputData["xssf_inter_%s%s" % pair][:] = ( + self._outputData[f"xssf_inter_{pair_str}"][:] = ( 1.0 + fact1 * np.sum((r**2) * (pdfInter - 1.0) * sincqr, axis=1) * dr ) - self._outputData["xssf_total_%s%s" % pair][:] = ( - self._outputData["xssf_intra_%s%s" % pair][:] - + self._outputData["xssf_inter_%s%s" % pair][:] + self._outputData[f"xssf_total_{pair_str}"][:] = ( + self._outputData[f"xssf_intra_{pair_str}"][:] + + self._outputData[f"xssf_inter_{pair_str}"][:] ) self._outputData.add( @@ -209,12 +210,12 @@ def finalize(self): ) xssfIntra = weight( - asf, self._outputData, nAtomsPerElement, 2, "xssf_intra_%s%s" + asf, self._outputData, nAtomsPerElement, 2, f"xssf_intra_{pair_str}" ) self._outputData["xssf_intra"][:] = xssfIntra xssfInter = weight( - asf, self._outputData, nAtomsPerElement, 2, "xssf_inter_%s%s" + asf, self._outputData, nAtomsPerElement, 2, f"xssf_inter_{pair_str}" ) self._outputData["xssf_inter"][:] = xssfInter diff --git a/MDANSE/Src/MDANSE/Framework/OutputVariables/IOutputVariable.py b/MDANSE/Src/MDANSE/Framework/OutputVariables/IOutputVariable.py index 35508e6e03..a8d78540de 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 + f"Invalid number of dimensions for an output variable of type {cls.name!r}" ) # Input array is an already formed ndarray instance @@ -118,13 +117,8 @@ def __array_finalize__(self, obj): self.units = getattr(obj, "units", "unitless") def info(self): - info = [] - - info.append("# variable name: %s" % self.varname) - info.append("# \ttype: %s" % self.__class__.__name__) - info.append("# \taxis: %s" % str(self.axis)) - info.append("# \tunits: %s" % self.units) - - info = "\n".join(info) - - return info + return f"""\ +# variable name: {self.varname} +# \ttype: {self.__class__.__name__} +# \taxis: {self.axis!s} +# \tunits: {self.units}""" diff --git a/MDANSE/Src/MDANSE/Framework/Units.py b/MDANSE/Src/MDANSE/Framework/Units.py index b8dab49fe6..cd9326e826 100644 --- a/MDANSE/Src/MDANSE/Framework/Units.py +++ b/MDANSE/Src/MDANSE/Framework/Units.py @@ -389,55 +389,35 @@ def __sub__(self, other): def __str__(self): unit = copy.copy(self) - fmt = "{:%s}" % self._format - if self._ounit is None: - s = fmt.format(unit._factor) + s = format(unit._factor, self._format) positive_units = [] negative_units = [] for uname, uval in zip(_UNAMES, unit._dimension): if uval == 0: continue - elif uval > 0: - if uval == 1: - positive_units.append("{:s}".format(uname)) - else: - if isinstance(uval, int): - positive_units.append("{:s}{:d}".format(uname, int(uval))) - else: - positive_units.append("{:s}{}".format(uname, uval)) - elif uval < 0: - if uval == -1: - negative_units.append("{:s}".format(uname)) - else: - if isinstance(uval, int): - negative_units.append("{:s}{:d}".format(uname, int(-uval))) - else: - negative_units.append("{:s}{}".format(uname, -uval)) - - positive_units_str = "" - if positive_units: - positive_units_str = " ".join(positive_units) - - negative_units_str = "" - if negative_units: - negative_units_str = " ".join(negative_units) + + ref = positive_units if uval > 0 else negative_units + unit = str(uname) + (format(abs(uval), "d") if isinstance(uval, int) else str(uval)) + ref.append(unit) + + positive_units_str = " ".join(positive_units) + negative_units_str = " ".join(negative_units) if positive_units_str: - s += " {:s}".format(positive_units_str) + s += f" {positive_units_str}" if negative_units_str: if not positive_units_str: s += " 1" - s += " / {}".format(negative_units_str) + s += f" / {negative_units_str}" else: u = copy.deepcopy(self) u._div_by(self._out_factor) - s = fmt.format(u._factor) - s += " {}".format(self._ounit) + s = f"{u._factor:{self._format}} {self._ounit}" return s diff --git a/MDANSE/Src/MDANSE/Framework/UserDefinitionStore.py b/MDANSE/Src/MDANSE/Framework/UserDefinitionStore.py index 49c9cbee72..ac67c556b6 100644 --- a/MDANSE/Src/MDANSE/Framework/UserDefinitionStore.py +++ b/MDANSE/Src/MDANSE/Framework/UserDefinitionStore.py @@ -99,8 +99,8 @@ def remove_definition(self, *defs): def set_definition(self, target, section, name, value): if self.has_definition(target, section, name): raise UserDefinitionStoreError( - "Item %s is already registered as an user definition. You must delete it before setting it." - % (target, section, name) + f"Item {(target, section, name)} is already registered as an user definition. " + "You must delete it before setting it." ) self._definitions.setdefault(target, {}).setdefault(section, {})[name] = value diff --git a/MDANSE/Src/MDANSE/IO/FortranFormat.py b/MDANSE/Src/MDANSE/IO/FortranFormat.py index 2a22fddb4f..40943035e5 100644 --- a/MDANSE/Src/MDANSE/IO/FortranFormat.py +++ b/MDANSE/Src/MDANSE/IO/FortranFormat.py @@ -216,15 +216,15 @@ def _output(self): elif type == "I": s = repr(value) elif type == "D": - s = ("%" + repr(length) + "." + repr(fraction) + "e") % value + s = f"{value:{length!r}.{fraction!r}e}" n = s.find("e") s = s[:n] + "D" + s[n + 1 :] elif type == "E": - s = ("%" + repr(length) + "." + repr(fraction) + "e") % value + s = f"{value:{length!r}.{fraction!r}e}" elif type == "F": - s = ("%" + repr(length) + "." + repr(fraction) + "f") % value + s = f"{value:{length!r}.{fraction!r}f}" elif type == "G": - s = ("%" + repr(length) + "." + repr(fraction) + "g") % value + s = f"{value:{length!r}.{fraction!r}g}" else: raise ValueError("Not yet implemented") s = s.upper() diff --git a/MDANSE/Src/MDANSE/Mathematics/Arithmetic.py b/MDANSE/Src/MDANSE/Mathematics/Arithmetic.py index a43bdd511b..5ddc685b10 100644 --- a/MDANSE/Src/MDANSE/Mathematics/Arithmetic.py +++ b/MDANSE/Src/MDANSE/Mathematics/Arithmetic.py @@ -52,7 +52,7 @@ def get_weights(props, contents, dim): def weight(props, values, contents, dim, key, symmetric=True, update_partials=False): weights = get_weights(props, contents, dim)[0] weightedSum = None - matches = dict([(key % k, k) for k in list(weights.keys())]) + matches = {key % k: k for k in weights} for k, val in values.items(): if k not in matches: diff --git a/MDANSE/Src/MDANSE/Mathematics/LinearAlgebra.py b/MDANSE/Src/MDANSE/Mathematics/LinearAlgebra.py index 8a3330e60f..6a76995f76 100644 --- a/MDANSE/Src/MDANSE/Mathematics/LinearAlgebra.py +++ b/MDANSE/Src/MDANSE/Mathematics/LinearAlgebra.py @@ -71,11 +71,7 @@ def __copy__(self, memo=None): __deepcopy__ = __copy__ def __repr__(self): - return "Vector(%s,%s,%s)" % ( - repr(self.array[0]), - repr(self.array[1]), - repr(self.array[2]), - ) + return f"Vector({','.join(map(repr, self.array))})" def __str__(self): return repr(list(self.array)) diff --git a/MDANSE/Src/MDANSE/Mathematics/Transformation.py b/MDANSE/Src/MDANSE/Mathematics/Transformation.py index 7a4a7f5213..4caed8011f 100644 --- a/MDANSE/Src/MDANSE/Mathematics/Transformation.py +++ b/MDANSE/Src/MDANSE/Mathematics/Transformation.py @@ -309,8 +309,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) + f"FAILURE 2 malformed rotation Tensor (non orthogonal?) {_c / _norm:.8f}" ) # if _c/_norm > 1: raise ValueError('Step1: No solution') _th = angleFromSineAndCosine(_b / _norm, _a / _norm) diff --git a/MDANSE/Src/MDANSE/Scripts/mdanse.py b/MDANSE/Src/MDANSE/Scripts/mdanse.py index cdb13c6ef3..a5886c6f84 100644 --- a/MDANSE/Src/MDANSE/Scripts/mdanse.py +++ b/MDANSE/Src/MDANSE/Scripts/mdanse.py @@ -42,43 +42,40 @@ def format_description(self, description): return "" desc_width = self.width - self.current_indent indent = " " * self.current_indent - bits = description.split("\n") - formatted_bits = [ + bits = description.splitlines() + formatted_bits = ( textwrap.fill( bit, desc_width, initial_indent=indent, subsequent_indent=indent ) for bit in bits - ] + ) result = "\n".join(formatted_bits) + "\n" return result def format_option(self, option): - result = [] + indent = " " * self.current_indent + result = "" opts = self.option_strings[option] opt_width = self.help_position - self.current_indent - 2 if len(opts) > opt_width: - opts = "%*s%s\n" % (self.current_indent, "", opts) + opts = f"{indent}{opts}\n" indent_first = self.help_position else: # start help on same line as opts - opts = "%*s%-*s " % (self.current_indent, "", opt_width, opts) + opts = f"{indent}{opts} " indent_first = 0 - result.append(opts) + result += opts if option.help: help_text = self.expand_default(option) # Everything is the same up through here - help_lines = [] - for para in help_text.split("\n"): - help_lines.extend(textwrap.wrap(para, self.help_width)) + help_lines = [textwrap.wrap(para, self.help_width) for para in help_text.splitlines()] # 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:]] - ) - elif opts[-1] != "\n": - result.append("\n") + result += f"{indent_first}{help_lines[0]}\n" + result += "\n".join(f"{' '*self.help_position}{line}" for line in help_lines[1:]) + "\n" + elif not opts.endswith("\n"): + result += "\n" - return "".join(result) + return result class CommandLineParserError(Error): @@ -111,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(f"Invalid number of arguments for {opt_str!r} option") basename = parser.rargs[0] @@ -130,24 +125,22 @@ 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: - raise CommandLineParserError( - "The job %r could not be opened properly." % basename - ) + raise CommandLineParserError(f"The job {basename!r} could not be opened properly.") # The job file could be opened and unpickled properly else: # Check that the unpickled object is a JobStatus object if not isinstance(info, JobState): - raise CommandLineParserError("Invalid contents for job %r." % basename) + raise CommandLineParserError(f"Invalid contents for job {basename!r}.") - LOG.info("Information about %s job:" % basename) - for k, v in info.iteritems(): - LOG.info("%-20s [%s]" % (k, v)) + LOG.info("Information about %s job:", basename) + for k, v in info.items(): + LOG.info("%-20s [%s]", k, v) 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 + f"Invalid number of arguments for {opt_str!r} option" ) element = parser.rargs[0] @@ -158,7 +151,7 @@ def display_element_info(self, option, opt_str, value, parser): LOG.info(ATOMS_DATABASE.info(element)) except ValueError: raise CommandLineParserError( - "The entry %r is not registered in the database" % element + f"The entry {element!r} is not registered in the database" ) def display_jobs_list(self, option, opt_str, value, parser): @@ -178,9 +171,7 @@ 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(f"Invalid number of arguments for {opt_str!r} option") jobs = PLATFORM.temporary_files_directory().glob("*") @@ -230,7 +221,7 @@ def error(self, msg): """ self.print_help(sys.stderr) - self.exit(2, "Error: %s\n" % msg) + self.exit(2, f"Error: {msg}\n") def query_classes_registry(self, option, opt_str, value, parser): """ @@ -248,14 +239,12 @@ def query_classes_registry(self, option, opt_str, value, parser): if len(parser.rargs) == 0: LOG.info("Registered jobs:") for interfaceName in IJob.indirect_subclasses(): - LOG.info("\t- %s" % interfaceName) + LOG.info("\t- %s", interfaceName) elif len(parser.rargs) == 1: val = parser.rargs[0] LOG.info(IJob.create(val).info()) else: - raise CommandLineParserError( - "Invalid number of arguments for %r option" % opt_str - ) + raise CommandLineParserError(f"Invalid number of arguments for {opt_str!r} option") def run_job(self, option, opt_str, value, parser): """Run job file(s). @@ -274,16 +263,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(f"Invalid number of arguments for {opt_str!r} option") filename = Path(parser.rargs[0]) if not filename.exists(): - raise CommandLineParserError( - "The job file %r could not be executed" % filename - ) + raise CommandLineParserError(f"The job file {filename!r} could not be executed") subprocess.Popen([sys.executable, filename]) @@ -305,9 +290,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(f"Invalid number of arguments for {opt_str!r} option") jobs = IJob @@ -321,15 +304,13 @@ 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(f"Could not write the job template as {filename!r}") # 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) + raise CommandLineParserError(f"The job {name!r} is not a valid MDANSE job") # Otherwise, print some information about the saved template. else: - LOG.info("Saved template for job %r as %r" % (name, filename)) + LOG.info("Saved template for job %r as %r", name, filename) def save_job_template(self, option, opt_str, value, parser): """ @@ -371,7 +352,7 @@ def main(): # Creates the option parser. parser = CommandLineParser( - formatter=IndentedHelp(), version="MDANSE %s " % MDANSE.__version__ + formatter=IndentedHelp(), version=f"MDANSE {MDANSE.__version__} " ) # Creates a first the group of general options. From 600025ff3c53980013238bfc7120749d2a0ed2e5 Mon Sep 17 00:00:00 2001 From: Jacob Wilkins Date: Mon, 27 Jan 2025 14:19:39 +0000 Subject: [PATCH 2/2] Remove unnecessary `.format`. --- MDANSE/Src/MDANSE/Chemistry/Databases.py | 34 ++++++++------- MDANSE/Src/MDANSE/Framework/Configurable.py | 8 ++-- .../Framework/Configurators/IConfigurator.py | 4 +- .../Configurators/QVectorsConfigurator.py | 4 +- .../Configurators/RangeConfigurator.py | 2 +- .../Configurators/XYZFileConfigurator.py | 4 +- MDANSE/Src/MDANSE/Framework/Converters/DCD.py | 4 +- .../MDANSE/Framework/Converters/Forcite.py | 2 +- .../Src/MDANSE/Framework/Converters/LAMMPS.py | 6 +-- .../MDANSE/Framework/Formats/TextFormat.py | 12 ++---- .../InputData/HDFTrajectoryInputData.py | 6 +-- .../Framework/Jobs/CoordinationNumber.py | 6 ++- .../Jobs/CurrentCorrelationFunction.py | 2 +- .../Jobs/DynamicIncoherentStructureFactor.py | 2 +- .../Jobs/GeneralAutoCorrelationFunction.py | 8 ++-- MDANSE/Src/MDANSE/Framework/Jobs/IJob.py | 4 +- .../Framework/Jobs/McStasVirtualInstrument.py | 4 +- .../NeutronDynamicTotalStructureFactor.py | 20 ++++----- .../Jobs/PairDistributionFunction.py | 8 ++-- .../Framework/Jobs/RigidBodyTrajectory.py | 2 +- .../Framework/Jobs/RootMeanSquareDeviation.py | 8 ++-- .../Framework/Jobs/StaticStructureFactor.py | 2 +- .../Framework/Jobs/VanHoveFunctionDistinct.py | 4 +- .../Framework/Jobs/VanHoveFunctionSelf.py | 4 +- .../Jobs/XRayStaticStructureFactor.py | 6 +-- MDANSE/Src/MDANSE/Framework/Units.py | 10 +++-- MDANSE/Src/MDANSE/IO/HDF.py | 4 +- MDANSE/Src/MDANSE/IO/HDF5.py | 6 +-- .../MolecularDynamics/MockTrajectory.py | 4 +- MDANSE/Src/MDANSE/Scripts/mdanse.py | 41 ++++++++++++++----- .../Src/MDANSE/Trajectory/H5MDTrajectory.py | 4 +- .../Src/MDANSE/Trajectory/MdanseTrajectory.py | 4 +- 32 files changed, 120 insertions(+), 119 deletions(-) diff --git a/MDANSE/Src/MDANSE/Chemistry/Databases.py b/MDANSE/Src/MDANSE/Chemistry/Databases.py index 9448344bf1..a6a9827b3e 100644 --- a/MDANSE/Src/MDANSE/Chemistry/Databases.py +++ b/MDANSE/Src/MDANSE/Chemistry/Databases.py @@ -215,7 +215,7 @@ def __getitem__(self, item: str) -> dict: return copy.deepcopy(self._data[item]) except KeyError: raise AtomsDatabaseError( - "The element {} is not registered in the database.".format(item) + f"The element {item} is not registered in the database." ) def _load(self, user_database: str = None, default_database: str = None) -> None: @@ -253,7 +253,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) + f"The atom {atom} is already stored in the database" ) self._data[atom] = {} @@ -272,11 +272,11 @@ def add_property(self, pname: str, ptype: str) -> None: if pname in self._properties: raise AtomsDatabaseError( - "The property {} is already registered in the database.".format(pname) + f"The property {pname} is already registered in the database." ) if ptype not in AtomsDatabase._TYPES: - raise AtomsDatabaseError("The property type {} is unknown".format(ptype)) + raise AtomsDatabaseError(f"The property type {ptype} is unknown") self._properties[pname] = ptype ptype = AtomsDatabase._TYPES[ptype] @@ -307,7 +307,7 @@ def get_isotopes(self, atom: str) -> list[str]: """ if atom not in self._data: - raise AtomsDatabaseError("The atom {} is unknown".format(atom)) + raise AtomsDatabaseError(f"The atom {atom} is unknown") # The isotopes are searched according to |symbol| property symbol = self._data[atom]["symbol"] @@ -340,7 +340,7 @@ def get_property(self, pname: str) -> dict[str, Union[str, int, float, list]]: if pname not in self._properties: raise AtomsDatabaseError( - "The property {} is not registered in the database".format(pname) + f"The property {pname} is not registered in the database" ) ptype = AtomsDatabase._TYPES[self._properties[pname]] @@ -365,11 +365,11 @@ def get_value(self, atom: str, pname: str) -> Union[str, int, float, list]: """ if atom not in self._data: - raise AtomsDatabaseError("The atom {} is unknown".format(atom)) + raise AtomsDatabaseError(f"The atom {atom} is unknown") if pname not in self._properties: raise AtomsDatabaseError( - "The property {} is not registered in the database".format(pname) + f"The property {pname} is not registered in the database" ) ptype = self._properties[pname] @@ -397,12 +397,12 @@ def get_values_for_multiple_atoms( if not all(atom in self._data for atom in atoms): raise AtomsDatabaseError( - "One or more of the provided atoms {} are unknown".format(atoms) + f"One or more of the provided atoms {atoms} are unknown" ) if prop not in self._properties: raise AtomsDatabaseError( - "The property {} is not registered in the database".format(prop) + f"The property {prop} is not registered in the database" ) values = {name: self._data[name][prop] for name in unique_atoms} @@ -425,11 +425,11 @@ def set_value( """ if atom not in self._data: - raise AtomsDatabaseError("The element {} is unknown".format(atom)) + raise AtomsDatabaseError(f"The element {atom} is unknown") if pname not in self._properties: raise AtomsDatabaseError( - "The property {} is not registered in the database".format(pname) + f"The property {pname} is not registered in the database" ) try: @@ -438,7 +438,7 @@ def set_value( ) except ValueError: raise AtomsDatabaseError( - "Can not coerce {} to {} type".format(value, self._properties[pname]) + f"Can not coerce {value} to {self._properties[pname]} type" ) def has_atom(self, atom: str) -> bool: @@ -480,7 +480,7 @@ def info(self, atom: str) -> str: # A delimiter line. delimiter = "-" * 70 - tab_fmt = "{:<20}{:>50}" + tab_fmt = " {:<20}{!s:>50}" info = [ delimiter, @@ -491,9 +491,7 @@ def info(self, atom: str) -> str: # The values for all element's properties for pname in sorted(self._properties): - info.append( - tab_fmt.format(pname, self._data[atom].get(pname, None)) - ) + info.append(tab_fmt.format(pname, self._data[atom].get(pname, None))) info.append(delimiter) info = "\n".join(info) @@ -526,7 +524,7 @@ def match_numeric_property( ) except KeyError: raise AtomsDatabaseError( - "The property {} is not registered in the database".format(pname) + f"The property {pname} is not registered in the database" ) tolerance = abs(tolerance) diff --git a/MDANSE/Src/MDANSE/Framework/Configurable.py b/MDANSE/Src/MDANSE/Framework/Configurable.py index 2d68c083a0..ef8664e1b4 100644 --- a/MDANSE/Src/MDANSE/Framework/Configurable.py +++ b/MDANSE/Src/MDANSE/Framework/Configurable.py @@ -251,17 +251,19 @@ def build_doc_texttable(cls, doclist): v["Description"] = v["Description"].strip() v["Description"] = v["Description"].splitlines() v["Description"] = ["| " + vv.strip() for vv in v["Description"]] - sizes[2] = max(sizes[2], max(v["Description"], key=len)) + sizes[2] = max(sizes[2], max(map(len, v["Description"]))) data_line = "| " + "| ".join(f"{{}}:<{size}" for size in sizes) + "|\n" - sep_line = "+" + "+".join("-" * (size+1) for size in sizes) + "+\n" + sep_line = "+" + "+".join("-" * (size + 1) for size in sizes) + "+\n" docstring += sep_line docstring += data_line.format(*columns) docstring += sep_line.replace("-", "=") for v in doclist: - docstring += data_line.format(v["Configurator"], v["Default value"], v["Description"][0]) + docstring += data_line.format( + v["Configurator"], v["Default value"], v["Description"][0] + ) if len(v["Description"]) > 1: for descr in v["Description"][1:]: data_line.format("", "", descr) diff --git a/MDANSE/Src/MDANSE/Framework/Configurators/IConfigurator.py b/MDANSE/Src/MDANSE/Framework/Configurators/IConfigurator.py index 17c93689d4..b1015712c5 100644 --- a/MDANSE/Src/MDANSE/Framework/Configurators/IConfigurator.py +++ b/MDANSE/Src/MDANSE/Framework/Configurators/IConfigurator.py @@ -59,7 +59,9 @@ def __str__(self): """ if self._configurator is not None: - self._message = f"Configurator: {self._configurator.name!r} --> {self._message}" + self._message = ( + f"Configurator: {self._configurator.name!r} --> {self._message}" + ) return self._message diff --git a/MDANSE/Src/MDANSE/Framework/Configurators/QVectorsConfigurator.py b/MDANSE/Src/MDANSE/Framework/Configurators/QVectorsConfigurator.py index 42c8033d5c..0434425c51 100644 --- a/MDANSE/Src/MDANSE/Framework/Configurators/QVectorsConfigurator.py +++ b/MDANSE/Src/MDANSE/Framework/Configurators/QVectorsConfigurator.py @@ -122,8 +122,6 @@ def get_information(self): return "QVectors could not be configured correctly" else: for qValue, qVectors in self["q_vectors"].items(): - info.append( - f"Shell {qValue}: {len(qVectors)} Q vectors generated\n" - ) + info.append(f"Shell {qValue}: {len(qVectors)} Q vectors generated\n") return "".join(info) diff --git a/MDANSE/Src/MDANSE/Framework/Configurators/RangeConfigurator.py b/MDANSE/Src/MDANSE/Framework/Configurators/RangeConfigurator.py index 84508d850a..11c00d616a 100644 --- a/MDANSE/Src/MDANSE/Framework/Configurators/RangeConfigurator.py +++ b/MDANSE/Src/MDANSE/Framework/Configurators/RangeConfigurator.py @@ -213,7 +213,7 @@ def get_information(self): if self._valid: - info = f"{self['number']} values from {self['first']} to {self['last']}" + info = f"{self['number']:d} values from {self['first']} to {self['last']}" if self._includeLast: info += " last value included" diff --git a/MDANSE/Src/MDANSE/Framework/Configurators/XYZFileConfigurator.py b/MDANSE/Src/MDANSE/Framework/Configurators/XYZFileConfigurator.py index 72d69119cd..94cc953929 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( - f"Could not read the number of atoms in {filename} file" - ) + raise XYZFileError(f"Could not read the number of atoms in {filename} file") self._nAtomsLineSize = self["instance"].tell() self["instance"].readline() diff --git a/MDANSE/Src/MDANSE/Framework/Converters/DCD.py b/MDANSE/Src/MDANSE/Framework/Converters/DCD.py index 3e4510eb71..f857de26a2 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( - f"Invalid byte order. {filename} not a valid DCD file" - ) + raise ByteOrderError(f"Invalid byte order. {filename} not a valid DCD file") return byteOrder diff --git a/MDANSE/Src/MDANSE/Framework/Converters/Forcite.py b/MDANSE/Src/MDANSE/Framework/Converters/Forcite.py index ad177b57d6..75f1f80a4c 100644 --- a/MDANSE/Src/MDANSE/Framework/Converters/Forcite.py +++ b/MDANSE/Src/MDANSE/Framework/Converters/Forcite.py @@ -173,7 +173,7 @@ 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 = "!" + (f"{self['totmov']}{self._fp}8x" * 9) + self._configRec = "!" + (f"!{self['totmov']}{self._fp}8x" * 9) else: # Frame record 8,9,10,11,12,13 self._configRec = "!" + (f"{self['totmov']}{self._fp}8x" * 6) diff --git a/MDANSE/Src/MDANSE/Framework/Converters/LAMMPS.py b/MDANSE/Src/MDANSE/Framework/Converters/LAMMPS.py index e06e156f27..b36f591d81 100644 --- a/MDANSE/Src/MDANSE/Framework/Converters/LAMMPS.py +++ b/MDANSE/Src/MDANSE/Framework/Converters/LAMMPS.py @@ -222,7 +222,7 @@ def parse_first_step(self, aliases, config): ) label = str(config["elements"][ty][0]) mass = str(config["elements"][ty][1]) - name = "{:s}_{:d}".format(str(config["elements"][ty][0]), idx) + name = f"{label}_{idx:d}" try: temp_index = int(temp[0]) except ValueError: @@ -470,7 +470,7 @@ def parse_first_step(self, aliases, config): ty = atom_types[i] - 1 label = str(config["elements"][ty][0]) mass = str(config["elements"][ty][1]) - name = "{:s}_{:d}".format(str(config["elements"][ty][0]), idx) + name = f"{label}_{idx:d}" self._rankToName[idx] = name element_list.append(get_element_from_mapping(aliases, label, mass=mass)) name_list.append(str(ty + 1)) @@ -579,7 +579,7 @@ def parse_first_step(self, aliases, config): ty = atom_types[i] - 1 label = str(config["elements"][ty][0]) mass = str(config["elements"][ty][1]) - name = "{:s}_{:d}".format(str(config["elements"][ty][0]), idx) + name = f"{label}_{idx:d}" self._rankToName[idx] = name element_list.append(get_element_from_mapping(aliases, label, mass=mass)) name_list.append(str(ty + 1)) diff --git a/MDANSE/Src/MDANSE/Framework/Formats/TextFormat.py b/MDANSE/Src/MDANSE/Framework/Formats/TextFormat.py index fdcab8c1d9..cd408e26c1 100644 --- a/MDANSE/Src/MDANSE/Framework/Formats/TextFormat.py +++ b/MDANSE/Src/MDANSE/Framework/Formats/TextFormat.py @@ -141,18 +141,14 @@ def write_data(cls, fileobject, data, allData): fileobject.write(f"# 1st column: {xData} (au)\n") else: xValues = allData[xData] - fileobject.write( - f"# 1st column: {xValues.varname} ({xValues.units})\n" - ) + fileobject.write(f"# 1st column: {xValues.varname} ({xValues.units})\n") if yData == "index": yValues = np.arange(data.shape[1]) fileobject.write(f"# 1st row: {yData} (au)\n\n") else: yValues = allData[yData] - fileobject.write( - f"# 1st row: {yValues.varname} ({yValues.units})\n\n" - ) + fileobject.write(f"# 1st row: {yValues.varname} ({yValues.units})\n\n") zData = np.zeros((data.shape[0] + 1, data.shape[1] + 1), dtype=np.float64) zData[1:, 0] = xValues @@ -170,9 +166,7 @@ def write_data(cls, fileobject, data, allData): fileobject.write(f"# 1st column: {xData} (au)\n") else: xValues = allData[xData] - fileobject.write( - f"# 1st column: {xValues.varname} ({xValues.units})\n" - ) + fileobject.write(f"# 1st column: {xValues.varname} ({xValues.units})\n") fileobject.write(f"# 2nd column: {data.varname} ({data.units})\n\n") diff --git a/MDANSE/Src/MDANSE/Framework/InputData/HDFTrajectoryInputData.py b/MDANSE/Src/MDANSE/Framework/InputData/HDFTrajectoryInputData.py index 1f773a1081..c99672f784 100644 --- a/MDANSE/Src/MDANSE/Framework/InputData/HDFTrajectoryInputData.py +++ b/MDANSE/Src/MDANSE/Framework/InputData/HDFTrajectoryInputData.py @@ -61,11 +61,9 @@ def info(self): val.append("Number of steps:") val.append(f"{self._data}\n") val.append("Configuration:") - val.append(f"\tIs periodic: {"unit_cell" in self._data.file}\n") + val.append(f"\tIs periodic: {'unit_cell' in self._data.file}\n") try: - val.append( - f"First unit cell (nm):\n{self._data.unit_cell(0)._unit_cell}\n" - ) + val.append(f"First unit cell (nm):\n{self._data.unit_cell(0)._unit_cell}\n") except: val.append("No unit cell information\n") val.append("Frame times (1st, 2nd, ..., last) in ps:") diff --git a/MDANSE/Src/MDANSE/Framework/Jobs/CoordinationNumber.py b/MDANSE/Src/MDANSE/Framework/Jobs/CoordinationNumber.py index fc725617fe..085507894d 100644 --- a/MDANSE/Src/MDANSE/Framework/Jobs/CoordinationNumber.py +++ b/MDANSE/Src/MDANSE/Framework/Jobs/CoordinationNumber.py @@ -154,6 +154,10 @@ def finalize(self): nAtomsPerElement = self.configuration["atom_selection"].get_natoms() for pair in self._elementsPairs: at1, at2 = pair + invPair = pair[::-1] + pair_str = "".join(map(str, pair)) + inv_pair_str = "".join(map(str, invPair)) + ni = nAtomsPerElement[at1] nj = nAtomsPerElement[at2] @@ -179,8 +183,6 @@ def finalize(self): cAlpha = self._concentrations[pair[0]] cBeta = self._concentrations[pair[1]] - invPair = pair[::-1] - self._outputData[f"cn_intra_{pair_str}"][:] = ( self.averageDensity * cBeta * cnIntra ) diff --git a/MDANSE/Src/MDANSE/Framework/Jobs/CurrentCorrelationFunction.py b/MDANSE/Src/MDANSE/Framework/Jobs/CurrentCorrelationFunction.py index 3fe6154ae5..26cc75509a 100644 --- a/MDANSE/Src/MDANSE/Framework/Jobs/CurrentCorrelationFunction.py +++ b/MDANSE/Src/MDANSE/Framework/Jobs/CurrentCorrelationFunction.py @@ -378,7 +378,7 @@ def finalize(self): self._outputData[f"j(q,t)_long_{pair_str}"][:] /= ni * nj self._outputData[f"j(q,t)_trans_{pair_str}"][:] /= ni * nj self._outputData[f"J(q,f)_long_{pair_str}"][:] = get_spectrum( - self._outputData["j(q,t)_long_{pair_str}"], + self._outputData[f"j(q,t)_long_{pair_str}"], self.configuration["instrument_resolution"]["time_window"], self.configuration["instrument_resolution"]["time_step"], axis=1, diff --git a/MDANSE/Src/MDANSE/Framework/Jobs/DynamicIncoherentStructureFactor.py b/MDANSE/Src/MDANSE/Framework/Jobs/DynamicIncoherentStructureFactor.py index 1c20b0af50..0c69b43444 100644 --- a/MDANSE/Src/MDANSE/Framework/Jobs/DynamicIncoherentStructureFactor.py +++ b/MDANSE/Src/MDANSE/Framework/Jobs/DynamicIncoherentStructureFactor.py @@ -245,7 +245,7 @@ def combine(self, index, disf_per_q_shell): element = self.configuration["atom_selection"]["names"][index] for i, v in enumerate(disf_per_q_shell.values()): - self._outputData["f(q,t)_{}".format(element)][i, :] += v + self._outputData[f"f(q,t)_{element}"][i, :] += v def finalize(self): """ diff --git a/MDANSE/Src/MDANSE/Framework/Jobs/GeneralAutoCorrelationFunction.py b/MDANSE/Src/MDANSE/Framework/Jobs/GeneralAutoCorrelationFunction.py index 2e3e36ab1c..be158c6dab 100644 --- a/MDANSE/Src/MDANSE/Framework/Jobs/GeneralAutoCorrelationFunction.py +++ b/MDANSE/Src/MDANSE/Framework/Jobs/GeneralAutoCorrelationFunction.py @@ -95,7 +95,7 @@ def initialize(self): # Will store the mean square displacement evolution. for element in self.configuration["atom_selection"]["unique_names"]: self._outputData.add( - "gacf_{}".format(element), + f"gacf_{element}", "LineOutputVariable", (self.configuration["frames"]["number"],), axis="time", @@ -161,14 +161,14 @@ def finalize(self): self.configuration["atom_selection"]["n_atoms_per_element"] = nAtomsPerElement for element, number in nAtomsPerElement.items(): - self._outputData["gacf_{}".format(element)] /= number + self._outputData[f"gacf_{element}"] /= number if self.configuration["normalize"]["value"]: for element in nAtomsPerElement.keys(): - if self._outputData["gacf_{}}".format(element)][0] == 0: + if self._outputData[f"gacf_{element}}}"][0] == 0: raise ValueError("The normalization factor is equal to zero") else: - self._outputData["gacf_{}".format(element)] = normalize( + self._outputData[f"gacf_{element}"] = normalize( self._outputData[f"gacf_{element}"], axis=0 ) diff --git a/MDANSE/Src/MDANSE/Framework/Jobs/IJob.py b/MDANSE/Src/MDANSE/Framework/Jobs/IJob.py index 60aee6b948..b087e71744 100644 --- a/MDANSE/Src/MDANSE/Framework/Jobs/IJob.py +++ b/MDANSE/Src/MDANSE/Framework/Jobs/IJob.py @@ -439,7 +439,7 @@ def save_template(cls, shortname, classname): from MDANSE.Framework.Jobs.IJob import IJob -class {classname}s(IJob): +class {classname}(IJob): """ You should enter the description of your job here ... """ @@ -498,7 +498,7 @@ def finalize(self): self.configuration['trajectory']['instance'].close() ''' - ) + ) except IOError: return None diff --git a/MDANSE/Src/MDANSE/Framework/Jobs/McStasVirtualInstrument.py b/MDANSE/Src/MDANSE/Framework/Jobs/McStasVirtualInstrument.py index e14bc0bd22..9cf8acae1b 100644 --- a/MDANSE/Src/MDANSE/Framework/Jobs/McStasVirtualInstrument.py +++ b/MDANSE/Src/MDANSE/Framework/Jobs/McStasVirtualInstrument.py @@ -233,9 +233,7 @@ def run_step(self, index): for k, v in list(self._mcStasPhysicalParameters.items()): fout.write(f"# {k} {v} \n") - fout.write( - f"# Temperature {self.configuration['temperature']['value']} \n" - ) + fout.write(f"# Temperature {self.configuration['temperature']['value']} \n") fout.write("#\n") for var in self.configuration[typ].variables: diff --git a/MDANSE/Src/MDANSE/Framework/Jobs/NeutronDynamicTotalStructureFactor.py b/MDANSE/Src/MDANSE/Framework/Jobs/NeutronDynamicTotalStructureFactor.py index 0538309edd..a69acaecb1 100644 --- a/MDANSE/Src/MDANSE/Framework/Jobs/NeutronDynamicTotalStructureFactor.py +++ b/MDANSE/Src/MDANSE/Framework/Jobs/NeutronDynamicTotalStructureFactor.py @@ -198,15 +198,16 @@ def initialize(self): ) ) for pair in self._elementsPairs: + pair_str = "".join(map(str, pair)) if ( - "f(q,t)_{}{}".format(*pair) + f"f(q,t)_{pair_str}" not in self.configuration["dcsf_input_file"]["instance"] ): raise NeutronDynamicTotalStructureFactorError( "Missing f(q,t) in dcsf input file" ) if ( - "s(q,f)_{}{}".format(*pair) + f"s(q,f)_{pair_str}" not in self.configuration["dcsf_input_file"]["instance"] ): raise NeutronDynamicTotalStructureFactorError( @@ -215,14 +216,14 @@ def initialize(self): for element in self.configuration["atom_selection"]["unique_names"]: if ( - "f(q,t)_{}".format(element) + f"f(q,t)_{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) + f"s(q,f)_{element}" not in self.configuration["disf_input_file"]["instance"] ): raise NeutronDynamicTotalStructureFactorError( @@ -230,12 +231,8 @@ def initialize(self): ) 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"f(q,t)_{element}"] + sqf = self.configuration["disf_input_file"]["instance"][f"s(q,f)_{element}"] self._outputData.add( f"f(q,t)_inc_{element}", "SurfaceOutputVariable", @@ -266,7 +263,7 @@ def initialize(self): ) for pair in self._elementsPairs: - pair_str = ''.join(map(str, pair)) + pair_str = "".join(map(str, pair)) fqt = self.configuration["dcsf_input_file"]["instance"][ f"f(q,t)_{pair_str}" ] @@ -390,6 +387,7 @@ def finalize(self): # Compute coherent functions and structure factor for pair in self._elementsPairs: + pair_str = "".join(map(str, pair)) bi = self.configuration["trajectory"]["instance"].get_atom_property( pair[0], "b_coherent" ) diff --git a/MDANSE/Src/MDANSE/Framework/Jobs/PairDistributionFunction.py b/MDANSE/Src/MDANSE/Framework/Jobs/PairDistributionFunction.py index a5e8a7dc61..9f5363cea2 100644 --- a/MDANSE/Src/MDANSE/Framework/Jobs/PairDistributionFunction.py +++ b/MDANSE/Src/MDANSE/Framework/Jobs/PairDistributionFunction.py @@ -138,11 +138,11 @@ def finalize(self): for i, pdf in zip( ["intra", "inter", "total"], [pdf_intra, pdf_inter, pdf_total] ): - self._outputData[f"pdf_{i}_{pair[0]}{pair[1]}")][:] = pdf - self._outputData[f"rdf_{i}_{pair[0]}{pair[1]}")][:] = ( + self._outputData[f"pdf_{i}_{pair[0]}{pair[1]}"][:] = pdf + self._outputData[f"rdf_{i}_{pair[0]}{pair[1]}"][:] = ( shellSurfaces * self.averageDensity * pdf ) - self._outputData[f"tcf_{i}_{pair[0]}{pair[1]}")][:] = ( + self._outputData[f"tcf_{i}_{pair[0]}{pair[1]}"][:] = ( densityFactor * self.averageDensity * (pdf if i == "intra" else pdf - 1) @@ -156,7 +156,7 @@ def finalize(self): self._outputData, nAtomsPerElement, 2, - f"pdf{i if i else "_total"}_%s%s", + f"pdf{i if i else '_total'}_%s%s", ) self._outputData[f"pdf{i}_total"][:] = pdf self._outputData[f"rdf{i}_total"][:] = ( diff --git a/MDANSE/Src/MDANSE/Framework/Jobs/RigidBodyTrajectory.py b/MDANSE/Src/MDANSE/Framework/Jobs/RigidBodyTrajectory.py index 1cb5f0c487..ba4e25af63 100644 --- a/MDANSE/Src/MDANSE/Framework/Jobs/RigidBodyTrajectory.py +++ b/MDANSE/Src/MDANSE/Framework/Jobs/RigidBodyTrajectory.py @@ -91,7 +91,7 @@ def initialize(self): raise JobError( self, "Invalid reference frame. Must be an integer in " - f"[{0},{self.configuration['trajectory']['length']}[" + f"[{0},{self.configuration['trajectory']['length']}[", ) self._quaternions = np.zeros( diff --git a/MDANSE/Src/MDANSE/Framework/Jobs/RootMeanSquareDeviation.py b/MDANSE/Src/MDANSE/Framework/Jobs/RootMeanSquareDeviation.py index 74d34d9698..40dad188a5 100644 --- a/MDANSE/Src/MDANSE/Framework/Jobs/RootMeanSquareDeviation.py +++ b/MDANSE/Src/MDANSE/Framework/Jobs/RootMeanSquareDeviation.py @@ -93,7 +93,7 @@ def initialize(self): # Will initially store the mean square deviation before appling the root for element in self.configuration["atom_selection"]["unique_names"]: self._outputData.add( - "rmsd_{}".format(element), + f"rmsd_{element}", "LineOutputVariable", (self.configuration["frames"]["number"],), axis="time", @@ -156,11 +156,11 @@ def finalize(self): nAtomsPerElement = self.configuration["atom_selection"].get_natoms() for element, number in nAtomsPerElement.items(): - self._outputData["rmsd_{}".format(element)] /= number + self._outputData[f"rmsd_{element}"] /= number for element, number in nAtomsPerElement.items(): - self._outputData["rmsd_{}".format(element)] = np.sqrt( - self._outputData["rmsd_{}".format(element)] + self._outputData[f"rmsd_{element}"] = np.sqrt( + self._outputData[f"rmsd_{element}"] ) self._outputData["rmsd_all"] /= self.configuration[ diff --git a/MDANSE/Src/MDANSE/Framework/Jobs/StaticStructureFactor.py b/MDANSE/Src/MDANSE/Framework/Jobs/StaticStructureFactor.py index 3392e686ce..9b0321681e 100644 --- a/MDANSE/Src/MDANSE/Framework/Jobs/StaticStructureFactor.py +++ b/MDANSE/Src/MDANSE/Framework/Jobs/StaticStructureFactor.py @@ -142,7 +142,7 @@ def finalize(self): nAtomsPerElement = self.configuration["atom_selection"].get_natoms() for pair in self._elementsPairs: - pair_str = ''.join(map(str, pair)) + pair_str = "".join(map(str, pair)) self._outputData.add( f"ssf_intra_{pair_str}", "LineOutputVariable", diff --git a/MDANSE/Src/MDANSE/Framework/Jobs/VanHoveFunctionDistinct.py b/MDANSE/Src/MDANSE/Framework/Jobs/VanHoveFunctionDistinct.py index 953971b88b..a0aa77df39 100644 --- a/MDANSE/Src/MDANSE/Framework/Jobs/VanHoveFunctionDistinct.py +++ b/MDANSE/Src/MDANSE/Framework/Jobs/VanHoveFunctionDistinct.py @@ -484,9 +484,7 @@ def finalize(self): ["intra", "inter", "total"], [van_hove_intra, van_hove_inter, van_hove_total], ): - self._outputData[f"g(r,t)_{i}_{pair[0]}{pair[1]}"][ - ... - ] = van_hove + self._outputData[f"g(r,t)_{i}_{pair[0]}{pair[1]}"][...] = van_hove 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 738610c13e..9d7b0749ad 100644 --- a/MDANSE/Src/MDANSE/Framework/Jobs/VanHoveFunctionSelf.py +++ b/MDANSE/Src/MDANSE/Framework/Jobs/VanHoveFunctionSelf.py @@ -274,8 +274,8 @@ def combine(self, atm_index: int, histogram: np.ndarray): time t0 and t0 + t. """ element = self.configuration["atom_selection"]["names"][atm_index] - self._outputData["g(r,t)_{}".format(element)][:] += histogram - self._outputData["4_pi_r2_g(r,t)_{}".format(element)][:] += histogram + self._outputData[f"g(r,t)_{element}"][:] += histogram + self._outputData[f"4_pi_r2_g(r,t)_{element}"][:] += histogram def finalize(self): """Using the distance histograms calculate, normalize and save the diff --git a/MDANSE/Src/MDANSE/Framework/Jobs/XRayStaticStructureFactor.py b/MDANSE/Src/MDANSE/Framework/Jobs/XRayStaticStructureFactor.py index 1b15b10fae..3e14db0c6e 100644 --- a/MDANSE/Src/MDANSE/Framework/Jobs/XRayStaticStructureFactor.py +++ b/MDANSE/Src/MDANSE/Framework/Jobs/XRayStaticStructureFactor.py @@ -135,7 +135,7 @@ def finalize(self): nAtomsPerElement = self.configuration["atom_selection"].get_natoms() for pair in self._elementsPairs: - pair_str = ''.join(map(str, pair)) + pair_str = "".join(map(str, pair)) self._outputData.add( f"xssf_intra_{pair_str}", "LineOutputVariable", @@ -210,12 +210,12 @@ def finalize(self): ) xssfIntra = weight( - asf, self._outputData, nAtomsPerElement, 2, f"xssf_intra_{pair_str}" + asf, self._outputData, nAtomsPerElement, 2, f"xssf_intra_%s%s" ) self._outputData["xssf_intra"][:] = xssfIntra xssfInter = weight( - asf, self._outputData, nAtomsPerElement, 2, f"xssf_inter_{pair_str}" + asf, self._outputData, nAtomsPerElement, 2, f"xssf_inter_%s%s" ) self._outputData["xssf_inter"][:] = xssfInter diff --git a/MDANSE/Src/MDANSE/Framework/Units.py b/MDANSE/Src/MDANSE/Framework/Units.py index cd9326e826..5083435d2f 100644 --- a/MDANSE/Src/MDANSE/Framework/Units.py +++ b/MDANSE/Src/MDANSE/Framework/Units.py @@ -95,11 +95,11 @@ def _parse_unit(iunit): iunit = iunit[i:] break else: - raise UnitError("The unit {} is unknown".format(iunit)) + raise UnitError(f"The unit {iunit} is unknown") if prefix: if prefix not in _PREFIXES: - raise UnitError("The prefix {} is unknown".format(prefix)) + raise UnitError(f"The prefix {prefix} is unknown") prefix = _PREFIXES[prefix] else: prefix = 1.0 @@ -150,7 +150,7 @@ def _str_to_unit(s): return unit else: - raise UnitError("Invalid unit: {}".format(s)) + raise UnitError(f"Invalid unit: {s}") class _Unit(object): @@ -399,7 +399,9 @@ def __str__(self): continue ref = positive_units if uval > 0 else negative_units - unit = str(uname) + (format(abs(uval), "d") if isinstance(uval, int) else str(uval)) + unit = str(uname) + ( + format(abs(uval), "d") if isinstance(uval, int) else str(uval) + ) ref.append(unit) positive_units_str = " ".join(positive_units) diff --git a/MDANSE/Src/MDANSE/IO/HDF.py b/MDANSE/Src/MDANSE/IO/HDF.py index 5efc264399..d48a15e9a4 100644 --- a/MDANSE/Src/MDANSE/IO/HDF.py +++ b/MDANSE/Src/MDANSE/IO/HDF.py @@ -29,9 +29,9 @@ def find_numeric_variables(variables, group): find_numeric_variables(variables, var) else: if var.parent.name == "/": - path = "/{}".format(var_key) + path = f"/{var_key}" else: - path = "{}/{}".format(var.parent.name, var_key) + path = f"{var.parent.name}/{var_key}" if not np.issubdtype(var.dtype, np.number): continue diff --git a/MDANSE/Src/MDANSE/IO/HDF5.py b/MDANSE/Src/MDANSE/IO/HDF5.py index 28f0a06852..61d41a48d0 100644 --- a/MDANSE/Src/MDANSE/IO/HDF5.py +++ b/MDANSE/Src/MDANSE/IO/HDF5.py @@ -56,9 +56,9 @@ def find_numeric_variables(var_dict, group): find_numeric_variables(var_dict, var) else: if var.parent.name == "/": - path = "/{}".format(var_key) + path = f"/{var_key}" else: - path = "{}/{}".format(var.parent.name, var_key) + path = f"{var.parent.name}/{var_key}" # Non-numeric variables are not supported by the plotter if not np.issubdtype(var.dtype, np.number): @@ -70,7 +70,7 @@ def find_numeric_variables(var_dict, group): comp = 1 while var_key in var_dict: - var_key = "{:s}_{:d}".format(var_key, comp) + var_key = f"{var_key:s}_{comp:d}" comp += 1 var_dict[var_key] = (path, HDFFileVariable(var)) diff --git a/MDANSE/Src/MDANSE/MolecularDynamics/MockTrajectory.py b/MDANSE/Src/MDANSE/MolecularDynamics/MockTrajectory.py index 91c8185939..fe930f49f2 100644 --- a/MDANSE/Src/MDANSE/MolecularDynamics/MockTrajectory.py +++ b/MDANSE/Src/MDANSE/MolecularDynamics/MockTrajectory.py @@ -502,9 +502,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(f"The variable {variable} is not stored in the trajectory") variable = grp[variable][first:last:step, index, :].astype(np.float64) diff --git a/MDANSE/Src/MDANSE/Scripts/mdanse.py b/MDANSE/Src/MDANSE/Scripts/mdanse.py index a5886c6f84..7f7b5d5ee6 100644 --- a/MDANSE/Src/MDANSE/Scripts/mdanse.py +++ b/MDANSE/Src/MDANSE/Scripts/mdanse.py @@ -68,10 +68,15 @@ def format_option(self, option): if option.help: help_text = self.expand_default(option) # Everything is the same up through here - help_lines = [textwrap.wrap(para, self.help_width) for para in help_text.splitlines()] + help_lines = [ + textwrap.wrap(para, self.help_width) for para in help_text.splitlines() + ] # Everything is the same after here result += f"{indent_first}{help_lines[0]}\n" - result += "\n".join(f"{' '*self.help_position}{line}" for line in help_lines[1:]) + "\n" + result += ( + "\n".join(f"{' '*self.help_position}{line}" for line in help_lines[1:]) + + "\n" + ) elif not opts.endswith("\n"): result += "\n" @@ -108,7 +113,9 @@ def check_job(self, option, opt_str, value, parser): """ if len(parser.rargs) != 1: - raise CommandLineParserError(f"Invalid number of arguments for {opt_str!r} option") + raise CommandLineParserError( + f"Invalid number of arguments for {opt_str!r} option" + ) basename = parser.rargs[0] @@ -125,7 +132,9 @@ 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: - raise CommandLineParserError(f"The job {basename!r} could not be opened properly.") + raise CommandLineParserError( + f"The job {basename!r} could not be opened properly." + ) # The job file could be opened and unpickled properly else: @@ -171,7 +180,9 @@ def display_jobs_list(self, option, opt_str, value, parser): """ if len(parser.rargs) != 0: - raise CommandLineParserError(f"Invalid number of arguments for {opt_str!r} option") + raise CommandLineParserError( + f"Invalid number of arguments for {opt_str!r} option" + ) jobs = PLATFORM.temporary_files_directory().glob("*") @@ -244,7 +255,9 @@ def query_classes_registry(self, option, opt_str, value, parser): val = parser.rargs[0] LOG.info(IJob.create(val).info()) else: - raise CommandLineParserError(f"Invalid number of arguments for {opt_str!r} option") + raise CommandLineParserError( + f"Invalid number of arguments for {opt_str!r} option" + ) def run_job(self, option, opt_str, value, parser): """Run job file(s). @@ -263,12 +276,16 @@ def run_job(self, option, opt_str, value, parser): """ if len(parser.rargs) != 1: - raise CommandLineParserError(f"Invalid number of arguments for {opt_str!r} option") + raise CommandLineParserError( + f"Invalid number of arguments for {opt_str!r} option" + ) filename = Path(parser.rargs[0]) if not filename.exists(): - raise CommandLineParserError(f"The job file {filename!r} could not be executed") + raise CommandLineParserError( + f"The job file {filename!r} could not be executed" + ) subprocess.Popen([sys.executable, filename]) @@ -290,7 +307,9 @@ def save_job(self, option, opt_str, value, parser): """ if len(parser.rargs) != 1: - raise CommandLineParserError(f"Invalid number of arguments for {opt_str!r} option") + raise CommandLineParserError( + f"Invalid number of arguments for {opt_str!r} option" + ) jobs = IJob @@ -304,7 +323,9 @@ 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(f"Could not write the job template as {filename!r}") + raise CommandLineParserError( + f"Could not write the job template as {filename!r}" + ) # If the job class has no save method, thisis not a valid MDANSE job. except KeyError: raise CommandLineParserError(f"The job {name!r} is not a valid MDANSE job") diff --git a/MDANSE/Src/MDANSE/Trajectory/H5MDTrajectory.py b/MDANSE/Src/MDANSE/Trajectory/H5MDTrajectory.py index 02aa55b937..241245aa52 100644 --- a/MDANSE/Src/MDANSE/Trajectory/H5MDTrajectory.py +++ b/MDANSE/Src/MDANSE/Trajectory/H5MDTrajectory.py @@ -516,9 +516,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(f"The variable {variable} is not stored in the trajectory") 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 b2641d9b56..431eb6fa6f 100644 --- a/MDANSE/Src/MDANSE/Trajectory/MdanseTrajectory.py +++ b/MDANSE/Src/MDANSE/Trajectory/MdanseTrajectory.py @@ -409,9 +409,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(f"The variable {variable} is not stored in the trajectory") grp = self._h5_file["/configuration"] variable = grp[variable][first:last:step, index, :].astype(np.float64)