Skip to content

Commit

Permalink
Update ruff linter (#398)
Browse files Browse the repository at this point in the history
* Update ruff linter

* add keys again

* fix

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* fix tests

---------

Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
  • Loading branch information
jan-janssen and pre-commit-ci[bot] authored Feb 4, 2025
1 parent 831e0ae commit 82f1323
Show file tree
Hide file tree
Showing 29 changed files with 209 additions and 221 deletions.
2 changes: 1 addition & 1 deletion .pre-commit-config.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ repos:
hooks:
- id: ruff
name: ruff lint
args: ["--select", "I", "--fix"]
args: ["--fix"]
files: ^atomistics/
- id: ruff-format
name: ruff format
48 changes: 24 additions & 24 deletions atomistics/calculators/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,14 +10,14 @@
from atomistics.calculators.hessian import evaluate_with_hessian

__all__ = [
calc_molecular_dynamics_langevin_with_ase,
calc_molecular_dynamics_npt_with_ase,
calc_molecular_dynamics_thermal_expansion_with_ase,
calc_static_with_ase,
evaluate_with_ase,
optimize_positions_with_ase,
optimize_positions_and_volume_with_ase,
evaluate_with_hessian,
"calc_molecular_dynamics_langevin_with_ase",
"calc_molecular_dynamics_npt_with_ase",
"calc_molecular_dynamics_thermal_expansion_with_ase",
"calc_static_with_ase",
"evaluate_with_ase",
"optimize_positions_with_ase",
"optimize_positions_and_volume_with_ase",
"evaluate_with_hessian",
]


Expand All @@ -29,9 +29,9 @@
)

__all__ += [
calc_static_with_qe,
evaluate_with_qe,
optimize_positions_and_volume_with_qe,
"calc_static_with_qe",
"evaluate_with_qe",
"optimize_positions_and_volume_with_qe",
]
except ImportError:
pass
Expand All @@ -53,18 +53,18 @@
)

__all__ += [
calc_molecular_dynamics_thermal_expansion_with_lammps,
calc_molecular_dynamics_nph_with_lammps,
calc_molecular_dynamics_npt_with_lammps,
calc_molecular_dynamics_nvt_with_lammps,
calc_molecular_dynamics_langevin_with_lammps,
calc_static_with_lammps,
evaluate_with_lammps,
evaluate_with_lammps_library,
get_potential_dataframe,
get_potential_by_name,
optimize_positions_and_volume_with_lammps,
optimize_positions_with_lammps,
"calc_molecular_dynamics_thermal_expansion_with_lammps",
"calc_molecular_dynamics_nph_with_lammps",
"calc_molecular_dynamics_npt_with_lammps",
"calc_molecular_dynamics_nvt_with_lammps",
"calc_molecular_dynamics_langevin_with_lammps",
"calc_static_with_lammps",
"evaluate_with_lammps",
"evaluate_with_lammps_library",
"get_potential_dataframe",
"get_potential_by_name",
"optimize_positions_and_volume_with_lammps",
"optimize_positions_with_lammps",
]
except ImportError:
pass
Expand All @@ -74,6 +74,6 @@
calc_molecular_dynamics_phonons_with_lammps,
)

__all__ += [calc_molecular_dynamics_phonons_with_lammps]
__all__ += ["calc_molecular_dynamics_phonons_with_lammps"]
except ImportError:
pass
68 changes: 10 additions & 58 deletions atomistics/calculators/ase.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,5 @@
from __future__ import annotations

from typing import List

import numpy as np
from ase import units
from ase.atoms import Atoms
Expand All @@ -24,7 +22,7 @@
from atomistics.shared.tqdm_iterator import get_tqdm_iterator


class ASEExecutor(object):
class ASEExecutor:
def __init__(self, ase_structure: Atoms, ase_calculator: ASECalculator) -> None:
"""
Initialize the ASEExecutor.
Expand Down Expand Up @@ -147,10 +145,10 @@ def volume(self) -> float:
@as_task_dict_evaluator
def evaluate_with_ase(
structure: Atoms,
tasks: List[str],
tasks: list[str],
ase_calculator: ASECalculator,
ase_optimizer: Optimizer = None,
ase_optimizer_kwargs: dict = {},
ase_optimizer_kwargs: dict = None,
) -> dict:
"""
Evaluate tasks using ASE calculator.
Expand All @@ -165,6 +163,8 @@ def evaluate_with_ase(
Returns:
dict: Dictionary containing the results of the evaluated tasks.
"""
if ase_optimizer_kwargs is None:
ase_optimizer_kwargs = {}
results = {}
if "optimize_positions" in tasks:
results["structure_with_optimized_positions"] = optimize_positions_with_ase(
Expand Down Expand Up @@ -215,54 +215,6 @@ def calc_static_with_ase(
)


def optimize_positions_with_ase(
structure: Atoms,
ase_calculator: ASECalculator,
ase_optimizer: Optimizer,
ase_optimizer_kwargs: dict,
) -> Atoms:
"""
Optimize the atomic positions of the structure using ASE optimizer.
Args:
structure (Atoms): The ASE structure object.
ase_calculator (ASECalculator): The ASE calculator object.
ase_optimizer (Optimizer): The ASE optimizer object.
ase_optimizer_kwargs (dict): Keyword arguments for the ASE optimizer.
Returns:
Atoms: The optimized structure.
"""
structure.set_calculator(ase_calculator)
dyn = ase_optimizer(structure, **ase_optimizer_kwargs)
dyn.run(fmax=0.05)
return structure


def optimize_positions_and_volume_with_ase(
structure: Atoms,
ase_calculator: ASECalculator,
ase_optimizer: Optimizer,
ase_optimizer_kwargs: dict,
) -> Atoms:
"""
Optimize the atomic positions and cell volume of the structure using ASE optimizer.
Args:
structure (Atoms): The ASE structure object.
ase_calculator (ASECalculator): The ASE calculator object.
ase_optimizer (Optimizer): The ASE optimizer object.
ase_optimizer_kwargs (dict): Keyword arguments for the ASE optimizer.
Returns:
Atoms: The optimized structure.
"""
structure.set_calculator(ase_calculator)
dyn = ase_optimizer(structure, **ase_optimizer_kwargs)
dyn.run(fmax=0.05, volume=True)
return structure


def calc_molecular_dynamics_langevin_with_ase(
structure: Atoms,
ase_calculator: ASECalculator,
Expand All @@ -271,7 +223,7 @@ def calc_molecular_dynamics_langevin_with_ase(
timestep: float = 1.0,
temperature: float = 100.0,
friction: float = 0.002,
output_keys: List[str] = OutputMolecularDynamics.keys(),
output_keys: list[str] = OutputMolecularDynamics.keys(),
) -> dict:
"""
Perform molecular dynamics simulation using the Langevin algorithm with ASE.
Expand Down Expand Up @@ -367,7 +319,7 @@ def calc_molecular_dynamics_thermal_expansion_with_ase(
ttime: float = 100 * units.fs,
pfactor: float = 2e6 * units.GPa * (units.fs**2),
externalstress: np.ndarray = np.array([0.0, 0.0, 0.0, 0.0, 0.0, 0.0]) * units.bar,
output_keys: List[str] = OutputThermalExpansion.keys(),
output_keys: list[str] = OutputThermalExpansion.keys(),
) -> dict:
"""
Calculate thermal expansion using molecular dynamics simulation with ASE.
Expand Down Expand Up @@ -426,7 +378,7 @@ def calc_molecular_dynamics_npt_with_ase(
pfactor: float = 2e6 * units.GPa * (units.fs**2),
temperature: float = 300.0,
externalstress: np.ndarray = np.array([0.0, 0.0, 0.0, 0.0, 0.0, 0.0]) * units.bar,
output_keys: List[str] = OutputMolecularDynamics.keys(),
output_keys: list[str] = OutputMolecularDynamics.keys(),
) -> dict:
"""
Perform NPT molecular dynamics simulation using ASE.
Expand Down Expand Up @@ -477,7 +429,7 @@ def _calc_molecular_dynamics_with_ase(
temperature: float,
run: int,
thermo: int,
output_keys: List[str],
output_keys: list[str],
) -> dict:
"""
Perform molecular dynamics simulation using ASE.
Expand All @@ -497,7 +449,7 @@ def _calc_molecular_dynamics_with_ase(
structure.calc = ase_calculator
MaxwellBoltzmannDistribution(atoms=structure, temperature_K=temperature)
cache = {q: [] for q in output_keys}
for i in range(int(run / thermo)):
for _i in range(int(run / thermo)):
dyn.run(thermo)
ase_instance = ASEExecutor(
ase_structure=structure, ase_calculator=ase_calculator
Expand Down
4 changes: 2 additions & 2 deletions atomistics/calculators/hessian.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
from typing import Tuple, Union
from typing import Union

import numpy as np
from ase.atoms import Atoms
Expand Down Expand Up @@ -68,7 +68,7 @@ def get_displacement(structure_equilibrium: Atoms, structure: Atoms) -> np.ndarr

def calc_forces_transformed(
force_constants: np.ndarray, structure_equilibrium: Atoms, structure: Atoms
) -> Tuple[np.ndarray, np.ndarray]:
) -> tuple[np.ndarray, np.ndarray]:
"""
Calculate the transformed forces and displacements.
Expand Down
26 changes: 13 additions & 13 deletions atomistics/calculators/lammps/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,23 +21,23 @@
)

__all__ = [
calc_molecular_dynamics_phonons_with_lammps,
"calc_molecular_dynamics_phonons_with_lammps",
]
except ImportError:
__all__ = []


__all__ += [
calc_molecular_dynamics_thermal_expansion_with_lammps,
calc_molecular_dynamics_nph_with_lammps,
calc_molecular_dynamics_npt_with_lammps,
calc_molecular_dynamics_nvt_with_lammps,
calc_molecular_dynamics_langevin_with_lammps,
calc_static_with_lammps,
evaluate_with_lammps,
evaluate_with_lammps_library,
optimize_positions_and_volume_with_lammps,
optimize_positions_with_lammps,
get_potential_dataframe,
get_potential_by_name,
"calc_molecular_dynamics_thermal_expansion_with_lammps",
"calc_molecular_dynamics_nph_with_lammps",
"calc_molecular_dynamics_npt_with_lammps",
"calc_molecular_dynamics_nvt_with_lammps",
"calc_molecular_dynamics_langevin_with_lammps",
"calc_static_with_lammps",
"evaluate_with_lammps",
"evaluate_with_lammps_library",
"optimize_positions_and_volume_with_lammps",
"optimize_positions_with_lammps",
"get_potential_dataframe",
"get_potential_by_name",
]
8 changes: 6 additions & 2 deletions atomistics/calculators/lammps/calculator.py
Original file line number Diff line number Diff line change
Expand Up @@ -426,8 +426,10 @@ def evaluate_with_lammps_library(
tasks: list[TaskName],
potential_dataframe: DataFrame,
lmp: LammpsASELibrary,
lmp_optimizer_kwargs: dict = {},
lmp_optimizer_kwargs: dict = None,
) -> dict:
if lmp_optimizer_kwargs is None:
lmp_optimizer_kwargs = {}
results = {}
if "optimize_positions_and_volume" in tasks:
results["structure_with_optimized_positions_and_volume"] = (
Expand Down Expand Up @@ -478,8 +480,10 @@ def evaluate_with_lammps(
log_file=None,
library=None,
disable_log_file: bool = True,
lmp_optimizer_kwargs={},
lmp_optimizer_kwargs=None,
) -> dict:
if lmp_optimizer_kwargs is None:
lmp_optimizer_kwargs = {}
lmp = LammpsASELibrary(
working_directory=working_directory,
cores=cores,
Expand Down
20 changes: 12 additions & 8 deletions atomistics/calculators/lammps/phonon.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
import sys

import dynaphopy.dynamics as dyn
import numpy as np
import pandas
Expand All @@ -24,27 +26,27 @@ def generate_pylammps_trajectory(
sampling_interval: int = 1, # in timesteps
):
lmp.interactive_lib_command("neighbor 0.3 bin")
lmp.interactive_lib_command("timestep {}".format(time_step))
lmp.interactive_lib_command(f"timestep {time_step}")

# Force reset temperature (overwrites lammps script)
# This forces NVT simulation
if temperature is not None:
lmp.interactive_lib_command(
"fix int all nvt temp {0} {0} {1}".format(temperature, thermostat_mass)
f"fix int all nvt temp {temperature} {temperature} {thermostat_mass}"
)

# Check if correct number of atoms
if lmp._interactive_library.extract_global("natoms", 0) < 2:
print("Number of atoms in MD should be higher than 1!")
exit()
sys.exit()

# Check if initial velocities all zero
if not np.array(lmp._interactive_library.gather_atoms("v", 1, 3)).any():
t = temperature if temperature is not None else 100
lmp.interactive_lib_command(
"velocity all create {} 3627941 dist gaussian mom yes".format(t)
f"velocity all create {t} 3627941 dist gaussian mom yes"
)
lmp.interactive_lib_command("velocity all scale {}".format(t))
lmp.interactive_lib_command(f"velocity all scale {t}")

lmp.interactive_lib_command("run 0")
simulation_cell = lmp.interactive_cells_getter()
Expand All @@ -57,7 +59,7 @@ def generate_pylammps_trajectory(
template = get_correct_arrangement(reference, structure)
indexing = np.argsort(template)

lmp.interactive_lib_command("run {}".format(int(relaxation_time / time_step)))
lmp.interactive_lib_command(f"run {int(relaxation_time / time_step)}")

if not silent:
_progress_bar(0, "lammps")
Expand All @@ -70,7 +72,7 @@ def generate_pylammps_trajectory(
"lammps",
)

lmp.interactive_lib_command("run {}".format(sampling_interval))
lmp.interactive_lib_command(f"run {sampling_interval}")
energy.append(lmp.interactive_energy_pot_getter())
velocity.append(lmp.interactive_velocities_getter()[indexing, :])

Expand Down Expand Up @@ -103,11 +105,13 @@ def calc_molecular_dynamics_phonons_with_lammps(
time_step: float = 0.001, # ps
relaxation_time: int = 5, # ps
silent: bool = True,
supercell: list[int] = [2, 2, 2],
supercell: list[int] = None,
memmap: bool = False,
velocity_only: bool = True,
temperature: float = 300.0,
):
if supercell is None:
supercell = [2, 2, 2]
dp_structure = Structure(
cell=phonopy_unitcell.get_cell(),
scaled_positions=phonopy_unitcell.get_scaled_positions(),
Expand Down
Loading

0 comments on commit 82f1323

Please sign in to comment.