From 9e4086c7fef043ed3210994a17b0b8e62920f18e Mon Sep 17 00:00:00 2001 From: Maciej Bartkowiak Date: Fri, 7 Feb 2025 16:35:18 +0000 Subject: [PATCH 1/6] Make code more ruff-compatible --- .../Src/MDANSE/Trajectory/H5MDTrajectory.py | 27 +++++++++---------- 1 file changed, 13 insertions(+), 14 deletions(-) diff --git a/MDANSE/Src/MDANSE/Trajectory/H5MDTrajectory.py b/MDANSE/Src/MDANSE/Trajectory/H5MDTrajectory.py index 8b1ec0f8f..f547427b5 100644 --- a/MDANSE/Src/MDANSE/Trajectory/H5MDTrajectory.py +++ b/MDANSE/Src/MDANSE/Trajectory/H5MDTrajectory.py @@ -91,7 +91,7 @@ def __init__(self, h5_filename: Union[Path, str]): except Exception: conv_factor = 1.0 else: - if pos_unit == "Ang" or pos_unit == "Angstrom": + if pos_unit in ("Ang", "Angstrom"): pos_unit = "ang" conv_factor = measure(1.0, pos_unit).toval("nm") coords *= conv_factor @@ -128,13 +128,12 @@ def __getitem__(self, frame): :rtype: dict of ndarray """ - 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" or pos_unit == "Angstrom": + if pos_unit in ("Ang", "Angstrom"): pos_unit = "ang" conv_factor = measure(1.0, pos_unit).toval("nm") configuration = {} @@ -144,12 +143,12 @@ def __getitem__(self, frame): 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] @@ -186,7 +185,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: @@ -209,10 +208,10 @@ 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" or pos_unit == "Angstrom": + if pos_unit in ("Ang", "Angstrom"): pos_unit = "ang" conv_factor = measure(1.0, pos_unit).toval("nm") @@ -243,7 +242,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) @@ -395,10 +394,10 @@ 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" or pos_unit == "Angstrom": + if pos_unit in ("Ang", "Angstrom"): pos_unit = "ang" conv_factor = measure(1.0, pos_unit).toval("nm") @@ -493,10 +492,10 @@ 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" or pos_unit == "Angstrom": + if pos_unit in ("Ang", "Angstrom"): pos_unit = "ang" conv_factor = measure(1.0, pos_unit).toval("nm") coords = grp[first:last:step, index, :].astype(np.float64) * conv_factor From 9115ab9deb77c167d5021f476f65ac3a5e20d0d2 Mon Sep 17 00:00:00 2001 From: Jacob Wilkins <46597752+oerc0122@users.noreply.github.com> Date: Mon, 10 Feb 2025 13:27:28 +0000 Subject: [PATCH 2/6] Fix ruff issues (#653) Add to workflows --- .github/workflows/{black.yml => lint.yml} | 11 ++- .../Src/MDANSE_GUI/ElementsDatabaseEditor.py | 8 +- .../InputWidgets/AseInputFileWidget.py | 2 +- .../MDANSE_GUI/InputWidgets/BackupWidget.py | 2 +- .../MDANSE_GUI/InputWidgets/DummyWidget.py | 2 +- .../MDANSE_GUI/InputWidgets/FramesWidget.py | 4 +- .../InputWidgets/InputFileWidget.py | 2 +- .../InputWidgets/InterpolationOrderWidget.py | 2 +- .../InputWidgets/MultiInputFileWidget.py | 4 +- .../InputWidgets/OutputFilesWidget.py | 2 +- .../InputWidgets/OutputStructureWidget.py | 2 +- .../InputWidgets/OutputTrajectoryWidget.py | 2 +- .../InputWidgets/PartialChargeWidget.py | 2 +- .../InputWidgets/ProjectionWidget.py | 2 +- .../MDANSE_GUI/InputWidgets/RangeWidget.py | 2 +- .../MDANSE_GUI/InputWidgets/UnitCellWidget.py | 2 +- .../MDANSE_GUI/InputWidgets/VectorWidget.py | 2 +- .../Src/MDANSE_GUI/InputWidgets/WidgetBase.py | 2 +- .../MDANSE_GUI/MolecularViewer/Contents.py | 4 +- .../MDANSE_GUI/MolecularViewer/Controls.py | 2 +- .../MolecularViewer/MolecularViewer.py | 7 +- .../Src/MDANSE_GUI/Session/LocalSession.py | 4 +- .../MDANSE_GUI/Session/StructuredSession.py | 2 +- .../MDANSE_GUI/Subprocess/JobStatusProcess.py | 6 +- MDANSE_GUI/Src/MDANSE_GUI/TabbedWindow.py | 2 +- MDANSE_GUI/Src/MDANSE_GUI/Tabs/GeneralTab.py | 2 +- MDANSE_GUI/Src/MDANSE_GUI/Tabs/LoggingTab.py | 4 +- .../Src/MDANSE_GUI/Tabs/Models/JobHolder.py | 6 +- .../Src/MDANSE_GUI/Tabs/Models/JobTree.py | 2 +- .../MDANSE_GUI/Tabs/Models/PlotDataModel.py | 2 +- .../MDANSE_GUI/Tabs/Models/PlottingContext.py | 12 +-- .../Src/MDANSE_GUI/Tabs/Plotters/Grid.py | 2 +- .../Src/MDANSE_GUI/Tabs/Plotters/Heatmap.py | 8 +- .../Tabs/Plotters/PlotterTemplate.py | 18 ++-- .../Src/MDANSE_GUI/Tabs/Plotters/Single.py | 4 +- .../Src/MDANSE_GUI/Tabs/Plotters/Text.py | 6 +- .../Src/MDANSE_GUI/Tabs/Views/Delegates.py | 2 +- .../Src/MDANSE_GUI/Tabs/Views/PlotDataView.py | 2 +- .../Src/MDANSE_GUI/Tabs/Visualisers/Action.py | 84 +++++++++++++------ .../Tabs/Visualisers/AnalysisInfo.py | 4 +- .../Tabs/Visualisers/DataPlotter.py | 2 +- .../MDANSE_GUI/Tabs/Visualisers/DataWidget.py | 16 ++-- .../Tabs/Visualisers/InstrumentDetails.py | 2 +- .../Tabs/Visualisers/InstrumentInfo.py | 9 +- .../Tabs/Visualisers/PlotDataInfo.py | 2 +- .../Tabs/Visualisers/PlotSettings.py | 28 +++---- .../MDANSE_GUI/Tabs/Visualisers/PlotWidget.py | 2 +- MDANSE_GUI/Src/MDANSE_GUI/UnitsEditor.py | 2 +- .../Src/MDANSE_GUI/Widgets/GeneralWidgets.py | 4 +- .../MDANSE_GUI/Widgets/ResolutionWidget.py | 12 +-- .../Src/MDANSE_GUI/Widgets/VectorWidget.py | 4 +- MDANSE_GUI/pyproject.toml | 43 ++++++++++ 52 files changed, 226 insertions(+), 140 deletions(-) rename .github/workflows/{black.yml => lint.yml} (68%) diff --git a/.github/workflows/black.yml b/.github/workflows/lint.yml similarity index 68% rename from .github/workflows/black.yml rename to .github/workflows/lint.yml index 6f3db0d75..bd9d08053 100644 --- a/.github/workflows/black.yml +++ b/.github/workflows/lint.yml @@ -1,4 +1,4 @@ -name: Black +name: Lint on: push: @@ -24,3 +24,12 @@ jobs: with: options: "--check --verbose" src: "MDANSE_GUI/Src" + + lint_check_ruff_gui: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + - uses: astral-sh/ruff-action@v3 + with: + src: "./MDANSE_GUI/Src" + args: "check" diff --git a/MDANSE_GUI/Src/MDANSE_GUI/ElementsDatabaseEditor.py b/MDANSE_GUI/Src/MDANSE_GUI/ElementsDatabaseEditor.py index f95606019..451564b7f 100644 --- a/MDANSE_GUI/Src/MDANSE_GUI/ElementsDatabaseEditor.py +++ b/MDANSE_GUI/Src/MDANSE_GUI/ElementsDatabaseEditor.py @@ -146,7 +146,7 @@ def new_line_dialog(self): ne_dialog = InputDialog(fields=dialog_variables) ne_dialog.got_values.connect(self.add_new_line) ne_dialog.show() - result = ne_dialog.exec() + _result = ne_dialog.exec() @Slot() def new_column_dialog(self): @@ -173,7 +173,7 @@ def new_column_dialog(self): ne_dialog = InputDialog(fields=dialog_variables) ne_dialog.got_values.connect(self.add_new_column) ne_dialog.show() - result = ne_dialog.exec() + _result = ne_dialog.exec() @Slot(dict) def add_new_line(self, input_variables: dict): @@ -182,7 +182,7 @@ def add_new_line(self, input_variables: dict): new_label = input_variables["atom_name"] except KeyError: return None - if not new_label in self.database.atoms: + if new_label not in self.database.atoms: self.database.add_atom(new_label) row = [] for key in self.all_column_names: @@ -209,7 +209,7 @@ def add_new_column(self, input_variables: dict): new_type = input_variables["property_type"] except KeyError: return None - if not new_label in self.database.atoms: + if new_label not in self.database.atoms: self.database.add_property(new_label, new_type) column = [] for key in self.all_row_names: diff --git a/MDANSE_GUI/Src/MDANSE_GUI/InputWidgets/AseInputFileWidget.py b/MDANSE_GUI/Src/MDANSE_GUI/InputWidgets/AseInputFileWidget.py index 2cfad4942..5f9acd718 100644 --- a/MDANSE_GUI/Src/MDANSE_GUI/InputWidgets/AseInputFileWidget.py +++ b/MDANSE_GUI/Src/MDANSE_GUI/InputWidgets/AseInputFileWidget.py @@ -87,7 +87,7 @@ def valueFromDialog(self): self.updateValue() try: type_guess = filetype(new_value[0]) - except: + except Exception: type_guess = "guess" self._type_combo.setCurrentText(type_guess) diff --git a/MDANSE_GUI/Src/MDANSE_GUI/InputWidgets/BackupWidget.py b/MDANSE_GUI/Src/MDANSE_GUI/InputWidgets/BackupWidget.py index 3ae63d7d0..8818a3816 100644 --- a/MDANSE_GUI/Src/MDANSE_GUI/InputWidgets/BackupWidget.py +++ b/MDANSE_GUI/Src/MDANSE_GUI/InputWidgets/BackupWidget.py @@ -21,7 +21,7 @@ class BackupWidget(WidgetBase): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) - source_object = kwargs.get("source_object", None) + _source_object = kwargs.get("source_object", None) self._field = QLineEdit(str(self._configurator.default)) self._field.setPlaceholderText(str(self._configurator.default)) self._layout.addWidget(self._field) diff --git a/MDANSE_GUI/Src/MDANSE_GUI/InputWidgets/DummyWidget.py b/MDANSE_GUI/Src/MDANSE_GUI/InputWidgets/DummyWidget.py index 415305d5b..8b5d2c2e1 100644 --- a/MDANSE_GUI/Src/MDANSE_GUI/InputWidgets/DummyWidget.py +++ b/MDANSE_GUI/Src/MDANSE_GUI/InputWidgets/DummyWidget.py @@ -21,7 +21,7 @@ class DummyWidget(WidgetBase): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) - source_object = kwargs.get("source_object", None) + _source_object = kwargs.get("source_object", None) self._layout.addWidget(QLabel("content is missing here", self._base)) self._configurator = {"value": "Oops!"} self.default_labels() diff --git a/MDANSE_GUI/Src/MDANSE_GUI/InputWidgets/FramesWidget.py b/MDANSE_GUI/Src/MDANSE_GUI/InputWidgets/FramesWidget.py index 73a53fdba..99a0de9ae 100644 --- a/MDANSE_GUI/Src/MDANSE_GUI/InputWidgets/FramesWidget.py +++ b/MDANSE_GUI/Src/MDANSE_GUI/InputWidgets/FramesWidget.py @@ -28,7 +28,7 @@ def __init__(self, *args, **kwargs): if trajectory_configurator is not None: try: self._last_frame = trajectory_configurator["length"] - except: + except Exception: self._last_frame = -1 else: self._last_frame = -1 @@ -93,7 +93,7 @@ def get_widget_value(self): strval = field.text() try: val = int(strval) - except: + except Exception: val = int(self._default_values[n]) result.append(val) return result diff --git a/MDANSE_GUI/Src/MDANSE_GUI/InputWidgets/InputFileWidget.py b/MDANSE_GUI/Src/MDANSE_GUI/InputWidgets/InputFileWidget.py index 2daaaab7b..ad51830f1 100644 --- a/MDANSE_GUI/Src/MDANSE_GUI/InputWidgets/InputFileWidget.py +++ b/MDANSE_GUI/Src/MDANSE_GUI/InputWidgets/InputFileWidget.py @@ -103,7 +103,7 @@ def valueFromDialog(self): self._parent._default_path = str( PurePath(os.path.split(new_value[0])[0]) ) - except: + except Exception: LOG.error( f"session.set_path failed for {self._job_name}, {os.path.split(new_value[0])[0]}" ) diff --git a/MDANSE_GUI/Src/MDANSE_GUI/InputWidgets/InterpolationOrderWidget.py b/MDANSE_GUI/Src/MDANSE_GUI/InputWidgets/InterpolationOrderWidget.py index 84a234023..567788bfa 100644 --- a/MDANSE_GUI/Src/MDANSE_GUI/InputWidgets/InterpolationOrderWidget.py +++ b/MDANSE_GUI/Src/MDANSE_GUI/InputWidgets/InterpolationOrderWidget.py @@ -33,7 +33,7 @@ class InterpolationOrderWidget(WidgetBase): def __init__(self, *args, **kwargs): super().__init__(*args, layout_type="QHBoxLayout", **kwargs) - source_object = kwargs.get("source_object", None) + _source_object = kwargs.get("source_object", None) self._field = QSpinBox(self._base) self._field.setMaximum(5) diff --git a/MDANSE_GUI/Src/MDANSE_GUI/InputWidgets/MultiInputFileWidget.py b/MDANSE_GUI/Src/MDANSE_GUI/InputWidgets/MultiInputFileWidget.py index 3fb641da9..0aea3a972 100644 --- a/MDANSE_GUI/Src/MDANSE_GUI/InputWidgets/MultiInputFileWidget.py +++ b/MDANSE_GUI/Src/MDANSE_GUI/InputWidgets/MultiInputFileWidget.py @@ -37,7 +37,7 @@ def valueFromDialog(self): paths_group = self._settings.group("paths") try: self.default_path = paths_group.get(self._job_name) - except: + except Exception: LOG.warning(f"session.get_path failed for {self._job_name}") new_value = self._file_dialog( self.parent(), @@ -57,7 +57,7 @@ def valueFromDialog(self): paths_group.set( self._job_name, str(PurePath(os.path.split(new_value[0][0])[0])) ) - except: + except Exception: LOG.error( f"session.set_path failed for {self._job_name}, {os.path.split(new_value[0][0])[0]}" ) diff --git a/MDANSE_GUI/Src/MDANSE_GUI/InputWidgets/OutputFilesWidget.py b/MDANSE_GUI/Src/MDANSE_GUI/InputWidgets/OutputFilesWidget.py index de0bb8056..22f1ca1c3 100644 --- a/MDANSE_GUI/Src/MDANSE_GUI/InputWidgets/OutputFilesWidget.py +++ b/MDANSE_GUI/Src/MDANSE_GUI/InputWidgets/OutputFilesWidget.py @@ -50,7 +50,7 @@ def __init__(self, *args, **kwargs): guess_name = str( PurePath(os.path.join(self.default_path, jobname + "_result1")) ) - except: + except Exception: guess_name = str(PurePath(default_value[0])) LOG.error("It was not possible to get the job name from the parent") while os.path.exists(guess_name + ".mda"): diff --git a/MDANSE_GUI/Src/MDANSE_GUI/InputWidgets/OutputStructureWidget.py b/MDANSE_GUI/Src/MDANSE_GUI/InputWidgets/OutputStructureWidget.py index 809b3cec6..a0c73b25b 100644 --- a/MDANSE_GUI/Src/MDANSE_GUI/InputWidgets/OutputStructureWidget.py +++ b/MDANSE_GUI/Src/MDANSE_GUI/InputWidgets/OutputStructureWidget.py @@ -46,7 +46,7 @@ def __init__(self, *args, **kwargs): try: parent = kwargs.get("parent", None) guess_name = str(PurePath(os.path.join(self.default_path, "POSCAR"))) - except: + except Exception: guess_name = str(PurePath(default_value[0])) LOG.error("It was not possible to get the job name from the parent") else: diff --git a/MDANSE_GUI/Src/MDANSE_GUI/InputWidgets/OutputTrajectoryWidget.py b/MDANSE_GUI/Src/MDANSE_GUI/InputWidgets/OutputTrajectoryWidget.py index 5df88bf81..3854c9a64 100644 --- a/MDANSE_GUI/Src/MDANSE_GUI/InputWidgets/OutputTrajectoryWidget.py +++ b/MDANSE_GUI/Src/MDANSE_GUI/InputWidgets/OutputTrajectoryWidget.py @@ -62,7 +62,7 @@ def __init__(self, *args, **kwargs): guess_name = str( PurePath(os.path.join(self.default_path, jobname + "_trajectory1")) ) - except: + except Exception: guess_name = str(PurePath(default_value[0])) LOG.error("It was not possible to get the job name from the parent") while os.path.exists(guess_name + ".mdt"): diff --git a/MDANSE_GUI/Src/MDANSE_GUI/InputWidgets/PartialChargeWidget.py b/MDANSE_GUI/Src/MDANSE_GUI/InputWidgets/PartialChargeWidget.py index d9d9b9770..4d357189a 100644 --- a/MDANSE_GUI/Src/MDANSE_GUI/InputWidgets/PartialChargeWidget.py +++ b/MDANSE_GUI/Src/MDANSE_GUI/InputWidgets/PartialChargeWidget.py @@ -131,7 +131,7 @@ def update_charge_textbox(self) -> None: """ map = self.mapper.get_full_setting() - text = [f"Partial charge mapping:\n"] + text = ["Partial charge mapping:\n"] atoms = self.selector.system.atom_list for idx, charge in map.items(): text.append(f"{idx} ({atoms[idx]}) -> {charge}\n") diff --git a/MDANSE_GUI/Src/MDANSE_GUI/InputWidgets/ProjectionWidget.py b/MDANSE_GUI/Src/MDANSE_GUI/InputWidgets/ProjectionWidget.py index d9431c766..650bde8ac 100644 --- a/MDANSE_GUI/Src/MDANSE_GUI/InputWidgets/ProjectionWidget.py +++ b/MDANSE_GUI/Src/MDANSE_GUI/InputWidgets/ProjectionWidget.py @@ -23,7 +23,7 @@ class ProjectionWidget(WidgetBase): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) - source_object = kwargs.get("source_object", None) + _source_object = kwargs.get("source_object", None) bgroup = QButtonGroup(self._base) for id, blabel in enumerate(["None", "Axial", "Planar"]): rbutton = QRadioButton(blabel, parent=self._base) diff --git a/MDANSE_GUI/Src/MDANSE_GUI/InputWidgets/RangeWidget.py b/MDANSE_GUI/Src/MDANSE_GUI/InputWidgets/RangeWidget.py index 9a37357e3..fb9bb03dd 100644 --- a/MDANSE_GUI/Src/MDANSE_GUI/InputWidgets/RangeWidget.py +++ b/MDANSE_GUI/Src/MDANSE_GUI/InputWidgets/RangeWidget.py @@ -95,7 +95,7 @@ def get_widget_value(self): strval = field.text() try: val = self._num_type(strval) - except: + except Exception: val = self._num_type(self._default_values[n]) result.append(val) return result diff --git a/MDANSE_GUI/Src/MDANSE_GUI/InputWidgets/UnitCellWidget.py b/MDANSE_GUI/Src/MDANSE_GUI/InputWidgets/UnitCellWidget.py index 9cd21342a..99f64febc 100644 --- a/MDANSE_GUI/Src/MDANSE_GUI/InputWidgets/UnitCellWidget.py +++ b/MDANSE_GUI/Src/MDANSE_GUI/InputWidgets/UnitCellWidget.py @@ -81,7 +81,7 @@ def get_widget_value(self): for key, value in self._array_fields.items(): try: array[key[0]][key[1]] = float(value.text()) - except: + except Exception: LOG.error( f"Could not set value ({key[0]}, {key[1]}) to {value.text()}" ) diff --git a/MDANSE_GUI/Src/MDANSE_GUI/InputWidgets/VectorWidget.py b/MDANSE_GUI/Src/MDANSE_GUI/InputWidgets/VectorWidget.py index e976061e9..8865afbd8 100644 --- a/MDANSE_GUI/Src/MDANSE_GUI/InputWidgets/VectorWidget.py +++ b/MDANSE_GUI/Src/MDANSE_GUI/InputWidgets/VectorWidget.py @@ -45,6 +45,6 @@ def get_widget_value(self): """Collect the results from the input widgets and return the value.""" try: vector = [float(x.text()) for x in self._vector_fields] - except: + except Exception: vector = [0, 0, 0] return vector diff --git a/MDANSE_GUI/Src/MDANSE_GUI/InputWidgets/WidgetBase.py b/MDANSE_GUI/Src/MDANSE_GUI/InputWidgets/WidgetBase.py index bc87a6952..8591de9f5 100644 --- a/MDANSE_GUI/Src/MDANSE_GUI/InputWidgets/WidgetBase.py +++ b/MDANSE_GUI/Src/MDANSE_GUI/InputWidgets/WidgetBase.py @@ -126,7 +126,7 @@ def updateValue(self): self.configure_using_default() try: self._configurator.configure(current_value) - except: + except Exception: self.mark_error( "COULD NOT SET THIS VALUE - you may need to change the values in other widgets" ) diff --git a/MDANSE_GUI/Src/MDANSE_GUI/MolecularViewer/Contents.py b/MDANSE_GUI/Src/MDANSE_GUI/MolecularViewer/Contents.py index 1365f6e9a..10cda1870 100644 --- a/MDANSE_GUI/Src/MDANSE_GUI/MolecularViewer/Contents.py +++ b/MDANSE_GUI/Src/MDANSE_GUI/MolecularViewer/Contents.py @@ -63,8 +63,8 @@ def parseInformation(self, unique=True): atom_ids = self._reader.atom_ids grouped_by_type = {} name_by_type = {} - colour_by_type = {} - radius_by_type = {} + _colour_by_type = {} + _radius_by_type = {} unique_types = np.unique(atom_types) for type in unique_types: crit = np.where(atom_types == type) diff --git a/MDANSE_GUI/Src/MDANSE_GUI/MolecularViewer/Controls.py b/MDANSE_GUI/Src/MDANSE_GUI/MolecularViewer/Controls.py index 49518e1aa..a1acbcc0f 100644 --- a/MDANSE_GUI/Src/MDANSE_GUI/MolecularViewer/Controls.py +++ b/MDANSE_GUI/Src/MDANSE_GUI/MolecularViewer/Controls.py @@ -96,7 +96,7 @@ class ViewerControls(QWidget): def __init__(self, *args, **kwargs): super(QWidget, self).__init__(*args, **kwargs) - layout = QGridLayout(self) + _layout = QGridLayout(self) self._viewer = None self._buttons = {} self._delegates = {} diff --git a/MDANSE_GUI/Src/MDANSE_GUI/MolecularViewer/MolecularViewer.py b/MDANSE_GUI/Src/MDANSE_GUI/MolecularViewer/MolecularViewer.py index 7f48c6a2f..fdc22a331 100644 --- a/MDANSE_GUI/Src/MDANSE_GUI/MolecularViewer/MolecularViewer.py +++ b/MDANSE_GUI/Src/MDANSE_GUI/MolecularViewer/MolecularViewer.py @@ -13,6 +13,7 @@ # You should have received a copy of the GNU General Public License # along with this program. If not, see . # + from typing import List import numpy as np @@ -199,9 +200,9 @@ def _draw_isosurface(self, index): LOG.info("Computing isosurface ...") - initial_coords = self._reader.read_frame(0) + _initial_coords = self._reader.read_frame(0) coords, lower_bounds, upper_bounds = self._reader.read_atom_trajectory(index) - spacing, self._atomic_trace_histogram = histogram_3d( + spacing, self._atomic_trace_histogram = histogram_3d( # noqa coords, lower_bounds, upper_bounds, 100, 100, 100 ) @@ -548,7 +549,7 @@ def on_open_atomic_trace_settings_dialog(self): hist_max = self._atomic_trace_histogram.max() hist_mean = self._atomic_trace_histogram.mean() - dlg = AtomicTraceSettingsDialog(hist_min, hist_max, hist_mean, self) + dlg = AtomicTraceSettingsDialog(hist_min, hist_max, hist_mean, self) # noqa dlg.rendering_type_changed.connect(self.on_change_atomic_trace_rendering_type) dlg.opacity_changed.connect(self.on_change_atomic_trace_opacity) diff --git a/MDANSE_GUI/Src/MDANSE_GUI/Session/LocalSession.py b/MDANSE_GUI/Src/MDANSE_GUI/Session/LocalSession.py index 23dba2409..c34e96cda 100644 --- a/MDANSE_GUI/Src/MDANSE_GUI/Session/LocalSession.py +++ b/MDANSE_GUI/Src/MDANSE_GUI/Session/LocalSession.py @@ -111,7 +111,7 @@ def save(self, fname: str = None): try: with open(fname, "w") as target: target.write(output) - except: + except Exception: return else: self._filename = fname @@ -122,7 +122,7 @@ def load(self, fname: str = None): try: with open(fname, "r") as source: all_items_text = source.readline() - except: + except Exception: LOG.warning(f"Failed to read session settings from {fname}") else: all_items = json_decoder.decode(all_items_text) diff --git a/MDANSE_GUI/Src/MDANSE_GUI/Session/StructuredSession.py b/MDANSE_GUI/Src/MDANSE_GUI/Session/StructuredSession.py index 4ea4b1e23..be8536e4b 100644 --- a/MDANSE_GUI/Src/MDANSE_GUI/Session/StructuredSession.py +++ b/MDANSE_GUI/Src/MDANSE_GUI/Session/StructuredSession.py @@ -135,7 +135,7 @@ def save_new_value(self, item_index: QModelIndex): group.set(item_key, new_value) elif column_number == 2: group.set_comment(item_key, new_value) - except: + except Exception: LOG.warning( f"Could not store {new_value} in group[{group_key}]->[{item_key}]" ) diff --git a/MDANSE_GUI/Src/MDANSE_GUI/Subprocess/JobStatusProcess.py b/MDANSE_GUI/Src/MDANSE_GUI/Subprocess/JobStatusProcess.py index 8bb1c505f..fc5052de1 100644 --- a/MDANSE_GUI/Src/MDANSE_GUI/Subprocess/JobStatusProcess.py +++ b/MDANSE_GUI/Src/MDANSE_GUI/Subprocess/JobStatusProcess.py @@ -53,12 +53,12 @@ def terminate_the_process(self): LOG.info(f"JobCommunicator PID: {os.getpid()} started 'terminate_the_process") try: self._process.terminate() - except: + except Exception: return else: try: self._process.close() - except: + except Exception: return @@ -91,7 +91,7 @@ def start_status(self): LOG.info(f"JobStatusProcess PID: {os.getpid()} started 'start_status") try: temp = int(self._nSteps) - except: + except Exception: self._pipe.send(("STARTED", None)) else: self._pipe.send(("STARTED", temp)) diff --git a/MDANSE_GUI/Src/MDANSE_GUI/TabbedWindow.py b/MDANSE_GUI/Src/MDANSE_GUI/TabbedWindow.py index af0e29d32..a684a0088 100644 --- a/MDANSE_GUI/Src/MDANSE_GUI/TabbedWindow.py +++ b/MDANSE_GUI/Src/MDANSE_GUI/TabbedWindow.py @@ -177,7 +177,7 @@ def version_information(self): version = "" version += f"MDANSE version: {metadata.version('MDANSE')}\n" version += f"MDANSE_GUI version: {metadata.version('MDANSE_GUI')}\n" - popup = QMessageBox.about(self, "MDANSE Version Information", version) + _popup = QMessageBox.about(self, "MDANSE Version Information", version) def setupToolbar(self): self._toolBar = QToolBar("Main MDANSE toolbar", self) diff --git a/MDANSE_GUI/Src/MDANSE_GUI/Tabs/GeneralTab.py b/MDANSE_GUI/Src/MDANSE_GUI/Tabs/GeneralTab.py index 37635b55e..51cc0e9ca 100644 --- a/MDANSE_GUI/Src/MDANSE_GUI/Tabs/GeneralTab.py +++ b/MDANSE_GUI/Src/MDANSE_GUI/Tabs/GeneralTab.py @@ -154,7 +154,7 @@ def conversion_factor(self, input_unit: str) -> Tuple[float, str]: conversion_factor = measure(1.0, input_unit, equivalent=True).toval( target_unit ) - except: + except Exception: target_unit = self._settings.default_value("units", property) conversion_factor = measure(1.0, input_unit, equivalent=True).toval( target_unit diff --git a/MDANSE_GUI/Src/MDANSE_GUI/Tabs/LoggingTab.py b/MDANSE_GUI/Src/MDANSE_GUI/Tabs/LoggingTab.py index d41cb5b05..2f5df8ea1 100644 --- a/MDANSE_GUI/Src/MDANSE_GUI/Tabs/LoggingTab.py +++ b/MDANSE_GUI/Src/MDANSE_GUI/Tabs/LoggingTab.py @@ -78,7 +78,7 @@ def change_log_level(self, new_level: str): return try: self._extra_handler.setLevel(new_level) - except: + except Exception: LOG.error(f"Could not set GuiLogHandler to log level {new_level}") else: self._visualiser.append_text( @@ -88,7 +88,7 @@ def change_log_level(self, new_level: str): def add_handler(self, new_handler): try: current_level = self._loglevel_combo.currentText() - except: + except Exception: current_level = "INFO" self._extra_handler = new_handler self._extra_handler.add_visualiser(self._visualiser) diff --git a/MDANSE_GUI/Src/MDANSE_GUI/Tabs/Models/JobHolder.py b/MDANSE_GUI/Src/MDANSE_GUI/Tabs/Models/JobHolder.py index f001a5cfe..42329dc4a 100644 --- a/MDANSE_GUI/Src/MDANSE_GUI/Tabs/Models/JobHolder.py +++ b/MDANSE_GUI/Src/MDANSE_GUI/Tabs/Models/JobHolder.py @@ -83,7 +83,7 @@ def run(self): while self._keep_running: try: status_update = self._pipe_end.recv() - except: + except Exception: self.fail() else: self._job_comm.status_update(status_update) @@ -329,7 +329,7 @@ def startProcess(self, job_vars: list, load_afterwards=False): else: try: int(job_vars[1]["output_files"][1]) - except: + except Exception: item_th.for_loading.connect(self.results_for_loading) else: item_th.for_loading.connect(self.trajectory_for_loading) @@ -341,7 +341,7 @@ def startProcess(self, job_vars: list, load_afterwards=False): watcher_thread.start() try: task_name = str(job_vars[0]) - except: + except Exception: task_name = str("This should have been a job name") name_item = QStandardItem(task_name) name_item.setData(entry_number, role=Qt.ItemDataRole.UserRole) diff --git a/MDANSE_GUI/Src/MDANSE_GUI/Tabs/Models/JobTree.py b/MDANSE_GUI/Src/MDANSE_GUI/Tabs/Models/JobTree.py index 83d19428b..c29d48ab7 100644 --- a/MDANSE_GUI/Src/MDANSE_GUI/Tabs/Models/JobTree.py +++ b/MDANSE_GUI/Src/MDANSE_GUI/Tabs/Models/JobTree.py @@ -112,7 +112,7 @@ def parentsFromCategories(self, category_tuple): """ parent = self.invisibleRootItem() for cat_string in category_tuple: - if not cat_string in self._categories.keys(): + if cat_string not in self._categories: current_node = QStandardItem(cat_string) parent.appendRow(current_node) parent = current_node diff --git a/MDANSE_GUI/Src/MDANSE_GUI/Tabs/Models/PlotDataModel.py b/MDANSE_GUI/Src/MDANSE_GUI/Tabs/Models/PlotDataModel.py index f5c2b91b5..ce58df9ba 100644 --- a/MDANSE_GUI/Src/MDANSE_GUI/Tabs/Models/PlotDataModel.py +++ b/MDANSE_GUI/Src/MDANSE_GUI/Tabs/Models/PlotDataModel.py @@ -58,7 +58,7 @@ def populate(self, file): child.setData(key, role=Qt.ItemDataRole.UserRole) try: file[key][:] - except: + except Exception: child._item_type = "group" self.appendRow(child) diff --git a/MDANSE_GUI/Src/MDANSE_GUI/Tabs/Models/PlottingContext.py b/MDANSE_GUI/Src/MDANSE_GUI/Tabs/Models/PlottingContext.py index 5ea30bc5e..d31ce8368 100644 --- a/MDANSE_GUI/Src/MDANSE_GUI/Tabs/Models/PlottingContext.py +++ b/MDANSE_GUI/Src/MDANSE_GUI/Tabs/Models/PlottingContext.py @@ -102,27 +102,27 @@ def set_data_limits(self, limit_string: str): if ":" in token: try: slice_parts = [int(x) for x in token.split(":")] - except: + except Exception: continue if len(slice_parts) < 4: complete_subset_list += list(range(*slice_parts)) elif "-" in token: try: slice_parts = [int(x) for x in token.split("-")] - except: + except Exception: continue if len(slice_parts) == 2: complete_subset_list += list(range(slice_parts[0], slice_parts[1])) elif "," in token: try: slice_parts = [int(x) for x in token.split(",")] - except: + except Exception: continue complete_subset_list += list(slice_parts) else: try: complete_subset_list += [int(token)] - except: + except Exception: continue if len(complete_subset_list) == 0: self._data_limits = None @@ -189,7 +189,7 @@ def curves_vs_axis(self, axis_unit: str) -> List[np.ndarray]: def planes_vs_axis(self, axis_number: int) -> List[np.ndarray]: self._planes = {} self._plane_labels = {} - found = -1 + _found = -1 total_ndim = len(self._data.shape) if total_ndim == 1: return @@ -321,7 +321,7 @@ def colormap(self): backup_cmap = "viridis" try: cmap = self._unit_lookup._settings.group("colours").get("colormap") - except: + except Exception: return backup_cmap else: if cmap in mpl.colormaps(): diff --git a/MDANSE_GUI/Src/MDANSE_GUI/Tabs/Plotters/Grid.py b/MDANSE_GUI/Src/MDANSE_GUI/Tabs/Plotters/Grid.py index 284b8b5e7..57526ba5d 100644 --- a/MDANSE_GUI/Src/MDANSE_GUI/Tabs/Plotters/Grid.py +++ b/MDANSE_GUI/Src/MDANSE_GUI/Tabs/Plotters/Grid.py @@ -103,7 +103,7 @@ def plot( except ValueError: try: temp_curve.set_marker(int(marker)) - except: + except Exception: pass xlimits, ylimits = axes.get_xlim(), axes.get_ylim() try: diff --git a/MDANSE_GUI/Src/MDANSE_GUI/Tabs/Plotters/Heatmap.py b/MDANSE_GUI/Src/MDANSE_GUI/Tabs/Plotters/Heatmap.py index 658cf29f0..2feeb3139 100644 --- a/MDANSE_GUI/Src/MDANSE_GUI/Tabs/Plotters/Heatmap.py +++ b/MDANSE_GUI/Src/MDANSE_GUI/Tabs/Plotters/Heatmap.py @@ -130,8 +130,8 @@ def plot( self._backup_images = {} self._backup_arrays = {} self._backup_scale_interpolators = {} - xaxis_unit = None - yaxis_unit = None + _xaxis_unit = None + _yaxis_unit = None self._axes = [] if not update_only: self._last_axes_units = {} @@ -158,7 +158,7 @@ def plot( nplots += 1 try: self._backup_scale_interpolators[ds_num](51.2) - except: + except Exception: percentiles = np.linspace(0, 100.0, 21) results = [np.percentile(ds._data, perc) for perc in percentiles] self._backup_scale_interpolators[ds_num] = interp1d( @@ -200,7 +200,7 @@ def plot( conversion_factor = measure(1.0, value, equivalent=True).toval( target_unit ) - except: + except Exception: limits += [axis_array[0], axis_array[-1]] axis_units.append(value) else: diff --git a/MDANSE_GUI/Src/MDANSE_GUI/Tabs/Plotters/PlotterTemplate.py b/MDANSE_GUI/Src/MDANSE_GUI/Tabs/Plotters/PlotterTemplate.py index c13d75692..c0334df2a 100644 --- a/MDANSE_GUI/Src/MDANSE_GUI/Tabs/Plotters/PlotterTemplate.py +++ b/MDANSE_GUI/Src/MDANSE_GUI/Tabs/Plotters/PlotterTemplate.py @@ -73,21 +73,21 @@ def convert_units(self): best_unit, best_axis = (dataset._axes_units[axis_label], axis_label) except KeyError: best_unit, best_axis = dataset.longest_axis() - plotlabel = dataset._labels["medium"] + _plotlabel = dataset._labels["medium"] xaxis_unit = self._plotting_context.get_conversion_factor(best_unit) try: - conversion_factor = measure(1.0, best_unit, equivalent=True).toval( + _conversion_factor = measure(1.0, best_unit, equivalent=True).toval( xaxis_unit ) - except: + except Exception: LOG.warning(f"Could not convert {best_unit} to {xaxis_unit}") - conversion_factor = 1.0 + _conversion_factor = 1.0 def apply_weights(self): for dataset_number, dataset in self._datasets: try: scale_factor = self._weight_generator(dataset) - except: + except Exception: scale_factor = 1.0 self._scale_factors[dataset_number].append([scale_factor]) @@ -95,7 +95,7 @@ def apply_norms(self): for dataset_number, dataset in self._datasets.items(): try: scale_factor = self._norm_generator(dataset) - except: + except Exception: scale_factor = 1.0 self._scale_factors[dataset_number].append([scale_factor]) @@ -191,14 +191,14 @@ def apply_settings(self, plotting_context: "PlottingContext", colours=None): return try: matplotlib_style = colours["style"] - except: + except Exception: pass else: if matplotlib_style is not None: mpl_style.use(matplotlib_style) try: bkg_col = colours["background"] - except: + except Exception: pass else: if bkg_col is not None: @@ -206,7 +206,7 @@ def apply_settings(self, plotting_context: "PlottingContext", colours=None): axes.set_facecolor(bkg_col) try: col_seq = colours["curves"] - except: + except Exception: pass else: if col_seq is not None: diff --git a/MDANSE_GUI/Src/MDANSE_GUI/Tabs/Plotters/Single.py b/MDANSE_GUI/Src/MDANSE_GUI/Tabs/Plotters/Single.py index 0dba100ea..307d3ad08 100644 --- a/MDANSE_GUI/Src/MDANSE_GUI/Tabs/Plotters/Single.py +++ b/MDANSE_GUI/Src/MDANSE_GUI/Tabs/Plotters/Single.py @@ -146,7 +146,7 @@ def plot( conversion_factor = measure(1.0, best_unit, equivalent=True).toval( xaxis_unit ) - except: + except Exception: continue else: if dataset._n_dim == 1: @@ -162,7 +162,7 @@ def plot( except ValueError: try: temp.set_marker(int(marker)) - except: + except Exception: pass self._active_curves.append(temp) self._backup_curves.append([temp.get_xdata(), temp.get_ydata()]) diff --git a/MDANSE_GUI/Src/MDANSE_GUI/Tabs/Plotters/Text.py b/MDANSE_GUI/Src/MDANSE_GUI/Tabs/Plotters/Text.py index 9a8aad707..0fc20d034 100644 --- a/MDANSE_GUI/Src/MDANSE_GUI/Tabs/Plotters/Text.py +++ b/MDANSE_GUI/Src/MDANSE_GUI/Tabs/Plotters/Text.py @@ -186,7 +186,7 @@ def process_1D_data( conversion_factor = measure(1.0, best_unit, equivalent=True).toval( xaxis_unit ) - except: + except Exception: return f"Could not convert {best_unit} to {xaxis_unit}." else: header_lines.append(f"{self._comment} units of x axis here: {xaxis_unit}") @@ -316,7 +316,7 @@ def process_ND_data( ) LOG.debug(f"Data shape: {dataset._data.shape}") temp = [] - ncols = len(new_axes) + 1 + _ncols = len(new_axes) + 1 ax_lengths = [len(new_axes[ax_num]) for ax_num in axis_numbers.values()] total_lines = reduce(lambda x, y: x * y, ax_lengths) if is_preview: @@ -472,7 +472,7 @@ def plot( self._toolbar = toolbar self._pc_backup = plotting_context self._figure = target - xaxis_unit = None + _xaxis_unit = None self._active_curves = [] self._backup_curves = [] self.apply_settings(plotting_context, colours) diff --git a/MDANSE_GUI/Src/MDANSE_GUI/Tabs/Views/Delegates.py b/MDANSE_GUI/Src/MDANSE_GUI/Tabs/Views/Delegates.py index 7b72b38a5..83df1d672 100644 --- a/MDANSE_GUI/Src/MDANSE_GUI/Tabs/Views/Delegates.py +++ b/MDANSE_GUI/Src/MDANSE_GUI/Tabs/Views/Delegates.py @@ -152,7 +152,7 @@ def paint(self, painter, option, index): progress_max = max(index.data(self.progress_role + 1) - 1, 1) try: int(progress) - except: + except Exception: progress = 0 opt = QStyleOptionProgressBar() opt.rect = option.rect diff --git a/MDANSE_GUI/Src/MDANSE_GUI/Tabs/Views/PlotDataView.py b/MDANSE_GUI/Src/MDANSE_GUI/Tabs/Views/PlotDataView.py index 4aff58457..bf1ae6f8d 100644 --- a/MDANSE_GUI/Src/MDANSE_GUI/Tabs/Views/PlotDataView.py +++ b/MDANSE_GUI/Src/MDANSE_GUI/Tabs/Views/PlotDataView.py @@ -104,7 +104,7 @@ def on_select_dataset(self, index): for attr in mda_data_structure.attrs: text += f"{attr}: {mda_data_structure.attrs[attr]}\n" self.item_details.emit(text) - except: + except Exception: self.item_details.emit("No additional information included.") @Slot(QModelIndex) diff --git a/MDANSE_GUI/Src/MDANSE_GUI/Tabs/Visualisers/Action.py b/MDANSE_GUI/Src/MDANSE_GUI/Tabs/Visualisers/Action.py index e70ba43ab..a71be0447 100644 --- a/MDANSE_GUI/Src/MDANSE_GUI/Tabs/Visualisers/Action.py +++ b/MDANSE_GUI/Src/MDANSE_GUI/Tabs/Visualisers/Action.py @@ -14,28 +14,64 @@ # along with this program. If not, see . # import os -from pathlib import PurePath import traceback +from pathlib import PurePath import numpy as np +from MDANSE.Framework.Jobs.IJob import IJob +from MDANSE.MLogging import LOG +from MDANSE_GUI.InputWidgets import ( + AseInputFileWidget, + AtomMappingWidget, + AtomSelectionWidget, + AtomTransmutationWidget, + BackupWidget, + BooleanWidget, + ComboWidget, + CorrelationFramesWidget, + DerivativeOrderWidget, + DistHistCutoffWidget, + FloatWidget, + FramesWidget, + HDFTrajectoryWidget, + InputDirectoryWidget, + InputFileWidget, + InstrumentResolutionWidget, + IntegerWidget, + InterpolationOrderWidget, + MDAnalysisCoordinateFileWidget, + MDAnalysisMDTrajTimeStepWidget, + MDAnalysisTopologyFileWidget, + MDTrajTopologyFileWidget, + MoleculeWidget, + MultiInputFileWidget, + MultipleCombosWidget, + OptionalFloatWidget, + OutputDirectoryWidget, + OutputFilesWidget, + OutputStructureWidget, + OutputTrajectoryWidget, + PartialChargeWidget, + ProjectionWidget, + QVectorsWidget, + RangeWidget, + RunningModeWidget, + StringWidget, + UnitCellWidget, + VectorWidget, +) +from MDANSE_GUI.Tabs.Visualisers.InstrumentInfo import SimpleInstrument +from MDANSE_GUI.Widgets.DelayedButton import DelayedButton +from qtpy.QtCore import Signal, Slot from qtpy.QtWidgets import ( - QPushButton, + QCheckBox, QFileDialog, - QVBoxLayout, - QWidget, QHBoxLayout, - QCheckBox, + QPushButton, QTextEdit, + QVBoxLayout, + QWidget, ) -from qtpy.QtCore import Signal, Slot - -from MDANSE.MLogging import LOG -from MDANSE.Framework.Jobs.IJob import IJob - -from MDANSE_GUI.Widgets.DelayedButton import DelayedButton -from MDANSE_GUI.InputWidgets import * -from MDANSE_GUI.Tabs.Visualisers.InstrumentInfo import SimpleInstrument - widget_lookup = { # these all come from MDANSE_GUI.InputWidgets "FloatConfigurator": FloatWidget, @@ -190,8 +226,7 @@ def update_panel(self, job_name: str) -> None: dtype = value[0] ddict = value[1] configurator = job_instance.configuration[key] - if not "label" in ddict.keys(): - ddict["label"] = key + ddict.setdefault("label", key) ddict["configurator"] = configurator ddict["source_object"] = self._input_trajectory widget_class = widget_lookup[dtype] @@ -208,12 +243,11 @@ def update_panel(self, job_name: str) -> None: dtype = value[0] ddict = value[1] configurator = job_instance.configuration[key] - if not "label" in ddict.keys(): - ddict["label"] = key + ddict.setdefault("label", key) ddict["configurator"] = configurator ddict["source_object"] = self._input_trajectory ddict["trajectory_configurator"] = self._trajectory_configurator - if not dtype in widget_lookup.keys(): + if dtype not in widget_lookup: ddict["tooltip"] = ( "This is not implemented in the MDANSE GUI at the moment, and it MUST BE!" ) @@ -258,8 +292,8 @@ def update_panel(self, job_name: str) -> None: default_check_status = ( self._parent_tab._settings.group("Execution").get("auto-load") == "True" ) - except: - LOG.debug(f"Converter tab could not load auto-load settings") + except Exception: + LOG.debug("Converter tab could not load auto-load settings") default_check_status = False if default_check_status: self.post_execute_checkbox.setChecked(True) @@ -373,8 +407,8 @@ def cancel_dialog(self): @Slot() def save_dialog(self): try: - cname = self._job_name - except: + _cname = self._job_name + except Exception: currentpath = PurePath(os.path.abspath(".")) else: currentpath = PurePath( @@ -390,8 +424,8 @@ def save_dialog(self): return None path = PurePath(os.path.split(result)[0]) try: - cname = self._job_name - except: + _cname = self._job_name + except Exception: pass else: self._parent_tab.set_path(self._job_name + "_script", str(path)) diff --git a/MDANSE_GUI/Src/MDANSE_GUI/Tabs/Visualisers/AnalysisInfo.py b/MDANSE_GUI/Src/MDANSE_GUI/Tabs/Visualisers/AnalysisInfo.py index b22b663b7..9113bda71 100644 --- a/MDANSE_GUI/Src/MDANSE_GUI/Tabs/Visualisers/AnalysisInfo.py +++ b/MDANSE_GUI/Src/MDANSE_GUI/Tabs/Visualisers/AnalysisInfo.py @@ -46,14 +46,14 @@ def filter(self, some_text: str, line_break="
"): def summarise_chemical_system(self, job_name): try: temp_instance = IJob.create(job_name) - except: + except Exception: return "" text = "\n ==== Input Parameter summary ==== \n" params = temp_instance.get_default_parameters() for key, value in params.items(): try: text += f"parameters['{key}'] = {value[0]} # {value[1]} \n" - except: + except Exception: continue text += " ===== \n" return text diff --git a/MDANSE_GUI/Src/MDANSE_GUI/Tabs/Visualisers/DataPlotter.py b/MDANSE_GUI/Src/MDANSE_GUI/Tabs/Visualisers/DataPlotter.py index 62a851479..327f0cd6b 100644 --- a/MDANSE_GUI/Src/MDANSE_GUI/Tabs/Visualisers/DataPlotter.py +++ b/MDANSE_GUI/Src/MDANSE_GUI/Tabs/Visualisers/DataPlotter.py @@ -154,4 +154,4 @@ def clear(self): if self._model is None: return self._model.clear() - LOG.info(f"Cleared the plot") + LOG.info("Cleared the plot") diff --git a/MDANSE_GUI/Src/MDANSE_GUI/Tabs/Visualisers/DataWidget.py b/MDANSE_GUI/Src/MDANSE_GUI/Tabs/Visualisers/DataWidget.py index c618ce68a..4ce6f53f7 100644 --- a/MDANSE_GUI/Src/MDANSE_GUI/Tabs/Visualisers/DataWidget.py +++ b/MDANSE_GUI/Src/MDANSE_GUI/Tabs/Visualisers/DataWidget.py @@ -159,7 +159,7 @@ def save_to_file(self): nsets = len(self._plotter._pc_backup.datasets()) except AttributeError: return - except: + except Exception: LOG.warning("DataWidget could not determine the number of datasets.") else: if nsets == 0: # do not create a file if there are no data @@ -167,7 +167,7 @@ def save_to_file(self): try: PLATFORM.create_directory(os.path.dirname(self._output_widget.text())) target = open(target_path, "w", newline="") - except: + except Exception: LOG.error(f"Could not open file for writing: {target_path}") else: writer = csv.writer( @@ -181,13 +181,13 @@ def save_to_file(self): writer.writerow(row) target.close() - @Slot(object) - def slider_change(self, new_values: object): - """Not used for text output.""" + # @Slot(object) + # def slider_change(self, new_values: object): + # """Not used for text output.""" - @Slot(bool) - def set_slider_values(self, reset_needed: bool): - """Not used for text output.""" + # @Slot(bool) + # def set_slider_values(self, reset_needed: bool): + # """Not used for text output.""" def set_context(self, new_context: "PlottingContext"): self._plotting_context = new_context diff --git a/MDANSE_GUI/Src/MDANSE_GUI/Tabs/Visualisers/InstrumentDetails.py b/MDANSE_GUI/Src/MDANSE_GUI/Tabs/Visualisers/InstrumentDetails.py index 2731e227f..3d575cda8 100644 --- a/MDANSE_GUI/Src/MDANSE_GUI/Tabs/Visualisers/InstrumentDetails.py +++ b/MDANSE_GUI/Src/MDANSE_GUI/Tabs/Visualisers/InstrumentDetails.py @@ -149,7 +149,7 @@ def toggle_axis_fields(self): else: widget.setEnabled(True) if "axis_2" in name: - if not "Circular" in self._current_instrument._qvector_type: + if "Circular" not in self._current_instrument._qvector_type: widget.setEnabled(False) else: widget.setEnabled(True) diff --git a/MDANSE_GUI/Src/MDANSE_GUI/Tabs/Visualisers/InstrumentInfo.py b/MDANSE_GUI/Src/MDANSE_GUI/Tabs/Visualisers/InstrumentInfo.py index 3f83f68bc..935d30acb 100644 --- a/MDANSE_GUI/Src/MDANSE_GUI/Tabs/Visualisers/InstrumentInfo.py +++ b/MDANSE_GUI/Src/MDANSE_GUI/Tabs/Visualisers/InstrumentInfo.py @@ -13,9 +13,8 @@ # You should have received a copy of the GNU General Public License # along with this program. If not, see . # -from qtpy.QtCore import Slot, Signal -from qtpy.QtWidgets import QTextBrowser from qtpy.QtCore import Signal, Slot, Qt +from qtpy.QtWidgets import QTextBrowser from qtpy.QtGui import QStandardItem from MDANSE.MLogging import LOG @@ -84,7 +83,7 @@ def update_item(self): def create_resolution_params(self): if not self._configured: return - general_resolution = ("gaussian", {"mu": 0.0, "sigma": 0.2}) + _general_resolution = ("gaussian", {"mu": 0.0, "sigma": 0.2}) calculator = ResolutionCalculator() try: calculator.update_model(self._resolution_type) @@ -131,7 +130,7 @@ def create_q_vector_params(self): _q_step, _q_min, _q_max, _q_width = self.sanitize_numbers() try: conversion_factor = measure(1.0, iunit=self._q_unit).toval("1/nm") - except: + except Exception: raise ValueError(f"Could not convert unit: {self._q_unit}") else: conversion_factor = float(conversion_factor) @@ -164,7 +163,7 @@ def create_q_vector_params(self): def filter_qvector_generator(self): new_list = [str(x) for x in self.qvector_options] if self._sample == "isotropic": - new_list = [str(x) for x in new_list if not "Lattice" in x] + new_list = [str(x) for x in new_list if "Lattice" not in x] if self._technique == "QENS": new_list = [str(x) for x in new_list if "Spherical" in x] return new_list diff --git a/MDANSE_GUI/Src/MDANSE_GUI/Tabs/Visualisers/PlotDataInfo.py b/MDANSE_GUI/Src/MDANSE_GUI/Tabs/Visualisers/PlotDataInfo.py index e8bac120a..6fea8ce93 100644 --- a/MDANSE_GUI/Src/MDANSE_GUI/Tabs/Visualisers/PlotDataInfo.py +++ b/MDANSE_GUI/Src/MDANSE_GUI/Tabs/Visualisers/PlotDataInfo.py @@ -37,7 +37,7 @@ def __init__(self, *args, **kwargs): def update_panel(self, input_text): try: text = "\n".join([f"{key}: {item}" for key, item in input_text.items()]) - except: + except Exception: text = str(input_text) filtered = self.filter(text) self.setHtml(filtered) diff --git a/MDANSE_GUI/Src/MDANSE_GUI/Tabs/Visualisers/PlotSettings.py b/MDANSE_GUI/Src/MDANSE_GUI/Tabs/Visualisers/PlotSettings.py index c29af48d7..dc135778b 100644 --- a/MDANSE_GUI/Src/MDANSE_GUI/Tabs/Visualisers/PlotSettings.py +++ b/MDANSE_GUI/Src/MDANSE_GUI/Tabs/Visualisers/PlotSettings.py @@ -52,7 +52,7 @@ def set_style(self, style_name: str): ) try: mpl.style.use(style_name) - except: + except Exception: LOG.error(f"Could not set matplotlib style to {style_name}") backup_style = self._unit_lookup._settings.default_value( "matplotlib", "style" @@ -84,12 +84,12 @@ def update_units(self): unit_group = self._settings.group("units") try: energy = self._unit_fields["energy"].currentText() - except: + except Exception: LOG.warning("Could not get the energy unit from GUI") else: try: measure(1.0, "rad/ps", equivalent=True).toval(energy) - except: + except Exception: energy = self._settings.default_value("units", "energy") else: if not unit_group.set("energy", energy): @@ -100,12 +100,12 @@ def update_units(self): ) try: time = self._unit_fields["time"].currentText() - except: + except Exception: LOG.warning("Could not get the time unit from GUI") else: try: measure(1.0, "ps").toval(time) - except: + except Exception: time = self._settings.default_value("units", "time") else: if not unit_group.set("time", time): @@ -114,12 +114,12 @@ def update_units(self): ) try: distance = self._unit_fields["distance"].currentText() - except: + except Exception: LOG.warning("Could not get the distance unit from GUI") else: try: measure(1.0, "nm").toval(distance) - except: + except Exception: distance = self._settings.default_value("units", "distance") else: if not unit_group.set("distance", distance): @@ -130,12 +130,12 @@ def update_units(self): ) try: reciprocal = self._unit_fields["reciprocal"].currentText() - except: + except Exception: LOG.warning("Could not get the reciprocal space unit from GUI") else: try: measure(1.0, "1/nm").toval(reciprocal) - except: + except Exception: reciprocal = self._settings.default_value("units", "reciprocal") else: if not unit_group.set("reciprocal", reciprocal): @@ -174,7 +174,7 @@ def make_layout(self, width=12.0, height=9.0, dpi=100): style_selector.addItems(style_list_filtered) try: style_string = self._settings.group("matplotlib").get("style") - except: + except Exception: style_string = "default" style_selector.setCurrentText(style_string) style_selector.currentTextChanged.connect(self.set_style) @@ -184,7 +184,7 @@ def make_layout(self, width=12.0, height=9.0, dpi=100): try: current_cmap = colour_group.get("colormap") except KeyError: - LOG.warning(f"Could not get colormap from colours") + LOG.warning("Could not get colormap from colours") colour_group.add( "colormap", "viridis", @@ -194,8 +194,8 @@ def make_layout(self, width=12.0, height=9.0, dpi=100): else: if current_cmap not in mpl.colormaps(): current_cmap = "viridis" - except: - LOG.warning(f"Could not get the colours group") + except Exception: + LOG.warning("Could not get the colours group") current_cmap = "viridis" cmap_selector = QComboBox(self) cmap_selector.addItems(mpl.colormaps()) @@ -229,7 +229,7 @@ def make_layout(self, width=12.0, height=9.0, dpi=100): self._unit_fields["reciprocal"] = reciprocal_combo try: unit_group = self._settings.group("units") - except: + except Exception: pass else: current_energy = unit_group.get("energy") diff --git a/MDANSE_GUI/Src/MDANSE_GUI/Tabs/Visualisers/PlotWidget.py b/MDANSE_GUI/Src/MDANSE_GUI/Tabs/Visualisers/PlotWidget.py index 271b936a8..7dfca46ab 100644 --- a/MDANSE_GUI/Src/MDANSE_GUI/Tabs/Visualisers/PlotWidget.py +++ b/MDANSE_GUI/Src/MDANSE_GUI/Tabs/Visualisers/PlotWidget.py @@ -175,7 +175,7 @@ def set_context(self, new_context: "PlottingContext"): def set_plotter(self, plotter_option: str): try: self._plotter = Plotter.create(plotter_option) - except: + except Exception: self._plotter = Plotter() self.change_slider_labels.emit(self._plotter.slider_labels()) self.change_slider_limits.emit(self._plotter.slider_limits()) diff --git a/MDANSE_GUI/Src/MDANSE_GUI/UnitsEditor.py b/MDANSE_GUI/Src/MDANSE_GUI/UnitsEditor.py index 2393f0d7b..e7c5a0804 100644 --- a/MDANSE_GUI/Src/MDANSE_GUI/UnitsEditor.py +++ b/MDANSE_GUI/Src/MDANSE_GUI/UnitsEditor.py @@ -196,7 +196,7 @@ def newUnitDialog(self): nu_dialog = InputDialog(fields=dialog_variables) nu_dialog.got_values.connect(self.model.addNewUnit) nu_dialog.show() - result = nu_dialog.exec() + _result = nu_dialog.exec() if __name__ == "__main__": diff --git a/MDANSE_GUI/Src/MDANSE_GUI/Widgets/GeneralWidgets.py b/MDANSE_GUI/Src/MDANSE_GUI/Widgets/GeneralWidgets.py index 7dfc028e3..49d233125 100644 --- a/MDANSE_GUI/Src/MDANSE_GUI/Widgets/GeneralWidgets.py +++ b/MDANSE_GUI/Src/MDANSE_GUI/Widgets/GeneralWidgets.py @@ -350,7 +350,7 @@ def createTrajectory(*args, direction="out", **kwargs): direction -- if 'in', create a FileDialog for an exisitng file, if 'out', a FileDialog for creating a new file. """ - kind = kwargs.get("kind", "String") + _kind = kwargs.get("kind", "String") default_value = kwargs.get("default", "") tooltip_text = kwargs.get( "tooltip", "Specify the name of the output trajectory." @@ -580,7 +580,7 @@ def __init__(self, *args, fields: Iterable["InputVariable"] = None, **kwargs): format = var.format values = var.values widget = var.widget - helper_dialog = var.helper_dialog + _helper_dialog = var.helper_dialog tooltip = var.tooltip placeholder = var.placeholder number_of_inputs = var.number_of_inputs diff --git a/MDANSE_GUI/Src/MDANSE_GUI/Widgets/ResolutionWidget.py b/MDANSE_GUI/Src/MDANSE_GUI/Widgets/ResolutionWidget.py index b0c39e762..7f895eba9 100644 --- a/MDANSE_GUI/Src/MDANSE_GUI/Widgets/ResolutionWidget.py +++ b/MDANSE_GUI/Src/MDANSE_GUI/Widgets/ResolutionWidget.py @@ -211,7 +211,7 @@ def recalculate_peak(self, fwhm, centre, eta, unit): ) try: self._resolution.set_kernel(self._omega_axis, 1.0) - except: + except Exception: self._valid = False else: self._valid = True @@ -363,16 +363,16 @@ def recalculate_peak(self): """ try: fwhm = abs(float(self._fwhm.text())) - except: + except Exception: return try: centre = float(self._centre.text()) - except: + except Exception: return if "oigt" in self._resolution_name: try: eta = float(self._eta.text()) - except: + except Exception: return else: eta = None @@ -411,7 +411,7 @@ def update_fields(self, widget_values): new_eta = new_params.get("eta", "0.0") try: fwhm, centre = revert_parameters(new_params, new_function_name) - except: + except Exception: self.blockSignals(False) return self._peak_selector.setCurrentText(offical_name) @@ -490,7 +490,7 @@ def update_plot(self): + self._calculator._centre_value ) ys = np.array([0.0, hh, hh, 0.0]) - if not "deal" in self._resolution_name: + if "deal" not in self._resolution_name: axes.plot(xs * self._calculator._factor_value, ys, "r:") axes.grid(True) scale = self._calculator._factor_value diff --git a/MDANSE_GUI/Src/MDANSE_GUI/Widgets/VectorWidget.py b/MDANSE_GUI/Src/MDANSE_GUI/Widgets/VectorWidget.py index b9153c452..568af83f2 100644 --- a/MDANSE_GUI/Src/MDANSE_GUI/Widgets/VectorWidget.py +++ b/MDANSE_GUI/Src/MDANSE_GUI/Widgets/VectorWidget.py @@ -32,7 +32,7 @@ class VectorWidget(QWidget): def __init__(self, *args, dtype=None, **kwargs) -> None: label_text = kwargs.pop("label", "Vector input") super().__init__(*args, **kwargs) - if dtype is "int": + if dtype == "int": self._dtype = "int" else: self._dtype = "float" @@ -76,7 +76,7 @@ def setText(self, input_string: str): self.set_value( [converter(x) for x in input_string.strip("[]()").split(",")] ) - except: + except Exception: self.set_value([0, 0, 0]) def text(self): diff --git a/MDANSE_GUI/pyproject.toml b/MDANSE_GUI/pyproject.toml index 72c184f87..c4bf93ed7 100644 --- a/MDANSE_GUI/pyproject.toml +++ b/MDANSE_GUI/pyproject.toml @@ -61,3 +61,46 @@ mdanse_elements_database = "MDANSE_GUI.Scripts.mdanse_elements_database:main" mdanse_gui = "MDANSE_GUI.Scripts.mdanse_gui:main" mdanse_periodic_table = "MDANSE_GUI.Scripts.mdanse_periodic_table:main" mdanse_units_editor = "MDANSE_GUI.Scripts.mdanse_units_editor:main" + +[tool.ruff] +line-length = 88 +indent-width = 4 +target-version = "py39" + +[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"] From ac32bba932310c34035c556b897a003e7a00a322 Mon Sep 17 00:00:00 2001 From: Jacob Wilkins <46597752+oerc0122@users.noreply.github.com> Date: Tue, 11 Feb 2025 10:32:44 +0000 Subject: [PATCH 3/6] Modernise strings (#643) * First stage of string modernisation * Remove unnecessary `.format`. --- MDANSE/Src/MDANSE/Chemistry/Databases.py | 37 +++++----- MDANSE/Src/MDANSE/Framework/Configurable.py | 66 +++++------------ .../Configurators/AseInputFileConfigurator.py | 2 +- .../AtomSelectionConfigurator.py | 4 +- .../AtomTransmutationConfigurator.py | 2 +- .../Configurators/AtomsListConfigurator.py | 16 ++--- .../AxisSelectionConfigurator.py | 14 ++-- .../BasisSelectionConfigurator.py | 14 ++-- .../Configurators/BooleanConfigurator.py | 2 +- .../Configurators/FloatConfigurator.py | 2 +- .../Configurators/FramesConfigurator.py | 13 ++-- .../GroupingLevelConfigurator.py | 2 +- .../Configurators/HDFInputFileConfigurator.py | 4 +- .../HDFTrajectoryConfigurator.py | 7 +- .../Framework/Configurators/IConfigurator.py | 5 +- .../InputDirectoryConfigurator.py | 2 +- .../InstrumentResolutionConfigurator.py | 8 +-- .../Configurators/IntegerConfigurator.py | 2 +- .../MDMCTrajectoryConfigurator.py | 5 +- .../McStasOptionsConfigurator.py | 4 +- .../McStasParametersConfigurator.py | 4 +- .../MockTrajectoryConfigurator.py | 5 +- .../MultipleChoicesConfigurator.py | 2 +- .../OptionalFloatConfigurator.py | 2 +- .../OutputDirectoryConfigurator.py | 2 +- .../OutputTrajectoryConfigurator.py | 2 +- .../Configurators/ProjectionConfigurator.py | 6 +- .../Configurators/PythonObjectConfigurator.py | 2 +- .../Configurators/QVectorsConfigurator.py | 12 ++-- .../Configurators/RangeConfigurator.py | 6 +- .../Configurators/RunningModeConfigurator.py | 4 +- .../Configurators/SingleChoiceConfigurator.py | 2 +- .../SingleOutputFileConfigurator.py | 2 +- .../Configurators/StringConfigurator.py | 2 +- .../TrajectoryVariableConfigurator.py | 2 +- .../Configurators/UnitCellConfigurator.py | 2 +- .../Configurators/VectorConfigurator.py | 2 +- .../Configurators/WeightsConfigurator.py | 2 +- .../Configurators/XYZFileConfigurator.py | 4 +- MDANSE/Src/MDANSE/Framework/Converters/DCD.py | 6 +- .../MDANSE/Framework/Converters/Discover.py | 36 ++++------ .../MDANSE/Framework/Converters/Forcite.py | 48 ++++++------- .../MDANSE/Framework/Converters/Gromacs.py | 2 +- .../Src/MDANSE/Framework/Converters/LAMMPS.py | 6 +- .../Src/MDANSE/Framework/Formats/SVGFormat.py | 6 +- .../MDANSE/Framework/Formats/TextFormat.py | 25 +++---- .../InputData/HDFTrajectoryInputData.py | 16 ++--- .../InputData/MockTrajectoryInputData.py | 7 +- .../MDANSE/Framework/Jobs/AreaPerMolecule.py | 4 +- .../Framework/Jobs/CoordinationNumber.py | 32 +++++---- .../Jobs/CurrentCorrelationFunction.py | 30 ++++---- .../MDANSE/Framework/Jobs/DensityOfStates.py | 12 ++-- .../MDANSE/Framework/Jobs/DensityProfile.py | 6 +- .../Jobs/DynamicCoherentStructureFactor.py | 15 ++-- .../Jobs/DynamicIncoherentStructureFactor.py | 12 ++-- .../Jobs/ElasticIncoherentStructureFactor.py | 6 +- ...aussianDynamicIncoherentStructureFactor.py | 12 ++-- .../Jobs/GeneralAutoCorrelationFunction.py | 12 ++-- MDANSE/Src/MDANSE/Framework/Jobs/IJob.py | 39 +++++----- .../Framework/Jobs/McStasVirtualInstrument.py | 18 +++-- .../Framework/Jobs/MeanSquareDisplacement.py | 6 +- .../NeutronDynamicTotalStructureFactor.py | 67 +++++++++-------- .../Jobs/PairDistributionFunction.py | 26 +++---- .../Jobs/PositionAutoCorrelationFunction.py | 12 ++-- .../Framework/Jobs/PositionPowerSpectrum.py | 12 ++-- .../Framework/Jobs/RigidBodyTrajectory.py | 9 +-- .../Framework/Jobs/RootMeanSquareDeviation.py | 10 +-- .../Framework/Jobs/StaticStructureFactor.py | 17 ++--- .../StructureFactorFromScatteringFunction.py | 4 +- .../Framework/Jobs/VanHoveFunctionDistinct.py | 14 ++-- .../Framework/Jobs/VanHoveFunctionSelf.py | 12 ++-- .../Jobs/VelocityAutoCorrelationFunction.py | 10 +-- .../Jobs/XRayStaticStructureFactor.py | 21 +++--- .../OutputVariables/IOutputVariable.py | 18 ++--- MDANSE/Src/MDANSE/Framework/Units.py | 50 +++++-------- .../MDANSE/Framework/UserDefinitionStore.py | 4 +- MDANSE/Src/MDANSE/IO/FortranFormat.py | 8 +-- MDANSE/Src/MDANSE/IO/HDF.py | 4 +- MDANSE/Src/MDANSE/IO/HDF5.py | 6 +- MDANSE/Src/MDANSE/Mathematics/Arithmetic.py | 2 +- .../Src/MDANSE/Mathematics/LinearAlgebra.py | 6 +- .../Src/MDANSE/Mathematics/Transformation.py | 3 +- .../MolecularDynamics/MockTrajectory.py | 4 +- MDANSE/Src/MDANSE/Scripts/mdanse.py | 72 ++++++++++--------- .../Src/MDANSE/Trajectory/H5MDTrajectory.py | 4 +- .../Src/MDANSE/Trajectory/MdanseTrajectory.py | 4 +- 86 files changed, 456 insertions(+), 575 deletions(-) diff --git a/MDANSE/Src/MDANSE/Chemistry/Databases.py b/MDANSE/Src/MDANSE/Chemistry/Databases.py index e7b52792d..a6a9827b3 100644 --- a/MDANSE/Src/MDANSE/Chemistry/Databases.py +++ b/MDANSE/Src/MDANSE/Chemistry/Databases.py @@ -215,7 +215,7 @@ def __getitem__(self, item: str) -> dict: return copy.deepcopy(self._data[item]) except KeyError: raise AtomsDatabaseError( - "The element {} is not registered in the database.".format(item) + f"The element {item} is not registered in the database." ) def _load(self, user_database: str = None, default_database: str = None) -> None: @@ -253,7 +253,7 @@ def add_atom(self, atom: str) -> None: if atom in self._data: raise AtomsDatabaseError( - "The atom {} is already stored in the database".format(atom) + f"The atom {atom} is already stored in the database" ) self._data[atom] = {} @@ -272,11 +272,11 @@ def add_property(self, pname: str, ptype: str) -> None: if pname in self._properties: raise AtomsDatabaseError( - "The property {} is already registered in the database.".format(pname) + f"The property {pname} is already registered in the database." ) if ptype not in AtomsDatabase._TYPES: - raise AtomsDatabaseError("The property type {} is unknown".format(ptype)) + raise AtomsDatabaseError(f"The property type {ptype} is unknown") self._properties[pname] = ptype ptype = AtomsDatabase._TYPES[ptype] @@ -307,7 +307,7 @@ def get_isotopes(self, atom: str) -> list[str]: """ if atom not in self._data: - raise AtomsDatabaseError("The atom {} is unknown".format(atom)) + raise AtomsDatabaseError(f"The atom {atom} is unknown") # The isotopes are searched according to |symbol| property symbol = self._data[atom]["symbol"] @@ -340,7 +340,7 @@ def get_property(self, pname: str) -> dict[str, Union[str, int, float, list]]: if pname not in self._properties: raise AtomsDatabaseError( - "The property {} is not registered in the database".format(pname) + f"The property {pname} is not registered in the database" ) ptype = AtomsDatabase._TYPES[self._properties[pname]] @@ -365,11 +365,11 @@ def get_value(self, atom: str, pname: str) -> Union[str, int, float, list]: """ if atom not in self._data: - raise AtomsDatabaseError("The atom {} is unknown".format(atom)) + raise AtomsDatabaseError(f"The atom {atom} is unknown") if pname not in self._properties: raise AtomsDatabaseError( - "The property {} is not registered in the database".format(pname) + f"The property {pname} is not registered in the database" ) ptype = self._properties[pname] @@ -397,12 +397,12 @@ def get_values_for_multiple_atoms( if not all(atom in self._data for atom in atoms): raise AtomsDatabaseError( - "One or more of the provided atoms {} are unknown".format(atoms) + f"One or more of the provided atoms {atoms} are unknown" ) if prop not in self._properties: raise AtomsDatabaseError( - "The property {} is not registered in the database".format(prop) + f"The property {prop} is not registered in the database" ) values = {name: self._data[name][prop] for name in unique_atoms} @@ -425,11 +425,11 @@ def set_value( """ if atom not in self._data: - raise AtomsDatabaseError("The element {} is unknown".format(atom)) + raise AtomsDatabaseError(f"The element {atom} is unknown") if pname not in self._properties: raise AtomsDatabaseError( - "The property {} is not registered in the database".format(pname) + f"The property {pname} is not registered in the database" ) try: @@ -438,7 +438,7 @@ def set_value( ) except ValueError: raise AtomsDatabaseError( - "Can not coerce {} to {} type".format(value, self._properties[pname]) + f"Can not coerce {value} to {self._properties[pname]} type" ) def has_atom(self, atom: str) -> bool: @@ -480,19 +480,18 @@ def info(self, atom: str) -> str: # A delimiter line. delimiter = "-" * 70 + tab_fmt = " {:<20}{!s:>50}" info = [ delimiter, - "%s" % atom.center(70), - "%s" % " {0:<20}{1:>50}".format("property", "value"), + f"{atom:^70}", + tab_fmt.format("property", "value"), delimiter, ] # The values for all element's properties for pname in sorted(self._properties): - info.append( - " {0:<20}{1:>50}".format(pname, str(self._data[atom].get(pname, None))) - ) + info.append(tab_fmt.format(pname, self._data[atom].get(pname, None))) info.append(delimiter) info = "\n".join(info) @@ -525,7 +524,7 @@ def match_numeric_property( ) except KeyError: raise AtomsDatabaseError( - "The property {} is not registered in the database".format(pname) + f"The property {pname} is not registered in the database" ) tolerance = abs(tolerance) diff --git a/MDANSE/Src/MDANSE/Framework/Configurable.py b/MDANSE/Src/MDANSE/Framework/Configurable.py index bedb732b5..ef8664e1b 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 @@ -94,7 +94,7 @@ def build_configuration(self): ) # Any kind of error has to be caught except: - raise ConfigurationError("Could not set %r configuration item" % name) + raise ConfigurationError(f"Could not set {name!r} configuration item") def set_settings(self, settings): self.settings = settings @@ -228,10 +228,10 @@ def build_doc_example(cls): docstring += ">>> \n" docstring += ">>> \n" docstring += ">>> parameters = {}\n" - for k, v in list(cls.get_default_parameters().items()): - docstring += ">>> parameters[%r]=%r\n" % (k, v) + for k, v in cls.get_default_parameters().items(): + docstring += f">>> parameters[{k!r}]={v!r}\n" docstring += ">>> \n" - docstring += ">>> job = IJob.create(%r)\n" % cls.__name__ + docstring += f">>> job = IJob.create({cls.__name__!r})\n" docstring += ">>> job.setup(parameters)\n" docstring += ">>> job.run()\n" return docstring @@ -249,53 +249,25 @@ def build_doc_texttable(cls, doclist): sizes[1] = max(sizes[1], len(v["Default value"])) # Case of Description field: has to be splitted and parsed for inserting sphinx "|" keyword for multiline v["Description"] = v["Description"].strip() - v["Description"] = v["Description"].split("\n") + v["Description"] = v["Description"].splitlines() v["Description"] = ["| " + vv.strip() for vv in v["Description"]] - sizes[2] = max(sizes[2], max([len(d) for d in v["Description"]])) - - docstring += "+%s+%s+%s+\n" % ( - "-" * (sizes[0] + 1), - "-" * (sizes[1] + 1), - "-" * (sizes[2] + 1), - ) - docstring += "| %-*s| %-*s| %-*s|\n" % ( - sizes[0], - columns[0], - sizes[1], - columns[1], - sizes[2], - columns[2], - ) - docstring += "+%s+%s+%s+\n" % ( - "=" * (sizes[0] + 1), - "=" * (sizes[1] + 1), - "=" * (sizes[2] + 1), - ) + sizes[2] = max(sizes[2], max(map(len, v["Description"]))) + + data_line = "| " + "| ".join(f"{{}}:<{size}" for size in sizes) + "|\n" + sep_line = "+" + "+".join("-" * (size + 1) for size in sizes) + "+\n" + + docstring += sep_line + docstring += data_line.format(*columns) + docstring += sep_line.replace("-", "=") for v in doclist: - docstring += "| %-*s| %-*s| %-*s|\n" % ( - sizes[0], - v["Configurator"], - sizes[1], - v["Default value"], - sizes[2], - v["Description"][0], + docstring += data_line.format( + v["Configurator"], v["Default value"], v["Description"][0] ) if len(v["Description"]) > 1: for descr in v["Description"][1:]: - docstring += "| %-*s| %-*s| %-*s|\n" % ( - sizes[0], - "", - sizes[1], - "", - sizes[2], - descr, - ) - docstring += "+%s+%s+%s+\n" % ( - "-" * (sizes[0] + 1), - "-" * (sizes[1] + 1), - "-" * (sizes[2] + 1), - ) + data_line.format("", "", descr) + docstring += sep_line docstring += "\n" return docstring diff --git a/MDANSE/Src/MDANSE/Framework/Configurators/AseInputFileConfigurator.py b/MDANSE/Src/MDANSE/Framework/Configurators/AseInputFileConfigurator.py index d69e05bbf..0654a47b3 100644 --- a/MDANSE/Src/MDANSE/Framework/Configurators/AseInputFileConfigurator.py +++ b/MDANSE/Src/MDANSE/Framework/Configurators/AseInputFileConfigurator.py @@ -105,4 +105,4 @@ def get_information(self): 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/AtomSelectionConfigurator.py b/MDANSE/Src/MDANSE/Framework/Configurators/AtomSelectionConfigurator.py index 5d7be86ca..5ed11f7e8 100644 --- a/MDANSE/Src/MDANSE/Framework/Configurators/AtomSelectionConfigurator.py +++ b/MDANSE/Src/MDANSE/Framework/Configurators/AtomSelectionConfigurator.py @@ -127,8 +127,8 @@ def get_information(self) -> str: return "Not configured yet\n" info = [] - info.append("Number of selected atoms:%d" % self["selection_length"]) - info.append("Selected elements:%s" % self["unique_names"]) + info.append(f"Number of selected atoms:{self['selection_length']:d}") + info.append(f"Selected elements:{self['unique_names']}") return "\n".join(info) + "\n" diff --git a/MDANSE/Src/MDANSE/Framework/Configurators/AtomTransmutationConfigurator.py b/MDANSE/Src/MDANSE/Framework/Configurators/AtomTransmutationConfigurator.py index 6ec3f36fe..ddd2ce27d 100644 --- a/MDANSE/Src/MDANSE/Framework/Configurators/AtomTransmutationConfigurator.py +++ b/MDANSE/Src/MDANSE/Framework/Configurators/AtomTransmutationConfigurator.py @@ -203,7 +203,7 @@ def get_information(self) -> str: if self["value"] is None: return "No atoms selected for transmutation\n" - return "Number of transmuted atoms:%d\n" % self._nTransmutedAtoms + return f"Number of transmuted atoms:{self._nTransmutedAtoms:d}\n" def get_transmuter(self) -> AtomTransmuter: """ diff --git a/MDANSE/Src/MDANSE/Framework/Configurators/AtomsListConfigurator.py b/MDANSE/Src/MDANSE/Framework/Configurators/AtomsListConfigurator.py index d465ef6dd..6699704b3 100644 --- a/MDANSE/Src/MDANSE/Framework/Configurators/AtomsListConfigurator.py +++ b/MDANSE/Src/MDANSE/Framework/Configurators/AtomsListConfigurator.py @@ -64,10 +64,10 @@ def configure(self, value): traj_configurator = self._configurable[self._dependencies["trajectory"]] if UD_STORE.has_definition( - traj_configurator["basename"], "%d_atoms_list" % self._nAtoms, value + traj_configurator["basename"], f"{self._nAtoms:d}_atoms_list", value ): molecule, atoms = UD_STORE.get_definition( - traj_configurator["basename"], "%d_atoms_list" % self._nAtoms, value + traj_configurator["basename"], f"{self._nAtoms:d}_atoms_list", value ) elif UD_STORE.has_definition( traj_configurator["basename"], "AtomsListConfigurator", value @@ -78,11 +78,8 @@ def configure(self, value): natoms = tempdict["natoms"] if not natoms == self._nAtoms: raise ValueError( - "The atom list must have " - + str(self._nAtoms) - + " atoms per molecule, but " - + str(natoms) - + " were found." + f"The atom list must have {self._nAtoms} " + f"atoms per molecule, but {natoms} were found." ) atoms = tempdict["indices"] self["value"] = value @@ -111,9 +108,6 @@ def get_information(self): if "atoms" not in self: return "No configured yet" - info = [] - info.append( - "Number of selected %d-tuplets:%d" % (self._nAtoms, self["n_values"]) - ) + info = [f"Number of selected {self._nAtoms:d}-tuplets:{self['n_values']:d}"] return "\n".join(info) + "\n" diff --git a/MDANSE/Src/MDANSE/Framework/Configurators/AxisSelectionConfigurator.py b/MDANSE/Src/MDANSE/Framework/Configurators/AxisSelectionConfigurator.py index c49ee605a..7c67eb26d 100644 --- a/MDANSE/Src/MDANSE/Framework/Configurators/AxisSelectionConfigurator.py +++ b/MDANSE/Src/MDANSE/Framework/Configurators/AxisSelectionConfigurator.py @@ -33,19 +33,19 @@ class AxisSelectionConfigurator(IConfigurator): def configure(self, value): """ - Configure an input value. - + Configure an input value. + The value can be: - + #. a dict with *'molecule'*, *'endpoint1'* and *'endpoint2'* keys. *'molecule'* key \ is the name of the molecule for which the axis selection will be performed and *'endpoint1'* \ - and *'endpoint2'* keys are the names of two atoms of the molecule along which the axis will be defined + and *'endpoint2'* keys are the names of two atoms of the molecule along which the axis will be defined #. str: the axis selection will be performed by reading the corresponding user definition. - + :param configuration: the current configuration :type configuration: MDANSE.Framework.Configurable.Configurable :param value: the input value - :type value: tuple or str + :type value: tuple or str """ self._original_input = value @@ -88,4 +88,4 @@ def get_information(self): if "value" not in self: return "Not configured yet\n" - return "Axis vector:%s\n" % self["value"] + return f"Axis vector:{self['value']}\n" diff --git a/MDANSE/Src/MDANSE/Framework/Configurators/BasisSelectionConfigurator.py b/MDANSE/Src/MDANSE/Framework/Configurators/BasisSelectionConfigurator.py index c11e70a78..ed9e3da79 100644 --- a/MDANSE/Src/MDANSE/Framework/Configurators/BasisSelectionConfigurator.py +++ b/MDANSE/Src/MDANSE/Framework/Configurators/BasisSelectionConfigurator.py @@ -33,17 +33,17 @@ class BasisSelectionConfigurator(IConfigurator): def configure(self, value): """ - Configure an input value. - + Configure an input value. + The value can be: - + #. a dict with *'molecule'*, *'origin'*, *'x_axis'* and *'y_axis'* keys. *'molecule'* key is \ the name of the molecule for which the axis selection will be performed and *'origin'*, *'x_axis'* and *'y_axis'* \ - keys are the names of three atoms of the molecule that will be used to define respectively the origin, the X and Y axis of the basis + keys are the names of three atoms of the molecule that will be used to define respectively the origin, the X and Y axis of the basis #. str: the axis selection will be performed by reading the corresponding user definition. - + :param value: the input value - :type value: tuple or str + :type value: tuple or str :note: this configurator depends on 'trajectory' configurator to be configured """ @@ -85,4 +85,4 @@ def get_information(self): if "value" not in self: return "Not configured yet\n" - return "Basis vector:%s\n" % self["value"] + return f"Basis vector:{self['value']}\n" diff --git a/MDANSE/Src/MDANSE/Framework/Configurators/BooleanConfigurator.py b/MDANSE/Src/MDANSE/Framework/Configurators/BooleanConfigurator.py index 6cbe4ce04..e51ada377 100644 --- a/MDANSE/Src/MDANSE/Framework/Configurators/BooleanConfigurator.py +++ b/MDANSE/Src/MDANSE/Framework/Configurators/BooleanConfigurator.py @@ -70,4 +70,4 @@ def get_information(self): if "value" not in self: return "Not configured yet\n" - return "Value: %r\n" % self["value"] + return f"Value: {self['value']!r}\n" diff --git a/MDANSE/Src/MDANSE/Framework/Configurators/FloatConfigurator.py b/MDANSE/Src/MDANSE/Framework/Configurators/FloatConfigurator.py index 8a0b8eed2..3234e06f4 100644 --- a/MDANSE/Src/MDANSE/Framework/Configurators/FloatConfigurator.py +++ b/MDANSE/Src/MDANSE/Framework/Configurators/FloatConfigurator.py @@ -125,4 +125,4 @@ def get_information(self): if "value" not in self: return "Not configured yet\n" - return "Value: %r\n" % self["value"] + return f"Value: {self['value']!r}\n" diff --git a/MDANSE/Src/MDANSE/Framework/Configurators/FramesConfigurator.py b/MDANSE/Src/MDANSE/Framework/Configurators/FramesConfigurator.py index 21233a23b..12905cfcb 100644 --- a/MDANSE/Src/MDANSE/Framework/Configurators/FramesConfigurator.py +++ b/MDANSE/Src/MDANSE/Framework/Configurators/FramesConfigurator.py @@ -19,9 +19,9 @@ class FramesConfigurator(RangeConfigurator): """ This configurator allows to input a frame selection for the analysis. - + The frame selection can be input as: - + #. a 3-tuple where the 1st, 2nd will correspond respectively to the indices of the first and \ last (excluded) frames to be selected while the 3rd element will correspond to the step number between two frames. For example (1,11,3) will give 1,4,7,10 #. *'all'* keyword, in such case, all the frames of the trajectory are selected @@ -123,13 +123,8 @@ def get_information(self): try: result = ( - "%d frames selected (first=%.3f ; last = %.3f ; time step = %.3f)\n" - % ( - self["n_frames"], - self["time"][0], - self["time"][-1], - self["time_step"], - ) + f"{self['n_frames']} frames selected " + f"(first={self['time'][0]:.3f} ; last = {self['time'][-1]:.3f} ; time step = {self['time_step']:.3f})\n" ) except KeyError: result = "FramesConfigurator could not be configured!" diff --git a/MDANSE/Src/MDANSE/Framework/Configurators/GroupingLevelConfigurator.py b/MDANSE/Src/MDANSE/Framework/Configurators/GroupingLevelConfigurator.py index a9144d5a0..1b635682b 100644 --- a/MDANSE/Src/MDANSE/Framework/Configurators/GroupingLevelConfigurator.py +++ b/MDANSE/Src/MDANSE/Framework/Configurators/GroupingLevelConfigurator.py @@ -149,4 +149,4 @@ def get_information(self): if "value" not in self: return "Not configured yet\n" - return "Grouping level: %r\n" % self["value"] + return f"Grouping level: {self['value']!r}\n" diff --git a/MDANSE/Src/MDANSE/Framework/Configurators/HDFInputFileConfigurator.py b/MDANSE/Src/MDANSE/Framework/Configurators/HDFInputFileConfigurator.py index 5582ea5ad..6efce61cc 100644 --- a/MDANSE/Src/MDANSE/Framework/Configurators/HDFInputFileConfigurator.py +++ b/MDANSE/Src/MDANSE/Framework/Configurators/HDFInputFileConfigurator.py @@ -117,7 +117,7 @@ def get_information(self): if "value" not in self: return "Not configured yet\n" - info = ["HDF input file: %r" % self["value"]] + info = [f"HDF input file: {self['value']!r}"] if "instance" in self: info.append("Contains the following variables:") @@ -125,6 +125,6 @@ def get_information(self): find_numeric_variables(variables, self["instance"]) for v in variables: - info.append("\t-{}".format(v)) + info.append(f"\t-{v}") return "\n".join(info) + "\n" diff --git a/MDANSE/Src/MDANSE/Framework/Configurators/HDFTrajectoryConfigurator.py b/MDANSE/Src/MDANSE/Framework/Configurators/HDFTrajectoryConfigurator.py index be357df2d..ce18ef700 100644 --- a/MDANSE/Src/MDANSE/Framework/Configurators/HDFTrajectoryConfigurator.py +++ b/MDANSE/Src/MDANSE/Framework/Configurators/HDFTrajectoryConfigurator.py @@ -80,14 +80,13 @@ def get_information(self): :rtype: str """ try: - info = ["HDF input trajectory: %r\n" % self["filename"]] - info.append("Number of steps: %d\n" % self["length"]) + info = [f"HDF input trajectory: {self['filename']!r}\n"] + info.append(f"Number of steps: {self['length']:d}\n") except KeyError: info = "Input trajectory has not been configured" else: info.append( - "Size of the chemical system: %d\n" - % self["instance"].chemical_system.number_of_atoms + f"Size of the chemical system: {self['instance'].chemical_system.number_of_atoms:d}\n" ) if self["has_velocities"]: diff --git a/MDANSE/Src/MDANSE/Framework/Configurators/IConfigurator.py b/MDANSE/Src/MDANSE/Framework/Configurators/IConfigurator.py index 9372e7be0..b1015712c 100644 --- a/MDANSE/Src/MDANSE/Framework/Configurators/IConfigurator.py +++ b/MDANSE/Src/MDANSE/Framework/Configurators/IConfigurator.py @@ -59,9 +59,8 @@ def __str__(self): """ if self._configurator is not None: - self._message = "Configurator: %r --> %s" % ( - self._configurator.name, - self._message, + self._message = ( + f"Configurator: {self._configurator.name!r} --> {self._message}" ) return self._message diff --git a/MDANSE/Src/MDANSE/Framework/Configurators/InputDirectoryConfigurator.py b/MDANSE/Src/MDANSE/Framework/Configurators/InputDirectoryConfigurator.py index 8313b41d5..b745bb13f 100644 --- a/MDANSE/Src/MDANSE/Framework/Configurators/InputDirectoryConfigurator.py +++ b/MDANSE/Src/MDANSE/Framework/Configurators/InputDirectoryConfigurator.py @@ -56,4 +56,4 @@ def get_information(self): if "value" not in self: return "Not configured yet\n" - return "Input directory: %r\n" % self["value"] + return f"Input directory: {self['value']!r}\n" diff --git a/MDANSE/Src/MDANSE/Framework/Configurators/InstrumentResolutionConfigurator.py b/MDANSE/Src/MDANSE/Framework/Configurators/InstrumentResolutionConfigurator.py index 1fdf6768d..40ad8e4e4 100644 --- a/MDANSE/Src/MDANSE/Framework/Configurators/InstrumentResolutionConfigurator.py +++ b/MDANSE/Src/MDANSE/Framework/Configurators/InstrumentResolutionConfigurator.py @@ -53,7 +53,7 @@ class InstrumentResolutionConfigurator(IConfigurator): def configure(self, value): """ Configure the instrument resolution. - + :param value: the instrument resolution. It must a 2-tuple where the 1st element is the \ is a string representing one of the supported instrument resolution and the 2nd element \ is a dictionary that stores the parameters for this kernel. @@ -122,11 +122,11 @@ def get_information(self): if "kernel" not in self: return "No configured yet" - info = ["Instrument resolution kernel: %s" % self["kernel"]] + info = [f"Instrument resolution kernel: {self['kernel']}"] if self["parameters"]: info.append("Parameters:") - for k, v in list(self["parameters"].items()): - info.append("%s = %s" % (k, v)) + for k, v in self["parameters"].items(): + info.append(f"{k} = {v}") info = "\n".join(info) diff --git a/MDANSE/Src/MDANSE/Framework/Configurators/IntegerConfigurator.py b/MDANSE/Src/MDANSE/Framework/Configurators/IntegerConfigurator.py index d8ded23b8..73307c54f 100644 --- a/MDANSE/Src/MDANSE/Framework/Configurators/IntegerConfigurator.py +++ b/MDANSE/Src/MDANSE/Framework/Configurators/IntegerConfigurator.py @@ -137,4 +137,4 @@ def get_information(self): if "value" not in self: return "Not configured yet\n" - return "Value: %r\n" % self["value"] + return f"Value: {self['value']!r}\n" diff --git a/MDANSE/Src/MDANSE/Framework/Configurators/MDMCTrajectoryConfigurator.py b/MDANSE/Src/MDANSE/Framework/Configurators/MDMCTrajectoryConfigurator.py index a0c503be1..ffc25444b 100644 --- a/MDANSE/Src/MDANSE/Framework/Configurators/MDMCTrajectoryConfigurator.py +++ b/MDANSE/Src/MDANSE/Framework/Configurators/MDMCTrajectoryConfigurator.py @@ -72,10 +72,9 @@ def get_information(self): """ info = ["MDMC trajectory used as input"] - info.append("Number of steps: %d\n" % self["length"]) + info.append(f"Number of steps: {self['length']:d}\n") info.append( - "Size of the chemical system: %d\n" - % self["instance"].chemical_system.number_of_atoms + f"Size of the chemical system: {self['instance'].chemical_system.number_of_atoms:d}\n" ) if self["has_velocities"]: info.append("The trajectory contains atomic velocities\n") diff --git a/MDANSE/Src/MDANSE/Framework/Configurators/McStasOptionsConfigurator.py b/MDANSE/Src/MDANSE/Framework/Configurators/McStasOptionsConfigurator.py index c9cf35aaa..1bfa4170c 100644 --- a/MDANSE/Src/MDANSE/Framework/Configurators/McStasOptionsConfigurator.py +++ b/MDANSE/Src/MDANSE/Framework/Configurators/McStasOptionsConfigurator.py @@ -84,7 +84,7 @@ def configure(self, value): if Path(v).exists(): v = self._default["dir"] self["mcstas_output_directory"] = Path(v) - tmp.append("--%s=%s" % (k, v)) + tmp.append(f"--{k}={v}") dirname = self["mcstas_output_directory"].parent @@ -107,4 +107,4 @@ def get_information(self): if "value" not in self: return "Not configured yet\n" - return "McStas command line options: %s\n" % self["value"] + return f"McStas command line options: {self['value']}\n" diff --git a/MDANSE/Src/MDANSE/Framework/Configurators/McStasParametersConfigurator.py b/MDANSE/Src/MDANSE/Framework/Configurators/McStasParametersConfigurator.py index 18b556728..99daff6f4 100644 --- a/MDANSE/Src/MDANSE/Framework/Configurators/McStasParametersConfigurator.py +++ b/MDANSE/Src/MDANSE/Framework/Configurators/McStasParametersConfigurator.py @@ -101,7 +101,7 @@ def configure(self, value): continue val[k] = self._mcStasTypes[instrParameters[k][0]](v) - self["value"] = ["%s=%s" % (k, v) for k, v in list(val.items())] + self["value"] = [f"{k}={v}" for k, v in val.items()] @property def exclude(self): @@ -124,4 +124,4 @@ def get_information(self): if "value" not in self: return "Not configured yet\n" - return "McStas command line parameters:%s\n" % self["value"] + return f"McStas command line parameters:{self['value']}\n" diff --git a/MDANSE/Src/MDANSE/Framework/Configurators/MockTrajectoryConfigurator.py b/MDANSE/Src/MDANSE/Framework/Configurators/MockTrajectoryConfigurator.py index 85da7def7..14f096911 100644 --- a/MDANSE/Src/MDANSE/Framework/Configurators/MockTrajectoryConfigurator.py +++ b/MDANSE/Src/MDANSE/Framework/Configurators/MockTrajectoryConfigurator.py @@ -75,10 +75,9 @@ def get_information(self): """ info = ["Mock trajectory used as input"] - info.append("Number of steps: %d\n" % self["length"]) + info.append(f"Number of steps: {self['length']:d}\n") info.append( - "Size of the chemical system: %d\n" - % self["instance"].chemical_system.number_of_atoms + f"Size of the chemical system: {self['instance'].chemical_system.number_of_atoms}\n" ) if self["has_velocities"]: info.append("The trajectory contains atomic velocities\n") diff --git a/MDANSE/Src/MDANSE/Framework/Configurators/MultipleChoicesConfigurator.py b/MDANSE/Src/MDANSE/Framework/Configurators/MultipleChoicesConfigurator.py index 640a9479b..255067866 100644 --- a/MDANSE/Src/MDANSE/Framework/Configurators/MultipleChoicesConfigurator.py +++ b/MDANSE/Src/MDANSE/Framework/Configurators/MultipleChoicesConfigurator.py @@ -102,7 +102,7 @@ def nChoices(self): def get_information(self): try: - info = "Selected items: %r\n" % self["choices"] + info = f"Selected items: {self['choices']!r}\n" except KeyError: info = "MultipleChoicesConfigurator could not be set up" return info diff --git a/MDANSE/Src/MDANSE/Framework/Configurators/OptionalFloatConfigurator.py b/MDANSE/Src/MDANSE/Framework/Configurators/OptionalFloatConfigurator.py index 2fb3066f0..8ab4439ed 100644 --- a/MDANSE/Src/MDANSE/Framework/Configurators/OptionalFloatConfigurator.py +++ b/MDANSE/Src/MDANSE/Framework/Configurators/OptionalFloatConfigurator.py @@ -132,4 +132,4 @@ def get_information(self): if "value" not in self: return "Not configured yet\n" - return "Value: %r\n" % self["value"] + return f"Value: {self['value']!r}\n" diff --git a/MDANSE/Src/MDANSE/Framework/Configurators/OutputDirectoryConfigurator.py b/MDANSE/Src/MDANSE/Framework/Configurators/OutputDirectoryConfigurator.py index 00bb8b7e9..39f0a7512 100644 --- a/MDANSE/Src/MDANSE/Framework/Configurators/OutputDirectoryConfigurator.py +++ b/MDANSE/Src/MDANSE/Framework/Configurators/OutputDirectoryConfigurator.py @@ -72,4 +72,4 @@ def get_information(self): if "value" not in self: return "Not configured yet\n" - return "Output directory: %r\n" % self["value"] + return f"Output directory: {self['value']!r}\n" diff --git a/MDANSE/Src/MDANSE/Framework/Configurators/OutputTrajectoryConfigurator.py b/MDANSE/Src/MDANSE/Framework/Configurators/OutputTrajectoryConfigurator.py index e92988de9..4488affba 100644 --- a/MDANSE/Src/MDANSE/Framework/Configurators/OutputTrajectoryConfigurator.py +++ b/MDANSE/Src/MDANSE/Framework/Configurators/OutputTrajectoryConfigurator.py @@ -126,7 +126,7 @@ def get_information(self): :rtype: str """ try: - info = "Output file: %s\n" % self["file"] + info = f"Output file: {self['file']}\n" except KeyError: info = "Output Trajectory has not been defined" diff --git a/MDANSE/Src/MDANSE/Framework/Configurators/ProjectionConfigurator.py b/MDANSE/Src/MDANSE/Framework/Configurators/ProjectionConfigurator.py index 1c9aa1574..2c43de6d8 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'*) \ @@ -96,4 +96,4 @@ def get_information(self): if self["axis"] is not None: return "No projection performed\n" else: - return "Projection along %r axis\n" % self["axis"] + return f"Projection along {self['axis']!r} axis\n" diff --git a/MDANSE/Src/MDANSE/Framework/Configurators/PythonObjectConfigurator.py b/MDANSE/Src/MDANSE/Framework/Configurators/PythonObjectConfigurator.py index 5fc91cc11..f3c3053a0 100644 --- a/MDANSE/Src/MDANSE/Framework/Configurators/PythonObjectConfigurator.py +++ b/MDANSE/Src/MDANSE/Framework/Configurators/PythonObjectConfigurator.py @@ -59,4 +59,4 @@ def get_information(self): if "value" not in self: return "Not configured yet\n" - return "Python object: %r\n" % self["value"] + return f"Python object: {self['value']}\n" diff --git a/MDANSE/Src/MDANSE/Framework/Configurators/QVectorsConfigurator.py b/MDANSE/Src/MDANSE/Framework/Configurators/QVectorsConfigurator.py index cd8a7c8ef..0434425c5 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 \ @@ -117,13 +117,11 @@ def get_information(self): """ try: - info = ["%d Q shells generated\n" % self["n_shells"]] + info = [f"{self['n_shells']} Q shells generated\n"] except KeyError: return "QVectors could not be configured correctly" else: - for qValue, qVectors in list(self["q_vectors"].items()): - info.append( - "Shell %s: %d Q vectors generated\n" % (qValue, len(qVectors)) - ) + for qValue, qVectors in self["q_vectors"].items(): + info.append(f"Shell {qValue}: {len(qVectors)} Q vectors generated\n") return "".join(info) diff --git a/MDANSE/Src/MDANSE/Framework/Configurators/RangeConfigurator.py b/MDANSE/Src/MDANSE/Framework/Configurators/RangeConfigurator.py index 2edad306e..11c00d616 100644 --- a/MDANSE/Src/MDANSE/Framework/Configurators/RangeConfigurator.py +++ b/MDANSE/Src/MDANSE/Framework/Configurators/RangeConfigurator.py @@ -213,11 +213,7 @@ def get_information(self): if self._valid: - info = "%d values from %s to %s" % ( - self["number"], - self["first"], - self["last"], - ) + info = f"{self['number']:d} values from {self['first']} to {self['last']}" if self._includeLast: info += " last value included" diff --git a/MDANSE/Src/MDANSE/Framework/Configurators/RunningModeConfigurator.py b/MDANSE/Src/MDANSE/Framework/Configurators/RunningModeConfigurator.py index 56fcc870a..068bec563 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 @@ -81,7 +81,7 @@ def get_information(self): :rtype: str """ try: - info = "Run in %s mode (%d slots)\n" % (self["mode"], self["slots"]) + info = f"Run in {self['mode']} mode ({self['slots']:d} slots)\n" except KeyError: info = "Running mode has not been configured" diff --git a/MDANSE/Src/MDANSE/Framework/Configurators/SingleChoiceConfigurator.py b/MDANSE/Src/MDANSE/Framework/Configurators/SingleChoiceConfigurator.py index e8264551f..d651d3f6a 100644 --- a/MDANSE/Src/MDANSE/Framework/Configurators/SingleChoiceConfigurator.py +++ b/MDANSE/Src/MDANSE/Framework/Configurators/SingleChoiceConfigurator.py @@ -81,4 +81,4 @@ def get_information(self): if "value" not in self: return "Not configured yet\n" - return "Selected item: %r\n" % self["value"] + return f"Selected item: {self['value']!r}\n" diff --git a/MDANSE/Src/MDANSE/Framework/Configurators/SingleOutputFileConfigurator.py b/MDANSE/Src/MDANSE/Framework/Configurators/SingleOutputFileConfigurator.py index 7e26065e3..adf63c6fc 100644 --- a/MDANSE/Src/MDANSE/Framework/Configurators/SingleOutputFileConfigurator.py +++ b/MDANSE/Src/MDANSE/Framework/Configurators/SingleOutputFileConfigurator.py @@ -119,7 +119,7 @@ def get_information(self): :rtype: str """ try: - info = "Output file: %s\n" % self["file"] + info = f"Output file: {self['file']}\n" except KeyError: info = "Output file has not been configured" diff --git a/MDANSE/Src/MDANSE/Framework/Configurators/StringConfigurator.py b/MDANSE/Src/MDANSE/Framework/Configurators/StringConfigurator.py index 31559c5a2..5312a1431 100644 --- a/MDANSE/Src/MDANSE/Framework/Configurators/StringConfigurator.py +++ b/MDANSE/Src/MDANSE/Framework/Configurators/StringConfigurator.py @@ -104,4 +104,4 @@ def get_information(self): if "value" not in self: return "Not configured yet\n" - return "Value: %r\n" % self["value"] + return f"Value: {self['value']!r}\n" diff --git a/MDANSE/Src/MDANSE/Framework/Configurators/TrajectoryVariableConfigurator.py b/MDANSE/Src/MDANSE/Framework/Configurators/TrajectoryVariableConfigurator.py index 78f17da57..6d70a5c35 100644 --- a/MDANSE/Src/MDANSE/Framework/Configurators/TrajectoryVariableConfigurator.py +++ b/MDANSE/Src/MDANSE/Framework/Configurators/TrajectoryVariableConfigurator.py @@ -57,4 +57,4 @@ def get_information(self): if "value" not in self: return "Not configured yet\n" - return "Selected variable: %r\n" % self["value"] + return f"Selected variable: {self['value']!r}\n" diff --git a/MDANSE/Src/MDANSE/Framework/Configurators/UnitCellConfigurator.py b/MDANSE/Src/MDANSE/Framework/Configurators/UnitCellConfigurator.py index 99b4ed13c..d2be900d6 100644 --- a/MDANSE/Src/MDANSE/Framework/Configurators/UnitCellConfigurator.py +++ b/MDANSE/Src/MDANSE/Framework/Configurators/UnitCellConfigurator.py @@ -123,4 +123,4 @@ def get_information(self): if "value" not in self: return "Not configured yet\n" - return "Value: %r\n" % self["value"] + return f"Value: {self['value']!r}\n" diff --git a/MDANSE/Src/MDANSE/Framework/Configurators/VectorConfigurator.py b/MDANSE/Src/MDANSE/Framework/Configurators/VectorConfigurator.py index 5881a7712..79bb6131f 100644 --- a/MDANSE/Src/MDANSE/Framework/Configurators/VectorConfigurator.py +++ b/MDANSE/Src/MDANSE/Framework/Configurators/VectorConfigurator.py @@ -142,4 +142,4 @@ def get_information(self): if "value" not in self: return "Not configured yet\n" - return "Value: %r\n" % self["value"] + return f"Value: {self['value']!r}\n" diff --git a/MDANSE/Src/MDANSE/Framework/Configurators/WeightsConfigurator.py b/MDANSE/Src/MDANSE/Framework/Configurators/WeightsConfigurator.py index ffa7853fb..eb64b7040 100644 --- a/MDANSE/Src/MDANSE/Framework/Configurators/WeightsConfigurator.py +++ b/MDANSE/Src/MDANSE/Framework/Configurators/WeightsConfigurator.py @@ -134,7 +134,7 @@ def get_information(self): :rtype: str """ try: - info = "selected weight: %s\n" % self["property"] + info = f"selected weight: {self['property']}\n" except KeyError: info = "Weights have not been configured" diff --git a/MDANSE/Src/MDANSE/Framework/Configurators/XYZFileConfigurator.py b/MDANSE/Src/MDANSE/Framework/Configurators/XYZFileConfigurator.py index 62bc1a567..94cc95392 100644 --- a/MDANSE/Src/MDANSE/Framework/Configurators/XYZFileConfigurator.py +++ b/MDANSE/Src/MDANSE/Framework/Configurators/XYZFileConfigurator.py @@ -47,9 +47,7 @@ def parse(self): try: self["n_atoms"] = int(self["instance"].readline().strip()) except ValueError: - raise XYZFileError( - "Could not read the number of atoms in %s file" % filename - ) + raise XYZFileError(f"Could not read the number of atoms in {filename} file") self._nAtomsLineSize = self["instance"].tell() self["instance"].readline() diff --git a/MDANSE/Src/MDANSE/Framework/Converters/DCD.py b/MDANSE/Src/MDANSE/Framework/Converters/DCD.py index ded2bddb4..f857de26a 100644 --- a/MDANSE/Src/MDANSE/Framework/Converters/DCD.py +++ b/MDANSE/Src/MDANSE/Framework/Converters/DCD.py @@ -69,9 +69,7 @@ def get_byte_order(filename): break if byteOrder is None: - raise ByteOrderError( - "Invalid byte order. %s is not a valid DCD file" % filename - ) + raise ByteOrderError(f"Invalid byte order. {filename} not a valid DCD file") return byteOrder @@ -237,7 +235,7 @@ def read_step(self): else: unitCell = None - fmt = "%df" % self["natoms"] + fmt = f"{self['natoms']}f" config = np.empty((self["natoms"], 3), dtype=np.float64) config[:, 0] = np.array(self.get_record(fmt), dtype=np.float64) config[:, 1] = np.array(self.get_record(fmt), dtype=np.float64) diff --git a/MDANSE/Src/MDANSE/Framework/Converters/Discover.py b/MDANSE/Src/MDANSE/Framework/Converters/Discover.py index 7906087c9..c5468182f 100644 --- a/MDANSE/Src/MDANSE/Framework/Converters/Discover.py +++ b/MDANSE/Src/MDANSE/Framework/Converters/Discover.py @@ -61,7 +61,7 @@ def parse_header(self): rec = "!i" recSize = struct.calcsize(rec) N_ATTYP = struct.unpack(rec, hisfile.read(recSize))[0] - rec = "!" + "%ds" % (4 * N_ATTYP) + "%dd" % N_ATTYP + "8x" + rec = f"!{4 * N_ATTYP}s{N_ATTYP}d8x" recSize = struct.calcsize(rec) hisfile.read(recSize) @@ -69,7 +69,7 @@ def parse_header(self): rec = "!i" recSize = struct.calcsize(rec) N_NMRES = struct.unpack(rec, hisfile.read(recSize))[0] - rec = "!" + "%ds" % (4 * N_NMRES) + "8x" + rec = f"!{4 * N_NMRES}s8x" recSize = struct.calcsize(rec) hisfile.read(recSize) @@ -77,12 +77,7 @@ def parse_header(self): rec = "!i" recSize = struct.calcsize(rec) self["n_atoms"] = N_ATOMS = struct.unpack(rec, hisfile.read(recSize))[0] - rec = "!" + "%di" % N_ATOMS - if VERSION < 2.9: - rec += "%ds" % (4 * N_ATOMS) - else: - rec += "%ds" % (5 * N_ATOMS) - rec += "8x" + rec = f"!{N_ATOMS}i{N_ATOMS * (4 if VERSION < 2.9 else 5)}s8x" recSize = struct.calcsize(rec) hisfile.read(recSize) @@ -91,7 +86,7 @@ def parse_header(self): recSize = struct.calcsize(rec) _, N_MOVAT = struct.unpack(rec, hisfile.read(recSize)) if VERSION >= 2.6: - rec = "!" + "%di" % N_MOVAT + rec = f"!{N_MOVAT}i" recSize = struct.calcsize(rec) self["movable_atoms"] = ( np.array(struct.unpack(rec, hisfile.read(recSize)), dtype=np.int32) - 1 @@ -106,7 +101,7 @@ def parse_header(self): rec = "!i" recSize = struct.calcsize(rec) N_MOL = struct.unpack(rec, hisfile.read(recSize))[0] - rec = "!" + "%di" % N_MOL + "%di" % N_MOL + "8x" + rec = f"!{N_MOL}i{N_MOL}i8x" recSize = struct.calcsize(rec) hisfile.read(recSize) @@ -114,7 +109,7 @@ def parse_header(self): rec = "!i" recSize = struct.calcsize(rec) N_RES = struct.unpack(rec, hisfile.read(recSize))[0] - rec = "!" + "%di" % (2 * N_RES) + "%di" % N_RES + "8x" + rec = f"!{2 * N_RES}i{N_RES}i8x" recSize = struct.calcsize(rec) hisfile.read(recSize) @@ -123,7 +118,7 @@ def parse_header(self): recSize = struct.calcsize(rec) N_BONDS = struct.unpack(rec, hisfile.read(recSize))[0] if N_BONDS > 0: - rec = "!" + "%di" % (2 * N_BONDS) + rec = f"!{2 * N_BONDS}i" recSize = struct.calcsize(rec) _ = struct.unpack(rec, hisfile.read(recSize)) rec = "!8x" @@ -152,19 +147,12 @@ def parse_header(self): self["time_step"] = TIME_STEP * measure(1.0, "fs").toval("ps") # Record 14 - rec = ( - "!3d" - + "%dd" % N_ENER - + "%dd" % N_MOL - + "%dd" % (N_MOL * N_ENER) - + "%dd" % (4 * N_MOL + 2 + 54) - + "8x" - ) + rec = f"!3d{N_ENER}d{N_MOL}d{N_MOL * N_ENER}d{4 * N_MOL + 2 + 54}d8x" self._rec14Size = struct.calcsize(rec) hisfile.read(self._rec14Size) # Record 15 - rec = "!" + "%df" % (3 * N_ATOMS) + "8x" + rec = f"!{3 * N_ATOMS}f8x" recSize = struct.calcsize(rec) self["initial_coordinates"] = np.reshape( struct.unpack(rec, hisfile.read(recSize)), (N_ATOMS, 3) @@ -172,7 +160,7 @@ def parse_header(self): self["initial_coordinates"] *= measure(1.0, "ang").toval("nm") # Record 16 - rec = "!" + "%df" % (3 * N_ATOMS) + "8x" + rec = f"!{3 * N_ATOMS}f8x" recSize = struct.calcsize(rec) self["initial_velocities"] = np.reshape( struct.unpack(rec, hisfile.read(recSize)), (N_ATOMS, 3) @@ -188,9 +176,9 @@ def parse_header(self): self["n_movable_atoms"] = N_ATOMS else: self["n_movable_atoms"] = N_MOVAT - self._recCoord = "!" + "%df" % (3 * self["n_movable_atoms"]) + "8x" + self._recCoord = f"!{3 * self['n_movable_atoms']}f8x" self._recCoordSize = struct.calcsize(self._recCoord) - self._recVel = "!" + "%df" % (3 * self["n_movable_atoms"]) + "8x" + self._recVel = f"!{3 * self['n_movable_atoms']}f8x" self._recVelSize = struct.calcsize(self._recVel) self._frameSize = ( diff --git a/MDANSE/Src/MDANSE/Framework/Converters/Forcite.py b/MDANSE/Src/MDANSE/Framework/Converters/Forcite.py index 49296abf1..75f1f80a4 100644 --- a/MDANSE/Src/MDANSE/Framework/Converters/Forcite.py +++ b/MDANSE/Src/MDANSE/Framework/Converters/Forcite.py @@ -55,7 +55,7 @@ def parse_header(self): rec = "!i" recSize = struct.calcsize(rec) (NTRJTI,) = struct.unpack(rec, trjfile.read(recSize)) - rec = "!%ds8x" % (80 * NTRJTI) + rec = f"!{80*NTRJTI}s8x" recSize = struct.calcsize(rec) self["title"] = struct.unpack(rec, trjfile.read(recSize)) self["title"] = "\n".join([t.decode("utf-8") for t in self["title"]]) @@ -64,7 +64,7 @@ def parse_header(self): rec = "!i" recSize = struct.calcsize(rec) NEEXTI = struct.unpack(rec, trjfile.read(recSize))[0] - rec = "!" + "%ds" % (80 * NEEXTI) + "8x" + rec = f"!{80 * NEEXTI}s8x" recSize = struct.calcsize(rec) trjfile.read(recSize) @@ -82,7 +82,7 @@ def parse_header(self): recSize = struct.calcsize(rec) NFLUSD = struct.unpack(rec, trjfile.read(recSize))[0] - rec = "!%di%di%ds8x" % (NFLUSD, NFLUSD, 8 * NFLUSD) + rec = f"!{NFLUSD}i{NFLUSD}i{8*NFLUSD}s8x" recSize = struct.calcsize(rec) trjfile.read(recSize) @@ -90,7 +90,7 @@ def parse_header(self): recSize = struct.calcsize(rec) self["totmov"] = struct.unpack(rec, trjfile.read(recSize))[0] - rec = "!%di8x" % self["totmov"] + rec = f"!{self['totmov']}i8x" recSize = struct.calcsize(rec) self["mvofst"] = ( np.array(struct.unpack(rec, trjfile.read(recSize)), dtype=np.int32) - 1 @@ -100,7 +100,7 @@ def parse_header(self): rec = "!i" recSize = struct.calcsize(rec) (LEEXTI,) = struct.unpack(rec, trjfile.read(recSize)) - rec = "!%ds8x" % LEEXTI + rec = f"!{LEEXTI}s8x" recSize = struct.calcsize(rec) trjfile.read(recSize) @@ -108,7 +108,7 @@ def parse_header(self): rec = "!i" recSize = struct.calcsize(rec) (LPARTI,) = struct.unpack(rec, trjfile.read(recSize)) - rec = "!%ds8x" % LPARTI + rec = f"!{LPARTI}s8x" recSize = struct.calcsize(rec) trjfile.read(recSize) @@ -116,11 +116,11 @@ def parse_header(self): # Frame record 1 if VERSION == 2000: - rec1 = "!%si33%s5i8x" % (self._fp, self._fp) + rec1 = f"!{self._fp}i33{self.fp}5i8x" elif VERSION == 2010: - rec1 = "!%si57%s6i8x" % (self._fp, self._fp) + rec1 = f"!{self._fp}i57{self._fp}6i8x" else: - rec1 = "!%si58%s6i8x" % (self._fp, self._fp) + rec1 = f"!{self._fp}i58{self._fp}6i8x" recSize = struct.calcsize(rec1) DATA = struct.unpack(rec1, trjfile.read(recSize)) @@ -133,38 +133,38 @@ def parse_header(self): self["gradients_written"] = DATA[-3] # Frame record 2 - rec = "!12%s8x" % self._fp + rec = f"!12{self._fp}8x" recSize = struct.calcsize(rec) trjfile.read(recSize) # Frame record 3 if LCANON: - rec = "!4%s8x" % self._fp + rec = f"!4{self._fp}8x" recSize = struct.calcsize(rec) trjfile.read(recSize) if PERTYPE > 0: # Frame record 4 self._defCellRecPos = trjfile.tell() - self._headerSize - self._defCellRec = "!22%s8x" % self._fp + self._defCellRec = f"!22{self._fp}8x" self._defCellRecSize = struct.calcsize(self._defCellRec) trjfile.read(self._defCellRecSize) if PERTYPE > 0: # Frame record 5 - rec = "!i14%s8x" % self._fp + rec = f"!i14{self._fp}8x" recSize = struct.calcsize(rec) trjfile.read(recSize) if LNPECAN: # Frame record 6 - rec = "!3%s8x" % self._fp + rec = f"!3{self._fp}8x" recSize = struct.calcsize(rec) trjfile.read(recSize) if LTMPDAMP: # Frame record 7 - rec = "!%s8x" % self._fp + rec = f"!{self._fp}8x" recSize = struct.calcsize(rec) trjfile.read(recSize) @@ -173,25 +173,17 @@ def parse_header(self): if self["velocities_written"]: if self["gradients_written"]: # Frame record 8,9,10,11,12,13,14,15,16 - self._configRec = "!" + ("%d%s8x" * 9) % ( - (self["totmov"], self._fp) * 9 - ) + self._configRec = "!" + (f"!{self['totmov']}{self._fp}8x" * 9) else: # Frame record 8,9,10,11,12,13 - self._configRec = "!" + ("%d%s8x" * 6) % ( - (self["totmov"], self._fp) * 6 - ) + self._configRec = "!" + (f"{self['totmov']}{self._fp}8x" * 6) else: if self["gradients_written"]: # Frame record 8,9,10,14,15,16 - self._configRec = "!" + ("%d%s8x" * 6) % ( - (self["totmov"], self._fp) * 6 - ) + self._configRec = "!" + (f"{self['totmov']}{self._fp}8x" * 6) else: # Frame record 8,9,10 - self._configRec = "!" + ("%d%s8x" * 3) % ( - (self["totmov"], self._fp) * 3 - ) + self._configRec = "!" + (f"{self['totmov']}{self._fp}8x" * 3) self._configRecSize = struct.calcsize(self._configRec) trjfile.read(self._configRecSize) @@ -211,7 +203,7 @@ def read_step(self, index): trjfile.seek(pos, 0) - rec = "!%s" % self._fp + rec = f"!{self._fp}" recSize = struct.calcsize(rec) (timeStep,) = struct.unpack(rec, trjfile.read(recSize)) diff --git a/MDANSE/Src/MDANSE/Framework/Converters/Gromacs.py b/MDANSE/Src/MDANSE/Framework/Converters/Gromacs.py index a01cac532..bf956d3a8 100644 --- a/MDANSE/Src/MDANSE/Framework/Converters/Gromacs.py +++ b/MDANSE/Src/MDANSE/Framework/Converters/Gromacs.py @@ -113,7 +113,7 @@ def initialize(self): else: raise GromacsConverterError( "Invalid file format: Gromacs converter can only convert XTC and TRR files, " - "but %s was provided." % self.configuration["xtc_file"]["filename"][-4:] + f"but {self.configuration['xtc_file']['filename'][-4:]} was provided." ) # The number of steps of the analysis. diff --git a/MDANSE/Src/MDANSE/Framework/Converters/LAMMPS.py b/MDANSE/Src/MDANSE/Framework/Converters/LAMMPS.py index e06e156f2..b36f591d8 100644 --- a/MDANSE/Src/MDANSE/Framework/Converters/LAMMPS.py +++ b/MDANSE/Src/MDANSE/Framework/Converters/LAMMPS.py @@ -222,7 +222,7 @@ def parse_first_step(self, aliases, config): ) label = str(config["elements"][ty][0]) mass = str(config["elements"][ty][1]) - name = "{:s}_{:d}".format(str(config["elements"][ty][0]), idx) + name = f"{label}_{idx:d}" try: temp_index = int(temp[0]) except ValueError: @@ -470,7 +470,7 @@ def parse_first_step(self, aliases, config): ty = atom_types[i] - 1 label = str(config["elements"][ty][0]) mass = str(config["elements"][ty][1]) - name = "{:s}_{:d}".format(str(config["elements"][ty][0]), idx) + name = f"{label}_{idx:d}" self._rankToName[idx] = name element_list.append(get_element_from_mapping(aliases, label, mass=mass)) name_list.append(str(ty + 1)) @@ -579,7 +579,7 @@ def parse_first_step(self, aliases, config): ty = atom_types[i] - 1 label = str(config["elements"][ty][0]) mass = str(config["elements"][ty][1]) - name = "{:s}_{:d}".format(str(config["elements"][ty][0]), idx) + name = f"{label}_{idx:d}" self._rankToName[idx] = name element_list.append(get_element_from_mapping(aliases, label, mass=mass)) name_list.append(str(ty + 1)) diff --git a/MDANSE/Src/MDANSE/Framework/Formats/SVGFormat.py b/MDANSE/Src/MDANSE/Framework/Formats/SVGFormat.py index e7acd8170..3f6ae3127 100644 --- a/MDANSE/Src/MDANSE/Framework/Formats/SVGFormat.py +++ b/MDANSE/Src/MDANSE/Framework/Formats/SVGFormat.py @@ -70,12 +70,12 @@ def write(cls, filename: Union[Path, str], data, header=""): if var.axis in data: axis = data[var.axis] - xtitle = "%s (%s)" % (axis.name, format_unit_string(axis.units)) + xtitle = f"{axis.name} ({format_unit_string(axis.units)})" else: axis = np.arange(len(var)) xtitle = "index" - ytitle = "%s (%s)" % (var.varname, format_unit_string(var.units)) + ytitle = f"{var.varname} ({format_unit_string(var.units)})" pl = Poly(list(zip(axis, var)), stroke="blue") @@ -91,7 +91,7 @@ def write(cls, filename: Union[Path, str], data, header=""): ytitle=ytitle, ).SVG().save(svgfilename) - tf.add(svgfilename, arcname="%s%s" % (var.varname, cls.extensions[0])) + tf.add(svgfilename, arcname=f"{var.varname}{cls.extensions[0]}") svgfilename.unlink() diff --git a/MDANSE/Src/MDANSE/Framework/Formats/TextFormat.py b/MDANSE/Src/MDANSE/Framework/Formats/TextFormat.py index e355f733c..cd408e26c 100644 --- a/MDANSE/Src/MDANSE/Framework/Formats/TextFormat.py +++ b/MDANSE/Src/MDANSE/Framework/Formats/TextFormat.py @@ -108,7 +108,7 @@ def write( cls.write_data(tempStr, var, data) real_buffer.seek(0) - info = tarfile.TarInfo(name="%s%s" % (var.varname, cls.extensions[0])) + info = tarfile.TarInfo(name=f"{var.varname}{cls.extensions[0]}") info.size = length_stringio(real_buffer) info.mtime = time.time() tf.addfile(tarinfo=info, fileobj=real_buffer) @@ -138,23 +138,17 @@ def write_data(cls, fileobject, data, allData): if xData == "index": xValues = np.arange(data.shape[0]) - fileobject.write("# 1st column: %s (%s)\n" % (xData, "au")) + fileobject.write(f"# 1st column: {xData} (au)\n") else: xValues = allData[xData] - fileobject.write( - "# 1st column: %s (%s)\n" - % (allData[xData].varname, allData[xData].units) - ) + fileobject.write(f"# 1st column: {xValues.varname} ({xValues.units})\n") if yData == "index": yValues = np.arange(data.shape[1]) - fileobject.write("# 1st row: %s (%s)\n\n" % (yData, "au")) + fileobject.write(f"# 1st row: {yData} (au)\n\n") else: yValues = allData[yData] - fileobject.write( - "# 1st row: %s (%s)\n\n" - % (allData[yData].varname, allData[yData].units) - ) + fileobject.write(f"# 1st row: {yValues.varname} ({yValues.units})\n\n") zData = np.zeros((data.shape[0] + 1, data.shape[1] + 1), dtype=np.float64) zData[1:, 0] = xValues @@ -169,15 +163,12 @@ def write_data(cls, fileobject, data, allData): if xData == "index": xValues = np.arange(data.size) - fileobject.write("# 1st column: %s (%s)\n" % (xData, "au")) + fileobject.write(f"# 1st column: {xData} (au)\n") else: xValues = allData[xData] - fileobject.write( - "# 1st column: %s (%s)\n" - % (allData[xData].varname, allData[xData].units) - ) + fileobject.write(f"# 1st column: {xValues.varname} ({xValues.units})\n") - fileobject.write("# 2nd column: %s (%s)\n\n" % (data.varname, data.units)) + fileobject.write(f"# 2nd column: {data.varname} ({data.units})\n\n") np.savetxt(fileobject, np.column_stack([xValues, data])) fileobject.write("\n") diff --git a/MDANSE/Src/MDANSE/Framework/InputData/HDFTrajectoryInputData.py b/MDANSE/Src/MDANSE/Framework/InputData/HDFTrajectoryInputData.py index 715213aa3..c99672f78 100644 --- a/MDANSE/Src/MDANSE/Framework/InputData/HDFTrajectoryInputData.py +++ b/MDANSE/Src/MDANSE/Framework/InputData/HDFTrajectoryInputData.py @@ -57,15 +57,13 @@ def info(self): timeline = f"[{time_axis[0]}, {time_axis[1]}, ..., {time_axis[-1]}]\n" val.append("Path:") - val.append("%s\n" % self._name) + val.append(f"{self._name}\n") val.append("Number of steps:") - val.append("%s\n" % len(self._data)) + val.append(f"{self._data}\n") val.append("Configuration:") - val.append("\tIs periodic: {}\n".format("unit_cell" in self._data.file)) + val.append(f"\tIs periodic: {'unit_cell' in self._data.file}\n") try: - val.append( - "First unit cell (nm):\n{}\n".format(self._data.unit_cell(0)._unit_cell) - ) + val.append(f"First unit cell (nm):\n{self._data.unit_cell(0)._unit_cell}\n") except: val.append("No unit cell information\n") val.append("Frame times (1st, 2nd, ..., last) in ps:") @@ -74,10 +72,10 @@ def info(self): for k in self._data.variables(): v = self._data.variable(k) try: - val.append("\t- {}: {}".format(k, v.shape)) + val.append(f"\t- {k}: {v.shape}") except AttributeError: try: - val.append("\t- {}: {}".format(k, v["value"].shape)) + val.append(f"\t- {k}: {v['value'].shape}") except KeyError: continue @@ -91,7 +89,7 @@ def info(self): val.append(f"Molecule: {molname}; Count: {len(mollist)}") for k, v in mol_types.items(): - val.append("\t- {:d} {}".format(v, k)) + val.append(f"\t- {v:d} {k}") val = "\n".join(val) diff --git a/MDANSE/Src/MDANSE/Framework/InputData/MockTrajectoryInputData.py b/MDANSE/Src/MDANSE/Framework/InputData/MockTrajectoryInputData.py index b1f262194..997f16691 100644 --- a/MDANSE/Src/MDANSE/Framework/InputData/MockTrajectoryInputData.py +++ b/MDANSE/Src/MDANSE/Framework/InputData/MockTrajectoryInputData.py @@ -43,16 +43,17 @@ def info(self): val = [] val.append("Path:") - val.append("%s\n" % self._name) + val.append(f"{self._name}\n") val.append("Number of steps:") - val.append("%s\n" % len(self._data)) + val.append(f"{self._data}\n") + mol_types = {} val.append("\nMolecular types found:") for name, list in self._data.chemical_system._clusters.items(): mol_types[name] = len(list) for k, v in mol_types.items(): - val.append("\t- {:d} {}".format(v, k)) + val.append(f"\t- {v:d} {k}") val = "\n".join(val) diff --git a/MDANSE/Src/MDANSE/Framework/Jobs/AreaPerMolecule.py b/MDANSE/Src/MDANSE/Framework/Jobs/AreaPerMolecule.py index dece49de2..2c19d0ba5 100644 --- a/MDANSE/Src/MDANSE/Framework/Jobs/AreaPerMolecule.py +++ b/MDANSE/Src/MDANSE/Framework/Jobs/AreaPerMolecule.py @@ -98,8 +98,8 @@ def initialize(self): ) if self._nMolecules == 0: raise AreaPerMoleculeError( - "No molecule matches %r name." - % self.configuration["molecule_name"]["value"] + "No molecule matches " + f"{self.configuration['molecule_name']['value']!r} name." ) self._outputData.add( diff --git a/MDANSE/Src/MDANSE/Framework/Jobs/CoordinationNumber.py b/MDANSE/Src/MDANSE/Framework/Jobs/CoordinationNumber.py index 04a5a7f07..085507894 100644 --- a/MDANSE/Src/MDANSE/Framework/Jobs/CoordinationNumber.py +++ b/MDANSE/Src/MDANSE/Framework/Jobs/CoordinationNumber.py @@ -90,43 +90,45 @@ def finalize(self): for pair in self._elementsPairs: invPair = pair[::-1] + pair_str = "".join(map(str, pair)) + inv_pair_str = "".join(map(str, invPair)) self._outputData.add( - "cn_intra_%s%s" % pair, + f"cn_intra_{pair_str}", "LineOutputVariable", (npoints,), axis="r", units="au", ) self._outputData.add( - "cn_inter_%s%s" % pair, + f"cn_inter_{pair_str}", "LineOutputVariable", (npoints,), axis="r", units="au", ) self._outputData.add( - "cn_total_%s%s" % pair, + f"cn_total_{pair_str}", "LineOutputVariable", (npoints,), axis="r", units="au", ) self._outputData.add( - "cn_intra_%s%s" % invPair, + f"cn_intra_{inv_pair_str}", "LineOutputVariable", (npoints,), axis="r", units="au", ) self._outputData.add( - "cn_inter_%s%s" % invPair, + f"cn_inter_{inv_pair_str}", "LineOutputVariable", (npoints,), axis="r", units="au", ) self._outputData.add( - "cn_total_%s%s" % invPair, + f"cn_total_{inv_pair_str}", "LineOutputVariable", (npoints,), axis="r", @@ -152,6 +154,10 @@ def finalize(self): nAtomsPerElement = self.configuration["atom_selection"].get_natoms() for pair in self._elementsPairs: at1, at2 = pair + invPair = pair[::-1] + pair_str = "".join(map(str, pair)) + inv_pair_str = "".join(map(str, invPair)) + ni = nAtomsPerElement[at1] nj = nAtomsPerElement[at2] @@ -177,24 +183,22 @@ def finalize(self): cAlpha = self._concentrations[pair[0]] cBeta = self._concentrations[pair[1]] - invPair = pair[::-1] - - self._outputData["cn_intra_%s%s" % pair][:] = ( + self._outputData[f"cn_intra_{pair_str}"][:] = ( self.averageDensity * cBeta * cnIntra ) - self._outputData["cn_inter_%s%s" % pair][:] = ( + self._outputData[f"cn_inter_{pair_str}"][:] = ( self.averageDensity * cBeta * cnInter ) - self._outputData["cn_total_%s%s" % pair][:] = ( + self._outputData[f"cn_total_{pair_str}"][:] = ( self.averageDensity * cBeta * cnTotal ) - self._outputData["cn_intra_%s%s" % invPair][:] = ( + self._outputData[f"cn_intra_{inv_pair_str}"][:] = ( self.averageDensity * cAlpha * cnIntra ) - self._outputData["cn_inter_%s%s" % invPair][:] = ( + self._outputData[f"cn_inter_{inv_pair_str}"][:] = ( self.averageDensity * cAlpha * cnInter ) - self._outputData["cn_total_%s%s" % invPair][:] = ( + self._outputData[f"cn_total_{inv_pair_str}"][:] = ( self.averageDensity * cAlpha * cnTotal ) diff --git a/MDANSE/Src/MDANSE/Framework/Jobs/CurrentCorrelationFunction.py b/MDANSE/Src/MDANSE/Framework/Jobs/CurrentCorrelationFunction.py index 87aca2d6b..26cc75509 100644 --- a/MDANSE/Src/MDANSE/Framework/Jobs/CurrentCorrelationFunction.py +++ b/MDANSE/Src/MDANSE/Framework/Jobs/CurrentCorrelationFunction.py @@ -171,22 +171,23 @@ def initialize(self): self._indicesPerElement = self.configuration["atom_selection"].get_indices() for pair in self._elementsPairs: + pair_str = "".join(map(str, pair)) self._outputData.add( - "j(q,t)_long_%s%s" % pair, + f"j(q,t)_long_{pair_str}", "SurfaceOutputVariable", (nQShells, self._nFrames), axis="q|time", units="au", ) self._outputData.add( - "j(q,t)_trans_%s%s" % pair, + f"j(q,t)_trans_{pair_str}", "SurfaceOutputVariable", (nQShells, self._nFrames), axis="q|time", units="au", ) self._outputData.add( - "J(q,f)_long_%s%s" % pair, + f"J(q,f)_long_{pair_str}", "SurfaceOutputVariable", (nQShells, self._nOmegas), axis="q|romega", @@ -195,7 +196,7 @@ def initialize(self): partial_result=True, ) self._outputData.add( - "J(q,f)_trans_%s%s" % pair, + f"J(q,f)_trans_{pair_str}", "SurfaceOutputVariable", (nQShells, self._nOmegas), axis="q|romega", @@ -344,10 +345,10 @@ def combine(self, index: int, x: Optional[tuple[np.ndarray, np.ndarray]]): """ if x is None: for at1, at2 in self._elementsPairs: - self._outputData["j(q,t)_long_%s%s" % (at1, at2)][index, :] = np.zeros( + self._outputData[f"j(q,t)_long_{at1}{at2}"][index, :] = np.zeros( self._nFrames ) - self._outputData["j(q,t)_trans_%s%s" % (at1, at2)][index, :] = np.zeros( + self._outputData[f"j(q,t)_trans_{at1}{at2}"][index, :] = np.zeros( self._nFrames ) return @@ -358,11 +359,11 @@ def combine(self, index: int, x: Optional[tuple[np.ndarray, np.ndarray]]): corr_l = correlate(rho_l[at1], rho_l[at2][:n_configs], mode="valid")[ :, 0, 0 ] / (3 * n_configs * rho_l[at1].shape[2]) - self._outputData["j(q,t)_long_%s%s" % (at1, at2)][index, :] += corr_l.real + self._outputData[f"j(q,t)_long_{at1}{at2}"][index, :] += corr_l.real corr_t = correlate(rho_t[at1], rho_t[at2][:n_configs], mode="valid")[ :, 0, 0 ] / (3 * n_configs * rho_t[at1].shape[2]) - self._outputData["j(q,t)_trans_%s%s" % (at1, at2)][index, :] += corr_t.real + self._outputData[f"j(q,t)_trans_{at1}{at2}"][index, :] += corr_t.real def finalize(self): """Normalize, Fourier transform and write the results out to @@ -370,20 +371,21 @@ def finalize(self): """ nAtomsPerElement = self.configuration["atom_selection"].get_natoms() for pair in self._elementsPairs: + pair_str = "".join(map(str, pair)) at1, at2 = pair ni = nAtomsPerElement[at1] nj = nAtomsPerElement[at2] - self._outputData["j(q,t)_long_%s%s" % pair][:] /= ni * nj - self._outputData["j(q,t)_trans_%s%s" % pair][:] /= ni * nj - self._outputData["J(q,f)_long_%s%s" % pair][:] = get_spectrum( - self._outputData["j(q,t)_long_%s%s" % pair], + self._outputData[f"j(q,t)_long_{pair_str}"][:] /= ni * nj + self._outputData[f"j(q,t)_trans_{pair_str}"][:] /= ni * nj + self._outputData[f"J(q,f)_long_{pair_str}"][:] = get_spectrum( + self._outputData[f"j(q,t)_long_{pair_str}"], self.configuration["instrument_resolution"]["time_window"], self.configuration["instrument_resolution"]["time_step"], axis=1, fft="rfft", ) - self._outputData["J(q,f)_trans_%s%s" % pair][:] = get_spectrum( - self._outputData["j(q,t)_trans_%s%s" % pair], + self._outputData[f"J(q,f)_trans_{pair_str}"][:] = get_spectrum( + self._outputData[f"j(q,t)_trans_{pair_str}"], self.configuration["instrument_resolution"]["time_window"], self.configuration["instrument_resolution"]["time_step"], axis=1, diff --git a/MDANSE/Src/MDANSE/Framework/Jobs/DensityOfStates.py b/MDANSE/Src/MDANSE/Framework/Jobs/DensityOfStates.py index 9fc07955c..a9a02470e 100644 --- a/MDANSE/Src/MDANSE/Framework/Jobs/DensityOfStates.py +++ b/MDANSE/Src/MDANSE/Framework/Jobs/DensityOfStates.py @@ -130,14 +130,14 @@ def initialize(self): for element in self.configuration["atom_selection"]["unique_names"]: self._outputData.add( - "vacf_%s" % element, + f"vacf_{element}", "LineOutputVariable", (self.configuration["frames"]["n_frames"],), axis="time", units="nm2/ps2", ) self._outputData.add( - "dos_%s" % element, + f"dos_{element}", "LineOutputVariable", (instrResolution["n_romegas"],), axis="romega", @@ -225,7 +225,7 @@ def combine(self, index, x): # The symbol of the atom. element = self.configuration["atom_selection"]["names"][index] - self._outputData["vacf_%s" % element] += x + self._outputData[f"vacf_{element}"] += x def finalize(self): """ @@ -234,9 +234,9 @@ def finalize(self): nAtomsPerElement = self.configuration["atom_selection"].get_natoms() for element, number in nAtomsPerElement.items(): - self._outputData["vacf_%s" % element][:] /= number - self._outputData["dos_%s" % element][:] = get_spectrum( - self._outputData["vacf_%s" % element], + self._outputData[f"vacf_{element}"][:] /= number + self._outputData[f"dos_{element}"][:] = get_spectrum( + self._outputData[f"vacf_{element}"], self.configuration["instrument_resolution"]["time_window"], self.configuration["instrument_resolution"]["time_step"], fft="rfft", diff --git a/MDANSE/Src/MDANSE/Framework/Jobs/DensityProfile.py b/MDANSE/Src/MDANSE/Framework/Jobs/DensityProfile.py index 5dae1d530..fa7332aa8 100644 --- a/MDANSE/Src/MDANSE/Framework/Jobs/DensityProfile.py +++ b/MDANSE/Src/MDANSE/Framework/Jobs/DensityProfile.py @@ -115,7 +115,7 @@ def initialize(self): for element in self._indices_per_element.keys(): self._outputData.add( - "dp_%s" % element, + f"dp_{element}", "LineOutputVariable", (self._n_bins,), axis="r", @@ -168,7 +168,7 @@ def combine(self, index, x): self._extent += x[0] for element, hist in list(x[1].items()): - self._outputData["dp_%s" % element] += hist + self._outputData[f"dp_{element}"] += hist def finalize(self): """ @@ -177,7 +177,7 @@ def finalize(self): n_atoms_per_element = self.configuration["atom_selection"].get_natoms() for element in n_atoms_per_element.keys(): - self._outputData["dp_%s" % element] += self.numberOfSteps + self._outputData[f"dp_{element}"] += self.numberOfSteps dp_total = weight( self.configuration["weights"].get_weights(), diff --git a/MDANSE/Src/MDANSE/Framework/Jobs/DynamicCoherentStructureFactor.py b/MDANSE/Src/MDANSE/Framework/Jobs/DynamicCoherentStructureFactor.py index 3482ee4ff..1feeadcf9 100644 --- a/MDANSE/Src/MDANSE/Framework/Jobs/DynamicCoherentStructureFactor.py +++ b/MDANSE/Src/MDANSE/Framework/Jobs/DynamicCoherentStructureFactor.py @@ -148,15 +148,16 @@ def initialize(self): self._indicesPerElement = self.configuration["atom_selection"].get_indices() for pair in self._elementsPairs: + pair_str = "".join(map(str, pair)) self._outputData.add( - "f(q,t)_%s%s" % pair, + f"f(q,t)_{pair_str}", "SurfaceOutputVariable", (nQShells, self._nFrames), axis="q|time", units="au", ) self._outputData.add( - "s(q,f)_%s%s" % pair, + f"s(q,f)_{pair_str}", "SurfaceOutputVariable", (nQShells, self._nOmegas), axis="q|omega", @@ -236,12 +237,13 @@ def combine(self, index, x): if x is not None: n_configs = self.configuration["frames"]["n_configs"] for pair in self._elementsPairs: + pair_str = "".join(map(str, pair)) # F_ab(Q,t) = F_ba(Q,t) this is valid as long as # n_configs is sufficiently large corr = correlate(x[pair[0]], x[pair[1]][:n_configs], mode="valid").T[ 0 ] / (n_configs * x[pair[0]].shape[1]) - self._outputData["f(q,t)_%s%s" % pair][index, :] += corr.real + self._outputData[f"f(q,t)_{pair_str}"][index, :] += corr.real def finalize(self): """ @@ -250,11 +252,12 @@ def finalize(self): nAtomsPerElement = self.configuration["atom_selection"].get_natoms() for pair in self._elementsPairs: + pair_str = "".join(map(str, pair)) ni = nAtomsPerElement[pair[0]] nj = nAtomsPerElement[pair[1]] - self._outputData["f(q,t)_%s%s" % pair][:] /= np.sqrt(ni * nj) - self._outputData["s(q,f)_%s%s" % pair][:] = get_spectrum( - self._outputData["f(q,t)_%s%s" % pair], + self._outputData[f"f(q,t)_{pair_str}"][:] /= np.sqrt(ni * nj) + self._outputData[f"s(q,f)_{pair_str}"][:] = get_spectrum( + self._outputData[f"f(q,t)_{pair_str}"], self.configuration["instrument_resolution"]["time_window"], self.configuration["instrument_resolution"]["time_step"], axis=1, diff --git a/MDANSE/Src/MDANSE/Framework/Jobs/DynamicIncoherentStructureFactor.py b/MDANSE/Src/MDANSE/Framework/Jobs/DynamicIncoherentStructureFactor.py index ef6d2ceb7..0c69b4344 100644 --- a/MDANSE/Src/MDANSE/Framework/Jobs/DynamicIncoherentStructureFactor.py +++ b/MDANSE/Src/MDANSE/Framework/Jobs/DynamicIncoherentStructureFactor.py @@ -153,14 +153,14 @@ def initialize(self): for element in self.configuration["atom_selection"]["unique_names"]: self._outputData.add( - "f(q,t)_%s" % element, + f"f(q,t)_{element}", "SurfaceOutputVariable", (self._nQShells, self._nFrames), axis="q|time", units="au", ) self._outputData.add( - "s(q,f)_%s" % element, + f"s(q,f)_{element}", "SurfaceOutputVariable", (self._nQShells, self._nOmegas), axis="q|omega", @@ -245,7 +245,7 @@ def combine(self, index, disf_per_q_shell): element = self.configuration["atom_selection"]["names"][index] for i, v in enumerate(disf_per_q_shell.values()): - self._outputData["f(q,t)_{}".format(element)][i, :] += v + self._outputData[f"f(q,t)_{element}"][i, :] += v def finalize(self): """ @@ -254,9 +254,9 @@ def finalize(self): nAtomsPerElement = self.configuration["atom_selection"].get_natoms() for element, number in list(nAtomsPerElement.items()): - self._outputData["f(q,t)_%s" % element][:] /= number - self._outputData["s(q,f)_%s" % element][:] = get_spectrum( - self._outputData["f(q,t)_%s" % element], + self._outputData[f"f(q,t)_{element}"][:] /= number + self._outputData[f"s(q,f)_{element}"][:] = get_spectrum( + self._outputData[f"f(q,t)_{element}"], self.configuration["instrument_resolution"]["time_window"], self.configuration["instrument_resolution"]["time_step"], axis=1, diff --git a/MDANSE/Src/MDANSE/Framework/Jobs/ElasticIncoherentStructureFactor.py b/MDANSE/Src/MDANSE/Framework/Jobs/ElasticIncoherentStructureFactor.py index 755c1a55b..face85b9a 100644 --- a/MDANSE/Src/MDANSE/Framework/Jobs/ElasticIncoherentStructureFactor.py +++ b/MDANSE/Src/MDANSE/Framework/Jobs/ElasticIncoherentStructureFactor.py @@ -116,7 +116,7 @@ def initialize(self): for element in self.configuration["atom_selection"]["unique_names"]: self._outputData.add( - "eisf_%s" % element, + f"eisf_{element}", "LineOutputVariable", (self._nQShells,), axis="q", @@ -187,7 +187,7 @@ def combine(self, index, x): # The symbol of the atom. element = self.configuration["atom_selection"]["names"][index] - self._outputData["eisf_%s" % element] += x + self._outputData[f"eisf_{element}"] += x def finalize(self): """ @@ -196,7 +196,7 @@ def finalize(self): nAtomsPerElement = self.configuration["atom_selection"].get_natoms() for element, number in list(nAtomsPerElement.items()): - self._outputData["eisf_%s" % element][:] /= number + self._outputData[f"eisf_{element}"][:] /= number weights = self.configuration["weights"].get_weights() self._outputData["eisf_total"][:] = weight( diff --git a/MDANSE/Src/MDANSE/Framework/Jobs/GaussianDynamicIncoherentStructureFactor.py b/MDANSE/Src/MDANSE/Framework/Jobs/GaussianDynamicIncoherentStructureFactor.py index 5e8ce62d0..dc67d8caa 100644 --- a/MDANSE/Src/MDANSE/Framework/Jobs/GaussianDynamicIncoherentStructureFactor.py +++ b/MDANSE/Src/MDANSE/Framework/Jobs/GaussianDynamicIncoherentStructureFactor.py @@ -151,14 +151,14 @@ def initialize(self): for element in self.configuration["atom_selection"]["unique_names"]: self._outputData.add( - "f(q,t)_%s" % element, + f"f(q,t)_{element}", "SurfaceOutputVariable", (self._nQShells, self._nFrames), axis="q|time", units="au", ) self._outputData.add( - "s(q,f)_%s" % element, + f"s(q,f)_{element}", "SurfaceOutputVariable", (self._nQShells, self._nOmegas), axis="q|omega", @@ -234,7 +234,7 @@ def combine(self, index, x): # The symbol of the atom. element = self.configuration["atom_selection"]["names"][index] - self._outputData["f(q,t)_%s" % element] += x + self._outputData[f"f(q,t)_{element}"] += x def finalize(self): """ @@ -243,9 +243,9 @@ def finalize(self): nAtomsPerElement = self.configuration["atom_selection"].get_natoms() for element, number in nAtomsPerElement.items(): - self._outputData["f(q,t)_%s" % element][:] /= number - self._outputData["s(q,f)_%s" % element][:] = get_spectrum( - self._outputData["f(q,t)_%s" % element], + self._outputData[f"f(q,t)_{element}"][:] /= number + self._outputData[f"s(q,f)_{element}"][:] = get_spectrum( + self._outputData[f"f(q,t)_{element}"], self.configuration["instrument_resolution"]["time_window"], self.configuration["instrument_resolution"]["time_step"], axis=1, diff --git a/MDANSE/Src/MDANSE/Framework/Jobs/GeneralAutoCorrelationFunction.py b/MDANSE/Src/MDANSE/Framework/Jobs/GeneralAutoCorrelationFunction.py index cddda4c8d..be158c6da 100644 --- a/MDANSE/Src/MDANSE/Framework/Jobs/GeneralAutoCorrelationFunction.py +++ b/MDANSE/Src/MDANSE/Framework/Jobs/GeneralAutoCorrelationFunction.py @@ -95,7 +95,7 @@ def initialize(self): # Will store the mean square displacement evolution. for element in self.configuration["atom_selection"]["unique_names"]: self._outputData.add( - "gacf_{}".format(element), + f"gacf_{element}", "LineOutputVariable", (self.configuration["frames"]["number"],), axis="time", @@ -150,7 +150,7 @@ def combine(self, index, x): element = self.configuration["atom_selection"]["names"][index] - self._outputData["gacf_%s" % element] += x + self._outputData[f"gacf_{element}"] += x def finalize(self): """ @@ -161,15 +161,15 @@ def finalize(self): self.configuration["atom_selection"]["n_atoms_per_element"] = nAtomsPerElement for element, number in nAtomsPerElement.items(): - self._outputData["gacf_{}".format(element)] /= number + self._outputData[f"gacf_{element}"] /= number 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( - self._outputData["gacf_%s" % element], axis=0 + self._outputData[f"gacf_{element}"] = normalize( + self._outputData[f"gacf_{element}"], axis=0 ) weights = self.configuration["weights"].get_weights() diff --git a/MDANSE/Src/MDANSE/Framework/Jobs/IJob.py b/MDANSE/Src/MDANSE/Framework/Jobs/IJob.py index f41191ce2..b087e7174 100644 --- a/MDANSE/Src/MDANSE/Framework/Jobs/IJob.py +++ b/MDANSE/Src/MDANSE/Framework/Jobs/IJob.py @@ -63,7 +63,7 @@ def __init__(self, job, message=None): self._message = str(message) - trace.append("\n%s" % self._message) + trace.append(f"\n{self._message}") trace = "\n".join(trace) @@ -83,7 +83,7 @@ def key_generator(keySize, chars=None, prefix=""): key = "".join(random.choice(chars) for _ in range(keySize)) if prefix: - key = "%s_%s" % (prefix, key) + key = f"{prefix}_{key}" return key @@ -103,7 +103,7 @@ def define_unique_name(): Sets a name for the job that is not already in use by another running job. """ - prefix = "%s_%d" % (PLATFORM.username()[:4], PLATFORM.pid()) + prefix = f"{PLATFORM.username()[:4]}_{PLATFORM.pid():d}" # The list of the registered jobs. registeredJobs = [ @@ -197,7 +197,7 @@ def save(cls, jobFile, parameters=None): # The first line contains the call to the python executable. This is necessary for the file to # be autostartable. - f.write("#!%s\n\n" % sys.executable) + f.write(f"#!{sys.executable}\n\n") # Writes the input file header. f.write("########################################################\n") @@ -230,8 +230,8 @@ def save(cls, jobFile, parameters=None): f.write("\n") f.write('if __name__ == "__main__":\n') - f.write(" %s = IJob.create(%r)\n" % (cls.__name__.lower(), cls.__name__)) - f.write(" %s.run(parameters, status=True)\n" % (cls.__name__.lower())) + f.write(f" {cls.__name__.lower()} = IJob.create({cls.__name__!r})\n") + f.write(f" {cls.__name__.lower()}.run(parameters, status=True)\n") f.close() @@ -386,7 +386,7 @@ def run(self, parameters, status=False): """ try: - self._name = "%s_%s" % (self.__class__.__name__, IJob.define_unique_name()) + self._name = f"{self.__class__.__name__}_{IJob.define_unique_name()}" if status and self._status is None: self._status = self._status_constructor(self) @@ -400,7 +400,7 @@ def run(self, parameters, status=False): self._status.state["info"] = str(self) if getattr(self, "numberOfSteps", 0) <= 0: - raise JobError(self, "Invalid number of steps for job %s" % self._name) + raise JobError(self, f"Invalid number of steps for job {self._name}") if "running_mode" in self.configuration: mode = self.configuration["running_mode"]["mode"] @@ -426,26 +426,26 @@ def info(self): def save_template(cls, shortname, classname): if shortname in IJob.subclasses(): raise KeyError( - "A job with %r name is already stored in the registry" % shortname + f"A job with {shortname!r} name is already stored in the registry" ) templateFile = PLATFORM.macros_directory() / f"{classname}.py" try: + label = "label of the class" with templateFile.open("w") as f: - 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',) @@ -455,9 +455,9 @@ class %(classname)s(IJob): # 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): """ @@ -497,12 +497,7 @@ def finalize(self): # The trajectory is closed self.configuration['trajectory']['instance'].close() - ''' - % { - "classname": classname, - "label": "label of the class", - "shortname": shortname, - } +''' ) except IOError: diff --git a/MDANSE/Src/MDANSE/Framework/Jobs/McStasVirtualInstrument.py b/MDANSE/Src/MDANSE/Framework/Jobs/McStasVirtualInstrument.py index 89fdf873d..9cf8acae1 100644 --- a/MDANSE/Src/MDANSE/Framework/Jobs/McStasVirtualInstrument.py +++ b/MDANSE/Src/MDANSE/Framework/Jobs/McStasVirtualInstrument.py @@ -231,15 +231,13 @@ def run_step(self, index): fout.write("# Physical parameters:\n") for k, v in list(self._mcStasPhysicalParameters.items()): - fout.write("# %s %s \n" % (k, v)) + fout.write(f"# {k} {v} \n") - fout.write( - "# Temperature %s \n" % self.configuration["temperature"]["value"] - ) + fout.write(f"# Temperature {self.configuration['temperature']['value']} \n") fout.write("#\n") for var in self.configuration[typ].variables: - fout.write("# %s\n" % var) + fout.write(f"# {var}\n") data = self.configuration[typ][var][:] LOG.info(f"In {typ} the variable {var} has shape {data.shape}") @@ -261,7 +259,7 @@ def run_step(self, index): # + typ # + ".sqw" # ) - sqwInput += "%s=%s " % (typ, fout.name) + sqwInput += f"{typ}={fout.name} " # sys.exit(0) @@ -290,7 +288,7 @@ def run_step(self, index): for line in out.splitlines(): if "ERROR" in line.decode(encoding="utf-8"): - raise McStasError("An error occured during McStas run: %s" % out) + raise McStasError(f"An error occured during McStas run: {out}") out_file = self.mcstas_output_dir / "mcstas_mdanse.mvi" with out_file.open("w") as f: @@ -340,7 +338,7 @@ def unique(self, key, d, value=None): if np.allclose(v, value): return k while key in d: - key = skey + "_%d" % i + key = f"{skey}_{i:d}" i += 1 return key @@ -432,7 +430,7 @@ def save_single(self, FileStruct): "LineOutputVariable", x, xlabel, units="au" ) self._outputData[Title] = IOutputVariable.create( - "LineOutputVariable", y, Title, axis="%s" % xlabel, units="au" + "LineOutputVariable", y, Title, axis=str(xlabel), units="au" ) elif typ == "array_2d": @@ -467,7 +465,7 @@ def save_single(self, FileStruct): title, "SurfaceOutputVariable", I, - axis="%s|%s" % (xlabel, ylabel), + axis=f"{xlabel}|{ylabel}", units="au", main_result=True, partial_result=True, diff --git a/MDANSE/Src/MDANSE/Framework/Jobs/MeanSquareDisplacement.py b/MDANSE/Src/MDANSE/Framework/Jobs/MeanSquareDisplacement.py index b59d04729..320351c6b 100644 --- a/MDANSE/Src/MDANSE/Framework/Jobs/MeanSquareDisplacement.py +++ b/MDANSE/Src/MDANSE/Framework/Jobs/MeanSquareDisplacement.py @@ -123,7 +123,7 @@ def initialize(self): # Will store the mean square displacement evolution. for element in self.configuration["atom_selection"]["unique_names"]: self._outputData.add( - "msd_%s" % element, + f"msd_{element}", "LineOutputVariable", (self.configuration["frames"]["n_frames"],), axis="time", @@ -186,7 +186,7 @@ def combine(self, index, result): # The symbol of the atom. element = self.configuration["atom_selection"]["names"][index] - self._outputData["msd_%s" % element] += result + self._outputData[f"msd_{element}"] += result def finalize(self): """ @@ -196,7 +196,7 @@ def finalize(self): # The MSDs per element are averaged. nAtomsPerElement = self.configuration["atom_selection"].get_natoms() for element, number in list(nAtomsPerElement.items()): - self._outputData["msd_%s" % element] /= number + self._outputData[f"msd_{element}"] /= number weights = self.configuration["weights"].get_weights() msdTotal = weight(weights, self._outputData, nAtomsPerElement, 1, "msd_%s") diff --git a/MDANSE/Src/MDANSE/Framework/Jobs/NeutronDynamicTotalStructureFactor.py b/MDANSE/Src/MDANSE/Framework/Jobs/NeutronDynamicTotalStructureFactor.py index cb827cde9..a69acaecb 100644 --- a/MDANSE/Src/MDANSE/Framework/Jobs/NeutronDynamicTotalStructureFactor.py +++ b/MDANSE/Src/MDANSE/Framework/Jobs/NeutronDynamicTotalStructureFactor.py @@ -198,15 +198,16 @@ def initialize(self): ) ) for pair in self._elementsPairs: + pair_str = "".join(map(str, pair)) if ( - "f(q,t)_{}{}".format(*pair) + f"f(q,t)_{pair_str}" not in self.configuration["dcsf_input_file"]["instance"] ): raise NeutronDynamicTotalStructureFactorError( "Missing f(q,t) in dcsf input file" ) if ( - "s(q,f)_{}{}".format(*pair) + f"s(q,f)_{pair_str}" not in self.configuration["dcsf_input_file"]["instance"] ): raise NeutronDynamicTotalStructureFactorError( @@ -215,14 +216,14 @@ def initialize(self): for element in self.configuration["atom_selection"]["unique_names"]: if ( - "f(q,t)_{}".format(element) + f"f(q,t)_{element}" not in self.configuration["disf_input_file"]["instance"] ): raise NeutronDynamicTotalStructureFactorError( "Missing f(q,t) in disf input file" ) if ( - "s(q,f)_{}".format(element) + f"s(q,f)_{element}" not in self.configuration["disf_input_file"]["instance"] ): raise NeutronDynamicTotalStructureFactorError( @@ -230,35 +231,31 @@ def initialize(self): ) for element in self.configuration["atom_selection"]["unique_names"]: - fqt = self.configuration["disf_input_file"]["instance"][ - "f(q,t)_{}".format(element) - ] - sqf = self.configuration["disf_input_file"]["instance"][ - "s(q,f)_{}".format(element) - ] + fqt = self.configuration["disf_input_file"]["instance"][f"f(q,t)_{element}"] + sqf = self.configuration["disf_input_file"]["instance"][f"s(q,f)_{element}"] self._outputData.add( - "f(q,t)_inc_%s" % element, + f"f(q,t)_inc_{element}", "SurfaceOutputVariable", fqt, axis="q|time", units="au", ) self._outputData.add( - "s(q,f)_inc_%s" % element, + f"s(q,f)_inc_{element}", "SurfaceOutputVariable", sqf, axis="q|omega", units="nm2/ps", ) self._outputData.add( - "f(q,t)_inc_weighted_%s" % element, + f"f(q,t)_inc_weighted_{element}", "SurfaceOutputVariable", fqt.shape, axis="q|time", units="au", ) self._outputData.add( - "s(q,f)_inc_weighted_%s" % element, + f"s(q,f)_inc_weighted_{element}", "SurfaceOutputVariable", sqf.shape, axis="q|omega", @@ -266,35 +263,36 @@ def initialize(self): ) for pair in self._elementsPairs: + pair_str = "".join(map(str, pair)) fqt = self.configuration["dcsf_input_file"]["instance"][ - "f(q,t)_{}{}".format(*pair) + f"f(q,t)_{pair_str}" ] sqf = self.configuration["dcsf_input_file"]["instance"][ - "s(q,f)_{}{}".format(*pair) + f"s(q,f)_{pair_str}" ] self._outputData.add( - "f(q,t)_coh_%s%s" % pair, + f"f(q,t)_coh_{pair_str}", "SurfaceOutputVariable", fqt, axis="q|time", units="au", ) self._outputData.add( - "s(q,f)_coh_%s%s" % pair, + f"s(q,f)_coh_{pair_str}", "SurfaceOutputVariable", sqf, axis="q|omega", units="nm2/ps", ) self._outputData.add( - "f(q,t)_coh_weighted_%s%s" % pair, + f"f(q,t)_coh_weighted_{pair_str}", "SurfaceOutputVariable", fqt.shape, axis="q|time", units="au", ) self._outputData.add( - "s(q,f)_coh_weighted_%s%s" % pair, + f"s(q,f)_coh_weighted_{pair_str}", "SurfaceOutputVariable", sqf.shape, axis="q|omega", @@ -389,6 +387,7 @@ def finalize(self): # Compute coherent functions and structure factor for pair in self._elementsPairs: + pair_str = "".join(map(str, pair)) bi = self.configuration["trajectory"]["instance"].get_atom_property( pair[0], "b_coherent" ) @@ -400,31 +399,31 @@ def finalize(self): ci = ni / nTotalAtoms cj = nj / nTotalAtoms - self._outputData["f(q,t)_coh_weighted_%s%s" % pair][:] = ( - self._outputData["f(q,t)_coh_%s%s" % pair][:] + self._outputData[f"f(q,t)_coh_weighted_{pair_str}"][:] = ( + self._outputData[f"f(q,t)_coh_{pair_str}"][:] * np.sqrt(ci * cj) * bi * bj ) - self._outputData["s(q,f)_coh_weighted_%s%s" % pair][:] = ( - self._outputData["s(q,f)_coh_%s%s" % pair][:] + self._outputData[f"s(q,f)_coh_weighted_{pair_str}"][:] = ( + self._outputData[f"s(q,f)_coh_{pair_str}"][:] * np.sqrt(ci * cj) * bi * bj ) if pair[0] == pair[1]: # Add a factor 2 if the two elements are different self._outputData["f(q,t)_coh_total"][:] += self._outputData[ - "f(q,t)_coh_weighted_%s%s" % pair + f"f(q,t)_coh_weighted_{pair_str}" ][:] self._outputData["s(q,f)_coh_total"][:] += self._outputData[ - "s(q,f)_coh_weighted_%s%s" % pair + f"s(q,f)_coh_weighted_{pair_str}" ][:] else: self._outputData["f(q,t)_coh_total"][:] += ( - 2 * self._outputData["f(q,t)_coh_weighted_%s%s" % pair][:] + 2 * self._outputData[f"f(q,t)_coh_weighted_{pair_str}"][:] ) self._outputData["s(q,f)_coh_total"][:] += ( - 2 * self._outputData["s(q,f)_coh_weighted_%s%s" % pair][:] + 2 * self._outputData[f"s(q,f)_coh_weighted_{pair_str}"][:] ) # Compute incoherent functions and structure factor @@ -435,18 +434,18 @@ def finalize(self): ni = nAtomsPerElement[element] ci = ni / nTotalAtoms - self._outputData["f(q,t)_inc_weighted_%s" % element][:] = ( - self._outputData["f(q,t)_inc_%s" % element][:] * ci * bi + self._outputData[f"f(q,t)_inc_weighted_{element}"][:] = ( + self._outputData[f"f(q,t)_inc_{element}"][:] * ci * bi ) - self._outputData["s(q,f)_inc_weighted_%s" % element][:] = ( - self._outputData["s(q,f)_inc_%s" % element][:] * ci * bi + self._outputData[f"s(q,f)_inc_weighted_{element}"][:] = ( + self._outputData[f"s(q,f)_inc_{element}"][:] * ci * bi ) self._outputData["f(q,t)_inc_total"][:] += self._outputData[ - "f(q,t)_inc_weighted_%s" % element + f"f(q,t)_inc_weighted_{element}" ][:] self._outputData["s(q,f)_inc_total"][:] += self._outputData[ - "s(q,f)_inc_weighted_%s" % element + f"s(q,f)_inc_weighted_{element}" ][:] # Compute total F(Q,t) = inc + coh diff --git a/MDANSE/Src/MDANSE/Framework/Jobs/PairDistributionFunction.py b/MDANSE/Src/MDANSE/Framework/Jobs/PairDistributionFunction.py index 5a78dfeba..9f5363cea 100644 --- a/MDANSE/Src/MDANSE/Framework/Jobs/PairDistributionFunction.py +++ b/MDANSE/Src/MDANSE/Framework/Jobs/PairDistributionFunction.py @@ -63,21 +63,21 @@ def finalize(self): for x, y in self._elementsPairs: for i in ["pdf", "rdf", "tcf"]: self._outputData.add( - "%s_intra_%s%s" % (i, x, y), + f"{i}_intra_{x}{y}", "LineOutputVariable", (npoints,), axis="r", units="au", ) self._outputData.add( - "%s_inter_%s%s" % (i, x, y), + f"{i}_inter_{x}{y}", "LineOutputVariable", (npoints,), axis="r", units="au", ) self._outputData.add( - "%s_total_%s%s" % (i, x, y), + f"{i}_total_{x}{y}", "LineOutputVariable", (npoints,), axis="r", @@ -86,21 +86,21 @@ def finalize(self): for i in ["pdf", "rdf", "tcf"]: self._outputData.add( - "%s_intra_total" % i, + f"{i}_intra_total", "LineOutputVariable", (npoints,), axis="r", units="au", ) self._outputData.add( - "%s_inter_total" % i, + f"{i}_inter_total", "LineOutputVariable", (npoints,), axis="r", units="au", ) self._outputData.add( - "%s_total" % i, "LineOutputVariable", (npoints,), axis="r", units="au" + f"{i}_total", "LineOutputVariable", (npoints,), axis="r", units="au" ) nFrames = self.configuration["frames"]["number"] @@ -138,11 +138,11 @@ def finalize(self): for i, pdf in zip( ["intra", "inter", "total"], [pdf_intra, pdf_inter, pdf_total] ): - self._outputData["pdf_%s_%s%s" % (i, pair[0], pair[1])][:] = pdf - self._outputData["rdf_%s_%s%s" % (i, pair[0], pair[1])][:] = ( + self._outputData[f"pdf_{i}_{pair[0]}{pair[1]}"][:] = pdf + self._outputData[f"rdf_{i}_{pair[0]}{pair[1]}"][:] = ( shellSurfaces * self.averageDensity * pdf ) - self._outputData["tcf_%s_%s%s" % (i, pair[0], pair[1])][:] = ( + self._outputData[f"tcf_{i}_{pair[0]}{pair[1]}"][:] = ( densityFactor * self.averageDensity * (pdf if i == "intra" else pdf - 1) @@ -156,13 +156,13 @@ def finalize(self): self._outputData, nAtomsPerElement, 2, - "pdf{}_%s%s".format(i if i else "_total"), + f"pdf{i if i else '_total'}_%s%s", ) - self._outputData["pdf%s_total" % i][:] = pdf - self._outputData["rdf%s_total" % i][:] = ( + self._outputData[f"pdf{i}_total"][:] = pdf + self._outputData[f"rdf{i}_total"][:] = ( shellSurfaces * self.averageDensity * pdf ) - self._outputData["tcf%s_total" % i][:] = ( + self._outputData[f"tcf{i}_total"][:] = ( densityFactor * self.averageDensity * (pdf if i == "_intra" else pdf - 1) diff --git a/MDANSE/Src/MDANSE/Framework/Jobs/PositionAutoCorrelationFunction.py b/MDANSE/Src/MDANSE/Framework/Jobs/PositionAutoCorrelationFunction.py index 1143f0f3f..ec2cb62ea 100644 --- a/MDANSE/Src/MDANSE/Framework/Jobs/PositionAutoCorrelationFunction.py +++ b/MDANSE/Src/MDANSE/Framework/Jobs/PositionAutoCorrelationFunction.py @@ -105,7 +105,7 @@ def initialize(self): # Will store the mean square displacement evolution. for element in self.configuration["atom_selection"]["unique_names"]: self._outputData.add( - "pacf_%s" % element, + f"pacf_{element}", "LineOutputVariable", (self.configuration["frames"]["n_frames"],), axis="time", @@ -160,7 +160,7 @@ def combine(self, index, x): element = self.configuration["atom_selection"]["names"][index] # The MSD for element |symbol| is updated. - self._outputData["pacf_%s" % element] += x + self._outputData[f"pacf_{element}"] += x def finalize(self): """ @@ -171,15 +171,15 @@ def finalize(self): self.configuration["atom_selection"]["n_atoms_per_element"] = nAtomsPerElement for element, number in list(nAtomsPerElement.items()): - self._outputData["pacf_%s" % element] /= number + self._outputData[f"pacf_{element}"] /= number if self.configuration["normalize"]["value"]: for element in list(nAtomsPerElement.keys()): - if self._outputData["pacf_%s" % element][0] == 0: + if self._outputData[f"pacf_{element}"][0] == 0: raise ValueError("The normalization factor is equal to zero !!!") else: - self._outputData["pacf_%s" % element] = normalize( - self._outputData["pacf_%s" % element], axis=0 + self._outputData[f"pacf_{element}"] = normalize( + self._outputData[f"pacf_{element}"], axis=0 ) weights = self.configuration["weights"].get_weights() diff --git a/MDANSE/Src/MDANSE/Framework/Jobs/PositionPowerSpectrum.py b/MDANSE/Src/MDANSE/Framework/Jobs/PositionPowerSpectrum.py index 28989ade7..181871998 100644 --- a/MDANSE/Src/MDANSE/Framework/Jobs/PositionPowerSpectrum.py +++ b/MDANSE/Src/MDANSE/Framework/Jobs/PositionPowerSpectrum.py @@ -122,14 +122,14 @@ def initialize(self): for element in self.configuration["atom_selection"]["unique_names"]: self._outputData.add( - "pacf_%s" % element, + f"pacf_{element}", "LineOutputVariable", (self.configuration["frames"]["n_frames"],), axis="time", units="nm2", ) self._outputData.add( - "pps_%s" % element, + f"pps_{element}", "LineOutputVariable", (instrResolution["n_romegas"],), axis="romega", @@ -202,7 +202,7 @@ def combine(self, index, x): # The symbol of the atom. element = self.configuration["atom_selection"]["names"][index] - self._outputData["pacf_%s" % element] += x + self._outputData[f"pacf_{element}"] += x def finalize(self): """ @@ -211,9 +211,9 @@ def finalize(self): nAtomsPerElement = self.configuration["atom_selection"].get_natoms() for element, number in nAtomsPerElement.items(): - self._outputData["pacf_%s" % element][:] /= number - self._outputData["pps_%s" % element][:] = get_spectrum( - self._outputData["pacf_%s" % element], + self._outputData[f"pacf_{element}"][:] /= number + self._outputData[f"pps_{element}"][:] = get_spectrum( + self._outputData[f"pacf_{element}"], self.configuration["instrument_resolution"]["time_window"], self.configuration["instrument_resolution"]["time_step"], fft="rfft", diff --git a/MDANSE/Src/MDANSE/Framework/Jobs/RigidBodyTrajectory.py b/MDANSE/Src/MDANSE/Framework/Jobs/RigidBodyTrajectory.py index 1aa6682ae..ba4e25af6 100644 --- a/MDANSE/Src/MDANSE/Framework/Jobs/RigidBodyTrajectory.py +++ b/MDANSE/Src/MDANSE/Framework/Jobs/RigidBodyTrajectory.py @@ -90,8 +90,8 @@ def initialize(self): ): raise JobError( self, - "Invalid reference frame. Must be an integer in [%d,%d[" - % (0, self.configuration["trajectory"]["length"]), + "Invalid reference frame. Must be an integer in " + f"[{0},{self.configuration['trajectory']['length']}[", ) self._quaternions = np.zeros( @@ -260,10 +260,7 @@ def finalize(self): for comp in range(self.configuration["atom_selection"]["selection_length"]): aIndexes = self.configuration["atom_selection"]["indices"][comp] - outputFile.attrs["info"] += "Group %s: %s\n" % ( - comp, - [index for index in aIndexes], - ) + outputFile.attrs["info"] += f"Group {comp}: {list(aIndexes)}\n" quaternions[comp, :, :] = self._quaternions[comp, :, :] coms[comp, :, :] = self._coms[comp, :, :] diff --git a/MDANSE/Src/MDANSE/Framework/Jobs/RootMeanSquareDeviation.py b/MDANSE/Src/MDANSE/Framework/Jobs/RootMeanSquareDeviation.py index 1ceeb2001..40dad188a 100644 --- a/MDANSE/Src/MDANSE/Framework/Jobs/RootMeanSquareDeviation.py +++ b/MDANSE/Src/MDANSE/Framework/Jobs/RootMeanSquareDeviation.py @@ -93,7 +93,7 @@ def initialize(self): # Will initially store the mean square deviation before appling the root for element in self.configuration["atom_selection"]["unique_names"]: self._outputData.add( - "rmsd_{}".format(element), + f"rmsd_{element}", "LineOutputVariable", (self.configuration["frames"]["number"],), axis="time", @@ -146,7 +146,7 @@ def combine(self, index, x): element = self.configuration["atom_selection"]["names"][index] - self._outputData["rmsd_%s" % element] += x + self._outputData[f"rmsd_{element}"] += x self._outputData["rmsd_all"] += x def finalize(self): @@ -156,11 +156,11 @@ def finalize(self): nAtomsPerElement = self.configuration["atom_selection"].get_natoms() for element, number in nAtomsPerElement.items(): - self._outputData["rmsd_{}".format(element)] /= number + self._outputData[f"rmsd_{element}"] /= number for element, number in nAtomsPerElement.items(): - self._outputData["rmsd_{}".format(element)] = np.sqrt( - self._outputData["rmsd_{}".format(element)] + self._outputData[f"rmsd_{element}"] = np.sqrt( + self._outputData[f"rmsd_{element}"] ) self._outputData["rmsd_all"] /= self.configuration[ diff --git a/MDANSE/Src/MDANSE/Framework/Jobs/StaticStructureFactor.py b/MDANSE/Src/MDANSE/Framework/Jobs/StaticStructureFactor.py index 2c9445f0a..9b0321681 100644 --- a/MDANSE/Src/MDANSE/Framework/Jobs/StaticStructureFactor.py +++ b/MDANSE/Src/MDANSE/Framework/Jobs/StaticStructureFactor.py @@ -142,22 +142,23 @@ def finalize(self): nAtomsPerElement = self.configuration["atom_selection"].get_natoms() for pair in self._elementsPairs: + pair_str = "".join(map(str, pair)) self._outputData.add( - "ssf_intra_%s%s" % pair, + f"ssf_intra_{pair_str}", "LineOutputVariable", (nq,), axis="q", units="au", ) self._outputData.add( - "ssf_inter_%s%s" % pair, + f"ssf_inter_{pair_str}", "LineOutputVariable", (nq,), axis="q", units="au", ) self._outputData.add( - "ssf_total_%s%s" % pair, + f"ssf_total_{pair_str}", "LineOutputVariable", (nq,), axis="q", @@ -182,15 +183,15 @@ def finalize(self): pdfIntra = self.hIntra[idi, idj, :] / fact pdfInter = self.hInter[idi, idj, :] / fact - self._outputData["ssf_intra_%s%s" % pair][:] = ( + self._outputData[f"ssf_intra_{pair_str}"][:] = ( fact1 * np.sum((r**2) * pdfIntra * sincqr, axis=1) * dr ) - self._outputData["ssf_inter_%s%s" % pair][:] = ( + self._outputData[f"ssf_inter_{pair_str}"][:] = ( 1.0 + fact1 * np.sum((r**2) * (pdfInter - 1.0) * sincqr, axis=1) * dr ) - self._outputData["ssf_total_%s%s" % pair][:] = ( - self._outputData["ssf_intra_%s%s" % pair][:] - + self._outputData["ssf_inter_%s%s" % pair][:] + self._outputData[f"ssf_total_{pair_str}"][:] = ( + self._outputData[f"ssf_intra_{pair_str}"][:] + + self._outputData[f"ssf_inter_{pair_str}"][:] ) self._outputData.add( diff --git a/MDANSE/Src/MDANSE/Framework/Jobs/StructureFactorFromScatteringFunction.py b/MDANSE/Src/MDANSE/Framework/Jobs/StructureFactorFromScatteringFunction.py index f8b706c79..dfbb18cf9 100644 --- a/MDANSE/Src/MDANSE/Framework/Jobs/StructureFactorFromScatteringFunction.py +++ b/MDANSE/Src/MDANSE/Framework/Jobs/StructureFactorFromScatteringFunction.py @@ -100,7 +100,7 @@ def initialize(self): ) suffix = k[7:] self._outputData.add( - "s(q,f)_%s" % suffix, + f"s(q,f)_{suffix}", "SurfaceOutputVariable", (nQVectors, nOmegas), axis="q|omega", @@ -108,7 +108,7 @@ def initialize(self): main_result=True, partial_result=True, ) - self._outputData["s(q,f)_%s" % suffix][:] = get_spectrum( + self._outputData[f"s(q,f)_{suffix}"][:] = get_spectrum( v[:], self.configuration["instrument_resolution"]["time_window"], self.configuration["instrument_resolution"]["time_step"], diff --git a/MDANSE/Src/MDANSE/Framework/Jobs/VanHoveFunctionDistinct.py b/MDANSE/Src/MDANSE/Framework/Jobs/VanHoveFunctionDistinct.py index 7dfd56178..a0aa77df3 100644 --- a/MDANSE/Src/MDANSE/Framework/Jobs/VanHoveFunctionDistinct.py +++ b/MDANSE/Src/MDANSE/Framework/Jobs/VanHoveFunctionDistinct.py @@ -315,21 +315,21 @@ def initialize(self): ) for x, y in self._elementsPairs: self._outputData.add( - "g(r,t)_intra_%s%s" % (x, y), + f"g(r,t)_intra_{x}{y}", "SurfaceOutputVariable", (self.n_mid_points, self.numberOfSteps), axis="r|time", units="au", ) self._outputData.add( - "g(r,t)_inter_%s%s" % (x, y), + f"g(r,t)_inter_{x}{y}", "SurfaceOutputVariable", (self.n_mid_points, self.numberOfSteps), axis="r|time", units="au", ) self._outputData.add( - "g(r,t)_total_%s%s" % (x, y), + f"g(r,t)_total_{x}{y}", "SurfaceOutputVariable", (self.n_mid_points, self.numberOfSteps), axis="r|time", @@ -484,9 +484,7 @@ def finalize(self): ["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])][ - ... - ] = van_hove + self._outputData[f"g(r,t)_{i}_{pair[0]}{pair[1]}"][...] = van_hove weights = self.configuration["weights"].get_weights() for i in ["_intra", "_inter", ""]: @@ -495,9 +493,9 @@ def finalize(self): self._outputData, nAtomsPerElement, 2, - "g(r,t){}_%s%s".format(i if i else "_total"), + f"g(r,t){i if i else '_total'}_%s%s", ) - self._outputData["g(r,t)%s_total" % i][...] = pdf + self._outputData[f"g(r,t){i}_total"][...] = pdf self._outputData.write( self.configuration["output_files"]["root"], diff --git a/MDANSE/Src/MDANSE/Framework/Jobs/VanHoveFunctionSelf.py b/MDANSE/Src/MDANSE/Framework/Jobs/VanHoveFunctionSelf.py index 16bceccbf..9d7b0749a 100644 --- a/MDANSE/Src/MDANSE/Framework/Jobs/VanHoveFunctionSelf.py +++ b/MDANSE/Src/MDANSE/Framework/Jobs/VanHoveFunctionSelf.py @@ -182,14 +182,14 @@ def initialize(self): ) for element in self.selectedElements: self._outputData.add( - "g(r,t)_%s" % element, + f"g(r,t)_{element}", "SurfaceOutputVariable", (self.n_mid_points, self.n_frames), axis="r|time", units="au", ) self._outputData.add( - "4_pi_r2_g(r,t)_%s" % element, + f"4_pi_r2_g(r,t)_{element}", "SurfaceOutputVariable", (self.n_mid_points, self.n_frames), axis="r|time", @@ -274,8 +274,8 @@ def combine(self, atm_index: int, histogram: np.ndarray): time t0 and t0 + t. """ element = self.configuration["atom_selection"]["names"][atm_index] - self._outputData["g(r,t)_{}".format(element)][:] += histogram - self._outputData["4_pi_r2_g(r,t)_{}".format(element)][:] += histogram + self._outputData[f"g(r,t)_{element}"][:] += histogram + self._outputData[f"4_pi_r2_g(r,t)_{element}"][:] += histogram def finalize(self): """Using the distance histograms calculate, normalize and save the @@ -284,10 +284,10 @@ def finalize(self): nAtomsPerElement = self.configuration["atom_selection"].get_natoms() for element, number in list(nAtomsPerElement.items()): - self._outputData["g(r,t)_%s" % element][:] /= ( + self._outputData[f"g(r,t)_{element}"][:] /= ( self.shell_volumes[:, np.newaxis] * number**2 * self.n_configs ) - self._outputData["4_pi_r2_g(r,t)_%s" % element][:] /= ( + self._outputData[f"4_pi_r2_g(r,t)_{element}"][:] /= ( number**2 * self.n_configs * self.configuration["r_values"]["step"] ) diff --git a/MDANSE/Src/MDANSE/Framework/Jobs/VelocityAutoCorrelationFunction.py b/MDANSE/Src/MDANSE/Framework/Jobs/VelocityAutoCorrelationFunction.py index dbe8c64db..272a5df1d 100644 --- a/MDANSE/Src/MDANSE/Framework/Jobs/VelocityAutoCorrelationFunction.py +++ b/MDANSE/Src/MDANSE/Framework/Jobs/VelocityAutoCorrelationFunction.py @@ -123,7 +123,7 @@ def initialize(self): for element in self.configuration["atom_selection"]["unique_names"]: self._outputData.add( - "vacf_%s" % element, + f"vacf_{element}", "LineOutputVariable", (self.configuration["frames"]["n_frames"],), axis="time", @@ -205,7 +205,7 @@ def combine(self, index, x): # The symbol of the atom. element = self.configuration["atom_selection"]["names"][index] - self._outputData["vacf_%s" % element] += x + self._outputData[f"vacf_{element}"] += x def finalize(self): """ @@ -214,7 +214,7 @@ def finalize(self): nAtomsPerElement = self.configuration["atom_selection"].get_natoms() for element, number in nAtomsPerElement.items(): - self._outputData["vacf_%s" % element] /= number + self._outputData[f"vacf_{element}"] /= number weights = self.configuration["weights"].get_weights() @@ -223,8 +223,8 @@ def finalize(self): if self.configuration["normalize"]["value"]: for element in nAtomsPerElement.keys(): - self._outputData["vacf_%s" % element] = normalize( - self._outputData["vacf_%s" % element], axis=0 + self._outputData[f"vacf_{element}"] = normalize( + self._outputData[f"vacf_{element}"], axis=0 ) self._outputData["vacf_total"] = normalize( self._outputData["vacf_total"], axis=0 diff --git a/MDANSE/Src/MDANSE/Framework/Jobs/XRayStaticStructureFactor.py b/MDANSE/Src/MDANSE/Framework/Jobs/XRayStaticStructureFactor.py index 5da649cec..3e14db0c6 100644 --- a/MDANSE/Src/MDANSE/Framework/Jobs/XRayStaticStructureFactor.py +++ b/MDANSE/Src/MDANSE/Framework/Jobs/XRayStaticStructureFactor.py @@ -135,22 +135,23 @@ def finalize(self): nAtomsPerElement = self.configuration["atom_selection"].get_natoms() for pair in self._elementsPairs: + pair_str = "".join(map(str, pair)) self._outputData.add( - "xssf_intra_%s%s" % pair, + f"xssf_intra_{pair_str}", "LineOutputVariable", (nq,), axis="q", units="au", ) self._outputData.add( - "xssf_inter_%s%s" % pair, + f"xssf_inter_{pair_str}", "LineOutputVariable", (nq,), axis="q", units="au", ) self._outputData.add( - "xssf_total_%s%s" % pair, + f"xssf_total_{pair_str}", "LineOutputVariable", (nq,), axis="q", @@ -175,15 +176,15 @@ def finalize(self): pdfIntra = self.hIntra[idi, idj, :] / fact pdfInter = self.hInter[idi, idj, :] / fact - self._outputData["xssf_intra_%s%s" % pair][:] = ( + self._outputData[f"xssf_intra_{pair_str}"][:] = ( fact1 * np.sum((r**2) * pdfIntra * sincqr, axis=1) * dr ) - self._outputData["xssf_inter_%s%s" % pair][:] = ( + self._outputData[f"xssf_inter_{pair_str}"][:] = ( 1.0 + fact1 * np.sum((r**2) * (pdfInter - 1.0) * sincqr, axis=1) * dr ) - self._outputData["xssf_total_%s%s" % pair][:] = ( - self._outputData["xssf_intra_%s%s" % pair][:] - + self._outputData["xssf_inter_%s%s" % pair][:] + self._outputData[f"xssf_total_{pair_str}"][:] = ( + self._outputData[f"xssf_intra_{pair_str}"][:] + + self._outputData[f"xssf_inter_{pair_str}"][:] ) self._outputData.add( @@ -209,12 +210,12 @@ def finalize(self): ) xssfIntra = weight( - asf, self._outputData, nAtomsPerElement, 2, "xssf_intra_%s%s" + asf, self._outputData, nAtomsPerElement, 2, f"xssf_intra_%s%s" ) self._outputData["xssf_intra"][:] = xssfIntra xssfInter = weight( - asf, self._outputData, nAtomsPerElement, 2, "xssf_inter_%s%s" + asf, self._outputData, nAtomsPerElement, 2, f"xssf_inter_%s%s" ) self._outputData["xssf_inter"][:] = xssfInter diff --git a/MDANSE/Src/MDANSE/Framework/OutputVariables/IOutputVariable.py b/MDANSE/Src/MDANSE/Framework/OutputVariables/IOutputVariable.py index 35508e6e0..a8d78540d 100644 --- a/MDANSE/Src/MDANSE/Framework/OutputVariables/IOutputVariable.py +++ b/MDANSE/Src/MDANSE/Framework/OutputVariables/IOutputVariable.py @@ -82,8 +82,7 @@ def __new__( if value.ndim != cls._nDimensions: raise OutputVariableError( - "Invalid number of dimensions for an output variable of type %r" - % cls.name + f"Invalid number of dimensions for an output variable of type {cls.name!r}" ) # Input array is an already formed ndarray instance @@ -118,13 +117,8 @@ def __array_finalize__(self, obj): self.units = getattr(obj, "units", "unitless") def info(self): - info = [] - - info.append("# variable name: %s" % self.varname) - info.append("# \ttype: %s" % self.__class__.__name__) - info.append("# \taxis: %s" % str(self.axis)) - info.append("# \tunits: %s" % self.units) - - info = "\n".join(info) - - return info + return f"""\ +# variable name: {self.varname} +# \ttype: {self.__class__.__name__} +# \taxis: {self.axis!s} +# \tunits: {self.units}""" diff --git a/MDANSE/Src/MDANSE/Framework/Units.py b/MDANSE/Src/MDANSE/Framework/Units.py index b8dab49fe..5083435d2 100644 --- a/MDANSE/Src/MDANSE/Framework/Units.py +++ b/MDANSE/Src/MDANSE/Framework/Units.py @@ -95,11 +95,11 @@ def _parse_unit(iunit): iunit = iunit[i:] break else: - raise UnitError("The unit {} is unknown".format(iunit)) + raise UnitError(f"The unit {iunit} is unknown") if prefix: if prefix not in _PREFIXES: - raise UnitError("The prefix {} is unknown".format(prefix)) + raise UnitError(f"The prefix {prefix} is unknown") prefix = _PREFIXES[prefix] else: prefix = 1.0 @@ -150,7 +150,7 @@ def _str_to_unit(s): return unit else: - raise UnitError("Invalid unit: {}".format(s)) + raise UnitError(f"Invalid unit: {s}") class _Unit(object): @@ -389,55 +389,37 @@ def __sub__(self, other): def __str__(self): unit = copy.copy(self) - fmt = "{:%s}" % self._format - if self._ounit is None: - s = fmt.format(unit._factor) + s = format(unit._factor, self._format) positive_units = [] negative_units = [] for uname, uval in zip(_UNAMES, unit._dimension): if uval == 0: continue - elif uval > 0: - if uval == 1: - positive_units.append("{:s}".format(uname)) - else: - if isinstance(uval, int): - positive_units.append("{:s}{:d}".format(uname, int(uval))) - else: - positive_units.append("{:s}{}".format(uname, uval)) - elif uval < 0: - if uval == -1: - negative_units.append("{:s}".format(uname)) - else: - if isinstance(uval, int): - negative_units.append("{:s}{:d}".format(uname, int(-uval))) - else: - negative_units.append("{:s}{}".format(uname, -uval)) - - positive_units_str = "" - if positive_units: - positive_units_str = " ".join(positive_units) - - negative_units_str = "" - if negative_units: - negative_units_str = " ".join(negative_units) + + ref = positive_units if uval > 0 else negative_units + unit = str(uname) + ( + format(abs(uval), "d") if isinstance(uval, int) else str(uval) + ) + ref.append(unit) + + positive_units_str = " ".join(positive_units) + negative_units_str = " ".join(negative_units) if positive_units_str: - s += " {:s}".format(positive_units_str) + s += f" {positive_units_str}" if negative_units_str: if not positive_units_str: s += " 1" - s += " / {}".format(negative_units_str) + s += f" / {negative_units_str}" else: u = copy.deepcopy(self) u._div_by(self._out_factor) - s = fmt.format(u._factor) - s += " {}".format(self._ounit) + s = f"{u._factor:{self._format}} {self._ounit}" return s diff --git a/MDANSE/Src/MDANSE/Framework/UserDefinitionStore.py b/MDANSE/Src/MDANSE/Framework/UserDefinitionStore.py index 49c9cbee7..ac67c556b 100644 --- a/MDANSE/Src/MDANSE/Framework/UserDefinitionStore.py +++ b/MDANSE/Src/MDANSE/Framework/UserDefinitionStore.py @@ -99,8 +99,8 @@ 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 2a22fddb4..40943035e 100644 --- a/MDANSE/Src/MDANSE/IO/FortranFormat.py +++ b/MDANSE/Src/MDANSE/IO/FortranFormat.py @@ -216,15 +216,15 @@ def _output(self): elif type == "I": s = repr(value) elif type == "D": - s = ("%" + repr(length) + "." + repr(fraction) + "e") % value + s = f"{value:{length!r}.{fraction!r}e}" n = s.find("e") s = s[:n] + "D" + s[n + 1 :] elif type == "E": - s = ("%" + repr(length) + "." + repr(fraction) + "e") % value + s = f"{value:{length!r}.{fraction!r}e}" elif type == "F": - s = ("%" + repr(length) + "." + repr(fraction) + "f") % value + s = f"{value:{length!r}.{fraction!r}f}" elif type == "G": - s = ("%" + repr(length) + "." + repr(fraction) + "g") % value + s = f"{value:{length!r}.{fraction!r}g}" else: raise ValueError("Not yet implemented") s = s.upper() diff --git a/MDANSE/Src/MDANSE/IO/HDF.py b/MDANSE/Src/MDANSE/IO/HDF.py index 5efc26439..d48a15e9a 100644 --- a/MDANSE/Src/MDANSE/IO/HDF.py +++ b/MDANSE/Src/MDANSE/IO/HDF.py @@ -29,9 +29,9 @@ def find_numeric_variables(variables, group): find_numeric_variables(variables, var) else: if var.parent.name == "/": - path = "/{}".format(var_key) + path = f"/{var_key}" else: - path = "{}/{}".format(var.parent.name, var_key) + path = f"{var.parent.name}/{var_key}" if not np.issubdtype(var.dtype, np.number): continue diff --git a/MDANSE/Src/MDANSE/IO/HDF5.py b/MDANSE/Src/MDANSE/IO/HDF5.py index 28f0a0685..61d41a48d 100644 --- a/MDANSE/Src/MDANSE/IO/HDF5.py +++ b/MDANSE/Src/MDANSE/IO/HDF5.py @@ -56,9 +56,9 @@ def find_numeric_variables(var_dict, group): find_numeric_variables(var_dict, var) else: if var.parent.name == "/": - path = "/{}".format(var_key) + path = f"/{var_key}" else: - path = "{}/{}".format(var.parent.name, var_key) + path = f"{var.parent.name}/{var_key}" # Non-numeric variables are not supported by the plotter if not np.issubdtype(var.dtype, np.number): @@ -70,7 +70,7 @@ def find_numeric_variables(var_dict, group): comp = 1 while var_key in var_dict: - var_key = "{:s}_{:d}".format(var_key, comp) + var_key = f"{var_key:s}_{comp:d}" comp += 1 var_dict[var_key] = (path, HDFFileVariable(var)) diff --git a/MDANSE/Src/MDANSE/Mathematics/Arithmetic.py b/MDANSE/Src/MDANSE/Mathematics/Arithmetic.py index a43bdd511..5ddc685b1 100644 --- a/MDANSE/Src/MDANSE/Mathematics/Arithmetic.py +++ b/MDANSE/Src/MDANSE/Mathematics/Arithmetic.py @@ -52,7 +52,7 @@ def get_weights(props, contents, dim): def weight(props, values, contents, dim, key, symmetric=True, update_partials=False): weights = get_weights(props, contents, dim)[0] weightedSum = None - matches = dict([(key % k, k) for k in list(weights.keys())]) + matches = {key % k: k for k in weights} for k, val in values.items(): if k not in matches: diff --git a/MDANSE/Src/MDANSE/Mathematics/LinearAlgebra.py b/MDANSE/Src/MDANSE/Mathematics/LinearAlgebra.py index 8a3330e60..6a76995f7 100644 --- a/MDANSE/Src/MDANSE/Mathematics/LinearAlgebra.py +++ b/MDANSE/Src/MDANSE/Mathematics/LinearAlgebra.py @@ -71,11 +71,7 @@ def __copy__(self, memo=None): __deepcopy__ = __copy__ def __repr__(self): - return "Vector(%s,%s,%s)" % ( - repr(self.array[0]), - repr(self.array[1]), - repr(self.array[2]), - ) + return f"Vector({','.join(map(repr, self.array))})" def __str__(self): return repr(list(self.array)) diff --git a/MDANSE/Src/MDANSE/Mathematics/Transformation.py b/MDANSE/Src/MDANSE/Mathematics/Transformation.py index 7a4a7f521..4caed8011 100644 --- a/MDANSE/Src/MDANSE/Mathematics/Transformation.py +++ b/MDANSE/Src/MDANSE/Mathematics/Transformation.py @@ -309,8 +309,7 @@ def threeAngles(self, e1, e2, e3, tolerance=1e-7): raise ValueError("FAILURE 1, norm = 0") if abs(_c / _norm) > 1 + tolerance: raise ValueError( - "FAILURE 2" - + "malformed rotation Tensor (non orthogonal?) %.8f" % (_c / _norm) + f"FAILURE 2 malformed rotation Tensor (non orthogonal?) {_c / _norm:.8f}" ) # if _c/_norm > 1: raise ValueError('Step1: No solution') _th = angleFromSineAndCosine(_b / _norm, _a / _norm) diff --git a/MDANSE/Src/MDANSE/MolecularDynamics/MockTrajectory.py b/MDANSE/Src/MDANSE/MolecularDynamics/MockTrajectory.py index 91c818593..fe930f49f 100644 --- a/MDANSE/Src/MDANSE/MolecularDynamics/MockTrajectory.py +++ b/MDANSE/Src/MDANSE/MolecularDynamics/MockTrajectory.py @@ -502,9 +502,7 @@ def read_configuration_trajectory( grp = self._variables if variable not in grp: - raise KeyError( - "The variable {} is not stored in the trajectory".format(variable) - ) + raise KeyError(f"The variable {variable} is not stored in the trajectory") variable = grp[variable][first:last:step, index, :].astype(np.float64) diff --git a/MDANSE/Src/MDANSE/Scripts/mdanse.py b/MDANSE/Src/MDANSE/Scripts/mdanse.py index cdb13c6ef..7f7b5d5ee 100644 --- a/MDANSE/Src/MDANSE/Scripts/mdanse.py +++ b/MDANSE/Src/MDANSE/Scripts/mdanse.py @@ -42,43 +42,45 @@ def format_description(self, description): return "" desc_width = self.width - self.current_indent indent = " " * self.current_indent - bits = description.split("\n") - formatted_bits = [ + bits = description.splitlines() + formatted_bits = ( textwrap.fill( bit, desc_width, initial_indent=indent, subsequent_indent=indent ) for bit in bits - ] + ) result = "\n".join(formatted_bits) + "\n" return result def format_option(self, option): - result = [] + indent = " " * self.current_indent + result = "" opts = self.option_strings[option] opt_width = self.help_position - self.current_indent - 2 if len(opts) > opt_width: - opts = "%*s%s\n" % (self.current_indent, "", opts) + opts = f"{indent}{opts}\n" indent_first = self.help_position else: # start help on same line as opts - opts = "%*s%-*s " % (self.current_indent, "", opt_width, opts) + opts = f"{indent}{opts} " indent_first = 0 - result.append(opts) + result += opts if option.help: help_text = self.expand_default(option) # Everything is the same up through here - help_lines = [] - for para in help_text.split("\n"): - help_lines.extend(textwrap.wrap(para, self.help_width)) + help_lines = [ + textwrap.wrap(para, self.help_width) for para in help_text.splitlines() + ] # Everything is the same after here - result.append("%*s%s\n" % (indent_first, "", help_lines[0])) - result.extend( - ["%*s%s\n" % (self.help_position, "", line) for line in help_lines[1:]] + result += f"{indent_first}{help_lines[0]}\n" + result += ( + "\n".join(f"{' '*self.help_position}{line}" for line in help_lines[1:]) + + "\n" ) - elif opts[-1] != "\n": - result.append("\n") + elif not opts.endswith("\n"): + result += "\n" - return "".join(result) + return result class CommandLineParserError(Error): @@ -112,7 +114,7 @@ def check_job(self, option, opt_str, value, parser): if len(parser.rargs) != 1: raise CommandLineParserError( - "Invalid number of arguments for %r option" % opt_str + f"Invalid number of arguments for {opt_str!r} option" ) basename = parser.rargs[0] @@ -131,23 +133,23 @@ def check_job(self, option, opt_str, value, parser): # If the file could not be opened/unpickled for whatever reason, try at the next checkpoint except: raise CommandLineParserError( - "The job %r could not be opened properly." % basename + f"The job {basename!r} could not be opened properly." ) # The job file could be opened and unpickled properly else: # Check that the unpickled object is a JobStatus object if not isinstance(info, JobState): - raise CommandLineParserError("Invalid contents for job %r." % basename) + raise CommandLineParserError(f"Invalid contents for job {basename!r}.") - LOG.info("Information about %s job:" % basename) - for k, v in info.iteritems(): - LOG.info("%-20s [%s]" % (k, v)) + LOG.info("Information about %s job:", basename) + for k, v in info.items(): + LOG.info("%-20s [%s]", k, v) def display_element_info(self, option, opt_str, value, parser): if len(parser.rargs) != 1: raise CommandLineParserError( - "Invalid number of arguments for %r option" % opt_str + f"Invalid number of arguments for {opt_str!r} option" ) element = parser.rargs[0] @@ -158,7 +160,7 @@ def display_element_info(self, option, opt_str, value, parser): LOG.info(ATOMS_DATABASE.info(element)) except ValueError: raise CommandLineParserError( - "The entry %r is not registered in the database" % element + f"The entry {element!r} is not registered in the database" ) def display_jobs_list(self, option, opt_str, value, parser): @@ -179,7 +181,7 @@ def display_jobs_list(self, option, opt_str, value, parser): if len(parser.rargs) != 0: raise CommandLineParserError( - "Invalid number of arguments for %r option" % opt_str + f"Invalid number of arguments for {opt_str!r} option" ) jobs = PLATFORM.temporary_files_directory().glob("*") @@ -230,7 +232,7 @@ def error(self, msg): """ self.print_help(sys.stderr) - self.exit(2, "Error: %s\n" % msg) + self.exit(2, f"Error: {msg}\n") def query_classes_registry(self, option, opt_str, value, parser): """ @@ -248,13 +250,13 @@ def query_classes_registry(self, option, opt_str, value, parser): if len(parser.rargs) == 0: LOG.info("Registered jobs:") for interfaceName in IJob.indirect_subclasses(): - LOG.info("\t- %s" % interfaceName) + LOG.info("\t- %s", interfaceName) elif len(parser.rargs) == 1: val = parser.rargs[0] LOG.info(IJob.create(val).info()) else: raise CommandLineParserError( - "Invalid number of arguments for %r option" % opt_str + f"Invalid number of arguments for {opt_str!r} option" ) def run_job(self, option, opt_str, value, parser): @@ -275,14 +277,14 @@ def run_job(self, option, opt_str, value, parser): if len(parser.rargs) != 1: raise CommandLineParserError( - "Invalid number of arguments for %r option" % opt_str + f"Invalid number of arguments for {opt_str!r} option" ) filename = Path(parser.rargs[0]) if not filename.exists(): raise CommandLineParserError( - "The job file %r could not be executed" % filename + f"The job file {filename!r} could not be executed" ) subprocess.Popen([sys.executable, filename]) @@ -306,7 +308,7 @@ def save_job(self, option, opt_str, value, parser): if len(parser.rargs) != 1: raise CommandLineParserError( - "Invalid number of arguments for %r option" % opt_str + f"Invalid number of arguments for {opt_str!r} option" ) jobs = IJob @@ -322,14 +324,14 @@ def save_job(self, option, opt_str, value, parser): # Case where an error occured when writing the template. except IOError: raise CommandLineParserError( - "Could not write the job template as %r" % filename + f"Could not write the job template as {filename!r}" ) # If the job class has no save method, thisis not a valid MDANSE job. except KeyError: - raise CommandLineParserError("The job %r is not a valid MDANSE job" % name) + raise CommandLineParserError(f"The job {name!r} is not a valid MDANSE job") # Otherwise, print some information about the saved template. else: - LOG.info("Saved template for job %r as %r" % (name, filename)) + LOG.info("Saved template for job %r as %r", name, filename) def save_job_template(self, option, opt_str, value, parser): """ @@ -371,7 +373,7 @@ def main(): # Creates the option parser. parser = CommandLineParser( - formatter=IndentedHelp(), version="MDANSE %s " % MDANSE.__version__ + formatter=IndentedHelp(), version=f"MDANSE {MDANSE.__version__} " ) # Creates a first the group of general options. diff --git a/MDANSE/Src/MDANSE/Trajectory/H5MDTrajectory.py b/MDANSE/Src/MDANSE/Trajectory/H5MDTrajectory.py index 02aa55b93..241245aa5 100644 --- a/MDANSE/Src/MDANSE/Trajectory/H5MDTrajectory.py +++ b/MDANSE/Src/MDANSE/Trajectory/H5MDTrajectory.py @@ -516,9 +516,7 @@ def read_configuration_trajectory( last = len(self) if not self.has_variable(variable): - raise KeyError( - "The variable {} is not stored in the trajectory".format(variable) - ) + raise KeyError(f"The variable {variable} is not stored in the trajectory") grp = self._h5_file["/particles/all"] variable = grp[variable]["value"][first:last:step, index, :].astype(np.float64) diff --git a/MDANSE/Src/MDANSE/Trajectory/MdanseTrajectory.py b/MDANSE/Src/MDANSE/Trajectory/MdanseTrajectory.py index b2641d9b5..431eb6fa6 100644 --- a/MDANSE/Src/MDANSE/Trajectory/MdanseTrajectory.py +++ b/MDANSE/Src/MDANSE/Trajectory/MdanseTrajectory.py @@ -409,9 +409,7 @@ def read_configuration_trajectory( last = len(self) if not self.has_variable(variable): - raise KeyError( - "The variable {} is not stored in the trajectory".format(variable) - ) + raise KeyError(f"The variable {variable} is not stored in the trajectory") grp = self._h5_file["/configuration"] variable = grp[variable][first:last:step, index, :].astype(np.float64) From 97124ebdd5959fc0a823186e0a277d9b6a579a0e Mon Sep 17 00:00:00 2001 From: Jacob Wilkins <46597752+oerc0122@users.noreply.github.com> Date: Tue, 11 Feb 2025 13:46:23 +0000 Subject: [PATCH 4/6] Add ruff (#642) * Add ruff * Fix ruff errors --- .github/workflows/lint.yml | 9 ++++ MDANSE/Src/MDANSE/Core/SubclassFactory.py | 4 +- .../Framework/AtomMapping/atom_mapping.py | 2 +- .../MDANSE/Framework/AtomSelector/selector.py | 24 ++++++++-- MDANSE/Src/MDANSE/Framework/Configurable.py | 2 +- .../Configurators/ASEFileConfigurator.py | 2 +- .../Configurators/AseInputFileConfigurator.py | 4 +- .../Configurators/BooleanConfigurator.py | 2 - .../Configurators/ConfigFileConfigurator.py | 20 ++++---- .../CorrelationFramesConfigurator.py | 10 ++-- .../DerivativeOrderConfigurator.py | 6 +-- .../DistHistCutoffConfigurator.py | 2 +- .../FileWithAtomDataConfigurator.py | 2 +- .../Configurators/FloatConfigurator.py | 4 +- .../Configurators/HDFInputFileConfigurator.py | 2 +- .../Framework/Configurators/IConfigurator.py | 2 +- .../Configurators/IntegerConfigurator.py | 3 +- .../InterpolationOrderConfigurator.py | 14 +++--- .../MDAnalysisCoordinateFileConfigurator.py | 2 +- .../MDAnalysisTimeStepConfigurator.py | 2 +- .../MDAnalysisTopologyFileConfigurator.py | 2 +- .../MDTrajTimeStepConfigurator.py | 2 +- .../MDTrajTopologyFileConfigurator.py | 2 +- .../MDTrajTrajectoryFileConfigurator.py | 2 +- .../McStasOptionsConfigurator.py | 6 +-- .../MultiInputFileConfigurator.py | 6 +-- .../MultipleChoicesConfigurator.py | 2 +- .../OptionalFloatConfigurator.py | 4 +- .../Configurators/OutputFilesConfigurator.py | 6 +-- .../OutputStructureConfigurator.py | 6 +-- .../OutputTrajectoryConfigurator.py | 2 +- .../PartialChargeConfigurator.py | 2 +- .../Configurators/ProjectionConfigurator.py | 2 +- .../Configurators/QVectorsConfigurator.py | 6 +-- .../Configurators/RangeConfigurator.py | 1 - .../Configurators/RunningModeConfigurator.py | 2 +- .../Configurators/SingleChoiceConfigurator.py | 1 - .../SingleOutputFileConfigurator.py | 4 +- .../Configurators/UnitCellConfigurator.py | 5 +- MDANSE/Src/MDANSE/Framework/Converters/ASE.py | 7 +-- .../MDANSE/Framework/Converters/Converter.py | 2 +- .../Framework/Converters/ImprovedASE.py | 14 +++--- .../Src/MDANSE/Framework/Converters/LAMMPS.py | 6 +-- .../Handlers/ColorizingStreamHandler.py | 2 +- .../InputData/HDFTrajectoryInputData.py | 6 +-- .../MDANSE/Framework/Jobs/AreaPerMolecule.py | 2 +- .../MDANSE/Framework/Jobs/AverageStructure.py | 14 +++--- MDANSE/Src/MDANSE/Framework/Jobs/Density.py | 2 +- .../MDANSE/Framework/Jobs/DensityProfile.py | 2 +- .../Framework/Jobs/DistanceHistogram.py | 2 +- .../Jobs/DynamicCoherentStructureFactor.py | 2 +- .../Jobs/ElasticIncoherentStructureFactor.py | 2 +- .../Jobs/GeneralAutoCorrelationFunction.py | 2 +- MDANSE/Src/MDANSE/Framework/Jobs/IJob.py | 4 +- MDANSE/Src/MDANSE/Framework/Jobs/JobStatus.py | 3 -- .../Framework/Jobs/McStasVirtualInstrument.py | 27 ++++++----- .../MDANSE/Framework/Jobs/OrderParameter.py | 1 - .../Framework/Jobs/RigidBodyTrajectory.py | 2 +- .../Framework/Jobs/StaticStructureFactor.py | 2 +- .../Framework/Jobs/VanHoveFunctionDistinct.py | 6 +-- .../Framework/Jobs/VanHoveFunctionSelf.py | 2 +- MDANSE/Src/MDANSE/Framework/Jobs/Voronoi.py | 2 +- .../Jobs/XRayStaticStructureFactor.py | 4 +- .../MDANSE/Framework/QVectors/IQVectors.py | 2 +- .../Framework/Session/CurrentSession.py | 2 +- MDANSE/Src/MDANSE/Framework/Units.py | 2 +- MDANSE/Src/MDANSE/IO/FortranFormat.py | 24 +++++----- MDANSE/Src/MDANSE/IO/MinimalPDBReader.py | 2 +- MDANSE/Src/MDANSE/IO/TextFile.py | 11 ++--- .../Src/MDANSE/Mathematics/LinearAlgebra.py | 2 +- .../Src/MDANSE/Mathematics/Transformation.py | 6 +-- .../MDANSE/MolecularDynamics/Trajectory.py | 13 ++--- MDANSE/Src/MDANSE/Scripts/mdanse.py | 6 +-- .../Src/MDANSE/Trajectory/H5MDTrajectory.py | 34 +++++++------- .../Src/MDANSE/Trajectory/MdanseTrajectory.py | 2 +- MDANSE/pyproject.toml | 47 +++++++++++++++++++ 76 files changed, 257 insertions(+), 195 deletions(-) diff --git a/.github/workflows/lint.yml b/.github/workflows/lint.yml index bd9d08053..4641bae38 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 39de5a6d3..2a2bdb072 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 f518f8a0e..b2ee2ca97 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 f98d9aafd..3562149e7 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 ef8664e1b..1ee336434 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 3323569b5..8f57aa1e2 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 0654a47b3..883873b5e 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 e51ada377..640c8e8f7 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 33bd20fe5..1af42d671 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 bdfec1a23..4de5aa93c 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 43d2eb935..71436b964 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 eeb4c2af8..dee9d13c9 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 ba5228358..8f3c8d540 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 3234e06f4..0168a2d5b 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 6efce61cc..ae092df74 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 b1015712c..70d3436a4 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 73307c54f..b74080169 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 d259a6c47..f42ed27e4 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 51c8da812..ce9d17c17 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 53b52fcfc..eab8d125a 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 c454dc99c..50b0c4e9a 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 e3bb891d5..dea06a4d9 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 a67b24013..ee3e6fe22 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 a44cac00b..41df11c7a 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 1bfa4170c..e4fe3c697 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 bd327045a..772c64efb 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 255067866..75b111d8c 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 8ab4439ed..8bde4cd50 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 145ab6e29..ce191021d 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 c55f0d1e3..102d406a6 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 4488affba..e3040f06a 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 5222728af..a85bd46a9 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 2c43de6d8..9c30229a4 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 0434425c5..a9fde6687 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 11c00d616..477524ac4 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 068bec563..8527386db 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 d651d3f6a..e0258eb20 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 adf63c6fc..578e9ad8d 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 d2be900d6..2830bcf45 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 bef661b95..b0aa8dd40 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 c291fc7c4..ba728b2e1 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 1b8754114..2f1d1678b 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 b36f591d8..06557f171 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 237bc46c3..ab3459ed7 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 c99672f78..fa10a77c2 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 2c19d0ba5..f507a4b39 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 f30e5ebdc..32821eddf 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 ac97da0fb..e092d911d 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 fa7332aa8..3d37d4559 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 f5ddb7577..462be1c99 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 1feeadcf9..a88a5b58d 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 face85b9a..750c6eabd 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 be158c6da..615693c85 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 b087e7174..e0fc7ba37 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 408f0f6d3..27110c9d9 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 9cf8acae1..97862c0d9 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 135c01898..80222fc00 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 ba4e25af6..2de79cee9 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 9b0321681..891ae9fed 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 a0aa77df3..93d281e04 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 9d7b0749a..6abb58a1b 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 19dde6be1..bca7c9575 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 3e14db0c6..2efef2951 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 573c1be92..b3fadad0e 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 74619200a..3864cd286 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 5083435d2..c97e35588 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 40943035e..350b0c6fb 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 afb0b28d1..0baab13af 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 6892a2d0d..737ae0f8c 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 6a76995f7..1f6ab7116 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 4caed8011..b2ed7a06a 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 9cc8a5b72..4b6772b9e 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 7f7b5d5ee..d77b09b30 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 241245aa5..a0695f067 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 431eb6fa6..23e634de1 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 95bc164b6..434f12b33 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"] From 7d7693333d140ae3ce4ce3e3b03752c2fc0743e1 Mon Sep 17 00:00:00 2001 From: Maciej Bartkowiak <108934199+MBartkowiakSTFC@users.noreply.github.com> Date: Tue, 11 Feb 2025 14:43:20 +0000 Subject: [PATCH 5/6] Update MDANSE/Src/MDANSE/Trajectory/H5MDTrajectory.py Co-authored-by: Jacob Wilkins <46597752+oerc0122@users.noreply.github.com> Signed-off-by: Maciej Bartkowiak <108934199+MBartkowiakSTFC@users.noreply.github.com> --- MDANSE/Src/MDANSE/Trajectory/H5MDTrajectory.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/MDANSE/Src/MDANSE/Trajectory/H5MDTrajectory.py b/MDANSE/Src/MDANSE/Trajectory/H5MDTrajectory.py index f547427b5..116aafd74 100644 --- a/MDANSE/Src/MDANSE/Trajectory/H5MDTrajectory.py +++ b/MDANSE/Src/MDANSE/Trajectory/H5MDTrajectory.py @@ -264,7 +264,7 @@ def _load_unit_cells(self): except (AttributeError, KeyError): conv_factor = 0.1 else: - if box_unit == "Ang" or box_unit == "Angstrom": + if box_unit in ("Ang", "Angstrom"): box_unit = "ang" conv_factor = measure(1.0, box_unit).toval("nm") try: From 14219ecaf16840ecf012c181bd5d416c28a6990b Mon Sep 17 00:00:00 2001 From: Maciej Bartkowiak Date: Tue, 11 Feb 2025 14:54:50 +0000 Subject: [PATCH 6/6] Correct text info for H5MD --- MDANSE/Src/MDANSE/Framework/InputData/HDFTrajectoryInputData.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/MDANSE/Src/MDANSE/Framework/InputData/HDFTrajectoryInputData.py b/MDANSE/Src/MDANSE/Framework/InputData/HDFTrajectoryInputData.py index fa10a77c2..b70042b64 100644 --- a/MDANSE/Src/MDANSE/Framework/InputData/HDFTrajectoryInputData.py +++ b/MDANSE/Src/MDANSE/Framework/InputData/HDFTrajectoryInputData.py @@ -61,7 +61,7 @@ def info(self): val.append("Number of steps:") val.append(f"{self._data}\n") val.append("Configuration:") - val.append(f"\tIs periodic: {'unit_cell' in self._data.file}\n") + val.append(f"\tIs periodic: {self._data.unit_cell(0) is not None}\n") try: val.append(f"First unit cell (nm):\n{self._data.unit_cell(0)._unit_cell}\n") except Exception: