12
12
import json
13
13
import yaml
14
14
15
- import numpy as np
16
15
17
-
18
- def dict2str (d : dict , indent : int = 2 ):
16
+ def dict2str (d : dict , indent : int = 2 ):
19
17
"""Convert a nested dict to str."""
20
18
21
19
def _dict2str (d_ : dict , indent_ : int ):
22
20
"""Recursive function."""
23
21
content = ""
24
22
for k , v in d_ .items ():
25
23
if isinstance (v , dict ):
26
- content += f"{ k } :\n " + _dict2str (v , indent_ + indent )
24
+ content += f"{ k } :\n " + _dict2str (v , indent_ + indent )
27
25
else :
28
- content += " " * indent_ + f"{ k } : { v } \n "
26
+ content += " " * indent_ + f"{ k } : { v } \n "
29
27
30
28
return content
31
29
@@ -34,49 +32,57 @@ def _dict2str(d_: dict, indent_: int):
34
32
return content
35
33
36
34
37
- class CustomTimer () :
35
+ class CustomTimer :
38
36
39
37
def __init__ (self , name = "code" , func = print ):
40
38
""""""
41
39
self .name = name
42
40
self ._print = func
43
41
44
42
return
45
-
43
+
46
44
def __call__ (self , func ) -> Any :
47
45
""""""
48
46
49
47
def func_timer (* args , ** kwargs ):
50
48
st = time .time ()
51
49
ret = func (* args , ** kwargs )
52
50
et = time .time ()
53
- content = "*** " + self .name + " time: " + "{:>8.4f}" .format (et - st )+ " ***"
51
+ content = (
52
+ "*** " + self .name + " time: " + "{:>8.4f}" .format (et - st ) + " ***"
53
+ )
54
54
self ._print (content )
55
55
56
56
return ret
57
57
58
58
return func_timer
59
59
60
-
61
60
def __enter__ (self ):
62
61
""""""
63
- self .st = time .time () # start time
62
+ self .st = time .time () # start time
64
63
65
64
return self
66
-
65
+
67
66
def __exit__ (self , * args ):
68
67
""""""
69
- self .et = time .time () # end time
70
-
71
- content = "*** " + self .name + " time: " + "{:>8.4f}" .format (self .et - self .st )+ " ***"
68
+ self .et = time .time () # end time
69
+
70
+ content = (
71
+ "*** "
72
+ + self .name
73
+ + " time: "
74
+ + "{:>8.4f}" .format (self .et - self .st )
75
+ + " ***"
76
+ )
72
77
self ._print (content )
73
78
74
79
return
75
80
81
+
76
82
def check_path (target_dir : Union [str , Path ]) -> bool :
77
- """ check path existence, if so skip the following
78
- TODO: add output option
79
- make this into a context?
83
+ """check path existence, if so skip the following
84
+ TODO: add output option
85
+ make this into a context?
80
86
"""
81
87
target_dir = Path (target_dir )
82
88
if not target_dir .exists ():
@@ -86,26 +92,31 @@ def check_path(target_dir: Union[str, Path]) -> bool:
86
92
87
93
return
88
94
95
+
89
96
def find_backups (dpath , fname , prefix = "bak" ):
90
- """ find a series of files in a dir
91
- such as fname, bak.0.fname, bak.1.fname
97
+ """find a series of files in a dir
98
+ such as fname, bak.0.fname, bak.1.fname
92
99
"""
93
100
dpath = Path (dpath )
94
101
fpath = dpath / fname
95
102
if not fpath .exists ():
96
103
raise FileNotFoundError (f"fpath does not exist." )
97
104
98
- backups = list (dpath .glob (prefix + ".[0-9]*." + fname ))
105
+ backups = list (dpath .glob (prefix + ".[0-9]*." + fname ))
99
106
backups = sorted (backups , key = lambda x : int (x .name .split ("." )[1 ]))
100
107
backups .append (fpath )
101
108
102
109
return backups
103
110
111
+
104
112
def run_command (directory , command , comment = "" , timeout = None ):
105
113
proc = subprocess .Popen (
106
- command , shell = True , cwd = directory ,
107
- stdout = subprocess .PIPE , stderr = subprocess .PIPE ,
108
- encoding = "utf-8"
114
+ command ,
115
+ shell = True ,
116
+ cwd = directory ,
117
+ stdout = subprocess .PIPE ,
118
+ stderr = subprocess .PIPE ,
119
+ encoding = "utf-8" ,
109
120
)
110
121
if timeout is None :
111
122
errorcode = proc .wait ()
@@ -115,20 +126,21 @@ def run_command(directory, command, comment="", timeout=None):
115
126
msg = "Message: " + "" .join (proc .stdout .readlines ())
116
127
print (msg )
117
128
if errorcode :
118
- raise RuntimeError ("Error in %s at %s." % (comment , directory ))
119
-
129
+ raise RuntimeError ("Error in %s at %s." % (comment , directory ))
130
+
120
131
return msg
121
132
122
- def convert_indices (indices : Union [str ,List [int ]], index_convention = "lmp" ):
123
- """ parse indices for reading xyz by ase, get start for counting
124
- constrained indices followed by lammps convention
125
- "2:4 3:8"
126
- convert [1,2,3,6,7,8] to "1:3 6:8"
127
- lammps convention starts from 1 and includes end
128
- ---
129
- input can be either py or lmp
130
- output for indices is in py since it can be used to access atoms
131
- output for text is in lmp since it can be used in lammps or sth
133
+
134
+ def convert_indices (indices : Union [str , List [int ]], index_convention = "lmp" ):
135
+ """parse indices for reading xyz by ase, get start for counting
136
+ constrained indices followed by lammps convention
137
+ "2:4 3:8"
138
+ convert [1,2,3,6,7,8] to "1:3 6:8"
139
+ lammps convention starts from 1 and includes end
140
+ ---
141
+ input can be either py or lmp
142
+ output for indices is in py since it can be used to access atoms
143
+ output for text is in lmp since it can be used in lammps or sth
132
144
"""
133
145
ret = []
134
146
if isinstance (indices , str ):
@@ -140,9 +152,9 @@ def convert_indices(indices: Union[str,List[int]], index_convention="lmp"):
140
152
else :
141
153
start , end = cur_range
142
154
if index_convention == "lmp" :
143
- ret .extend ([i - 1 for i in list (range (start ,end + 1 ))])
155
+ ret .extend ([i - 1 for i in list (range (start , end + 1 ))])
144
156
elif index_convention == "py" :
145
- ret .extend (list (range (start ,end )))
157
+ ret .extend (list (range (start , end )))
146
158
else :
147
159
pass
148
160
elif isinstance (indices , list ):
@@ -151,17 +163,17 @@ def convert_indices(indices: Union[str,List[int]], index_convention="lmp"):
151
163
if index_convention == "lmp" :
152
164
pass
153
165
elif index_convention == "py" :
154
- indices = [i + 1 for i in indices ]
166
+ indices = [i + 1 for i in indices ]
155
167
ret = []
156
- #ranges = []
157
- for k , g in groupby (enumerate (indices ),lambda x :x [0 ]- x [1 ]):
158
- group = ( map (itemgetter (1 ),g ) )
159
- group = list (map (int ,group ))
160
- #ranges.append((group[0],group[-1]))
168
+ # ranges = []
169
+ for k , g in groupby (enumerate (indices ), lambda x : x [0 ] - x [1 ]):
170
+ group = map (itemgetter (1 ), g )
171
+ group = list (map (int , group ))
172
+ # ranges.append((group[0],group[-1]))
161
173
if group [0 ] == group [- 1 ]:
162
174
ret .append (str (group [0 ]))
163
175
else :
164
- ret .append ("{}:{}" .format (group [0 ],group [- 1 ]))
176
+ ret .append ("{}:{}" .format (group [0 ], group [- 1 ]))
165
177
ret = " " .join (ret )
166
178
else :
167
179
pass
@@ -171,11 +183,11 @@ def convert_indices(indices: Union[str,List[int]], index_convention="lmp"):
171
183
172
184
def parse_input_file (
173
185
input_fpath : Union [str , Path ],
174
- write_json : bool = False # write readin dict to check if alright
186
+ write_json : bool = False , # write readin dict to check if alright
175
187
):
176
188
""""""
177
189
input_dict = None
178
-
190
+
179
191
# - parse input type
180
192
if isinstance (input_fpath , dict ):
181
193
input_dict = input_fpath
@@ -203,7 +215,7 @@ def parse_input_file(
203
215
except FileNotFoundError as e :
204
216
# NOTE: There is json or yaml in the string but it is not a file though.
205
217
input_dict = None
206
-
218
+
207
219
# NOTE: recursive read internal json or yaml files
208
220
if input_dict is not None :
209
221
for key , value in input_dict .items ():
@@ -212,11 +224,12 @@ def parse_input_file(
212
224
input_dict [key ] = key_dict
213
225
214
226
if input_dict and write_json :
215
- with open (json_path / "params.json" , "w" ) as fopen :
227
+ with open (json_path / "params.json" , "w" ) as fopen :
216
228
json .dump (input_dict , fopen , indent = 4 )
217
229
print ("See params.json for values of all parameters..." )
218
230
219
231
return input_dict
220
232
233
+
221
234
if __name__ == "__main__" :
222
235
...
0 commit comments