diff --git a/.github/workflows/lint.yml b/.github/workflows/lint.yml index 0e314fde82..f26a6c1a1a 100644 --- a/.github/workflows/lint.yml +++ b/.github/workflows/lint.yml @@ -9,23 +9,22 @@ on: jobs: lint_format_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 format --check + steps: + - uses: actions/checkout@v4 + - uses: astral-sh/ruff-action@v3 + with: + src: "./MDANSE/Src" + args: "format --check" + - 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 diff --git a/MDANSE/Src/MDANSE/Core/Platform.py b/MDANSE/Src/MDANSE/Core/Platform.py index 9a0fb9d92e..8b3f0b771e 100644 --- a/MDANSE/Src/MDANSE/Core/Platform.py +++ b/MDANSE/Src/MDANSE/Core/Platform.py @@ -20,10 +20,9 @@ import getpass import inspect import os +import platform import re import subprocess -import tempfile - from MDANSE.Core.Error import Error @@ -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), @@ -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 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..4b9db97c55 100644 --- a/MDANSE/Src/MDANSE/Framework/AtomSelector/selector.py +++ b/MDANSE/Src/MDANSE/Framework/AtomSelector/selector.py @@ -13,15 +13,20 @@ # 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 bedb732b5d..d4343d4958 100644 --- a/MDANSE/Src/MDANSE/Framework/Configurable.py +++ b/MDANSE/Src/MDANSE/Framework/Configurable.py @@ -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 @@ -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): 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 ecefe18fee..4551bb60e1 100644 --- a/MDANSE/Src/MDANSE/Framework/Configurators/AseInputFileConfigurator.py +++ b/MDANSE/Src/MDANSE/Framework/Configurators/AseInputFileConfigurator.py @@ -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 @@ -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" diff --git a/MDANSE/Src/MDANSE/Framework/Configurators/BooleanConfigurator.py b/MDANSE/Src/MDANSE/Framework/Configurators/BooleanConfigurator.py index 6cbe4ce046..ba4a90750c 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 8a0b8eed2a..9c3034c9ce 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 5582ea5ade..7557a7d57a 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 c77ea5c795..185b060008 100644 --- a/MDANSE/Src/MDANSE/Framework/Configurators/IConfigurator.py +++ b/MDANSE/Src/MDANSE/Framework/Configurators/IConfigurator.py @@ -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 @@ -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 diff --git a/MDANSE/Src/MDANSE/Framework/Configurators/IntegerConfigurator.py b/MDANSE/Src/MDANSE/Framework/Configurators/IntegerConfigurator.py index d8ded23b8a..e9d18b307f 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 933ae97b4b..1d3c7574e8 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 59497623fb..ae1054d47f 100644 --- a/MDANSE/Src/MDANSE/Framework/Configurators/MultiInputFileConfigurator.py +++ b/MDANSE/Src/MDANSE/Framework/Configurators/MultiInputFileConfigurator.py @@ -55,7 +55,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: @@ -63,10 +63,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 640a9479b3..d3fede9d54 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 2fb3066f0e..3e5a10f0f9 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 194b4c555b..bb0b1c6bfc 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" ) @@ -132,7 +132,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 24c7b16a71..94d03a3fe4 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 @@ -113,7 +113,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 c2bec2e22a..63a6d4244f 100644 --- a/MDANSE/Src/MDANSE/Framework/Configurators/OutputTrajectoryConfigurator.py +++ b/MDANSE/Src/MDANSE/Framework/Configurators/OutputTrajectoryConfigurator.py @@ -93,7 +93,7 @@ def configure(self, value: tuple): self["format"] = self._format self["extension"] = IFormat.create(self._format).extension temp_name = root - if not self["extension"] in temp_name[-5:]: # capture most extension lengths + if self["extension"] not in temp_name[-5:]: # capture most extension lengths temp_name += self["extension"] self["file"] = temp_name if PurePath(os.path.abspath(self["file"])) 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 1c9aa15747..c9801f22f2 100644 --- a/MDANSE/Src/MDANSE/Framework/Configurators/ProjectionConfigurator.py +++ b/MDANSE/Src/MDANSE/Framework/Configurators/ProjectionConfigurator.py @@ -33,8 +33,8 @@ class ProjectionConfigurator(IConfigurator): def configure(self, value): """ - Configure a projector. - + Configure a projector. + :param value: the input projector definition. It can be a 2-tuple whose 1st element if the name \ of the projector (one of *'null'*,*'axial'* or *'planar'*) and the 2nd element the parameters for the selected \ projector (None for *'null'*, a Scientific.Vector for *'axial'* and a list of two Scientific.Vector for *'planar'*) \ @@ -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 cd8a7c8ef0..66a5306570 100644 --- a/MDANSE/Src/MDANSE/Framework/Configurators/QVectorsConfigurator.py +++ b/MDANSE/Src/MDANSE/Framework/Configurators/QVectorsConfigurator.py @@ -45,8 +45,8 @@ class QVectorsConfigurator(IConfigurator): def configure(self, value): """ - Configure a Q vectors generator. - + Configure a Q vectors generator. + :param configuration: the current configuration. :type configuration: a MDANSE.Framework.Configurable.Configurable object :param value: the Q vectors generator definition. It can be a 2-tuple, whose 1st element is the name of the Q vector generator \ @@ -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 2edad306eb..ceb5f4b8f5 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 56fcc870ad..4e7a012581 100644 --- a/MDANSE/Src/MDANSE/Framework/Configurators/RunningModeConfigurator.py +++ b/MDANSE/Src/MDANSE/Framework/Configurators/RunningModeConfigurator.py @@ -33,7 +33,7 @@ class RunningModeConfigurator(IConfigurator): def configure(self, value): """ Configure the running mode. - + :param value: the running mode specification. It can be *'single-core'* or a 2-tuple whose first element \ must be *'multicore'* and 2nd element the number of slots allocated for running the analysis. :type value: *'single-core'* or 2-tuple @@ -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 e8264551fa..09872cb26b 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 872c7a5708..85cb56fe71 100644 --- a/MDANSE/Src/MDANSE/Framework/Configurators/SingleOutputFileConfigurator.py +++ b/MDANSE/Src/MDANSE/Framework/Configurators/SingleOutputFileConfigurator.py @@ -69,7 +69,7 @@ def configure(self, value): try: PLATFORM.create_directory(dirname) - except: + except Exception: self.error_status = f"the directory {dirname} is not writable" return @@ -91,7 +91,7 @@ def configure(self, value): self["format"] = format self["extension"] = IFormat.create(format).extension temp_name = root - if not self["extension"] in temp_name[-5:]: # capture most extension lengths + if self["extension"] not in temp_name[-5:]: # capture most extension lengths temp_name += 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 99b4ed13c2..6d65cb3571 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 e06e156f27..b50addc1dc 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 715213aa36..62cf3fef03 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: @@ -66,7 +66,7 @@ def info(self): val.append( "First unit cell (nm):\n{}\n".format(self._data.unit_cell(0)._unit_cell) ) - except: + except Exception: val.append("No unit cell information\n") val.append("Frame times (1st, 2nd, ..., last) in ps:") val.append(timeline) @@ -103,7 +103,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 dece49de23..0a0c85c002 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 d91602e680..5bf43c6479 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 5dae1d5302..4c823fb9e4 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 3482ee4ff4..c9287fd041 100644 --- a/MDANSE/Src/MDANSE/Framework/Jobs/DynamicCoherentStructureFactor.py +++ b/MDANSE/Src/MDANSE/Framework/Jobs/DynamicCoherentStructureFactor.py @@ -194,7 +194,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 755c1a55b4..49365e622b 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 cddda4c8d7..9387a3497b 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["gacf_{}}".format(element)][0] == 0: + if self._outputData[f"gacf_{element}}}"][0] == 0: raise ValueError("The normalization factor is equal to zero") else: self._outputData["gacf_{}".format(element)] = normalize( diff --git a/MDANSE/Src/MDANSE/Framework/Jobs/IJob.py b/MDANSE/Src/MDANSE/Framework/Jobs/IJob.py index 447157bc9e..6427a36985 100644 --- a/MDANSE/Src/MDANSE/Framework/Jobs/IJob.py +++ b/MDANSE/Src/MDANSE/Framework/Jobs/IJob.py @@ -115,7 +115,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 @@ -414,7 +414,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) @@ -434,32 +434,32 @@ def save_template(cls, shortname, classname): try: f = open(templateFile, "w") - + label = "label of the class" f.write( - '''import collections + f'''import collections from MDANSE.Framework.Jobs.IJob import IJob -class %(classname)s(IJob): +class {classname}(IJob): """ You should enter the description of your job here ... """ - + # You should enter the label under which your job will be viewed from the gui. - label = %(label)r + label = {label!r} # You should enter the category under which your job will be references. category = ('My jobs',) - + ancestor = ["hdf_trajectory"] # You should enter the configuration of your job here # Here a basic example of a job that will use a HDF trajectory, a frame selection and an output file in HDF5 and Text file formats settings = collections.OrderedDict() - settings['trajectory']=('hdf_trajectory',{}) - settings['frames']=('frames', {"dependencies":{'trajectory':'trajectory'}}) - settings['output_files']=('output_files', {"formats":["HDFFormat","netcdf","TextFormat"]}) - + settings['trajectory']=('hdf_trajectory',{{}}) + settings['frames']=('frames', {{"dependencies":{{'trajectory':'trajectory'}}}}) + settings['output_files']=('output_files', {{"formats":["HDFFormat","netcdf","TextFormat"]}}) + def initialize(self): """ Initialize the input parameters and analysis self variables @@ -468,7 +468,7 @@ def initialize(self): # Compulsory. You must enter the number of steps of your job. # Here for example the number of selected frames self.numberOfSteps = self.configuration['frames']['number'] - + # Create an output data for the selected frames. self._outputData.add("time", "LineOutputVariable", self.configuration['frames']['time'], units='ps') @@ -477,33 +477,28 @@ def run_step(self, index): """ Runs a single step of the job. """ - + return index, None - - + + def combine(self, index, x): """ Synchronize the output of each individual run_step output. - """ - + """ + def finalize(self): """ Finalizes the job (e.g. averaging the total term, output files creations ...). - """ + """ # The output data are written self._outputData.write(self.configuration['output_files']['root'], self.configuration['output_files']['formats'], self._info, self.output_configuration()) - + # The trajectory is closed - self.configuration['trajectory']['instance'].close() + self.configuration['trajectory']['instance'].close() ''' - % { - "classname": classname, - "label": "label of the class", - "shortname": shortname, - } ) except IOError: 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 8ef6dc5fdd..f5d8a096b4 100644 --- a/MDANSE/Src/MDANSE/Framework/Jobs/McStasVirtualInstrument.py +++ b/MDANSE/Src/MDANSE/Framework/Jobs/McStasVirtualInstrument.py @@ -19,6 +19,7 @@ import subprocess import tempfile import io +from functools import partial import numpy as np @@ -38,6 +39,8 @@ NAVOGADRO = 6.02214129e23 +def _startswith(key: str, line: str) -> bool: + return line.strip().startswith(key) class McStasError(Error): pass @@ -362,8 +365,8 @@ def convert(self, sim_dir): if not sim_file: raise Exception("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 @@ -383,7 +386,7 @@ def convert(self, sim_dir): 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(": ") @@ -441,9 +444,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]) @@ -468,7 +471,7 @@ def save_single(self, FileStruct): self._outputData.add( title, "SurfaceOutputVariable", - I, + data, axis="%s|%s" % (xlabel, ylabel), units="au", main_result=True, @@ -489,7 +492,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)) @@ -518,8 +521,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: @@ -527,7 +530,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/PositionPowerSpectrum.py b/MDANSE/Src/MDANSE/Framework/Jobs/PositionPowerSpectrum.py index 28989ade79..aa848f9f8d 100644 --- a/MDANSE/Src/MDANSE/Framework/Jobs/PositionPowerSpectrum.py +++ b/MDANSE/Src/MDANSE/Framework/Jobs/PositionPowerSpectrum.py @@ -21,6 +21,7 @@ from MDANSE.Framework.Jobs.IJob import IJob from MDANSE.Mathematics.Arithmetic import weight from MDANSE.Mathematics.Signal import get_spectrum +from MDANSE.MolecularDynamics.TrajectoryUtils import sorted_atoms from MDANSE.MLogging import LOG diff --git a/MDANSE/Src/MDANSE/Framework/Jobs/RigidBodyTrajectory.py b/MDANSE/Src/MDANSE/Framework/Jobs/RigidBodyTrajectory.py index 1aa6682aed..012b7f1e7e 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 2c9445f0a1..5616e060dd 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 7dfd561780..0b38211e56 100644 --- a/MDANSE/Src/MDANSE/Framework/Jobs/VanHoveFunctionDistinct.py +++ b/MDANSE/Src/MDANSE/Framework/Jobs/VanHoveFunctionDistinct.py @@ -24,7 +24,6 @@ from MDANSE.MolecularDynamics.TrajectoryUtils import atom_index_to_molecule_index from MDANSE.Mathematics.Arithmetic import weight - def distance_array_2D( ref_atoms: np.ndarray, other_atoms: np.ndarray, cell_array: np.ndarray ): @@ -274,7 +273,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,13 +479,13 @@ 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["g(r,t)_%s_%s%s" % (i, pair[0], pair[1])][ + self._outputData[f"g(r,t)_{i}_{''.join(pair)}"][ ... - ] = van_hove + ] = 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 16bceccbf1..59c6c23850 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..2368be80e9 100644 --- a/MDANSE/Src/MDANSE/Framework/Jobs/Voronoi.py +++ b/MDANSE/Src/MDANSE/Framework/Jobs/Voronoi.py @@ -34,7 +34,6 @@ def no_exc_min(numbers: List[float]): except TypeError: return -2 - class VoronoiError(Exception): pass @@ -110,7 +109,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/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 844b7eb8a3..4782218609 100644 --- a/MDANSE/Src/MDANSE/Framework/Session/CurrentSession.py +++ b/MDANSE/Src/MDANSE/Framework/Session/CurrentSession.py @@ -53,4 +53,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 53e7addcdf..55accca7c8 100644 --- a/MDANSE/Src/MDANSE/Framework/Units.py +++ b/MDANSE/Src/MDANSE/Framework/Units.py @@ -729,7 +729,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/Framework/UserDefinitionStore.py b/MDANSE/Src/MDANSE/Framework/UserDefinitionStore.py index 15fc4f620c..768ad98239 100644 --- a/MDANSE/Src/MDANSE/Framework/UserDefinitionStore.py +++ b/MDANSE/Src/MDANSE/Framework/UserDefinitionStore.py @@ -100,8 +100,7 @@ def remove_definition(self, *defs): def set_definition(self, target, section, name, value): if self.has_definition(target, section, name): raise UserDefinitionStoreError( - "Item %s is already registered as an user definition. You must delete it before setting it." - % (target, section, name) + f"Item {(target, section, name)} is already registered as an user definition. You must delete it before setting it." ) self._definitions.setdefault(target, {}).setdefault(section, {})[name] = value diff --git a/MDANSE/Src/MDANSE/IO/FortranFormat.py b/MDANSE/Src/MDANSE/IO/FortranFormat.py index 2a22fddb4f..5ef241ab1c 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 34abdcdbb9..b2996a8f5b 100644 --- a/MDANSE/Src/MDANSE/IO/TextFile.py +++ b/MDANSE/Src/MDANSE/IO/TextFile.py @@ -18,20 +18,19 @@ Text files with line iteration and transparent compression """ -import os, string, sys +import os +import sys +from contextlib import suppress # Use the gzip module for Python version 1.5.2 or higher -gzip = None -try: - _version = [int(c) for c in string.split(string.split(sys.version)[0], ".")] - - if _version >= [1, 5, 2]: +with suppress(Exception): + if sys.version_info >= (1, 5, 2): try: import gzip except ImportError: gzip = None -except: - pass + else: + gzip = None class TextFile: @@ -63,7 +62,9 @@ def __init__(self, filename, mode="r"): if filename.find(":/") > 1: # URL if mode != "r": raise IOError("can't write to a URL") - import urllib.request, urllib.parse, urllib.error + import urllib.request + import urllib.parse + import urllib.error self.file = urllib.request.urlopen(filename) else: @@ -84,7 +85,7 @@ def __init__(self, filename, mode="r"): try: self.file = open(filename, mode) except IOError as details: - if type(details) == type(()): + if isinstance(details, tuple): details = details + (filename,) raise IOError(details) elif mode == "w": @@ -101,7 +102,7 @@ def __init__(self, filename, mode="r"): try: self.file = open(filename, mode) except IOError as details: - if type(details) == type(()): + if isinstance(details, tuple): details = details + (filename,) raise IOError(details) elif mode == "a": diff --git a/MDANSE/Src/MDANSE/Mathematics/LinearAlgebra.py b/MDANSE/Src/MDANSE/Mathematics/LinearAlgebra.py index 8a3330e60f..955ffb6169 100644 --- a/MDANSE/Src/MDANSE/Mathematics/LinearAlgebra.py +++ b/MDANSE/Src/MDANSE/Mathematics/LinearAlgebra.py @@ -492,7 +492,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 7a4a7f5213..2b799819d8 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 0abda4616c..8be6f992c3 100644 --- a/MDANSE/Src/MDANSE/MolecularDynamics/Trajectory.py +++ b/MDANSE/Src/MDANSE/MolecularDynamics/Trajectory.py @@ -153,7 +153,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)): @@ -877,9 +877,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) @@ -963,9 +964,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 f24110110a..4d5db5afac 100644 --- a/MDANSE/Src/MDANSE/Scripts/mdanse.py +++ b/MDANSE/Src/MDANSE/Scripts/mdanse.py @@ -130,7 +130,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( "The job %r could not be opened properly." % basename ) @@ -196,7 +196,7 @@ def display_jobs_list(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: continue # The job file could be opened and unpickled properly @@ -367,7 +367,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 2684e54bfe..32dd79aca7 100644 --- a/MDANSE/Src/MDANSE/Trajectory/H5MDTrajectory.py +++ b/MDANSE/Src/MDANSE/Trajectory/H5MDTrajectory.py @@ -72,7 +72,7 @@ def __init__(self, h5_filename): 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": @@ -87,12 +87,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 @@ -113,26 +113,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] @@ -169,7 +167,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: @@ -192,7 +190,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": @@ -226,7 +224,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) @@ -245,7 +243,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": @@ -272,13 +270,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 @@ -368,7 +366,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": @@ -466,7 +464,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 eab9d9dd8e..c9387179f4 100644 --- a/MDANSE/Src/MDANSE/Trajectory/MdanseTrajectory.py +++ b/MDANSE/Src/MDANSE/Trajectory/MdanseTrajectory.py @@ -66,7 +66,7 @@ def file_is_right(self, filename): result = True try: file_object = h5py.File(filename) - except FileNotFoundError: + except Exception: result = False else: try: