Skip to content

Commit

Permalink
replace all numpy.testing.assert_array_almost_equal with assert_allclose
Browse files Browse the repository at this point in the history
for consistency
  • Loading branch information
janosh committed Nov 14, 2023
1 parent 7c5c79f commit 8aee215
Show file tree
Hide file tree
Showing 21 changed files with 150 additions and 132 deletions.
6 changes: 3 additions & 3 deletions pymatgen/analysis/graphs.py
Original file line number Diff line number Diff line change
Expand Up @@ -1086,13 +1086,13 @@ def __mul__(self, scaling_matrix):
raise NotImplementedError("Not tested with 3x3 scaling matrices yet.")
new_lattice = Lattice(np.dot(scale_matrix, self.structure.lattice.matrix))

f_lat = lattice_points_in_supercell(scale_matrix)
c_lat = new_lattice.get_cartesian_coords(f_lat)
frac_lattice = lattice_points_in_supercell(scale_matrix)
cart_lattice = new_lattice.get_cartesian_coords(frac_lattice)

new_sites = []
new_graphs = []

for v in c_lat:
for v in cart_lattice:
# create a map of nodes from original graph to its image
mapping = {n: n + len(new_sites) for n in range(len(self.structure))}

Expand Down
32 changes: 25 additions & 7 deletions pymatgen/command_line/critic2_caller.py
Original file line number Diff line number Diff line change
Expand Up @@ -353,7 +353,7 @@ def __init__(
coords=None,
field_hessian=None,
):
"""Class to characterise a critical point from a topological
"""Class to characterize a critical point from a topological
analysis of electron charge density.
Note this class is usually associated with a Structure, so
Expand Down Expand Up @@ -388,7 +388,7 @@ def __str__(self):
return f"Critical Point: {self.type.name} ({self.frac_coords})"

@property
def laplacian(self):
def laplacian(self) -> float:
"""Returns: The Laplacian of the field at the critical point."""
return np.trace(self.field_hessian)

Expand All @@ -408,7 +408,15 @@ def ellipticity(self):
class Critic2Analysis(MSONable):
"""Class to process the standard output from critic2 into pymatgen-compatible objects."""

def __init__(self, structure: Structure, stdout=None, stderr=None, cpreport=None, yt=None, zpsp=None):
def __init__(
self,
structure: Structure,
stdout: str | None = None,
stderr: str | None = None,
cpreport: dict | None = None,
yt: dict | None = None,
zpsp: dict | None = None,
) -> None:
"""This class is used to store results from the Critic2Caller.
To explore the bond graph, use the "structure_graph"
Expand Down Expand Up @@ -443,6 +451,18 @@ class with bonding information. By default, this returns
:param zpsp (dict): Dict of element/symbol name to number of electrons
(ZVAL in VASP pseudopotential), with which to calculate charge transfer.
Optional.
Args:
structure (Structure): Associated Structure.
stdout (str, optional): stdout from running critic2 in automatic mode.
stderr (str, optional): stderr from running critic2 in automatic mode.
cpreport (dict, optional): JSON output from CPREPORT command. Either this or stdout required.
yt (dict, optional): JSON output from YT command.
zpsp (dict, optional): Dict of element/symbol name to number of electrons (ZVAL in VASP pseudopotential),
with which to calculate charge transfer. Optional.
Raises:
ValueError: If one of cpreport or stdout is not provided.
"""
self.structure = structure

Expand Down Expand Up @@ -471,10 +491,8 @@ def structure_graph(self, include_critical_points=("bond", "ring", "cage")):
"""A StructureGraph object describing bonding information in the crystal.
Args:
include_critical_points: add DummySpecies for
the critical points themselves, a list of
"nucleus", "bond", "ring", "cage", set to None
to disable
include_critical_points: add DummySpecies for the critical points themselves, a list of
"nucleus", "bond", "ring", "cage", set to None to disable
Returns:
StructureGraph
Expand Down
3 changes: 2 additions & 1 deletion pymatgen/command_line/gulp_caller.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,8 @@
__status__ = "Production"
__date__ = "Jun 22, 2013M"

module_dir = os.path.dirname(os.path.abspath(__file__))

_anions = set(map(Element, ["O", "S", "F", "Cl", "Br", "N", "P"]))
_cations = set(
map(
Expand Down Expand Up @@ -861,7 +863,6 @@ class TersoffPotential:

def __init__(self):
"""Init TersoffPotential."""
module_dir = os.path.dirname(os.path.abspath(__file__))
with open(f"{module_dir}/OxideTersoffPotentials") as f:
data = {}
for row in f:
Expand Down
2 changes: 1 addition & 1 deletion pymatgen/core/composition.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@
from collections.abc import Generator, Iterator

SpeciesLike = Union[str, Element, Species, DummySpecies]
module_dir = os.path.dirname(os.path.abspath(__file__))


@total_ordering
Expand Down Expand Up @@ -928,7 +929,6 @@ def _get_oxi_state_guesses(self, all_oxi_states, max_sites, oxi_states_override,

# Load prior probabilities of oxidation states, used to rank solutions
if not Composition.oxi_prob:
module_dir = os.path.join(os.path.dirname(os.path.abspath(__file__)))
all_data = loadfn(f"{module_dir}/../analysis/icsd_bv.yaml")
Composition.oxi_prob = {Species.from_str(sp): data for sp, data in all_data["occurrence"].items()}
oxi_states_override = oxi_states_override or {}
Expand Down
14 changes: 8 additions & 6 deletions pymatgen/core/structure.py
Original file line number Diff line number Diff line change
Expand Up @@ -1357,12 +1357,12 @@ def __mul__(self, scaling_matrix: int | Sequence[int] | Sequence[Sequence[int]])
scale_matrix = scale_matrix * np.eye(3)
new_lattice = Lattice(np.dot(scale_matrix, self.lattice.matrix))

f_lat = lattice_points_in_supercell(scale_matrix)
c_lat = new_lattice.get_cartesian_coords(f_lat)
frac_lattice = lattice_points_in_supercell(scale_matrix)
cart_lattice = new_lattice.get_cartesian_coords(frac_lattice)

new_sites = []
for site in self:
for vec in c_lat:
for vec in cart_lattice:
periodic_site = PeriodicSite(
site.species,
site.coords + vec,
Expand Down Expand Up @@ -2228,11 +2228,13 @@ def interpolate(
for x in images:
if interpolate_lattices:
l_a = np.dot(np.identity(3) + x * lvec, lstart).T
lat = Lattice(l_a)
lattice = Lattice(l_a)
else:
lat = self.lattice
lattice = self.lattice
fcoords = start_coords + x * vec
structs.append(self.__class__(lat, sp, fcoords, site_properties=self.site_properties, labels=self.labels))
structs.append(
self.__class__(lattice, sp, fcoords, site_properties=self.site_properties, labels=self.labels)
)
return structs

def get_miller_index_from_site_indexes(self, site_ids, round_dp=4, verbose=True):
Expand Down
8 changes: 4 additions & 4 deletions pymatgen/io/vasp/inputs.py
Original file line number Diff line number Diff line change
Expand Up @@ -1202,16 +1202,16 @@ def automatic_density(structure: Structure, kppa: float, force_gamma: bool = Fal
comment = f"pymatgen with grid density = {kppa:.0f} / number of atoms"
if math.fabs((math.floor(kppa ** (1 / 3) + 0.5)) ** 3 - kppa) < 1:
kppa += kppa * 0.01
latt = structure.lattice
lengths = latt.abc
lattice = structure.lattice
lengths = lattice.abc
ngrid = kppa / len(structure)
mult = (ngrid * lengths[0] * lengths[1] * lengths[2]) ** (1 / 3)

num_div = [int(math.floor(max(mult / length, 1))) for length in lengths]

is_hexagonal = latt.is_hexagonal()
is_hexagonal = lattice.is_hexagonal()
is_face_centered = structure.get_space_group_info()[0][0] == "F"
has_odd = any(i % 2 == 1 for i in num_div)
has_odd = any(idx % 2 == 1 for idx in num_div)
if has_odd or is_hexagonal or is_face_centered or force_gamma:
style = Kpoints.supported_modes.Gamma
else:
Expand Down
26 changes: 13 additions & 13 deletions pymatgen/io/xr.py
Original file line number Diff line number Diff line change
Expand Up @@ -81,11 +81,11 @@ def from_str(cls, string, use_cores=True, thresh=1.0e-4):
Args:
string (str): string representation of an Xr object.
use_cores (bool): use core positions and discard shell
positions if set to True (default). Otherwise,
use shell positions and discard core positions.
positions if set to True (default). Otherwise,
use shell positions and discard core positions.
thresh (float): relative threshold for consistency check
between cell parameters (lengths and angles) from
header information and cell vectors, respectively.
between cell parameters (lengths and angles) from
header information and cell vectors, respectively.
Returns:
xr (Xr): Xr object corresponding to the input
Expand All @@ -106,18 +106,18 @@ def from_str(cls, string, use_cores=True, thresh=1.0e-4):
if item != tokens_2[j]:
raise RuntimeError("expected both matrices to be the same in xr file")
mat[i] = np.array([float(w) for w in tokens])
lat = Lattice(mat)
lattice = Lattice(mat)
if (
fabs(lat.a - lengths[0]) / fabs(lat.a) > thresh
or fabs(lat.b - lengths[1]) / fabs(lat.b) > thresh
or fabs(lat.c - lengths[2]) / fabs(lat.c) > thresh
or fabs(lat.alpha - angles[0]) / fabs(lat.alpha) > thresh
or fabs(lat.beta - angles[1]) / fabs(lat.beta) > thresh
or fabs(lat.gamma - angles[2]) / fabs(lat.gamma) > thresh
fabs(lattice.a - lengths[0]) / fabs(lattice.a) > thresh
or fabs(lattice.b - lengths[1]) / fabs(lattice.b) > thresh
or fabs(lattice.c - lengths[2]) / fabs(lattice.c) > thresh
or fabs(lattice.alpha - angles[0]) / fabs(lattice.alpha) > thresh
or fabs(lattice.beta - angles[1]) / fabs(lattice.beta) > thresh
or fabs(lattice.gamma - angles[2]) / fabs(lattice.gamma) > thresh
):
raise RuntimeError(
f"cell parameters in header ({lengths}, {angles}) are not consistent with Cartesian "
f"lattice vectors ({lat.abc}, {lat.angles})"
f"lattice vectors ({lattice.abc}, {lattice.angles})"
)
# Ignore line w/ index 3.
sp = []
Expand All @@ -138,7 +138,7 @@ def from_str(cls, string, use_cores=True, thresh=1.0e-4):
else:
sp.append(tmp_sp)
coords.append([float(m.group(i)) for i in range(2, 5)])
return cls(Structure(lat, sp, coords, coords_are_cartesian=True))
return cls(Structure(lattice, sp, coords, coords_are_cartesian=True))

@classmethod
def from_file(cls, filename, use_cores=True, thresh=1.0e-4):
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -83,19 +83,19 @@ def test_init(self):
assert len(cc2.graph) == 6

def test_serialization(self):
lat = Lattice.hexagonal(a=2.0, c=2.5)
lattice = Lattice.hexagonal(a=2.0, c=2.5)
en1 = EnvironmentNode(
central_site=PeriodicSite("Si", coords=np.array([0.0, 0.0, 0.0]), lattice=lat),
central_site=PeriodicSite("Si", coords=np.array([0.0, 0.0, 0.0]), lattice=lattice),
i_central_site=3,
ce_symbol="T:4",
)
en2 = EnvironmentNode(
central_site=PeriodicSite("Ag", coords=np.array([0.0, 0.0, 0.5]), lattice=lat),
central_site=PeriodicSite("Ag", coords=np.array([0.0, 0.0, 0.5]), lattice=lattice),
i_central_site=5,
ce_symbol="T:4",
)
en3 = EnvironmentNode(
central_site=PeriodicSite("Ag", coords=np.array([0.0, 0.5, 0.5]), lattice=lat),
central_site=PeriodicSite("Ag", coords=np.array([0.0, 0.5, 0.5]), lattice=lattice),
i_central_site=8,
ce_symbol="O:6",
)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@

import json

from numpy.testing import assert_allclose, assert_array_almost_equal
from numpy.testing import assert_allclose
from pytest import approx

from pymatgen.analysis.chemenv.coordination_environments.chemenv_strategies import (
Expand Down Expand Up @@ -103,8 +103,8 @@ def test_structure_environments_neighbors_sets(self):

neighb_coords = nb_set.coords

assert_array_almost_equal(coords, neighb_coords[1:])
assert_array_almost_equal(nb_set.structure[nb_set.isite].coords, neighb_coords[0])
assert_allclose(coords, neighb_coords[1:], atol=1e-6)
assert_allclose(nb_set.structure[nb_set.isite].coords, neighb_coords[0])

norm_dist = nb_set.normalized_distances
assert sorted(norm_dist) == approx(sorted([1.001792, 1.001792, 1, 1]))
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
import os

import numpy as np
from numpy.testing import assert_allclose, assert_array_almost_equal
from numpy.testing import assert_allclose
from pytest import approx

from pymatgen.analysis.chemenv.coordination_environments.chemenv_strategies import (
Expand Down Expand Up @@ -32,24 +32,24 @@ def test_structure_environments(self):
struct_envs = StructureEnvironments.from_dict(dd)
isite = 6
_csm_and_maps_fig, csm_and_maps_ax = struct_envs.get_csm_and_maps(isite=isite)
assert_array_almost_equal(csm_and_maps_ax.lines[0].get_xydata().flatten(), [0, 0.53499332])
assert_array_almost_equal(csm_and_maps_ax.lines[1].get_xydata().flatten(), [1, 0.47026441])
assert_array_almost_equal(csm_and_maps_ax.lines[2].get_xydata().flatten(), [2, 0.00988778])
assert_allclose(csm_and_maps_ax.lines[0].get_xydata().flatten(), [0, 0.53499332])
assert_allclose(csm_and_maps_ax.lines[1].get_xydata().flatten(), [1, 0.47026441])
assert_allclose(csm_and_maps_ax.lines[2].get_xydata().flatten(), [2, 0.00988778], atol=1e-8)

_envs_fig, envs_ax = struct_envs.get_environments_figure(isite=isite)
assert_array_almost_equal(
assert_allclose(
np.array(envs_ax.patches[0].get_xy()),
[[1, 1], [1, 0.99301365], [1.00179228, 0.99301365], [1.00179228, 1], [1, 1]],
)
assert_array_almost_equal(
assert_allclose(
np.array(envs_ax.patches[1].get_xy()),
[[1, 0.99301365], [1, 0], [1.00179228, 0], [1.00179228, 0.99301365], [1, 0.99301365]],
)
assert_array_almost_equal(
assert_allclose(
np.array(envs_ax.patches[2].get_xy()),
[[1.00179228, 1], [1.00179228, 0.99301365], [2.25, 0.99301365], [2.25, 1], [1.00179228, 1]],
)
assert_array_almost_equal(
assert_allclose(
np.array(envs_ax.patches[3].get_xy()),
[
[1.00179228, 0.99301365],
Expand All @@ -60,10 +60,12 @@ def test_structure_environments(self):
[2.25, 0.99301365],
[1.00179228, 0.99301365],
],
atol=1e-8,
)
assert_array_almost_equal(
assert_allclose(
np.array(envs_ax.patches[4].get_xy()),
[[2.22376156, 0.0060837], [2.22376156, 0], [2.25, 0], [2.25, 0.0060837], [2.22376156, 0.0060837]],
atol=1e-8,
)

struct_envs.save_environments_figure(isite=isite, imagename="image.png")
Expand All @@ -81,7 +83,7 @@ def test_structure_environments(self):
assert symbol == "T:4"
assert min_geometry["symmetry_measure"] == approx(0.00988778424054)

assert_array_almost_equal(
assert_allclose(
min_geometry["other_symmetry_measures"]["rotation_matrix_wcs_csc"],
[
[-0.8433079817973094, -0.19705747216466898, 0.5000000005010193],
Expand Down Expand Up @@ -137,13 +139,13 @@ def test_light_structure_environments(self):
neighb_indices = [0, 3, 5, 1]
neighb_images = [[0, 0, -1], [0, 0, 0], [0, 0, -1], [0, 0, 0]]

assert_array_almost_equal(neighb_coords, nb_set.neighb_coords)
assert_array_almost_equal(neighb_coords, [s.coords for s in nb_set.neighb_sites])
assert_allclose(neighb_coords, nb_set.neighb_coords)
assert_allclose(neighb_coords, [s.coords for s in nb_set.neighb_sites])
nb_sai = nb_set.neighb_sites_and_indices
assert_array_almost_equal(neighb_coords, [sai["site"].coords for sai in nb_sai])
assert_array_almost_equal(neighb_indices, [sai["index"] for sai in nb_sai])
assert_allclose(neighb_coords, [sai["site"].coords for sai in nb_sai])
assert_allclose(neighb_indices, [sai["index"] for sai in nb_sai])
nb_iai = nb_set.neighb_indices_and_images
assert_array_almost_equal(neighb_indices, [iai["index"] for iai in nb_iai])
assert_allclose(neighb_indices, [iai["index"] for iai in nb_iai])
np.testing.assert_array_equal(neighb_images, [iai["image_cell"] for iai in nb_iai])

assert len(nb_set) == 4
Expand Down Expand Up @@ -182,8 +184,8 @@ def test_light_structure_environments(self):
assert stats["fraction_atom_coordination_environments_present"] == {"Si": {"T:4": 1}}

site_info_ce = lse.get_site_info_for_specie_ce(specie=Species("Si4+"), ce_symbol="T:4")
assert_array_almost_equal(site_info_ce["fractions"], [1, 1, 1])
assert_array_almost_equal(
assert_allclose(site_info_ce["fractions"], [1, 1, 1])
assert_allclose(
site_info_ce["csms"],
[0.009887784240541068, 0.009887786546730826, 0.009887787384385317],
)
Expand Down
2 changes: 1 addition & 1 deletion tests/analysis/interfaces/test_zsl.py
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,7 @@ def test_zsl(self):
assert fast_norm(np.array([3, 2, 1])) == approx(3.74165738)
assert_array_equal(reduce_vectors(np.array([1, 0, 0]), np.array([2, 2, 0])), [[1, 0, 0], [0, 2, 0]])
assert vec_area(np.array([1, 0, 0]), np.array([0, 2, 0])) == 2
assert_array_equal(list(get_factors(18)), [1, 2, 3, 6, 9, 18])
assert list(get_factors(18)) == [1, 2, 3, 6, 9, 18]
assert is_same_vectors(
np.array([[1.01, 0, 0], [0, 2, 0]], dtype=float), np.array([[1, 0, 0], [0, 2.01, 0]], dtype=float)
)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@
from pymatgen.core import Structure
from pymatgen.util.testing import PymatgenTest

module_dir = os.path.join(os.path.dirname(os.path.abspath(__file__)))
module_dir = os.path.dirname(os.path.abspath(__file__))


class TestRLSVolumePredictor(PymatgenTest):
Expand Down
2 changes: 1 addition & 1 deletion tests/analysis/test_bond_dissociation.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@

from pymatgen.analysis.bond_dissociation import BondDissociationEnergies

module_dir = os.path.join(os.path.dirname(os.path.abspath(__file__)))
module_dir = os.path.dirname(os.path.abspath(__file__))


class TestBondDissociation(unittest.TestCase):
Expand Down
Loading

0 comments on commit 8aee215

Please sign in to comment.