-
Notifications
You must be signed in to change notification settings - Fork 838
/
test_structure.py
2140 lines (1877 loc) · 87.5 KB
/
test_structure.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
from __future__ import annotations
import json
import os
import random
from pathlib import Path
from shutil import which
from unittest import skipIf
import numpy as np
import pytest
from monty.json import MontyDecoder, MontyEncoder
from numpy.testing import assert_allclose, assert_array_equal
from pytest import approx
from pymatgen.core.composition import Composition
from pymatgen.core.lattice import Lattice
from pymatgen.core.operations import SymmOp
from pymatgen.core.periodic_table import Element, Species
from pymatgen.core.structure import (
IMolecule,
IStructure,
Molecule,
Neighbor,
PeriodicNeighbor,
Structure,
StructureError,
)
from pymatgen.electronic_structure.core import Magmom
from pymatgen.io.ase import AseAtomsAdaptor
from pymatgen.util.testing import TEST_FILES_DIR, PymatgenTest
try:
from ase.atoms import Atoms
from ase.calculators.calculator import Calculator
from ase.calculators.emt import EMT
except ImportError:
ase = None
enum_cmd = which("enum.x") or which("multienum.x")
mcsqs_cmd = which("mcsqs")
class TestNeighbor(PymatgenTest):
def test_msonable(self):
struct = PymatgenTest.get_structure("Li2O")
nn = struct.get_neighbors(struct[0], r=3)
assert isinstance(nn[0], PeriodicNeighbor)
str_ = json.dumps(nn, cls=MontyEncoder)
nn = json.loads(str_, cls=MontyDecoder)
assert isinstance(nn[0], PeriodicNeighbor)
def test_neighbor_labels(self):
comp = Composition("C")
for label in (None, "", "str label", ("tuple", "label")):
neighbor = Neighbor(comp, (0, 0, 0), label=label)
assert neighbor.label == label if label is not None else "C"
p_neighbor = PeriodicNeighbor(comp, (0, 0, 0), (10, 10, 10), label=label)
assert p_neighbor.label == label if label is not None else "C"
class TestIStructure(PymatgenTest):
def setUp(self):
coords = [[0, 0, 0], [0.75, 0.5, 0.75]]
self.lattice = Lattice(
[[3.8401979337, 0, 0], [1.9200989668, 3.3257101909, 0], [0, -2.2171384943, 3.1355090603]]
)
self.struct = IStructure(self.lattice, ["Si"] * 2, coords)
assert len(self.struct) == 2, "Wrong number of sites in structure!"
assert self.struct.is_ordered
assert self.struct.ntypesp == 1
coords = [[0, 0, 0], [0.0, 0, 0.0000001]]
with pytest.raises(StructureError, match="Structure contains sites that are less than 0.01 Angstrom apart"):
IStructure(self.lattice, ["Si"] * 2, coords, validate_proximity=True)
self.propertied_structure = IStructure(
self.lattice, ["Si"] * 2, coords, site_properties={"magmom": [5, -5]}, properties={"test_property": "test"}
)
self.labeled_structure = IStructure(self.lattice, ["Si"] * 2, coords, labels=["Si1", "Si2"])
self.lattice_pbc = Lattice(
[[3.8401979337, 0, 0], [1.9200989668, 3.3257101909, 0], [0, -2.2171384943, 3.1355090603]],
pbc=(True, True, False),
)
@skipIf(not (mcsqs_cmd and enum_cmd), "enumlib or mcsqs executable not present")
def test_get_orderings(self):
ordered = Structure.from_spacegroup("Im-3m", Lattice.cubic(3), ["Fe"], [[0, 0, 0]])
assert ordered.get_orderings()[0] == ordered
disordered = Structure.from_spacegroup("Im-3m", Lattice.cubic(3), [Composition("Fe0.5Mn0.5")], [[0, 0, 0]])
orderings = disordered.get_orderings()
assert len(orderings) == 1
super_cell = disordered * 2
orderings = super_cell.get_orderings()
assert len(orderings) == 59
sqs = disordered.get_orderings(mode="sqs", scaling=[2, 2, 2])
assert sqs[0].formula == "Mn8 Fe8"
sqs = super_cell.get_orderings(mode="sqs")
assert sqs[0].formula == "Mn8 Fe8"
def test_as_dataframe(self):
df = self.propertied_structure.as_dataframe()
assert df.attrs["Reduced Formula"] == "Si"
assert df.shape == (2, 8)
def test_equal(self):
struct = self.struct
assert struct == struct
assert struct == struct.copy()
assert struct != 2 * struct
assert struct != "a" * len(struct) # GH-2584
assert struct is not None
assert struct != 42 # GH-2587
assert struct == Structure.from_dict(struct.as_dict())
struct_2 = Structure.from_sites(struct)
assert struct, struct_2
struct_2.apply_strain(0.5)
assert struct != struct_2
def test_matches(self):
supercell = self.struct * 2
assert supercell.matches(self.struct)
def test_bad_structure(self):
coords = []
coords.append([0, 0, 0])
coords.append([0.75, 0.5, 0.75])
coords.append([0.75, 0.5, 0.75])
with pytest.raises(StructureError, match="Structure contains sites that are less than 0.01 Angstrom apart"):
IStructure(self.lattice, ["Si"] * 3, coords, validate_proximity=True)
# these shouldn't raise an error
IStructure(self.lattice, ["Si"] * 2, coords[:2], True)
IStructure(self.lattice, ["Si"], coords[:1], True)
def test_volume(self):
assert self.struct.volume == approx(40.04, abs=1e-2), "Volume wrong!"
def test_density(self):
assert self.struct.density == approx(2.33, abs=1e-2), "Incorrect density"
def test_formula(self):
assert self.struct.formula == "Si2"
assert self.labeled_structure.formula == "Si2"
assert self.propertied_structure.formula == "Si2"
def test_elements(self):
assert self.struct.elements == [Element("Si")]
assert self.propertied_structure.elements == [Element("Si")]
def test_specie_init(self):
coords = []
coords.append([0, 0, 0])
coords.append([0.75, 0.5, 0.75])
struct = IStructure(self.lattice, [{Species("O", -2): 1.0}, {Species("Mg", 2): 0.8}], coords)
assert struct.composition.formula == "Mg0.8 O1"
def test_get_sorted_structure(self):
coords = []
coords.append([0, 0, 0])
coords.append([0.75, 0.5, 0.75])
struct = IStructure(self.lattice, ["O", "Li"], coords, site_properties={"charge": [-2, 1]})
sorted_s = struct.get_sorted_structure()
assert sorted_s[0].species == Composition("Li")
assert sorted_s[1].species == Composition("O")
assert sorted_s[0].charge == 1
assert sorted_s[1].charge == -2
struct = IStructure(
self.lattice,
["Se", "C", "Se", "C"],
[[0] * 3, [0.5] * 3, [0.25] * 3, [0.75] * 3],
)
assert [site.specie.symbol for site in struct.get_sorted_structure()] == ["C", "C", "Se", "Se"]
def test_get_space_group_data(self):
assert self.struct.get_space_group_info() == ("Fd-3m", 227)
def test_fractional_occupations(self):
coords = []
coords.append([0, 0, 0])
coords.append([0.75, 0.5, 0.75])
struct = IStructure(self.lattice, [{"O": 1.0}, {"Mg": 0.8}], coords)
assert struct.composition.formula == "Mg0.8 O1"
assert not struct.is_ordered
def test_labeled_structure(self):
assert self.labeled_structure.labels == ["Si1", "Si2"]
assert self.struct.labels == ["Si", "Si"]
def test_get_distance(self):
assert self.struct.get_distance(0, 1) == approx(2.35, abs=1e-2), "Distance calculated wrongly!"
pt = [0.9, 0.9, 0.8]
assert self.struct[0].distance_from_point(pt) == approx(1.50332963784, abs=1e-2), "Distance calculated wrongly!"
def test_as_dict(self):
si = Species("Si", 4)
mn = Element("Mn")
coords = []
coords.append([0, 0, 0])
coords.append([0.75, 0.5, 0.75])
struct = IStructure(self.lattice, [{si: 0.5, mn: 0.5}, {si: 0.5}], coords)
assert "lattice" in struct.as_dict()
assert "sites" in struct.as_dict()
d = self.propertied_structure.as_dict()
assert d["sites"][0]["properties"]["magmom"] == 5
coords = []
coords.append([0, 0, 0])
coords.append([0.75, 0.5, 0.75])
struct = IStructure(
self.lattice,
[
{Species("O", -2, spin=3): 1.0},
{Species("Mg", 2, spin=2): 0.8},
],
coords,
site_properties={"magmom": [5, -5]},
properties={"general_property": "test"},
)
d = struct.as_dict()
assert d["sites"][0]["properties"]["magmom"] == 5
assert d["sites"][0]["species"][0]["spin"] == 3
assert d["properties"]["general_property"] == "test"
d = struct.as_dict(0)
assert "volume" not in d["lattice"]
assert "xyz" not in d["sites"][0]
def test_from_dict(self):
d = self.propertied_structure.as_dict()
struct = IStructure.from_dict(d)
assert struct[0].magmom == 5
d = self.propertied_structure.as_dict(0)
s2 = IStructure.from_dict(d)
assert struct == s2
d = {
"lattice": {
"a": 3.8401979337,
"volume": 40.044794644251596,
"c": 3.8401979337177736,
"b": 3.840198994344244,
"matrix": [
[3.8401979337, 0.0, 0.0],
[1.9200989668, 3.3257101909, 0.0],
[0.0, -2.2171384943, 3.1355090603],
],
"alpha": 119.9999908639842,
"beta": 90.0,
"gamma": 60.000009137322195,
},
"sites": [
{
"properties": {"magmom": 5},
"abc": [0.0, 0.0, 0.0],
"occu": 1.0,
"species": [
{
"occu": 1.0,
"oxidation_state": -2,
"spin": 3,
"element": "O",
}
],
"label": "O2-",
"xyz": [0.0, 0.0, 0.0],
},
{
"properties": {"magmom": -5},
"abc": [0.75, 0.5, 0.75],
"occu": 0.8,
"species": [
{
"occu": 0.8,
"oxidation_state": 2,
"spin": 2,
"element": "Mg",
}
],
"label": "Mg2+:0.800",
"xyz": [3.8401979336749994, 1.2247250003039056e-06, 2.351631795225],
},
],
"properties": {"test_property": "test"},
}
struct = IStructure.from_dict(d)
assert struct[0].magmom == 5
assert struct[0].specie.spin == 3
assert struct.properties["test_property"] == "test"
assert isinstance(struct, IStructure)
def test_site_properties(self):
site_props = self.propertied_structure.site_properties
assert site_props["magmom"] == [5, -5]
assert self.propertied_structure[0].magmom == 5
assert self.propertied_structure[1].magmom == -5
def test_properties_dict(self):
assert self.propertied_structure.properties == {"test_property": "test"}
def test_copy(self):
new_struct = self.propertied_structure.copy(
site_properties={"charge": [2, 3]}, properties={"another_prop": "test"}
)
assert new_struct[0].magmom == 5
assert new_struct[1].magmom == -5
assert new_struct[0].charge == 2
assert new_struct[1].charge == 3
assert new_struct.properties["another_prop"] == "test"
assert new_struct.properties["test_property"] == "test"
coords = []
coords.append([0, 0, 0])
coords.append([0.0, 0, 0.0000001])
struct = IStructure(
self.lattice, ["O", "Si"], coords, site_properties={"magmom": [5, -5]}, properties={"test_property": "test"}
)
new_struct = struct.copy(site_properties={"charge": [2, 3]}, sanitize=True, properties={"another_prop": "test"})
assert new_struct[0].magmom == -5
assert new_struct[1].magmom == 5
assert new_struct[0].charge == 3
assert new_struct[1].charge == 2
assert new_struct.volume == approx(struct.volume)
assert new_struct.properties["another_prop"] == "test"
assert new_struct.properties["test_property"] == "test"
def test_interpolate(self):
coords = []
coords.append([0, 0, 0])
coords.append([0.75, 0.5, 0.75])
struct = IStructure(self.lattice, ["Si"] * 2, coords)
coords2 = []
coords2.append([0, 0, 0])
coords2.append([0.5, 0.5, 0.5])
struct2 = IStructure(self.struct.lattice, ["Si"] * 2, coords2)
interpolated_structs = struct.interpolate(struct2, 10)
for inter_struct in interpolated_structs:
assert inter_struct is not None, "Interpolation Failed!"
assert interpolated_structs[0].lattice == inter_struct.lattice
assert_array_equal(interpolated_structs[1][1].frac_coords, [0.725, 0.5, 0.725])
# test ximages
interpolated_structs = struct.interpolate(struct2, nimages=np.linspace(0.0, 1.0, 3))
for inter_struct in interpolated_structs:
assert inter_struct is not None, "Interpolation Failed!"
assert interpolated_structs[0].lattice == inter_struct.lattice
assert_array_equal(interpolated_structs[1][1].frac_coords, [0.625, 0.5, 0.625])
bad_lattice = [[1, 0, 0], [0, 1, 0], [0, 0, 1]]
struct2 = IStructure(bad_lattice, ["Si"] * 2, coords2)
with pytest.raises(ValueError, match="Structures with different lattices"):
struct.interpolate(struct2)
coords2 = []
coords2.append([0, 0, 0])
coords2.append([0.5, 0.5, 0.5])
struct2 = IStructure(self.struct.lattice, ["Si", "Fe"], coords2)
with pytest.raises(ValueError, match="Different species"):
struct.interpolate(struct2)
# Test autosort feature.
s1 = Structure.from_spacegroup("Fm-3m", Lattice.cubic(3), ["Fe"], [[0, 0, 0]])
s1.pop(0)
s2 = Structure.from_spacegroup("Fm-3m", Lattice.cubic(3), ["Fe"], [[0, 0, 0]])
s2.pop(2)
random.shuffle(s2)
for struct in s1.interpolate(s2, autosort_tol=0.5):
assert_allclose(s1[0].frac_coords, struct[0].frac_coords)
assert_allclose(s1[2].frac_coords, struct[2].frac_coords)
# Make sure autosort has no effect on simpler interpolations,
# and with shuffled sites.
s1 = Structure.from_spacegroup("Fm-3m", Lattice.cubic(3), ["Fe"], [[0, 0, 0]])
s2 = Structure.from_spacegroup("Fm-3m", Lattice.cubic(3), ["Fe"], [[0, 0, 0]])
s2[0] = "Fe", [0.01, 0.01, 0.01]
random.shuffle(s2)
for struct in s1.interpolate(s2, autosort_tol=0.5):
assert_allclose(s1[1].frac_coords, struct[1].frac_coords)
assert_allclose(s1[2].frac_coords, struct[2].frac_coords)
assert_allclose(s1[3].frac_coords, struct[3].frac_coords)
# Test non-hexagonal setting.
lattice = Lattice.rhombohedral(4.0718, 89.459)
species = [{"S": 1.0}, {"Ni": 1.0}]
coordinate = [(0.252100, 0.252100, 0.252100), (0.500000, 0.244900, -0.244900)]
struct = Structure.from_spacegroup("R32:R", lattice, species, coordinate)
assert struct.formula == "Ni3 S2"
# test pbc
coords = [[0.85, 0.85, 0.85]]
coords2 = [[0.25, 0.25, 0.25]]
struct_pbc = IStructure(self.lattice_pbc, ["Si"], coords)
struct2_pbc = IStructure(self.lattice_pbc, ["Si"], coords2)
int_s_pbc = struct_pbc.interpolate(struct2_pbc, nimages=2)
assert_allclose(int_s_pbc[1][0].frac_coords, [1.05, 1.05, 0.55])
def test_interpolate_lattice(self):
coords = []
coords.append([0, 0, 0])
coords.append([0.75, 0.5, 0.75])
struct = IStructure(self.lattice, ["Si"] * 2, coords)
coords2 = []
coords2.append([0, 0, 0])
coords2.append([0.5, 0.5, 0.5])
l2 = Lattice.from_parameters(3, 4, 4, 100, 100, 70)
struct2 = IStructure(l2, ["Si"] * 2, coords2)
int_s = struct.interpolate(struct2, 2, interpolate_lattices=True)
assert_allclose(struct.lattice.abc, int_s[0].lattice.abc)
assert_allclose(struct.lattice.angles, int_s[0].lattice.angles)
assert_allclose(struct2.lattice.abc, int_s[2].lattice.abc)
assert_allclose(struct2.lattice.angles, int_s[2].lattice.angles)
int_angles = [110.3976469, 94.5359731, 64.5165856]
assert_allclose(int_angles, int_s[1].lattice.angles)
# Assert that volume is monotonic
assert struct2.volume >= int_s[1].volume
assert int_s[1].volume >= struct.volume
def test_interpolate_lattice_rotation(self):
l1 = Lattice([[1, 0, 0], [0, 1, 0], [0, 0, 1]])
l2 = Lattice([[-1.01, 0, 0], [0, -1.01, 0], [0, 0, 1]])
coords = [[0, 0, 0], [0.75, 0.5, 0.75]]
struct1 = IStructure(l1, ["Si"] * 2, coords)
struct2 = IStructure(l2, ["Si"] * 2, coords)
int_s = struct1.interpolate(struct2, 2, interpolate_lattices=True)
# Assert that volume is monotonic
assert struct2.volume >= int_s[1].volume
assert int_s[1].volume >= struct1.volume
def test_get_primitive_structure(self):
coords = [[0, 0, 0], [0.5, 0.5, 0], [0, 0.5, 0.5], [0.5, 0, 0.5]]
fcc_ag = IStructure(Lattice.cubic(4.09), ["Ag"] * 4, coords)
assert len(fcc_ag.get_primitive_structure()) == 1
coords = [[0, 0, 0], [0.5, 0.5, 0.5]]
bcc_li = IStructure(Lattice.cubic(4.09), ["Li"] * 2, coords)
bcc_prim = bcc_li.get_primitive_structure()
assert len(bcc_prim) == 1
assert bcc_prim.lattice.alpha == approx(109.47122)
bcc_li = IStructure(Lattice.cubic(4.09), ["Li"] * 2, coords, site_properties={"magmom": [1, -1]})
bcc_prim = bcc_li.get_primitive_structure()
assert len(bcc_prim) == 1
assert bcc_prim.lattice.alpha == approx(109.47122)
bcc_prim = bcc_li.get_primitive_structure(use_site_props=True)
assert len(bcc_prim) == 2
assert bcc_prim.lattice.alpha == approx(90)
coords = [[0] * 3, [0.5] * 3, [0.25] * 3, [0.26] * 3]
struct = IStructure(Lattice.cubic(4.09), ["Ag"] * 4, coords)
assert len(struct.get_primitive_structure()) == 4
def test_primitive_cell_site_merging(self):
latt = Lattice.cubic(10)
coords = [[0, 0, 0], [0, 0, 0.5], [0, 0, 0.26], [0, 0, 0.74]]
sp = ["Ag", "Ag", "Be", "Be"]
struct = Structure(latt, sp, coords)
dm = struct.get_primitive_structure().distance_matrix
assert_allclose(dm, [[0, 2.5], [2.5, 0]])
def test_primitive_on_large_supercell(self):
coords = [[0, 0, 0], [0.5, 0.5, 0], [0, 0.5, 0.5], [0.5, 0, 0.5]]
fcc_ag = Structure(Lattice.cubic(4.09), ["Ag"] * 4, coords)
fcc_ag.make_supercell([2, 2, 2])
fcc_ag_prim = fcc_ag.get_primitive_structure()
assert len(fcc_ag_prim) == 1
assert fcc_ag_prim.volume == approx(17.10448225)
def test_primitive_positions(self):
coords = [[0, 0, 0], [0.3, 0.35, 0.45]]
struct = Structure(Lattice.from_parameters(1, 2, 3, 50, 66, 88), ["Ag"] * 2, coords)
c = [[2, 0, 0], [1, 3, 0], [1, 1, 1]]
for sc_matrix in [c]:
sc = struct.copy()
sc.make_supercell(sc_matrix)
prim = sc.get_primitive_structure(0.01)
assert len(prim) == 2
assert prim.distance_matrix[0, 1] == approx(1.0203432356739286)
def test_primitive_structure_volume_check(self):
latt = Lattice.tetragonal(10, 30)
coords = [
[0.5, 0.8, 0],
[0.5, 0.2, 0],
[0.5, 0.8, 0.333],
[0.5, 0.5, 0.333],
[0.5, 0.5, 0.666],
[0.5, 0.2, 0.666],
]
struct = IStructure(latt, ["Ag"] * 6, coords)
sprim = struct.get_primitive_structure(tolerance=0.1)
assert len(sprim) == 6
def test_get_miller_index(self):
"""Test for get miller index convenience method."""
struct = Structure(
[2.319, -4.01662582, 0.0, 2.319, 4.01662582, 0.0, 0.0, 0.0, 7.252],
["Sn", "Sn", "Sn"],
[
[2.319, 1.33887527, 6.3455],
[1.1595, 0.66943764, 4.5325],
[1.1595, 0.66943764, 0.9065],
],
coords_are_cartesian=True,
)
hkl = struct.get_miller_index_from_site_indexes([0, 1, 2])
assert hkl == (2, -1, 0)
def test_get_all_neighbors_and_get_neighbors(self):
struct = self.struct
nn = struct.get_neighbors_in_shell(struct[0].frac_coords, 2, 4, include_index=True, include_image=True)
assert len(nn) == 47
rand_radius = random.uniform(3, 6)
all_nn = struct.get_all_neighbors(rand_radius, True, True)
for idx, site in enumerate(struct):
assert len(all_nn[idx][0]) == 4
assert len(all_nn[idx]) == len(struct.get_neighbors(site, rand_radius))
for site, nns in zip(struct, all_nn):
for nn in nns:
assert nn[0].is_periodic_image(struct[nn[2]])
dist = sum((site.coords - nn[0].coords) ** 2) ** 0.5
assert dist == approx(nn[1])
struct = Structure(Lattice.cubic(1), ["Li"], [[0, 0, 0]])
struct.make_supercell([2, 2, 2])
assert sum(map(len, struct.get_all_neighbors(3))) == 976
all_nn = struct.get_all_neighbors(0.05)
assert [len(nn) for nn in all_nn] == [0] * len(struct)
# the following test is from issue #2226
poscar = """POSCAR
1.0000000000000000
6.9082208665474800 0.0000000000000005 0.0000000000000011
-0.0000000000000008 14.1745610988433715 0.0000000000000004
0.0000000000000005 -0.0000000000000019 20.0189293405157045
C
14
Direct
1.2615805559557376 1.4846778919841908 0.3162565598606580
-0.7615805559557360 -0.9846778919841882 -0.1837434401393425
1.2615805559557380 -0.4846778919841886 -0.1837434401393425
-0.7615805559557358 0.9846778919841882 0.3162565598606581
-0.2615805559557363 -0.4846778919841892 0.6837434401393432
0.7615805559557360 0.9846778919841881 0.1837434401393430
-0.2653510291469959 0.5275483828607898 0.1211255106369795
0.7653510291469972 -0.0275483828607906 0.6211255106369804
1.2653510291469956 0.5275483828607898 0.3788744893630209
-0.7653510291469972 -0.0275483828607906 -0.1211255106369797
1.2653510291469956 0.4724516171392097 -0.1211255106369793
-0.7653510291469972 0.0275483828607905 0.3788744893630209
-0.2653510291469959 0.4724516171392097 0.6211255106369801
-0.2705230397846415 1.4621722452479102 0.0625618775773844
"""
struct = Structure.from_str(poscar, fmt="poscar")
site0 = struct[1]
site1 = struct[9]
neigh_sites = struct.get_neighbors(site0, 2.0)
assert len(neigh_sites) == 1
neigh_sites = struct.get_neighbors(site1, 2.0)
assert len(neigh_sites) == 1
def test_get_neighbor_list(self):
struct = self.struct
c_indices1, c_indices2, c_offsets, c_distances = struct.get_neighbor_list(3)
p_indices1, p_indices2, p_offsets, p_distances = struct._get_neighbor_list_py(3)
assert_allclose(sorted(c_distances), sorted(p_distances))
# test mutable structure after applying strain (which makes lattice.matrix array no longer contiguous)
# https://github.com/materialsproject/pymatgen/pull/3108
mutable_struct = Structure.from_sites(struct)
mutable_struct.apply_strain(0.01)
c_indices1, c_indices2, c_offsets, c_distances = mutable_struct.get_neighbor_list(3)
p_indices1, p_indices2, p_offsets, p_distances = mutable_struct._get_neighbor_list_py(3)
assert_allclose(sorted(c_distances), sorted(p_distances))
# @skipIf(not os.getenv("CI"), "Only run this in CI tests")
# def test_get_all_neighbors_crosscheck_old(self):
#
# for i in range(100):
# alpha, beta = np.random.rand(2) * 90
# a, b, c = 3 + np.random.rand(3) * 5
# species = ["H"] * 5
# frac_coords = np.random.rand(5, 3)
# try:
# latt = Lattice.from_parameters(a, b, c, alpha, beta, 90)
# struct = Structure.from_spacegroup("P1", latt, species, frac_coords)
# for nn_new, nn_old in zip(struct.get_all_neighbors(4), struct.get_all_neighbors_old(4)):
# sites1 = [i[0] for i in nn_new]
# sites2 = [i[0] for i in nn_old]
# assert set(sites1) == set(sites2)
# break
# except Exception:
# pass
# else:
# raise ValueError("No valid structure tested.")
# from pymatgen.electronic_structure.core import Spin
# d = {
# "@module": "pymatgen.core.structure",
# "@class": "Structure",
# "charge": None,
# "lattice": {
# "matrix": [
# [0.0, 0.0, 5.5333],
# [5.7461, 0.0, 3.518471486290303e-16],
# [-4.692662837312786e-16, 7.6637, 4.692662837312786e-16],
# ],
# "a": 5.5333,
# "b": 5.7461,
# "c": 7.6637,
# "alpha": 90.0,
# "beta": 90.0,
# "gamma": 90.0,
# "volume": 243.66653780778103,
# },
# "sites": [
# {
# "species": [{"element": "Mn", "oxidation_state": 0, "spin": Spin.down, "occu": 1}],
# "abc": [0.0, 0.5, 0.5],
# "xyz": [2.8730499999999997, 3.83185, 4.1055671618015446e-16],
# "label": "Mn0+,spin=-1",
# "properties": {},
# },
# {
# "species": [{"element": "Mn", "oxidation_state": None, "occu": 1.0}],
# "abc": [1.232595164407831e-32, 0.5, 0.5],
# "xyz": [2.8730499999999997, 3.83185, 4.105567161801545e-16],
# "label": "Mn",
# "properties": {},
# },
# ],
# }
# struct = Structure.from_dict(d)
# assert {i[0] for i in struct.get_neighbors(struct[0], 0.05)} == {
# i[0] for i in struct.get_neighbors_old(struct[0], 0.05)
# }
def test_get_symmetric_neighbor_list(self):
# tetragonal group with all bonds related by symmetry
struct = Structure.from_spacegroup(100, [[1, 0, 0], [0, 1, 0], [0, 0, 2]], ["Fe"], [[0.0, 0.0, 0.0]])
c_indices, p_indices, offsets, distances, s_indices, symops = struct.get_symmetric_neighbor_list(0.8, sg=100)
assert len(np.unique(s_indices)) == 1
assert s_indices[0] == 0
assert (~np.isnan(s_indices)).all()
assert (symops[0].affine_matrix == np.eye(4)).all()
# now more complicated example with bonds of same length but with different symmetry
s2 = Structure.from_spacegroup(198, [[8.908, 0, 0], [0, 8.908, 0], [0, 0, 8.908]], ["Cu"], [[0.0, 0.0, 0.0]])
c_indices2, p_indices2, offsets2, distances2, s_indices2, symops2 = s2.get_symmetric_neighbor_list(7, sg=198)
assert len(np.unique(s_indices2)) == 2
assert len(s_indices2) == 48
assert len(s_indices2[s_indices2 == 0]) == len(s_indices2[s_indices2 == 1])
assert s_indices2[0] == 0
assert s_indices2[24] == 1
assert np.isclose(distances2[0], distances2[24])
assert (symops2[0].affine_matrix == np.eye(4)).all()
assert (symops2[24].affine_matrix == np.eye(4)).all()
from_a2 = s2[c_indices2[0]].frac_coords
to_a2 = s2[p_indices2[0]].frac_coords
r_a2 = offsets2[0]
from_b2 = s2[c_indices2[1]].frac_coords
to_b2 = s2[p_indices2[1]].frac_coords
r_b2 = offsets2[1]
assert symops2[1].are_symmetrically_related_vectors(from_a2, to_a2, r_a2, from_b2, to_b2, r_b2)
assert symops2[1].are_symmetrically_related_vectors(from_b2, to_b2, r_b2, from_a2, to_a2, r_a2)
c_indices3, p_indices3, offsets3, distances3, s_indices3, symops3 = s2.get_symmetric_neighbor_list(
7, sg=198, unique=True
)
assert (np.sort(np.array([c_indices3, p_indices3]).flatten()) == np.sort(c_indices2)).all()
assert (np.sort(np.array([c_indices3, p_indices3]).flatten()) == np.sort(p_indices2)).all()
def test_get_all_neighbors_outside_cell(self):
struct = Structure(
Lattice.cubic(2),
["Li", "Li", "Li", "Si"],
[[3.1] * 3, [0.11] * 3, [-1.91] * 3, [0.5] * 3],
)
all_nn = struct.get_all_neighbors(0.2, True)
for site, nns in zip(struct, all_nn):
for nn in nns:
assert nn[0].is_periodic_image(struct[nn[2]])
d = sum((site.coords - nn[0].coords) ** 2) ** 0.5
assert d == approx(nn[1])
assert list(map(len, all_nn)) == [2, 2, 2, 0]
def test_get_all_neighbors_small_cutoff(self):
struct = Structure(
Lattice.cubic(2),
["Li", "Li", "Li", "Si"],
[[3.1] * 3, [0.11] * 3, [-1.91] * 3, [0.5] * 3],
)
all_nn = struct.get_all_neighbors(1e-5, True)
assert len(all_nn) == len(struct)
assert [] == all_nn[0]
all_nn = struct.get_all_neighbors(0, True)
assert len(all_nn) == len(struct)
assert [] == all_nn[0]
def test_coincide_sites(self):
struct = Structure(
Lattice.cubic(5),
["Li", "Li", "Li"],
[[0.1, 0.1, 0.1], [0.1, 0.1, 0.1], [3, 3, 3]],
coords_are_cartesian=True,
)
all_nn = struct.get_all_neighbors(1e-5, True)
assert [len(i) for i in all_nn] == [0, 0, 0]
def test_get_all_neighbors_equal(self):
with pytest.warns(FutureWarning, match="get_all_neighbors_old is deprecated"):
struct = Structure(
Lattice.cubic(2),
["Li", "Li", "Li", "Si"],
[[3.1] * 3, [0.11] * 3, [-1.91] * 3, [0.5] * 3],
)
nn_traditional = struct.get_all_neighbors_old(4, include_index=True, include_image=True, include_site=True)
nn_cell_lists = struct.get_all_neighbors(4, include_index=True, include_image=True)
for i in range(4):
assert len(nn_traditional[i]) == len(nn_cell_lists[i])
assert (
np.linalg.norm(
np.array(sorted(j[1] for j in nn_traditional[i]))
- np.array(sorted(j[1] for j in nn_cell_lists[i]))
)
< 1e-3
)
def test_get_dist_matrix(self):
ans = [[0.0, 2.3516318], [2.3516318, 0.0]]
assert_allclose(self.struct.distance_matrix, ans)
def test_to_from_file_string(self):
for fmt in ["cif", "json", "poscar", "cssr"]:
struct = self.struct.to(fmt=fmt)
assert struct is not None
ss = IStructure.from_str(struct, fmt=fmt)
assert_allclose(ss.lattice.parameters, self.struct.lattice.parameters, atol=1e-5)
assert_allclose(ss.frac_coords, self.struct.frac_coords)
assert isinstance(ss, IStructure)
assert "Fd-3m" in self.struct.to(fmt="CIF", symprec=0.1)
poscar_path = f"{self.tmp_path}/POSCAR.testing"
poscar_str = self.struct.to(filename=poscar_path)
with open(poscar_path) as file:
assert file.read() == poscar_str
assert Structure.from_file(poscar_path) == self.struct
yaml_path = f"{self.tmp_path}/Si_testing.yaml"
yaml_str = self.struct.to(filename=yaml_path)
with open(yaml_path) as file:
assert file.read() == yaml_str
assert Structure.from_file(yaml_path) == self.struct
# Test Path support
struct = Structure.from_file(Path(yaml_path))
assert struct == self.struct
# Test .yml extension works too.
yml_path = yaml_path.replace(".yaml", ".yml")
os.replace(yaml_path, yml_path)
assert Structure.from_file(yml_path) == self.struct
with pytest.raises(ValueError, match="Format not specified and could not infer from filename='whatever'"):
self.struct.to(filename="whatever")
with pytest.raises(ValueError, match="Invalid format='badformat'"):
self.struct.to(fmt="badformat")
self.struct.to(filename="POSCAR.testing.gz")
struct = Structure.from_file("POSCAR.testing.gz")
assert struct == self.struct
# test CIF file with unicode error
# https://github.com/materialsproject/pymatgen/issues/2947
struct = Structure.from_file(f"{TEST_FILES_DIR}/bad-unicode-gh-2947.mcif")
assert struct.formula == "Ni32 O32"
def test_pbc(self):
assert_array_equal(self.struct.pbc, (True, True, True))
assert self.struct.is_3d_periodic
struct_pbc = Structure(self.lattice_pbc, ["Si"] * 2, self.struct.frac_coords)
assert_array_equal(struct_pbc.pbc, (True, True, False))
assert not struct_pbc.is_3d_periodic
def test_sites_setter(self):
struct = self.struct.copy()
new_sites = struct.sites[::-1] # reverse order of sites
struct.sites = new_sites
assert struct.sites == new_sites
class TestStructure(PymatgenTest):
def setUp(self):
coords = []
coords.append([0, 0, 0])
coords.append([0.75, 0.5, 0.75])
lattice = Lattice([[3.8401979337, 0, 0], [1.9200989668, 3.3257101909, 0], [0, -2.2171384943, 3.1355090603]])
self.struct = Structure(lattice, ["Si", "Si"], coords)
self.cu_structure = Structure(lattice, ["Cu", "Cu"], coords)
self.disordered = Structure.from_spacegroup("Im-3m", Lattice.cubic(3), [Composition("Fe0.5Mn0.5")], [[0, 0, 0]])
self.labeled_structure = Structure(lattice, ["Si", "Si"], coords, labels=["Si1", "Si2"])
def test_mutable_sequence_methods(self):
struct = self.struct
struct[0] = "Fe"
assert struct.formula == "Fe1 Si1"
struct[0] = "Fe", [0.5, 0.5, 0.5]
assert struct.formula == "Fe1 Si1"
assert_allclose(struct[0].frac_coords, [0.5, 0.5, 0.5])
struct.reverse()
assert struct[0].specie == Element("Si")
assert_allclose(struct[0].frac_coords, [0.75, 0.5, 0.75])
struct[0] = {"Mn": 0.5}
assert struct.formula == "Mn0.5 Fe1"
del struct[1]
assert struct.formula == "Mn0.5"
struct[0] = "Fe", [0.9, 0.9, 0.9], {"magmom": 5}
assert struct.formula == "Fe1"
assert struct[0].magmom == 5
# Test atomic replacement.
struct["Fe"] = "Mn"
assert struct.formula == "Mn1"
# Test slice replacement.
struct = PymatgenTest.get_structure("Li2O")
struct[0:2] = "S"
assert struct.formula == "Li1 S2"
def test_not_hashable(self):
with pytest.raises(TypeError, match="unhashable type: 'Structure'"):
_ = {self.struct: 1}
def test_sort(self):
struct = self.struct
struct[0] = "F"
struct.sort()
assert struct[0].species_string == "Si"
assert struct[1].species_string == "F"
struct.sort(key=lambda site: site.species_string)
assert struct[0].species_string == "F"
assert struct[1].species_string == "Si"
struct.sort(key=lambda site: site.species_string, reverse=True)
assert struct[0].species_string == "Si"
assert struct[1].species_string == "F"
def test_replace_species(self):
struct = self.struct
struct.replace_species({"Si": "Na"})
assert struct.formula == "Na2"
# test replacement with a dictionary
struct.replace_species({"Na": {"K": 0.75, "P": 0.25}})
assert struct.formula == "K1.5 P0.5"
# test replacement with species not present in structure
with pytest.warns(UserWarning, match="Some species to be substituted are not present in structure."):
struct.replace_species({"Li": "Na"})
# test in_place=False
new_struct = struct.replace_species({"K": "Li"}, in_place=False)
assert struct.formula == "K1.5 P0.5"
assert new_struct.formula == "Li1.5 P0.5"
def test_append_insert_remove_replace_substitute(self):
struct = self.struct
struct.insert(1, "O", [0.5, 0.5, 0.5])
assert struct.formula == "Si2 O1"
assert struct.ntypesp == 2
assert struct.symbol_set == ("O", "Si")
assert struct.indices_from_symbol("Si") == (0, 2)
assert struct.indices_from_symbol("O") == (1,)
del struct[2]
assert struct.formula == "Si1 O1"
assert struct.indices_from_symbol("Si") == (0,)
assert struct.indices_from_symbol("O") == (1,)
struct.append("N", [0.25, 0.25, 0.25])
assert struct.formula == "Si1 N1 O1"
assert struct.ntypesp == 3
assert struct.symbol_set == ("N", "O", "Si")
assert struct.indices_from_symbol("Si") == (0,)
assert struct.indices_from_symbol("O") == (1,)
assert struct.indices_from_symbol("N") == (2,)
struct[0] = "Ge"
assert struct.formula == "Ge1 N1 O1"
assert struct.symbol_set == ("Ge", "N", "O")
struct.replace_species({"Ge": "Si"})
assert struct.formula == "Si1 N1 O1"
assert struct.ntypesp == 3
struct.replace_species({"Si": {"Ge": 0.5, "Si": 0.5}})
assert struct.formula == "Si0.5 Ge0.5 N1 O1"
# this should change the .5Si .5Ge sites to .75Si .25Ge
struct.replace_species({"Ge": {"Ge": 0.5, "Si": 0.5}})
assert struct.formula == "Si0.75 Ge0.25 N1 O1"
assert struct.ntypesp == 4
struct.replace_species({"Ge": "Si"})
struct.substitute(1, "hydroxyl")
assert struct.formula == "Si1 H1 N1 O1"
assert struct.symbol_set == ("H", "N", "O", "Si")
# Distance between O and H
assert struct.get_distance(2, 3) == approx(0.96)
# Distance between Si and H
assert struct.get_distance(0, 3) == approx(2.09840889)
struct.remove_species(["H"])
assert struct.formula == "Si1 N1 O1"
struct.remove_sites([1, 2])
assert struct.formula == "Si1"
def test_add_remove_site_property(self):
struct = self.struct
struct.add_site_property("charge", [4.1, -5])
assert struct[0].charge == 4.1
assert struct[1].charge == -5
struct.add_site_property("magmom", [3, 2])
assert struct[0].charge == 4.1
assert struct[0].magmom == 3
struct.remove_site_property("magmom")
with pytest.raises(AttributeError, match="attr='magmom' not found on PeriodicSite"):
_ = struct[0].magmom
def test_propertied_structure(self):
# Make sure that site properties are set to None for missing values.
self.struct.add_site_property("charge", [4.1, -5])
self.struct.append("Li", [0.3, 0.3, 0.3])
assert len(self.struct.site_properties["charge"]) == 3
props = {"test_property": 42}
struct_with_props = Structure(
lattice=Lattice.cubic(3),
species=("Fe", "Fe"),
coords=((0, 0, 0), (0.5, 0.5, 0.5)),
site_properties={"magmom": [5, -5]},
properties=props,
)
dct = struct_with_props.as_dict()
struct = Structure.from_dict(dct)
assert struct.properties == props
assert dct == struct.as_dict()
json_str = struct_with_props.to(fmt="json")
assert '"test_property": 42' in json_str
struct = Structure.from_str(json_str, fmt="json")
assert struct.properties == props
assert dct == struct.as_dict()
def test_perturb(self):
dist = 0.1
pre_perturbation_sites = self.struct.copy()
self.struct.perturb(distance=dist)
post_perturbation_sites = self.struct.sites
for idx, site in enumerate(pre_perturbation_sites):
assert site.distance(post_perturbation_sites[idx]) == approx(dist), "Bad perturbation distance"
structure2 = pre_perturbation_sites.copy()
structure2.perturb(distance=dist, min_distance=0)
post_perturbation_sites2 = structure2.sites
for idx, site in enumerate(pre_perturbation_sites):
assert site.distance(post_perturbation_sites2[idx]) <= dist
assert site.distance(post_perturbation_sites2[idx]) >= 0
def test_add_oxidation_states_by_element(self):
oxidation_states = {"Si": -4}
self.struct.add_oxidation_state_by_element(oxidation_states)
for site in self.struct:
for specie in site.species:
assert specie.oxi_state == oxidation_states[specie.symbol], "Wrong oxidation state assigned!"
oxidation_states = {"Fe": 2}
with pytest.raises(ValueError, match="Oxidation states not specified for all elements, missing={'Si'}"):
self.struct.add_oxidation_state_by_element(oxidation_states)
def test_add_oxidation_states_by_site(self):
self.struct.add_oxidation_state_by_site([2, -4])
assert self.struct[0].specie.oxi_state == 2
with pytest.raises(
ValueError, match="Oxidation states of all sites must be specified, expected 2 values, got 1"
):
self.struct.add_oxidation_state_by_site([1])
def test_remove_oxidation_states(self):