From d159deb079ed0f5c11b7b0a5c3c1141cf044af2b Mon Sep 17 00:00:00 2001 From: Chris Sewell Date: Tue, 28 Nov 2023 16:01:17 +0000 Subject: [PATCH 1/3] =?UTF-8?q?=F0=9F=94=A7=20Replace=20black/isort/pyupgr?= =?UTF-8?q?ade=20with=20ruff?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .pre-commit-config.yaml | 21 +++------- aiida_lammps/calculations/base.py | 9 ++--- aiida_lammps/calculations/raw.py | 5 +-- aiida_lammps/data/potential.py | 32 +++++++-------- aiida_lammps/data/trajectory.py | 40 +++++++++---------- aiida_lammps/parsers/base.py | 22 +++++----- aiida_lammps/parsers/inputfile.py | 31 +++++++------- aiida_lammps/parsers/parse_raw/final_data.py | 6 ++- .../parsers/parse_raw/lammps_output.py | 15 ++++--- aiida_lammps/parsers/utils.py | 11 +++-- aiida_lammps/workflows/base.py | 2 - aiida_lammps/workflows/relax.py | 14 +++---- conftest.py | 25 +++++------- examples/calculations/launch_lammps_md.py | 1 - .../calculations/launch_lammps_minimize.py | 1 - examples/launch_lammps_base_restart_file.py | 1 - examples/launch_lammps_base_restart_folder.py | 1 - examples/launch_lammps_base_script.py | 1 - examples/launch_lammps_raw_script.py | 2 +- pyproject.toml | 18 +++------ tests/test_calculations.py | 4 +- tests/test_generate_inputs.py | 1 - tests/test_generate_structure.py | 4 +- tests/test_parsers.py | 1 + tests/test_potential_data.py | 1 + tests/test_trajectory.py | 17 +++----- tests/test_workflows.py | 10 ++--- 27 files changed, 126 insertions(+), 170 deletions(-) diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml index b0e0d042..cb44e6fe 100644 --- a/.pre-commit-config.yaml +++ b/.pre-commit-config.yaml @@ -8,25 +8,16 @@ exclude: > repos: - repo: https://github.com/pre-commit/pre-commit-hooks - rev: v4.1.0 + rev: v4.5.0 hooks: - id: check-json - id: check-yaml - id: end-of-file-fixer - id: trailing-whitespace - - repo: https://github.com/asottile/pyupgrade - rev: v2.31.1 + - repo: https://github.com/astral-sh/ruff-pre-commit + rev: v0.1.6 hooks: - - id: pyupgrade - args: [--py38-plus] - - - repo: https://github.com/pycqa/isort - rev: 5.12.0 - hooks: - - id: isort - - - repo: https://github.com/psf/black - rev: 22.3.0 - hooks: - - id: black + - id: ruff + args: [--fix] + - id: ruff-format diff --git a/aiida_lammps/calculations/base.py b/aiida_lammps/calculations/base.py index 3a1dad37..e146bb41 100644 --- a/aiida_lammps/calculations/base.py +++ b/aiida_lammps/calculations/base.py @@ -7,7 +7,7 @@ the input structure and whether or not a restart file is provided. """ import os -from typing import Union +from typing import ClassVar, Dict, Union from aiida import orm from aiida.common import datastructures @@ -30,7 +30,7 @@ class LammpsBaseCalculation(CalcJob): the input structure and whether or not a restart file is provided. """ - _DEFAULT_VARIABLES = { + _DEFAULT_VARIABLES: ClassVar[Dict[str, str]] = { "input_filename": "input.in", "structure_filename": "structure.dat", "output_filename": "lammps.out", @@ -325,10 +325,7 @@ def prepare_for_submission(self, folder): else: _parameters = {} - if "settings" in self.inputs: - settings = self.inputs.settings.get_dict() - else: - settings = {} + settings = self.inputs.settings.get_dict() if "settings" in self.inputs else {} # Set the remote copy list and the symlink so that if one needs to use restartfiles from # a previous calculations one can do so without problems diff --git a/aiida_lammps/calculations/raw.py b/aiida_lammps/calculations/raw.py index d015541c..6ab7b5b3 100644 --- a/aiida_lammps/calculations/raw.py +++ b/aiida_lammps/calculations/raw.py @@ -131,9 +131,8 @@ def prepare_for_submission(self, folder: Folder) -> CalcInfo: # namespace, falling back to the filename of the ``SinglefileData`` node if not defined. filename = filenames.get(key, node.filename) - with folder.open(filename, "wb") as target: - with node.open(mode="rb") as source: - shutil.copyfileobj(source, target) + with folder.open(filename, "wb") as target, node.open(mode="rb") as source: + shutil.copyfileobj(source, target) provenance_exclude_list.append(filename) diff --git a/aiida_lammps/data/potential.py b/aiida_lammps/data/potential.py index 40b4beec..3a9ab683 100644 --- a/aiida_lammps/data/potential.py +++ b/aiida_lammps/data/potential.py @@ -23,7 +23,7 @@ class written by Sebastiaan Huber. import json import os import pathlib -from typing import BinaryIO, List, Optional, Union +from typing import Any, BinaryIO, ClassVar, Dict, List, Optional, Union import warnings from aiida import orm, plugins @@ -164,7 +164,7 @@ class written by Sebaastian Huber. "lammps_potentials.json", ) - _extra_keys = { + _extra_keys: ClassVar[Dict[str, Any]] = { "title": {"validator": _validate_string}, "developer": {"validator": _validate_string_list}, "publication_year": {"validator": _validate_datetime}, @@ -190,12 +190,12 @@ class written by Sebaastian Huber. def get_or_create( cls, source: Union[str, pathlib.Path, BinaryIO], - filename: str = None, - pair_style: str = None, - species: list = None, - atom_style: str = None, - units: str = None, - extra_tags: dict = None, + filename: Optional[str] = None, + pair_style: Optional[str] = None, + species: Optional[list] = None, + atom_style: Optional[str] = None, + units: Optional[str] = None, + extra_tags: Optional[dict] = None, ): """ Get lammps potential data node from database or create a new one. @@ -290,7 +290,7 @@ def prepare_source(cls, source: Union[str, pathlib.Path, BinaryIO]) -> BinaryIO: ) and not cls.is_readable_byte_stream(source): raise TypeError( "`source` should be a `str` or `pathlib.Path` filepath on " - + f"disk or a stream of bytes, got: {source}" + f"disk or a stream of bytes, got: {source}" ) if isinstance(source, (str, pathlib.Path)): @@ -328,7 +328,7 @@ def validate_pair_style(self, pair_style: str): """ if pair_style is None: raise TypeError("The pair_style of the potential must be provided.") - if pair_style not in self.default_potential_info.keys(): + if pair_style not in self.default_potential_info: raise KeyError(f'The pair_style "{pair_style}" is not valid') self.base.attributes.set("pair_style", pair_style) @@ -440,12 +440,12 @@ def validate_extra_tags(self, extra_tags: dict): def set_file( self, source: Union[str, pathlib.Path, BinaryIO], - filename: str = None, - pair_style: str = None, - species: list = None, - atom_style: str = None, - units: str = None, - extra_tags: dict = None, + filename: Optional[str] = None, + pair_style: Optional[str] = None, + species: Optional[list] = None, + atom_style: Optional[str] = None, + units: Optional[str] = None, + extra_tags: Optional[dict] = None, **kwargs, ): """Set the file content. diff --git a/aiida_lammps/data/trajectory.py b/aiida_lammps/data/trajectory.py index 6d0198e1..0ba888d9 100644 --- a/aiida_lammps/data/trajectory.py +++ b/aiida_lammps/data/trajectory.py @@ -90,7 +90,6 @@ def set_from_fileobj(self, fileobj, aliases=None): self._compression_method, ) as zip_file: for step_id, trajectory_step in enumerate(iter_trajectories(fileobj)): - # extract data to store in attributes time_steps.append(trajectory_step.timestep) if number_atoms is None: @@ -135,13 +134,13 @@ def set_from_fileobj(self, fileobj, aliases=None): self.base.attributes.set("number_steps", len(time_steps)) self.base.attributes.set("number_atoms", number_atoms) - self.base.attributes.set("field_names", list(sorted(field_names))) + self.base.attributes.set("field_names", sorted(field_names)) self.base.attributes.set("trajectory_filename", self._trajectory_filename) self.base.attributes.set("timestep_filename", self._timestep_filename) self.base.attributes.set("zip_prefix", self._zip_prefix) self.base.attributes.set("compression_method", self._compression_method) self.base.attributes.set("aliases", aliases) - self.base.attributes.set("elements", list(sorted(elements))) + self.base.attributes.set("elements", sorted(elements)) @property def number_steps(self): @@ -199,14 +198,12 @@ def get_step_string(self, step_idx): with self.base.repository.open( self.base.attributes.get("trajectory_filename"), mode="rb", - ) as handle: - with ZipFile( - handle, - "r", - self.base.attributes.get("compression_method"), - ) as zip_file: - with zip_file.open(zip_name, "r") as step_file: - content = step_file.read() + ) as handle, ZipFile( + handle, + "r", + self.base.attributes.get("compression_method"), + ) as zip_file, zip_file.open(zip_name, "r") as step_file: + content = step_file.read() return content.decode("utf8") def get_step_data(self, step_idx): @@ -224,17 +221,16 @@ def iter_step_strings(self, steps=None): with self.base.repository.open( self.base.attributes.get("trajectory_filename"), mode="rb", - ) as handle: - with ZipFile( - handle, - "r", - self.base.attributes.get("compression_method"), - ) as zip_file: - for step_idx in steps: - zip_name = f'{self.base.attributes.get("zip_prefix")}{step_idx}' - with zip_file.open(zip_name) as step_file: - content = step_file.read() - yield content + ) as handle, ZipFile( + handle, + "r", + self.base.attributes.get("compression_method"), + ) as zip_file: + for step_idx in steps: + zip_name = f'{self.base.attributes.get("zip_prefix")}{step_idx}' + with zip_file.open(zip_name) as step_file: + content = step_file.read() + yield content def get_step_structure( self, diff --git a/aiida_lammps/parsers/base.py b/aiida_lammps/parsers/base.py index adfd17a4..a6ef2be5 100644 --- a/aiida_lammps/parsers/base.py +++ b/aiida_lammps/parsers/base.py @@ -208,16 +208,18 @@ def parse_restartfile( restart_filename = "" - if parameters.get("restart", {}).get("print_final", False): - if input_restart_filename in list_of_files: - with self.node.outputs.retrieved.base.repository.open( - input_restart_filename, - mode="rb", - ) as handle: - restart_file = orm.SinglefileData(handle) - self.out("restartfile", restart_file) - restart_found = True - restart_filename = input_restart_filename + if ( + parameters.get("restart", {}).get("print_final", False) + and input_restart_filename in list_of_files + ): + with self.node.outputs.retrieved.base.repository.open( + input_restart_filename, + mode="rb", + ) as handle: + restart_file = orm.SinglefileData(handle) + self.out("restartfile", restart_file) + restart_found = True + restart_filename = input_restart_filename if ( parameters.get("restart", {}).get("print_intermediate", False) diff --git a/aiida_lammps/parsers/inputfile.py b/aiida_lammps/parsers/inputfile.py index 78d09279..43cd89f6 100644 --- a/aiida_lammps/parsers/inputfile.py +++ b/aiida_lammps/parsers/inputfile.py @@ -14,7 +14,7 @@ import json import os import re -from typing import Union +from typing import Optional, Union from aiida import orm import numpy as np @@ -32,7 +32,7 @@ def generate_input_file( potential_filename: str = "potential.dat", structure_filename: str = "structure.dat", variables_filename: str = "aiida_lammps.yaml", - read_restart_filename: str = None, + read_restart_filename: Optional[str] = None, ) -> str: """ Generate the text for the lammps input file. @@ -317,7 +317,6 @@ def write_structure_block( for _group in parameters_structure["groups"]: # Check if the given type name corresponds to the ones assigned to the atom types if "type" in _group["args"]: - _subset = _group["args"][_group["args"].index("type") + 1 :] if not all(kind in kind_name_id_map.values() for kind in _subset): @@ -631,7 +630,7 @@ def generate_integration_options( def write_fix_block( parameters_fix: dict, - group_names: list = None, + group_names: Optional[list] = None, ) -> str: """ Generate the input block with the fix options. @@ -663,9 +662,9 @@ def write_fix_block( for key, value in parameters_fix.items(): for entry in value: _group = entry.get("group", "all") - if _group not in group_names + ["all"]: + if _group not in [*group_names, "all"]: raise ValueError( - f'group name "{_group}" is not the defined groups {group_names + ["all"]}' + f'group name "{_group}" is not the defined groups {[*group_names, "all"]}' ) fix_block += f"fix {generate_id_tag(key, _group)} {_group} {key} " fix_block += f'{join_keywords(entry["type"])}\n' @@ -675,7 +674,7 @@ def write_fix_block( def write_compute_block( parameters_compute: dict, - group_names: list = None, + group_names: Optional[list] = None, ) -> str: """ Generate the input block with the compute options. @@ -701,7 +700,7 @@ def write_compute_block( for key, value in parameters_compute.items(): for entry in value: _group = entry.get("group", "all") - if _group not in group_names + ["all"]: + if _group not in [*group_names, "all"]: raise ValueError(f'group name "{_group}" is not the defined groups') compute_block += f"compute {generate_id_tag(key, _group)} {_group} {key} " compute_block += f'{join_keywords(entry["type"])}\n' @@ -713,8 +712,8 @@ def write_dump_block( parameters_dump: dict, trajectory_filename: str, atom_style: str, - parameters_compute: dict = None, - kind_symbols: list = None, + parameters_compute: Optional[dict] = None, + kind_symbols: Optional[list] = None, ) -> str: """Generate the block with dumps commands. @@ -777,7 +776,7 @@ def write_dump_block( def write_thermo_block( parameters_thermo: dict, - parameters_compute: dict = None, + parameters_compute: Optional[dict] = None, ) -> Union[str, list]: """Generate the block with the thermo command. @@ -826,13 +825,13 @@ def write_thermo_block( else: fixed_thermo = [key for key, value in computes_printing.items() if value] if "step" not in fixed_thermo: - fixed_thermo = ["step"] + fixed_thermo + fixed_thermo = ["step", *fixed_thermo] if "etotal" not in fixed_thermo: - fixed_thermo = fixed_thermo + ["etotal"] + fixed_thermo = [*fixed_thermo, "etotal"] if fixed_thermo.index("step") != 0: fixed_thermo.remove("step") - fixed_thermo = ["step"] + fixed_thermo + fixed_thermo = ["step", *fixed_thermo] thermo_block = generate_header("Start of the Thermo information") thermo_block += ( @@ -866,7 +865,6 @@ def write_restart_block( restart_block = {"final": "", "intermediate": ""} if "print_final" in parameters_restart and parameters_restart["print_final"]: - restart_block["final"] += generate_header( "Start of the write restart information" ) @@ -879,7 +877,6 @@ def write_restart_block( "print_intermediate" in parameters_restart and parameters_restart["print_intermediate"] ): - restart_block["intermediate"] += generate_header( "Start of the intermediate write restart information" ) @@ -969,7 +966,7 @@ def generate_printing_string( return " ".join(_string) -def generate_id_tag(name: str = None, group: str = None) -> str: +def generate_id_tag(name: Optional[str] = None, group: Optional[str] = None) -> str: """Generate an id tag for fixes and/or computes. To standardize the naming of computes and/or fixes and to ensure that one diff --git a/aiida_lammps/parsers/parse_raw/final_data.py b/aiida_lammps/parsers/parse_raw/final_data.py index 73953cec..31f6b843 100644 --- a/aiida_lammps/parsers/parse_raw/final_data.py +++ b/aiida_lammps/parsers/parse_raw/final_data.py @@ -1,9 +1,13 @@ """Set of functions to parse the files containing the final variables printed by LAMMPS""" +from typing import Optional + import yaml -def parse_final_data(filename: str = None, file_contents: str = None) -> dict: +def parse_final_data( + filename: Optional[str] = None, file_contents: Optional[str] = None +) -> dict: """ Read the yaml file with the global final data. diff --git a/aiida_lammps/parsers/parse_raw/lammps_output.py b/aiida_lammps/parsers/parse_raw/lammps_output.py index 760ac194..5e5b53e1 100644 --- a/aiida_lammps/parsers/parse_raw/lammps_output.py +++ b/aiida_lammps/parsers/parse_raw/lammps_output.py @@ -2,13 +2,13 @@ # pylint: disable=fixme import ast import re -from typing import Union +from typing import Optional, Union import numpy as np def parse_outputfile( - filename: str = None, file_contents: str = None + filename: Optional[str] = None, file_contents: Optional[str] = None ) -> Union[dict, dict]: """ Parse the lammps output file file, this is the redirected screen output. @@ -30,7 +30,6 @@ def parse_outputfile( return None if filename is not None: - try: with open(filename) as handler: data = handler.read() @@ -110,9 +109,13 @@ def parse_outputfile( header_line = [ re.sub("[^a-zA-Z0-9_]", "__", entry) for entry in line.split() ] - if header_line_position > 0 and index != header_line_position and not end_found: - if not line.split()[0].replace(".", "", 1).isdigit(): - end_found = True + if ( + header_line_position > 0 + and index != header_line_position + and not end_found + and not line.split()[0].replace(".", "", 1).isdigit() + ): + end_found = True if header_line_position > 0 and index != header_line_position and not end_found: _data.append([ast.literal_eval(entry) for entry in line.split()]) _data = np.asarray(_data) diff --git a/aiida_lammps/parsers/utils.py b/aiida_lammps/parsers/utils.py index 335483ae..d3c64977 100644 --- a/aiida_lammps/parsers/utils.py +++ b/aiida_lammps/parsers/utils.py @@ -1,6 +1,6 @@ """Utility functions for the handling of the input files""" from collections.abc import Iterable -from typing import Union +from typing import Optional, Union import numpy as np @@ -36,8 +36,8 @@ def _transform_cell(cell) -> Union[np.array, np.array]: def generate_lammps_structure( structure, atom_style: str = "atomic", - charge_dict: dict = None, - round_dp: float = None, + charge_dict: Optional[dict] = None, + round_dp: Optional[float] = None, docstring: str = "generated by aiida_lammps", ) -> Union[str, np.array]: """Creation of the structure file content. @@ -105,7 +105,7 @@ def generate_lammps_structure( ) filestring += "Masses\n\n" - for kind_name in sorted(list(kind_name_id_map.keys())): + for kind_name in sorted(kind_name_id_map.keys()): filestring += ( f"{kind_name_id_map[kind_name]} {kind_mass_dict[kind_name]:20.10f} \n" ) @@ -114,7 +114,6 @@ def generate_lammps_structure( filestring += "Atoms\n\n" for site_index, (pos, site) in enumerate(zip(positions, structure.sites)): - kind_id = kind_name_id_map[site.kind_name] if atom_style == "atomic": @@ -175,7 +174,7 @@ def join_keywords(dct, ignore=None): value can be a single value or a list/tuple of values """ - ignore = [] if not ignore else ignore + ignore = ignore if ignore else [] return " ".join( [ f"{k} {_convert_values(dct[k])}" diff --git a/aiida_lammps/workflows/base.py b/aiida_lammps/workflows/base.py index 2f40d65b..a715ec4f 100644 --- a/aiida_lammps/workflows/base.py +++ b/aiida_lammps/workflows/base.py @@ -97,7 +97,6 @@ def _check_restart_in_remote(self, calculation): """ try: - return ( calculation.outputs.results.get_dict() .get("compute_variables", {}) @@ -143,7 +142,6 @@ def set_restart_type(self, restart_type, calculation): "Removing the velocity parameter from the MD control" ) if restart_type == RestartTypes.FROM_REMOTEFOLDER: - latest_file = self._check_restart_in_remote(calculation=calculation) if latest_file is not None: diff --git a/aiida_lammps/workflows/relax.py b/aiida_lammps/workflows/relax.py index 3336f958..a236a6b4 100644 --- a/aiida_lammps/workflows/relax.py +++ b/aiida_lammps/workflows/relax.py @@ -243,7 +243,7 @@ def _all_equal(iterable): if ( value["relax"]["volume"].value and value["relax"]["shape"].value - and not "target_pressure" in value["relax"] + and "target_pressure" not in value["relax"] ): return ( "When relaxing the shape and the volume at the same time one needs to give the " @@ -254,13 +254,13 @@ def _all_equal(iterable): value["relax"]["volume"].value and not value["relax"]["shape"].value and "target_pressure" in value["relax"] + and not _all_equal(value["relax"]["target_pressure"].get_dict().values()) ): - if not _all_equal(value["relax"]["target_pressure"].get_dict().values()): - return ( - "Requesting a volume relaxation without shape optimization, the values of " - "``target_pressure`` should all be equal or be just one value, instead " - f"got {value.relax.target_pressure.get_dict()}" - ) + return ( + "Requesting a volume relaxation without shape optimization, the values of " + "``target_pressure`` should all be equal or be just one value, instead " + f"got {value.relax.target_pressure.get_dict()}" + ) if value["relax"]["shape"].value and not value["relax"]["volume"].value: return "Cannot vary only the shape while keeping the shape constant." diff --git a/conftest.py b/conftest.py index 52b40345..39c17402 100644 --- a/conftest.py +++ b/conftest.py @@ -5,11 +5,12 @@ from __future__ import annotations from collections.abc import Mapping +from contextlib import suppress import os import pathlib import shutil import tempfile -from typing import Any, Optional +from typing import Any from aiida import orm from aiida.common import AttributeDict, CalcInfo, LinkType, exceptions @@ -516,10 +517,7 @@ def db_test_app(aiida_profile, pytestconfig): } test_workdir = get_work_directory(pytestconfig) - if test_workdir: - work_directory = test_workdir - else: - work_directory = tempfile.mkdtemp() + work_directory = test_workdir if test_workdir else tempfile.mkdtemp() yield AiidaTestApp(work_directory, executables, environment=aiida_profile) aiida_profile.clear_profile() @@ -634,7 +632,7 @@ def _generate_calc_job_node( filepath_folder = None if test_name is not None: - basepath = os.path.dirname(os.path.abspath(__file__)) + os.path.dirname(os.path.abspath(__file__)) filepath_folder = os.path.join(TEST_DIR, test_name) entry_point = format_entry_point_string("aiida.calculations", entry_point_name) @@ -670,13 +668,12 @@ def _generate_calc_job_node( if retrieve_temporary: dirpath, filenames = retrieve_temporary for filename in filenames: - try: + with suppress(FileNotFoundError): + # To test the absence of files in the retrieve_temporary folder shutil.copy( os.path.join(filepath_folder, filename), os.path.join(dirpath, filename), ) - except FileNotFoundError: - pass # To test the absence of files in the retrieve_temporary folder if filepath_folder: retrieved = orm.FolderData() @@ -684,10 +681,9 @@ def _generate_calc_job_node( # Remove files that are supposed to be only present in the retrieved temporary folder if retrieve_temporary: for filename in filenames: - try: + with suppress(OSError): + # To test the absence of files in the retrieve_temporary folder retrieved.base.repository.delete_object(filename) - except OSError: - pass # To test the absence of files in the retrieve_temporary folder retrieved.base.links.add_incoming( node, link_type=LinkType.CREATE, link_label="retrieved" @@ -1096,10 +1092,7 @@ def _generate_lammps_results( ): entry_point = format_entry_point_string("aiida.calculations", entry_point_name) - if data: - _results = data - else: - _results = {"compute_variables": {}} + _results = data if data else {"compute_variables": {}} results = orm.Dict(_results) if entry_point_name is not None: creator = orm.CalcJobNode(computer=computer, process_type=entry_point) diff --git a/examples/calculations/launch_lammps_md.py b/examples/calculations/launch_lammps_md.py index a6ed72fb..8b9bdefd 100644 --- a/examples/calculations/launch_lammps_md.py +++ b/examples/calculations/launch_lammps_md.py @@ -146,7 +146,6 @@ def main( if __name__ == "__main__": - # Get the structure that will be used in the calculation STRUCTURE = generate_structure() # Get the potential that will be used in the calculation diff --git a/examples/calculations/launch_lammps_minimize.py b/examples/calculations/launch_lammps_minimize.py index ecdfd1f8..5da8bf8f 100644 --- a/examples/calculations/launch_lammps_minimize.py +++ b/examples/calculations/launch_lammps_minimize.py @@ -148,7 +148,6 @@ def main( if __name__ == "__main__": - # Get the structure that will be used in the calculation STRUCTURE = generate_structure() # Get the potential that will be used in the calculation diff --git a/examples/launch_lammps_base_restart_file.py b/examples/launch_lammps_base_restart_file.py index 8ccda75e..6676b9eb 100644 --- a/examples/launch_lammps_base_restart_file.py +++ b/examples/launch_lammps_base_restart_file.py @@ -191,7 +191,6 @@ def main( if __name__ == "__main__": - # Get the structure that will be used in the calculation STRUCTURE = generate_structure() # Get the potential that will be used in the calculation diff --git a/examples/launch_lammps_base_restart_folder.py b/examples/launch_lammps_base_restart_folder.py index 8ccda75e..6676b9eb 100644 --- a/examples/launch_lammps_base_restart_folder.py +++ b/examples/launch_lammps_base_restart_folder.py @@ -191,7 +191,6 @@ def main( if __name__ == "__main__": - # Get the structure that will be used in the calculation STRUCTURE = generate_structure() # Get the potential that will be used in the calculation diff --git a/examples/launch_lammps_base_script.py b/examples/launch_lammps_base_script.py index 804b14b6..bcfe79d1 100644 --- a/examples/launch_lammps_base_script.py +++ b/examples/launch_lammps_base_script.py @@ -43,7 +43,6 @@ def main( if __name__ == "__main__": - # Get the lammps code defined in AiiDA database CODE = orm.load_code("lammps-23.06.2022@localhost") # Define the parameters for the resources requested for the calculation diff --git a/examples/launch_lammps_raw_script.py b/examples/launch_lammps_raw_script.py index 4dfb3355..abb83145 100644 --- a/examples/launch_lammps_raw_script.py +++ b/examples/launch_lammps_raw_script.py @@ -49,7 +49,7 @@ "https://raw.githubusercontent.com/lammps/lammps/develop/bench/data.rhodo", timeout=20, ) -data = SinglefileData(io.StringIO(request.text)) +data = orm.SinglefileData(io.StringIO(request.text)) builder = plugins.CalculationFactory("lammps.raw").get_builder() builder.code = orm.load_code("lammps-23.06.2022@localhost") diff --git a/pyproject.toml b/pyproject.toml index 0a7c3353..cbacf1fd 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -96,18 +96,12 @@ exclude = [ # reporting which lines of your plugin are covered by tests source=["aiida_lammps"] -[tool.isort] -skip = ["venv"] -# Force imports to be sorted by module, independent of import type -force_sort_within_sections = true -# Group first party and local folder imports together -no_lines_before = ["LOCALFOLDER"] - -# Configure isort to work without access to site-packages -known_first_party = ["aiida_lammps"] - -# Settings for Black compatibility -profile = "black" +[tool.ruff] +extend-select = ["B0", "C4", "I", "ICN", "ISC", "N", "RUF", "SIM", "UP"] +extend-ignore = ["B028", "ISC001"] + +[tool.ruff.lint.isort] +force-sort-within-sections = true [tool.tox] legacy_tox_ini = """ diff --git a/tests/test_calculations.py b/tests/test_calculations.py index c3d400f5..209de4b1 100644 --- a/tests/test_calculations.py +++ b/tests/test_calculations.py @@ -185,8 +185,8 @@ def test_lammps_base( ) def test_lammps_restart_generation( db_test_app, - generate_structure, # pylint: disable=redefined-outer-name # noqa: F811 - get_potential_fe_eam, # pylint: disable=redefined-outer-name # noqa: F811 + generate_structure, # pylint: disable=redefined-outer-name + get_potential_fe_eam, # pylint: disable=redefined-outer-name parameters, restart_parameters, request, diff --git a/tests/test_generate_inputs.py b/tests/test_generate_inputs.py index b89a6a40..528219a7 100644 --- a/tests/test_generate_inputs.py +++ b/tests/test_generate_inputs.py @@ -6,7 +6,6 @@ from aiida_lammps.data.potential import LammpsPotentialData from aiida_lammps.parsers import inputfile from aiida_lammps.validation.utils import validate_against_schema -from .utils import TEST_DIR def validate_input_parameters(parameters: dict): diff --git a/tests/test_generate_structure.py b/tests/test_generate_structure.py index db7708a4..669f8930 100644 --- a/tests/test_generate_structure.py +++ b/tests/test_generate_structure.py @@ -8,9 +8,7 @@ "structure", ["Fe", "pyrite", "fes_cubic-zincblende", "greigite"], ) -def test_generate( - db_test_app, get_structure_data, structure, file_regression -): # pylint: disable=unused-argument +def test_generate(db_test_app, get_structure_data, structure, file_regression): # pylint: disable=unused-argument """Test the structure generation in aiida-lammps""" structure = get_structure_data(structure) text, _ = generate_lammps_structure(structure, round_dp=8) diff --git a/tests/test_parsers.py b/tests/test_parsers.py index 74d073ac..d227dfcf 100644 --- a/tests/test_parsers.py +++ b/tests/test_parsers.py @@ -6,6 +6,7 @@ from aiida.plugins import ParserFactory from aiida_lammps.parsers.parse_raw import parse_final_data, parse_outputfile + from .utils import TEST_DIR diff --git a/tests/test_potential_data.py b/tests/test_potential_data.py index 58d9faef..dc26c212 100644 --- a/tests/test_potential_data.py +++ b/tests/test_potential_data.py @@ -6,6 +6,7 @@ from aiida_lammps.data.potential import LammpsPotentialData from aiida_lammps.parsers import inputfile + from .utils import TEST_DIR diff --git a/tests/test_trajectory.py b/tests/test_trajectory.py index 100d2f7d..50b56c5d 100644 --- a/tests/test_trajectory.py +++ b/tests/test_trajectory.py @@ -3,6 +3,7 @@ from aiida_lammps.data.trajectory import LammpsTrajectory from aiida_lammps.parsers.parse_raw import create_structure, iter_trajectories + from .utils import TEST_DIR, recursive_round @@ -19,9 +20,7 @@ def test_iter_trajectories(data_regression): data_regression.check(output) -def test_create_structure( - db_test_app, data_regression -): # pylint: disable=unused-argument +def test_create_structure(db_test_app, data_regression): # pylint: disable=unused-argument """Test that one can create an structure from a trajectory step""" path = os.path.join(TEST_DIR, "input_files", "trajectory.lammpstrj") with open(path) as handle: @@ -33,27 +32,21 @@ def test_create_structure( ) -def test_lammps_trajectory_data( - db_test_app, data_regression -): # pylint: disable=unused-argument +def test_lammps_trajectory_data(db_test_app, data_regression): # pylint: disable=unused-argument """Test that one can generate a trajectory from a file""" path = os.path.join(TEST_DIR, "input_files", "trajectory.lammpstrj") data = LammpsTrajectory(path) data_regression.check(data.base.attributes.all) -def test_lammpstraj_get_step_string( - db_test_app, file_regression -): # pylint: disable=unused-argument +def test_lammpstraj_get_step_string(db_test_app, file_regression): # pylint: disable=unused-argument """Get the step information from a trajectory data file""" path = os.path.join(TEST_DIR, "input_files", "trajectory.lammpstrj") data = LammpsTrajectory(path) file_regression.check(data.get_step_string(-1)) -def test_lammpstraj_get_step_struct( - db_test_app, data_regression -): # pylint: disable=unused-argument +def test_lammpstraj_get_step_struct(db_test_app, data_regression): # pylint: disable=unused-argument """Get the structure data for a given trajectory step""" path = os.path.join(TEST_DIR, "input_files", "trajectory.lammpstrj") data = LammpsTrajectory(path) diff --git a/tests/test_workflows.py b/tests/test_workflows.py index baa99815..a9cdd6d6 100644 --- a/tests/test_workflows.py +++ b/tests/test_workflows.py @@ -9,6 +9,7 @@ from aiida_lammps.calculations.base import LammpsBaseCalculation from aiida_lammps.workflows.base import LammpsBaseWorkChain + from .utils import get_default_metadata, recursive_round @@ -26,7 +27,6 @@ def _generate_workchain_base( return_inputs=False, lammps_base_outputs=None, ): - entry_point = "lammps.base" if inputs is None: @@ -75,11 +75,9 @@ def _generate_workchain_relax( return_inputs=False, lammps_base_outputs=None, ): - entry_point = "lammps.relax" if inputs is None: - _inputs = generate_inputs_minimize() _parameters = _inputs["parameters"].get_dict() @@ -142,14 +140,12 @@ def test_handle_unrecoverable_failure(generate_workchain_base): assert isinstance(result, ProcessHandlerReport) assert result.do_break assert ( - result.exit_code - == LammpsBaseWorkChain.exit_codes.ERROR_UNRECOVERABLE_FAILURE # pylint: disable=no-member + result.exit_code == LammpsBaseWorkChain.exit_codes.ERROR_UNRECOVERABLE_FAILURE # pylint: disable=no-member ) result = process.inspect_process() assert ( - result - == LammpsBaseWorkChain.exit_codes.ERROR_UNRECOVERABLE_FAILURE # pylint: disable=no-member + result == LammpsBaseWorkChain.exit_codes.ERROR_UNRECOVERABLE_FAILURE # pylint: disable=no-member ) From 3843bd8bef52326d918d5c4b29a66f78cf580f79 Mon Sep 17 00:00:00 2001 From: Chris Sewell Date: Tue, 28 Nov 2023 16:04:32 +0000 Subject: [PATCH 2/3] Update pyproject.toml --- pyproject.toml | 7 ------- 1 file changed, 7 deletions(-) diff --git a/pyproject.toml b/pyproject.toml index cbacf1fd..9ed3c836 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -46,13 +46,6 @@ tests = [ "pytest-regressions" ] -pre-commit = [ - 'pre-commit~=2.17', - 'pylint~=2.17.2', - 'pylint-aiida~=0.1.1', - 'toml', -] - docs = [ 'sphinx~=6.2.1', 'sphinx-copybutton~=0.5.2', From 24ed85a6f59f94135cc1cc649311a8819bd3ecf4 Mon Sep 17 00:00:00 2001 From: Chris Sewell Date: Tue, 28 Nov 2023 16:06:42 +0000 Subject: [PATCH 3/3] update --- README.md | 12 +++--------- pyproject.toml | 12 ------------ 2 files changed, 3 insertions(+), 21 deletions(-) diff --git a/README.md b/README.md index a3f36b12..ca79ac2a 100644 --- a/README.md +++ b/README.md @@ -107,11 +107,10 @@ pytest --lammps-workdir "test_workdir" ### Pre-commit -The code is formatted and linted using [pre-commit](https://pre-commit.com/), so that the code conform to the standard. One must simply install the repository with the `pre-commit` extra dependencies: +The code is formatted and linted using [pre-commit](https://pre-commit.com/), so that the code conform to the standard: ```shell cd aiida-lammps -pip install -e .[pre-commit] pre-commit run --all ``` or to automate runs, triggered before each commit: @@ -120,11 +119,6 @@ or to automate runs, triggered before each commit: pre-commit install ``` -The pre-commit can also be run in an isolated environment via `tox` with: - -```shell -tox -e pre-commit -``` - ## License -The `aiida-lammps` plugin package is released under the MIT license. See the `LICENSE.txt` file for more details. + +The `aiida-lammps` plugin package is released under the MIT license. See the `LICENSE` file for more details. diff --git a/pyproject.toml b/pyproject.toml index 9ed3c836..f357a919 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -114,13 +114,6 @@ commands = rm -r {toxworkdir}/.aiida extras = tests -[testenv:pre-commit] -allowlist_externals = bash -commands = bash -ec 'pre-commit run --all-files || ( git diff; git status; exit 1; )' -extras = - pre-commit - tests - [testenv:docs-{clean,update}] extras = docs description = @@ -148,9 +141,4 @@ filterwarnings = markers = lammps_call: calls the lammps executable -[flake8] -max-line-length = 140 -import-order-style = edited -[pycodestyle] -max-line-length = 140 """