diff --git a/MDANSE/Src/MDANSE/Chemistry/Databases.py b/MDANSE/Src/MDANSE/Chemistry/Databases.py index 9448344bf..a6a9827b3 100644 --- a/MDANSE/Src/MDANSE/Chemistry/Databases.py +++ b/MDANSE/Src/MDANSE/Chemistry/Databases.py @@ -215,7 +215,7 @@ def __getitem__(self, item: str) -> dict: return copy.deepcopy(self._data[item]) except KeyError: raise AtomsDatabaseError( - "The element {} is not registered in the database.".format(item) + f"The element {item} is not registered in the database." ) def _load(self, user_database: str = None, default_database: str = None) -> None: @@ -253,7 +253,7 @@ def add_atom(self, atom: str) -> None: if atom in self._data: raise AtomsDatabaseError( - "The atom {} is already stored in the database".format(atom) + f"The atom {atom} is already stored in the database" ) self._data[atom] = {} @@ -272,11 +272,11 @@ def add_property(self, pname: str, ptype: str) -> None: if pname in self._properties: raise AtomsDatabaseError( - "The property {} is already registered in the database.".format(pname) + f"The property {pname} is already registered in the database." ) if ptype not in AtomsDatabase._TYPES: - raise AtomsDatabaseError("The property type {} is unknown".format(ptype)) + raise AtomsDatabaseError(f"The property type {ptype} is unknown") self._properties[pname] = ptype ptype = AtomsDatabase._TYPES[ptype] @@ -307,7 +307,7 @@ def get_isotopes(self, atom: str) -> list[str]: """ if atom not in self._data: - raise AtomsDatabaseError("The atom {} is unknown".format(atom)) + raise AtomsDatabaseError(f"The atom {atom} is unknown") # The isotopes are searched according to |symbol| property symbol = self._data[atom]["symbol"] @@ -340,7 +340,7 @@ def get_property(self, pname: str) -> dict[str, Union[str, int, float, list]]: if pname not in self._properties: raise AtomsDatabaseError( - "The property {} is not registered in the database".format(pname) + f"The property {pname} is not registered in the database" ) ptype = AtomsDatabase._TYPES[self._properties[pname]] @@ -365,11 +365,11 @@ def get_value(self, atom: str, pname: str) -> Union[str, int, float, list]: """ if atom not in self._data: - raise AtomsDatabaseError("The atom {} is unknown".format(atom)) + raise AtomsDatabaseError(f"The atom {atom} is unknown") if pname not in self._properties: raise AtomsDatabaseError( - "The property {} is not registered in the database".format(pname) + f"The property {pname} is not registered in the database" ) ptype = self._properties[pname] @@ -397,12 +397,12 @@ def get_values_for_multiple_atoms( if not all(atom in self._data for atom in atoms): raise AtomsDatabaseError( - "One or more of the provided atoms {} are unknown".format(atoms) + f"One or more of the provided atoms {atoms} are unknown" ) if prop not in self._properties: raise AtomsDatabaseError( - "The property {} is not registered in the database".format(prop) + f"The property {prop} is not registered in the database" ) values = {name: self._data[name][prop] for name in unique_atoms} @@ -425,11 +425,11 @@ def set_value( """ if atom not in self._data: - raise AtomsDatabaseError("The element {} is unknown".format(atom)) + raise AtomsDatabaseError(f"The element {atom} is unknown") if pname not in self._properties: raise AtomsDatabaseError( - "The property {} is not registered in the database".format(pname) + f"The property {pname} is not registered in the database" ) try: @@ -438,7 +438,7 @@ def set_value( ) except ValueError: raise AtomsDatabaseError( - "Can not coerce {} to {} type".format(value, self._properties[pname]) + f"Can not coerce {value} to {self._properties[pname]} type" ) def has_atom(self, atom: str) -> bool: @@ -480,7 +480,7 @@ def info(self, atom: str) -> str: # A delimiter line. delimiter = "-" * 70 - tab_fmt = "{:<20}{:>50}" + tab_fmt = " {:<20}{!s:>50}" info = [ delimiter, @@ -491,9 +491,7 @@ def info(self, atom: str) -> str: # The values for all element's properties for pname in sorted(self._properties): - info.append( - tab_fmt.format(pname, self._data[atom].get(pname, None)) - ) + info.append(tab_fmt.format(pname, self._data[atom].get(pname, None))) info.append(delimiter) info = "\n".join(info) @@ -526,7 +524,7 @@ def match_numeric_property( ) except KeyError: raise AtomsDatabaseError( - "The property {} is not registered in the database".format(pname) + f"The property {pname} is not registered in the database" ) tolerance = abs(tolerance) diff --git a/MDANSE/Src/MDANSE/Framework/Configurable.py b/MDANSE/Src/MDANSE/Framework/Configurable.py index 2d68c083a..ef8664e1b 100644 --- a/MDANSE/Src/MDANSE/Framework/Configurable.py +++ b/MDANSE/Src/MDANSE/Framework/Configurable.py @@ -251,17 +251,19 @@ def build_doc_texttable(cls, doclist): v["Description"] = v["Description"].strip() v["Description"] = v["Description"].splitlines() v["Description"] = ["| " + vv.strip() for vv in v["Description"]] - sizes[2] = max(sizes[2], max(v["Description"], key=len)) + sizes[2] = max(sizes[2], max(map(len, v["Description"]))) data_line = "| " + "| ".join(f"{{}}:<{size}" for size in sizes) + "|\n" - sep_line = "+" + "+".join("-" * (size+1) for size in sizes) + "+\n" + sep_line = "+" + "+".join("-" * (size + 1) for size in sizes) + "+\n" docstring += sep_line docstring += data_line.format(*columns) docstring += sep_line.replace("-", "=") for v in doclist: - docstring += data_line.format(v["Configurator"], v["Default value"], v["Description"][0]) + docstring += data_line.format( + v["Configurator"], v["Default value"], v["Description"][0] + ) if len(v["Description"]) > 1: for descr in v["Description"][1:]: data_line.format("", "", descr) diff --git a/MDANSE/Src/MDANSE/Framework/Configurators/IConfigurator.py b/MDANSE/Src/MDANSE/Framework/Configurators/IConfigurator.py index 17c93689d..b1015712c 100644 --- a/MDANSE/Src/MDANSE/Framework/Configurators/IConfigurator.py +++ b/MDANSE/Src/MDANSE/Framework/Configurators/IConfigurator.py @@ -59,7 +59,9 @@ def __str__(self): """ if self._configurator is not None: - self._message = f"Configurator: {self._configurator.name!r} --> {self._message}" + self._message = ( + f"Configurator: {self._configurator.name!r} --> {self._message}" + ) return self._message diff --git a/MDANSE/Src/MDANSE/Framework/Configurators/QVectorsConfigurator.py b/MDANSE/Src/MDANSE/Framework/Configurators/QVectorsConfigurator.py index 42c8033d5..0434425c5 100644 --- a/MDANSE/Src/MDANSE/Framework/Configurators/QVectorsConfigurator.py +++ b/MDANSE/Src/MDANSE/Framework/Configurators/QVectorsConfigurator.py @@ -122,8 +122,6 @@ def get_information(self): return "QVectors could not be configured correctly" else: for qValue, qVectors in self["q_vectors"].items(): - info.append( - f"Shell {qValue}: {len(qVectors)} Q vectors generated\n" - ) + info.append(f"Shell {qValue}: {len(qVectors)} Q vectors generated\n") return "".join(info) diff --git a/MDANSE/Src/MDANSE/Framework/Configurators/RangeConfigurator.py b/MDANSE/Src/MDANSE/Framework/Configurators/RangeConfigurator.py index 84508d850..11c00d616 100644 --- a/MDANSE/Src/MDANSE/Framework/Configurators/RangeConfigurator.py +++ b/MDANSE/Src/MDANSE/Framework/Configurators/RangeConfigurator.py @@ -213,7 +213,7 @@ def get_information(self): if self._valid: - info = f"{self['number']} values from {self['first']} to {self['last']}" + info = f"{self['number']:d} values from {self['first']} to {self['last']}" if self._includeLast: info += " last value included" diff --git a/MDANSE/Src/MDANSE/Framework/Configurators/XYZFileConfigurator.py b/MDANSE/Src/MDANSE/Framework/Configurators/XYZFileConfigurator.py index 72d69119c..94cc95392 100644 --- a/MDANSE/Src/MDANSE/Framework/Configurators/XYZFileConfigurator.py +++ b/MDANSE/Src/MDANSE/Framework/Configurators/XYZFileConfigurator.py @@ -47,9 +47,7 @@ def parse(self): try: self["n_atoms"] = int(self["instance"].readline().strip()) except ValueError: - raise XYZFileError( - f"Could not read the number of atoms in {filename} file" - ) + raise XYZFileError(f"Could not read the number of atoms in {filename} file") self._nAtomsLineSize = self["instance"].tell() self["instance"].readline() diff --git a/MDANSE/Src/MDANSE/Framework/Converters/DCD.py b/MDANSE/Src/MDANSE/Framework/Converters/DCD.py index 3e4510eb7..f857de26a 100644 --- a/MDANSE/Src/MDANSE/Framework/Converters/DCD.py +++ b/MDANSE/Src/MDANSE/Framework/Converters/DCD.py @@ -69,9 +69,7 @@ def get_byte_order(filename): break if byteOrder is None: - raise ByteOrderError( - f"Invalid byte order. {filename} not a valid DCD file" - ) + raise ByteOrderError(f"Invalid byte order. {filename} not a valid DCD file") return byteOrder diff --git a/MDANSE/Src/MDANSE/Framework/Converters/Forcite.py b/MDANSE/Src/MDANSE/Framework/Converters/Forcite.py index ad177b57d..75f1f80a4 100644 --- a/MDANSE/Src/MDANSE/Framework/Converters/Forcite.py +++ b/MDANSE/Src/MDANSE/Framework/Converters/Forcite.py @@ -173,7 +173,7 @@ def parse_header(self): if self["velocities_written"]: if self["gradients_written"]: # Frame record 8,9,10,11,12,13,14,15,16 - self._configRec = "!" + (f"{self['totmov']}{self._fp}8x" * 9) + self._configRec = "!" + (f"!{self['totmov']}{self._fp}8x" * 9) else: # Frame record 8,9,10,11,12,13 self._configRec = "!" + (f"{self['totmov']}{self._fp}8x" * 6) diff --git a/MDANSE/Src/MDANSE/Framework/Converters/LAMMPS.py b/MDANSE/Src/MDANSE/Framework/Converters/LAMMPS.py index e06e156f2..b36f591d8 100644 --- a/MDANSE/Src/MDANSE/Framework/Converters/LAMMPS.py +++ b/MDANSE/Src/MDANSE/Framework/Converters/LAMMPS.py @@ -222,7 +222,7 @@ def parse_first_step(self, aliases, config): ) label = str(config["elements"][ty][0]) mass = str(config["elements"][ty][1]) - name = "{:s}_{:d}".format(str(config["elements"][ty][0]), idx) + name = f"{label}_{idx:d}" try: temp_index = int(temp[0]) except ValueError: @@ -470,7 +470,7 @@ def parse_first_step(self, aliases, config): ty = atom_types[i] - 1 label = str(config["elements"][ty][0]) mass = str(config["elements"][ty][1]) - name = "{:s}_{:d}".format(str(config["elements"][ty][0]), idx) + name = f"{label}_{idx:d}" self._rankToName[idx] = name element_list.append(get_element_from_mapping(aliases, label, mass=mass)) name_list.append(str(ty + 1)) @@ -579,7 +579,7 @@ def parse_first_step(self, aliases, config): ty = atom_types[i] - 1 label = str(config["elements"][ty][0]) mass = str(config["elements"][ty][1]) - name = "{:s}_{:d}".format(str(config["elements"][ty][0]), idx) + name = f"{label}_{idx:d}" self._rankToName[idx] = name element_list.append(get_element_from_mapping(aliases, label, mass=mass)) name_list.append(str(ty + 1)) diff --git a/MDANSE/Src/MDANSE/Framework/Formats/TextFormat.py b/MDANSE/Src/MDANSE/Framework/Formats/TextFormat.py index fdcab8c1d..cd408e26c 100644 --- a/MDANSE/Src/MDANSE/Framework/Formats/TextFormat.py +++ b/MDANSE/Src/MDANSE/Framework/Formats/TextFormat.py @@ -141,18 +141,14 @@ def write_data(cls, fileobject, data, allData): fileobject.write(f"# 1st column: {xData} (au)\n") else: xValues = allData[xData] - fileobject.write( - f"# 1st column: {xValues.varname} ({xValues.units})\n" - ) + fileobject.write(f"# 1st column: {xValues.varname} ({xValues.units})\n") if yData == "index": yValues = np.arange(data.shape[1]) fileobject.write(f"# 1st row: {yData} (au)\n\n") else: yValues = allData[yData] - fileobject.write( - f"# 1st row: {yValues.varname} ({yValues.units})\n\n" - ) + fileobject.write(f"# 1st row: {yValues.varname} ({yValues.units})\n\n") zData = np.zeros((data.shape[0] + 1, data.shape[1] + 1), dtype=np.float64) zData[1:, 0] = xValues @@ -170,9 +166,7 @@ def write_data(cls, fileobject, data, allData): fileobject.write(f"# 1st column: {xData} (au)\n") else: xValues = allData[xData] - fileobject.write( - f"# 1st column: {xValues.varname} ({xValues.units})\n" - ) + fileobject.write(f"# 1st column: {xValues.varname} ({xValues.units})\n") fileobject.write(f"# 2nd column: {data.varname} ({data.units})\n\n") diff --git a/MDANSE/Src/MDANSE/Framework/InputData/HDFTrajectoryInputData.py b/MDANSE/Src/MDANSE/Framework/InputData/HDFTrajectoryInputData.py index 1f773a108..c99672f78 100644 --- a/MDANSE/Src/MDANSE/Framework/InputData/HDFTrajectoryInputData.py +++ b/MDANSE/Src/MDANSE/Framework/InputData/HDFTrajectoryInputData.py @@ -61,11 +61,9 @@ def info(self): val.append("Number of steps:") val.append(f"{self._data}\n") val.append("Configuration:") - val.append(f"\tIs periodic: {"unit_cell" in self._data.file}\n") + val.append(f"\tIs periodic: {'unit_cell' in self._data.file}\n") try: - val.append( - f"First unit cell (nm):\n{self._data.unit_cell(0)._unit_cell}\n" - ) + val.append(f"First unit cell (nm):\n{self._data.unit_cell(0)._unit_cell}\n") except: val.append("No unit cell information\n") val.append("Frame times (1st, 2nd, ..., last) in ps:") diff --git a/MDANSE/Src/MDANSE/Framework/Jobs/CoordinationNumber.py b/MDANSE/Src/MDANSE/Framework/Jobs/CoordinationNumber.py index fc725617f..085507894 100644 --- a/MDANSE/Src/MDANSE/Framework/Jobs/CoordinationNumber.py +++ b/MDANSE/Src/MDANSE/Framework/Jobs/CoordinationNumber.py @@ -154,6 +154,10 @@ def finalize(self): nAtomsPerElement = self.configuration["atom_selection"].get_natoms() for pair in self._elementsPairs: at1, at2 = pair + invPair = pair[::-1] + pair_str = "".join(map(str, pair)) + inv_pair_str = "".join(map(str, invPair)) + ni = nAtomsPerElement[at1] nj = nAtomsPerElement[at2] @@ -179,8 +183,6 @@ def finalize(self): cAlpha = self._concentrations[pair[0]] cBeta = self._concentrations[pair[1]] - invPair = pair[::-1] - self._outputData[f"cn_intra_{pair_str}"][:] = ( self.averageDensity * cBeta * cnIntra ) diff --git a/MDANSE/Src/MDANSE/Framework/Jobs/CurrentCorrelationFunction.py b/MDANSE/Src/MDANSE/Framework/Jobs/CurrentCorrelationFunction.py index 3fe6154ae..26cc75509 100644 --- a/MDANSE/Src/MDANSE/Framework/Jobs/CurrentCorrelationFunction.py +++ b/MDANSE/Src/MDANSE/Framework/Jobs/CurrentCorrelationFunction.py @@ -378,7 +378,7 @@ def finalize(self): self._outputData[f"j(q,t)_long_{pair_str}"][:] /= ni * nj self._outputData[f"j(q,t)_trans_{pair_str}"][:] /= ni * nj self._outputData[f"J(q,f)_long_{pair_str}"][:] = get_spectrum( - self._outputData["j(q,t)_long_{pair_str}"], + self._outputData[f"j(q,t)_long_{pair_str}"], self.configuration["instrument_resolution"]["time_window"], self.configuration["instrument_resolution"]["time_step"], axis=1, diff --git a/MDANSE/Src/MDANSE/Framework/Jobs/DynamicIncoherentStructureFactor.py b/MDANSE/Src/MDANSE/Framework/Jobs/DynamicIncoherentStructureFactor.py index 1c20b0af5..0c69b4344 100644 --- a/MDANSE/Src/MDANSE/Framework/Jobs/DynamicIncoherentStructureFactor.py +++ b/MDANSE/Src/MDANSE/Framework/Jobs/DynamicIncoherentStructureFactor.py @@ -245,7 +245,7 @@ def combine(self, index, disf_per_q_shell): element = self.configuration["atom_selection"]["names"][index] for i, v in enumerate(disf_per_q_shell.values()): - self._outputData["f(q,t)_{}".format(element)][i, :] += v + self._outputData[f"f(q,t)_{element}"][i, :] += v def finalize(self): """ diff --git a/MDANSE/Src/MDANSE/Framework/Jobs/GeneralAutoCorrelationFunction.py b/MDANSE/Src/MDANSE/Framework/Jobs/GeneralAutoCorrelationFunction.py index 2e3e36ab1..be158c6da 100644 --- a/MDANSE/Src/MDANSE/Framework/Jobs/GeneralAutoCorrelationFunction.py +++ b/MDANSE/Src/MDANSE/Framework/Jobs/GeneralAutoCorrelationFunction.py @@ -95,7 +95,7 @@ def initialize(self): # Will store the mean square displacement evolution. for element in self.configuration["atom_selection"]["unique_names"]: self._outputData.add( - "gacf_{}".format(element), + f"gacf_{element}", "LineOutputVariable", (self.configuration["frames"]["number"],), axis="time", @@ -161,14 +161,14 @@ def finalize(self): self.configuration["atom_selection"]["n_atoms_per_element"] = nAtomsPerElement for element, number in nAtomsPerElement.items(): - self._outputData["gacf_{}".format(element)] /= number + self._outputData[f"gacf_{element}"] /= number if self.configuration["normalize"]["value"]: for element in nAtomsPerElement.keys(): - if self._outputData["gacf_{}}".format(element)][0] == 0: + if self._outputData[f"gacf_{element}}}"][0] == 0: raise ValueError("The normalization factor is equal to zero") else: - self._outputData["gacf_{}".format(element)] = normalize( + self._outputData[f"gacf_{element}"] = normalize( self._outputData[f"gacf_{element}"], axis=0 ) diff --git a/MDANSE/Src/MDANSE/Framework/Jobs/IJob.py b/MDANSE/Src/MDANSE/Framework/Jobs/IJob.py index 60aee6b94..b087e7174 100644 --- a/MDANSE/Src/MDANSE/Framework/Jobs/IJob.py +++ b/MDANSE/Src/MDANSE/Framework/Jobs/IJob.py @@ -439,7 +439,7 @@ def save_template(cls, shortname, classname): from MDANSE.Framework.Jobs.IJob import IJob -class {classname}s(IJob): +class {classname}(IJob): """ You should enter the description of your job here ... """ @@ -498,7 +498,7 @@ def finalize(self): self.configuration['trajectory']['instance'].close() ''' - ) + ) except IOError: return None diff --git a/MDANSE/Src/MDANSE/Framework/Jobs/McStasVirtualInstrument.py b/MDANSE/Src/MDANSE/Framework/Jobs/McStasVirtualInstrument.py index e14bc0bd2..9cf8acae1 100644 --- a/MDANSE/Src/MDANSE/Framework/Jobs/McStasVirtualInstrument.py +++ b/MDANSE/Src/MDANSE/Framework/Jobs/McStasVirtualInstrument.py @@ -233,9 +233,7 @@ def run_step(self, index): for k, v in list(self._mcStasPhysicalParameters.items()): fout.write(f"# {k} {v} \n") - fout.write( - f"# Temperature {self.configuration['temperature']['value']} \n" - ) + fout.write(f"# Temperature {self.configuration['temperature']['value']} \n") fout.write("#\n") for var in self.configuration[typ].variables: diff --git a/MDANSE/Src/MDANSE/Framework/Jobs/NeutronDynamicTotalStructureFactor.py b/MDANSE/Src/MDANSE/Framework/Jobs/NeutronDynamicTotalStructureFactor.py index 0538309ed..a69acaecb 100644 --- a/MDANSE/Src/MDANSE/Framework/Jobs/NeutronDynamicTotalStructureFactor.py +++ b/MDANSE/Src/MDANSE/Framework/Jobs/NeutronDynamicTotalStructureFactor.py @@ -198,15 +198,16 @@ def initialize(self): ) ) for pair in self._elementsPairs: + pair_str = "".join(map(str, pair)) if ( - "f(q,t)_{}{}".format(*pair) + f"f(q,t)_{pair_str}" not in self.configuration["dcsf_input_file"]["instance"] ): raise NeutronDynamicTotalStructureFactorError( "Missing f(q,t) in dcsf input file" ) if ( - "s(q,f)_{}{}".format(*pair) + f"s(q,f)_{pair_str}" not in self.configuration["dcsf_input_file"]["instance"] ): raise NeutronDynamicTotalStructureFactorError( @@ -215,14 +216,14 @@ def initialize(self): for element in self.configuration["atom_selection"]["unique_names"]: if ( - "f(q,t)_{}".format(element) + f"f(q,t)_{element}" not in self.configuration["disf_input_file"]["instance"] ): raise NeutronDynamicTotalStructureFactorError( "Missing f(q,t) in disf input file" ) if ( - "s(q,f)_{}".format(element) + f"s(q,f)_{element}" not in self.configuration["disf_input_file"]["instance"] ): raise NeutronDynamicTotalStructureFactorError( @@ -230,12 +231,8 @@ def initialize(self): ) for element in self.configuration["atom_selection"]["unique_names"]: - fqt = self.configuration["disf_input_file"]["instance"][ - "f(q,t)_{}".format(element) - ] - sqf = self.configuration["disf_input_file"]["instance"][ - "s(q,f)_{}".format(element) - ] + fqt = self.configuration["disf_input_file"]["instance"][f"f(q,t)_{element}"] + sqf = self.configuration["disf_input_file"]["instance"][f"s(q,f)_{element}"] self._outputData.add( f"f(q,t)_inc_{element}", "SurfaceOutputVariable", @@ -266,7 +263,7 @@ def initialize(self): ) for pair in self._elementsPairs: - pair_str = ''.join(map(str, pair)) + pair_str = "".join(map(str, pair)) fqt = self.configuration["dcsf_input_file"]["instance"][ f"f(q,t)_{pair_str}" ] @@ -390,6 +387,7 @@ def finalize(self): # Compute coherent functions and structure factor for pair in self._elementsPairs: + pair_str = "".join(map(str, pair)) bi = self.configuration["trajectory"]["instance"].get_atom_property( pair[0], "b_coherent" ) diff --git a/MDANSE/Src/MDANSE/Framework/Jobs/PairDistributionFunction.py b/MDANSE/Src/MDANSE/Framework/Jobs/PairDistributionFunction.py index a5e8a7dc6..9f5363cea 100644 --- a/MDANSE/Src/MDANSE/Framework/Jobs/PairDistributionFunction.py +++ b/MDANSE/Src/MDANSE/Framework/Jobs/PairDistributionFunction.py @@ -138,11 +138,11 @@ def finalize(self): for i, pdf in zip( ["intra", "inter", "total"], [pdf_intra, pdf_inter, pdf_total] ): - self._outputData[f"pdf_{i}_{pair[0]}{pair[1]}")][:] = pdf - self._outputData[f"rdf_{i}_{pair[0]}{pair[1]}")][:] = ( + self._outputData[f"pdf_{i}_{pair[0]}{pair[1]}"][:] = pdf + self._outputData[f"rdf_{i}_{pair[0]}{pair[1]}"][:] = ( shellSurfaces * self.averageDensity * pdf ) - self._outputData[f"tcf_{i}_{pair[0]}{pair[1]}")][:] = ( + self._outputData[f"tcf_{i}_{pair[0]}{pair[1]}"][:] = ( densityFactor * self.averageDensity * (pdf if i == "intra" else pdf - 1) @@ -156,7 +156,7 @@ def finalize(self): self._outputData, nAtomsPerElement, 2, - f"pdf{i if i else "_total"}_%s%s", + f"pdf{i if i else '_total'}_%s%s", ) self._outputData[f"pdf{i}_total"][:] = pdf self._outputData[f"rdf{i}_total"][:] = ( diff --git a/MDANSE/Src/MDANSE/Framework/Jobs/RigidBodyTrajectory.py b/MDANSE/Src/MDANSE/Framework/Jobs/RigidBodyTrajectory.py index 1cb5f0c48..ba4e25af6 100644 --- a/MDANSE/Src/MDANSE/Framework/Jobs/RigidBodyTrajectory.py +++ b/MDANSE/Src/MDANSE/Framework/Jobs/RigidBodyTrajectory.py @@ -91,7 +91,7 @@ def initialize(self): raise JobError( self, "Invalid reference frame. Must be an integer in " - f"[{0},{self.configuration['trajectory']['length']}[" + f"[{0},{self.configuration['trajectory']['length']}[", ) self._quaternions = np.zeros( diff --git a/MDANSE/Src/MDANSE/Framework/Jobs/RootMeanSquareDeviation.py b/MDANSE/Src/MDANSE/Framework/Jobs/RootMeanSquareDeviation.py index 74d34d969..40dad188a 100644 --- a/MDANSE/Src/MDANSE/Framework/Jobs/RootMeanSquareDeviation.py +++ b/MDANSE/Src/MDANSE/Framework/Jobs/RootMeanSquareDeviation.py @@ -93,7 +93,7 @@ def initialize(self): # Will initially store the mean square deviation before appling the root for element in self.configuration["atom_selection"]["unique_names"]: self._outputData.add( - "rmsd_{}".format(element), + f"rmsd_{element}", "LineOutputVariable", (self.configuration["frames"]["number"],), axis="time", @@ -156,11 +156,11 @@ def finalize(self): nAtomsPerElement = self.configuration["atom_selection"].get_natoms() for element, number in nAtomsPerElement.items(): - self._outputData["rmsd_{}".format(element)] /= number + self._outputData[f"rmsd_{element}"] /= number for element, number in nAtomsPerElement.items(): - self._outputData["rmsd_{}".format(element)] = np.sqrt( - self._outputData["rmsd_{}".format(element)] + self._outputData[f"rmsd_{element}"] = np.sqrt( + self._outputData[f"rmsd_{element}"] ) self._outputData["rmsd_all"] /= self.configuration[ diff --git a/MDANSE/Src/MDANSE/Framework/Jobs/StaticStructureFactor.py b/MDANSE/Src/MDANSE/Framework/Jobs/StaticStructureFactor.py index 3392e686c..9b0321681 100644 --- a/MDANSE/Src/MDANSE/Framework/Jobs/StaticStructureFactor.py +++ b/MDANSE/Src/MDANSE/Framework/Jobs/StaticStructureFactor.py @@ -142,7 +142,7 @@ def finalize(self): nAtomsPerElement = self.configuration["atom_selection"].get_natoms() for pair in self._elementsPairs: - pair_str = ''.join(map(str, pair)) + pair_str = "".join(map(str, pair)) self._outputData.add( f"ssf_intra_{pair_str}", "LineOutputVariable", diff --git a/MDANSE/Src/MDANSE/Framework/Jobs/VanHoveFunctionDistinct.py b/MDANSE/Src/MDANSE/Framework/Jobs/VanHoveFunctionDistinct.py index 953971b88..a0aa77df3 100644 --- a/MDANSE/Src/MDANSE/Framework/Jobs/VanHoveFunctionDistinct.py +++ b/MDANSE/Src/MDANSE/Framework/Jobs/VanHoveFunctionDistinct.py @@ -484,9 +484,7 @@ def finalize(self): ["intra", "inter", "total"], [van_hove_intra, van_hove_inter, van_hove_total], ): - self._outputData[f"g(r,t)_{i}_{pair[0]}{pair[1]}"][ - ... - ] = van_hove + self._outputData[f"g(r,t)_{i}_{pair[0]}{pair[1]}"][...] = van_hove weights = self.configuration["weights"].get_weights() for i in ["_intra", "_inter", ""]: diff --git a/MDANSE/Src/MDANSE/Framework/Jobs/VanHoveFunctionSelf.py b/MDANSE/Src/MDANSE/Framework/Jobs/VanHoveFunctionSelf.py index 738610c13..9d7b0749a 100644 --- a/MDANSE/Src/MDANSE/Framework/Jobs/VanHoveFunctionSelf.py +++ b/MDANSE/Src/MDANSE/Framework/Jobs/VanHoveFunctionSelf.py @@ -274,8 +274,8 @@ def combine(self, atm_index: int, histogram: np.ndarray): time t0 and t0 + t. """ element = self.configuration["atom_selection"]["names"][atm_index] - self._outputData["g(r,t)_{}".format(element)][:] += histogram - self._outputData["4_pi_r2_g(r,t)_{}".format(element)][:] += histogram + self._outputData[f"g(r,t)_{element}"][:] += histogram + self._outputData[f"4_pi_r2_g(r,t)_{element}"][:] += histogram def finalize(self): """Using the distance histograms calculate, normalize and save the diff --git a/MDANSE/Src/MDANSE/Framework/Jobs/XRayStaticStructureFactor.py b/MDANSE/Src/MDANSE/Framework/Jobs/XRayStaticStructureFactor.py index 1b15b10fa..3e14db0c6 100644 --- a/MDANSE/Src/MDANSE/Framework/Jobs/XRayStaticStructureFactor.py +++ b/MDANSE/Src/MDANSE/Framework/Jobs/XRayStaticStructureFactor.py @@ -135,7 +135,7 @@ def finalize(self): nAtomsPerElement = self.configuration["atom_selection"].get_natoms() for pair in self._elementsPairs: - pair_str = ''.join(map(str, pair)) + pair_str = "".join(map(str, pair)) self._outputData.add( f"xssf_intra_{pair_str}", "LineOutputVariable", @@ -210,12 +210,12 @@ def finalize(self): ) xssfIntra = weight( - asf, self._outputData, nAtomsPerElement, 2, f"xssf_intra_{pair_str}" + asf, self._outputData, nAtomsPerElement, 2, f"xssf_intra_%s%s" ) self._outputData["xssf_intra"][:] = xssfIntra xssfInter = weight( - asf, self._outputData, nAtomsPerElement, 2, f"xssf_inter_{pair_str}" + asf, self._outputData, nAtomsPerElement, 2, f"xssf_inter_%s%s" ) self._outputData["xssf_inter"][:] = xssfInter diff --git a/MDANSE/Src/MDANSE/Framework/Units.py b/MDANSE/Src/MDANSE/Framework/Units.py index cd9326e82..5083435d2 100644 --- a/MDANSE/Src/MDANSE/Framework/Units.py +++ b/MDANSE/Src/MDANSE/Framework/Units.py @@ -95,11 +95,11 @@ def _parse_unit(iunit): iunit = iunit[i:] break else: - raise UnitError("The unit {} is unknown".format(iunit)) + raise UnitError(f"The unit {iunit} is unknown") if prefix: if prefix not in _PREFIXES: - raise UnitError("The prefix {} is unknown".format(prefix)) + raise UnitError(f"The prefix {prefix} is unknown") prefix = _PREFIXES[prefix] else: prefix = 1.0 @@ -150,7 +150,7 @@ def _str_to_unit(s): return unit else: - raise UnitError("Invalid unit: {}".format(s)) + raise UnitError(f"Invalid unit: {s}") class _Unit(object): @@ -399,7 +399,9 @@ def __str__(self): continue ref = positive_units if uval > 0 else negative_units - unit = str(uname) + (format(abs(uval), "d") if isinstance(uval, int) else str(uval)) + unit = str(uname) + ( + format(abs(uval), "d") if isinstance(uval, int) else str(uval) + ) ref.append(unit) positive_units_str = " ".join(positive_units) diff --git a/MDANSE/Src/MDANSE/IO/HDF.py b/MDANSE/Src/MDANSE/IO/HDF.py index 5efc26439..d48a15e9a 100644 --- a/MDANSE/Src/MDANSE/IO/HDF.py +++ b/MDANSE/Src/MDANSE/IO/HDF.py @@ -29,9 +29,9 @@ def find_numeric_variables(variables, group): find_numeric_variables(variables, var) else: if var.parent.name == "/": - path = "/{}".format(var_key) + path = f"/{var_key}" else: - path = "{}/{}".format(var.parent.name, var_key) + path = f"{var.parent.name}/{var_key}" if not np.issubdtype(var.dtype, np.number): continue diff --git a/MDANSE/Src/MDANSE/IO/HDF5.py b/MDANSE/Src/MDANSE/IO/HDF5.py index 28f0a0685..61d41a48d 100644 --- a/MDANSE/Src/MDANSE/IO/HDF5.py +++ b/MDANSE/Src/MDANSE/IO/HDF5.py @@ -56,9 +56,9 @@ def find_numeric_variables(var_dict, group): find_numeric_variables(var_dict, var) else: if var.parent.name == "/": - path = "/{}".format(var_key) + path = f"/{var_key}" else: - path = "{}/{}".format(var.parent.name, var_key) + path = f"{var.parent.name}/{var_key}" # Non-numeric variables are not supported by the plotter if not np.issubdtype(var.dtype, np.number): @@ -70,7 +70,7 @@ def find_numeric_variables(var_dict, group): comp = 1 while var_key in var_dict: - var_key = "{:s}_{:d}".format(var_key, comp) + var_key = f"{var_key:s}_{comp:d}" comp += 1 var_dict[var_key] = (path, HDFFileVariable(var)) diff --git a/MDANSE/Src/MDANSE/MolecularDynamics/MockTrajectory.py b/MDANSE/Src/MDANSE/MolecularDynamics/MockTrajectory.py index 91c818593..fe930f49f 100644 --- a/MDANSE/Src/MDANSE/MolecularDynamics/MockTrajectory.py +++ b/MDANSE/Src/MDANSE/MolecularDynamics/MockTrajectory.py @@ -502,9 +502,7 @@ def read_configuration_trajectory( grp = self._variables if variable not in grp: - raise KeyError( - "The variable {} is not stored in the trajectory".format(variable) - ) + raise KeyError(f"The variable {variable} is not stored in the trajectory") variable = grp[variable][first:last:step, index, :].astype(np.float64) diff --git a/MDANSE/Src/MDANSE/Scripts/mdanse.py b/MDANSE/Src/MDANSE/Scripts/mdanse.py index a5886c6f8..7f7b5d5ee 100644 --- a/MDANSE/Src/MDANSE/Scripts/mdanse.py +++ b/MDANSE/Src/MDANSE/Scripts/mdanse.py @@ -68,10 +68,15 @@ def format_option(self, option): if option.help: help_text = self.expand_default(option) # Everything is the same up through here - help_lines = [textwrap.wrap(para, self.help_width) for para in help_text.splitlines()] + help_lines = [ + textwrap.wrap(para, self.help_width) for para in help_text.splitlines() + ] # Everything is the same after here result += f"{indent_first}{help_lines[0]}\n" - result += "\n".join(f"{' '*self.help_position}{line}" for line in help_lines[1:]) + "\n" + result += ( + "\n".join(f"{' '*self.help_position}{line}" for line in help_lines[1:]) + + "\n" + ) elif not opts.endswith("\n"): result += "\n" @@ -108,7 +113,9 @@ def check_job(self, option, opt_str, value, parser): """ if len(parser.rargs) != 1: - raise CommandLineParserError(f"Invalid number of arguments for {opt_str!r} option") + raise CommandLineParserError( + f"Invalid number of arguments for {opt_str!r} option" + ) basename = parser.rargs[0] @@ -125,7 +132,9 @@ def check_job(self, option, opt_str, value, parser): # If the file could not be opened/unpickled for whatever reason, try at the next checkpoint except: - raise CommandLineParserError(f"The job {basename!r} could not be opened properly.") + raise CommandLineParserError( + f"The job {basename!r} could not be opened properly." + ) # The job file could be opened and unpickled properly else: @@ -171,7 +180,9 @@ def display_jobs_list(self, option, opt_str, value, parser): """ if len(parser.rargs) != 0: - raise CommandLineParserError(f"Invalid number of arguments for {opt_str!r} option") + raise CommandLineParserError( + f"Invalid number of arguments for {opt_str!r} option" + ) jobs = PLATFORM.temporary_files_directory().glob("*") @@ -244,7 +255,9 @@ def query_classes_registry(self, option, opt_str, value, parser): val = parser.rargs[0] LOG.info(IJob.create(val).info()) else: - raise CommandLineParserError(f"Invalid number of arguments for {opt_str!r} option") + raise CommandLineParserError( + f"Invalid number of arguments for {opt_str!r} option" + ) def run_job(self, option, opt_str, value, parser): """Run job file(s). @@ -263,12 +276,16 @@ def run_job(self, option, opt_str, value, parser): """ if len(parser.rargs) != 1: - raise CommandLineParserError(f"Invalid number of arguments for {opt_str!r} option") + raise CommandLineParserError( + f"Invalid number of arguments for {opt_str!r} option" + ) filename = Path(parser.rargs[0]) if not filename.exists(): - raise CommandLineParserError(f"The job file {filename!r} could not be executed") + raise CommandLineParserError( + f"The job file {filename!r} could not be executed" + ) subprocess.Popen([sys.executable, filename]) @@ -290,7 +307,9 @@ def save_job(self, option, opt_str, value, parser): """ if len(parser.rargs) != 1: - raise CommandLineParserError(f"Invalid number of arguments for {opt_str!r} option") + raise CommandLineParserError( + f"Invalid number of arguments for {opt_str!r} option" + ) jobs = IJob @@ -304,7 +323,9 @@ def save_job(self, option, opt_str, value, parser): jobs.create(name).save(filename) # Case where an error occured when writing the template. except IOError: - raise CommandLineParserError(f"Could not write the job template as {filename!r}") + raise CommandLineParserError( + f"Could not write the job template as {filename!r}" + ) # If the job class has no save method, thisis not a valid MDANSE job. except KeyError: raise CommandLineParserError(f"The job {name!r} is not a valid MDANSE job") diff --git a/MDANSE/Src/MDANSE/Trajectory/H5MDTrajectory.py b/MDANSE/Src/MDANSE/Trajectory/H5MDTrajectory.py index 02aa55b93..241245aa5 100644 --- a/MDANSE/Src/MDANSE/Trajectory/H5MDTrajectory.py +++ b/MDANSE/Src/MDANSE/Trajectory/H5MDTrajectory.py @@ -516,9 +516,7 @@ def read_configuration_trajectory( last = len(self) if not self.has_variable(variable): - raise KeyError( - "The variable {} is not stored in the trajectory".format(variable) - ) + raise KeyError(f"The variable {variable} is not stored in the trajectory") grp = self._h5_file["/particles/all"] variable = grp[variable]["value"][first:last:step, index, :].astype(np.float64) diff --git a/MDANSE/Src/MDANSE/Trajectory/MdanseTrajectory.py b/MDANSE/Src/MDANSE/Trajectory/MdanseTrajectory.py index b2641d9b5..431eb6fa6 100644 --- a/MDANSE/Src/MDANSE/Trajectory/MdanseTrajectory.py +++ b/MDANSE/Src/MDANSE/Trajectory/MdanseTrajectory.py @@ -409,9 +409,7 @@ def read_configuration_trajectory( last = len(self) if not self.has_variable(variable): - raise KeyError( - "The variable {} is not stored in the trajectory".format(variable) - ) + raise KeyError(f"The variable {variable} is not stored in the trajectory") grp = self._h5_file["/configuration"] variable = grp[variable][first:last:step, index, :].astype(np.float64)