forked from aiidateam/aiida-core
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtest_dataclasses.py
3804 lines (3226 loc) · 138 KB
/
test_dataclasses.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
###########################################################################
# Copyright (c), The AiiDA team. All rights reserved. #
# This file is part of the AiiDA code. #
# #
# The code is hosted on GitHub at https://github.com/aiidateam/aiida-core #
# For further information on the license, see the LICENSE.txt file #
# For further information please visit http://www.aiida.net #
###########################################################################
# ruff: noqa: N806
"""Tests for specific subclasses of Data."""
import os
import tempfile
import numpy as np
import pytest
from aiida.common.exceptions import ModificationNotAllowed
from aiida.common.utils import Capturing
from aiida.orm import ArrayData, BandsData, CifData, Dict, KpointsData, StructureData, TrajectoryData, load_node
from aiida.orm.nodes.data.cif import has_pycifrw
from aiida.orm.nodes.data.structure import (
Kind,
Site,
_atomic_masses,
ase_refine_cell,
get_formula,
get_pymatgen_version,
has_ase,
has_pymatgen,
has_spglib,
)
def has_seekpath():
"""Check if there is the seekpath dependency
:return: True if seekpath is installed, False otherwise
"""
try:
import seekpath # noqa: F401
return True
except ImportError:
return False
def to_list_of_lists(lofl):
"""Converts an iterable of iterables to a list of lists, needed
for some tests (e.g. when one has a tuple of lists, a list of tuples, ...)
:param lofl: an iterable of iterables
:return: a list of lists
"""
return [[el for el in lst] for lst in lofl]
def simplify(string):
"""Takes a string, strips spaces in each line and returns it
Useful to compare strings when different versions of a code give
different spaces.
"""
return '\n'.join(s.strip() for s in string.split())
skip_ase = pytest.mark.skipif(not has_ase(), reason='Unable to import ase')
skip_spglib = pytest.mark.skipif(not has_spglib(), reason='Unable to import spglib')
skip_pycifrw = pytest.mark.skipif(not has_pycifrw(), reason='Unable to import PyCifRW')
skip_pymatgen = pytest.mark.skipif(not has_pymatgen(), reason='Unable to import pymatgen')
@skip_pymatgen
def test_get_pymatgen_version():
assert isinstance(get_pymatgen_version(), str)
class TestCifData:
"""Tests for CifData class."""
valid_sample_cif_str = """
data_test
_cell_length_a 10
_cell_length_b 10
_cell_length_c 10
_cell_angle_alpha 90
_cell_angle_beta 90
_cell_angle_gamma 90
_chemical_formula_sum 'C O2'
loop_
_atom_site_label
_atom_site_fract_x
_atom_site_fract_y
_atom_site_fract_z
_atom_site_attached_hydrogens
C 0 0 0 0
O 0.5 0.5 0.5 .
H 0.75 0.75 0.75 0
"""
valid_sample_cif_str_2 = """
data_test
_cell_length_a 10
_cell_length_b 10
_cell_length_c 10
_cell_angle_alpha 90
_cell_angle_beta 90
_cell_angle_gamma 90
_chemical_formula_sum 'C O'
loop_
_atom_site_label
_atom_site_fract_x
_atom_site_fract_y
_atom_site_fract_z
_atom_site_attached_hydrogens
C 0 0 0 0
O 0.5 0.5 0.5 .
"""
@skip_pycifrw
def test_reload_cifdata(self):
"""Test `CifData` cycle."""
file_content = 'data_test _cell_length_a 10(1)'
with tempfile.NamedTemporaryFile(mode='w+') as tmpf:
filename = tmpf.name
basename = os.path.split(filename)[1]
tmpf.write(file_content)
tmpf.flush()
a = CifData(file=filename, source={'version': '1234', 'db_name': 'COD', 'id': '0000001'})
# Key 'db_kind' is not allowed in source description:
with pytest.raises(KeyError):
a.source = {'db_kind': 'small molecule'}
the_uuid = a.uuid
assert a.base.repository.list_object_names() == [basename]
with a.open() as fhandle:
assert fhandle.read() == file_content
a.store()
assert a.source == {
'db_name': 'COD',
'id': '0000001',
'version': '1234',
}
with a.open() as fhandle:
assert fhandle.read() == file_content
assert a.base.repository.list_object_names() == [basename]
b = load_node(the_uuid)
# I check the retrieved object
assert isinstance(b, CifData)
assert b.base.repository.list_object_names() == [basename]
with b.open() as fhandle:
assert fhandle.read() == file_content
# Checking the get_or_create() method:
with tempfile.NamedTemporaryFile(mode='w+') as tmpf:
tmpf.write(file_content)
tmpf.flush()
c, created = CifData.get_or_create(tmpf.name, store_cif=False)
assert isinstance(c, CifData)
assert not created
assert c.get_content() == file_content
other_content = 'data_test _cell_length_b 10(1)'
with tempfile.NamedTemporaryFile(mode='w+') as tmpf:
tmpf.write(other_content)
tmpf.flush()
c, created = CifData.get_or_create(tmpf.name, store_cif=False)
assert isinstance(c, CifData)
assert created
assert c.get_content() == other_content
@skip_pycifrw
def test_parse_cifdata(self):
"""Test parsing a CIF file."""
file_content = 'data_test _cell_length_a 10(1)'
with tempfile.NamedTemporaryFile(mode='w+') as tmpf:
tmpf.write(file_content)
tmpf.flush()
a = CifData(file=tmpf.name)
assert list(a.values.keys()) == ['test']
@skip_pycifrw
def test_change_cifdata_file(self):
"""Test changing file for `CifData` before storing."""
file_content_1 = 'data_test _cell_length_a 10(1)'
file_content_2 = 'data_test _cell_length_a 11(1)'
with tempfile.NamedTemporaryFile(mode='w+') as tmpf:
tmpf.write(file_content_1)
tmpf.flush()
a = CifData(file=tmpf.name)
assert a.values['test']['_cell_length_a'] == '10(1)'
with tempfile.NamedTemporaryFile(mode='w+') as tmpf:
tmpf.write(file_content_2)
tmpf.flush()
a.set_file(tmpf.name)
assert a.values['test']['_cell_length_a'] == '11(1)'
@skip_ase
@skip_pycifrw
@pytest.mark.requires_rmq
def test_get_structure(self):
"""Test `CifData.get_structure`."""
with tempfile.NamedTemporaryFile(mode='w+') as tmpf:
tmpf.write(
"""
data_test
_cell_length_a 10
_cell_length_b 10
_cell_length_c 10
_cell_angle_alpha 90
_cell_angle_beta 90
_cell_angle_gamma 90
loop_
_symmetry_equiv_pos_site_id
_symmetry_equiv_pos_as_xyz
1 +x,+y,+z
loop_
_atom_site_label
_atom_site_fract_x
_atom_site_fract_y
_atom_site_fract_z
C 0 0 0
O 0.5 0.5 0.5
"""
)
tmpf.flush()
a = CifData(file=tmpf.name)
with pytest.raises(ValueError):
a.get_structure(converter='none')
c = a.get_structure()
assert c.get_kind_names() == ['C', 'O']
@skip_ase
@skip_pycifrw
@pytest.mark.requires_rmq
def test_ase_primitive_and_conventional_cells_ase(self):
"""Checking the number of atoms per primitive/conventional cell
returned by ASE ase.io.read() method. Test input is
adapted from http://www.crystallography.net/cod/9012064.cif@120115
"""
with tempfile.NamedTemporaryFile(mode='w+') as tmpf:
tmpf.write(
"""
data_9012064
_space_group_IT_number 166
_symmetry_space_group_name_H-M 'R -3 m :H'
_cell_angle_alpha 90
_cell_angle_beta 90
_cell_angle_gamma 120
_cell_length_a 4.395
_cell_length_b 4.395
_cell_length_c 30.440
_cod_database_code 9012064
loop_
_atom_site_label
_atom_site_fract_x
_atom_site_fract_y
_atom_site_fract_z
_atom_site_U_iso_or_equiv
Bi 0.00000 0.00000 0.40046 0.02330
Te1 0.00000 0.00000 0.00000 0.01748
Te2 0.00000 0.00000 0.79030 0.01912
"""
)
tmpf.flush()
c = CifData(file=tmpf.name)
assert c.get_structure(converter='ase', primitive_cell=False).get_ase().get_global_number_of_atoms() == 15
assert c.get_structure(converter='ase').get_ase().get_global_number_of_atoms() == 15
structure = c.get_structure(converter='ase', primitive_cell=True, subtrans_included=False)
assert structure.get_ase().get_global_number_of_atoms() == 5
@skip_ase
@skip_pycifrw
@skip_pymatgen
@pytest.mark.requires_rmq
def test_ase_primitive_and_conventional_cells_pymatgen(self):
"""Checking the number of atoms per primitive/conventional cell
returned by ASE ase.io.read() method. Test input is
adapted from http://www.crystallography.net/cod/9012064.cif@120115
"""
with tempfile.NamedTemporaryFile(mode='w+') as tmpf:
tmpf.write(
"""
data_9012064
_space_group_IT_number 166
_symmetry_space_group_name_H-M 'R -3 m :H'
_cell_angle_alpha 90
_cell_angle_beta 90
_cell_angle_gamma 120
_cell_length_a 4.395
_cell_length_b 4.395
_cell_length_c 30.440
_cod_database_code 9012064
loop_
_symmetry_equiv_pos_as_xyz
x,y,z
2/3+x,1/3+y,1/3+z
1/3+x,2/3+y,2/3+z
x,x-y,z
2/3+x,1/3+x-y,1/3+z
1/3+x,2/3+x-y,2/3+z
y,x,-z
2/3+y,1/3+x,1/3-z
1/3+y,2/3+x,2/3-z
-x+y,y,z
loop_
_atom_site_label
_atom_site_fract_x
_atom_site_fract_y
_atom_site_fract_z
_atom_site_U_iso_or_equiv
Bi 0.00000 0.00000 0.40046 0.02330
Te1 0.00000 0.00000 0.00000 0.01748
Te2 0.00000 0.00000 0.79030 0.01912
"""
)
tmpf.flush()
c = CifData(file=tmpf.name)
ase = c.get_structure(converter='pymatgen', primitive_cell=False).get_ase()
assert ase.get_global_number_of_atoms() == 15
ase = c.get_structure(converter='pymatgen').get_ase()
assert ase.get_global_number_of_atoms() == 15
ase = c.get_structure(converter='pymatgen', primitive_cell=True).get_ase()
assert ase.get_global_number_of_atoms() == 5
@skip_pycifrw
def test_pycifrw_from_datablocks(self):
"""Tests CifData.pycifrw_from_cif()"""
import re
from aiida.orm.nodes.data.cif import pycifrw_from_cif
datablocks = [
{
'_atom_site_label': ['A', 'B', 'C'],
'_atom_site_occupancy': [1.0, 0.5, 0.5],
'_publ_section_title': 'Test CIF',
}
]
with Capturing():
lines = pycifrw_from_cif(datablocks).WriteOut().split('\n')
non_comments = []
for line in lines:
if not re.search('^#', line):
non_comments.append(line)
assert simplify('\n'.join(non_comments)) == simplify(
"""
data_0
loop_
_atom_site_label
A
B
C
loop_
_atom_site_occupancy
1.0
0.5
0.5
_publ_section_title 'Test CIF'
"""
)
loops = {'_atom_site': ['_atom_site_label', '_atom_site_occupancy']}
with Capturing():
lines = pycifrw_from_cif(datablocks, loops).WriteOut().split('\n')
non_comments = []
for line in lines:
if not re.search('^#', line):
non_comments.append(line)
assert simplify('\n'.join(non_comments)) == simplify(
"""
data_0
loop_
_atom_site_label
_atom_site_occupancy
A 1.0
B 0.5
C 0.5
_publ_section_title 'Test CIF'
"""
)
@skip_pycifrw
def test_pycifrw_syntax(self):
"""Tests CifData.pycifrw_from_cif() - check syntax pb in PyCifRW 3.6."""
import re
from aiida.orm.nodes.data.cif import pycifrw_from_cif
datablocks = [
{
'_tag': '[value]',
}
]
with Capturing():
lines = pycifrw_from_cif(datablocks).WriteOut().split('\n')
non_comments = []
for line in lines:
if not re.search('^#', line):
non_comments.append(line)
assert simplify('\n'.join(non_comments)) == simplify(
"""
data_0
_tag '[value]'
"""
)
@skip_pycifrw
@staticmethod
def test_cif_with_long_line():
"""Tests CifData - check that long lines (longer than 2048 characters) are supported.
Should not raise any error.
"""
with tempfile.NamedTemporaryFile(mode='w+') as tmpf:
tmpf.write(
f"""
data_0
_tag {'a' * 5000}
"""
)
tmpf.flush()
_ = CifData(file=tmpf.name)
@skip_ase
@skip_pycifrw
def test_cif_roundtrip(self):
"""Test the `CifData` roundtrip."""
with tempfile.NamedTemporaryFile(mode='w+') as tmpf:
tmpf.write(
"""
data_test
_cell_length_a 10
_cell_length_b 10
_cell_length_c 10
_cell_angle_alpha 90
_cell_angle_beta 90
_cell_angle_gamma 90
loop_
_atom_site_label
_atom_site_fract_x
_atom_site_fract_y
_atom_site_fract_z
C 0 0 0
O 0.5 0.5 0.5
_cod_database_code 0000001
_[local]_flags ''
"""
)
tmpf.flush()
a = CifData(file=tmpf.name)
b = CifData(values=a.values)
c = CifData(values=b.values)
assert b._prepare_cif() == c._prepare_cif()
b = CifData(ase=a.ase)
c = CifData(ase=b.ase)
assert b._prepare_cif() == c._prepare_cif()
def test_symop_string_from_symop_matrix_tr(self):
"""Test symmetry operations."""
from aiida.tools.data.cif import symop_string_from_symop_matrix_tr
assert symop_string_from_symop_matrix_tr([[1, 0, 0], [0, 1, 0], [0, 0, 1]]) == 'x,y,z'
assert symop_string_from_symop_matrix_tr([[1, 0, 0], [0, -1, 0], [0, 1, 1]]) == 'x,-y,y+z'
assert symop_string_from_symop_matrix_tr([[-1, 0, 0], [0, 1, 0], [0, 0, 1]], [1, -1, 0]) == '-x+1,y-1,z'
@skip_ase
@skip_pycifrw
def test_attached_hydrogens(self):
"""Test parsing of file with attached hydrogens."""
with tempfile.NamedTemporaryFile(mode='w+') as tmpf:
tmpf.write(
"""
data_test
_cell_length_a 10
_cell_length_b 10
_cell_length_c 10
_cell_angle_alpha 90
_cell_angle_beta 90
_cell_angle_gamma 90
loop_
_atom_site_label
_atom_site_fract_x
_atom_site_fract_y
_atom_site_fract_z
_atom_site_attached_hydrogens
C 0 0 0 ?
O 0.5 0.5 0.5 .
H 0.75 0.75 0.75 0
"""
)
tmpf.flush()
a = CifData(file=tmpf.name)
assert a.has_attached_hydrogens is False
with tempfile.NamedTemporaryFile(mode='w+') as tmpf:
tmpf.write(
"""
data_test
_cell_length_a 10
_cell_length_b 10
_cell_length_c 10
_cell_angle_alpha 90
_cell_angle_beta 90
_cell_angle_gamma 90
loop_
_atom_site_label
_atom_site_fract_x
_atom_site_fract_y
_atom_site_fract_z
_atom_site_attached_hydrogens
C 0 0 0 ?
O 0.5 0.5 0.5 1
H 0.75 0.75 0.75 0
"""
)
tmpf.flush()
a = CifData(file=tmpf.name)
assert a.has_attached_hydrogens is True
@skip_ase
@skip_pycifrw
@skip_spglib
@pytest.mark.requires_rmq
def test_refine(self):
"""Test case for refinement (space group determination) for a
CifData object.
"""
from aiida.tools.data.cif import refine_inline
with tempfile.NamedTemporaryFile(mode='w+') as tmpf:
tmpf.write(
"""
data_test
_cell_length_a 10
_cell_length_b 10
_cell_length_c 10
_cell_angle_alpha 90
_cell_angle_beta 90
_cell_angle_gamma 90
loop_
_atom_site_label
_atom_site_fract_x
_atom_site_fract_y
_atom_site_fract_z
C 0.5 0.5 0.5
O 0.25 0.5 0.5
O 0.75 0.5 0.5
"""
)
tmpf.flush()
a = CifData(file=tmpf.name)
ret_dict = refine_inline(a)
b = ret_dict['cif']
assert list(b.values.keys()) == ['test']
assert b.values['test']['_chemical_formula_sum'] == 'C O2'
assert b.values['test']['_symmetry_equiv_pos_as_xyz'] == [
'x,y,z',
'-x,-y,-z',
'-y,x,z',
'y,-x,-z',
'-x,-y,z',
'x,y,-z',
'y,-x,z',
'-y,x,-z',
'x,-y,-z',
'-x,y,z',
'-y,-x,-z',
'y,x,z',
'-x,y,-z',
'x,-y,z',
'y,x,-z',
'-y,-x,z',
]
with tempfile.NamedTemporaryFile(mode='w+') as tmpf:
tmpf.write(
"""
data_a
data_b
"""
)
tmpf.flush()
c = CifData(file=tmpf.name)
with pytest.raises(ValueError):
ret_dict = refine_inline(c)
@skip_pycifrw
def test_scan_type(self):
"""Check that different scan_types of PyCifRW produce the same result."""
with tempfile.NamedTemporaryFile(mode='w+') as tmpf:
tmpf.write(self.valid_sample_cif_str)
tmpf.flush()
default = CifData(file=tmpf.name)
default2 = CifData(file=tmpf.name, scan_type='standard')
assert default._prepare_cif() == default2._prepare_cif()
flex = CifData(file=tmpf.name, scan_type='flex')
assert default._prepare_cif() == flex._prepare_cif()
@skip_pycifrw
def test_empty_cif(self):
"""Test empty CifData
Note: This test does not need PyCifRW.
"""
with tempfile.NamedTemporaryFile(mode='w+') as tmpf:
tmpf.write(self.valid_sample_cif_str)
tmpf.flush()
# empty cifdata should be possible
a = CifData()
# but it does not have a file
with pytest.raises(AttributeError):
_ = a.filename
# now it has
a.set_file(tmpf.name)
_ = a.filename
a.store()
@skip_pycifrw
def test_parse_policy(self):
"""Test that loading of CIF file occurs as defined by parse_policy."""
with tempfile.NamedTemporaryFile(mode='w+') as tmpf:
tmpf.write(self.valid_sample_cif_str)
tmpf.flush()
# this will parse the cif
eager = CifData(file=tmpf.name, parse_policy='eager')
assert eager._values is not None
# this should not parse the cif
lazy = CifData(file=tmpf.name, parse_policy='lazy')
assert lazy._values is None
# also lazy-loaded nodes should be storable
lazy.store()
# this should parse the cif
_ = lazy.values
assert lazy._values is not None
@skip_pycifrw
def test_set_file(self):
"""Test that setting a new file clears formulae and spacegroups."""
with tempfile.NamedTemporaryFile(mode='w+') as tmpf:
tmpf.write(self.valid_sample_cif_str)
tmpf.flush()
a = CifData(file=tmpf.name)
f1 = a.get_formulae()
assert f1 is not None
with tempfile.NamedTemporaryFile(mode='w+') as tmpf:
tmpf.write(self.valid_sample_cif_str_2)
tmpf.flush()
# this should reset formulae and spacegroup_numbers
a.set_file(tmpf.name)
assert a.base.attributes.get('formulae') is None
assert a.base.attributes.get('spacegroup_numbers') is None
# this should populate formulae
a.parse()
f2 = a.get_formulae()
assert f2 is not None
# empty cifdata should be possible
a = CifData()
# but it does not have a file
with pytest.raises(AttributeError):
_ = a.filename
# now it has
a.set_file(tmpf.name)
a.parse()
_ = a.filename
assert f1 != f2
@skip_pycifrw
def test_has_partial_occupancies(self):
"""Test structure with partial occupancies."""
tests = [
# Unreadable occupations should not count as a partial occupancy
('O 0.5 0.5(1) 0.5 ?', False),
# The default epsilon for deviation of unity for an occupation to be considered partial is 1E-6
('O 0.5 0.5(1) 0.5 1.0(000000001)', False),
# Partial occupancies should be able to deal with parentheses in the value
('O 0.5 0.5(1) 0.5 1.0(000132)', True),
# Partial occupancies should be able to deal with parentheses in the value
('O 0.5 0.5(1) 0.5 0.9(0000132)', True),
]
for test_string, result in tests:
with tempfile.NamedTemporaryFile(mode='w+') as handle:
handle.write(
f"""
data_test
loop_
_atom_site_label
_atom_site_fract_x
_atom_site_fract_y
_atom_site_fract_z
_atom_site_occupancy
{test_string}
"""
)
handle.flush()
cif = CifData(file=handle.name)
assert cif.has_partial_occupancies == result
@skip_pycifrw
def test_has_unknown_species(self):
"""Test structure with unknown species."""
tests = [
('H2 O', False), # No unknown species
('OsAx', True), # Ax is an unknown specie
('UX', True), # X counts as unknown specie despite being defined in aiida.common.constants.elements
('', None), # If no chemical formula is defined, None should be returned
]
for formula, result in tests:
with tempfile.NamedTemporaryFile(mode='w+') as handle:
formula_string = f"_chemical_formula_sum '{formula}'" if formula else '\n'
handle.write(f"""data_test\n{formula_string}\n""")
handle.flush()
cif = CifData(file=handle.name)
assert cif.has_unknown_species == result, formula_string
@skip_pycifrw
def test_has_undefined_atomic_sites(self):
"""Test structure with undefined atomic sites."""
tests = [
('C 0.0 0.0 0.0', False), # Should return False because all sites have valid coordinates
('C 0.0 0.0 ?', True), # Should return True because one site has an undefined coordinate
('', True), # Should return True if no sites defined at all
]
for test_string, result in tests:
with tempfile.NamedTemporaryFile(mode='w+') as handle:
base = 'loop_\n_atom_site_label\n_atom_site_fract_x\n_atom_site_fract_y\n_atom_site_fract_z'
atomic_site_string = f'{base}\n{test_string}' if test_string else ''
handle.write(f"""data_test\n{atomic_site_string}\n""")
handle.flush()
cif = CifData(file=handle.name)
assert cif.has_undefined_atomic_sites == result
class TestKindValidSymbols:
"""Tests the symbol validation of the aiida.orm.nodes.data.structure.Kind class."""
def test_bad_symbol(self):
"""Should not accept a non-existing symbol."""
with pytest.raises(ValueError):
Kind(symbols='Hxx')
def test_empty_list_symbols(self):
"""Should not accept an empty list."""
with pytest.raises(ValueError):
Kind(symbols=[])
@staticmethod
def test_valid_list():
"""Should not raise any error."""
Kind(symbols=['H', 'He'], weights=[0.5, 0.5])
@staticmethod
def test_unknown_symbol():
"""Should test if symbol X is valid and defined in the elements dictionary."""
Kind(symbols=['X'])
class TestSiteValidWeights:
"""Tests valid weight lists."""
def test_isnot_list(self):
"""Should not accept a non-list, non-number weight."""
with pytest.raises(ValueError):
Kind(symbols='Ba', weights='aaa')
def test_empty_list_weights(self):
"""Should not accept an empty list."""
with pytest.raises(ValueError):
Kind(symbols='Ba', weights=[])
def test_symbol_weight_mismatch(self):
"""Should not accept a size mismatch of the symbols and weights list."""
with pytest.raises(ValueError):
Kind(symbols=['Ba', 'C'], weights=[1.0])
with pytest.raises(ValueError):
Kind(symbols=['Ba'], weights=[0.1, 0.2])
def test_negative_value(self):
"""Should not accept a negative weight."""
with pytest.raises(ValueError):
Kind(symbols=['Ba', 'C'], weights=[-0.1, 0.3])
def test_sum_greater_one(self):
"""Should not accept a sum of weights larger than one."""
with pytest.raises(ValueError):
Kind(symbols=['Ba', 'C'], weights=[0.5, 0.6])
@staticmethod
def test_sum_one_weights():
"""Should accept a sum equal to one."""
Kind(symbols=['Ba', 'C'], weights=[1.0 / 3.0, 2.0 / 3.0])
@staticmethod
def test_sum_less_one_weights():
"""Should accept a sum equal less than one."""
Kind(symbols=['Ba', 'C'], weights=[1.0 / 3.0, 1.0 / 3.0])
@staticmethod
def test_none():
"""Should accept None."""
Kind(symbols='Ba', weights=None)
class TestKindTestGeneral:
"""Tests the creation of Kind objects and their methods."""
def test_sum_one_general(self):
"""Should accept a sum equal to one."""
a = Kind(symbols=['Ba', 'C'], weights=[1.0 / 3.0, 2.0 / 3.0])
assert a.is_alloy
assert not a.has_vacancies
def test_sum_less_one_general(self):
"""Should accept a sum equal less than one."""
a = Kind(symbols=['Ba', 'C'], weights=[1.0 / 3.0, 1.0 / 3.0])
assert a.is_alloy
assert a.has_vacancies
def test_no_position(self):
"""Should not accept a 'positions' parameter."""
with pytest.raises(ValueError):
Kind(position=[0.0, 0.0, 0.0], symbols=['Ba'], weights=[1.0])
def test_simple(self):
"""Should recognize a simple element."""
a = Kind(symbols='Ba')
assert not a.is_alloy
assert not a.has_vacancies
b = Kind(symbols='Ba', weights=1.0)
assert not b.is_alloy
assert not b.has_vacancies
c = Kind(symbols='Ba', weights=None)
assert not c.is_alloy
assert not c.has_vacancies
def test_automatic_name(self):
"""Check the automatic name generator."""
a = Kind(symbols='Ba')
assert a.name == 'Ba'
a = Kind(symbols='X')
assert a.name == 'X'
a = Kind(symbols=('Si', 'Ge'), weights=(1.0 / 3.0, 2.0 / 3.0))
assert a.name == 'GeSi'
a = Kind(symbols=('Si', 'X'), weights=(1.0 / 3.0, 2.0 / 3.0))
assert a.name == 'SiX'
a = Kind(symbols=('Si', 'Ge'), weights=(0.4, 0.5))
assert a.name == 'GeSiX'
a = Kind(symbols=('Si', 'X'), weights=(0.4, 0.5))
assert a.name == 'SiXX'
# Manually setting the name of the species
a.name = 'newstring'
assert a.name == 'newstring'
class TestKindTestMasses:
"""Tests the management of masses during the creation of Kind objects."""
def test_auto_mass_one(self):
"""Mass for elements with sum one"""
a = Kind(symbols=['Ba', 'C'], weights=[1.0 / 3.0, 2.0 / 3.0])
assert round(abs(a.mass - (_atomic_masses['Ba'] + 2.0 * _atomic_masses['C']) / 3.0), 7) == 0
def test_sum_less_one_masses(self):
"""Mass for elements with sum less than one"""
a = Kind(symbols=['Ba', 'C'], weights=[1.0 / 3.0, 1.0 / 3.0])
assert round(abs(a.mass - (_atomic_masses['Ba'] + _atomic_masses['C']) / 2.0), 7) == 0
def test_sum_less_one_singleelem(self):
"""Mass for a single element"""
a = Kind(symbols=['Ba'])
assert round(abs(a.mass - _atomic_masses['Ba']), 7) == 0
def test_manual_mass(self):
"""Mass set manually"""
a = Kind(symbols=['Ba', 'C'], weights=[1.0 / 3.0, 1.0 / 3.0], mass=1000.0)
assert round(abs(a.mass - 1000.0), 7) == 0
class TestStructureDataInit:
"""Tests the creation of StructureData objects (cell and pbc)."""
def test_cell_wrong_size_1(self):
"""Wrong cell size (not 3x3)"""
with pytest.raises(ValueError):
StructureData(cell=((1.0, 2.0, 3.0),))
def test_cell_wrong_size_2(self):
"""Wrong cell size (not 3x3)"""
with pytest.raises(ValueError):
StructureData(cell=((1.0, 0.0, 0.0), (0.0, 0.0, 3.0), (0.0, 3.0)))
def test_cell_zero_vector(self):
"""Wrong cell (one vector has zero length)"""
with pytest.raises(ValueError):
StructureData(cell=((0.0, 0.0, 0.0), (0.0, 1.0, 0.0), (0.0, 0.0, 1.0))).store()
def test_cell_zero_volume(self):
"""Wrong cell (volume is zero)"""
with pytest.raises(ValueError):
StructureData(cell=((1.0, 0.0, 0.0), (0.0, 1.0, 0.0), (1.0, 1.0, 0.0))).store()
def test_cell_ok_init(self):
"""Correct cell"""
cell = ((1.0, 0.0, 0.0), (0.0, 2.0, 0.0), (0.0, 0.0, 3.0))
a = StructureData(cell=cell)
out_cell = a.cell
for i in range(3):
for j in range(3):
assert round(abs(cell[i][j] - out_cell[i][j]), 7) == 0
def test_volume(self):
"""Check the volume calculation"""
a = StructureData(cell=((1.0, 0.0, 0.0), (0.0, 2.0, 0.0), (0.0, 0.0, 3.0)))
assert round(abs(a.get_cell_volume() - 6.0), 7) == 0
def test_wrong_pbc_1(self):
"""Wrong pbc parameter (not bool or iterable)"""
with pytest.raises(ValueError):
cell = ((1.0, 0.0, 0.0), (0.0, 2.0, 0.0), (0.0, 0.0, 3.0))
StructureData(cell=cell, pbc=1)
def test_wrong_pbc_2(self):
"""Wrong pbc parameter (iterable but with wrong len)"""
with pytest.raises(ValueError):
cell = ((1.0, 0.0, 0.0), (0.0, 2.0, 0.0), (0.0, 0.0, 3.0))
StructureData(cell=cell, pbc=[True, True])
def test_wrong_pbc_3(self):
"""Wrong pbc parameter (iterable but with wrong len)"""
with pytest.raises(ValueError):
cell = ((1.0, 0.0, 0.0), (0.0, 2.0, 0.0), (0.0, 0.0, 3.0))
StructureData(cell=cell, pbc=[])
def test_ok_pbc_1(self):
"""Single pbc value"""
cell = ((1.0, 0.0, 0.0), (0.0, 2.0, 0.0), (0.0, 0.0, 3.0))
a = StructureData(cell=cell, pbc=True)
assert a.pbc == tuple([True, True, True])