Skip to content

Commit e766122

Browse files
authored
Migrate from warnings.catch_warnings(record=True) to pytest.warns() (#3125)
* add args missing from doc strings * refactor warnings.catch_warnings(record=True) to pytest.warns() * np.math deprecated in numpy 1.25, was just an alias to std lib math * finish warnings.catch_warnings(record=True) to pytest.warns() migration * rename single-letter vars
1 parent 8999bb3 commit e766122

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

50 files changed

+434
-456
lines changed

pymatgen/alchemy/tests/test_materials.py

Lines changed: 6 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,6 @@
22

33
import json
44
import os
5-
import warnings
65

76
import pytest
87

@@ -106,15 +105,15 @@ def test_as_dict(self):
106105

107106
def test_snl(self):
108107
self.trans.set_parameter("author", "will")
109-
with warnings.catch_warnings(record=True) as w:
110-
warnings.simplefilter("always")
108+
with pytest.warns(UserWarning) as warns:
111109
snl = self.trans.to_snl([("will", "[email protected]")])
112-
assert len(w) == 1, "Warning not raised on type conversion with other_parameters"
110+
assert len(warns) == 1, "Warning not raised on type conversion with other_parameters"
111+
113112
ts = TransformedStructure.from_snl(snl)
114113
assert ts.history[-1]["@class"] == "SubstitutionTransformation"
115114

116-
h = ("testname", "testURL", {"test": "testing"})
117-
snl = StructureNL(ts.final_structure, [("will", "[email protected]")], history=[h])
115+
hist = ("testname", "testURL", {"test": "testing"})
116+
snl = StructureNL(ts.final_structure, [("will", "[email protected]")], history=[hist])
118117
snl = TransformedStructure.from_snl(snl).to_snl([("notwill", "[email protected]")])
119-
assert snl.history == [h]
118+
assert snl.history == [hist]
120119
assert snl.authors == [("notwill", "[email protected]")]

pymatgen/analysis/chemenv/utils/scripts_utils.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -239,8 +239,8 @@ def compute_environments(chemenv_configuration):
239239
if source_type == "cif":
240240
if not found:
241241
input_source = input("Enter path to cif file : ")
242-
cp = CifParser(input_source)
243-
structure = cp.get_structures()[0]
242+
parser = CifParser(input_source)
243+
structure = parser.get_structures()[0]
244244
elif source_type == "mp":
245245
if not found:
246246
input_source = input('Enter materials project id (e.g. "mp-1902") : ')

pymatgen/analysis/elasticity/elastic.py

Lines changed: 8 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@
77
from __future__ import annotations
88

99
import itertools
10+
import math
1011
import warnings
1112
from typing import TYPE_CHECKING
1213

@@ -443,7 +444,7 @@ def get_structure_property_dict(
443444
def from_pseudoinverse(cls, strains, stresses):
444445
"""
445446
Class method to fit an elastic tensor from stress/strain
446-
data. Method uses Moore-Penrose pseudoinverse to invert
447+
data. Method uses Moore-Penrose pseudo-inverse to invert
447448
the s = C*e equation with elastic tensor, stress, and
448449
strain in voigt notation.
449450
@@ -453,11 +454,11 @@ def from_pseudoinverse(cls, strains, stresses):
453454
"""
454455
# convert the stress/strain to Nx6 arrays of voigt-notation
455456
warnings.warn(
456-
"Pseudoinverse fitting of Strain/Stress lists may yield "
457+
"Pseudo-inverse fitting of Strain/Stress lists may yield "
457458
"questionable results from vasp data, use with caution."
458459
)
459460
stresses = np.array([Stress(stress).voigt for stress in stresses])
460-
with warnings.catch_warnings(record=True):
461+
with warnings.catch_warnings():
461462
strains = np.array([Strain(strain).voigt for strain in strains])
462463

463464
voigt_fit = np.transpose(np.dot(np.linalg.pinv(strains), stresses))
@@ -837,7 +838,7 @@ def diff_fit(strains, stresses, eq_stress=None, order=2, tol: float = 1e-10):
837838
3. Find first, second .. nth derivatives of each stress
838839
with respect to scalar variable corresponding to
839840
the smallest perturbation in the strain.
840-
4. Use the pseudoinverse of a matrix-vector expression
841+
4. Use the pseudo-inverse of a matrix-vector expression
841842
corresponding to the parameterized stress-strain
842843
relationship and multiply that matrix by the respective
843844
calculated first or second derivatives from the
@@ -969,13 +970,13 @@ def get_strain_state_dict(strains, stresses, eq_stress=None, tol: float = 1e-10,
969970

970971
def generate_pseudo(strain_states, order=3):
971972
"""
972-
Generates the pseudoinverse for a given set of strains.
973+
Generates the pseudo-inverse for a given set of strains.
973974
974975
Args:
975976
strain_states (6xN array like): a list of voigt-notation
976977
"strain-states", i. e. perturbed indices of the strain
977978
as a function of the smallest strain e. g. (0, 1, 0, 0, 1, 0)
978-
order (int): order of pseudoinverse to calculate
979+
order (int): order of pseudo-inverse to calculate
979980
980981
Returns:
981982
mis: pseudo inverses for each order tensor, these can
@@ -996,7 +997,7 @@ def generate_pseudo(strain_states, order=3):
996997
exps = carr.copy()
997998
for _ in range(degree - 1):
998999
exps = np.dot(exps, strain_v)
999-
exps /= np.math.factorial(degree - 1)
1000+
exps /= math.factorial(degree - 1)
10001001
sarr[n] = [sp.diff(exp, s, degree - 1) for exp in exps]
10011002
svec = sarr.ravel()
10021003
present_syms = set.union(*(exp.atoms(sp.Symbol) for exp in svec))

pymatgen/analysis/elasticity/tests/test_elastic.py

Lines changed: 22 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -169,9 +169,11 @@ def test_new(self):
169169
self.assert_all_close(self.elastic_tensor_1, ElasticTensor(self.ft))
170170
non_symm = self.ft
171171
non_symm[0, 1, 2, 2] += 1.0
172-
with warnings.catch_warnings(record=True) as w:
172+
with pytest.warns(
173+
UserWarning, match="Input elastic tensor does not satisfy standard Voigt symmetries"
174+
) as warns:
173175
ElasticTensor(non_symm)
174-
assert len(w) == 1
176+
assert len(warns) == 1
175177
bad_tensor1 = np.zeros((3, 3, 3))
176178
bad_tensor2 = np.zeros((3, 3, 3, 2))
177179
with pytest.raises(ValueError, match="ElasticTensor input must be rank 4"):
@@ -185,7 +187,11 @@ def test_new(self):
185187
def test_from_pseudoinverse(self):
186188
strain_list = [Strain.from_deformation(def_matrix) for def_matrix in self.def_stress_dict["deformations"]]
187189
stress_list = list(self.def_stress_dict["stresses"])
188-
with warnings.catch_warnings(record=True):
190+
with pytest.warns(
191+
UserWarning,
192+
match="Pseudo-inverse fitting of Strain/Stress lists may yield questionable results from "
193+
"vasp data, use with caution",
194+
):
189195
et_fl = -0.1 * ElasticTensor.from_pseudoinverse(strain_list, stress_list).voigt
190196
self.assert_all_close(
191197
et_fl.round(2),
@@ -202,8 +208,9 @@ def test_from_pseudoinverse(self):
202208
def test_from_independent_strains(self):
203209
strains = self.toec_dict["strains"]
204210
stresses = self.toec_dict["stresses"]
205-
with warnings.catch_warnings(record=True):
211+
with pytest.warns(UserWarning, match="No eq state found, returning zero voigt stress") as warns:
206212
et = ElasticTensor.from_independent_strains(strains, stresses)
213+
assert len(warns) == 2
207214
self.assert_all_close(et.voigt, self.toec_dict["C2_raw"], decimal=-1)
208215

209216
def test_energy_density(self):
@@ -429,9 +436,8 @@ def test_get_strain_state_dict(self):
429436
def test_find_eq_stress(self):
430437
test_strains = deepcopy(self.strains)
431438
test_stresses = deepcopy(self.pk_stresses)
432-
with warnings.catch_warnings(record=True):
433-
no_eq = find_eq_stress(test_strains, test_stresses)
434-
self.assert_all_close(no_eq, np.zeros((3, 3)))
439+
no_eq = find_eq_stress(test_strains, test_stresses)
440+
self.assert_all_close(no_eq, np.zeros((3, 3)))
435441
test_strains[3] = Strain.from_voigt(np.zeros(6))
436442
eq_stress = find_eq_stress(test_strains, test_stresses)
437443
self.assert_all_close(test_stresses[3], eq_stress)
@@ -445,15 +451,7 @@ def test_get_diff_coeff(self):
445451
self.assert_all_close(forward_13, [-11 / 6, 3, -3 / 2, 1 / 3])
446452
self.assert_all_close(
447453
backward_26,
448-
[
449-
137 / 180,
450-
-27 / 5,
451-
33 / 2,
452-
-254 / 9,
453-
117 / 4,
454-
-87 / 5,
455-
203 / 45,
456-
],
454+
[137 / 180, -27 / 5, 33 / 2, -254 / 9, 117 / 4, -87 / 5, 203 / 45],
457455
)
458456
self.assert_all_close(central_29, central_diff_weights(9, 2))
459457

@@ -468,12 +466,11 @@ def test_fit(self):
468466
reduced = [(e, pk) for e, pk in zip(self.strains, self.pk_stresses) if not (abs(abs(e) - 0.05) < 1e-10).any()]
469467
# Get reduced dataset
470468
r_strains, r_pk_stresses = zip(*reduced)
471-
with warnings.catch_warnings(record=True):
472-
c2 = diff_fit(r_strains, r_pk_stresses, self.data_dict["eq_stress"], order=2)
473-
c2, c3, c4 = diff_fit(r_strains, r_pk_stresses, self.data_dict["eq_stress"], order=4)
474-
c2, c3 = diff_fit(self.strains, self.pk_stresses, self.data_dict["eq_stress"], order=3)
475-
c2_red, c3_red = diff_fit(r_strains, r_pk_stresses, self.data_dict["eq_stress"], order=3)
476-
self.assert_all_close(c2.voigt, self.data_dict["C2_raw"])
477-
self.assert_all_close(c3.voigt, self.data_dict["C3_raw"], decimal=5)
478-
self.assert_all_close(c2, c2_red, decimal=0)
479-
self.assert_all_close(c3, c3_red, decimal=-1)
469+
c2 = diff_fit(r_strains, r_pk_stresses, self.data_dict["eq_stress"], order=2)
470+
c2, c3, c4 = diff_fit(r_strains, r_pk_stresses, self.data_dict["eq_stress"], order=4)
471+
c2, c3 = diff_fit(self.strains, self.pk_stresses, self.data_dict["eq_stress"], order=3)
472+
c2_red, c3_red = diff_fit(r_strains, r_pk_stresses, self.data_dict["eq_stress"], order=3)
473+
self.assert_all_close(c2.voigt, self.data_dict["C2_raw"])
474+
self.assert_all_close(c3.voigt, self.data_dict["C3_raw"], decimal=5)
475+
self.assert_all_close(c2, c2_red, decimal=0)
476+
self.assert_all_close(c3, c3_red, decimal=-1)

pymatgen/analysis/elasticity/tests/test_strain.py

Lines changed: 1 addition & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,5 @@
11
from __future__ import annotations
22

3-
import warnings
4-
53
import numpy as np
64
import pytest
75

@@ -91,9 +89,7 @@ def setUp(self):
9189

9290
self.non_ind_str = Strain.from_deformation([[1, 0.02, 0.02], [0, 1, 0], [0, 0, 1]])
9391

94-
with warnings.catch_warnings(record=True):
95-
warnings.simplefilter("always")
96-
self.no_dfm = Strain([[0, 0.01, 0], [0.01, 0.0002, 0], [0, 0, 0]])
92+
self.no_dfm = Strain([[0, 0.01, 0], [0.01, 0.0002, 0], [0, 0, 0]])
9793

9894
def test_new(self):
9995
test_strain = Strain([[0, 0.01, 0], [0.01, 0.0002, 0], [0, 0, 0]])

pymatgen/analysis/elasticity/tests/test_stress.py

Lines changed: 7 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
from __future__ import annotations
22

33
import numpy as np
4+
import pytest
45
from pytest import approx
56

67
from pymatgen.analysis.elasticity.strain import Deformation
@@ -45,6 +46,9 @@ def test_properties(self):
4546
)
4647
# voigt
4748
assert list(self.symm_stress.voigt) == [0.51, 5.14, 5.33, 5.07, 2.42, 2.29]
48-
# with warnings.catch_warnings(record=True) as w:
49-
# self.non_symm.voigt
50-
# assert len(w) == 1
49+
50+
with pytest.warns(
51+
UserWarning, match="Tensor is not symmetric, information may be lost in voigt conversion"
52+
) as warns:
53+
_ = self.non_symm.voigt
54+
assert len(warns) == 1

pymatgen/analysis/molecule_matcher.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -867,7 +867,7 @@ def match(self, mol: Molecule, ignore_warning: bool = False) -> tuple[np.ndarray
867867
_, count = np.unique(mol.atomic_numbers, return_counts=True)
868868
total_permutations = 1
869869
for c in count:
870-
total_permutations *= np.math.factorial(c) # type: ignore
870+
total_permutations *= math.factorial(c)
871871

872872
if not ignore_warning and total_permutations > 1_000_000:
873873
raise ValueError(

pymatgen/analysis/solar/slme.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -39,8 +39,8 @@
3939

4040
def get_dir_indir_gap(run=""):
4141
"""Get direct and indirect bandgaps for a vasprun.xml."""
42-
v = Vasprun(run)
43-
bandstructure = v.get_band_structure()
42+
vasp_run = Vasprun(run)
43+
bandstructure = vasp_run.get_band_structure()
4444
dir_gap = bandstructure.get_direct_band_gap()
4545
indir_gap = bandstructure.get_band_gap()["energy"]
4646
return dir_gap, indir_gap

pymatgen/analysis/tests/test_fragmenter.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -72,7 +72,7 @@ def test_babel_pc_frag1(self):
7272
def test_babel_pc_old_defaults(self):
7373
pytest.importorskip("openbabel")
7474
fragmenter = Fragmenter(molecule=self.pc, open_rings=True)
75-
assert fragmenter.open_rings is True
75+
assert fragmenter.open_rings
7676
assert fragmenter.opt_steps == 10000
7777
default_mol_graph = MoleculeGraph.with_local_env_strategy(self.pc, OpenBabelNN())
7878
assert fragmenter.mol_graph == default_mol_graph

pymatgen/analysis/tests/test_interface_reactions.py

Lines changed: 6 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,6 @@
11
from __future__ import annotations
22

33
import unittest
4-
import warnings
54

65
import numpy as np
76
import pytest
@@ -163,15 +162,13 @@ def setUp(self):
163162

164163
def test_get_entry_energy(self):
165164
comp = Composition("MnO3")
166-
with warnings.catch_warnings(record=True) as record:
167-
warnings.simplefilter("always")
165+
with pytest.warns(
166+
UserWarning,
167+
match="The reactant MnO3 has no matching entry with negative formation energy, instead "
168+
"convex hull energy for this composition will be used for reaction energy calculation.",
169+
) as warns:
168170
energy = InterfacialReactivity._get_entry_energy(self.pd, comp)
169-
assert len(record) == 1
170-
assert (
171-
"The reactant MnO3 has no matching entry with negative formation energy, "
172-
"instead convex hull energy for this composition will be used"
173-
" for reaction energy calculation." in str(record[-1].message)
174-
)
171+
assert len(warns) == 1
175172
test1 = np.isclose(energy, -30, atol=1e-03)
176173
assert test1, f"_get_entry_energy: energy for {comp.reduced_formula} is wrong!"
177174
# Test normal functionality

0 commit comments

Comments
 (0)