Skip to content

Commit

Permalink
Fix ruff errors
Browse files Browse the repository at this point in the history
  • Loading branch information
oerc0122 committed Jan 24, 2025
1 parent 1fa9c32 commit 64be73e
Show file tree
Hide file tree
Showing 85 changed files with 251 additions and 272 deletions.
2 changes: 1 addition & 1 deletion MDANSE/Src/MDANSE/Chemistry/ChemicalEntity.py
Original file line number Diff line number Diff line change
Expand Up @@ -2410,7 +2410,7 @@ def translate_atom_names(
:return: The list of renamed atoms.
:rtype: list
"""
if not molname in database:
if molname not in database:
raise UnknownMoleculeError("The molecule {} is unknown".format(molname))

renamed_atoms = []
Expand Down
4 changes: 2 additions & 2 deletions MDANSE/Src/MDANSE/Chemistry/Structrures.py
Original file line number Diff line number Diff line change
Expand Up @@ -62,7 +62,7 @@ def identify_molecule(self, frame_num: int = 0) -> str:
}
try:
temp_pdb.writeLine("ATOM", atom_data)
except:
except Exception:
LOG.warning(atom_data)
temp_pdb.close()
mol_object = MolFromPDBBlock(buffer.getvalue())
Expand Down Expand Up @@ -122,7 +122,7 @@ def scan_trajectory_frame(self, frame_num: int = 0):
}
try:
temp_pdb.writeLine("ATOM", atom_data)
except:
except Exception:
LOG.warning(atom_data)
temp_pdb.close()
mol_object = MolFromPDBBlock(buffer.getvalue())
Expand Down
7 changes: 2 additions & 5 deletions MDANSE/Src/MDANSE/Core/Platform.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,10 +20,9 @@
import getpass
import inspect
import os
import platform
import re
import subprocess
import tempfile


from MDANSE.Core.Error import Error

Expand Down Expand Up @@ -521,7 +520,7 @@ def get_process_creation_time(self, process):
exittime = ctypes.c_ulonglong()
kerneltime = ctypes.c_ulonglong()
usertime = ctypes.c_ulonglong()
rc = ctypes.windll.kernel32.GetProcessTimes(
ctypes.windll.kernel32.GetProcessTimes(
process,
ctypes.byref(creationtime),
ctypes.byref(exittime),
Expand Down Expand Up @@ -623,8 +622,6 @@ def kill_process(self, pid):
ctypes.windll.kernel32.CloseHandle(handle)


import platform

system = platform.system()

# Instantiate the proper platform class depending on the OS on which MDANSE runs
Expand Down
4 changes: 2 additions & 2 deletions MDANSE/Src/MDANSE/Core/SubclassFactory.py
Original file line number Diff line number Diff line change
Expand Up @@ -90,7 +90,7 @@ def recursive_keys(parent_class: type) -> list:
"""
try:
results = parent_class.subclasses()
except:
except Exception:
return []
else:
for child in parent_class.subclasses():
Expand All @@ -117,7 +117,7 @@ def recursive_dict(parent_class: type) -> dict:
ckey: parent_class._registered_subclasses[ckey]
for ckey in parent_class.subclasses()
}
except:
except Exception:
return {}
else:
for child in parent_class.subclasses():
Expand Down
2 changes: 1 addition & 1 deletion MDANSE/Src/MDANSE/Framework/AtomMapping/atom_mapping.py
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,7 @@ def __init__(self, atm_label: str, **kwargs):
# methods as of writing e.g. re.sub
translation = str.maketrans("", "", ";=")
self.atm_label = atm_label.translate(translation)
self.grp_label = f""
self.grp_label = ""
if kwargs:
for k, v in kwargs.items():
self.grp_label += f"{k}={str(v).translate(translation)};"
Expand Down
13 changes: 9 additions & 4 deletions MDANSE/Src/MDANSE/Framework/AtomSelector/selector.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,14 +13,19 @@
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <https://www.gnu.org/licenses/>.
#
import json
import copy
import json
from typing import Union

from MDANSE.Chemistry.ChemicalEntity import ChemicalSystem
from MDANSE.Framework.AtomSelector.all_selector import select_all
from MDANSE.Framework.AtomSelector.atom_selectors import *
from MDANSE.Framework.AtomSelector.group_selectors import *
from MDANSE.Framework.AtomSelector.molecule_selectors import *
from MDANSE.Framework.AtomSelector.atom_selectors import (
select_atom_fullname, select_atom_name, select_dummy, select_element,
select_hs_on_element, select_hs_on_heteroatom, select_index)
from MDANSE.Framework.AtomSelector.group_selectors import (
select_hydroxy, select_methly, select_phosphate, select_primary_amine,
select_sulphate, select_thiol)
from MDANSE.Framework.AtomSelector.molecule_selectors import select_water


class Selector:
Expand Down
6 changes: 3 additions & 3 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 @@ -93,7 +93,7 @@ def build_configuration(self):
typ, name, configurable=self, **kwds
)
# Any kind of error has to be caught
except:
except Exception:
raise ConfigurationError("Could not set %r configuration item" % name)

def set_settings(self, settings):
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ def parse(self):

try:
self._input = ASETrajectory(self["filename"])
except:
except Exception:
self._input = iread(self["filename"], index="[:]")
first_frame = read(self["filename"], index=0)
else:
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -71,7 +71,7 @@ def configure(self, values):
if file_format == "guess":
file_format = None

if file_format is not None and not file_format in self._allowed_formats:
if file_format is not None and file_format not in self._allowed_formats:
LOG.error(f"WRONG FORMAT in {self._name}")
self.error_status = f"The ASE file format {file_format} is not supported"
return
Expand Down Expand Up @@ -100,10 +100,10 @@ def get_information(self):
:rtype: str
"""
try:
val = self["value"]
self["value"]
except KeyError:
result = f"No VALUE in {self._name}"
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 @@ -32,13 +32,11 @@ class BooleanConfigurator(IConfigurator):
"yes": True,
"y": True,
"1": True,
1: True,
False: False,
"false": False,
"no": False,
"n": False,
"0": False,
0: False,
}

def configure(self, value):
Expand Down
20 changes: 10 additions & 10 deletions MDANSE/Src/MDANSE/Framework/Configurators/ConfigFileConfigurator.py
Original file line number Diff line number Diff line change
Expand Up @@ -75,30 +75,30 @@ def parse(self):

with open(self._filename, "r") as source_file:
lines = []
for l in source_file.readlines():
l = l.strip()
if l:
lines.append(l)
for line in source_file.readlines():
line = line.strip()
if line:
lines.append(line)

for i, line in enumerate(lines):
toks = line.split()

if "xlo" in line and "xhi" in line:
try:
x_inputs = [float(x) for x in toks[0:3]]
except:
except Exception:
xspan = float(toks[1]) - float(toks[0])
self["unit_cell"][0, 0] = xspan
elif "ylo" in line and "yhi" in line:
try:
y_inputs = [float(x) for x in toks[0:3]]
except:
except Exception:
yspan = float(toks[1]) - float(toks[0])
self["unit_cell"][1, 1] = yspan
elif "zlo" in line and "zhi" in line:
try:
z_inputs = [float(x) for x in toks[0:3]]
except:
except Exception:
zspan = float(toks[1]) - float(toks[0])
self["unit_cell"][2, 2] = zspan

Expand Down Expand Up @@ -142,7 +142,7 @@ def parse(self):
self["bonds"] = np.array(self["bonds"], dtype=np.int32)

if re.match("^\s*Atoms\s*$", line.split("#")[0]):
if not "#" in line:
if "#" not in line:
num_of_columns = len(lines[i + 2].split())
if num_of_columns <= 5:
type_index = 1
Expand Down Expand Up @@ -184,8 +184,8 @@ def parse(self):
self["unit_cell"] = parse_unit_cell(
np.concatenate([x_inputs, y_inputs, z_inputs])
)
except:
LOG.error(f"LAMMPS ConfigFileConfigurator failed to find a unit cell")
except Exception:
LOG.error("LAMMPS ConfigFileConfigurator failed to find a unit cell")

def atom_labels(self) -> Iterable[AtomLabel]:
"""
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -42,16 +42,16 @@ def configure(self, value: tuple[int, int, int, int]):

if c_frames > self["n_frames"]:
self.error_status = (
f"Number of frames used for the correlation "
f"greater than the total number of frames of "
f"the trajectory."
"Number of frames used for the correlation "
"greater than the total number of frames of "
"the trajectory."
)
return

if c_frames < 2:
self.error_status = (
f"Number of frames used for the correlation "
f"should be greater then zero."
"Number of frames used for the correlation "
"should be greater then zero."
)
return

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,7 @@ def configure(self, value: Optional[int]) -> None:
"""
frames_configurator = self._configurable[self._dependencies["frames"]]
if not frames_configurator._valid:
self.error_status = f"Frames configurator is not valid."
self.error_status = "Frames configurator is not valid."
return

self._original_input = value
Expand All @@ -54,8 +54,8 @@ def configure(self, value: Optional[int]) -> None:

if value <= 0 or value > 5:
self.error_status = (
f"Use an interpolation order less than or equal to zero or "
f"greater than 5 is not implemented."
"Use an interpolation order less than or equal to zero or "
"greater than 5 is not implemented."
)
return

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,7 @@ def get_largest_cutoff(self) -> float:
for frame in range(len(traj_config))
]
)
except:
except Exception:
return np.linalg.norm(traj_config.min_span)
else:
if np.allclose(trajectory_array, 0.0):
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,7 @@ def configure(self, filepath: str) -> None:

self.labels = self.unique_labels()
if len(self.labels) == 0:
self.error_status = f"Unable to generate atom labels"
self.error_status = "Unable to generate atom labels"
return

@abstractmethod
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -60,12 +60,12 @@ def configure(self, value):

try:
value = float(value)
except (TypeError, ValueError) as e:
except (TypeError, ValueError):
self.error_status = f"Wrong value {value} in {self}"
return

if self._choices:
if not value in self._choices:
if value not in self._choices:
self.error_status = "the input value is not a valid choice."
return

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -76,7 +76,7 @@ def configure(self, value):
self[v] = self["instance"][v][:]
try:
self._units[v] = self["instance"][v].attrs["units"]
except:
except Exception:
self._units[v] = "unitless"
else:
self.error_status = (
Expand Down
6 changes: 3 additions & 3 deletions MDANSE/Src/MDANSE/Framework/Configurators/IConfigurator.py
Original file line number Diff line number Diff line change
Expand Up @@ -90,12 +90,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
Expand Down Expand Up @@ -285,7 +285,7 @@ def check_dependencies(self, configured=None):
:rtype: bool
"""

if configured == None:
if configured is None:
names = [str(key) for key in self._configurable._configuration.keys()]
configured = [
name
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,6 @@

from MDANSE.Framework.Configurators.IConfigurator import (
IConfigurator,
ConfiguratorError,
)


Expand Down Expand Up @@ -72,7 +71,7 @@ def configure(self, value):
return

if self._choices:
if not value in self._choices:
if value not in self._choices:
self.error_status = "the input value is not a valid choice."
return

Expand Down
Loading

0 comments on commit 64be73e

Please sign in to comment.