forked from deepmodeling/dpdata
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsystem.py
More file actions
1800 lines (1589 loc) · 66.6 KB
/
system.py
File metadata and controls
1800 lines (1589 loc) · 66.6 KB
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 glob
import hashlib
import numbers
import os
import warnings
from copy import deepcopy
from typing import (
TYPE_CHECKING,
Any,
Iterable,
Literal,
overload,
)
import numpy as np
import dpdata
import dpdata.md.pbc
# ensure all plugins are loaded!
import dpdata.plugins
import dpdata.plugins.deepmd
from dpdata.amber.mask import load_param_file, pick_by_amber_mask
from dpdata.data_type import Axis, DataError, DataType, get_data_types
from dpdata.driver import Driver, Minimizer
from dpdata.format import Format
from dpdata.plugin import Plugin
from dpdata.utils import (
add_atom_names,
elements_index_map,
remove_pbc,
sort_atom_names,
utf8len,
)
if TYPE_CHECKING:
import parmed
def load_format(fmt):
fmt = fmt.lower()
formats = Format.get_formats()
if fmt in formats:
return formats[fmt]()
raise NotImplementedError(
"Unsupported data format {}. Supported formats: {}".format(
fmt, " ".join(formats)
)
)
class System:
"""The data System.
A data System (a concept used by `deepmd-kit <https://github.com/deepmodeling/deepmd-kit>`_)
contains frames (e.g. produced by an MD simulation) that has the same number of atoms of the same type.
The order of the atoms should be consistent among the frames in one System.
For example, a water system named `d_example` has two molecules. The properties can be accessed by
- `d_example['atom_numbs']` : [2, 4]
- `d_example['atom_names']` : ['O', 'H']
- `d_example['atom_types']` : [0, 1, 1, 0, 1, 1]
- `d_example['orig']` : [0, 0, 0]
- `d_example['cells']` : a numpy array of size nframes x 3 x 3
- `d_example['coords']` : a numpy array of size nframes x natoms x 3
It is noted that
- The order of frames stored in `'atom_types'`, `'cells'` and `'coords'` should be consistent.
- The order of atoms in **all** frames of `'atom_types'` and `'coords'` should be consistent.
Restrictions:
- `d_example['orig']` is always [0, 0, 0]
- `d_example['cells'][ii]` is always lower triangular (lammps cell tensor convention)
Attributes
----------
DTYPES : tuple[DataType, ...]
data types of this class
"""
DTYPES: tuple[DataType, ...] = (
DataType("atom_numbs", list, (Axis.NTYPES,)),
DataType("atom_names", list, (Axis.NTYPES,)),
DataType("atom_types", np.ndarray, (Axis.NATOMS,)),
DataType("orig", np.ndarray, (3,)),
DataType("cells", np.ndarray, (Axis.NFRAMES, 3, 3), deepmd_name="box"),
DataType(
"coords", np.ndarray, (Axis.NFRAMES, Axis.NATOMS, 3), deepmd_name="coord"
),
DataType(
"real_atom_types", np.ndarray, (Axis.NFRAMES, Axis.NATOMS), required=False
),
DataType("real_atom_names", list, (Axis.NTYPES,), required=False),
DataType("nopbc", bool, required=False),
)
def __init__(
self,
# some formats do not use string as input
file_name: Any = None,
fmt: str = "auto",
type_map: list[str] | None = None,
begin: int = 0,
step: int = 1,
data: dict[str, Any] | None = None,
convergence_check: bool = True,
**kwargs,
):
"""Constructor.
Parameters
----------
file_name : str
The file to load the system
fmt : str
Format of the file, supported formats are
- ``auto``: infered from `file_name`'s extension
- ``lammps/lmp``: Lammps data
- ``lammps/dump``: Lammps dump
- ``deepmd/raw``: deepmd-kit raw
- ``deepmd/npy``: deepmd-kit compressed format (numpy binary)
- ``vasp/poscar``: vasp POSCAR
- ``vasp/contcar``: vasp contcar
- ``vasp/string``: vasp string
- ``vasp/outcar``: vasp outcar
- ``vasp/xml``: vasp xml
- ``qe/cp/traj``: Quantum Espresso CP trajectory files. should have: file_name+'.in' and file_name+'.pos'
- ``qe/pw/scf``: Quantum Espresso PW single point calculations. Both input and output files are required. If file_name is a string, it denotes the output file name. Input file name is obtained by replacing 'out' by 'in' from file_name. Or file_name is a list, with the first element being the input file name and the second element being the output filename.
- ``abacus/scf``: ABACUS pw/lcao scf. The directory containing INPUT file is required.
- ``abacus/md``: ABACUS pw/lcao MD. The directory containing INPUT file is required.
- ``abacus/relax``: ABACUS pw/lcao relax or cell-relax. The directory containing INPUT file is required.
- ``abacus/stru``: abacus stru
- ``abacus/lcao/scf``: abacus lcao scf
- ``abacus/pw/scf``: abacus pw scf
- ``abacus/lcao/md``: abacus lcao md
- ``abacus/pw/md``: abacus pw md
- ``abacus/lcao/relax``: abacus lcao relax
- ``abacus/pw/relax``: abacus pw relax
- ``siesta/output``: siesta SCF output file
- ``siesta/aimd_output``: siesta aimd output file
- ``pwmat/atom.config``: pwmat atom.config
- ``pwmat/movement``: pwmat movement
- ``pwmat/output``: pwmat output
- ``pwmat/mlmd``: pwmat mlmd
- ``pwmat/final.config``: pwmat final.config
- ``quip/gap/xyz_file``: quip gap xyz_file
- ``quip/gap/xyz``: quip gap xyz
- ``fhi_aims/output``: fhi_aims output
- ``fhi_aims/md``: fhi_aims md
- ``fhi_aims/scf``: fhi_aims scf
- ``pymatgen/structure``: pymatgen structure
- ``pymatgen/molecule``: pymatgen molecule
- ``pymatgen/computedstructureentry``: pymatgen computedstructureentry
- ``amber/md``: amber md
- ``sqm/out``: sqm out
- ``sqm/in``: sqm in
- ``ase/structure``: ase structure
- ``gaussian/log``: gaussian log
- ``gaussian/md``: gaussian md
- ``gaussian/gjf``: gaussian gjf
- ``deepmd/comp``: deepmd comp
- ``deepmd/hdf5``: deepmd hdf5
- ``gromacs/gro``: gromacs gro
- ``cp2k/aimd_output``: cp2k aimd_output
- ``cp2k/output``: cp2k output
type_map : list of str
Needed by formats lammps/lmp and lammps/dump. Maps atom type to name. The atom with type `ii` is mapped to `type_map[ii]`.
If not provided the atom names are assigned to `'Type_1'`, `'Type_2'`, `'Type_3'`...
begin : int
The beginning frame when loading MD trajectory.
step : int
The number of skipped frames when loading MD trajectory.
data : dict
The raw data of System class.
convergence_check : boolean
Whether to request a convergence check.
**kwargs : dict
other parameters
"""
self.data = {}
self.data["atom_numbs"] = []
self.data["atom_names"] = []
self.data["atom_types"] = []
self.data["orig"] = np.array([0, 0, 0])
self.data["cells"] = []
self.data["coords"] = []
if data:
self.data = data
self.check_data()
return
if file_name is None:
return
self.from_fmt(
file_name,
fmt,
type_map=type_map,
begin=begin,
step=step,
convergence_check=convergence_check,
**kwargs,
)
if type_map is not None:
self.apply_type_map(type_map)
def check_data(self):
"""Check if data is correct.
Raises
------
DataError
if data is not correct
"""
if not isinstance(self.data, dict):
raise DataError("data is not a dict!")
for dd in self.DTYPES:
dd.check(self)
if sum(self.get_atom_numbs()) != self.get_natoms():
raise DataError(
"Sum of atom_numbs (%d) is not equal to natoms (%d)." # noqa: UP031
% (sum(self.get_atom_numbs()), self.get_natoms())
)
post_funcs = Plugin()
def from_fmt(self, file_name: Any, fmt: str = "auto", **kwargs: Any):
fmt = fmt.lower()
if fmt == "auto":
fmt = os.path.basename(file_name).split(".")[-1].lower()
return self.from_fmt_obj(load_format(fmt), file_name, **kwargs)
def from_fmt_obj(self, fmtobj: Format, file_name: Any, **kwargs: Any):
data = fmtobj.from_system(file_name, **kwargs)
if data:
if isinstance(data, (list, tuple)):
for dd in data:
self.append(System(data=dd))
else:
self.data = {**self.data, **data}
self.check_data()
if hasattr(fmtobj.from_system, "post_func"):
for post_f in fmtobj.from_system.post_func: # type: ignore
self.post_funcs.get_plugin(post_f)(self)
return self
def to(self, fmt: str, *args: Any, **kwargs: Any) -> System:
"""Dump systems to the specific format.
Parameters
----------
fmt : str
format
*args
arguments
**kwargs
keyword arguments
Returns
-------
System
self
"""
return self.to_fmt_obj(load_format(fmt), *args, **kwargs)
def to_fmt_obj(self, fmtobj: Format, *args: Any, **kwargs: Any):
return fmtobj.to_system(self.data, *args, **kwargs)
def __repr__(self):
return self.__str__()
def __str__(self):
ret = "Data Summary"
ret += "\nUnlabeled System"
ret += "\n-------------------"
ret += "\nFrame Numbers : %d" % self.get_nframes() # noqa: UP031
ret += "\nAtom Numbers : %d" % self.get_natoms() # noqa: UP031
ret += "\nElement List :"
ret += "\n-------------------"
ret += "\n" + " ".join(map(str, self.get_atom_names()))
ret += "\n" + " ".join(map(str, self.get_atom_numbs()))
return ret
@overload
def __getitem__(self, key: int | slice | list | np.ndarray) -> System: ...
@overload
def __getitem__(
self, key: Literal["atom_names", "real_atom_names"]
) -> list[str]: ...
@overload
def __getitem__(self, key: Literal["atom_numbs"]) -> list[int]: ...
@overload
def __getitem__(self, key: Literal["nopbc"]) -> bool: ...
@overload
def __getitem__(
self, key: Literal["orig", "coords", "energies", "forces", "virials"]
) -> np.ndarray: ...
@overload
def __getitem__(self, key: str) -> Any:
# other cases, for example customized data
...
def __getitem__(self, key):
"""Returns proerty stored in System by key or by idx."""
if isinstance(key, (int, slice, list, np.ndarray)):
return self.sub_system(key)
return self.data[key]
def __len__(self) -> int:
"""Returns number of frames in the system."""
return self.get_nframes()
def __add__(self, others):
"""Magic method "+" operation."""
self_copy = self.copy()
if isinstance(others, System):
other_copy = others.copy()
self_copy.append(other_copy)
elif isinstance(others, list):
for ii in others:
assert isinstance(ii, System)
ii_copy = ii.copy()
self_copy.append(ii_copy)
else:
raise RuntimeError("Unspported data structure")
return self.__class__.from_dict({"data": self_copy.data})
def dump(self, filename: str, indent: int = 4):
"""Dump .json or .yaml file."""
from monty.serialization import dumpfn
dumpfn(self.as_dict(), filename, indent=indent)
def map_atom_types(
self, type_map: dict[str, int] | list[str] | None = None
) -> np.ndarray:
"""Map the atom types of the system.
Parameters
----------
type_map
dict : {"H":0,"O":1}
or list ["H","C","O","N"]
The map between elements and index
if no map_dict is given, index will
be set according to atomic number
Returns
-------
new_atom_types : np.ndarray
The mapped atom types
"""
if isinstance(type_map, dict) or type_map is None:
pass
elif isinstance(type_map, list):
type_map = dict(zip(type_map, range(len(type_map))))
else:
raise RuntimeError("Unknown format")
if type_map is None:
type_map = elements_index_map(self.get_atom_names().copy(), standard=True)
_set1 = set(self.get_atom_names())
_set2 = set(list(type_map.keys()))
assert _set1.issubset(_set2)
atom_types_list = []
for name, numb in zip(self.get_atom_names(), self.get_atom_numbs()):
atom_types_list.extend([name] * numb)
new_atom_types = np.array([type_map[ii] for ii in atom_types_list], dtype=int)
return new_atom_types
@staticmethod
def load(filename: str):
"""Rebuild System obj. from .json or .yaml file."""
from monty.serialization import loadfn
return loadfn(filename)
@classmethod
def from_dict(cls, data: dict):
"""Construct a System instance from a data dict."""
from monty.serialization import MontyDecoder # type: ignore
decoded = {
k: MontyDecoder().process_decoded(v)
for k, v in data.items()
if not k.startswith("@")
}
return cls(**decoded)
def as_dict(self) -> dict:
"""Returns data dict of System instance."""
d = {
"@module": self.__class__.__module__,
"@class": self.__class__.__name__,
"data": self.data,
}
return d
def get_atom_names(self) -> list[str]:
"""Returns name of atoms."""
return self.data["atom_names"]
def get_atom_types(self) -> np.ndarray:
"""Returns type of atoms."""
return self.data["atom_types"]
def get_atom_numbs(self) -> list[int]:
"""Returns number of atoms."""
return self.data["atom_numbs"]
def get_nframes(self) -> int:
"""Returns number of frames in the system."""
return len(self.data["cells"])
def get_natoms(self) -> int:
"""Returns total number of atoms in the system."""
return len(self.data["atom_types"])
def get_ntypes(self) -> int:
"""Returns total number of atom types in the system."""
return len(self.data["atom_names"])
def copy(self):
"""Returns a copy of the system."""
return self.__class__.from_dict({"data": deepcopy(self.data)})
def sub_system(self, f_idx: int | slice | list | np.ndarray):
"""Construct a subsystem from the system.
Parameters
----------
f_idx : int or index
Which frame to use in the subsystem
Returns
-------
sub_system : System
The subsystem
"""
tmp = self.__class__()
# convert int to array_like
if isinstance(f_idx, numbers.Integral):
f_idx = np.array([f_idx])
assert not isinstance(f_idx, int)
for tt in self.DTYPES:
if tt.name not in self.data:
# skip optional data
continue
if tt.shape is not None and Axis.NFRAMES in tt.shape:
axis_nframes = tt.shape.index(Axis.NFRAMES)
new_shape: list[slice | np.ndarray | list] = [
slice(None) for _ in self.data[tt.name].shape
]
new_shape[axis_nframes] = f_idx
tmp.data[tt.name] = self.data[tt.name][tuple(new_shape)]
else:
# keep the original data
tmp.data[tt.name] = self.data[tt.name]
return tmp
def append(self, system: System) -> bool:
"""Append a system to this system.
Parameters
----------
system : System
The system to append
"""
if not len(system.data["atom_numbs"]):
# skip if the system to append is non-converged
return False
elif not len(self.data["atom_numbs"]):
# this system is non-converged but the system to append is converged
self.data = system.data.copy()
return False
if system.uniq_formula != self.uniq_formula:
raise RuntimeError(
f"systems with inconsistent formula could not be append: {self.uniq_formula} v.s. {system.uniq_formula}"
)
if system.data["atom_names"] != self.data["atom_names"]:
# prevent original system to be modified
system = system.copy()
# allow to append a system with different atom_names order
system.sort_atom_names()
self.sort_atom_names()
if (system.data["atom_types"] != self.data["atom_types"]).any():
# prevent original system to be modified
system = system.copy()
# allow to append a system with different atom_types order
system.sort_atom_types()
self.sort_atom_types()
for ii in ["atom_numbs", "atom_names"]:
assert system.data[ii] == self.data[ii]
for ii in ["atom_types", "orig"]:
eq = [v1 == v2 for v1, v2 in zip(system.data[ii], self.data[ii])]
assert all(eq)
for tt in self.DTYPES:
# check if the first shape is nframes
if tt.shape is not None and Axis.NFRAMES in tt.shape:
if tt.name not in self.data and tt.name in system.data:
raise RuntimeError(f"system has {tt.name}, but this does not")
elif tt.name in self.data and tt.name not in system.data:
raise RuntimeError(f"this has {tt.name}, but system does not")
elif tt.name not in self.data and tt.name not in system.data:
# skip if both not exist
continue
# concat any data in nframes axis
axis_nframes = tt.shape.index(Axis.NFRAMES)
self.data[tt.name] = np.concatenate(
(self.data[tt.name], system[tt.name]), axis=axis_nframes
)
if self.nopbc and not system.nopbc:
# appended system uses PBC, cancel nopbc
self.data["nopbc"] = False
return True
def convert_to_mixed_type(self, type_map: list[str] | None = None):
"""Convert the data dict to mixed type format structure, in order to append systems
with different formula but the same number of atoms. Change the 'atom_names' to
one placeholder type 'MIXED_TOKEN' and add 'real_atom_types' to store the real type
vectors according to the given type_map.
Parameters
----------
type_map : list
type_map
"""
if "real_atom_types" in self.data.keys():
return
if type_map is None:
type_map = self.get_atom_names()
type_index = [type_map.index(i) for i in self.data["atom_names"]]
frames = self.get_nframes()
self.data["real_atom_types"] = np.tile(
np.array([type_index[i] for i in self.data["atom_types"]]), [frames, 1]
)
self.data["real_atom_names"] = type_map
natoms = self.get_natoms()
self.data["atom_types"] = np.zeros((natoms,), dtype=int)
self.data["atom_numbs"] = [natoms]
self.data["atom_names"] = ["MIXED_TOKEN"]
def sort_atom_names(self, type_map: list[str] | None = None):
"""Sort atom_names of the system and reorder atom_numbs and atom_types accoarding
to atom_names. If type_map is not given, atom_names will be sorted by
alphabetical order. If type_map is given, atom_names will be type_map.
Parameters
----------
type_map : list
type_map
"""
self.data = sort_atom_names(self.data, type_map=type_map)
def check_type_map(self, type_map: list[str] | None):
"""Assign atom_names to type_map if type_map is given and different from
atom_names.
Parameters
----------
type_map : list
type_map
"""
if type_map is not None and type_map != self.data["atom_names"]:
self.sort_atom_names(type_map=type_map)
def apply_type_map(self, type_map: list[str]):
"""Customize the element symbol order and it should maintain order
consistency in dpgen or deepmd-kit. It is especially recommended
for multiple complexsystems with multiple elements.
Parameters
----------
type_map : list
type_map
"""
if type_map is not None and isinstance(type_map, list):
self.check_type_map(type_map)
else:
raise RuntimeError("invalid type map, cannot be applied")
def sort_atom_types(self) -> np.ndarray:
"""Sort atom types.
Returns
-------
idx : np.ndarray
new atom index in the Axis.NATOMS
"""
idx = np.argsort(self.data["atom_types"], kind="stable")
for tt in self.DTYPES:
if tt.name not in self.data:
# skip optional data
continue
if tt.shape is not None and Axis.NATOMS in tt.shape:
axis_natoms = tt.shape.index(Axis.NATOMS)
new_shape: list[slice | np.ndarray] = [
slice(None) for _ in self.data[tt.name].shape
]
new_shape[axis_natoms] = idx
self.data[tt.name] = self.data[tt.name][tuple(new_shape)]
return idx
@property
def formula(self) -> str:
"""Return the formula of this system, like C3H5O2."""
return "".join(
[
f"{symbol}{numb}"
for symbol, numb in zip(
self.data["atom_names"], self.data["atom_numbs"]
)
]
)
@property
def uniq_formula(self) -> str:
"""Return the uniq_formula of this system.
The uniq_formula sort the elements in formula by names.
Systems with the same uniq_formula can be append together.
"""
return "".join(
[
f"{symbol}{numb}"
for symbol, numb in sorted(
zip(self.data["atom_names"], self.data["atom_numbs"])
)
]
)
@property
def short_formula(self) -> str:
"""Return the short formula of this system. Elements with zero number
will be removed.
"""
return "".join(
[
f"{symbol}{numb}"
for symbol, numb in zip(
self.data["atom_names"], self.data["atom_numbs"]
)
if numb
]
)
@property
def formula_hash(self) -> str:
"""Return the hash of the formula of this system."""
return hashlib.sha256(self.formula.encode("utf-8")).hexdigest()
@property
def short_name(self) -> str:
"""Return the short name of this system (no more than 255 bytes), in
the following order:
- formula
- short_formula
- formula_hash.
"""
formula = self.formula
if utf8len(formula) <= 255:
return formula
short_formula = self.short_formula
if utf8len(short_formula) <= 255:
return short_formula
return self.formula_hash
def extend(self, systems: Iterable[System]):
"""Extend a system list to this system.
Parameters
----------
systems : [System1, System2, System3 ]
The list to extend
"""
for system in systems:
self.append(system.copy())
def apply_pbc(self):
"""Append periodic boundary condition."""
ncoord = dpdata.md.pbc.dir_coord(self.data["coords"], self.data["cells"])
ncoord = ncoord % 1
self.data["coords"] = np.matmul(ncoord, self.data["cells"])
@post_funcs.register("remove_pbc")
def remove_pbc(self, protect_layer: int = 9):
"""This method does NOT delete the definition of the cells, it
(1) revises the cell to a cubic cell and ensures that the cell
boundary to any atom in the system is no less than `protect_layer`
(2) translates the system such that the center-of-geometry of the system
locates at the center of the cell.
Parameters
----------
protect_layer : the protect layer between the atoms and the cell
boundary
"""
assert protect_layer >= 0, "the protect_layer should be no less than 0"
remove_pbc(self.data, protect_layer)
def affine_map(self, trans, f_idx: int | numbers.Integral = 0):
assert np.linalg.det(trans) != 0
self.data["cells"][f_idx] = np.matmul(self.data["cells"][f_idx], trans)
self.data["coords"][f_idx] = np.matmul(self.data["coords"][f_idx], trans)
@post_funcs.register("shift_orig_zero")
def _shift_orig_zero(self):
for ff in self.data["coords"]:
for ii in ff:
ii = ii - self.data["orig"]
self.data["orig"] = self.data["orig"] - self.data["orig"]
assert (np.zeros([3]) == self.data["orig"]).all()
@post_funcs.register("rot_lower_triangular")
def rot_lower_triangular(self):
for ii in range(self.get_nframes()):
self.rot_frame_lower_triangular(ii)
def rot_frame_lower_triangular(self, f_idx: int | numbers.Integral = 0):
qq, rr = np.linalg.qr(self.data["cells"][f_idx].T)
if np.linalg.det(qq) < 0:
qq = -qq
rr = -rr
self.affine_map(qq, f_idx=f_idx)
rot = np.eye(3)
if self.data["cells"][f_idx][0][0] < 0:
rot[0][0] = -1
if self.data["cells"][f_idx][1][1] < 0:
rot[1][1] = -1
if self.data["cells"][f_idx][2][2] < 0:
rot[2][2] = -1
assert np.linalg.det(rot) == 1
self.affine_map(rot, f_idx=f_idx)
return np.matmul(qq, rot)
def add_atom_names(self, atom_names: list[str]):
"""Add atom_names that do not exist."""
self.data = add_atom_names(self.data, atom_names)
def replicate(self, ncopy: list[int] | tuple[int, int, int]):
"""Replicate the each frame in the system in 3 dimensions.
Each frame in the system will become a supercell.
Parameters
----------
ncopy
list: [4,2,3]
or tuple: (4,2,3,)
make `ncopy[0]` copys in x dimensions,
make `ncopy[1]` copys in y dimensions,
make `ncopy[2]` copys in z dimensions.
Returns
-------
tmp : System
The system after replication.
"""
if len(ncopy) != 3:
raise RuntimeError("ncopy must be a list or tuple with 3 int")
for ii in ncopy:
if not isinstance(ii, int):
raise RuntimeError("ncopy must be a list or tuple must with 3 int")
tmp = System()
nframes = self.get_nframes()
data = self.data
tmp.data["atom_names"] = list(np.copy(data["atom_names"]))
tmp.data["atom_numbs"] = list(
np.array(np.copy(data["atom_numbs"])) * np.prod(ncopy)
)
tmp.data["atom_types"] = np.tile(
np.copy(data["atom_types"]), (int(np.prod(ncopy)),) + (1,)
)
tmp.data["atom_types"] = np.transpose(tmp.data["atom_types"]).reshape([-1])
tmp.data["cells"] = np.copy(data["cells"])
for ii in range(3):
tmp.data["cells"][:, ii, :] *= ncopy[ii]
tmp.data["coords"] = np.tile(np.copy(data["coords"]), tuple(ncopy) + (1, 1, 1))
for xx in range(ncopy[0]):
for yy in range(ncopy[1]):
for zz in range(ncopy[2]):
tmp.data["coords"][xx, yy, zz, :, :, :] += (
xx * np.reshape(data["cells"][:, 0, :], [-1, 1, 3])
+ yy * np.reshape(data["cells"][:, 1, :], [-1, 1, 3])
+ zz * np.reshape(data["cells"][:, 2, :], [-1, 1, 3])
)
tmp.data["coords"] = np.reshape(
np.transpose(tmp.data["coords"], [3, 4, 0, 1, 2, 5]), (nframes, -1, 3)
)
return tmp
def replace(self, initial_atom_type: str, end_atom_type: str, replace_num: int):
if type(self) is not dpdata.System:
raise RuntimeError(
"Must use method replace() of the instance of class dpdata.System"
)
if not isinstance(replace_num, int):
raise ValueError(f"replace_num must be a integer. Now is {replace_num}")
if replace_num <= 0:
raise ValueError(f"replace_num must be larger than 0.Now is {replace_num}")
try:
initial_atom_index = self.data["atom_names"].index(initial_atom_type)
except ValueError as e:
raise ValueError(
"atom_type {initial_atom_type} not in {atom_names}".format(
initial_atom_type=initial_atom_type,
atom_names=self.data["atom_names"],
)
)
max_replace_num = self.data["atom_numbs"][initial_atom_index]
if replace_num > max_replace_num:
raise RuntimeError(
f"not enough {initial_atom_type} atom, only {max_replace_num} available, less than {replace_num}.Please check."
)
may_replace_indices = [
i for i, x in enumerate(self.data["atom_types"]) if x == initial_atom_index
]
to_replace_indices = np.random.choice(
may_replace_indices, size=replace_num, replace=False
)
if end_atom_type not in self.data["atom_names"]:
self.data["atom_names"].append(end_atom_type)
self.data["atom_numbs"].append(0)
end_atom_index = self.data["atom_names"].index(end_atom_type)
for ii in to_replace_indices:
self.data["atom_types"][ii] = end_atom_index
self.data["atom_numbs"][initial_atom_index] -= replace_num
self.data["atom_numbs"][end_atom_index] += replace_num
self.sort_atom_types()
def perturb(
self,
pert_num: int,
cell_pert_fraction: float,
atom_pert_distance: float,
atom_pert_style: str = "normal",
atom_pert_prob: float = 1.0,
):
"""Perturb each frame in the system randomly.
The cell will be deformed randomly, and atoms will be displaced by a random distance in random direction.
Parameters
----------
pert_num : int
Each frame in the system will make `pert_num` copies,
and all the copies will be perturbed.
That means the system to be returned will contain `pert_num` * frame_num of the input system.
cell_pert_fraction : float
A fraction determines how much (relatively) will cell deform.
The cell of each frame is deformed by a symmetric matrix perturbed from identity.
The perturbation to the diagonal part is subject to a uniform distribution in [-cell_pert_fraction, cell_pert_fraction),
and the perturbation to the off-diagonal part is subject to a uniform distribution in [-0.5*cell_pert_fraction, 0.5*cell_pert_fraction).
atom_pert_distance : float
unit: Angstrom. A distance determines how far atoms will move.
Atoms will move about `atom_pert_distance` in random direction.
The distribution of the distance atoms move is determined by atom_pert_style
atom_pert_style : str
Determines the distribution of the distance atoms move is subject to.
Avaliable options are
- `'normal'`: the `distance` will be object to `chi-square distribution with 3 degrees of freedom` after normalization.
The mean value of the distance is `atom_pert_fraction*side_length`
- `'uniform'`: will generate uniformly random points in a 3D-balls with radius as `atom_pert_distance`.
These points are treated as vector used by atoms to move.
Obviously, the max length of the distance atoms move is `atom_pert_distance`.
- `'const'`: The distance atoms move will be a constant `atom_pert_distance`.
atom_pert_prob : float
Determine the proportion of the total number of atoms in a frame that are perturbed.
Returns
-------
perturbed_system : System
The perturbed_system. It contains `pert_num` * frame_num of the input system frames.
"""
if type(self) is not dpdata.System:
raise RuntimeError(
f"Using method perturb() of an instance of {type(self)}. "
f"Must use method perturb() of the instance of class dpdata.System."
)
perturbed_system = System()
nframes = self.get_nframes()
for ii in range(nframes):
for jj in range(pert_num):
tmp_system = self[ii].copy()
cell_perturb_matrix = get_cell_perturb_matrix(cell_pert_fraction)
tmp_system.data["cells"][0] = np.matmul(
tmp_system.data["cells"][0], cell_perturb_matrix
)
tmp_system.data["coords"][0] = np.matmul(
tmp_system.data["coords"][0], cell_perturb_matrix
)
pert_natoms = int(atom_pert_prob * len(tmp_system.data["coords"][0]))
pert_atom_id = sorted(
np.random.choice(
range(len(tmp_system.data["coords"][0])),
pert_natoms,
replace=False,
).tolist()
)
for kk in pert_atom_id:
atom_perturb_vector = get_atom_perturb_vector(
atom_pert_distance, atom_pert_style
)
tmp_system.data["coords"][0][kk] += atom_perturb_vector
tmp_system.rot_lower_triangular()
perturbed_system.append(tmp_system)
return perturbed_system
@property
def nopbc(self):
if self.data.get("nopbc", False):
return True
return False
@nopbc.setter
def nopbc(self, value: bool):
self.data["nopbc"] = value
def shuffle(self):
"""Shuffle frames randomly."""
idx = np.random.permutation(self.get_nframes())
self.data = self.sub_system(idx).data
return idx
def predict(
self, *args: Any, driver: str | Driver = "dp", **kwargs: Any
) -> LabeledSystem:
"""Predict energies and forces by a driver.
Parameters
----------
*args : iterable
Arguments passing to the driver
driver : str, default=dp
The assigned driver. For compatibility, default is dp
**kwargs : dict
Other arguments passing to the driver
Returns
-------
labeled_sys : LabeledSystem
A new labeled system.
Examples
--------
The default driver is DP:
>>> labeled_sys = ori_sys.predict("frozen_model_compressed.pb")
"""
if not isinstance(driver, Driver):
driver = Driver.get_driver(driver)(*args, **kwargs)
data = driver.label(self.data.copy())
return LabeledSystem(data=data)
def minimize(
self, *args: Any, minimizer: str | Minimizer, **kwargs: Any
) -> LabeledSystem:
"""Minimize the geometry.
Parameters
----------
*args : iterable
Arguments passing to the minimizer
minimizer : str or Minimizer
The assigned minimizer
**kwargs : dict
Other arguments passing to the minimizer
Returns
-------
labeled_sys : LabeledSystem
A new labeled system.
"""
if not isinstance(minimizer, Minimizer):
minimizer = Minimizer.get_minimizer(minimizer)(*args, **kwargs)
data = minimizer.minimize(self.data.copy())
return LabeledSystem(data=data)
def pick_atom_idx(
self,
idx: int | numbers.Integral | list[int] | slice | np.ndarray,
nopbc: bool | None = None,
):
"""Pick atom index.
Parameters
----------
idx : int or list or slice
atom index