pwdata 0.3.2__tar.gz → 0.3.4__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.

Potentially problematic release.


This version of pwdata might be problematic. Click here for more details.

Files changed (71) hide show
  1. {pwdata-0.3.2 → pwdata-0.3.4}/PKG-INFO +1 -1
  2. {pwdata-0.3.2 → pwdata-0.3.4}/pwdata/build/write_struc.py +1 -1
  3. pwdata-0.3.4/pwdata/check_envs.py +51 -0
  4. pwdata-0.3.2/pwdata/main.py → pwdata-0.3.4/pwdata/config.py +4 -61
  5. pwdata-0.3.4/pwdata/convert_files.py +347 -0
  6. pwdata-0.3.4/pwdata/datasets_saver.py +190 -0
  7. {pwdata-0.3.2 → pwdata-0.3.4}/pwdata/deepmd.py +3 -3
  8. pwdata-0.3.4/pwdata/extendedxyz.py +196 -0
  9. pwdata-0.3.4/pwdata/fairchem/common/__init__.py +6 -0
  10. pwdata-0.3.4/pwdata/fairchem/common/registry.py +296 -0
  11. pwdata-0.3.4/pwdata/fairchem/common/typing.py +19 -0
  12. pwdata-0.3.4/pwdata/fairchem/common/utils.py +758 -0
  13. pwdata-0.3.4/pwdata/fairchem/datasets/__init__.py +23 -0
  14. pwdata-0.3.4/pwdata/fairchem/datasets/_utils.py +40 -0
  15. pwdata-0.3.4/pwdata/fairchem/datasets/ase_datasets.py +569 -0
  16. pwdata-0.3.4/pwdata/fairchem/datasets/base_dataset.py +140 -0
  17. pwdata-0.3.4/pwdata/fairchem/datasets/embeddings/__init__.py +13 -0
  18. pwdata-0.3.4/pwdata/fairchem/datasets/embeddings/atomic_radii.py +111 -0
  19. pwdata-0.3.4/pwdata/fairchem/datasets/embeddings/continuous_embeddings.py +1122 -0
  20. pwdata-0.3.4/pwdata/fairchem/datasets/embeddings/khot_embeddings.py +9414 -0
  21. pwdata-0.3.4/pwdata/fairchem/datasets/embeddings/qmof_khot_embeddings.py +7638 -0
  22. pwdata-0.3.4/pwdata/fairchem/datasets/lmdb_database.py +357 -0
  23. pwdata-0.3.4/pwdata/fairchem/datasets/target_metadata_guesser.py +192 -0
  24. pwdata-0.3.4/pwdata/fairchem/modules/__init__.py +6 -0
  25. pwdata-0.3.4/pwdata/fairchem/modules/transforms.py +38 -0
  26. pwdata-0.3.4/pwdata/fairchem/preprocessing/__init__.py +7 -0
  27. {pwdata-0.3.2 → pwdata-0.3.4}/pwdata/image.py +8 -2
  28. {pwdata-0.3.2 → pwdata-0.3.4}/pwdata/lammpsdata.py +1 -1
  29. pwdata-0.3.4/pwdata/main.py +473 -0
  30. pwdata-0.3.4/pwdata/meta.py +121 -0
  31. {pwdata-0.3.2 → pwdata-0.3.4}/pwdata/movement_saver.py +1 -1
  32. pwdata-0.3.4/pwdata/pertub/__init__.py +0 -0
  33. pwdata-0.3.4/pwdata/test/__init__.py +0 -0
  34. pwdata-0.3.4/pwdata/test.py +164 -0
  35. pwdata-0.3.4/pwdata/utils/__init__.py +0 -0
  36. pwdata-0.3.4/pwdata/utils/constant.py +128 -0
  37. {pwdata-0.3.2 → pwdata-0.3.4}/pwdata.egg-info/PKG-INFO +1 -1
  38. pwdata-0.3.4/pwdata.egg-info/SOURCES.txt +64 -0
  39. pwdata-0.3.4/pwdata.egg-info/entry_points.txt +2 -0
  40. pwdata-0.3.4/pwdata.egg-info/requires.txt +8 -0
  41. {pwdata-0.3.2 → pwdata-0.3.4}/setup.py +16 -1
  42. pwdata-0.3.2/pwdata/check_envs.py +0 -5
  43. pwdata-0.3.2/pwdata/datasets_saver.py +0 -188
  44. pwdata-0.3.2/pwdata/extendedxyz.py +0 -102
  45. pwdata-0.3.2/pwdata/test.py +0 -18
  46. pwdata-0.3.2/pwdata.egg-info/SOURCES.txt +0 -37
  47. {pwdata-0.3.2 → pwdata-0.3.4}/LICENSE +0 -0
  48. {pwdata-0.3.2 → pwdata-0.3.4}/README.md +0 -0
  49. {pwdata-0.3.2 → pwdata-0.3.4}/pwdata/__init__.py +0 -0
  50. {pwdata-0.3.2 → pwdata-0.3.4}/pwdata/atomconfig.py +0 -0
  51. {pwdata-0.3.2 → pwdata-0.3.4}/pwdata/build/__init__.py +0 -0
  52. {pwdata-0.3.2 → pwdata-0.3.4}/pwdata/build/cell.py +0 -0
  53. {pwdata-0.3.2 → pwdata-0.3.4}/pwdata/build/geometry.py +0 -0
  54. {pwdata-0.3.2 → pwdata-0.3.4}/pwdata/build/supercells.py +0 -0
  55. {pwdata-0.3.2 → pwdata-0.3.4}/pwdata/calculators/__init__.py +0 -0
  56. {pwdata-0.3.2 → pwdata-0.3.4}/pwdata/calculators/const.py +0 -0
  57. {pwdata-0.3.2 → pwdata-0.3.4}/pwdata/calculators/unitconvert_lmps.py +0 -0
  58. {pwdata-0.3.2 → pwdata-0.3.4}/pwdata/calculators/units.py +0 -0
  59. {pwdata-0.3.2 → pwdata-0.3.4}/pwdata/cp2kdata.py +0 -0
  60. {pwdata-0.3.2 → pwdata-0.3.4}/pwdata/dump.py +0 -0
  61. {pwdata-0.3.2/pwdata/pertub → pwdata-0.3.4/pwdata/fairchem}/__init__.py +0 -0
  62. {pwdata-0.3.2 → pwdata-0.3.4}/pwdata/lmps.py +0 -0
  63. {pwdata-0.3.2 → pwdata-0.3.4}/pwdata/movement.py +0 -0
  64. {pwdata-0.3.2 → pwdata-0.3.4}/pwdata/outcar.py +0 -0
  65. {pwdata-0.3.2 → pwdata-0.3.4}/pwdata/pertub/perturbation.py +0 -0
  66. {pwdata-0.3.2 → pwdata-0.3.4}/pwdata/pertub/scale.py +0 -0
  67. {pwdata-0.3.2 → pwdata-0.3.4}/pwdata/poscar.py +0 -0
  68. {pwdata-0.3.2 → pwdata-0.3.4}/pwdata/pwmlff.py +0 -0
  69. {pwdata-0.3.2 → pwdata-0.3.4}/pwdata.egg-info/dependency_links.txt +0 -0
  70. {pwdata-0.3.2 → pwdata-0.3.4}/pwdata.egg-info/top_level.txt +0 -0
  71. {pwdata-0.3.2 → pwdata-0.3.4}/setup.cfg +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.1
2
2
  Name: pwdata
3
- Version: 0.3.2
3
+ Version: 0.3.4
4
4
  Summary: pwdata is a data pre-processing tool for PWMLFF, which can be used to extract features and labels. It also provides convenient interfaces for data conversion between different software.
5
5
  Home-page: https://github.com/LonxunQuantum/pwdata
6
6
  Author: LonxunQuantum
@@ -20,7 +20,7 @@ def write_config(image,
20
20
  positions scaled coordinates (Direct), and constraints
21
21
  to file. fractional coordinates is default.
22
22
  """
23
- assert direct==True, "PWmat only support direct coordinates"
23
+ # assert direct==True, "PWmat only support direct coordinates"
24
24
  atom_nums = len(image) if image.atom_nums is None else image.atom_nums
25
25
  if isinstance(image, (list, tuple)):
26
26
  if atom_nums > 1:
@@ -0,0 +1,51 @@
1
+ def print_cmd():
2
+ cmd_infos()
3
+
4
+ def cmd_infos():
5
+ info = ""
6
+ info += "In functional development, please refer to the link\n\t\thttp://doc.lonxun.com/PWMLFF/Appendix-2/\n"
7
+
8
+ info += "scale_cell or scale:\n"
9
+ info += "\tScaling the structural lattice, the command example:\n"
10
+ info += "\tscale_cell -r 0.98 0.99 0.97 0.95 -i lisi_atom.config -f pwmat/config -s scale_atom.config -o pwmat/config\n"
11
+ info += "\t\nYou can also use 'pwdata scale_cell -h' to obtain a more detailed parameter list\n\n"
12
+
13
+ info += "super_cell or super:\n"
14
+ info += "\tConstruct a supercell based on the input original structure and supercell matrix, the command example:\n"
15
+ info += "\tpwdata super_cell -i input_file -f input_file_format -n output_format_name -o output_format\n"
16
+ info += "\tYou can also use 'pwdata super_cell -h' to obtain a more detailed parameter list\n\n"
17
+
18
+ info += "perturb:\n"
19
+ info += "\tDisturb the atomic positions and unit cells of the structure, the command example:\n"
20
+ info += "\tpwdata perturb -e 0.01 -d 0.04 -n 20 -i LiSi_POSCAR -f vasp/poscar -s perturb_lammps -o lammps/lmp -c\n\n"
21
+ info += "\tYou can also use 'pwdata perturb -h' to obtain a more detailed parameter list\n\n"
22
+
23
+ info += "convert_config or cvt_config:\n"
24
+ info += "\tTransferring structural files between different apps(PWmat\VASP\CP2K\Lammps), the command example:\n"
25
+ info += "\tpwdata cvt_config -i LiSi_POSCAR -f vasp/poscar -s cvtcnf_lammps.lmp -o lammps/lmp -c\n\n"
26
+ info += "\tYou can also use 'pwdata convert_config -h' to obtain a more detailed parameter list\n\n"
27
+
28
+ info += "convert_configs or cvt_configs:\n"
29
+ info += "\tExtract various trajectory files(movement of PWmat, outcar of Vasp, lammps/dump of Lammps, cp2k-mdfile of CP2K) or data sets (deepmd/npy, deepmd/raw, extxyz, meta aselmdb) into pwmlff/npy or extxyz format, the command example:\n"
30
+ info += "\tpwdata convert_images -i input_file1 input_file2 ... input_filen -f input_file_format -n output_format_name -o output_format\n\n"
31
+
32
+ info += "format suppport\n"
33
+ info += "__________________________________________________________________________________________|\n"
34
+ info += "| Software | file | multi-Image | label | format |\n"
35
+ info += "| ----------------- | ---------------- | ----------- | ----- | -------------------------- |\n"
36
+ info += "| PWmat | MOVEMENT | True | True | 'pwmat/movement' |\n"
37
+ info += "| PWmat | OUT.MLMD | False | True | 'pwmat/movement' |\n"
38
+ info += "| PWmat | atom.config | False | False | 'pwmat/config' |\n"
39
+ info += "| VASP | OUTCAR | True | True | 'vasp/outcar' |\n"
40
+ info += "| VASP | poscar | False | False | 'vasp/poscar' |\n"
41
+ info += "| LAMMPS | lmp.init | False | False | 'lammps/lmp' |\n"
42
+ info += "| LAMMPS | dump | True | False | 'lammps/dump' |\n"
43
+ info += "| CP2K | stdout, xyz, pdb | True | True | 'cp2k/md' |\n"
44
+ info += "| CP2K | stdout | False | True | 'cp2k/scf' |\n"
45
+ info += "| PWMLFF | \*.npy | True | True | 'pwmlff/npy' |\n"
46
+ info += "| DeepMD (read) | \*.npy, \*.raw | True | True | 'deepmd/npy', 'deepmd/raw' |\n"
47
+ info += "| \* (extended xyz) | \*.xyz | True | True | 'extxyz' |\n"
48
+ info += "| \* (meta aselmdb) | \*.aselmdb | True | True | 'meta' |\n"
49
+ info += "__________________________________________________________________________________________|\n\n"
50
+
51
+ print(info)
@@ -19,6 +19,7 @@ from pwdata.movement_saver import save_to_movement
19
19
  from pwdata.extendedxyz import EXTXYZ, save_to_extxyz
20
20
  from pwdata.datasets_saver import save_to_dataset, get_pw, save_to_raw, save_to_npy
21
21
  from pwdata.build.write_struc import write_config, write_vasp, write_lammps
22
+ from pwdata.meta import META
22
23
 
23
24
  class Save_Data(object):
24
25
  def __init__(self, data_path, datasets_path = "./PWdata", train_data_path = "train", valid_data_path = "valid",
@@ -188,6 +189,8 @@ class Config(object):
188
189
  image = DPRAW(data_path).image_list[index]
189
190
  elif format.lower() == 'pwmlff/npy':
190
191
  image = PWNPY(data_path).image_list[index]
192
+ elif format.lower() == 'meta':
193
+ image = META(data_path, atom_names, **kwargs).image_list[index]
191
194
  else:
192
195
  raise Exception("Error! The format of the input file is not supported!")
193
196
  return image
@@ -277,64 +280,4 @@ def string2index(string: str) -> Union[int, slice, str]:
277
280
  else:
278
281
  i.append(int(s))
279
282
  i += (3 - len(i)) * [None]
280
- return slice(*i)
281
-
282
- def run_cmd():
283
- from check_envs import print_cmd
284
- if len(sys.argv) == 1 or "-h".upper() == sys.argv[1].upper() or \
285
- "help".upper() == sys.argv[1].upper() or "-help".upper() == sys.argv[1].upper() or "--help".upper() == sys.argv[1].upper():
286
- print_cmd()
287
-
288
- elif "convert_config".upper() == sys.argv[1].upper():
289
- pass
290
-
291
-
292
- if __name__ == "__main__":
293
- # import argparse
294
- # SUPERCELL_MATRIX = [[2, 0, 0], [0, 2, 0], [0, 0, 2]]
295
- # data_file = "/data/home/hfhuang/2_MLFF/2-DP/19-json-version/8-Si2/atom.config"
296
- # # data_file = "/data/home/hfhuang/9_cp2k/1-SiO2/cp2k.out"
297
- # # data_file = "/data/home/hfhuang/software/mlff/Si/Si64-vasprun.xml"
298
- # # data_file = "/data/home/hfhuang/2_MLFF/3-outcar2movement/0/OUTCARC3N4"
299
- # output_path = "/data/home/hfhuang/2_MLFF/2-DP/19-json-version/8-Si2/mlff/"
300
- # output_file = "supercell.config"
301
- # format = "config"
302
- # pbc = [1, 1, 1]
303
- # # config = Config.read(format, data_file, atom_names=["Si"], index=-1) # read dump
304
- # config = Config.read(format, data_file)
305
- # Config.to(file_path = output_path,
306
- # file_name = output_file,
307
- # file_format = 'config',
308
- # direct = True,
309
- # sort = False)
310
- # parser = argparse.ArgumentParser(description='Convert and build structures.')
311
- # parser.add_argument('--format', type=str, required=False, help='Format of the input file', default="outcar")
312
- # parser.add_argument('--save_format', type=str, required=False, help='Format of the output file', default="config")
313
- # parser.add_argument('--outcar_file', type=str, required=False, help='Path to the OUTCAR file')
314
- # parser.add_argument('--movement_file', type=str, required=False, help='Path to the MOVEMENT file')
315
- # parser.add_argument('--output_path', type=str, required=False, help='Path to the output directory', default="./")
316
- # parser.add_argument('--output_file', type=str, required=False, help='Name of the output file', default="MOVEMENT")
317
- # parser.add_argument('--supercell_matrix', type=list, required=False, help='Supercell matrix', default=[[1, 0, 0], [0, 1, 0], [0, 0, 1]])
318
- # parser.add_argument('--pbc', type=list, required=False, help='Periodic boundary conditions flags', default=[1, 1, 1])
319
- # parser.add_argument('--direct', type=bool, required=False, help='Whether to write the positions in direct (frac) coordinates', default=True)
320
- # parser.add_argument('--sort', type=bool, required=False, help='Whether to sort the atoms by atomic number', default=True)
321
- # parser.add_argument('--pert_num', type=int, required=False, help='Number of perturbed structures', default=50)
322
- # parser.add_argument('--cell_pert_fraction', type=float, required=False, help='Fraction of the cell perturbation', default=0.03)
323
- # parser.add_argument('--atom_pert_distance', type=float, required=False, help='Distance of the atom perturbation', default=0.01)
324
- # parser.add_argument('--retain_raw', type=bool, required=False, help='Whether to retain raw data', default=False)
325
- # parser.add_argument('--train_ratio', type=float, required=False, help='Ratio of training data', default=0.8)
326
- # parser.add_argument('--random', type=bool, required=False, help='Whether to shuffle the data', default=True)
327
- # parser.add_argument('--scale_factor', type=float, required=False, help='Scale factor of the lattice', default=1.0)
328
- # parser.add_argument('--seed', type=int, required=False, help='Random seed', default=2024)
329
- # parser.add_argument('--index', type=Union[int, slice, str], required=False, help='Index of the configuration', default=-1)
330
- # parser.add_argument('--atom_names', type=list, required=False, help='Names of the atoms', default=["H"])
331
- # parser.add_argument('--style', type=str, required=False, help='Style of the lammps input file', default="atomic")
332
-
333
- # args = parser.parse_args()
334
-
335
- run_cmd()
336
-
337
- config = Config.read("vasp/outcar",
338
- "/data/home/wuxingxing/datas/al_dir/si_4_vasp/init_bulk/temp_init_bulk_work/aimd/init_config_0/0.9_scale/3_aimd/OUTCAR")
339
- print()
340
-
283
+ return slice(*i)
@@ -0,0 +1,347 @@
1
+ import os
2
+ import sys
3
+ import numpy as np
4
+ from pwdata.config import Config
5
+ from pwdata.build.supercells import make_supercell
6
+ from pwdata.pertub.perturbation import perturb_structure
7
+ from pwdata.pertub.scale import scale_cell
8
+ from pwdata.utils.constant import FORMAT, ELEMENTTABLE, get_atomic_name_from_number
9
+ from pwdata.image import Image
10
+ from collections import Counter
11
+ from ase.db.row import AtomsRow
12
+ from pwdata.fairchem.datasets.ase_datasets import AseDBDataset
13
+ from concurrent.futures import ProcessPoolExecutor, as_completed
14
+ import multiprocessing
15
+
16
+ def do_convert_config(input_file:str,
17
+ input_format:str,
18
+ atom_types:list[str],
19
+ savename:str,
20
+ output_format:str,
21
+ direct:bool = True): # True: save as fractional coordinates, False for cartesian coordinates
22
+ image = Config(data_path=input_file, format=input_format, atom_names=atom_types)
23
+ image.to(output_path = os.path.dirname(os.path.abspath(savename)),
24
+ data_name = os.path.basename(savename),
25
+ save_format = output_format,
26
+ direct = direct,
27
+ sort = True)
28
+ return os.path.abspath(savename)
29
+
30
+ def do_scale_cell(input_file:str,
31
+ input_format:str,
32
+ atom_types:list[str],
33
+ savename:str,
34
+ output_format:str,
35
+ scale_factor:list[float],
36
+ direct:bool = True): # True: save as fractional coordinates, False for cartesian coordinates
37
+ # for pwamt/movement movement or MLMD.OUT files
38
+ if not isinstance(scale_factor, list):
39
+ scale_factor = [scale_factor]
40
+ image = Config(data_path=input_file, format=input_format, atom_names=atom_types)
41
+ for idx, factor in enumerate(scale_factor):
42
+ scaled_structs = scale_cell(image, factor)
43
+ scaled_structs.to(output_path = os.path.dirname(os.path.abspath(savename)),
44
+ data_name = "{}_{}".format(factor, os.path.basename(savename)),
45
+ save_format = output_format,
46
+ direct = direct,
47
+ sort = True)
48
+ return os.path.abspath(savename)
49
+
50
+ def do_super_cell(input_file:str,
51
+ input_format:str,
52
+ atom_types:list[str],
53
+ savename:str,
54
+ output_format:str,
55
+ supercell_matrix:list[int],
56
+ direct:bool = True,
57
+ pbc:list =[1, 1, 1],
58
+ wrap=True,
59
+ tol=1e-5
60
+ ): # True: save as fractional coordinates, False for cartesian coordinates
61
+ # for pwamt/movement movement or MLMD.OUT files
62
+ image = Config(data_path=input_file, format=input_format, atom_names=atom_types)
63
+ scaled_structs = make_supercell(image, supercell_matrix, pbc=pbc, wrap=wrap, tol=tol)
64
+ scaled_structs.to(output_path = os.path.dirname(os.path.abspath(savename)),
65
+ data_name = os.path.basename(savename),
66
+ save_format = output_format,
67
+ direct = direct,
68
+ sort = True)
69
+ return os.path.abspath(savename)
70
+
71
+ def do_perturb(input_file:str,
72
+ input_format:str,
73
+ atom_types:list[str],
74
+ save_path:str,
75
+ save_name_prefix:str,
76
+ output_format:str,
77
+ cell_pert_fraction:float,
78
+ atom_pert_distance:float,
79
+ pert_num:int,
80
+ direct:bool = True
81
+ ): # True: save as fractional coordinates, False for cartesian coordinates
82
+ # for pwamt/movement movement or MLMD.OUT files
83
+ image = Config(data_path=input_file, format=input_format, atom_names=atom_types)
84
+ save_path = os.path.abspath(save_path)
85
+ perturbed_structs = perturb_structure(
86
+ image_data = image,
87
+ pert_num = pert_num,
88
+ cell_pert_fraction = cell_pert_fraction,
89
+ atom_pert_distance = atom_pert_distance)
90
+
91
+ perturb_files = []
92
+ for tmp_perturbed_idx, tmp_pertubed_struct in enumerate(perturbed_structs):
93
+ tmp_pertubed_struct.to(output_path = save_path,
94
+ data_name = "{}_{}".format(tmp_perturbed_idx, save_name_prefix),
95
+ save_format = output_format,
96
+ direct = direct,
97
+ sort = True)
98
+ perturb_files.append("{}_{}".format(tmp_perturbed_idx, save_name_prefix))
99
+ return perturb_files, perturbed_structs
100
+
101
+ def do_convert_images(
102
+ input:list[str],
103
+ input_format:str,
104
+ savepath, #'the/path/pwmlff-datas'
105
+ output_format,
106
+ train_valid_ratio,
107
+ data_shuffle,
108
+ gap,
109
+ atom_types:list[str]=None,
110
+ query:str=None,
111
+ cpu_nums:int=None,
112
+ merge:bool=True
113
+ ):
114
+ data_files = search_images(input, input_format)
115
+ image_data = load_files(data_files, input_format, atom_types=atom_types, query=query, cpu_nums=cpu_nums)
116
+ save_images(savepath, image_data, output_format, train_valid_ratio, data_shuffle, merge)
117
+
118
+ '''
119
+ description:
120
+ save the image_datas to pwmlff/npy or extxyz format
121
+ for pwmlff/npy, the images will save to subdir accordding to the atom types and atom nums of each type, such as Pb20Te30, Pb21Te30, ...
122
+ for extxyz, the images will save to subdir accordding to the atom types, such as PbTe, PbTeG
123
+ param {*} savepath
124
+ param {*} image_data
125
+ param {*} output_format
126
+ param {*} train_valid_ratio
127
+ param {*} data_shuffle
128
+ return {*}
129
+ author: wuxingxing
130
+ '''
131
+ def save_images(savepath, image_data, output_format, train_valid_ratio=1, data_shuffle=False, merge=True):
132
+ if merge is True and output_format == FORMAT.extxyz:
133
+ save_dir = savepath
134
+ image_data.to(
135
+ output_path=save_dir,
136
+ save_format=output_format,
137
+ train_ratio = train_valid_ratio,
138
+ random=data_shuffle,
139
+ seed = 2024,
140
+ retain_raw = False,
141
+ write_patthen="a"
142
+ )
143
+ else:
144
+ save_dict = split_image_by_atomtype_nums(image_data, format=output_format)
145
+ for key, images in save_dict.items():
146
+ # print(len(images))
147
+ save_dir = os.path.join(savepath, key) if output_format==FORMAT.extxyz else savepath #pwmlff/npy will do split when saving images
148
+ image_data.images = images
149
+ image_data.to(
150
+ output_path=save_dir,
151
+ save_format=output_format,
152
+ train_ratio = train_valid_ratio,
153
+ random=data_shuffle,
154
+ seed = 2024,
155
+ retain_raw = False,
156
+ write_patthen="a"
157
+ )
158
+
159
+ def search_images(input_list:list[str], input_format:str):
160
+ res_list = set()
161
+ for workDir in input_list:
162
+ workDir = os.path.abspath(workDir)
163
+ if os.path.isfile(workDir):
164
+ res_list.add(workDir)
165
+ else:
166
+ if input_format == FORMAT.pwmlff_npy:
167
+ for root, dirs, files in os.walk(workDir):
168
+ if 'energies.npy' in files:
169
+ if "train" in os.path.basename(root):
170
+ res_list.add(os.path.dirname(root))
171
+
172
+ elif input_format == FORMAT.extxyz:
173
+ for path, dirList, fileList in os.walk(workDir, followlinks=True):
174
+ for _ in fileList:
175
+ if ".xyz" in _:
176
+ res_list.add(os.path.join(path, _))
177
+
178
+ elif input_format == FORMAT.deepmd_npy:
179
+ for root, dirs, files in os.walk(workDir):
180
+ if 'energy.npy' in files:
181
+ res_list.add(os.path.dirname(root))
182
+
183
+ elif input_format == FORMAT.deepmd_raw:
184
+ for root, dirs, files in os.walk(workDir):
185
+ if 'energy.raw' in files:
186
+ res_list.add(os.path.dirname(root))
187
+
188
+ elif input_format == FORMAT.meta:
189
+ for root, dirs, files in os.walk(workDir):
190
+ for file in files:
191
+ if '.aselmdb' in file:
192
+ res_list.add(root)
193
+ break
194
+
195
+ return list(res_list)
196
+
197
+ def load_files(input_list:list[str], input_format:str, atom_types:list[str]=None, query:str=None, cpu_nums=None):
198
+ image_data = None
199
+ if input_format == FORMAT.meta:
200
+ image_data = Config(input_format, input_list, atom_names=atom_types, query=query, cpu_nums=cpu_nums)
201
+ if not isinstance(image_data.images, list): # for the first pwmlff/npy dir only has one picture
202
+ image_data.images = [image_data.images]
203
+ else:
204
+ for data_path in input_list:
205
+ if image_data is not None:
206
+ tmp_config = Config(input_format, data_path, atom_names=atom_types, query=query, cpu_nums=cpu_nums)
207
+ image_data.append(tmp_config)
208
+ else:
209
+ image_data = Config(input_format, data_path, atom_names=atom_types, query=query, cpu_nums=cpu_nums)
210
+ if not isinstance(image_data.images, list): # for the first pwmlff/npy dir only has one picture
211
+ image_data.images = [image_data.images]
212
+ return image_data
213
+
214
+ def split_image_by_atomtype_nums(image_data, format=None):
215
+ key_dict = {}
216
+ for idx, image in enumerate(image_data.images):
217
+ element_counts = Counter(image.atom_types_image)
218
+ atom_type = list(element_counts.keys())
219
+ counts = list(element_counts.values())
220
+ tmp_key = ""
221
+ for element, count in zip(atom_type, counts):
222
+ tmp_key += "{}_{}_".format(element, count)
223
+ if tmp_key not in key_dict:
224
+ key_dict[tmp_key] = [image]
225
+ else:
226
+ key_dict[tmp_key].append(image)
227
+
228
+ new_split = {}
229
+ for key in key_dict.keys():
230
+ elements = key.split('_')[:-1]
231
+ new_array = [int(elements[i]) for i in range(0, len(elements), 2)]
232
+ type_nums = elements[1::2]
233
+ atom_list = get_atomic_name_from_number(new_array)
234
+ new_key = []
235
+ if format == FORMAT.extxyz:
236
+ new_key = "".join(atom_list)
237
+ if new_key not in new_split:
238
+ new_split[new_key] = key_dict[key]
239
+ else:
240
+ new_split[new_key].extend(key_dict[key])
241
+ else: # for pwmlff/npy
242
+ for atom, num in zip(atom_list, type_nums):
243
+ new_key.append(atom)
244
+ new_key.append(num)
245
+ new_key = "".join(new_key)
246
+ new_split[new_key] = key_dict[key]
247
+ return new_split
248
+
249
+ def make_query(elements:list[str]):
250
+ # 这个闭包函数将捕获 elements 参数
251
+ def query(row):
252
+ if sorted(set(row.symbols)) == sorted(elements):
253
+ return True
254
+ return False
255
+ return query
256
+
257
+ def do_meta_data(input,
258
+ savepath,
259
+ output_format,
260
+ train_valid_ratio,
261
+ split_rand,
262
+ atom_types:list[str]=None,
263
+ query_str:str=None,
264
+ cpu_nums:int=None):
265
+ image_data = load_meta_datas(input, atom_types, query_str, cpu_nums)
266
+ save_images(savepath, image_data, output_format, train_valid_ratio, split_rand)
267
+
268
+ def load_meta_datas(input, atom_types: list[str] = None, query_str: str = None, cpu_nums: int=None):
269
+ search_dict = {'src': input}
270
+ dataset = AseDBDataset(config=search_dict)
271
+ image_list = []
272
+ for ids, dbs in enumerate(dataset.dbs):
273
+ if query_str is None and atom_types is None:
274
+ atom_list = list(dbs.select())
275
+ elif query_str is None and atom_types is not None:
276
+ atom_list = list(dbs.select("".join(atom_types)))
277
+ elif query_str is not None and atom_types is not None:
278
+ atom_list = list(dbs.select(query_str,filter=make_query))
279
+ else:# query_str is not None and atom_types is None:
280
+ atom_list = list(dbs.select(query_str))
281
+ for Atoms in atom_list:
282
+ image = to_image(Atoms)
283
+ image_list.append(image)
284
+ image_data = Config()
285
+ image_data.images = image_list
286
+ return image_data
287
+
288
+ ### ProcessPoolExecutor
289
+ def load_meta_datas_cpus(input, atom_types: list[str] = None, query_str: str = None, cpu_nums: int=None):
290
+ search_dict = {'src': input}
291
+ dataset = AseDBDataset(config=search_dict)
292
+ image_list = []
293
+ # 定义一个辅助函数,用于查询和转换每个数据库中的数据
294
+ def process_dbs(dbs):
295
+ # 根据条件构建 atom_list
296
+ if query_str is None and atom_types is None:
297
+ atom_list = list(dbs.select())
298
+ elif query_str is None and atom_types is not None:
299
+ atom_list = list(dbs.select("".join(atom_types)))
300
+ elif query_str is not None and atom_types is not None:
301
+ atom_list = list(dbs.select(query_str, filter=make_query))
302
+ else:
303
+ atom_list = list(dbs.select(query_str))
304
+ # 对每个原子对象进行转换并返回 image 列表
305
+ return [to_image(Atoms) for Atoms in atom_list]
306
+
307
+ # 使用多进程并行处理每个子数据库
308
+ if cpu_nums is None:
309
+ cpu_nums = multiprocessing.cpu_count()
310
+ with ProcessPoolExecutor(max_workers=cpu_nums) as executor:
311
+ futures = [executor.submit(process_dbs, dbs) for dbs in dataset.dbs]
312
+ for future in as_completed(futures):
313
+ image_list.extend(future.result())
314
+
315
+ image_data = Config()
316
+ image_data.images = image_list
317
+ return image_data
318
+
319
+ def to_image(Atoms):
320
+ image = Image()
321
+ image.formula = Atoms.formula
322
+ image.pbc = Atoms.pbc
323
+ image.atom_nums = Atoms.natoms
324
+ type_nums_dict = Counter(Atoms.numbers)
325
+ image.atom_type = np.array(list(type_nums_dict.keys()))
326
+ image.atom_type_num = np.array(list(type_nums_dict.values()))
327
+ image.atom_types_image = np.array(Atoms.numbers)
328
+ image.lattice = np.array(Atoms.cell)
329
+ image.position = Atoms.positions
330
+ image.cartesian = True
331
+ image.force = Atoms.forces
332
+ image.Ep = Atoms.energy
333
+
334
+ # 计算 Atomic-Energy
335
+ atomic_energy, _, _, _ = np.linalg.lstsq([image.atom_type_num], np.array([image.Ep]), rcond=1e-3)
336
+ atomic_energy = np.repeat(atomic_energy, image.atom_type_num)
337
+ image.atomic_energy = atomic_energy.tolist()
338
+
339
+ vol = Atoms.volume
340
+ virial = (-np.array(Atoms.stress) * vol)
341
+ image.virial = np.array([
342
+ [virial[0], virial[5], virial[4]],
343
+ [virial[5], virial[1], virial[3]],
344
+ [virial[4], virial[3], virial[2]]
345
+ ])
346
+ image.format = 'metadata'
347
+ return image