Skip to content

Commit

Permalink
Remove unnecessary .format.
Browse files Browse the repository at this point in the history
  • Loading branch information
oerc0122 committed Feb 3, 2025
1 parent 933c0c6 commit 560ed94
Show file tree
Hide file tree
Showing 32 changed files with 116 additions and 117 deletions.
34 changes: 16 additions & 18 deletions MDANSE/Src/MDANSE/Chemistry/Databases.py
Original file line number Diff line number Diff line change
Expand Up @@ -207,7 +207,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:
Expand Down Expand Up @@ -245,7 +245,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] = {}
Expand All @@ -264,11 +264,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]
Expand Down Expand Up @@ -299,7 +299,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"]
Expand Down Expand Up @@ -332,7 +332,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]]
Expand All @@ -357,11 +357,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]
Expand Down Expand Up @@ -389,12 +389,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}
Expand All @@ -417,11 +417,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:
Expand All @@ -430,7 +430,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:
Expand Down Expand Up @@ -472,7 +472,7 @@ def info(self, atom: str) -> str:

# A delimiter line.
delimiter = "-" * 70
tab_fmt = "{:<20}{:>50}"
tab_fmt = " {:<20}{!s:>50}"

info = [
delimiter,
Expand All @@ -483,9 +483,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)
Expand Down Expand Up @@ -518,7 +516,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)
Expand Down
2 changes: 1 addition & 1 deletion MDANSE/Src/MDANSE/Core/Platform.py
Original file line number Diff line number Diff line change
Expand Up @@ -217,7 +217,7 @@ def create_directory(self, path):
except OSError as e:
raise PlatformError(
"The following exception was raised while trying to create a directory at "
"{0}: /n {1}".format(str(path), e)
f"{path}: /n {e}"
)

@classmethod
Expand Down
8 changes: 5 additions & 3 deletions MDANSE/Src/MDANSE/Framework/Configurable.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
4 changes: 3 additions & 1 deletion MDANSE/Src/MDANSE/Framework/Configurators/IConfigurator.py
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,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

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Original file line number Diff line number Diff line change
Expand Up @@ -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"
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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()
Expand Down
4 changes: 1 addition & 3 deletions MDANSE/Src/MDANSE/Framework/Converters/DCD.py
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down
2 changes: 1 addition & 1 deletion MDANSE/Src/MDANSE/Framework/Converters/Forcite.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
6 changes: 3 additions & 3 deletions MDANSE/Src/MDANSE/Framework/Converters/LAMMPS.py
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand Down Expand Up @@ -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))
Expand Down Expand Up @@ -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))
Expand Down
12 changes: 3 additions & 9 deletions MDANSE/Src/MDANSE/Framework/Formats/TextFormat.py
Original file line number Diff line number Diff line change
Expand Up @@ -135,18 +135,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
Expand All @@ -164,9 +160,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")

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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:")
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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):
"""
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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",
Expand Down Expand Up @@ -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
)

Expand Down
2 changes: 1 addition & 1 deletion MDANSE/Src/MDANSE/Framework/Jobs/IJob.py
Original file line number Diff line number Diff line change
Expand Up @@ -440,7 +440,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 ...
"""
Expand Down
4 changes: 1 addition & 3 deletions MDANSE/Src/MDANSE/Framework/Jobs/McStasVirtualInstrument.py
Original file line number Diff line number Diff line change
Expand Up @@ -225,9 +225,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:
Expand Down
Loading

0 comments on commit 560ed94

Please sign in to comment.