diff --git a/MDANSE/Src/MDANSE/Chemistry/Databases.py b/MDANSE/Src/MDANSE/Chemistry/Databases.py index df6f51204c..42fcd7d69d 100644 --- a/MDANSE/Src/MDANSE/Chemistry/Databases.py +++ b/MDANSE/Src/MDANSE/Chemistry/Databases.py @@ -472,18 +472,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 ecefe18fee..b06504d624 100644 --- a/MDANSE/Src/MDANSE/Framework/Configurators/AseInputFileConfigurator.py +++ b/MDANSE/Src/MDANSE/Framework/Configurators/AseInputFileConfigurator.py @@ -106,4 +106,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 b58d8b1987..3d3f87fa89 100644 --- a/MDANSE/Src/MDANSE/Framework/Configurators/HDFTrajectoryConfigurator.py +++ b/MDANSE/Src/MDANSE/Framework/Configurators/HDFTrajectoryConfigurator.py @@ -82,14 +82,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 c77ea5c795..ef19aa0b06 100644 --- a/MDANSE/Src/MDANSE/Framework/Configurators/IConfigurator.py +++ b/MDANSE/Src/MDANSE/Framework/Configurators/IConfigurator.py @@ -49,10 +49,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 @@ -90,12 +87,12 @@ class IConfigurator(dict, metaclass=SubclassFactory): def __init__(self, name, **kwargs): """ Initializes a configurator object. - + :param name: the name of this configurator. :type name: str :param dependencies: the other configurators on which this configurator depends on to be configured. \ This has to be input as a dictionary that maps the name under which the dependency will be used within \ - the configurator implementation to the actual name of the configurator on which this configurator is depending on. + the configurator implementation to the actual name of the configurator on which this configurator is depending on. :type dependencies: (str,str)-dict :param default: the default value of this configurator. :type default: any python object 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 933ae97b4b..360c0c3258 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 os.path.exists(v): v = self._default["dir"] self["mcstas_output_directory"] = v - tmp.append("--%s=%s" % (k, v)) + tmp.append(f"--{k}={v}") dirname = os.path.dirname(self["mcstas_output_directory"]) @@ -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 62f74c32e4..08fb4c7167 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 c2bec2e22a..bf2b016eed 100644 --- a/MDANSE/Src/MDANSE/Framework/Configurators/OutputTrajectoryConfigurator.py +++ b/MDANSE/Src/MDANSE/Framework/Configurators/OutputTrajectoryConfigurator.py @@ -127,7 +127,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 872c7a5708..ca2fd5c7cb 100644 --- a/MDANSE/Src/MDANSE/Framework/Configurators/SingleOutputFileConfigurator.py +++ b/MDANSE/Src/MDANSE/Framework/Configurators/SingleOutputFileConfigurator.py @@ -114,7 +114,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 800b8d7dec..308fe94e46 100644 --- a/MDANSE/Src/MDANSE/Framework/Converters/Gromacs.py +++ b/MDANSE/Src/MDANSE/Framework/Converters/Gromacs.py @@ -115,7 +115,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/HDFFormat.py b/MDANSE/Src/MDANSE/Framework/Formats/HDFFormat.py index 7daf059098..73feee295d 100644 --- a/MDANSE/Src/MDANSE/Framework/Formats/HDFFormat.py +++ b/MDANSE/Src/MDANSE/Framework/Formats/HDFFormat.py @@ -69,7 +69,7 @@ def write( filename = os.path.splitext(filename)[0] - filename = "%s%s" % (filename, extension) + filename = f"{filename}{extension}" # The HDF output file is opened for writing. PLATFORM.create_directory(os.path.dirname(filename)) diff --git a/MDANSE/Src/MDANSE/Framework/Formats/SVGFormat.py b/MDANSE/Src/MDANSE/Framework/Formats/SVGFormat.py index 6b2a187615..df9201c1c6 100644 --- a/MDANSE/Src/MDANSE/Framework/Formats/SVGFormat.py +++ b/MDANSE/Src/MDANSE/Framework/Formats/SVGFormat.py @@ -60,7 +60,7 @@ def write(cls, filename, data, header=""): """ filename = os.path.splitext(filename)[0] - filename = "%s.tar" % filename + filename = f"{filename}.tar" tf = tarfile.open(filename, "w") @@ -70,17 +70,17 @@ def write(cls, filename, 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") svgfilename = os.path.join( - os.path.dirname(filename), "%s%s" % (var.varname, cls.extensions[0]) + os.path.dirname(filename), f"{var.varname}{cls.extensions[0]}" ) Frame( @@ -93,7 +93,7 @@ def write(cls, filename, 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]}") os.remove(svgfilename) diff --git a/MDANSE/Src/MDANSE/Framework/Formats/TextFormat.py b/MDANSE/Src/MDANSE/Framework/Formats/TextFormat.py index 8a62a82751..cc70b6ac19 100644 --- a/MDANSE/Src/MDANSE/Framework/Formats/TextFormat.py +++ b/MDANSE/Src/MDANSE/Framework/Formats/TextFormat.py @@ -62,7 +62,7 @@ def write(cls, filename, data, header: str = "", run_instance: "IJob" = None): """ filename = os.path.splitext(filename)[0] - filename = "%s_text.tar" % filename + filename = f"{filename}_text.tar" PLATFORM.create_directory(os.path.dirname(filename)) tf = tarfile.open(filename, "w") @@ -102,7 +102,7 @@ def write(cls, filename, data, header: str = "", run_instance: "IJob" = None): 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) @@ -132,22 +132,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) @@ -163,15 +161,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 447157bc9e..bf86e290b6 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 = [ @@ -198,7 +198,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") @@ -231,8 +231,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() @@ -387,7 +387,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) @@ -401,7 +401,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"] @@ -427,39 +427,39 @@ 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 = os.path.join(PLATFORM.macros_directory(), "%s.py" % classname) + templateFile = os.path.join(PLATFORM.macros_directory(), f"{classname}.py") try: f = open(templateFile, "w") - + label = "label of the class" 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',) - + ancestor = ["hdf_trajectory"] # 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): """ Initialize the input parameters and analysis self variables @@ -468,7 +468,7 @@ def initialize(self): # Compulsory. You must enter the number of steps of your job. # Here for example the number of selected frames self.numberOfSteps = self.configuration['frames']['number'] - + # Create an output data for the selected frames. self._outputData.add("time", "LineOutputVariable", self.configuration['frames']['time'], units='ps') @@ -477,33 +477,28 @@ def run_step(self, index): """ Runs a single step of the job. """ - + return index, None - - + + def combine(self, index, x): """ Synchronize the output of each individual run_step output. - """ - + """ + def finalize(self): """ Finalizes the job (e.g. averaging the total term, output files creations ...). - """ + """ # The output data are written self._outputData.write(self.configuration['output_files']['root'], self.configuration['output_files']['formats'], self._info, self.output_configuration()) - + # The trajectory is closed - self.configuration['trajectory']['instance'].close() + self.configuration['trajectory']['instance'].close() ''' - % { - "classname": classname, - "label": "label of the class", - "shortname": shortname, - } ) except IOError: diff --git a/MDANSE/Src/MDANSE/Framework/Jobs/McStasVirtualInstrument.py b/MDANSE/Src/MDANSE/Framework/Jobs/McStasVirtualInstrument.py index 8ef6dc5fdd..8946671e9e 100644 --- a/MDANSE/Src/MDANSE/Framework/Jobs/McStasVirtualInstrument.py +++ b/MDANSE/Src/MDANSE/Framework/Jobs/McStasVirtualInstrument.py @@ -223,15 +223,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}") @@ -253,7 +253,7 @@ def run_step(self, index): # + typ # + ".sqw" # ) - sqwInput += "%s=%s " % (typ, fout.name) + sqwInput += f"{typ}={fout.name} " # sys.exit(0) @@ -282,7 +282,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}") with open( os.path.join( @@ -343,7 +343,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 @@ -434,7 +434,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": @@ -469,7 +469,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 53e7addcdf..bf8c7c8726 100644 --- a/MDANSE/Src/MDANSE/Framework/Units.py +++ b/MDANSE/Src/MDANSE/Framework/Units.py @@ -390,55 +390,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 15fc4f620c..439ceb3087 100644 --- a/MDANSE/Src/MDANSE/Framework/UserDefinitionStore.py +++ b/MDANSE/Src/MDANSE/Framework/UserDefinitionStore.py @@ -100,8 +100,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 f24110110a..34e86c139e 100644 --- a/MDANSE/Src/MDANSE/Scripts/mdanse.py +++ b/MDANSE/Src/MDANSE/Scripts/mdanse.py @@ -43,43 +43,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): @@ -112,9 +109,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] @@ -131,24 +126,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] @@ -159,7 +152,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): @@ -179,9 +172,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 = [ f @@ -205,7 +196,7 @@ def display_jobs_list(self, option, opt_str, value, parser): if not isinstance(info, JobState): continue - LOG.info("%-20s [%s]" % (os.path.basename(j), info["state"])) + LOG.info("%-20s [%s]", os.path.basename(j), info["state"]) def display_trajectory_contents(self, option, opt_str, value, parser): """Displays trajectory contents @@ -235,7 +226,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): """ @@ -253,14 +244,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). @@ -279,16 +268,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 = parser.rargs[0] if not os.path.exists(filename): - 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]) @@ -310,31 +295,27 @@ 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 name = parser.rargs[0] # A name for the template is built. - filename = os.path.abspath("template_%s.py" % name.lower()) + filename = os.path.abspath(f"template_{name.lower()}.py") # Try to save the template for the job. try: 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): """ @@ -376,7 +357,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.