Skip to content

Commit

Permalink
First stage of string modernisation
Browse files Browse the repository at this point in the history
  • Loading branch information
oerc0122 committed Feb 10, 2025
1 parent 3f1535c commit 3691d09
Show file tree
Hide file tree
Showing 80 changed files with 398 additions and 518 deletions.
7 changes: 4 additions & 3 deletions MDANSE/Src/MDANSE/Chemistry/Databases.py
Original file line number Diff line number Diff line change
Expand Up @@ -480,18 +480,19 @@ def info(self, atom: str) -> str:

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

info = [
delimiter,
"%s" % atom.center(70),
"%s" % " {0:<20}{1:>50}".format("property", "value"),
f"{atom:^70}",
tab_fmt.format("property", "value"),
delimiter,
]

# The values for all element's properties
for pname in sorted(self._properties):
info.append(
" {0:<20}{1:>50}".format(pname, str(self._data[atom].get(pname, None)))
tab_fmt.format(pname, self._data[atom].get(pname, None))
)

info.append(delimiter)
Expand Down
66 changes: 18 additions & 48 deletions MDANSE/Src/MDANSE/Framework/Configurable.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand All @@ -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
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -105,4 +105,4 @@ def get_information(self):
LOG.error(result)
return result
else:
return "Input file: %r\n" % self["value"]
return f"Input file: {self['value']!r}\n"
Original file line number Diff line number Diff line change
Expand Up @@ -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"

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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:
"""
Expand Down
16 changes: 5 additions & 11 deletions MDANSE/Src/MDANSE/Framework/Configurators/AtomsListConfigurator.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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
Expand Down Expand Up @@ -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"
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down Expand Up @@ -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"
Original file line number Diff line number Diff line change
Expand Up @@ -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
"""
Expand Down Expand Up @@ -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"
Original file line number Diff line number Diff line change
Expand Up @@ -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"
Original file line number Diff line number Diff line change
Expand Up @@ -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"
13 changes: 4 additions & 9 deletions MDANSE/Src/MDANSE/Framework/Configurators/FramesConfigurator.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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!"
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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"
Original file line number Diff line number Diff line change
Expand Up @@ -117,14 +117,14 @@ 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:")
variables = []
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"
Original file line number Diff line number Diff line change
Expand Up @@ -80,14 +80,13 @@ def get_information(self):
:rtype: str
"""
try:
info = ["HDF input trajectory: %r\n" % self["filename"]]
info.append("Number of steps: %d\n" % self["length"])
info = [f"HDF input trajectory: {self['filename']!r}\n"]
info.append(f"Number of steps: {self['length']:d}\n")
except KeyError:
info = "Input trajectory has not been configured"
else:
info.append(
"Size of the chemical system: %d\n"
% self["instance"].chemical_system.number_of_atoms
f"Size of the chemical system: {self['instance'].chemical_system.number_of_atoms:d}\n"
)

if self["has_velocities"]:
Expand Down
5 changes: 1 addition & 4 deletions MDANSE/Src/MDANSE/Framework/Configurators/IConfigurator.py
Original file line number Diff line number Diff line change
Expand Up @@ -59,10 +59,7 @@ def __str__(self):
"""

if self._configurator is not None:
self._message = "Configurator: %r --> %s" % (
self._configurator.name,
self._message,
)
self._message = f"Configurator: {self._configurator.name!r} --> {self._message}"

return self._message

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

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

0 comments on commit 3691d09

Please sign in to comment.