Skip to content

Commit 8176b17

Browse files
committedApr 7, 2024
format codes
1 parent 455ccf9 commit 8176b17

File tree

1 file changed

+61
-48
lines changed

1 file changed

+61
-48
lines changed
 

‎src/gdpx/utils/command.py

+61-48
Original file line numberDiff line numberDiff line change
@@ -12,20 +12,18 @@
1212
import json
1313
import yaml
1414

15-
import numpy as np
1615

17-
18-
def dict2str(d: dict, indent: int=2):
16+
def dict2str(d: dict, indent: int = 2):
1917
"""Convert a nested dict to str."""
2018

2119
def _dict2str(d_: dict, indent_: int):
2220
"""Recursive function."""
2321
content = ""
2422
for k, v in d_.items():
2523
if isinstance(v, dict):
26-
content += f"{k}:\n" + _dict2str(v, indent_+indent)
24+
content += f"{k}:\n" + _dict2str(v, indent_ + indent)
2725
else:
28-
content += " "*indent_ + f"{k}: {v}\n"
26+
content += " " * indent_ + f"{k}: {v}\n"
2927

3028
return content
3129

@@ -34,49 +32,57 @@ def _dict2str(d_: dict, indent_: int):
3432
return content
3533

3634

37-
class CustomTimer():
35+
class CustomTimer:
3836

3937
def __init__(self, name="code", func=print):
4038
""""""
4139
self.name = name
4240
self._print = func
4341

4442
return
45-
43+
4644
def __call__(self, func) -> Any:
4745
""""""
4846

4947
def func_timer(*args, **kwargs):
5048
st = time.time()
5149
ret = func(*args, **kwargs)
5250
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+
)
5454
self._print(content)
5555

5656
return ret
5757

5858
return func_timer
5959

60-
6160
def __enter__(self):
6261
""""""
63-
self.st = time.time() # start time
62+
self.st = time.time() # start time
6463

6564
return self
66-
65+
6766
def __exit__(self, *args):
6867
""""""
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+
)
7277
self._print(content)
7378

7479
return
7580

81+
7682
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?
8086
"""
8187
target_dir = Path(target_dir)
8288
if not target_dir.exists():
@@ -86,26 +92,31 @@ def check_path(target_dir: Union[str, Path]) -> bool:
8692

8793
return
8894

95+
8996
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
9299
"""
93100
dpath = Path(dpath)
94101
fpath = dpath / fname
95102
if not fpath.exists():
96103
raise FileNotFoundError(f"fpath does not exist.")
97104

98-
backups = list(dpath.glob(prefix+".[0-9]*."+fname))
105+
backups = list(dpath.glob(prefix + ".[0-9]*." + fname))
99106
backups = sorted(backups, key=lambda x: int(x.name.split(".")[1]))
100107
backups.append(fpath)
101108

102109
return backups
103110

111+
104112
def run_command(directory, command, comment="", timeout=None):
105113
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",
109120
)
110121
if timeout is None:
111122
errorcode = proc.wait()
@@ -115,20 +126,21 @@ def run_command(directory, command, comment="", timeout=None):
115126
msg = "Message: " + "".join(proc.stdout.readlines())
116127
print(msg)
117128
if errorcode:
118-
raise RuntimeError("Error in %s at %s." %(comment, directory))
119-
129+
raise RuntimeError("Error in %s at %s." % (comment, directory))
130+
120131
return msg
121132

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
132144
"""
133145
ret = []
134146
if isinstance(indices, str):
@@ -140,9 +152,9 @@ def convert_indices(indices: Union[str,List[int]], index_convention="lmp"):
140152
else:
141153
start, end = cur_range
142154
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))])
144156
elif index_convention == "py":
145-
ret.extend(list(range(start,end)))
157+
ret.extend(list(range(start, end)))
146158
else:
147159
pass
148160
elif isinstance(indices, list):
@@ -151,17 +163,17 @@ def convert_indices(indices: Union[str,List[int]], index_convention="lmp"):
151163
if index_convention == "lmp":
152164
pass
153165
elif index_convention == "py":
154-
indices = [i+1 for i in indices]
166+
indices = [i + 1 for i in indices]
155167
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]))
161173
if group[0] == group[-1]:
162174
ret.append(str(group[0]))
163175
else:
164-
ret.append("{}:{}".format(group[0],group[-1]))
176+
ret.append("{}:{}".format(group[0], group[-1]))
165177
ret = " ".join(ret)
166178
else:
167179
pass
@@ -171,11 +183,11 @@ def convert_indices(indices: Union[str,List[int]], index_convention="lmp"):
171183

172184
def parse_input_file(
173185
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
175187
):
176188
""""""
177189
input_dict = None
178-
190+
179191
# - parse input type
180192
if isinstance(input_fpath, dict):
181193
input_dict = input_fpath
@@ -203,7 +215,7 @@ def parse_input_file(
203215
except FileNotFoundError as e:
204216
# NOTE: There is json or yaml in the string but it is not a file though.
205217
input_dict = None
206-
218+
207219
# NOTE: recursive read internal json or yaml files
208220
if input_dict is not None:
209221
for key, value in input_dict.items():
@@ -212,11 +224,12 @@ def parse_input_file(
212224
input_dict[key] = key_dict
213225

214226
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:
216228
json.dump(input_dict, fopen, indent=4)
217229
print("See params.json for values of all parameters...")
218230

219231
return input_dict
220232

233+
221234
if __name__ == "__main__":
222235
...

0 commit comments

Comments
 (0)
Please sign in to comment.