diff --git a/.github/workflows/lint.yml b/.github/workflows/lint.yml index bd9d080533..4641bae389 100644 --- a/.github/workflows/lint.yml +++ b/.github/workflows/lint.yml @@ -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: diff --git a/MDANSE/Src/MDANSE/Core/SubclassFactory.py b/MDANSE/Src/MDANSE/Core/SubclassFactory.py index 39de5a6d31..2a2bdb0721 100644 --- a/MDANSE/Src/MDANSE/Core/SubclassFactory.py +++ b/MDANSE/Src/MDANSE/Core/SubclassFactory.py @@ -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(): @@ -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(): diff --git a/MDANSE/Src/MDANSE/Framework/AtomMapping/atom_mapping.py b/MDANSE/Src/MDANSE/Framework/AtomMapping/atom_mapping.py index f518f8a0e7..b2ee2ca975 100644 --- a/MDANSE/Src/MDANSE/Framework/AtomMapping/atom_mapping.py +++ b/MDANSE/Src/MDANSE/Framework/AtomMapping/atom_mapping.py @@ -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)};" diff --git a/MDANSE/Src/MDANSE/Framework/AtomSelector/selector.py b/MDANSE/Src/MDANSE/Framework/AtomSelector/selector.py index f98d9aafdc..3562149e70 100644 --- a/MDANSE/Src/MDANSE/Framework/AtomSelector/selector.py +++ b/MDANSE/Src/MDANSE/Framework/AtomSelector/selector.py @@ -13,15 +13,31 @@ # You should have received a copy of the GNU General Public License # along with this program. If not, see . # -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: diff --git a/MDANSE/Src/MDANSE/Framework/Configurable.py b/MDANSE/Src/MDANSE/Framework/Configurable.py index ef8664e1b4..1ee336434e 100644 --- a/MDANSE/Src/MDANSE/Framework/Configurable.py +++ b/MDANSE/Src/MDANSE/Framework/Configurable.py @@ -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): diff --git a/MDANSE/Src/MDANSE/Framework/Configurators/ASEFileConfigurator.py b/MDANSE/Src/MDANSE/Framework/Configurators/ASEFileConfigurator.py index 3323569b56..8f57aa1e20 100644 --- a/MDANSE/Src/MDANSE/Framework/Configurators/ASEFileConfigurator.py +++ b/MDANSE/Src/MDANSE/Framework/Configurators/ASEFileConfigurator.py @@ -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: diff --git a/MDANSE/Src/MDANSE/Framework/Configurators/AseInputFileConfigurator.py b/MDANSE/Src/MDANSE/Framework/Configurators/AseInputFileConfigurator.py index 0654a47b3f..883873b5e7 100644 --- a/MDANSE/Src/MDANSE/Framework/Configurators/AseInputFileConfigurator.py +++ b/MDANSE/Src/MDANSE/Framework/Configurators/AseInputFileConfigurator.py @@ -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 @@ -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) diff --git a/MDANSE/Src/MDANSE/Framework/Configurators/BooleanConfigurator.py b/MDANSE/Src/MDANSE/Framework/Configurators/BooleanConfigurator.py index e51ada3771..640c8e8f7d 100644 --- a/MDANSE/Src/MDANSE/Framework/Configurators/BooleanConfigurator.py +++ b/MDANSE/Src/MDANSE/Framework/Configurators/BooleanConfigurator.py @@ -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): diff --git a/MDANSE/Src/MDANSE/Framework/Configurators/ConfigFileConfigurator.py b/MDANSE/Src/MDANSE/Framework/Configurators/ConfigFileConfigurator.py index 33bd20fe52..1af42d6711 100644 --- a/MDANSE/Src/MDANSE/Framework/Configurators/ConfigFileConfigurator.py +++ b/MDANSE/Src/MDANSE/Framework/Configurators/ConfigFileConfigurator.py @@ -75,10 +75,10 @@ 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() @@ -86,19 +86,19 @@ def parse(self): 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 @@ -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 @@ -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]: """ diff --git a/MDANSE/Src/MDANSE/Framework/Configurators/CorrelationFramesConfigurator.py b/MDANSE/Src/MDANSE/Framework/Configurators/CorrelationFramesConfigurator.py index bdfec1a231..4de5aa93c3 100644 --- a/MDANSE/Src/MDANSE/Framework/Configurators/CorrelationFramesConfigurator.py +++ b/MDANSE/Src/MDANSE/Framework/Configurators/CorrelationFramesConfigurator.py @@ -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 diff --git a/MDANSE/Src/MDANSE/Framework/Configurators/DerivativeOrderConfigurator.py b/MDANSE/Src/MDANSE/Framework/Configurators/DerivativeOrderConfigurator.py index 43d2eb9351..71436b9641 100644 --- a/MDANSE/Src/MDANSE/Framework/Configurators/DerivativeOrderConfigurator.py +++ b/MDANSE/Src/MDANSE/Framework/Configurators/DerivativeOrderConfigurator.py @@ -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 @@ -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 diff --git a/MDANSE/Src/MDANSE/Framework/Configurators/DistHistCutoffConfigurator.py b/MDANSE/Src/MDANSE/Framework/Configurators/DistHistCutoffConfigurator.py index eeb4c2af82..dee9d13c9d 100644 --- a/MDANSE/Src/MDANSE/Framework/Configurators/DistHistCutoffConfigurator.py +++ b/MDANSE/Src/MDANSE/Framework/Configurators/DistHistCutoffConfigurator.py @@ -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): diff --git a/MDANSE/Src/MDANSE/Framework/Configurators/FileWithAtomDataConfigurator.py b/MDANSE/Src/MDANSE/Framework/Configurators/FileWithAtomDataConfigurator.py index ba52283580..8f3c8d5407 100644 --- a/MDANSE/Src/MDANSE/Framework/Configurators/FileWithAtomDataConfigurator.py +++ b/MDANSE/Src/MDANSE/Framework/Configurators/FileWithAtomDataConfigurator.py @@ -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 diff --git a/MDANSE/Src/MDANSE/Framework/Configurators/FloatConfigurator.py b/MDANSE/Src/MDANSE/Framework/Configurators/FloatConfigurator.py index 3234e06f45..0168a2d5bb 100644 --- a/MDANSE/Src/MDANSE/Framework/Configurators/FloatConfigurator.py +++ b/MDANSE/Src/MDANSE/Framework/Configurators/FloatConfigurator.py @@ -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 diff --git a/MDANSE/Src/MDANSE/Framework/Configurators/HDFInputFileConfigurator.py b/MDANSE/Src/MDANSE/Framework/Configurators/HDFInputFileConfigurator.py index 6efce61cc5..ae092df745 100644 --- a/MDANSE/Src/MDANSE/Framework/Configurators/HDFInputFileConfigurator.py +++ b/MDANSE/Src/MDANSE/Framework/Configurators/HDFInputFileConfigurator.py @@ -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 = ( diff --git a/MDANSE/Src/MDANSE/Framework/Configurators/IConfigurator.py b/MDANSE/Src/MDANSE/Framework/Configurators/IConfigurator.py index b1015712c5..70d3436a4b 100644 --- a/MDANSE/Src/MDANSE/Framework/Configurators/IConfigurator.py +++ b/MDANSE/Src/MDANSE/Framework/Configurators/IConfigurator.py @@ -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 diff --git a/MDANSE/Src/MDANSE/Framework/Configurators/IntegerConfigurator.py b/MDANSE/Src/MDANSE/Framework/Configurators/IntegerConfigurator.py index 73307c54f5..b74080169f 100644 --- a/MDANSE/Src/MDANSE/Framework/Configurators/IntegerConfigurator.py +++ b/MDANSE/Src/MDANSE/Framework/Configurators/IntegerConfigurator.py @@ -17,7 +17,6 @@ from MDANSE.Framework.Configurators.IConfigurator import ( IConfigurator, - ConfiguratorError, ) @@ -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 diff --git a/MDANSE/Src/MDANSE/Framework/Configurators/InterpolationOrderConfigurator.py b/MDANSE/Src/MDANSE/Framework/Configurators/InterpolationOrderConfigurator.py index d259a6c470..f42ed27e48 100644 --- a/MDANSE/Src/MDANSE/Framework/Configurators/InterpolationOrderConfigurator.py +++ b/MDANSE/Src/MDANSE/Framework/Configurators/InterpolationOrderConfigurator.py @@ -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. """ @@ -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 @@ -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 diff --git a/MDANSE/Src/MDANSE/Framework/Configurators/MDAnalysisCoordinateFileConfigurator.py b/MDANSE/Src/MDANSE/Framework/Configurators/MDAnalysisCoordinateFileConfigurator.py index 51c8da812e..ce9d17c174 100644 --- a/MDANSE/Src/MDANSE/Framework/Configurators/MDAnalysisCoordinateFileConfigurator.py +++ b/MDANSE/Src/MDANSE/Framework/Configurators/MDAnalysisCoordinateFileConfigurator.py @@ -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"]] diff --git a/MDANSE/Src/MDANSE/Framework/Configurators/MDAnalysisTimeStepConfigurator.py b/MDANSE/Src/MDANSE/Framework/Configurators/MDAnalysisTimeStepConfigurator.py index 53b52fcfc1..eab8d125a1 100644 --- a/MDANSE/Src/MDANSE/Framework/Configurators/MDAnalysisTimeStepConfigurator.py +++ b/MDANSE/Src/MDANSE/Framework/Configurators/MDAnalysisTimeStepConfigurator.py @@ -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) diff --git a/MDANSE/Src/MDANSE/Framework/Configurators/MDAnalysisTopologyFileConfigurator.py b/MDANSE/Src/MDANSE/Framework/Configurators/MDAnalysisTopologyFileConfigurator.py index c454dc99cb..50b0c4e9ab 100644 --- a/MDANSE/Src/MDANSE/Framework/Configurators/MDAnalysisTopologyFileConfigurator.py +++ b/MDANSE/Src/MDANSE/Framework/Configurators/MDAnalysisTopologyFileConfigurator.py @@ -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) diff --git a/MDANSE/Src/MDANSE/Framework/Configurators/MDTrajTimeStepConfigurator.py b/MDANSE/Src/MDANSE/Framework/Configurators/MDTrajTimeStepConfigurator.py index e3bb891d51..dea06a4d9b 100644 --- a/MDANSE/Src/MDANSE/Framework/Configurators/MDTrajTimeStepConfigurator.py +++ b/MDANSE/Src/MDANSE/Framework/Configurators/MDTrajTimeStepConfigurator.py @@ -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) diff --git a/MDANSE/Src/MDANSE/Framework/Configurators/MDTrajTopologyFileConfigurator.py b/MDANSE/Src/MDANSE/Framework/Configurators/MDTrajTopologyFileConfigurator.py index a67b240138..ee3e6fe221 100644 --- a/MDANSE/Src/MDANSE/Framework/Configurators/MDTrajTopologyFileConfigurator.py +++ b/MDANSE/Src/MDANSE/Framework/Configurators/MDTrajTopologyFileConfigurator.py @@ -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:] diff --git a/MDANSE/Src/MDANSE/Framework/Configurators/MDTrajTrajectoryFileConfigurator.py b/MDANSE/Src/MDANSE/Framework/Configurators/MDTrajTrajectoryFileConfigurator.py index a44cac00ba..41df11c7ad 100644 --- a/MDANSE/Src/MDANSE/Framework/Configurators/MDTrajTrajectoryFileConfigurator.py +++ b/MDANSE/Src/MDANSE/Framework/Configurators/MDTrajTrajectoryFileConfigurator.py @@ -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)) diff --git a/MDANSE/Src/MDANSE/Framework/Configurators/McStasOptionsConfigurator.py b/MDANSE/Src/MDANSE/Framework/Configurators/McStasOptionsConfigurator.py index 1bfa4170ca..e4fe3c697f 100644 --- a/MDANSE/Src/MDANSE/Framework/Configurators/McStasOptionsConfigurator.py +++ b/MDANSE/Src/MDANSE/Framework/Configurators/McStasOptionsConfigurator.py @@ -34,10 +34,10 @@ def parse_dictionary(input: str) -> Dict[str, Any]: value = value.strip(" '") try: value = int(value) - except: + except Exception: try: value = float(value) - except: + except Exception: pass result[key] = value return result @@ -90,7 +90,7 @@ def configure(self, value): try: PLATFORM.create_directory(dirname) - except: + except Exception: self.error_status = f"The directory {dirname} is not writable" return diff --git a/MDANSE/Src/MDANSE/Framework/Configurators/MultiInputFileConfigurator.py b/MDANSE/Src/MDANSE/Framework/Configurators/MultiInputFileConfigurator.py index bd327045ab..772c64efb3 100644 --- a/MDANSE/Src/MDANSE/Framework/Configurators/MultiInputFileConfigurator.py +++ b/MDANSE/Src/MDANSE/Framework/Configurators/MultiInputFileConfigurator.py @@ -54,7 +54,7 @@ def configure(self, setting: Union[str, list]): return if type(values) is not list: self.error_status = ( - f"Input values should be able to be evaluated as a list" + "Input values should be able to be evaluated as a list" ) return else: @@ -62,10 +62,10 @@ def configure(self, setting: Union[str, list]): if type(values) is list: if not all([type(value) is str for value in values]): - self.error_status = f"Input values should be a list of str" + self.error_status = "Input values should be a list of str" return else: - self.error_status = f"Input values should be able to be evaluated as a list" + self.error_status = "Input values should be able to be evaluated as a list" return values = [PLATFORM.get_path(value) for value in values] diff --git a/MDANSE/Src/MDANSE/Framework/Configurators/MultipleChoicesConfigurator.py b/MDANSE/Src/MDANSE/Framework/Configurators/MultipleChoicesConfigurator.py index 2550678660..75b111d8ca 100644 --- a/MDANSE/Src/MDANSE/Framework/Configurators/MultipleChoicesConfigurator.py +++ b/MDANSE/Src/MDANSE/Framework/Configurators/MultipleChoicesConfigurator.py @@ -58,7 +58,7 @@ def configure(self, value): if self._nChoices is not None: if len(value) != self._nChoices: - self.error_status = f"invalid number of choices." + self.error_status = "invalid number of choices." return indices = [] diff --git a/MDANSE/Src/MDANSE/Framework/Configurators/OptionalFloatConfigurator.py b/MDANSE/Src/MDANSE/Framework/Configurators/OptionalFloatConfigurator.py index 8ab4439ed8..8bde4cd50b 100644 --- a/MDANSE/Src/MDANSE/Framework/Configurators/OptionalFloatConfigurator.py +++ b/MDANSE/Src/MDANSE/Framework/Configurators/OptionalFloatConfigurator.py @@ -66,12 +66,12 @@ def configure(self, value): try: value[1] = float(value[1]) - except (TypeError, ValueError) as e: + except (TypeError, ValueError): self.error_status = f"Wrong value {value[1]} in {self}" return if self._choices: - if not value[1] in self._choices: + if value[1] not in self._choices: self.error_status = "the input value is not a valid choice." return diff --git a/MDANSE/Src/MDANSE/Framework/Configurators/OutputFilesConfigurator.py b/MDANSE/Src/MDANSE/Framework/Configurators/OutputFilesConfigurator.py index 145ab6e294..ce191021d3 100644 --- a/MDANSE/Src/MDANSE/Framework/Configurators/OutputFilesConfigurator.py +++ b/MDANSE/Src/MDANSE/Framework/Configurators/OutputFilesConfigurator.py @@ -80,11 +80,11 @@ def configure(self, value): return if not formats: - self.error_status = f"no output formats specified" + self.error_status = "no output formats specified" return for fmt in formats: - if not fmt in self._formats: + if fmt not in self._formats: self.error_status = ( f"the output file format {fmt} is not a valid output format" ) @@ -127,7 +127,7 @@ def get_information(self): :return: the information about this configurator. :rtype: str """ - if not "files" in self: + if "files" not in self: return "Output Files have not been defined" info = ["Input files:\n"] diff --git a/MDANSE/Src/MDANSE/Framework/Configurators/OutputStructureConfigurator.py b/MDANSE/Src/MDANSE/Framework/Configurators/OutputStructureConfigurator.py index c55f0d1e39..102d406a67 100644 --- a/MDANSE/Src/MDANSE/Framework/Configurators/OutputStructureConfigurator.py +++ b/MDANSE/Src/MDANSE/Framework/Configurators/OutputStructureConfigurator.py @@ -78,8 +78,8 @@ def configure(self, value): self.error_status = f"the file {root} is not writable" return - if not format in self.formats: - self.error_status = f"Output format is not supported" + if format not in self.formats: + self.error_status = "Output format is not supported" return self["root"] = root @@ -110,7 +110,7 @@ def get_information(self): :return: the information about this configurator. :rtype: str """ - if not "file" in self: + if "file" not in self: return "Output File have not been defined" info = f"Output file: {self['file']}\n" diff --git a/MDANSE/Src/MDANSE/Framework/Configurators/OutputTrajectoryConfigurator.py b/MDANSE/Src/MDANSE/Framework/Configurators/OutputTrajectoryConfigurator.py index 4488affba2..e3040f06ad 100644 --- a/MDANSE/Src/MDANSE/Framework/Configurators/OutputTrajectoryConfigurator.py +++ b/MDANSE/Src/MDANSE/Framework/Configurators/OutputTrajectoryConfigurator.py @@ -94,7 +94,7 @@ def configure(self, value: tuple): self["extension"] = IFormat.create(self._format).extension temp_name = root if self["extension"] != root.suffix: # capture most extension lengths - temp_name = temp_name.with_suffix(temp_name.suffix + self["extension"]) + temp_name = root.with_suffix(root.suffix + self["extension"]) self["file"] = temp_name if self["file"].absolute() in self._forbidden_files: diff --git a/MDANSE/Src/MDANSE/Framework/Configurators/PartialChargeConfigurator.py b/MDANSE/Src/MDANSE/Framework/Configurators/PartialChargeConfigurator.py index 5222728afb..a85bd46a9e 100644 --- a/MDANSE/Src/MDANSE/Framework/Configurators/PartialChargeConfigurator.py +++ b/MDANSE/Src/MDANSE/Framework/Configurators/PartialChargeConfigurator.py @@ -40,7 +40,7 @@ def __init__(self, trajectory: Trajectory) -> None: for at_num, at in enumerate(system.atom_list): try: self._original_map[at_num] = charges[at_num] - except: + except Exception: self._original_map[at_num] = 0.0 self._new_map = {} diff --git a/MDANSE/Src/MDANSE/Framework/Configurators/ProjectionConfigurator.py b/MDANSE/Src/MDANSE/Framework/Configurators/ProjectionConfigurator.py index 2c43de6d86..9c30229a49 100644 --- a/MDANSE/Src/MDANSE/Framework/Configurators/ProjectionConfigurator.py +++ b/MDANSE/Src/MDANSE/Framework/Configurators/ProjectionConfigurator.py @@ -73,7 +73,7 @@ def configure(self, value): return else: if np.allclose(vector, 0): - self.error_status = f"Vector of 0 length does not define projection" + self.error_status = "Vector of 0 length does not define projection" return try: self["projector"].set_axis(vector) diff --git a/MDANSE/Src/MDANSE/Framework/Configurators/QVectorsConfigurator.py b/MDANSE/Src/MDANSE/Framework/Configurators/QVectorsConfigurator.py index 0434425c51..a9fde6687e 100644 --- a/MDANSE/Src/MDANSE/Framework/Configurators/QVectorsConfigurator.py +++ b/MDANSE/Src/MDANSE/Framework/Configurators/QVectorsConfigurator.py @@ -67,13 +67,13 @@ def configure(self, value): ) try: generator.setup(parameters) - except: + except Exception: self.error_status = f"Could not configure q vectors using {parameters}" return try: generator_success = generator.generate() - except: + except Exception: self.error_status = "Q Vector parameters were parsed correctly, but caused an error. Invalid values?" return else: @@ -81,7 +81,7 @@ def configure(self, value): self.error_status = "Q Vector parameters were parsed correctly, but caused an error. Invalid values?" return - if not "q_vectors" in generator.configuration: + if "q_vectors" not in generator.configuration: self.error_status = "Wrong inputs for q-vector generation. At the moment there are no valid Q points." return elif not generator.configuration["q_vectors"]: diff --git a/MDANSE/Src/MDANSE/Framework/Configurators/RangeConfigurator.py b/MDANSE/Src/MDANSE/Framework/Configurators/RangeConfigurator.py index 11c00d616a..477524ac49 100644 --- a/MDANSE/Src/MDANSE/Framework/Configurators/RangeConfigurator.py +++ b/MDANSE/Src/MDANSE/Framework/Configurators/RangeConfigurator.py @@ -19,7 +19,6 @@ from MDANSE.Framework.Configurators.IConfigurator import ( IConfigurator, - ConfiguratorError, ) diff --git a/MDANSE/Src/MDANSE/Framework/Configurators/RunningModeConfigurator.py b/MDANSE/Src/MDANSE/Framework/Configurators/RunningModeConfigurator.py index 068bec5632..8527386db3 100644 --- a/MDANSE/Src/MDANSE/Framework/Configurators/RunningModeConfigurator.py +++ b/MDANSE/Src/MDANSE/Framework/Configurators/RunningModeConfigurator.py @@ -45,7 +45,7 @@ def configure(self, value): else: mode = value[0].lower() - if not mode in self.availablesModes: + if mode not in self.availablesModes: self.error_status = f"{mode} is not a valid running mode." return diff --git a/MDANSE/Src/MDANSE/Framework/Configurators/SingleChoiceConfigurator.py b/MDANSE/Src/MDANSE/Framework/Configurators/SingleChoiceConfigurator.py index d651d3f6a1..e0258eb20e 100644 --- a/MDANSE/Src/MDANSE/Framework/Configurators/SingleChoiceConfigurator.py +++ b/MDANSE/Src/MDANSE/Framework/Configurators/SingleChoiceConfigurator.py @@ -17,7 +17,6 @@ from MDANSE.Framework.Configurators.IConfigurator import ( IConfigurator, - ConfiguratorError, ) diff --git a/MDANSE/Src/MDANSE/Framework/Configurators/SingleOutputFileConfigurator.py b/MDANSE/Src/MDANSE/Framework/Configurators/SingleOutputFileConfigurator.py index adf63c6fc7..578e9ad8d6 100644 --- a/MDANSE/Src/MDANSE/Framework/Configurators/SingleOutputFileConfigurator.py +++ b/MDANSE/Src/MDANSE/Framework/Configurators/SingleOutputFileConfigurator.py @@ -74,7 +74,7 @@ def configure(self, value: Tuple[str, str]): try: PLATFORM.create_directory(dirname) - except: + except Exception: self.error_status = f"the directory {dirname} is not writable" return @@ -97,7 +97,7 @@ def configure(self, value: Tuple[str, str]): self["extension"] = IFormat.create(format).extension temp_name = root if self["extension"] != root.suffix: - temp_name = temp_name.with_suffix(temp_name.suffix + self["extension"]) + temp_name = root.with_suffix(root.suffix + self["extension"]) self["file"] = temp_name self.error_status = "OK" diff --git a/MDANSE/Src/MDANSE/Framework/Configurators/UnitCellConfigurator.py b/MDANSE/Src/MDANSE/Framework/Configurators/UnitCellConfigurator.py index d2be900d67..2830bcf450 100644 --- a/MDANSE/Src/MDANSE/Framework/Configurators/UnitCellConfigurator.py +++ b/MDANSE/Src/MDANSE/Framework/Configurators/UnitCellConfigurator.py @@ -18,7 +18,6 @@ from MDANSE.MLogging import LOG from MDANSE.Framework.Configurators.IConfigurator import IConfigurator -from MDANSE.Mathematics.LinearAlgebra import Vector class UnitCellConfigurator(IConfigurator): @@ -56,7 +55,7 @@ def update_trajectory_information(self): try: first_cell = traj_config.unit_cell(0)._unit_cell last_cell = traj_config.unit_cell(len(traj_config) - 1)._unit_cell - except: + except Exception: has_valid_cell = False else: if first_cell is None: @@ -98,7 +97,7 @@ def configure(self, value): try: input_array = np.array(value[0], dtype=float) - except: + except Exception: self.error_status = ( "Could not convert the inputs into a floating point array" ) diff --git a/MDANSE/Src/MDANSE/Framework/Converters/ASE.py b/MDANSE/Src/MDANSE/Framework/Converters/ASE.py index bef661b957..b0aa8dd408 100644 --- a/MDANSE/Src/MDANSE/Framework/Converters/ASE.py +++ b/MDANSE/Src/MDANSE/Framework/Converters/ASE.py @@ -14,13 +14,10 @@ # along with this program. If not, see . # import collections -import os from ase.io import iread, read -from ase.atoms import Atoms as ASEAtoms from ase.io.trajectory import Trajectory as ASETrajectory import numpy as np -import h5py from MDANSE.Framework.AtomMapping import get_element_from_mapping from MDANSE.Chemistry.ChemicalSystem import ChemicalSystem @@ -221,7 +218,7 @@ def run_step(self, index): except KeyError: try: charges = frame.get_initial_charges() - except: + except Exception: pass else: self._trajectory.write_charges(charges, index) @@ -257,7 +254,7 @@ def finalize(self): def parse_first_step(self, mapping): try: self._input = ASETrajectory(self.configuration["trajectory_file"]["value"]) - except: + except Exception: first_frame = read(self.configuration["trajectory_file"]["value"], index=0) last_iterator = 0 generator = iread(self.configuration["trajectory_file"]["value"]) diff --git a/MDANSE/Src/MDANSE/Framework/Converters/Converter.py b/MDANSE/Src/MDANSE/Framework/Converters/Converter.py index c291fc7c4f..ba728b2e12 100644 --- a/MDANSE/Src/MDANSE/Framework/Converters/Converter.py +++ b/MDANSE/Src/MDANSE/Framework/Converters/Converter.py @@ -60,7 +60,7 @@ def finalize(self): try: output_file = h5py.File(self.configuration["output_files"]["file"], "a") # f = netCDF4.Dataset(self._trajectory.filename,'a') - except: + except Exception: LOG.warning("Skipping the finalize call in Converter") return diff --git a/MDANSE/Src/MDANSE/Framework/Converters/ImprovedASE.py b/MDANSE/Src/MDANSE/Framework/Converters/ImprovedASE.py index 1b87541144..2f1d1678b3 100644 --- a/MDANSE/Src/MDANSE/Framework/Converters/ImprovedASE.py +++ b/MDANSE/Src/MDANSE/Framework/Converters/ImprovedASE.py @@ -204,7 +204,7 @@ def finalize(self): self._input.close() try: self._extra_input.close() - except: + except Exception: pass # Close the output trajectory. self._trajectory.write_standard_atom_database() @@ -218,13 +218,13 @@ def extract_initial_information(self, ase_object): if self._fractionalCoordinates is None: try: self._fractionalCoordinates = np.all(ase_object.get_pbc()) - except: + except Exception: pass if self._masses is None: try: self._masses = ase_object.get_masses() - except: + except Exception: pass if self.configuration["elements_from_mass"]["value"]: @@ -236,7 +236,7 @@ def extract_initial_information(self, ase_object): else: try: element_list = ase_object.get_chemical_symbols() - except: + except Exception: pass if element_list is None: return @@ -256,7 +256,7 @@ def parse_optional_config(self): ) except FileNotFoundError: return - except: + except Exception: for file_format in self.configuration[ "configuration_file" ]._allowed_formats: @@ -265,7 +265,7 @@ def parse_optional_config(self): self.configuration["configuration_file"]["value"], format=file_format, ) - except: + except Exception: continue else: break @@ -276,7 +276,7 @@ def parse_first_step(self): self.parse_optional_config() try: self._input = ASETrajectory(self.configuration["trajectory_file"]["value"]) - except: + except Exception: self._input = iread( self.configuration["trajectory_file"]["value"], index="[:]", diff --git a/MDANSE/Src/MDANSE/Framework/Converters/LAMMPS.py b/MDANSE/Src/MDANSE/Framework/Converters/LAMMPS.py index b36f591d81..06557f1713 100644 --- a/MDANSE/Src/MDANSE/Framework/Converters/LAMMPS.py +++ b/MDANSE/Src/MDANSE/Framework/Converters/LAMMPS.py @@ -51,7 +51,7 @@ def __init__(self, *args, **kwargs): def close(self): try: self._file.close() - except: + except Exception: LOG.error(f"Could not close file: {self._file}") def set_output(self, output_trajectory): @@ -562,7 +562,7 @@ def parse_first_step(self, aliases, config): ) try: self._charges_fixed = self._file["/particles/all/charge"][:] - except: + except Exception: pass full_cell *= measure(1.0, self._length_unit).toval("nm") @@ -632,7 +632,7 @@ def run_step(self, index): if self._charges_fixed is None: try: charge = self._file["/particles/all/charge/value"][index] - except: + except Exception: pass else: self._trajectory.write_charges( diff --git a/MDANSE/Src/MDANSE/Framework/Handlers/ColorizingStreamHandler.py b/MDANSE/Src/MDANSE/Framework/Handlers/ColorizingStreamHandler.py index 237bc46c31..ab3459ed7a 100644 --- a/MDANSE/Src/MDANSE/Framework/Handlers/ColorizingStreamHandler.py +++ b/MDANSE/Src/MDANSE/Framework/Handlers/ColorizingStreamHandler.py @@ -97,7 +97,7 @@ def emit(self, record): self.flush() except (KeyboardInterrupt, SystemExit): raise - except: + except Exception: self.handleError(record) if os.name != "nt": diff --git a/MDANSE/Src/MDANSE/Framework/InputData/HDFTrajectoryInputData.py b/MDANSE/Src/MDANSE/Framework/InputData/HDFTrajectoryInputData.py index c99672f784..fa10a77c2a 100644 --- a/MDANSE/Src/MDANSE/Framework/InputData/HDFTrajectoryInputData.py +++ b/MDANSE/Src/MDANSE/Framework/InputData/HDFTrajectoryInputData.py @@ -46,7 +46,7 @@ def info(self): val = [] try: time_axis = self._data.time() - except: + except Exception: timeline = "No time information!\n" else: if len(time_axis) < 1: @@ -64,7 +64,7 @@ def info(self): 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") - except: + except Exception: val.append("No unit cell information\n") val.append("Frame times (1st, 2nd, ..., last) in ps:") val.append(timeline) @@ -101,7 +101,7 @@ def check_metadata(self): def put_into_dict(name, obj): try: string = obj[:][0].decode() - except: + except Exception: LOG.debug(f"Decode failed for {name}: {obj}") else: try: diff --git a/MDANSE/Src/MDANSE/Framework/Jobs/AreaPerMolecule.py b/MDANSE/Src/MDANSE/Framework/Jobs/AreaPerMolecule.py index 2c19d0ba58..f507a4b399 100644 --- a/MDANSE/Src/MDANSE/Framework/Jobs/AreaPerMolecule.py +++ b/MDANSE/Src/MDANSE/Framework/Jobs/AreaPerMolecule.py @@ -141,7 +141,7 @@ def run_step(self, index): normalVect = np.cross( unit_cell[self._axisIndexes[0]], unit_cell[self._axisIndexes[1]] ) - except: + except Exception: raise AreaPerMoleculeError( "The unit cell must be defined for AreaPerMolecule. " "You can add a box using TrajectoryEditor." diff --git a/MDANSE/Src/MDANSE/Framework/Jobs/AverageStructure.py b/MDANSE/Src/MDANSE/Framework/Jobs/AverageStructure.py index f30e5ebdcd..32821eddff 100644 --- a/MDANSE/Src/MDANSE/Framework/Jobs/AverageStructure.py +++ b/MDANSE/Src/MDANSE/Framework/Jobs/AverageStructure.py @@ -109,7 +109,7 @@ def initialize(self): unit_cells = [ trajectory.unit_cell(frame)._unit_cell for frame in frame_range ] - except: + except Exception: raise ValueError( "Unit cell needs to be defined for the AverageStructure analysis. " "You can add a unit cell using TrajectoryEditor." @@ -166,13 +166,13 @@ def finalize(self): Finalizes the calculations (e.g. averaging the total term, output files creations ...). """ - trajectory = self.configuration["trajectory"]["instance"] + # trajectory = self.configuration["trajectory"]["instance"] - frame_range = range( - self.configuration["frames"]["first"], - self.configuration["frames"]["last"] + 1, - self.configuration["frames"]["step"], - ) + # frame_range = range( + # self.configuration["frames"]["first"], + # self.configuration["frames"]["last"] + 1, + # self.configuration["frames"]["step"], + # ) average_unit_cell = np.mean(self._unit_cells, axis=0) * self._conversion_factor diff --git a/MDANSE/Src/MDANSE/Framework/Jobs/Density.py b/MDANSE/Src/MDANSE/Framework/Jobs/Density.py index ac97da0fb0..e092d911d9 100644 --- a/MDANSE/Src/MDANSE/Framework/Jobs/Density.py +++ b/MDANSE/Src/MDANSE/Framework/Jobs/Density.py @@ -124,7 +124,7 @@ def run_step(self, index): try: cell_volume = conf.unit_cell.volume * measure(1.0, "nm3").toval("cm3") - except: + except Exception: raise DensityError( "Density cannot be computed for chemical system without a defined simulation box. " "You can add a box using TrajectoryEditor." diff --git a/MDANSE/Src/MDANSE/Framework/Jobs/DensityProfile.py b/MDANSE/Src/MDANSE/Framework/Jobs/DensityProfile.py index fa7332aa86..3d37d45595 100644 --- a/MDANSE/Src/MDANSE/Framework/Jobs/DensityProfile.py +++ b/MDANSE/Src/MDANSE/Framework/Jobs/DensityProfile.py @@ -100,7 +100,7 @@ def initialize(self): try: axis = first_conf.unit_cell.direct[axis_index, :] - except: + except Exception: raise DensityProfileError( "Density profile cannot be computed without a simulation box. " "You can add a box using TrajectoryEditor." diff --git a/MDANSE/Src/MDANSE/Framework/Jobs/DistanceHistogram.py b/MDANSE/Src/MDANSE/Framework/Jobs/DistanceHistogram.py index f5ddb7577d..462be1c99d 100644 --- a/MDANSE/Src/MDANSE/Framework/Jobs/DistanceHistogram.py +++ b/MDANSE/Src/MDANSE/Framework/Jobs/DistanceHistogram.py @@ -178,7 +178,7 @@ def run_step(self, index): inverse_cell = conf.unit_cell.transposed_inverse cell_volume = conf.unit_cell.volume - except: + except Exception: self.detailed_unit_cell_error() else: if cell_volume < 1e-9: diff --git a/MDANSE/Src/MDANSE/Framework/Jobs/DynamicCoherentStructureFactor.py b/MDANSE/Src/MDANSE/Framework/Jobs/DynamicCoherentStructureFactor.py index 1feeadcf97..a88a5b58d8 100644 --- a/MDANSE/Src/MDANSE/Framework/Jobs/DynamicCoherentStructureFactor.py +++ b/MDANSE/Src/MDANSE/Framework/Jobs/DynamicCoherentStructureFactor.py @@ -195,7 +195,7 @@ def run_step(self, index): shell = self.configuration["q_vectors"]["shells"][index] - if not shell in self.configuration["q_vectors"]["value"]: + if shell not in self.configuration["q_vectors"]["value"]: return index, None else: diff --git a/MDANSE/Src/MDANSE/Framework/Jobs/ElasticIncoherentStructureFactor.py b/MDANSE/Src/MDANSE/Framework/Jobs/ElasticIncoherentStructureFactor.py index face85b9aa..750c6eabd7 100644 --- a/MDANSE/Src/MDANSE/Framework/Jobs/ElasticIncoherentStructureFactor.py +++ b/MDANSE/Src/MDANSE/Framework/Jobs/ElasticIncoherentStructureFactor.py @@ -164,7 +164,7 @@ def run_step(self, index): atomicEISF = np.zeros((self._nQShells,), dtype=np.float64) for i, q in enumerate(self.configuration["q_vectors"]["shells"]): - if not q in self.configuration["q_vectors"]["value"]: + if q not in self.configuration["q_vectors"]["value"]: continue qVectors = self.configuration["q_vectors"]["value"][q]["q_vectors"] diff --git a/MDANSE/Src/MDANSE/Framework/Jobs/GeneralAutoCorrelationFunction.py b/MDANSE/Src/MDANSE/Framework/Jobs/GeneralAutoCorrelationFunction.py index be158c6dab..615693c85d 100644 --- a/MDANSE/Src/MDANSE/Framework/Jobs/GeneralAutoCorrelationFunction.py +++ b/MDANSE/Src/MDANSE/Framework/Jobs/GeneralAutoCorrelationFunction.py @@ -165,7 +165,7 @@ def finalize(self): if self.configuration["normalize"]["value"]: for element in nAtomsPerElement.keys(): - if self._outputData[f"gacf_{element}}}"][0] == 0: + if self._outputData[f"gacf_{element}"][0] == 0: raise ValueError("The normalization factor is equal to zero") else: self._outputData[f"gacf_{element}"] = normalize( diff --git a/MDANSE/Src/MDANSE/Framework/Jobs/IJob.py b/MDANSE/Src/MDANSE/Framework/Jobs/IJob.py index b087e71744..e0fc7ba377 100644 --- a/MDANSE/Src/MDANSE/Framework/Jobs/IJob.py +++ b/MDANSE/Src/MDANSE/Framework/Jobs/IJob.py @@ -114,7 +114,7 @@ def define_unique_name(): # Followed by 4 random letters. name = key_generator(6, prefix=prefix) - if not name in registeredJobs: + if name not in registeredJobs: break return name @@ -413,7 +413,7 @@ def run(self, parameters, status=False): if self._status is not None: self._status.finish() - except: + except Exception: tb = traceback.format_exc() LOG.critical(f"Job failed with traceback: {tb}") raise JobError(self, tb) diff --git a/MDANSE/Src/MDANSE/Framework/Jobs/JobStatus.py b/MDANSE/Src/MDANSE/Framework/Jobs/JobStatus.py index 408f0f6d3f..27110c9d9f 100644 --- a/MDANSE/Src/MDANSE/Framework/Jobs/JobStatus.py +++ b/MDANSE/Src/MDANSE/Framework/Jobs/JobStatus.py @@ -15,9 +15,6 @@ # import collections -import pickle -import os -import threading import time from MDANSE import PLATFORM diff --git a/MDANSE/Src/MDANSE/Framework/Jobs/McStasVirtualInstrument.py b/MDANSE/Src/MDANSE/Framework/Jobs/McStasVirtualInstrument.py index 9cf8acae1b..97862c0d9c 100644 --- a/MDANSE/Src/MDANSE/Framework/Jobs/McStasVirtualInstrument.py +++ b/MDANSE/Src/MDANSE/Framework/Jobs/McStasVirtualInstrument.py @@ -20,6 +20,7 @@ import io from pathlib import Path from typing import Union +from functools import partial import numpy as np @@ -40,6 +41,10 @@ NAVOGADRO = 6.02214129e23 +def _startswith(key: str, line: str) -> bool: + return line.strip().startswith(key) + + class McStasError(Error): pass @@ -358,8 +363,8 @@ def convert(self, sim_dir: Union[Path, str]): if not sim_file: raise Exception(f"Dataset {sim_file} does not exist!") - isBegin = lambda line: line.strip().startswith("begin") - isCompFilename = lambda line: line.strip().startswith("filename:") + isBegin = partial(_startswith, "begin") + isCompFilename = partial(_startswith, "filename:") # First, determine if this is single or overview plot... SimFile = list(filter(isBegin, open(sim_file).readlines())) Datfile = 0 @@ -379,7 +384,7 @@ def convert(self, sim_dir: Union[Path, str]): if L == 0: """Scan view""" if Datfile == 0: - isFilename = lambda line: line.strip().startswith("filename") + isFilename = partial(_startswith, "filename") Scanfile = list(filter(isFilename, open(sim_file).readlines())) Scanfile = Scanfile[0].split(": ") @@ -437,9 +442,9 @@ def save_single(self, FileStruct): # 2D data set mysize = FileStruct["data"].shape - I = FileStruct["data"] - mysize = I.shape - I = I.T + data = FileStruct["data"] + mysize = data.shape + data = data.T Xmin = eval(FileStruct["xylimits"].split()[0]) Xmax = eval(FileStruct["xylimits"].split()[1]) @@ -464,7 +469,7 @@ def save_single(self, FileStruct): self._outputData.add( title, "SurfaceOutputVariable", - I, + data, axis=f"{xlabel}|{ylabel}", units="au", main_result=True, @@ -485,7 +490,7 @@ def read_monitor(self, simFile): """ # Read header - isHeader = lambda line: line.startswith("#") + isHeader = partial(_startswith, "#") f = open(simFile) Lines = f.readlines() Header = list(filter(isHeader, Lines)) @@ -514,8 +519,8 @@ def read_monitor(self, simFile): f.close() header = True - for l in lines: - if l.startswith("#"): + for line in lines: + if line.startswith("#"): if header: continue else: @@ -523,7 +528,7 @@ def read_monitor(self, simFile): else: if header: header = False - data.append(l) + data.append(line) Filestruct["data"] = np.genfromtxt(io.StringIO(" ".join(data))) Filestruct["fullpath"] = simFile diff --git a/MDANSE/Src/MDANSE/Framework/Jobs/OrderParameter.py b/MDANSE/Src/MDANSE/Framework/Jobs/OrderParameter.py index 135c01898f..80222fc001 100644 --- a/MDANSE/Src/MDANSE/Framework/Jobs/OrderParameter.py +++ b/MDANSE/Src/MDANSE/Framework/Jobs/OrderParameter.py @@ -15,7 +15,6 @@ # import collections -import os import numpy as np diff --git a/MDANSE/Src/MDANSE/Framework/Jobs/RigidBodyTrajectory.py b/MDANSE/Src/MDANSE/Framework/Jobs/RigidBodyTrajectory.py index ba4e25af63..2de79cee9b 100644 --- a/MDANSE/Src/MDANSE/Framework/Jobs/RigidBodyTrajectory.py +++ b/MDANSE/Src/MDANSE/Framework/Jobs/RigidBodyTrajectory.py @@ -20,8 +20,8 @@ import h5py -from MDANSE.Mathematics.Geometry import center_of_mass from MDANSE.Framework.Jobs.IJob import IJob, JobError +from MDANSE.Mathematics.Geometry import center_of_mass from MDANSE.Mathematics.LinearAlgebra import Quaternion, Vector from MDANSE.Mathematics.Transformation import Translation from MDANSE.MolecularDynamics.Configuration import RealConfiguration diff --git a/MDANSE/Src/MDANSE/Framework/Jobs/StaticStructureFactor.py b/MDANSE/Src/MDANSE/Framework/Jobs/StaticStructureFactor.py index 9b0321681e..891ae9fedd 100644 --- a/MDANSE/Src/MDANSE/Framework/Jobs/StaticStructureFactor.py +++ b/MDANSE/Src/MDANSE/Framework/Jobs/StaticStructureFactor.py @@ -95,7 +95,7 @@ def initialize(self): conf = self.configuration["trajectory"]["instance"].configuration(frame_index) try: cell_volume = conf.unit_cell.volume - except: + except Exception: raise ValueError( "Static Structure Factor cannot be computed for chemical system without a defined simulation box. " "You can add a box using TrajectoryEditor." diff --git a/MDANSE/Src/MDANSE/Framework/Jobs/VanHoveFunctionDistinct.py b/MDANSE/Src/MDANSE/Framework/Jobs/VanHoveFunctionDistinct.py index a0aa77df39..93d281e043 100644 --- a/MDANSE/Src/MDANSE/Framework/Jobs/VanHoveFunctionDistinct.py +++ b/MDANSE/Src/MDANSE/Framework/Jobs/VanHoveFunctionDistinct.py @@ -274,7 +274,7 @@ def initialize(self): ) try: cell_volume = conf.unit_cell.volume - except: + except Exception: self.detailed_unit_cell_error() else: if cell_volume < 1e-9: @@ -480,11 +480,11 @@ def finalize(self): van_hove_inter = self.h_inter[idi, idj, ...] / fact[:, np.newaxis] van_hove_total = van_hove_intra + van_hove_inter - for i, van_hove in zip( + for i, van_h in zip( ["intra", "inter", "total"], [van_hove_intra, van_hove_inter, van_hove_total], ): - self._outputData[f"g(r,t)_{i}_{pair[0]}{pair[1]}"][...] = van_hove + self._outputData[f"g(r,t)_{i}_{''.join(pair)}"][...] = van_h weights = self.configuration["weights"].get_weights() for i in ["_intra", "_inter", ""]: diff --git a/MDANSE/Src/MDANSE/Framework/Jobs/VanHoveFunctionSelf.py b/MDANSE/Src/MDANSE/Framework/Jobs/VanHoveFunctionSelf.py index 9d7b0749ad..6abb58a1b2 100644 --- a/MDANSE/Src/MDANSE/Framework/Jobs/VanHoveFunctionSelf.py +++ b/MDANSE/Src/MDANSE/Framework/Jobs/VanHoveFunctionSelf.py @@ -148,7 +148,7 @@ def initialize(self): ) try: cell_volume = conf.unit_cell.volume - except: + except Exception: self.detailed_unit_cell_error() else: if cell_volume < 1e-9: diff --git a/MDANSE/Src/MDANSE/Framework/Jobs/Voronoi.py b/MDANSE/Src/MDANSE/Framework/Jobs/Voronoi.py index 19dde6be18..bca7c95751 100644 --- a/MDANSE/Src/MDANSE/Framework/Jobs/Voronoi.py +++ b/MDANSE/Src/MDANSE/Framework/Jobs/Voronoi.py @@ -110,7 +110,7 @@ def initialize(self): self.cell_param = np.array( [cell[0, 0], cell[1, 1], cell[2, 2]], dtype=np.float64 ) - except: + except Exception: raise VoronoiError( "Voronoi analysis cannot be computed if simulation box is not defined. " "You can add a box using TrajectoryEditor." diff --git a/MDANSE/Src/MDANSE/Framework/Jobs/XRayStaticStructureFactor.py b/MDANSE/Src/MDANSE/Framework/Jobs/XRayStaticStructureFactor.py index 3e14db0c6e..2efef2951d 100644 --- a/MDANSE/Src/MDANSE/Framework/Jobs/XRayStaticStructureFactor.py +++ b/MDANSE/Src/MDANSE/Framework/Jobs/XRayStaticStructureFactor.py @@ -210,12 +210,12 @@ def finalize(self): ) xssfIntra = weight( - asf, self._outputData, nAtomsPerElement, 2, f"xssf_intra_%s%s" + asf, self._outputData, nAtomsPerElement, 2, "xssf_intra_%s%s" ) self._outputData["xssf_intra"][:] = xssfIntra xssfInter = weight( - asf, self._outputData, nAtomsPerElement, 2, f"xssf_inter_%s%s" + asf, self._outputData, nAtomsPerElement, 2, "xssf_inter_%s%s" ) self._outputData["xssf_inter"][:] = xssfInter diff --git a/MDANSE/Src/MDANSE/Framework/QVectors/IQVectors.py b/MDANSE/Src/MDANSE/Framework/QVectors/IQVectors.py index 573c1be92e..b3fadad0ee 100644 --- a/MDANSE/Src/MDANSE/Framework/QVectors/IQVectors.py +++ b/MDANSE/Src/MDANSE/Framework/QVectors/IQVectors.py @@ -48,7 +48,7 @@ def generate(self) -> bool: return True else: LOG.error( - f"Cannot generate vectors: q vector generator is not configured correctly." + "Cannot generate vectors: q vector generator is not configured correctly." ) return False diff --git a/MDANSE/Src/MDANSE/Framework/Session/CurrentSession.py b/MDANSE/Src/MDANSE/Framework/Session/CurrentSession.py index 74619200a0..3864cd286e 100644 --- a/MDANSE/Src/MDANSE/Framework/Session/CurrentSession.py +++ b/MDANSE/Src/MDANSE/Framework/Session/CurrentSession.py @@ -52,4 +52,4 @@ def __init__(self, fname=None): def loadSettings(self, fname=None): if fname is not None: - source = json.load(fname) + json.load(fname) diff --git a/MDANSE/Src/MDANSE/Framework/Units.py b/MDANSE/Src/MDANSE/Framework/Units.py index 5083435d2f..c97e355889 100644 --- a/MDANSE/Src/MDANSE/Framework/Units.py +++ b/MDANSE/Src/MDANSE/Framework/Units.py @@ -710,7 +710,7 @@ def load(self): try: with open(UnitsManager._USER_DATABASE, "r") as fin: d.update(json.load(fin)) - except: + except Exception: self.save() finally: for uname, udict in list(d.items()): diff --git a/MDANSE/Src/MDANSE/IO/FortranFormat.py b/MDANSE/Src/MDANSE/IO/FortranFormat.py index 40943035e5..350b0c6fb3 100644 --- a/MDANSE/Src/MDANSE/IO/FortranFormat.py +++ b/MDANSE/Src/MDANSE/IO/FortranFormat.py @@ -92,13 +92,13 @@ def __init__(self, line, format, length=80): extended by spaces to have the indicated length. The default value of 80 is almost always correct. """ - if type(line) == type(""): + if isinstance(line, str): self.text = line self.data = None else: self.text = None self.data = line - if type(format) == type(""): + if isinstance(format, str): self.format = FortranFormat(format) else: self.format = format @@ -153,9 +153,9 @@ def _input(self): text = text + (self.length - len(text)) * " " self.data = [] for field in self.format: - l = field[1] - s = text[:l] - text = text[l:] + w = field[1] + s = text[:w] + text = text[w:] type = field[0] value = None if type == "A": @@ -171,7 +171,7 @@ def _input(self): # catch this and set value to None try: value = int(s) - except: + except Exception: value = None elif type == "D" or type == "E" or type == "F" or type == "G": s = s.strip().lower() @@ -183,7 +183,7 @@ def _input(self): else: try: value = float(s) - except: + except Exception: value = None if value is not None: self.data.append(value) @@ -206,7 +206,7 @@ def _output(self): if type == "A": try: self.text = self.text + (value + length * " ")[:length] - except: + except Exception: LOG.warning(self.text) LOG.warning(value) LOG.warning(length) @@ -319,8 +319,8 @@ def __getitem__(self, i): if __name__ == "__main__": f = FortranFormat("'!!',D10.3,F10.3,G10.3,'!!'") - l = FortranLine([1.5707963, 3.14159265358, 2.71828], f) - print(str(l)) + w = FortranLine([1.5707963, 3.14159265358, 2.71828], f) + print(str(w)) f = FortranFormat("F12.0") - l = FortranLine("2.1D2", f) - print(l[0]) + w = FortranLine("2.1D2", f) + print(w[0]) diff --git a/MDANSE/Src/MDANSE/IO/MinimalPDBReader.py b/MDANSE/Src/MDANSE/IO/MinimalPDBReader.py index afb0b28d17..0baab13af8 100644 --- a/MDANSE/Src/MDANSE/IO/MinimalPDBReader.py +++ b/MDANSE/Src/MDANSE/IO/MinimalPDBReader.py @@ -69,7 +69,7 @@ def __init__(self, filename: str): try: ase_atoms = ase_read(filename, format="pdb", index=0) cell = ase_atoms.get_cell() - except: + except Exception: self.periodic = False else: self.periodic = True diff --git a/MDANSE/Src/MDANSE/IO/TextFile.py b/MDANSE/Src/MDANSE/IO/TextFile.py index 6892a2d0d9..737ae0f8c5 100644 --- a/MDANSE/Src/MDANSE/IO/TextFile.py +++ b/MDANSE/Src/MDANSE/IO/TextFile.py @@ -21,18 +21,17 @@ import os import sys from pathlib import Path +from contextlib import suppress # Use the gzip module for Python version 1.5.2 or higher -try: - _version = [int(c) for c in sys.version.split()[0].split(".")] - - if _version >= [1, 5, 2]: +with suppress(Exception): + if sys.version_info >= (1, 5, 2): try: import gzip except ImportError: gzip = None -except: - gzip = None + else: + gzip = None class TextFile: diff --git a/MDANSE/Src/MDANSE/Mathematics/LinearAlgebra.py b/MDANSE/Src/MDANSE/Mathematics/LinearAlgebra.py index 6a76995f76..1f6ab71164 100644 --- a/MDANSE/Src/MDANSE/Mathematics/LinearAlgebra.py +++ b/MDANSE/Src/MDANSE/Mathematics/LinearAlgebra.py @@ -488,7 +488,7 @@ def __len__(self): def __getitem__(self, index): elements = self.array[index] - if type(elements) == type(self.array): + if type(elements) is type(self.array): return Tensor(elements) else: return elements diff --git a/MDANSE/Src/MDANSE/Mathematics/Transformation.py b/MDANSE/Src/MDANSE/Mathematics/Transformation.py index 4caed8011f..b2ed7a06a7 100644 --- a/MDANSE/Src/MDANSE/Mathematics/Transformation.py +++ b/MDANSE/Src/MDANSE/Mathematics/Transformation.py @@ -161,11 +161,11 @@ def inverse(self): return Translation(-self.vector) def screwMotion(self): - l = self.vector.length() - if l == 0.0: + length = self.vector.length() + if length == 0.0: return Vector(0.0, 0.0, 0.0), Vector(0.0, 0.0, 1.0), 0.0, 0.0 else: - return Vector(0.0, 0.0, 0.0), self.vector / l, 0.0, l + return Vector(0.0, 0.0, 0.0), self.vector / length, 0.0, length # diff --git a/MDANSE/Src/MDANSE/MolecularDynamics/Trajectory.py b/MDANSE/Src/MDANSE/MolecularDynamics/Trajectory.py index 9cc8a5b725..4b6772b9e7 100644 --- a/MDANSE/Src/MDANSE/MolecularDynamics/Trajectory.py +++ b/MDANSE/Src/MDANSE/MolecularDynamics/Trajectory.py @@ -149,7 +149,7 @@ def unit_cell(self, frame): return self._trajectory.unit_cell(frame) - def calculate_coordinate_span(self) -> np.ndarray: + def calculate_coordinate_span(self) -> None: min_span = np.array(3 * [1e11]) max_span = np.zeros(3) for frame in range(len(self)): @@ -873,9 +873,10 @@ def __init__( r = r - rcms r = r[:, np.newaxis, :] - r = fold_coordinates.fold_coordinates( - r, unit_cells, inverse_unit_cells, True - ) + # Fold coordinates doesn't exist? + # r = fold_coordinates.fold_coordinates( + # r, unit_cells, inverse_unit_cells, True + # ) r = np.squeeze(r) r = self._trajectory.to_real_coordinates(r, first, last, step) @@ -959,9 +960,9 @@ def read_atoms_trajectory( if last is None: last = len(trajectory) - nFrames = len(list(range(first, last, step))) + # nFrames = len(range(first, last, step)) - serie = np.zeros((nFrames, 3), dtype=dtype) + # serie = np.zeros((nFrames, 3), dtype=dtype) if weights is None or len(atoms) == 1: weights = [1.0] * len(atoms) diff --git a/MDANSE/Src/MDANSE/Scripts/mdanse.py b/MDANSE/Src/MDANSE/Scripts/mdanse.py index 7f7b5d5ee6..d77b09b30d 100644 --- a/MDANSE/Src/MDANSE/Scripts/mdanse.py +++ b/MDANSE/Src/MDANSE/Scripts/mdanse.py @@ -131,7 +131,7 @@ def check_job(self, option, opt_str, value, parser): f.close() # If the file could not be opened/unpickled for whatever reason, try at the next checkpoint - except: + except Exception: raise CommandLineParserError( f"The job {basename!r} could not be opened properly." ) @@ -193,7 +193,7 @@ def display_jobs_list(self, option, opt_str, value, parser): info = pickle.load(f) # If the file could not be opened/unpickled for whatever reason, try at the next checkpoint - except: + except Exception: continue # The job file could be opened and unpickled properly @@ -364,7 +364,7 @@ def save_job_template(self, option, opt_str, value, parser): try: IJob.save_template(shortname, classname) - except (IOError, KeyError) as e: + except (IOError, KeyError): return diff --git a/MDANSE/Src/MDANSE/Trajectory/H5MDTrajectory.py b/MDANSE/Src/MDANSE/Trajectory/H5MDTrajectory.py index 241245aa52..a0695f067a 100644 --- a/MDANSE/Src/MDANSE/Trajectory/H5MDTrajectory.py +++ b/MDANSE/Src/MDANSE/Trajectory/H5MDTrajectory.py @@ -70,7 +70,7 @@ def __init__(self, h5_filename: Union[Path, str]): coords = self._h5_file["/particles/all/position/value"][0, :, :] try: pos_unit = self._h5_file["/particles/all/position/value"].attrs["unit"] - except: + except Exception: conv_factor = 1.0 else: if pos_unit == "Ang": @@ -85,12 +85,12 @@ def file_is_right(self, filename): result = True try: temp = h5py.File(filename) - except FileNotFoundError: + except Exception: result = False else: try: temp["h5md"] - except KeyError: + except Exception: result = False return result @@ -111,26 +111,24 @@ def __getitem__(self, frame): grp = self._h5_file["/particles/all/position/value"] try: - pos_unit = self._h5_file["/particles/all/position/value"].attrs["unit"] - except: + pos_unit = grp.attrs["unit"] + except Exception: conv_factor = 1.0 else: if pos_unit == "Ang": pos_unit = "ang" conv_factor = measure(1.0, pos_unit).toval("nm") configuration = {} - configuration["coordinates"] = ( - self._h5_file["/particles/all/position/value"][frame, :, :] * conv_factor - ) + configuration["coordinates"] = grp[frame, :, :] * conv_factor try: try: vel_unit = self._h5_file["/particles/all/velocity/value"].attrs["unit"] - except: + except Exception: vel_unit = "ang/fs" configuration["velocities"] = self._h5_file[ "/particles/all/velocity/value" ][frame, :, :] * measure(1.0, vel_unit).toval("nm/ps") - except: + except Exception: pass configuration["time"] = self.time()[frame] @@ -167,7 +165,7 @@ def charges(self, frame): except KeyError: LOG.debug(f"No charge information in trajectory {self._h5_filename}") charge = np.zeros(self._chemical_system.number_of_atoms) - except: + except Exception: try: charge = self._h5_file["/particles/all/charge"][:] except KeyError: @@ -190,7 +188,7 @@ def coordinates(self, frame): raise IndexError(f"Invalid frame number: {frame}") try: pos_unit = self._h5_file["/particles/all/position/value"].attrs["unit"] - except: + except Exception: conv_factor = 1.0 else: if pos_unit == "Ang": @@ -224,7 +222,7 @@ def configuration(self, frame): if k not in self._variables_to_skip: try: variables[k] = self.variable(k)[frame, :, :].astype(np.float64) - except: + except Exception: self._variables_to_skip.append(k) coordinates = self.coordinates(frame) @@ -243,7 +241,7 @@ def _load_unit_cells(self): self._unit_cells = [] try: box_unit = self._h5_file["/particles/all/box/edges/value"].attrs["unit"] - except: + except Exception: conv_factor = 1.0 else: if box_unit == "Ang": @@ -270,13 +268,13 @@ def _load_unit_cells(self): def time(self): try: time_unit = self._h5_file["/particles/all/position/time"].attrs["unit"] - except: + except Exception: conv_factor = 1.0 else: conv_factor = measure(1.0, time_unit).toval("ps") try: time = self._h5_file["/particles/all/position/time"] * conv_factor - except: + except Exception: time = [] return time @@ -366,7 +364,7 @@ def read_com_trajectory( grp = self._h5_file["/particles/all/position/value"] try: pos_unit = self._h5_file["/particles/all/position/value"].attrs["unit"] - except: + except Exception: conv_factor = 1.0 else: if pos_unit == "Ang": @@ -464,7 +462,7 @@ def read_atomic_trajectory( grp = self._h5_file["/particles/all/position/value"] try: pos_unit = self._h5_file["/particles/all/position/value"].attrs["unit"] - except: + except Exception: conv_factor = 1.0 else: if pos_unit == "Ang": diff --git a/MDANSE/Src/MDANSE/Trajectory/MdanseTrajectory.py b/MDANSE/Src/MDANSE/Trajectory/MdanseTrajectory.py index 431eb6fa6f..23e634de12 100644 --- a/MDANSE/Src/MDANSE/Trajectory/MdanseTrajectory.py +++ b/MDANSE/Src/MDANSE/Trajectory/MdanseTrajectory.py @@ -64,7 +64,7 @@ def file_is_right(self, filename: Union[Path, str]): result = True try: file_object = h5py.File(filename) - except FileNotFoundError: + except Exception: result = False else: try: diff --git a/MDANSE/pyproject.toml b/MDANSE/pyproject.toml index 95bc164b60..434f12b335 100644 --- a/MDANSE/pyproject.toml +++ b/MDANSE/pyproject.toml @@ -57,3 +57,50 @@ MDANSE = ["Chemistry/*.json", [project.scripts] mdanse = "MDANSE.Scripts.mdanse:main" + +[tool.ruff] +line-length = 100 +indent-width = 4 +target-version = "py39" +extend-exclude = [ + "Src/MDANSE/Framework/Jobs/RigidBodyTrajectory.py", + "Src/MDANSE/MolecularDynamics/Trajectory.py", +] + +[tool.ruff.lint] +select = [ + "E4", "E7", "E9", "F", # Defaults + # "PL", # Pylint errors + # "E", # Pycodestyle + # "W", # Pycodestyle warnings + # "F", # Pyflakes + # "B", # Flake8 bugbear + # "SIM", # Flake8 Simplify + # "A", # Flake8 builtins + # "COM", # Flake8 commas + # "ISC", # Flake8 implicit string concat + # "RSE", # Flake8 raise + # "FA", # Flake8 future + # "FBT", # Flake8 boolean trap + # "C4", # Flake8 comprehensions + # "Q", # Flake8 Quotes + # "RET", # Flake8 return + # "ARG", # Flake8 unused args + # "PTH", # Flake8 use pathlib + # "I", # Isort + # "RUF", # Ruff specific + # "FURB",# Refurb + # "PERF",# Perflint + # "D", # Pydocstyle + # "UP", # Pyupgrade +] +ignore = [ + "F401", # Unused import in init + "E402", # Import not at top + "PLR0913", # Too many arguments + "PLR0912", # Too many branches + "PLR0915", # Too many statements +] + +# [tool.setuptools.packages.find] +# where = ["src"]