Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add ruff #642

Merged
merged 2 commits into from
Feb 11, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 9 additions & 0 deletions .github/workflows/lint.yml
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,15 @@ jobs:
options: "--check --verbose"
src: "MDANSE/Src"

lint_check_ruff:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: astral-sh/ruff-action@v3
with:
src: "./MDANSE/Src"
args: "check"

lint-mdanse-gui:
runs-on: ubuntu-latest
steps:
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
24 changes: 20 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,31 @@
# 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
2 changes: 1 addition & 1 deletion MDANSE/Src/MDANSE/Framework/Configurable.py
Original file line number Diff line number Diff line change
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(f"Could not set {name!r} configuration item")

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,7 +99,7 @@ def get_information(self):
:rtype: str
"""
try:
val = self["value"]
self["value"]
except KeyError:
result = f"No VALUE in {self._name}"
LOG.error(result)
Expand Down
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 @@ -294,7 +294,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)
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,7 @@ def configure(self, setting: str) -> None:
if format in mda._PARSERS.keys():
self["format"] = format
else:
self.error_status = f"MDAnalysis topology file format not recognised."
self.error_status = "MDAnalysis topology file format not recognised."
return
super().configure(filepath)

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,7 @@ def configure(self, value):
)
return
else:
self.error_status = f"Unable to determine a time step from MDTraj"
self.error_status = "Unable to determine a time step from MDTraj"
return

super().configure(value)
Original file line number Diff line number Diff line change
Expand Up @@ -62,7 +62,7 @@ def configure(self, value: Optional[str]):

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"

else:
extension = "".join(Path(value).suffixes)[1:]
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ def configure(self, value):

extensions = {"".join(Path(value).suffixes)[1:] for value in self["values"]}
if len(extensions) != 1:
self.error_status = f"Files should be of a single format."
self.error_status = "Files should be of a single format."
return
self.extension = next(iter(extensions))

Expand Down
Loading