Skip to content

Commit

Permalink
Merge branch 'master' into dependabot/pip/tensorflow-2.9.1
Browse files Browse the repository at this point in the history
  • Loading branch information
shyuep authored Aug 1, 2022
2 parents 1c58caf + df64d74 commit 52d628c
Show file tree
Hide file tree
Showing 33 changed files with 433 additions and 417 deletions.
10 changes: 5 additions & 5 deletions .pre-commit-config.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -21,13 +21,13 @@ repos:
- --ignore-init-module-imports

- repo: https://github.com/asottile/pyupgrade
rev: v2.32.0
rev: v2.37.3
hooks:
- id: pyupgrade
args: [--py38-plus]

- repo: https://github.com/pre-commit/pre-commit-hooks
rev: v4.2.0
rev: v4.3.0
hooks:
- id: check-yaml
exclude: pymatgen/analysis/vesta_cutoffs.yaml
Expand All @@ -41,16 +41,16 @@ repos:
args: ["--profile", "black"]

- repo: https://github.com/psf/black
rev: 22.3.0
rev: 22.6.0
hooks:
- id: black

- repo: https://github.com/PyCQA/flake8
rev: 4.0.1
rev: 5.0.2
hooks:
- id: flake8

- repo: https://github.com/pre-commit/mirrors-mypy
rev: v0.950
rev: v0.971
hooks:
- id: mypy
2 changes: 1 addition & 1 deletion maml/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,6 @@
maml - materials machine learning
"""

__version__ = "2022.5.3"
__version__ = "2022.6.11"

__import__("pkg_resources").declare_namespace(__name__)
5 changes: 2 additions & 3 deletions maml/apps/bowsr/acquisition.py
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ def ensure_rng(seed: int = None) -> RandomState:
Create a random number generator based on an optional seed.
This can be an integer for a seeded rng or None for an unseeded rng.
"""
return np.random.RandomState(seed=seed)
return np.random.RandomState(seed=seed) # pylint: disable=E1101


def predict_mean_std(x: Union[List, np.ndarray], gpr: GaussianProcessRegressor, noise: float) -> Tuple[Any, ...]:
Expand Down Expand Up @@ -152,8 +152,7 @@ def __init__(self, acq_type: str, kappa: float, xi: float):

if acq_type not in ["ucb", "ei", "poi", "gp-ucb"]:
err_msg = (
"The utility function {} has not been implemented, "
"please choose one of ucb, ei, or poi.".format(acq_type)
f"The utility function {acq_type} has not been implemented, " "please choose one of ucb, ei, or poi."
)
raise NotImplementedError(err_msg)
self.acq_type = acq_type
Expand Down
4 changes: 2 additions & 2 deletions maml/apps/bowsr/model/cgcnn.py
Original file line number Diff line number Diff line change
Expand Up @@ -107,9 +107,9 @@ def _get_nbr_fea(self, all_nbrs: list, cif_id: int) -> Tuple[np.ndarray, ...]:
for nbr in all_nbrs:
if len(nbr) < self.max_num_nbr:
warnings.warn(
"{} not find enough neighbors to build graph. "
f"{cif_id} not find enough neighbors to build graph. "
"If it happens frequently, consider increase "
"radius.".format(cif_id)
"radius."
)
nbr_fea_idx.append(list(map(lambda x: x[2], nbr)) + [0] * (self.max_num_nbr - len(nbr)))
nbr_fea.append(list(map(lambda x: x[1], nbr)) + [self.radius + 1.0] * (self.max_num_nbr - len(nbr)))
Expand Down
2 changes: 1 addition & 1 deletion maml/apps/bowsr/model/dft.py
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,7 @@ def predict_energy(self, structure: Structure):
stdout, stderr = p_exe.communicate()
rc = p_exe.returncode
if rc != 0:
error_msg = "vasp exited with return code %d" % rc
error_msg = f"vasp exited with return code {rc}"
msg = stderr.decode("utf-8").split("\n")[:-1]
try:
error_line = [i for i, m in enumerate(msg) if m.startswith("ERROR")][0]
Expand Down
23 changes: 7 additions & 16 deletions maml/apps/bowsr/optimizer.py
Original file line number Diff line number Diff line change
Expand Up @@ -402,20 +402,11 @@ def gpr(self):

def __repr__(self):
return (
"{}(relax_coords={}, relax_lattice={}, use_symmetry={}"
"\n\t\twyckoff_dims={}, abc_dim={}, "
"\n\t\tangles_dim={}, kernel={}, scaler={}, noisy={})".format(
self.__class__.__name__,
self.relax_coords,
self.relax_lattice,
self.use_symmetry,
self.wyckoff_dims,
self.abc_dim,
self.angles_dim,
repr(self.gpr.kernel),
self.scaler.__class__.__name__,
self.noisy,
)
f"{self.__class__.__name__}(relax_coords={self.relax_coords}, relax_lattice={self.relax_lattice}, "
f"use_symmetry={self.use_symmetry}"
f"\n\t\twyckoff_dims={self.wyckoff_dims}, abc_dim={self.abc_dim}, "
f"\n\t\tangles_dim={self.angles_dim}, kernel={repr(self.gpr.kernel)}, "
f"scaler={self.scaler.__class__.__name__}, noisy={self.noisy})"
)

def as_dict(self):
Expand Down Expand Up @@ -522,7 +513,7 @@ def gpr_from_dict(gpr_d):

model = getattr(energy_model, d["model"])()
else:
raise AttributeError("model {} is not supported.".format(d["model"]))
raise AttributeError(f"model {d['model']} is not supported.")

structure = Structure.from_dict(d["structure"])
use_symmetry = d["use_symmetry"]
Expand Down Expand Up @@ -555,7 +546,7 @@ def gpr_from_dict(gpr_d):
space_params = np.array(space_d["params"])
space_target = np.array(space_d["target"])
space_bounds = np.array(space_d["bounds"])
space_random_state = np.random.RandomState()
space_random_state = np.random.RandomState() # pylint: disable=E1101
space_random_state.set_state(space_d["random_state"])
from maml.apps.bowsr import preprocessing

Expand Down
49 changes: 28 additions & 21 deletions maml/apps/bowsr/perturbation.py
Original file line number Diff line number Diff line change
Expand Up @@ -28,12 +28,24 @@

small_addup = np.array([1e-4] * 3)

perturbation_mapping = lambda x, fixed_indices: np.array(
[
0 if i in fixed_indices else x[np.argwhere(np.arange(3)[~np.isin(range(3), fixed_indices)] == i)[0][0]]
for i in range(3)
]
)

def perturbation_mapping(x, fixed_indices):
"""
Perturbation mapping.
Args:
x:
fixed_indices:
Returns:
"""
return np.array(
[
0 if i in fixed_indices else x[np.argwhere(np.arange(3)[~np.isin(range(3), fixed_indices)] == i)[0][0]]
for i in range(3)
]
)


class WyckoffPerturbation:
Expand Down Expand Up @@ -143,16 +155,12 @@ def fit_site(self):

def __repr__(self):
if self._site is not None:
return "{}(spg_int_number={}, wyckoff_symbol={}) {} [{:.4f}, {:.4f}, {:.4f}]".format(
self.__class__.__name__,
self.int_symbol,
self.wyckoff_symbol,
self._site.species_string,
*self._site.frac_coords,
a, b, c = self._site.frac_coords
return (
f"{self.__class__.__name__}(spg_int_number={self.int_symbol}, wyckoff_symbol={self.wyckoff_symbol})"
f" {self._site.species_string} [{a:.4f}, {b:.4f}, {c:.4f}]"
)
return "{}(spg_int_number={}, wyckoff_symbol={})".format(
self.__class__.__name__, self.int_symbol, self.wyckoff_symbol
)
return f"{self.__class__.__name__}(spg_int_number={self.int_symbol}, wyckoff_symbol={self.wyckoff_symbol})"


def crystal_system(int_number: int) -> str:
Expand Down Expand Up @@ -379,12 +387,11 @@ def abc(self) -> List[float]:

def __repr__(self):
if self._lattice is not None:
return "{}(spg_int_number={}, crystal_system={})\n".format(
self.__class__.__name__, self.spg_int_symbol, self.crys_system
) + repr(self.lattice)
return "{}(spg_int_number={}, crystal_system={})\n".format(
self.__class__.__name__, self.spg_int_symbol, self.crys_system
)
return (
f"{self.__class__.__name__}(spg_int_number={self.spg_int_symbol}, "
f"crystal_system={self.crys_system})\n" + repr(self.lattice)
)
return f"{self.__class__.__name__}(spg_int_number={self.spg_int_symbol}, crystal_system={self.crys_system})\n"


def get_standardized_structure(structure: Structure) -> Structure:
Expand Down
5 changes: 3 additions & 2 deletions maml/apps/bowsr/target_space.py
Original file line number Diff line number Diff line change
Expand Up @@ -198,6 +198,7 @@ def set_empty(self) -> None:
self._target = np.empty(shape=(0))

def __repr__(self):
return "{}(relax_coords={}, relax_lattice={}, dim={}, length={})".format(
self.__class__.__name__, self.relax_coords, self.relax_lattice, self.dim, len(self)
return (
f"{self.__class__.__name__}(relax_coords={self.relax_coords}, relax_lattice={self.relax_lattice},"
f" dim={self.dim}, length={len(self)})"
)
14 changes: 7 additions & 7 deletions maml/apps/pes/_gap.py
Original file line number Diff line number Diff line change
Expand Up @@ -87,12 +87,12 @@ def _line_up(structure, energy, forces, virial_stress):

description = []
if "Energy" in inputs:
description.append("dft_energy={}".format(inputs["Energy"]))
description.append("dft_energy=" + str(inputs["Energy"]))
if "Stress" in inputs:
description.append("dft_virial={%s}" % "\t".join(list(map(lambda f: str(f), inputs["Stress"]))))
if "SuperCell" in inputs:
SuperCell_str = list(map(lambda f: str(f), inputs["SuperCell"].matrix.ravel()))
description.append('Lattice="{}"'.format(" ".join(SuperCell_str)))
super_cell_str = list(map(lambda f: str(f), inputs["SuperCell"].matrix.ravel()))
description.append(f'Lattice="{" ".join(super_cell_str)}"')
description.append("Properties=species:S:1:pos:R:3:Z:I:1:dft_force:R:3")
lines.append(" ".join(description))

Expand Down Expand Up @@ -312,14 +312,14 @@ def train(
param = kwargs.get(param_name) if kwargs.get(param_name) else soap_params.get(param_name)
gap_command.append(param_name + "=" + f"{param}")
gap_command.append("add_species=T")
exe_command.append("gap=" + "{" + "{}".format(" ".join(gap_command)) + "}")
exe_command.append("gap={" + " ".join(gap_command) + "}")

for param_name in preprocess_params:
param = kwargs.get(param_name) if kwargs.get(param_name) else soap_params.get(param_name)
exe_command.append(param_name + "=" + f"{param}")

default_sigma = [str(f) for f in default_sigma]
exe_command.append("default_sigma={%s}" % (" ".join(default_sigma)))
exe_command.append(f"default_sigma={{{' '.join(default_sigma)}}}")

if use_energies:
exe_command.append("energy_parameter_name=dft_energy")
Expand All @@ -336,7 +336,7 @@ def train(
stdout = p.communicate()[0]
rc = p.returncode
if rc != 0:
error_msg = "gap_fit exited with return code %d" % rc
error_msg = f"gap_fit exited with return code {rc}"
msg = stdout.decode("utf-8").split("\n")[:-1]
try:
error_line = [i for i, m in enumerate(msg) if m.startswith("ERROR")][0]
Expand Down Expand Up @@ -392,7 +392,7 @@ def write_param(self, xml_filename="gap.2020.01.xml"):
tree.write(xml_filename)

pair_coeff = self.pair_coeff.format(
xml_filename, '"Potential xml_label={}"'.format(self.param.get("potential_label")), " ".join(atomic_numbers)
xml_filename, f'"Potential xml_label={self.param.get("potential_label")}"', " ".join(atomic_numbers)
)
ff_settings = [self.pair_style, pair_coeff]
return ff_settings
Expand Down
14 changes: 7 additions & 7 deletions maml/apps/pes/_lammps.py
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@ def get_default_lmp_exe():

for lmp_exe in ["lmp_serial", "lmp_mpi", "lmp_g++_serial", "lmp_g++_mpich", "lmp_intel_cpu_intelmpi"]:
if which(lmp_exe) is not None:
logger.info("Setting Lammps executable to %s" % lmp_exe)
logger.info(f"Setting Lammps executable to {lmp_exe}")
return lmp_exe
return None

Expand Down Expand Up @@ -83,7 +83,7 @@ def __init__(self, **kwargs):
if lmp_exe is None:
lmp_exe = get_default_lmp_exe()
if not which(lmp_exe):
raise ValueError("lammps executable %s not found" % str(lmp_exe))
raise ValueError(f"lammps executable {lmp_exe} not found")
self.LMP_EXE = lmp_exe
for i, j in kwargs.items():
if i not in self.allowed_kwargs:
Expand Down Expand Up @@ -148,7 +148,7 @@ def calculate(self, structures):
stdout = p.communicate()[0]
rc = p.returncode
if rc != 0:
error_msg = "LAMMPS exited with return code %d" % rc
error_msg = f"LAMMPS exited with return code {rc}"
msg = stdout.decode("utf-8").split("\n")[:-1]
try:
error_line = [i for i, m in enumerate(msg) if m.startswith("ERROR")][0]
Expand Down Expand Up @@ -578,7 +578,7 @@ def _setup(self):
stdout = p.communicate()[0]
rc = p.returncode
if rc != 0:
error_msg = "LAMMPS exited with return code %d" % rc
error_msg = f"LAMMPS exited with return code {rc}"
msg = stdout.decode("utf-8").split("\n")[:-1]
try:
error_line = [i for i, m in enumerate(msg) if m.startswith("ERROR")][0]
Expand All @@ -603,7 +603,7 @@ def _setup(self):
stdout = p.communicate()[0]
rc = p.returncode
if rc != 0:
error_msg = "LAMMPS exited with return code %d" % rc
error_msg = f"LAMMPS exited with return code {rc}"
msg = stdout.decode("utf-8").split("\n")[:-1]
try:
error_line = [i for i, m in enumerate(msg) if m.startswith("ERROR")][0]
Expand Down Expand Up @@ -663,7 +663,7 @@ def calculate(self):
stdout = p.communicate()[0]
rc = p.returncode
if rc != 0:
error_msg = "LAMMPS exited with return code %d" % rc
error_msg = f"LAMMPS exited with return code {rc}"
msg = stdout.decode("utf-8").split("\n")[:-1]
try:
error_line = [i for i, m in enumerate(msg) if m.startswith("ERROR")][0]
Expand Down Expand Up @@ -796,7 +796,7 @@ def calculate(self):
stdout = p.communicate()[0]
rc = p.returncode
if rc != 0:
error_msg = "LAMMPS exited with return code %d" % rc
error_msg = f"LAMMPS exited with return code {rc}"
msg = stdout.decode("utf-8").split("\n")[:-1]
try:
error_line = [i for i, m in enumerate(msg) if m.startswith("ERROR")][0]
Expand Down
12 changes: 6 additions & 6 deletions maml/apps/pes/_mtp.py
Original file line number Diff line number Diff line change
Expand Up @@ -90,11 +90,11 @@ def _line_up(self, structure, energy, forces, virial_stress):

if "Size" in inputs:
lines.append(" Size")
lines.append("{:>7d}".format(inputs["Size"]))
lines.append(f"{inputs['Size']:>7d}")
if "SuperCell" in inputs:
lines.append(" SuperCell")
for vec in inputs["SuperCell"].matrix:
lines.append("{:>17.6f}{:>14.6f}{:>14.6f}".format(*vec))
lines.append(f"{vec[0]:>17.6f}{vec[1]:>14.6f}{vec[2]:>14.6f}")
if "AtomData" in inputs:
format_str = "{:>14s}{:>5s}{:>15s}{:>14s}{:>14s}{:>13s}{:>13s}{:>13s}"
format_float = "{:>14d}{:>5d}{:>15f}{:>14f}{:>14f}{:>13f}{:>13f}{:>13f}"
Expand All @@ -105,7 +105,7 @@ def _line_up(self, structure, energy, forces, virial_stress):
lines.append(format_float.format(i + 1, self.elements.index(str(site.specie)), *site.coords, *force))
if "Energy" in inputs:
lines.append(" Energy")
lines.append("{:>24.12f}".format(inputs["Energy"]))
lines.append(f"{inputs['Energy']:>24.12f}")
if "Stress" in inputs:
if not hasattr(self, "version") or self.version == "mlip-2":
format_str = "{:>16s}{:>12s}{:>12s}{:>12s}{:>12s}{:>12s}"
Expand All @@ -114,7 +114,7 @@ def _line_up(self, structure, energy, forces, virial_stress):
format_str = "{:>12s}{:>12s}{:>12s}{:>12s}{:>12s}{:>12s}"
lines.append(format_str.format("Stress: xx", "yy", "zz", "yz", "xz", "xy"))
format_float = "{:>12f}{:>12f}{:>12f}{:>12f}{:>12f}{:>12f}"
lines.append(format_float.format(*np.array(virial_stress) / 1.228445))
lines.append(format_float.format(*np.array(virial_stress)))

lines.append("END_CFG")

Expand Down Expand Up @@ -632,7 +632,7 @@ def train(
stdout = p.communicate()[0]
rc = p.returncode
if rc != 0:
error_msg = "MLP exited with return code %d" % rc
error_msg = f"MLP exited with return code {rc}"
msg = stdout.decode("utf-8").split("\n")[:-1]
try:
error_line = [i for i, m in enumerate(msg) if m.startswith("ERROR")][0]
Expand Down Expand Up @@ -726,7 +726,7 @@ def evaluate(self, test_structures, test_energies, test_forces, test_stresses=No
stdout = p.communicate()[0]
rc = p.returncode
if rc != 0:
error_msg = "mlp exited with return code %d" % rc
error_msg = f"mlp exited with return code {rc}"
msg = stdout.decode("utf-8").split("\n")[:-1]
try:
error_line = [i for i, m in enumerate(msg) if m.startswith("ERROR")][0]
Expand Down
Loading

0 comments on commit 52d628c

Please sign in to comment.