Skip to content

Commit

Permalink
test refactor: assert np.allclose to numpy.testing.assert_allclose
Browse files Browse the repository at this point in the history
for much better error messages
  • Loading branch information
janosh committed Jul 3, 2023
1 parent cb213d9 commit 6bae163
Show file tree
Hide file tree
Showing 31 changed files with 186 additions and 164 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
import networkx as nx
import numpy as np
import pytest
from numpy.testing import assert_allclose

from pymatgen.analysis.chemenv.connectivity.connected_components import ConnectedComponent
from pymatgen.analysis.chemenv.connectivity.connectivity_finder import ConnectivityFinder
Expand Down Expand Up @@ -379,7 +380,7 @@ def test_periodicity(self):
assert not cc.is_3d
assert cc.is_periodic
assert cc.periodicity == "2D"
assert np.allclose(cc.periodicity_vectors, [np.array([0, 1, 0]), np.array([1, 1, 0])])
assert_allclose(cc.periodicity_vectors, [np.array([0, 1, 0]), np.array([1, 1, 0])])
assert isinstance(cc.periodicity_vectors, list)
assert cc.periodicity_vectors[0].dtype is np.dtype(int)

Expand Down Expand Up @@ -449,7 +450,7 @@ def test_periodicity(self):
assert cc.is_3d
assert cc.is_periodic
assert cc.periodicity == "3D"
assert np.allclose(
assert_allclose(
cc.periodicity_vectors,
[np.array([0, 1, 0]), np.array([1, 1, 0]), np.array([1, 1, 1])],
)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,7 @@
import shutil
import unittest

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

from pymatgen.analysis.chemenv.coordination_environments.chemenv_strategies import (
Expand Down Expand Up @@ -102,7 +101,7 @@ def test_structure_environments_neighbors_sets(self):
[2.25, 0.99301365328679292],
]

assert np.allclose(nb_set.voronoi_grid_surface_points(), nb_set_surface_points)
assert_allclose(nb_set.voronoi_grid_surface_points(), nb_set_surface_points)

neighb_sites = nb_set.neighb_sites
coords = [
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
import random

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

from pymatgen.analysis.chemenv.utils.coordination_geometry_utils import Plane
Expand All @@ -24,7 +25,7 @@ def setUp(self):
def test_factors_abcd_normal_vector(self):
factors = self.plane.coefficients / self.expected_coefficients
self.assert_all_close([factors[0]] * 4, list(factors))
assert np.allclose([2 / 3, 1 / 3, -2 / 3], self.plane.normal_vector)
assert_allclose([2 / 3, 1 / 3, -2 / 3], self.plane.normal_vector)

def test_from_npoints_plane(self):
best_fits = ["least_square_distance", "maximum_distance"]
Expand Down Expand Up @@ -94,12 +95,12 @@ def test_orthonormal_vectors(self):
assert np.isclose(np.dot(ortho[0], ortho[1]), 0)
assert np.isclose(np.dot(ortho[1], ortho[2]), 0)
assert np.isclose(np.dot(ortho[2], ortho[0]), 0)
assert np.allclose(np.cross(ortho[0], ortho[1]), ortho[2])
assert np.allclose(np.cross(ortho[0], ortho[1]), self.plane.normal_vector)
assert np.allclose(np.cross(ortho[1], ortho[2]), ortho[0])
assert np.allclose(np.cross(ortho[2], ortho[0]), ortho[1])
assert_allclose(np.cross(ortho[0], ortho[1]), ortho[2])
assert_allclose(np.cross(ortho[0], ortho[1]), self.plane.normal_vector)
assert_allclose(np.cross(ortho[1], ortho[2]), ortho[0])
assert_allclose(np.cross(ortho[2], ortho[0]), ortho[1])
assert not np.allclose(np.cross(ortho[1], ortho[0]), ortho[2])
assert np.allclose(np.cross(ortho[0], ortho[1]), self.plane.normal_vector)
assert_allclose(np.cross(ortho[0], ortho[1]), self.plane.normal_vector)

def test_plane_comparison(self):
plane_test_1 = Plane.from_coefficients(4, 2, -4, 3)
Expand Down Expand Up @@ -164,14 +165,14 @@ def test_indices_separate(self):
assert len(sep[0]) == 0
assert len(sep[1]) == 3
assert len(sep[2]) == 5
assert np.allclose(sep[1], [1, 2, 4])
assert np.allclose(sep[2], [0, 3, 5, 6, 7])
assert_allclose(sep[1], [1, 2, 4])
assert_allclose(sep[2], [0, 3, 5, 6, 7])
sep = self.plane.indices_separate(plist, 10)
assert len(sep[0]) == 0
assert len(sep[1]) == 6
assert len(sep[2]) == 2
assert np.allclose(sep[1], [0, 1, 2, 3, 4, 6])
assert np.allclose(sep[2], [5, 7])
assert_allclose(sep[1], [0, 1, 2, 3, 4, 6])
assert_allclose(sep[2], [5, 7])
sep = self.plane.indices_separate(plist, 100000)
assert len(sep[0]) == 0
assert len(sep[1]) == 8
Expand Down Expand Up @@ -313,7 +314,7 @@ def test_projections(self):
projected_points = self.plane.projectionpoints(expected_projected_points)
projected_2d = self.plane.project_and_to2dim(expected_projected_points, "mean")
for ii, pp in enumerate(expected_projected_points):
assert np.allclose(pp, projected_points[ii])
assert_allclose(pp, projected_points[ii])
for i1, i2 in itertools.combinations(list(range(len(expected_projected_points))), 2):
assert np.isclose(
np.linalg.norm(expected_projected_points[i1] - expected_projected_points[i2]),
Expand All @@ -333,15 +334,15 @@ def test_projections(self):
projected_2d = self.plane.project_and_to2dim(points_to_project, "mean")
projected_2d_bis = self.plane.project_and_to2dim(points_to_project, meanpoint)
for ii, pp in enumerate(projected_2d):
assert np.allclose(pp, projected_2d_bis[ii])
assert_allclose(pp, projected_2d_bis[ii])
for i1, i2 in itertools.combinations(list(range(len(projected_points))), 2):
assert np.isclose(
np.linalg.norm(projected_points[i1] - projected_points[i2]),
np.linalg.norm(projected_2d[i1] - projected_2d[i2]),
)
for pp in points_to_project:
projected_2d = self.plane.project_and_to2dim([pp], pp)
assert np.allclose(projected_2d[0], 0)
assert_allclose(projected_2d[0], 0)
# Check some specific projections
points = [
np.zeros(3, np.float_),
Expand All @@ -359,7 +360,7 @@ def test_projections(self):
np.array([-1.55555556, 0.72222222, -0.44444444]),
]
for ii, pp in enumerate(projected_points):
assert np.allclose(pp, expected_projected_points[ii])
assert_allclose(pp, expected_projected_points[ii])
assert self.plane.is_in_plane(pp, 0.0000001)
projected_2d_points_000 = self.plane.project_and_to2dim(points, [0, 0, 0])
projected_2d_points_mean = self.plane.project_and_to2dim(points, "mean")
Expand Down
6 changes: 3 additions & 3 deletions pymatgen/analysis/chemenv/utils/tests/test_graph_utils.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
from __future__ import annotations

import numpy as np
import pytest
from numpy.testing import assert_allclose

from pymatgen.analysis.chemenv.connectivity.environment_nodes import EnvironmentNode
from pymatgen.analysis.chemenv.utils.graph_utils import MultiGraphCycle, SimpleGraphCycle, get_delta
Expand Down Expand Up @@ -73,9 +73,9 @@ def test_get_delta(self):
n1 = FakeNode(3)
n2 = FakeNode(7)
edge_data = {"start": 3, "end": 7, "delta": [2, 6, 4]}
assert np.allclose(get_delta(n1, n2, edge_data), [2, 6, 4])
assert_allclose(get_delta(n1, n2, edge_data), [2, 6, 4])
edge_data = {"start": 7, "end": 3, "delta": [2, 6, 4]}
assert np.allclose(get_delta(n1, n2, edge_data), [-2, -6, -4])
assert_allclose(get_delta(n1, n2, edge_data), [-2, -6, -4])
edge_data = {"start": 6, "end": 3, "delta": [2, 6, 4]}
err_msg = "Trying to find a delta between two nodes with an edge that seems not to link these nodes."
with pytest.raises(ValueError, match=err_msg):
Expand Down
13 changes: 7 additions & 6 deletions pymatgen/analysis/interfaces/coherent_interfaces.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
from typing import TYPE_CHECKING, Iterator, Sequence

import numpy as np
from numpy.testing import assert_allclose
from scipy.linalg import polar

from pymatgen.analysis.elasticity.strain import Deformation
Expand Down Expand Up @@ -87,13 +88,13 @@ def _find_matches(self) -> None:
for match in self.zsl_matches:
xform = get_2d_transform(film_vectors, match.film_vectors)
strain, rot = polar(xform)
assert np.allclose(
assert_allclose(
strain, np.round(strain)
), "Film lattice vectors changed during ZSL match, check your ZSL Generator parameters"

xform = get_2d_transform(substrate_vectors, match.substrate_vectors)
strain, rot = polar(xform)
assert np.allclose(
assert_allclose(
strain, strain.astype(int)
), "Substrate lattice vectors changed during ZSL match, check your ZSL Generator parameters"

Expand Down Expand Up @@ -195,10 +196,10 @@ def get_interfaces(
).astype(int)
film_sl_slab = film_slab.copy()
film_sl_slab.make_supercell(super_film_transform)
assert np.allclose(
assert_allclose(
film_sl_slab.lattice.matrix[2], film_slab.lattice.matrix[2]
), "2D transformation affected C-axis for Film transformation"
assert np.allclose(
assert_allclose(
film_sl_slab.lattice.matrix[:2], match.film_sl_vectors
), "Transformation didn't make proper supercell for film"

Expand All @@ -208,10 +209,10 @@ def get_interfaces(
).astype(int)
sub_sl_slab = sub_slab.copy()
sub_sl_slab.make_supercell(super_sub_transform)
assert np.allclose(
assert_allclose(
sub_sl_slab.lattice.matrix[2], sub_slab.lattice.matrix[2]
), "2D transformation affected C-axis for Film transformation"
assert np.allclose(
assert_allclose(
sub_sl_slab.lattice.matrix[:2], match.substrate_sl_vectors
), "Transformation didn't make proper supercell for substrate"

Expand Down
6 changes: 3 additions & 3 deletions pymatgen/analysis/magnetism/tests/test_analyzer.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,9 +5,9 @@
import warnings
from shutil import which

import numpy as np
import pytest
from monty.serialization import loadfn
from numpy.testing import assert_allclose
from pytest import approx

from pymatgen.analysis.magnetism import (
Expand Down Expand Up @@ -226,13 +226,13 @@ def test_round_magmoms(self):
struct.add_site_property("magmom", [-5.0143, -5.02, 0.147, 0.146])

msa = CollinearMagneticStructureAnalyzer(struct, round_magmoms=0.001, make_primitive=False)
assert np.allclose(msa.magmoms, [5.0171, 5.0171, -0.1465, -0.1465])
assert_allclose(msa.magmoms, [5.0171, 5.0171, -0.1465, -0.1465])
assert msa.magnetic_species_and_magmoms["Ni"] == approx(5.0171)
assert msa.magnetic_species_and_magmoms["O"] == approx(0.1465)

struct.add_site_property("magmom", [-5.0143, 4.5, 0.147, 0.146])
msa = CollinearMagneticStructureAnalyzer(struct, round_magmoms=0.001, make_primitive=False)
assert np.allclose(msa.magmoms, [5.0143, -4.5, -0.1465, -0.1465])
assert_allclose(msa.magmoms, [5.0143, -4.5, -0.1465, -0.1465])
assert msa.magnetic_species_and_magmoms["Ni"][0] == approx(4.5)
assert msa.magnetic_species_and_magmoms["Ni"][1] == approx(5.0143)
assert msa.magnetic_species_and_magmoms["O"] == approx(0.1465)
Expand Down
9 changes: 5 additions & 4 deletions pymatgen/analysis/tests/test_interface_reactions.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
import numpy as np
import pytest
from matplotlib.figure import Figure as mpl_figure
from numpy.testing import assert_allclose
from pandas import DataFrame
from plotly.graph_objects import Figure as plotly_figure
from scipy.spatial import ConvexHull
Expand Down Expand Up @@ -241,13 +242,13 @@ def test_convert(self):
test_array = [(0.5, 1, 3), (0.4, 2, 3), (0, 1, 9), (1, 2, 7)]
result = [InterfacialReactivity._convert(x, f1, f2) for x, f1, f2 in test_array]
answer = [0.75, 0.5, 0, 1]
assert np.allclose(result, answer), f"_convert: conversion gets error! {answer} expected, but gets {result}"
assert_allclose(result, answer), f"_convert: conversion gets error! {answer} expected, but gets {result}"

def test_reverse_convert(self):
test_array = [(0.5, 1, 3), (0.4, 2, 3), (0, 1, 9), (1, 2, 7)]
result = [InterfacialReactivity._reverse_convert(x, f1, f2) for x, f1, f2 in test_array]
answer = [0.25, 0.3076923, 0, 1]
assert np.allclose(result, answer), f"_convert: conversion gets error! {answer} expected, but gets {result}"
assert_allclose(result, answer), f"_convert: conversion gets error! {answer} expected, but gets {result}"

def test_products_property(self):
test1 = sorted(self.ir[0].products) == sorted(["MnO2", "O2", "Mn"])
Expand Down Expand Up @@ -409,7 +410,7 @@ def test_minimum(self):
(0.3333333, -4.0),
]
for i, j in zip(self.ir, answer):
assert np.allclose(i.minimum, j), (
assert_allclose(i.minimum, j), (
f"minimum: the system with {i.c1_original.reduced_formula} and {i.c2_original.reduced_formula} "
f"gets error!{j} expected, but gets {i.minimum}"
)
Expand All @@ -435,7 +436,7 @@ def energy_lst(lst):
assert name_lst(i) == name_lst(
j
), f"get_no_mixing_energy: names get error, {name_lst(j)} expected but gets {name_lst(i)}"
assert np.allclose(energy_lst(i), energy_lst(j)), (
assert_allclose(energy_lst(i), energy_lst(j)), (
"get_no_mixing_energy: "
"no_mixing energies get error, "
f"{energy_lst(j)} expected but gets {energy_lst(i)}"
Expand Down
5 changes: 3 additions & 2 deletions pymatgen/analysis/tests/test_phase_diagram.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
import numpy as np
import pytest
from monty.serialization import dumpfn, loadfn
from numpy.testing import assert_allclose
from pytest import approx

from pymatgen.analysis.phase_diagram import (
Expand Down Expand Up @@ -950,9 +951,9 @@ def test_unique_lines(self):
def test_triangular_coord(self):
coord = [0.5, 0.5]
coord = triangular_coord(coord)
assert np.allclose(coord, [0.75, 0.4330127])
assert_allclose(coord, [0.75, 0.4330127])

def test_tet_coord(self):
coord = [0.5, 0.5, 0.5]
coord = tet_coord(coord)
assert np.allclose(coord, [1.0, 0.57735027, 0.40824829])
assert_allclose(coord, [1.0, 0.57735027, 0.40824829])
Loading

0 comments on commit 6bae163

Please sign in to comment.