From 6bae163b593b8f1e2a1000d82c4e2a0e5d45f87b Mon Sep 17 00:00:00 2001 From: Janosh Riebesell Date: Sun, 2 Jul 2023 19:46:00 -0700 Subject: [PATCH] test refactor: assert np.allclose to numpy.testing.assert_allclose for much better error messages --- .../tests/test_connected_components.py | 5 ++- .../tests/test_read_write.py | 5 +-- .../tests/test_coordination_geometry_utils.py | 29 +++++++------- .../chemenv/utils/tests/test_graph_utils.py | 6 +-- .../interfaces/coherent_interfaces.py | 13 ++++--- .../analysis/magnetism/tests/test_analyzer.py | 6 +-- .../tests/test_interface_reactions.py | 9 +++-- pymatgen/analysis/tests/test_phase_diagram.py | 5 ++- .../analysis/tests/test_piezo_sensitivity.py | 39 ++++++++++--------- .../analysis/tests/test_structure_analyzer.py | 7 ++-- .../analysis/tests/test_structure_matcher.py | 39 ++++++++++--------- pymatgen/analysis/xas/tests/test_spectrum.py | 6 +-- .../command_line/tests/test_bader_caller.py | 3 +- pymatgen/core/interface.py | 9 +++-- pymatgen/core/tests/test_interface.py | 17 ++++---- pymatgen/core/tests/test_operations.py | 5 ++- pymatgen/core/tests/test_spectrum.py | 11 +++--- pymatgen/core/tests/test_trajectory.py | 3 +- .../electronic_structure/tests/test_core.py | 33 ++++++++-------- pymatgen/entries/tests/test_mixing_scheme.py | 5 ++- pymatgen/io/feff/tests/test_sets.py | 5 ++- pymatgen/io/lobster/tests/test_lobster.py | 8 ++-- pymatgen/io/tests/test_wannier90.py | 13 ++++--- pymatgen/io/vasp/outputs.py | 3 +- pymatgen/io/vasp/tests/test_optics.py | 9 +++-- pymatgen/symmetry/tests/test_analyzer.py | 7 ++-- pymatgen/symmetry/tests/test_maggroups.py | 3 +- pymatgen/symmetry/tests/test_settings.py | 10 ++--- .../tests/test_advanced_transformations.py | 6 +-- .../tests/test_site_transformations.py | 17 ++++---- pymatgen/util/tests/test_coord.py | 14 +++---- 31 files changed, 186 insertions(+), 164 deletions(-) diff --git a/pymatgen/analysis/chemenv/connectivity/tests/test_connected_components.py b/pymatgen/analysis/chemenv/connectivity/tests/test_connected_components.py index 50e8970d632..06704d642e1 100644 --- a/pymatgen/analysis/chemenv/connectivity/tests/test_connected_components.py +++ b/pymatgen/analysis/chemenv/connectivity/tests/test_connected_components.py @@ -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 @@ -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) @@ -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])], ) diff --git a/pymatgen/analysis/chemenv/coordination_environments/tests/test_read_write.py b/pymatgen/analysis/chemenv/coordination_environments/tests/test_read_write.py index 573e9fcbf30..2fc6824b5ac 100644 --- a/pymatgen/analysis/chemenv/coordination_environments/tests/test_read_write.py +++ b/pymatgen/analysis/chemenv/coordination_environments/tests/test_read_write.py @@ -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 ( @@ -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 = [ diff --git a/pymatgen/analysis/chemenv/utils/tests/test_coordination_geometry_utils.py b/pymatgen/analysis/chemenv/utils/tests/test_coordination_geometry_utils.py index 5c400fbdc3e..27bcc91b6e7 100644 --- a/pymatgen/analysis/chemenv/utils/tests/test_coordination_geometry_utils.py +++ b/pymatgen/analysis/chemenv/utils/tests/test_coordination_geometry_utils.py @@ -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 @@ -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"] @@ -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) @@ -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 @@ -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]), @@ -333,7 +334,7 @@ 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]), @@ -341,7 +342,7 @@ def test_projections(self): ) 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_), @@ -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") diff --git a/pymatgen/analysis/chemenv/utils/tests/test_graph_utils.py b/pymatgen/analysis/chemenv/utils/tests/test_graph_utils.py index cc9f02f59c6..714bac44d71 100644 --- a/pymatgen/analysis/chemenv/utils/tests/test_graph_utils.py +++ b/pymatgen/analysis/chemenv/utils/tests/test_graph_utils.py @@ -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 @@ -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): diff --git a/pymatgen/analysis/interfaces/coherent_interfaces.py b/pymatgen/analysis/interfaces/coherent_interfaces.py index e668c833ec3..a1d441b3ca9 100644 --- a/pymatgen/analysis/interfaces/coherent_interfaces.py +++ b/pymatgen/analysis/interfaces/coherent_interfaces.py @@ -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 @@ -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" @@ -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" @@ -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" diff --git a/pymatgen/analysis/magnetism/tests/test_analyzer.py b/pymatgen/analysis/magnetism/tests/test_analyzer.py index 14dd484f951..22d45c17be9 100644 --- a/pymatgen/analysis/magnetism/tests/test_analyzer.py +++ b/pymatgen/analysis/magnetism/tests/test_analyzer.py @@ -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 ( @@ -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) diff --git a/pymatgen/analysis/tests/test_interface_reactions.py b/pymatgen/analysis/tests/test_interface_reactions.py index 6ff3a9c5721..aa957c8a477 100644 --- a/pymatgen/analysis/tests/test_interface_reactions.py +++ b/pymatgen/analysis/tests/test_interface_reactions.py @@ -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 @@ -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"]) @@ -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}" ) @@ -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)}" diff --git a/pymatgen/analysis/tests/test_phase_diagram.py b/pymatgen/analysis/tests/test_phase_diagram.py index 06d49589491..1668cf538e4 100644 --- a/pymatgen/analysis/tests/test_phase_diagram.py +++ b/pymatgen/analysis/tests/test_phase_diagram.py @@ -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 ( @@ -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]) diff --git a/pymatgen/analysis/tests/test_piezo_sensitivity.py b/pymatgen/analysis/tests/test_piezo_sensitivity.py index 3a20b7892c9..e3728299497 100644 --- a/pymatgen/analysis/tests/test_piezo_sensitivity.py +++ b/pymatgen/analysis/tests/test_piezo_sensitivity.py @@ -9,6 +9,7 @@ import numpy as np import pytest +from numpy.testing import assert_allclose import pymatgen from pymatgen.analysis.piezo_sensitivity import ( @@ -94,7 +95,7 @@ def test_get_rand_BEC(self): rand_BEC = bec.get_rand_BEC() for i in range(len(self.BEC_operations)): for j in range(len(self.BEC_operations[i][2])): - assert np.allclose( + assert_allclose( rand_BEC[self.BEC_operations[i][0]], self.BEC_operations[i][2][j].transform_tensor(rand_BEC[self.BEC_operations[i][1]]), atol=1e-03, @@ -106,7 +107,7 @@ def test_get_rand_IST(self): rand_IST = ist.get_rand_IST() for i in range(len(self.IST_operations)): for j in range(len(self.IST_operations[i])): - assert np.allclose( + assert_allclose( rand_IST[i], self.IST_operations[i][j][1].transform_tensor(rand_IST[self.IST_operations[i][j][0]]), atol=1e-03, @@ -127,7 +128,7 @@ def test_get_unstable_FCM(self): rand_FCM = np.reshape(rand_FCM, (10, 3, 10, 3)).swapaxes(1, 2) for i in range(len(self.FCM_operations)): for j in range(len(self.FCM_operations[i][4])): - assert np.allclose( + assert_allclose( self.FCM_operations[i][4][j].transform_tensor( rand_FCM[self.FCM_operations[i][2]][self.FCM_operations[i][3]] ), @@ -143,7 +144,7 @@ def test_get_FCM_symmetry(self): fcm = np.reshape(fcm, (10, 3, 10, 3)).swapaxes(1, 2) for i in range(len(self.FCM_operations)): for j in range(len(self.FCM_operations[i][4])): - assert np.allclose( + assert_allclose( self.FCM_operations[i][4][j].transform_tensor( fcm[self.FCM_operations[i][2]][self.FCM_operations[i][3]] ), @@ -160,7 +161,7 @@ def test_get_asum_FCM(self): for i in range(len(self.FCM_operations)): for j in range(len(self.FCM_operations[i][4])): - assert np.allclose( + assert_allclose( self.FCM_operations[i][4][j].transform_tensor( rand_FCM[self.FCM_operations[i][2]][self.FCM_operations[i][3]] ), @@ -174,8 +175,8 @@ def test_get_asum_FCM(self): for j in range(len(rand_FCM[i])): asum1 += rand_FCM[i][j] asum2 += rand_FCM[j][i] - assert np.allclose(asum1, np.zeros([3, 3]), atol=1e-05) - assert np.allclose(asum2, np.zeros([3, 3]), atol=1e-05) + assert_allclose(asum1, np.zeros([3, 3]), atol=1e-05) + assert_allclose(asum2, np.zeros([3, 3]), atol=1e-05) def test_get_stable_FCM(self): fcm = ForceConstantMatrix(self.piezo_struc, self.FCM, self.pointops, self.sharedops) @@ -192,7 +193,7 @@ def test_get_stable_FCM(self): for i in range(len(self.FCM_operations)): for j in range(len(self.FCM_operations[i][4])): - assert np.allclose( + assert_allclose( self.FCM_operations[i][4][j].transform_tensor( rand_FCM1[self.FCM_operations[i][2]][self.FCM_operations[i][3]] ), @@ -206,8 +207,8 @@ def test_get_stable_FCM(self): for j in range(len(rand_FCM1[i])): asum1 += rand_FCM1[i][j] asum2 += rand_FCM1[j][i] - assert np.allclose(asum1, np.zeros([3, 3]), atol=1e-05) - assert np.allclose(asum2, np.zeros([3, 3]), atol=1e-05) + assert_allclose(asum1, np.zeros([3, 3]), atol=1e-05) + assert_allclose(asum2, np.zeros([3, 3]), atol=1e-05) def test_rand_FCM(self): pytest.importorskip("phonopy") @@ -240,7 +241,7 @@ def test_rand_FCM(self): dynmass = np.reshape(dynmass, (10, 3, 10, 3)).swapaxes(1, 2) for i in range(len(self.FCM_operations)): for j in range(len(self.FCM_operations[i][4])): - assert np.allclose( + assert_allclose( self.FCM_operations[i][4][j].transform_tensor( dynmass[self.FCM_operations[i][2]][self.FCM_operations[i][3]] ), @@ -254,12 +255,12 @@ def test_rand_FCM(self): for j in range(len(dynmass[i])): asum1 += dynmass[i][j] asum2 += dynmass[j][i] - assert np.allclose(asum1, np.zeros([3, 3]), atol=1e-05) - assert np.allclose(asum2, np.zeros([3, 3]), atol=1e-05) + assert_allclose(asum1, np.zeros([3, 3]), atol=1e-05) + assert_allclose(asum2, np.zeros([3, 3]), atol=1e-05) def test_get_piezo(self): piezo = get_piezo(self.BEC, self.IST, self.FCM) - assert np.allclose(piezo, self.piezo, atol=1e-05) + assert_allclose(piezo, self.piezo, atol=1e-05) def test_rand_piezo(self): pytest.importorskip("phonopy") @@ -274,7 +275,7 @@ def test_rand_piezo(self): for i in range(len(self.BEC_operations)): for j in range(len(self.BEC_operations[i][2])): - assert np.allclose( + assert_allclose( rand_BEC[self.BEC_operations[i][0]], self.BEC_operations[i][2][j].transform_tensor(rand_BEC[self.BEC_operations[i][1]]), atol=1e-03, @@ -282,7 +283,7 @@ def test_rand_piezo(self): for i in range(len(self.IST_operations)): for j in range(len(self.IST_operations[i])): - assert np.allclose( + assert_allclose( rand_IST[i], self.IST_operations[i][j][1].transform_tensor(rand_IST[self.IST_operations[i][j][0]]), atol=1e-03, @@ -314,7 +315,7 @@ def test_rand_piezo(self): dynmass = np.reshape(dynmass, (10, 3, 10, 3)).swapaxes(1, 2) for i in range(len(self.FCM_operations)): for j in range(len(self.FCM_operations[i][4])): - assert np.allclose( + assert_allclose( self.FCM_operations[i][4][j].transform_tensor( dynmass[self.FCM_operations[i][2]][self.FCM_operations[i][3]] ), @@ -328,5 +329,5 @@ def test_rand_piezo(self): for j in range(len(dynmass[i])): asum1 += dynmass[i][j] asum2 += dynmass[j][i] - assert np.allclose(asum1, np.zeros([3, 3]), atol=1e-05) - assert np.allclose(asum2, np.zeros([3, 3]), atol=1e-05) + assert_allclose(asum1, np.zeros([3, 3]), atol=1e-05) + assert_allclose(asum2, np.zeros([3, 3]), atol=1e-05) diff --git a/pymatgen/analysis/tests/test_structure_analyzer.py b/pymatgen/analysis/tests/test_structure_analyzer.py index e6b3b1a3e7e..6147cf4572d 100644 --- a/pymatgen/analysis/tests/test_structure_analyzer.py +++ b/pymatgen/analysis/tests/test_structure_analyzer.py @@ -4,6 +4,7 @@ import unittest import numpy as np +from numpy.testing import assert_allclose from pytest import approx from pymatgen.analysis.structure_analyzer import ( @@ -71,15 +72,15 @@ def test_connectivity_array(self): vc = VoronoiConnectivity(self.get_structure("LiFePO4")) ca = vc.connectivity_array expected = np.array([0, 1.96338392, 0, 0.04594495]) - assert np.allclose(ca[15, :4, ca.shape[2] // 2], expected) + assert_allclose(ca[15, :4, ca.shape[2] // 2], expected) expected = np.array([0, 0, 0]) - assert np.allclose(ca[1, -3:, 51], expected) + assert_allclose(ca[1, -3:, 51], expected) site = vc.get_sitej(27, 51) assert site.specie == Element("O") expected = np.array([-0.29158, 0.74889, 0.95684]) - assert np.allclose(site.frac_coords, expected) + assert_allclose(site.frac_coords, expected) class MiscFunctionTest(PymatgenTest): diff --git a/pymatgen/analysis/tests/test_structure_matcher.py b/pymatgen/analysis/tests/test_structure_matcher.py index f944b2f9d36..b38c810aaf0 100644 --- a/pymatgen/analysis/tests/test_structure_matcher.py +++ b/pymatgen/analysis/tests/test_structure_matcher.py @@ -6,6 +6,7 @@ import numpy as np import pytest from monty.json import MontyDecoder +from numpy.testing import assert_allclose from pytest import approx from pymatgen.analysis.structure_matcher import ( @@ -120,21 +121,21 @@ def test_cart_dists(self): sm._cart_dists(s1, s2, latt, mask.T, n1) d, ft, s = sm._cart_dists(s1, s2, latt, mask, n1) - assert np.allclose(d, [0]) - assert np.allclose(ft, [-0.01, -0.02, -0.03]) - assert np.allclose(s, [1]) + assert_allclose(d, [0]) + assert_allclose(ft, [-0.01, -0.02, -0.03]) + assert_allclose(s, [1]) # check that masking best value works d, ft, s = sm._cart_dists(s1, s2, latt, mask2, n1) - assert np.allclose(d, [0]) - assert np.allclose(ft, [0.02, 0.03, 0.04]) - assert np.allclose(s, [0]) + assert_allclose(d, [0]) + assert_allclose(ft, [0.02, 0.03, 0.04]) + assert_allclose(s, [0]) # check that averaging of translation is done properly d, ft, s = sm._cart_dists(s1, s3, latt, mask3, n1) - assert np.allclose(d, [0.08093341] * 2) - assert np.allclose(ft, [0.01, 0.025, 0.035]) - assert np.allclose(s, [1, 0]) + assert_allclose(d, [0.08093341] * 2) + assert_allclose(ft, [0.01, 0.025, 0.035]) + assert_allclose(s, [1, 0]) # check distances are large when mask allows no 'real' mapping d, ft, s = sm._cart_dists(s1, s4, latt, mask4, n1) @@ -166,7 +167,7 @@ def test_get_mask(self): m, inds, i = sm._get_mask(s1, s2, 2, True) assert np.all(m == result) assert i == 2 - assert np.allclose(inds, np.array([4])) + assert_allclose(inds, np.array([4])) # test supercell without match result = [ @@ -178,7 +179,7 @@ def test_get_mask(self): m, inds, i = sm._get_mask(s2, s1, 2, True) assert np.all(m == result) assert i == 0 - assert np.allclose(inds, np.array([])) + assert_allclose(inds, np.array([])) # test s2_supercell result = [ @@ -194,7 +195,7 @@ def test_get_mask(self): m, inds, i = sm._get_mask(s2, s1, 2, False) assert np.all(m == result) assert i == 0 - assert np.allclose(inds, np.array([])) + assert_allclose(inds, np.array([])) # test for multiple translation indices s1 = Structure(latt, ["Cu", "Ag", "Cu", "Ag", "Ag"], [[0] * 3] * 5) @@ -204,7 +205,7 @@ def test_get_mask(self): assert np.all(m == result) assert i == 1 - assert np.allclose(inds, [0, 2]) + assert_allclose(inds, [0, 2]) def test_get_supercells(self): sm = StructureMatcher(comparator=ElementComparator()) @@ -488,8 +489,8 @@ def test_supercell_subsets(self): assert sm_no_s.fit(s2, s1) rms = (0.048604032430991401, 0.059527539448807391) - assert np.allclose(sm.get_rms_dist(s1, s2), rms) - assert np.allclose(sm.get_rms_dist(s2, s1), rms) + assert_allclose(sm.get_rms_dist(s1, s2), rms) + assert_allclose(sm.get_rms_dist(s2, s1), rms) # test when the supercell is a subset of s2 subset_supercell = s1.copy() @@ -506,8 +507,8 @@ def test_supercell_subsets(self): assert not sm_no_s.fit(s2, subset_supercell) rms = (0.053243049896333279, 0.059527539448807336) - assert np.allclose(sm.get_rms_dist(subset_supercell, s2), rms) - assert np.allclose(sm.get_rms_dist(s2, subset_supercell), rms) + assert_allclose(sm.get_rms_dist(subset_supercell, s2), rms) + assert_allclose(sm.get_rms_dist(s2, subset_supercell), rms) # test when s2 (once made a supercell) is a subset of s1 s2_missing_site = s2.copy() @@ -523,8 +524,8 @@ def test_supercell_subsets(self): assert not sm_no_s.fit(s2_missing_site, s1) rms = (0.029763769724403633, 0.029763769724403987) - assert np.allclose(sm.get_rms_dist(s1, s2_missing_site), rms) - assert np.allclose(sm.get_rms_dist(s2_missing_site, s1), rms) + assert_allclose(sm.get_rms_dist(s1, s2_missing_site), rms) + assert_allclose(sm.get_rms_dist(s2_missing_site, s1), rms) def test_get_s2_large_s2(self): sm = StructureMatcher( diff --git a/pymatgen/analysis/xas/tests/test_spectrum.py b/pymatgen/analysis/xas/tests/test_spectrum.py index bcb4415f17b..1d60555b806 100644 --- a/pymatgen/analysis/xas/tests/test_spectrum.py +++ b/pymatgen/analysis/xas/tests/test_spectrum.py @@ -6,7 +6,7 @@ import numpy as np import pytest from monty.json import MontyDecoder -from numpy.testing import assert_array_equal +from numpy.testing import assert_allclose, assert_array_equal from pytest import approx from pymatgen.analysis.xas.spectrum import XAS, site_weighted_spectrum @@ -52,8 +52,8 @@ def test_normalization(self): def test_add_mul(self): scaled_spect = self.k_xanes + self.k_xanes scaled_spect2 = self.k_xanes * 3 - assert np.allclose(scaled_spect.y, 2 * self.k_xanes.y) - assert np.allclose(scaled_spect2.y, 3 * self.k_xanes.y) + assert_allclose(scaled_spect.y, 2 * self.k_xanes.y) + assert_allclose(scaled_spect2.y, 3 * self.k_xanes.y) assert approx(self.k_xanes.get_interpolated_value(7720.422), abs=1e-3) == 0.274302 def test_to_from_dict(self): diff --git a/pymatgen/command_line/tests/test_bader_caller.py b/pymatgen/command_line/tests/test_bader_caller.py index ec3d0faa25f..c9f08bbfdc7 100644 --- a/pymatgen/command_line/tests/test_bader_caller.py +++ b/pymatgen/command_line/tests/test_bader_caller.py @@ -5,6 +5,7 @@ import warnings import numpy as np +from numpy.testing import assert_allclose from pytest import approx from pymatgen.command_line.bader_caller import BaderAnalysis, bader_analysis_from_path, which @@ -72,7 +73,7 @@ def test_from_path(self): analysis0 = BaderAnalysis(chgcar_filename=chgcar, chgref_filename=chgref) charge = np.array(analysis.summary["charge"]) charge0 = np.array(analysis0.summary["charge"]) - assert np.allclose(charge, charge0) + assert_allclose(charge, charge0) if os.path.exists("CHGREF"): os.remove("CHGREF") diff --git a/pymatgen/core/interface.py b/pymatgen/core/interface.py index 54834288180..68a9fadfbe2 100644 --- a/pymatgen/core/interface.py +++ b/pymatgen/core/interface.py @@ -5,6 +5,7 @@ from itertools import chain, combinations, product import numpy as np +from numpy.testing import assert_allclose from scipy.cluster.hierarchy import fcluster, linkage from scipy.spatial.distance import squareform @@ -348,10 +349,10 @@ def from_slabs( substrate_slab = substrate_slab.get_orthogonal_c_slab() if isinstance(film_slab, Slab): film_slab = film_slab.get_orthogonal_c_slab() - assert np.allclose(film_slab.lattice.alpha, 90, 0.1) - assert np.allclose(film_slab.lattice.beta, 90, 0.1) - assert np.allclose(substrate_slab.lattice.alpha, 90, 0.1) - assert np.allclose(substrate_slab.lattice.beta, 90, 0.1) + assert_allclose(film_slab.lattice.alpha, 90, 0.1) + assert_allclose(film_slab.lattice.beta, 90, 0.1) + assert_allclose(substrate_slab.lattice.alpha, 90, 0.1) + assert_allclose(substrate_slab.lattice.beta, 90, 0.1) # Ensure sub is right-handed # IE sub has surface facing "up" diff --git a/pymatgen/core/tests/test_interface.py b/pymatgen/core/tests/test_interface.py index dcd95821673..9b011738a2a 100644 --- a/pymatgen/core/tests/test_interface.py +++ b/pymatgen/core/tests/test_interface.py @@ -1,6 +1,7 @@ from __future__ import annotations import numpy as np +from numpy.testing import assert_allclose from pymatgen.core.interface import Interface from pymatgen.core.surface import SlabGenerator @@ -21,7 +22,7 @@ def test_basic_props(self): assert len(interface.film_sites) == len(interface.film_indices) assert len(interface.substrate_sites) == len(interface.substrate_indices) assert interface.gap == 2.0 - assert np.allclose(interface.in_plane_offset, [0, 0]) + assert_allclose(interface.in_plane_offset, [0, 0]) assert interface.vacuum_over_film == 20.0 assert interface.film_termination == "O2_P6/mmm_4" assert interface.substrate_termination == "Si_P6/mmm_7" @@ -36,33 +37,33 @@ def test_basic_props(self): def test_gap_setter(self): interface = self.interface - assert np.allclose(interface.gap, 2.0) + assert_allclose(interface.gap, 2.0) max_sub_c = np.max(np.array([s.frac_coords for s in interface.substrate])[:, 2]) min_film_c = np.min(np.array([f.frac_coords for f in interface.film])[:, 2]) gap = (min_film_c - max_sub_c) * interface.lattice.c - assert np.allclose(interface.gap, gap) + assert_allclose(interface.gap, gap) interface.gap += 1 - assert np.allclose(interface.gap, 3.0) + assert_allclose(interface.gap, 3.0) max_sub_c = np.max(np.array([s.frac_coords for s in interface.substrate])[:, 2]) min_film_c = np.min(np.array([f.frac_coords for f in interface.film])[:, 2]) gap = (min_film_c - max_sub_c) * interface.lattice.c - assert np.allclose(interface.gap, gap) + assert_allclose(interface.gap, gap) def test_in_plane_offset_setter(self): interface = self.interface init_coords = np.array(self.interface.frac_coords) interface.in_plane_offset = np.array([0.2, 0.2]) - assert np.allclose(interface.in_plane_offset, np.array([0.2, 0.2])) + assert_allclose(interface.in_plane_offset, np.array([0.2, 0.2])) test_coords = np.array(init_coords) for i in interface.film_indices: test_coords[i] += [0.2, 0.2, 0] - assert np.allclose(np.mod(test_coords, 1.0), np.mod(interface.frac_coords, 1.0)) + assert_allclose(np.mod(test_coords, 1.0), np.mod(interface.frac_coords, 1.0)) def test_vacuum_over_film_setter(self): interface = self.interface @@ -73,7 +74,7 @@ def test_vacuum_over_film_setter(self): interface.vacuum_over_film += 10 assert interface.vacuum_over_film == 30 - assert np.allclose(init_coords, interface.cart_coords) + assert_allclose(init_coords, interface.cart_coords) def test_get_shifts_based_on_adsorbate_sites(self): # Only testing two tolerances as there appears to be significant numerical noise in this method diff --git a/pymatgen/core/tests/test_operations.py b/pymatgen/core/tests/test_operations.py index 321293d6a27..d9a82ba47ed 100644 --- a/pymatgen/core/tests/test_operations.py +++ b/pymatgen/core/tests/test_operations.py @@ -1,6 +1,7 @@ from __future__ import annotations import numpy as np +from numpy.testing import assert_allclose from pymatgen.core.operations import MagSymmOp, SymmOp from pymatgen.electronic_structure.core import Magmom @@ -41,7 +42,7 @@ def test_reflection(self): point = np.random.rand(3) new_coord = refl.operate(point) # Distance to the plane should be negatives of each other. - assert np.allclose(np.dot(new_coord - origin, normal), -np.dot(point - origin, normal)) + assert_allclose(np.dot(new_coord - origin, normal), -np.dot(point - origin, normal)) def test_apply_rotation_only(self): point = np.random.rand(3) @@ -281,7 +282,7 @@ def test_operate_magmom(self): for xyzt_string, transformed_magmom in zip(xyzt_strings, transformed_magmoms): for magmom in magmoms: op = MagSymmOp.from_xyzt_string(xyzt_string) - assert np.allclose(transformed_magmom, op.operate_magmom(magmom).global_moment) + assert_allclose(transformed_magmom, op.operate_magmom(magmom).global_moment) if __name__ == "__main__": diff --git a/pymatgen/core/tests/test_spectrum.py b/pymatgen/core/tests/test_spectrum.py index 55b5e339506..2424f049186 100644 --- a/pymatgen/core/tests/test_spectrum.py +++ b/pymatgen/core/tests/test_spectrum.py @@ -1,6 +1,7 @@ from __future__ import annotations import numpy as np +from numpy.testing import assert_allclose from pytest import approx from scipy import stats @@ -32,17 +33,17 @@ def test_normalize(self): def test_operators(self): scaled_spect = 3 * self.spec1 + self.spec2 - assert np.allclose(scaled_spect.y, 3 * self.spec1.y + self.spec2.y) + assert_allclose(scaled_spect.y, 3 * self.spec1.y + self.spec2.y) assert self.spec1.get_interpolated_value(0.05) == approx((self.spec1.y[0] + self.spec1.y[1]) / 2) scaled_spect = self.spec1 - self.spec2 - assert np.allclose(scaled_spect.y, self.spec1.y - self.spec2.y) + assert_allclose(scaled_spect.y, self.spec1.y - self.spec2.y) scaled_spect = self.spec1 / 3 - assert np.allclose(scaled_spect.y, self.spec1.y / 3) + assert_allclose(scaled_spect.y, self.spec1.y / 3) scaled_spect = 3 * self.multi_spec1 + self.multi_spec2 - assert np.allclose(scaled_spect.y, 3 * self.multi_spec1.y + self.multi_spec2.y) + assert_allclose(scaled_spect.y, 3 * self.multi_spec1.y + self.multi_spec2.y) self.assert_all_close( self.multi_spec1.get_interpolated_value(0.05), (self.multi_spec1.y[0, :] + self.multi_spec1.y[1, :]) / 2, @@ -61,7 +62,7 @@ def test_smear(self): # Test direct callable use of smearing. spec2 = Spectrum(np.linspace(-10, 10, 100), y) spec2.smear(0, func=lambda x: stats.norm.pdf(x, scale=0.3)) - assert np.allclose(spec.y, spec2.y) + assert_allclose(spec.y, spec2.y) spec = Spectrum(np.linspace(-10, 10, 100), y) spec.smear(0.3, func="lorentzian") diff --git a/pymatgen/core/tests/test_trajectory.py b/pymatgen/core/tests/test_trajectory.py index a3f5d6cbcc3..8e8ba26f6c1 100644 --- a/pymatgen/core/tests/test_trajectory.py +++ b/pymatgen/core/tests/test_trajectory.py @@ -4,6 +4,7 @@ import os import numpy as np +from numpy.testing import assert_allclose from pymatgen.core.lattice import Lattice from pymatgen.core.structure import Molecule, Structure @@ -432,7 +433,7 @@ def test_displacements(self): traj = Trajectory.from_structures(structures, constant_lattice=True) traj.to_displacements() - assert np.allclose(traj.coords, displacements) + assert_allclose(traj.coords, displacements) def test_variable_lattice(self): structure = self.structures[0] diff --git a/pymatgen/electronic_structure/tests/test_core.py b/pymatgen/electronic_structure/tests/test_core.py index ca8c9430659..f723b3372d4 100644 --- a/pymatgen/electronic_structure/tests/test_core.py +++ b/pymatgen/electronic_structure/tests/test_core.py @@ -4,6 +4,7 @@ import numpy as np import pytest +from numpy.testing import assert_allclose from pymatgen.core import Lattice from pymatgen.electronic_structure.core import Magmom, Orbital, Spin @@ -46,21 +47,21 @@ def test_init(self): assert magmom2.global_moment.tolist() == [1, 2, 3] # non-default saxis, normalized internally magmom3 = Magmom([1, 2, 3], saxis=[1, 1, 1]) - assert np.allclose(magmom3.saxis, [np.sqrt(1 / 3.0)] * 3) + assert_allclose(magmom3.saxis, [np.sqrt(1 / 3.0)] * 3) # test construction from known global moment and desired, non-default saxis magmom4 = Magmom.from_global_moment_and_saxis([1, 2, 3], saxis=[1, 0, 0]) - assert np.allclose(magmom4.moment, [-3, 2, 1]) + assert_allclose(magmom4.moment, [-3, 2, 1]) # test global moments with non-default saxis magmom5 = Magmom([-3, 2, 1], saxis=[1, 0, 0]) - assert np.allclose(magmom5.global_moment, [1, 2, 3]) + assert_allclose(magmom5.global_moment, [1, 2, 3]) def test_get_moments(self): # simple cases magmom_along_x = Magmom([1, 0, 0]) - assert np.allclose(magmom_along_x.get_moment(saxis=[1, 0, 0]), [0, 0, 1]) + assert_allclose(magmom_along_x.get_moment(saxis=[1, 0, 0]), [0, 0, 1]) magmom_along_y = Magmom([0, 1, 0]) - assert np.allclose(magmom_along_y.get_moment(saxis=[0, 1, 0]), [0, 0, 1]) + assert_allclose(magmom_along_y.get_moment(saxis=[0, 1, 0]), [0, 0, 1]) # test transformations magmoms = [ @@ -78,13 +79,13 @@ def test_get_moments(self): magmom2 = magmom1.get_00t_magmom_with_xyz_saxis() # and back to default saxis magmom3 = magmom2.get_xyz_magmom_with_001_saxis() - assert np.allclose(magmom1.moment, magmom) - assert np.allclose(magmom1.saxis, [0, 0, 1]) - assert np.allclose(magmom1.get_moment(saxis=magmom1.saxis), magmom1.moment) - assert np.allclose(magmom1.get_moment(saxis=magmom2.saxis), magmom2.moment) - assert np.allclose(magmom2.get_moment(saxis=[0, 0, 1]), magmom1.moment) - assert np.allclose(magmom2.get_moment(saxis=magmom2.saxis), magmom2.moment) - assert np.allclose(magmom3.moment, magmom1.moment) + assert_allclose(magmom1.moment, magmom) + assert_allclose(magmom1.saxis, [0, 0, 1]) + assert_allclose(magmom1.get_moment(saxis=magmom1.saxis), magmom1.moment) + assert_allclose(magmom1.get_moment(saxis=magmom2.saxis), magmom2.moment) + assert_allclose(magmom2.get_moment(saxis=[0, 0, 1]), magmom1.moment) + assert_allclose(magmom2.get_moment(saxis=magmom2.saxis), magmom2.moment) + assert_allclose(magmom3.moment, magmom1.moment) def test_is_collinear(self): magmoms_list = [ @@ -112,18 +113,18 @@ def test_have_consistent_saxis(self): def test_get_consistent_set_and_saxis(self): magmoms = [1, 1, 2, 2, 0, 0, 2] magmoms, saxis = Magmom.get_consistent_set_and_saxis(magmoms) - assert np.allclose(saxis, [0, 0, 1]) + assert_allclose(saxis, [0, 0, 1]) magmoms = [[0, 0, 0], [1, 1, 1], [2, 2, 2]] magmoms, saxis = Magmom.get_consistent_set_and_saxis(magmoms) - assert np.allclose(saxis, [np.sqrt(1 / 3.0)] * 3) + assert_allclose(saxis, [np.sqrt(1 / 3.0)] * 3) def test_relative_to_crystal_axes(self): lattice = Lattice.from_parameters(5, 10, 5, 90, 110, 90) moment = [1, 0, 2] magmom = Magmom.from_moment_relative_to_crystal_axes(moment, lattice) - assert np.allclose(magmom.moment, [0.93969262, 0.0, 1.65797986]) - assert np.allclose(magmom.get_moment_relative_to_crystal_axes(lattice), moment) + assert_allclose(magmom.moment, [0.93969262, 0.0, 1.65797986]) + assert_allclose(magmom.get_moment_relative_to_crystal_axes(lattice), moment) def test_equality(self): assert Magmom([1, 1, 1]) == Magmom([1, 1, 1]) diff --git a/pymatgen/entries/tests/test_mixing_scheme.py b/pymatgen/entries/tests/test_mixing_scheme.py index 076193f2376..fee58df74c7 100644 --- a/pymatgen/entries/tests/test_mixing_scheme.py +++ b/pymatgen/entries/tests/test_mixing_scheme.py @@ -106,6 +106,7 @@ import pandas as pd import pytest from monty.json import MontyDecoder +from numpy.testing import assert_allclose from pymatgen.analysis.phase_diagram import PhaseDiagram from pymatgen.analysis.structure_matcher import StructureMatcher @@ -1583,7 +1584,7 @@ def test_state_all_gga_scan_gs(self, mixing_scheme_no_compat, ms_all_gga_scan_gs for e in entries: if e.parameters["run_type"] == "GGA": assert "onto the R2SCAN hull" in e.energy_adjustments[0].description - assert np.allclose(pd_mixed.get_e_above_hull(e), gga_hull_e[e.entry_id]) + assert_allclose(pd_mixed.get_e_above_hull(e), gga_hull_e[e.entry_id]) else: assert e.correction == 0 @@ -1622,7 +1623,7 @@ def test_state_novel_scan_comp(self, mixing_scheme_no_compat, ms_all_gga_scan_gs for e in entries: if e.parameters["run_type"] == "GGA": assert "onto the R2SCAN hull" in e.energy_adjustments[0].description - assert np.allclose(pd_mixed.get_e_above_hull(e), gga_hull_e[e.entry_id]) + assert_allclose(pd_mixed.get_e_above_hull(e), gga_hull_e[e.entry_id]) else: assert e.correction == 0 diff --git a/pymatgen/io/feff/tests/test_sets.py b/pymatgen/io/feff/tests/test_sets.py index 71dd55e4354..9ddf66676ca 100644 --- a/pymatgen/io/feff/tests/test_sets.py +++ b/pymatgen/io/feff/tests/test_sets.py @@ -6,6 +6,7 @@ import numpy as np import pytest +from numpy.testing import assert_allclose from pymatgen.core.structure import Molecule, Structure from pymatgen.io.cif import CifParser @@ -200,7 +201,7 @@ def test_postfeffset(self): original_mole_shell = [x.species_string for x in origin_mole] output_mole_shell = [x.species_string for x in output_mole] - assert np.allclose(original_mole_dist, output_mole_dist) + assert_allclose(original_mole_dist, output_mole_dist) assert origin_tags == output_tags assert original_mole_shell == output_mole_shell @@ -248,7 +249,7 @@ def test_post_distdiff(self): original_mole_shell = [x.species_string for x in origin_mole] output_mole_shell = [x.species_string for x in output_mole] - assert np.allclose(original_mole_dist, output_mole_dist) + assert_allclose(original_mole_dist, output_mole_dist) assert origin_tags == output_tags assert original_mole_shell == output_mole_shell diff --git a/pymatgen/io/lobster/tests/test_lobster.py b/pymatgen/io/lobster/tests/test_lobster.py index a90751d6cc2..28bfac1ba71 100644 --- a/pymatgen/io/lobster/tests/test_lobster.py +++ b/pymatgen/io/lobster/tests/test_lobster.py @@ -8,7 +8,7 @@ import numpy as np import pytest -from numpy.testing import assert_array_equal +from numpy.testing import assert_allclose, assert_array_equal from pytest import approx from pymatgen.core.structure import Structure @@ -716,11 +716,11 @@ def test_complete_dos(self): assert tdos_down == self.DOSCAR_spin_pol.completedos.densities[Spin.down].tolist() assert fermi == approx(self.DOSCAR_spin_pol.completedos.efermi) - assert np.allclose( + assert_allclose( self.DOSCAR_spin_pol.completedos.structure.frac_coords, self.structure.frac_coords, ) - assert np.allclose( + assert_allclose( self.DOSCAR_spin_pol2.completedos.structure.frac_coords, self.structure.frac_coords, ) @@ -2317,7 +2317,7 @@ def test_structure_with_grosspop(self): new_structure = self.grosspop1.get_structure_with_total_grosspop( os.path.join(PymatgenTest.TEST_FILES_DIR, "cohp", "POSCAR.SiO2") ) - assert np.allclose(new_structure.frac_coords, Structure.from_dict(struct_dict).frac_coords) + assert_allclose(new_structure.frac_coords, Structure.from_dict(struct_dict).frac_coords) class TestUtils(PymatgenTest): diff --git a/pymatgen/io/tests/test_wannier90.py b/pymatgen/io/tests/test_wannier90.py index 791f541f7a2..5c90b3902c4 100644 --- a/pymatgen/io/tests/test_wannier90.py +++ b/pymatgen/io/tests/test_wannier90.py @@ -6,6 +6,7 @@ import numpy as np import pytest +from numpy.testing import assert_allclose from pytest import approx from pymatgen.io.wannier90 import Unk @@ -28,8 +29,8 @@ def test_init(self): assert self.unk_std.ng[0] == 5 assert self.unk_std.ng[1] == 5 assert self.unk_std.ng[2] == 5 - assert np.allclose(self.unk_std.data.shape, (10, 5, 5, 5)) - assert np.allclose(self.unk_std.data, self.data_std) + assert_allclose(self.unk_std.data.shape, (10, 5, 5, 5)) + assert_allclose(self.unk_std.data, self.data_std) assert not self.unk_std.is_noncollinear # too small data @@ -48,8 +49,8 @@ def test_init(self): assert self.unk_ncl.ng[0] == 5 assert self.unk_ncl.ng[1] == 5 assert self.unk_ncl.ng[2] == 5 - assert np.allclose(self.unk_ncl.data.shape, (10, 2, 5, 5, 5)) - assert np.allclose(self.unk_ncl.data, self.data_ncl) + assert_allclose(self.unk_ncl.data.shape, (10, 2, 5, 5, 5)) + assert_allclose(self.unk_ncl.data, self.data_ncl) assert self.unk_ncl.is_noncollinear # too big data @@ -65,7 +66,7 @@ def test_from_file(self): assert unk.ng[1] == 6 assert unk.ng[2] == 8 assert not unk.is_noncollinear - assert np.allclose(unk.data.shape, (5, 6, 6, 8)) + assert_allclose(unk.data.shape, (5, 6, 6, 8)) unk = Unk.from_file(self.TEST_FILES_DIR / "UNK.ncl") assert unk.ik == 1 @@ -74,7 +75,7 @@ def test_from_file(self): assert unk.ng[1] == 6 assert unk.ng[2] == 8 assert unk.is_noncollinear - assert np.allclose(unk.data.shape, (5, 2, 6, 6, 8)) + assert_allclose(unk.data.shape, (5, 2, 6, 6, 8)) assert unk.data[0, 0, 0, 0, 0].real != 0.0 assert unk.data[0, 1, 0, 0, 0].real == approx(0.0) diff --git a/pymatgen/io/vasp/outputs.py b/pymatgen/io/vasp/outputs.py index 4b6640ff740..dc1f65b7bbe 100644 --- a/pymatgen/io/vasp/outputs.py +++ b/pymatgen/io/vasp/outputs.py @@ -22,6 +22,7 @@ from monty.json import MSONable, jsanitize from monty.os.path import zpath from monty.re import regrep +from numpy.testing import assert_allclose from pymatgen.core.composition import Composition from pymatgen.core.lattice import Lattice @@ -4605,7 +4606,7 @@ def __init__(self, filename="WAVECAR", verbose=False, precision="normal", vasp_t if ispin == 0: self.kpoints.append(kpoint) else: - assert np.allclose(self.kpoints[ink], kpoint) + assert_allclose(self.kpoints[ink], kpoint) if verbose: print(f"kpoint {ink: 4} with {nplane: 5} plane waves at {kpoint}") diff --git a/pymatgen/io/vasp/tests/test_optics.py b/pymatgen/io/vasp/tests/test_optics.py index 951a2b9c6aa..9ae9498b12c 100644 --- a/pymatgen/io/vasp/tests/test_optics.py +++ b/pymatgen/io/vasp/tests/test_optics.py @@ -3,6 +3,7 @@ import numpy as np import pytest import scipy.special +from numpy.testing import assert_allclose from pymatgen.io.vasp.optics import DielectricFunctionCalculator, delta_func, delta_methfessel_paxton, step_func from pymatgen.io.vasp.outputs import Vasprun @@ -69,16 +70,16 @@ def test_delta_func(): def test_step_func(): # array of positive values x = np.array([1, 2, 3, 4, 5]) - assert np.allclose(step_func(x, -1), 1 / (1.0 + np.exp(-x))) + assert_allclose(step_func(x, -1), 1 / (1.0 + np.exp(-x))) # array of negative values x = np.array([-1, -2, -3, -4, -5]) - assert np.allclose(step_func(x, -1), 1 / (1.0 + np.exp(-x))) + assert_allclose(step_func(x, -1), 1 / (1.0 + np.exp(-x))) # array that includes zero x = np.array([-1, 0, 1]) - assert np.allclose(step_func(x, -1), 1 / (1.0 + np.exp(-x))) + assert_allclose(step_func(x, -1), 1 / (1.0 + np.exp(-x))) # ismear == 0 x = np.array([1, 2, 3, 4, 5]) - assert np.allclose(step_func(x, 0), 0.5 + 0.5 * scipy.special.erf(x)) + assert_allclose(step_func(x, 0), 0.5 + 0.5 * scipy.special.erf(x)) diff --git a/pymatgen/symmetry/tests/test_analyzer.py b/pymatgen/symmetry/tests/test_analyzer.py index 5010cf688de..e50bf243b24 100644 --- a/pymatgen/symmetry/tests/test_analyzer.py +++ b/pymatgen/symmetry/tests/test_analyzer.py @@ -5,6 +5,7 @@ import numpy as np import pytest +from numpy.testing import assert_allclose from pytest import approx from pymatgen.core.sites import PeriodicSite @@ -95,7 +96,7 @@ def test_get_point_group_operations(self): for site in structure: new_frac = fop.operate(site.frac_coords) new_cart = op.operate(site.coords) - assert np.allclose(structure.lattice.get_fractional_coords(new_cart), new_frac) + assert_allclose(structure.lattice.get_fractional_coords(new_cart), new_frac) found = False new_site = PeriodicSite(site.species, new_cart, structure.lattice, coords_are_cartesian=True) for test_site in structure: @@ -110,7 +111,7 @@ def test_get_point_group_operations(self): random_ccoord = structure.lattice.get_cartesian_coords(random_fcoord) new_frac = fop.operate(random_fcoord) new_cart = op.operate(random_ccoord) - assert np.allclose(structure.lattice.get_fractional_coords(new_cart), new_frac) + assert_allclose(structure.lattice.get_fractional_coords(new_cart), new_frac) def test_get_point_group_operations_uniq(self): # https://github.com/materialsproject/pymatgen/pull/2942 @@ -638,7 +639,7 @@ def test_symmetrize_molecule1(self): for i, eq_set in eq_sets.items(): for j in eq_set: _ = np.dot(ops[i][j], coords[i]) - assert np.allclose(np.dot(ops[i][j], coords[i]), coords[j]) + assert_allclose(np.dot(ops[i][j], coords[i]), coords[j]) def test_symmetrize_molecule2(self): np.random.seed(77) diff --git a/pymatgen/symmetry/tests/test_maggroups.py b/pymatgen/symmetry/tests/test_maggroups.py index 6e64fcc1930..9c48258c42e 100644 --- a/pymatgen/symmetry/tests/test_maggroups.py +++ b/pymatgen/symmetry/tests/test_maggroups.py @@ -1,6 +1,7 @@ from __future__ import annotations import numpy as np +from numpy.testing import assert_allclose from pymatgen.core.lattice import Lattice from pymatgen.symmetry.groups import SpaceGroup @@ -163,7 +164,7 @@ def test_equivalence_to_spacegroup(self): pp_msg = np.array(msg.get_orbit(p, 0)[0]) # discarding magnetic moment information pp_sg = pp_sg[np.lexsort(np.transpose(pp_sg)[::-1])] # sorting arrays so we can compare them pp_msg = pp_msg[np.lexsort(np.transpose(pp_msg)[::-1])] - assert np.allclose(pp_sg, pp_msg) + assert_allclose(pp_sg, pp_msg) def test_str(self): msg = MagneticSpaceGroup([4, 11]) diff --git a/pymatgen/symmetry/tests/test_settings.py b/pymatgen/symmetry/tests/test_settings.py index 6ce9d294d76..1b2d44cbc95 100644 --- a/pymatgen/symmetry/tests/test_settings.py +++ b/pymatgen/symmetry/tests/test_settings.py @@ -2,7 +2,7 @@ import unittest -import numpy as np +from numpy.testing import assert_allclose from pymatgen.symmetry.settings import JonesFaithfulTransformation, Lattice, SymmOp @@ -34,8 +34,8 @@ def test_init(self): for test_string, test_Pp in zip(self.test_strings, self.test_Pps): jft = JonesFaithfulTransformation.from_transformation_string(test_string) jft2 = JonesFaithfulTransformation(test_Pp[0], test_Pp[1]) - assert np.allclose(jft.P, jft2.P) - assert np.allclose(jft.p, jft2.p) + assert_allclose(jft.P, jft2.P) + assert_allclose(jft.p, jft2.p) assert test_string == jft.transformation_string assert test_string == jft2.transformation_string @@ -57,7 +57,7 @@ def test_transform_lattice(self): for ref_lattice, (P, p) in zip(all_ref_lattices, self.test_Pps): jft = JonesFaithfulTransformation(P, p) - assert np.allclose(jft.transform_lattice(lattice).matrix, ref_lattice) + assert_allclose(jft.transform_lattice(lattice).matrix, ref_lattice) def test_transform_coords(self): coords = [[0, 0, 0], [0.5, 0.5, 0.5]] @@ -73,7 +73,7 @@ def test_transform_coords(self): jft = JonesFaithfulTransformation(P, p) transformed_coords = jft.transform_coords(coords) for coord, ref_coord in zip(transformed_coords, ref_coords): - assert np.allclose(coord, ref_coord) + assert_allclose(coord, ref_coord) def test_transform_symmops(self): # reference data for this test taken from GENPOS diff --git a/pymatgen/transformations/tests/test_advanced_transformations.py b/pymatgen/transformations/tests/test_advanced_transformations.py index 0acbafbb172..b5523c1d8f3 100644 --- a/pymatgen/transformations/tests/test_advanced_transformations.py +++ b/pymatgen/transformations/tests/test_advanced_transformations.py @@ -9,7 +9,7 @@ import numpy as np import pytest from monty.serialization import loadfn -from numpy.testing import assert_array_equal +from numpy.testing import assert_allclose, assert_array_equal from pytest import approx from pymatgen.analysis.energy_models import IsingModel @@ -784,9 +784,9 @@ def test_apply_transformation(self): s_trans = mcrt.apply_transformation(struct) assert not np.allclose(struct.cart_coords, s_trans.cart_coords, atol=0.01) - assert np.allclose(struct.cart_coords, s_trans.cart_coords, atol=1) + assert_allclose(struct.cart_coords, s_trans.cart_coords, atol=1) # test using same seed gives same coords mcrt = MonteCarloRattleTransformation(0.01, 2, seed=1) s_trans2 = mcrt.apply_transformation(struct) - assert np.allclose(s_trans.cart_coords, s_trans2.cart_coords) + assert_allclose(s_trans.cart_coords, s_trans2.cart_coords) diff --git a/pymatgen/transformations/tests/test_site_transformations.py b/pymatgen/transformations/tests/test_site_transformations.py index 7584583e336..c674b4946cb 100644 --- a/pymatgen/transformations/tests/test_site_transformations.py +++ b/pymatgen/transformations/tests/test_site_transformations.py @@ -5,6 +5,7 @@ import numpy as np import pytest +from numpy.testing import assert_allclose from pymatgen.core.lattice import Lattice from pymatgen.core.structure import Molecule, Structure @@ -48,18 +49,18 @@ def setUp(self): def test_apply_transformation(self): trafo = TranslateSitesTransformation([0, 1], [0.1, 0.2, 0.3]) s = trafo.apply_transformation(self.struct) - assert np.allclose(s[0].frac_coords, [0.1, 0.2, 0.3]) - assert np.allclose(s[1].frac_coords, [0.475, 0.575, 0.675]) + assert_allclose(s[0].frac_coords, [0.1, 0.2, 0.3]) + assert_allclose(s[1].frac_coords, [0.475, 0.575, 0.675]) inv_t = trafo.inverse s = inv_t.apply_transformation(s) assert s[0].distance_and_image_from_frac_coords([0, 0, 0])[0] == 0 - assert np.allclose(s[1].frac_coords, [0.375, 0.375, 0.375]) + assert_allclose(s[1].frac_coords, [0.375, 0.375, 0.375]) def test_apply_transformation_site_by_site(self): trafo = TranslateSitesTransformation([0, 1], [[0.1, 0.2, 0.3], [-0.075, -0.075, -0.075]]) s = trafo.apply_transformation(self.struct) - assert np.allclose(s[0].frac_coords, [0.1, 0.2, 0.3]) - assert np.allclose(s[1].frac_coords, [0.3, 0.3, 0.3]) + assert_allclose(s[0].frac_coords, [0.1, 0.2, 0.3]) + assert_allclose(s[1].frac_coords, [0.3, 0.3, 0.3]) inv_t = trafo.inverse s = inv_t.apply_transformation(s) assert s[0].distance_and_image_from_frac_coords([0, 0, 0])[0] == 0 @@ -72,9 +73,9 @@ def test_to_from_dict(self): t2 = TranslateSitesTransformation.from_dict(d2) s1 = t1.apply_transformation(self.struct) s2 = t2.apply_transformation(self.struct) - assert np.allclose(s1[0].frac_coords, [0.1, 0.2, 0.3]) - assert np.allclose(s2[0].frac_coords, [0.1, 0.2, 0.3]) - assert np.allclose(s2[1].frac_coords, [0.3, 0.3, 0.3]) + assert_allclose(s1[0].frac_coords, [0.1, 0.2, 0.3]) + assert_allclose(s2[0].frac_coords, [0.1, 0.2, 0.3]) + assert_allclose(s2[1].frac_coords, [0.3, 0.3, 0.3]) str(t1) str(t2) diff --git a/pymatgen/util/tests/test_coord.py b/pymatgen/util/tests/test_coord.py index dab6b84d9f4..9d7186d0b96 100644 --- a/pymatgen/util/tests/test_coord.py +++ b/pymatgen/util/tests/test_coord.py @@ -4,7 +4,7 @@ import numpy as np import pytest -from numpy.testing import assert_array_equal +from numpy.testing import assert_allclose, assert_array_equal from pytest import approx from pymatgen.core.lattice import Lattice @@ -45,7 +45,7 @@ def test_coord_list_mapping(self): a = np.array([c1, c2]) b = np.array([c3, c2, c1]) inds = coord.coord_list_mapping(a, b) - assert np.allclose(a, b[inds]) + assert_allclose(a, b[inds]) with pytest.raises(ValueError, match="not a subset of superset"): coord.coord_list_mapping([c1, c2], [c2, c3]) with pytest.raises(ValueError, match="Something wrong with the inputs, likely duplicates in superset"): @@ -63,7 +63,7 @@ def test_coord_list_mapping_pbc(self): inds = coord.coord_list_mapping_pbc(a, b) diff = a - b[inds] diff -= np.round(diff) - assert np.allclose(diff, 0) + assert_allclose(diff, 0) with pytest.raises(ValueError, match="not a subset of superset"): coord.coord_list_mapping_pbc([c1, c2], [c2, c3]) with pytest.raises(ValueError, match="Something wrong with the inputs, likely duplicates in superset"): @@ -177,18 +177,18 @@ def test_barycentric(self): output1 = coord.barycentric_coords(pts1, simplex1) # do back conversion to cartesian o_dot_s = np.sum(output1[:, :, None] * simplex1[None, :, :], axis=1) - assert np.allclose(pts1, o_dot_s) + assert_allclose(pts1, o_dot_s) # do 3d tests simplex2 = np.array([[0, 0, 1], [0, 1, 0], [1, 0, 0], [0, 0, 0]]) pts2 = np.array([[0, 0, 1], [0, 0.5, 0.5], [1.0 / 3, 1.0 / 3, 1.0 / 3]]) output2 = coord.barycentric_coords(pts2, simplex2) - assert np.allclose(output2[1], [0.5, 0.5, 0, 0]) + assert_allclose(output2[1], [0.5, 0.5, 0, 0]) # do back conversion to cartesian o_dot_s = np.sum(output2[:, :, None] * simplex2[None, :, :], axis=1) - assert np.allclose(pts2, o_dot_s) + assert_allclose(pts2, o_dot_s) # test single point - assert np.allclose(output2[2], coord.barycentric_coords(pts2[2], simplex2)) + assert_allclose(output2[2], coord.barycentric_coords(pts2[2], simplex2)) def test_pbc_shortest_vectors(self): frac_coords = np.array(