Skip to content

Commit

Permalink
Fix ruff errors
Browse files Browse the repository at this point in the history
  • Loading branch information
oerc0122 committed Feb 10, 2025
1 parent 91c80ca commit b0a0311
Show file tree
Hide file tree
Showing 76 changed files with 223 additions and 236 deletions.
30 changes: 14 additions & 16 deletions .github/workflows/lint.yml
Original file line number Diff line number Diff line change
Expand Up @@ -7,25 +7,23 @@ on:
- cron: "0 0 * * *"

jobs:
lint_format_ruff:
lint-mdanse:
runs-on: ubuntu-latest
- uses: actions/checkout@v4
- uses: astral-sh/ruff-action@v3
with:
src: "MDANSE/src"
- name: Analysing the code with Ruff
run: |
ruff format --check
steps:
- uses: actions/checkout@v4
- uses: psf/black@stable
with:
options: "--check --verbose"
src: "MDANSE_GUI/Src"

lint_ruff:
lint_check_ruff:
runs-on: ubuntu-latest
- uses: actions/checkout@v4
- uses: astral-sh/ruff-action@v3
with:
src: "MDANSE/src"
- name: Analysing the code with Ruff
run: |
ruff check
steps:
- uses: actions/checkout@v4
- uses: astral-sh/ruff-action@v3
with:
src: "./MDANSE/Src"
args: "check"

lint-mdanse-gui:
runs-on: ubuntu-latest
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,15 +13,20 @@
# 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.ChemicalSystem import ChemicalSystem
from MDANSE.MolecularDynamics.Trajectory import Trajectory
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_methyl, 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 @@ -70,7 +70,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 @@ -99,10 +99,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
2 changes: 1 addition & 1 deletion MDANSE/Src/MDANSE/Framework/Configurators/IConfigurator.py
Original file line number Diff line number Diff line change
Expand Up @@ -295,7 +295,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
Original file line number Diff line number Diff line change
Expand Up @@ -20,11 +20,11 @@ class InterpolationOrderConfigurator(IntegerConfigurator):
"""
This configurator allows to input the interpolation order to be applied when deriving velocities from atomic coordinates.
The allowed value are *'no interpolation'*,*'1st order'*,*'2nd order'*,*'3rd order'*,*'4th order'* or *'5th order'*, the
The allowed value are *'no interpolation'*,*'1st order'*,*'2nd order'*,*'3rd order'*,*'4th order'* or *'5th order'*, the
former one will not interpolate the velocities from atomic coordinates but will directly use the velocities stored in the trajectory file.
:attention: it is of paramount importance for the trajectory to be sampled with a very low time \
step to get accurate velocities interpolated from atomic coordinates.
step to get accurate velocities interpolated from atomic coordinates.
:note: this configurator depends on 'trajectory' configurator to be configured.
"""
Expand All @@ -50,7 +50,7 @@ def configure(self, value):
"""
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 @@ -62,15 +62,15 @@ def configure(self, value):
if value == 0:
trajConfig = self._configurable[self._dependencies["trajectory"]]

if not "velocities" in trajConfig["instance"].variables():
self.error_status = f"the trajectory does not contain any velocities. Use an interpolation order higher than 0"
if "velocities" not in trajConfig["instance"].variables():
self.error_status = "the trajectory does not contain any velocities. Use an interpolation order higher than 0"
return

self["variable"] = "velocities"

elif value > 5:
self.error_status = (
f"Use an interpolation order greater than 5 is not implemented."
"Use an interpolation order greater than 5 is not implemented."
)
return

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,7 @@ def configure(self, setting: tuple[Union[str, list], str]):
if format in mda._READERS.keys():
self["format"] = format
else:
self.error_status = f"MDAnalysis coordinate file format not recognised."
self.error_status = "MDAnalysis coordinate file format not recognised."
return

topology_configurator = self._configurable[self._dependencies["input_file"]]
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -60,7 +60,7 @@ def configure(self, value):
)
return
else:
self.error_status = f"Unable to determine a time step from MDAnalysis"
self.error_status = "Unable to determine a time step from MDAnalysis"
return

super().configure(value)
Loading

0 comments on commit b0a0311

Please sign in to comment.