forked from stfc/aiida-mlip
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathconverters.py
100 lines (83 loc) · 2.74 KB
/
converters.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
"""Some helpers to convert between different formats."""
from pathlib import Path
from typing import Union
from aiida.orm import Bool, Dict, Str, StructureData, TrajectoryData, load_code
from ase.io import read
import numpy as np
from aiida_mlip.helpers.help_load import load_model, load_structure
def convert_numpy(dictionary: dict) -> dict:
"""
Convert numpy ndarrays in dictionary into lists.
Parameters
----------
dictionary : dict
A dictionary with numpy array values to be converted into lists.
Returns
-------
dict
Converted dictionary.
"""
new_dict = dictionary.copy()
for key, value in new_dict.items():
if isinstance(value, np.ndarray):
new_dict[key] = value.tolist()
return new_dict
def xyz_to_aiida_traj(
traj_file: Union[str, Path],
) -> tuple[StructureData, TrajectoryData]:
"""
Convert xyz trajectory file to `TrajectoryData` data type.
Parameters
----------
traj_file : Union[str, Path]
The path to the XYZ file.
Returns
-------
Tuple[StructureData, TrajectoryData]
A tuple containing the last structure in the trajectory and a `TrajectoryData`
object containing all structures from the trajectory.
"""
# Read the XYZ file using ASE
struct_list = read(traj_file, index=":")
# Create a TrajectoryData object
traj = [StructureData(ase=struct) for struct in struct_list]
return traj[-1], TrajectoryData(traj)
def convert_to_nodes(dictionary: dict, convert_all: bool = False) -> dict:
"""
Convert each key of the config file to a aiida node.
Parameters
----------
dictionary : dict
The dictionary obtained from the config file.
convert_all : bool
Define if you want to convert all the parameters or only the main ones.
Returns
-------
dict
Returns the converted dictionary.
"""
new_dict = dictionary.copy()
arch = new_dict["arch"]
conv = {
"code": load_code,
"struct": load_structure,
"model": lambda v: load_model(v, arch),
"arch": Str,
"ensemble": Str,
"opt_cell_fully": Bool,
}
for key, value in new_dict.items():
if key in conv:
value = conv[key](value)
# This is only in the case in which we use the run_from_config function, in that
# case the config file would be made for aiida specifically not for janus
elif convert_all:
if key.endswith("_kwargs") or key.endswith("-kwargs"):
key = key.replace("-kwargs", "_kwargs")
value = Dict(value)
else:
value = Str(value)
else:
continue
new_dict[key] = value
return new_dict