Skip to content

Commit

Permalink
lint: ruff safe fixes
Browse files Browse the repository at this point in the history
  • Loading branch information
CompRhys committed Aug 20, 2024
1 parent 647e6af commit 60f207d
Show file tree
Hide file tree
Showing 58 changed files with 154 additions and 122 deletions.
2 changes: 2 additions & 0 deletions mace/__init__.py
Original file line number Diff line number Diff line change
@@ -1 +1,3 @@
from __future__ import annotations

from .__version__ import __version__
2 changes: 2 additions & 0 deletions mace/__version__.py
Original file line number Diff line number Diff line change
@@ -1 +1,3 @@
from __future__ import annotations

__version__ = "0.3.6"
2 changes: 2 additions & 0 deletions mace/calculators/__init__.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
from __future__ import annotations

from .foundations_models import mace_anicc, mace_mp, mace_off
from .lammps_mace import LAMMPS_MACE
from .mace import MACECalculator
Expand Down
2 changes: 2 additions & 0 deletions mace/calculators/foundations_models.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
from __future__ import annotations

import os
import urllib.request
from pathlib import Path
Expand Down
2 changes: 2 additions & 0 deletions mace/calculators/lammps_mace.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
from __future__ import annotations

from typing import Dict, List, Optional

import torch
Expand Down
2 changes: 1 addition & 1 deletion mace/calculators/mace.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
# Authors: Ilyes Batatia, David Kovacs
# This program is distributed under the MIT License (see MIT.md)
###########################################################################################

from __future__ import annotations

from glob import glob
from pathlib import Path
Expand Down
1 change: 1 addition & 0 deletions mace/cli/active_learning_md.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
"""Demonstrates active learning molecular dynamics with constant temperature."""
from __future__ import annotations

import argparse
import os
Expand Down
2 changes: 2 additions & 0 deletions mace/cli/create_lammps_model.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
from __future__ import annotations

import sys

import torch
Expand Down
1 change: 1 addition & 0 deletions mace/cli/eval_configs.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
# Authors: Ilyes Batatia, Gregor Simm
# This program is distributed under the MIT License (see MIT.md)
###########################################################################################
from __future__ import annotations

import argparse

Expand Down
4 changes: 3 additions & 1 deletion mace/cli/plot_train.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
from __future__ import annotations

import argparse
import dataclasses
import glob
Expand Down Expand Up @@ -49,7 +51,7 @@ def parse_path(path: str) -> RunInfo:
def parse_training_results(path: str) -> List[dict]:
run_info = parse_path(path)
results = []
with open(path, mode="r", encoding="utf-8") as f:
with open(path, encoding="utf-8") as f:
for line in f:
d = json.loads(line)
d["name"] = run_info.name
Expand Down
5 changes: 3 additions & 2 deletions mace/cli/preprocess_data.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
# This file loads an xyz dataset and prepares
# new hdf5 file that is ready for training with on-the-fly dataloading
from __future__ import annotations

import argparse
import ast
Expand Down Expand Up @@ -77,7 +78,7 @@ def split_array(a: np.ndarray, max_size: int):
factors = get_prime_factors(len(a))
max_factor = 1
for i in range(1, len(factors) + 1):
for j in range(0, len(factors) - i + 1):
for j in range(len(factors) - i + 1):
if np.prod(factors[j : j + i]) <= max_size:
test = np.prod(factors[j : j + i])
max_factor = max(test, max_factor)
Expand Down Expand Up @@ -208,7 +209,7 @@ def run(args: argparse.Namespace):
[atomic_energies_dict[z] for z in z_table.zs]
)
logging.info(f"Atomic energies: {atomic_energies.tolist()}")
_inputs = [args.h5_prefix+'train', z_table, args.r_max, atomic_energies, args.batch_size, args.num_process]
_inputs = [args.h5_prefix+"train", z_table, args.r_max, atomic_energies, args.batch_size, args.num_process]
avg_num_neighbors, mean, std=pool_compute_stats(_inputs)
logging.info(f"Average number of neighbors: {avg_num_neighbors}")
logging.info(f"Mean: {mean}")
Expand Down
33 changes: 16 additions & 17 deletions mace/cli/run_train.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
# Authors: Ilyes Batatia, Gregor Simm, David Kovacs
# This program is distributed under the MIT License (see MIT.md)
###########################################################################################
from __future__ import annotations

import argparse
import ast
Expand Down Expand Up @@ -60,7 +61,7 @@ def run(args: argparse.Namespace) -> None:
try:
distr_env = DistributedEnvironment()
except Exception as e: # pylint: disable=W0703
logging.error(f"Failed to initialize distributed environment: {e}")
logging.exception(f"Failed to initialize distributed environment: {e}")
return
world_size = distr_env.world_size
local_rank = distr_env.local_rank
Expand All @@ -69,7 +70,7 @@ def run(args: argparse.Namespace) -> None:
print(distr_env)
torch.distributed.init_process_group(backend="nccl")
else:
rank = int(0)
rank = 0

# Setup
tools.set_seeds(args.seed)
Expand Down Expand Up @@ -113,7 +114,7 @@ def run(args: argparse.Namespace) -> None:
args.r_max = model_foundation.r_max.item()

if args.statistics_file is not None:
with open(args.statistics_file, "r") as f: # pylint: disable=W1514
with open(args.statistics_file) as f: # pylint: disable=W1514
statistics = json.load(f)
logging.info("Using statistics json file")
args.r_max = statistics["r_max"] if args.foundation_model is None else args.r_max
Expand Down Expand Up @@ -182,11 +183,10 @@ def run(args: argparse.Namespace) -> None:
z: model_foundation.atomic_energies_fn.atomic_energies[z_table_foundation.z_to_index(z)].item()
for z in z_table.zs
}
elif args.train_file.endswith(".xyz"):
atomic_energies_dict = get_atomic_energies(args.E0s, collections.train, z_table)
else:
if args.train_file.endswith(".xyz"):
atomic_energies_dict = get_atomic_energies(args.E0s, collections.train, z_table)
else:
atomic_energies_dict = get_atomic_energies(args.E0s, None, z_table)
atomic_energies_dict = get_atomic_energies(args.E0s, None, z_table)

if args.model == "AtomicDipolesMACE":
atomic_energies = None
Expand Down Expand Up @@ -540,13 +540,12 @@ def run(args: argparse.Namespace) -> None:
swas.append(True)
if args.start_swa is None:
args.start_swa = max(1, args.max_num_epochs // 4 * 3)
else:
if args.start_swa > args.max_num_epochs:
logging.info(
f"Start Stage Two must be less than max_num_epochs, got {args.start_swa} > {args.max_num_epochs}"
)
args.start_swa = max(1, args.max_num_epochs // 4 * 3)
logging.info(f"Setting start Stage Two to {args.start_swa}")
elif args.start_swa > args.max_num_epochs:
logging.info(
f"Start Stage Two must be less than max_num_epochs, got {args.start_swa} > {args.max_num_epochs}"
)
args.start_swa = max(1, args.max_num_epochs // 4 * 3)
logging.info(f"Setting start Stage Two to {args.start_swa}")
if args.loss == "forces_only":
raise ValueError("Can not select Stage Two with forces only loss.")
if args.loss == "virials":
Expand Down Expand Up @@ -712,7 +711,7 @@ def run(args: argparse.Namespace) -> None:
)
try:
drop_last = test_set.drop_last
except AttributeError as e: # pylint: disable=W0612
except AttributeError: # pylint: disable=W0612
drop_last = False
test_loader = torch_geometric.dataloader.DataLoader(
test_set,
Expand Down Expand Up @@ -775,7 +774,7 @@ def run(args: argparse.Namespace) -> None:
path_complied,
_extra_files=extra_files,
)
except Exception as e: # pylint: disable=W0703
except Exception: # pylint: disable=W0703
pass
else:
torch.save(model, Path(args.model_dir) / (args.name + ".model"))
Expand All @@ -788,7 +787,7 @@ def run(args: argparse.Namespace) -> None:
path_complied,
_extra_files=extra_files,
)
except Exception as e: # pylint: disable=W0703
except Exception: # pylint: disable=W0703
pass

if args.distributed:
Expand Down
2 changes: 2 additions & 0 deletions mace/data/__init__.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
from __future__ import annotations

from .atomic_data import AtomicData
from .hdf5_dataset import HDF5Dataset, dataset_from_sharded_hdf5
from .neighborhood import get_neighborhood
Expand Down
11 changes: 3 additions & 8 deletions mace/data/atomic_data.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,18 +3,13 @@
# Authors: Ilyes Batatia, Gregor Simm
# This program is distributed under the MIT License (see MIT.md)
###########################################################################################
from __future__ import annotations

from typing import Optional, Sequence

import torch.utils.data

from mace.tools import (
AtomicNumberTable,
atomic_numbers_to_indices,
to_one_hot,
torch_geometric,
voigt_to_matrix,
)
from mace.tools import AtomicNumberTable, atomic_numbers_to_indices, to_one_hot, torch_geometric, voigt_to_matrix

from .neighborhood import get_neighborhood
from .utils import Configuration
Expand Down Expand Up @@ -107,7 +102,7 @@ def __init__(
super().__init__(**data)

@classmethod
def from_config(cls, config: Configuration, z_table: AtomicNumberTable, cutoff: float) -> "AtomicData":
def from_config(cls, config: Configuration, z_table: AtomicNumberTable, cutoff: float) -> AtomicData:
edge_index, shifts, unit_shifts = get_neighborhood(
positions=config.positions, cutoff=cutoff, pbc=config.pbc, cell=config.cell
)
Expand Down
2 changes: 2 additions & 0 deletions mace/data/hdf5_dataset.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
from __future__ import annotations

from glob import glob
from typing import List

Expand Down
2 changes: 2 additions & 0 deletions mace/data/neighborhood.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
from __future__ import annotations

from typing import Optional, Tuple

import numpy as np
Expand Down
3 changes: 2 additions & 1 deletion mace/data/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
# Authors: Ilyes Batatia, Gregor Simm and David Kovacs
# This program is distributed under the MIT License (see MIT.md)
###########################################################################################
from __future__ import annotations

import logging
from dataclasses import dataclass
Expand Down Expand Up @@ -226,7 +227,7 @@ def load_from_xyz(
for atoms in atoms_list:
try:
atoms.info["REF_stress"] = atoms.get_stress()
except Exception as e: # pylint: disable=W0703
except Exception: # pylint: disable=W0703
atoms.info["REF_stress"] = None
if not isinstance(atoms_list, list):
atoms_list = [atoms_list]
Expand Down
11 changes: 3 additions & 8 deletions mace/modules/__init__.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
from __future__ import annotations

from typing import Callable, Dict, Optional, Type

import torch
Expand Down Expand Up @@ -30,14 +32,7 @@
WeightedForcesLoss,
WeightedHuberEnergyForcesStressLoss,
)
from .models import (
MACE,
AtomicDipolesMACE,
BOTNet,
EnergyDipolesMACE,
ScaleShiftBOTNet,
ScaleShiftMACE,
)
from .models import MACE, AtomicDipolesMACE, BOTNet, EnergyDipolesMACE, ScaleShiftBOTNet, ScaleShiftMACE
from .radial import BesselBasis, GaussianBasis, PolynomialCutoff, ZBLBasis
from .symmetric_contraction import SymmetricContraction
from .utils import (
Expand Down
16 changes: 3 additions & 13 deletions mace/modules/blocks.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
# Authors: Ilyes Batatia, Gregor Simm
# This program is distributed under the MIT License (see MIT.md)
###########################################################################################
from __future__ import annotations

from abc import abstractmethod
from typing import Callable, List, Optional, Tuple, Union
Expand All @@ -15,19 +16,8 @@
from mace.tools.compile import simplify_if_compile
from mace.tools.scatter import scatter_sum

from .irreps_tools import (
linear_out_irreps,
reshape_irreps,
tp_out_irreps_with_instructions,
)
from .radial import (
AgnesiTransform,
BesselBasis,
ChebychevBasis,
GaussianBasis,
PolynomialCutoff,
SoftTransform,
)
from .irreps_tools import linear_out_irreps, reshape_irreps, tp_out_irreps_with_instructions
from .radial import AgnesiTransform, BesselBasis, ChebychevBasis, GaussianBasis, PolynomialCutoff, SoftTransform
from .symmetric_contraction import SymmetricContraction


Expand Down
1 change: 1 addition & 0 deletions mace/modules/irreps_tools.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
# Authors: Ilyes Batatia, Gregor Simm
# This program is distributed under the MIT License (see MIT.md)
###########################################################################################
from __future__ import annotations

from typing import List, Tuple

Expand Down
1 change: 1 addition & 0 deletions mace/modules/loss.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
# Authors: Ilyes Batatia, Gregor Simm
# This program is distributed under the MIT License (see MIT.md)
###########################################################################################
from __future__ import annotations

import torch

Expand Down
1 change: 1 addition & 0 deletions mace/modules/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
# Authors: Ilyes Batatia, Gregor Simm
# This program is distributed under the MIT License (see MIT.md)
###########################################################################################
from __future__ import annotations

from typing import Any, Callable, Dict, List, Optional, Type, Union

Expand Down
1 change: 1 addition & 0 deletions mace/modules/radial.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
# Authors: Ilyes Batatia, Gregor Simm
# This program is distributed under the MIT License (see MIT.md)
###########################################################################################
from __future__ import annotations

import ase
import numpy as np
Expand Down
1 change: 1 addition & 0 deletions mace/modules/symmetric_contraction.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
# Authors: Ilyes Batatia
# This program is distributed under the MIT License (see MIT.md)
###########################################################################################
from __future__ import annotations

from typing import Dict, Optional, Union

Expand Down
1 change: 1 addition & 0 deletions mace/modules/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
# Authors: Ilyes Batatia, Gregor Simm and David Kovacs
# This program is distributed under the MIT License (see MIT.md)
###########################################################################################
from __future__ import annotations

import logging
from typing import List, Optional, Tuple
Expand Down
2 changes: 2 additions & 0 deletions mace/tools/__init__.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
from __future__ import annotations

from .arg_parser import build_default_arg_parser, build_preprocess_arg_parser
from .cg import U_matrix_real
from .checkpoint import CheckpointHandler, CheckpointIO, CheckpointState
Expand Down
1 change: 1 addition & 0 deletions mace/tools/arg_parser.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
# Authors: Ilyes Batatia, Gregor Simm, David Kovacs
# This program is distributed under the MIT License (see MIT.md)
###########################################################################################
from __future__ import annotations

import argparse
import os
Expand Down
1 change: 1 addition & 0 deletions mace/tools/cg.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
# Authors: Ilyes Batatia
# This program is distributed under the MIT License (see MIT.md)
###########################################################################################
from __future__ import annotations

import collections
from typing import List, Union
Expand Down
1 change: 1 addition & 0 deletions mace/tools/checkpoint.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
# Authors: Gregor Simm
# This program is distributed under the MIT License (see MIT.md)
###########################################################################################
from __future__ import annotations

import dataclasses
import logging
Expand Down
2 changes: 2 additions & 0 deletions mace/tools/compile.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
from __future__ import annotations

from contextlib import contextmanager
from functools import wraps
from typing import Callable, Tuple
Expand Down
2 changes: 2 additions & 0 deletions mace/tools/finetuning_utils.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
from __future__ import annotations

import torch

from mace.tools.utils import AtomicNumberTable
Expand Down
Loading

0 comments on commit 60f207d

Please sign in to comment.