dockonsurf / modules / calculation.py @ 082685ad
Historique | Voir | Annoter | Télécharger (14,97 ko)
1 |
import os |
---|---|
2 |
import logging |
3 |
|
4 |
logger = logging.getLogger('DockOnSurf')
|
5 |
|
6 |
|
7 |
def check_finished_calcs(run_type, code): |
8 |
from modules.utilities import _human_key |
9 |
"""Returns two lists of calculations finished normally and abnormally.
|
10 |
|
11 |
@param run_type: The type of calculation to check.
|
12 |
@param code: The code used for the specified job.
|
13 |
@return finished_calcs: List of calculations that have finished normally.
|
14 |
@return unfinished_calcs: List of calculations that have finished abnormally
|
15 |
"""
|
16 |
from glob import glob |
17 |
import ase.io |
18 |
from pycp2k import CP2K |
19 |
from modules.utilities import tail |
20 |
|
21 |
finished_calcs = [] |
22 |
unfinished_calcs = [] |
23 |
for conf in sorted(os.listdir(run_type), key=_human_key): |
24 |
conf_path = f'{run_type}/{conf}'
|
25 |
if not os.path.isdir(conf_path) or 'conf_' not in conf: |
26 |
continue
|
27 |
if code == 'cp2k': |
28 |
cp2k = CP2K() |
29 |
restart_file_list = glob(f"{conf_path}/*-1.restart")
|
30 |
if len(restart_file_list) == 0: |
31 |
logger.warning(f"No *-1.restart file found on {conf_path}.")
|
32 |
unfinished_calcs.append(conf) |
33 |
continue
|
34 |
elif len(restart_file_list) > 1: |
35 |
warn_msg = f'There is more than one CP2K restart file ' \
|
36 |
f'(*-1.restart / in {conf_path}: ' \
|
37 |
f'{restart_file_list}. Skipping directory.'
|
38 |
unfinished_calcs.append(conf) |
39 |
logger.warning(warn_msg) |
40 |
continue
|
41 |
out_files = [] |
42 |
for file in os.listdir(conf_path): |
43 |
with open(conf_path+"/"+file, "rb") as out_fh: |
44 |
tail_out_str = tail(out_fh) |
45 |
if tail_out_str.count("PROGRAM STOPPED IN") == 1: |
46 |
out_files.append(file)
|
47 |
if len(out_files) > 1: |
48 |
warn_msg = f'There is more than one CP2K output file in ' \
|
49 |
f'{conf_path}: {out_files}. Skipping directory.'
|
50 |
logger.warning(warn_msg) |
51 |
unfinished_calcs.append(conf) |
52 |
elif len(out_files) == 0: |
53 |
warn_msg = f'There is no CP2K output file in {conf_path}. ' \
|
54 |
'Skipping directory.'
|
55 |
logger.warning(warn_msg) |
56 |
unfinished_calcs.append(conf) |
57 |
else:
|
58 |
finished_calcs.append(conf) |
59 |
elif code == 'vasp': |
60 |
out_file_list = glob(f"{conf_path}/OUTCAR")
|
61 |
if len(out_file_list) == 0: |
62 |
unfinished_calcs.append(conf) |
63 |
elif len(out_file_list) > 1: |
64 |
warn_msg = f'There is more than one file matching the {code} ' \
|
65 |
f'pattern for finished calculation (*.out / ' \
|
66 |
f'*-1.restart) in {conf_path}: ' \
|
67 |
f'{out_file_list}. Skipping directory.'
|
68 |
logger.warning(warn_msg) |
69 |
unfinished_calcs.append(conf) |
70 |
else:
|
71 |
try:
|
72 |
ase.io.read(f"{conf_path}/OUTCAR")
|
73 |
except ValueError: |
74 |
unfinished_calcs.append(conf) |
75 |
continue
|
76 |
except IndexError: |
77 |
unfinished_calcs.append(conf) |
78 |
continue
|
79 |
with open(f"{conf_path}/OUTCAR", 'rb') as out_fh: |
80 |
if "General timing and accounting" not in tail(out_fh): |
81 |
unfinished_calcs.append(conf) |
82 |
else:
|
83 |
finished_calcs.append(conf) |
84 |
else:
|
85 |
err_msg = f"Check not implemented for '{code}'."
|
86 |
logger.error(err_msg) |
87 |
raise NotImplementedError(err_msg) |
88 |
return finished_calcs, unfinished_calcs
|
89 |
|
90 |
|
91 |
def prep_cp2k(inp_file: str, run_type: str, atms_list: list, proj_name: str): |
92 |
"""Prepares the directories to run calculations with CP2K.
|
93 |
|
94 |
@param inp_file: CP2K Input file to run the calculations with.
|
95 |
@param run_type: Type of calculation. 'isolated', 'screening' or
|
96 |
'refinement'
|
97 |
@param atms_list: list of ase.Atoms objects to run the calculation of.
|
98 |
@param proj_name: name of the project
|
99 |
@return: None
|
100 |
"""
|
101 |
from shutil import copy |
102 |
from pycp2k import CP2K |
103 |
from modules.utilities import check_bak |
104 |
if not isinstance(inp_file, str): |
105 |
err_msg = "'inp_file' must be a string with the path of the CP2K " \
|
106 |
"input file."
|
107 |
logger.error(err_msg) |
108 |
raise ValueError(err_msg) |
109 |
cp2k = CP2K() |
110 |
cp2k.parse(inp_file) |
111 |
cp2k.CP2K_INPUT.GLOBAL.Project_name = proj_name+"_"+run_type
|
112 |
force_eval = cp2k.CP2K_INPUT.FORCE_EVAL_list[0]
|
113 |
if force_eval.SUBSYS.TOPOLOGY.Coord_file_name is None: |
114 |
logger.warning("'COORD_FILE_NAME' not specified on CP2K input. Using\n"
|
115 |
"'coord.xyz'. A new CP2K input file with "
|
116 |
"the 'COORD_FILE_NAME' variable is created.")
|
117 |
force_eval.SUBSYS.TOPOLOGY.Coord_file_name = 'coord.xyz'
|
118 |
check_bak(inp_file.split('/')[-1]) |
119 |
cp2k.write_input_file(inp_file.split('/')[-1]) |
120 |
|
121 |
coord_file = force_eval.SUBSYS.TOPOLOGY.Coord_file_name |
122 |
|
123 |
# Creating and setting up directories for every configuration.
|
124 |
for i, conf in enumerate(atms_list): |
125 |
subdir = f'{run_type}/conf_{i}/'
|
126 |
os.mkdir(subdir) |
127 |
copy(inp_file, subdir) |
128 |
conf.write(subdir + coord_file) |
129 |
|
130 |
|
131 |
def prep_vasp(inp_files, run_type, atms_list, proj_name, cell, potcar_dir): |
132 |
"""Prepares the directories to run calculations with VASP.
|
133 |
|
134 |
@param inp_files: VASP Input files to run the calculations with.
|
135 |
@param run_type: Type of calculation. 'isolated', 'screening' or
|
136 |
'refinement'
|
137 |
@param atms_list: list of ase.Atoms objects to run the calculation of.
|
138 |
@param proj_name: name of the project.
|
139 |
@param cell: Cell for the Periodic Boundary Conditions.
|
140 |
@param potcar_dir: Directory to find POTCARs for each element.
|
141 |
@return: None
|
142 |
"""
|
143 |
from shutil import copy |
144 |
import os |
145 |
|
146 |
import numpy as np |
147 |
from pymatgen.io.vasp.inputs import Incar |
148 |
|
149 |
if not potcar_dir: |
150 |
mand_files = ["INCAR", "KPOINTS", "POTCAR"] |
151 |
elif any("POTCAR" in inp_file for inp_file in inp_files): |
152 |
mand_files = ["INCAR", "KPOINTS", "POTCAR"] |
153 |
else:
|
154 |
mand_files = ["INCAR", "KPOINTS"] |
155 |
|
156 |
# Check that there are many specified files
|
157 |
if not isinstance(inp_files, list) and all(isinstance(inp_file, str) |
158 |
for inp_file in inp_files): |
159 |
err_msg = "'inp_files' should be a list of file names/paths"
|
160 |
logger.error(err_msg) |
161 |
ValueError(err_msg)
|
162 |
# Check that all mandatory files are defined
|
163 |
elif any(not any(mand_file in inp_file.split("/")[-1] |
164 |
for inp_file in inp_files) for mand_file in mand_files): |
165 |
err_msg = f"At least one of the mandatory files {mand_files} was " \
|
166 |
"not specified."
|
167 |
logger.error(err_msg) |
168 |
raise FileNotFoundError(err_msg)
|
169 |
# Check that the defined files exist
|
170 |
elif any(not os.path.isfile(inp_file) for inp_file in inp_files): |
171 |
err_msg = f"At least one of the mandatory files {mand_files} was " \
|
172 |
"not found."
|
173 |
logger.error(err_msg) |
174 |
raise FileNotFoundError(err_msg)
|
175 |
incar = ""
|
176 |
for i, inp_file in enumerate(inp_files): |
177 |
file_name = inp_file.split("/")[-1] |
178 |
if "INCAR" in file_name: |
179 |
incar = Incar.from_file(inp_file) |
180 |
incar["SYSTEM"] = proj_name+"_"+run_type |
181 |
|
182 |
for c, conf in enumerate(atms_list): |
183 |
subdir = f'{run_type}/conf_{c}/'
|
184 |
os.mkdir(subdir) |
185 |
for inp_file in inp_files: |
186 |
file_name = inp_file.split("/")[-1] |
187 |
if "INCAR" in file_name: |
188 |
incar.write_file(subdir+"INCAR")
|
189 |
elif "KPOINTS" in file_name and "KPOINTS" != file_name: |
190 |
copy(inp_file, subdir+"KPOINTS")
|
191 |
elif "POTCAR" in file_name and "POTCAR" != file_name: |
192 |
copy(inp_file, subdir+"POTCAR")
|
193 |
else:
|
194 |
copy(inp_file, subdir) |
195 |
if cell is not False and np.linalg.det(cell) != 0.0: |
196 |
conf.pbc = True
|
197 |
conf.cell = cell |
198 |
conf.center() |
199 |
elif np.linalg.det(conf.cell) == 0: |
200 |
err_msg = "Cell is not defined"
|
201 |
logger.error(err_msg) |
202 |
raise ValueError(err_msg) |
203 |
conf.write(subdir+"POSCAR", format="vasp") |
204 |
if "POTCAR" not in mand_files and potcar_dir: |
205 |
poscar_fh = open(subdir+"POSCAR", "r") |
206 |
grouped_symbols = poscar_fh.readline().split() |
207 |
poscar_fh.close() |
208 |
for symbol in grouped_symbols: |
209 |
potcar_sym_fh = open(f"{potcar_dir}/{symbol}/POTCAR", "r") |
210 |
potcar_sym_str = potcar_sym_fh.read() |
211 |
potcar_sym_fh.close() |
212 |
potcar_fh = open(subdir+"POTCAR", "a") |
213 |
potcar_fh.write(potcar_sym_str) |
214 |
potcar_fh.close() |
215 |
|
216 |
|
217 |
def get_jobs_status(job_ids, stat_cmd, stat_dict): |
218 |
"""Returns a list of job status for a list of job ids.
|
219 |
|
220 |
@param job_ids: list of all jobs to be checked their status.
|
221 |
@param stat_cmd: Command to check job status.
|
222 |
@param stat_dict: Dictionary with pairs of job status (r, p, f) and the
|
223 |
pattern it matches in the output of the stat_cmd.
|
224 |
@return: list of status for every job.
|
225 |
"""
|
226 |
from subprocess import PIPE, Popen |
227 |
status_list = [] |
228 |
for job in job_ids: |
229 |
stat_msg = Popen(stat_cmd % job, shell=True,
|
230 |
stdout=PIPE).communicate()[0].decode('utf-8').strip() |
231 |
if stat_dict['r'] == stat_msg: |
232 |
status_list.append('r')
|
233 |
elif stat_dict['p'] == stat_msg: |
234 |
status_list.append('p')
|
235 |
elif stat_dict['f'] == stat_msg: |
236 |
status_list.append('f')
|
237 |
else:
|
238 |
logger.warning(f'Unrecognized job {job} status: {stat_msg}')
|
239 |
return status_list
|
240 |
|
241 |
|
242 |
def submit_jobs(run_type, sub_cmd, sub_script, stat_cmd, stat_dict, max_jobs, |
243 |
name): |
244 |
"""Submits jobs to a custom queuing system with the provided script
|
245 |
|
246 |
@param run_type: Type of calculation. 'isolated', 'screening', 'refinement'
|
247 |
@param sub_cmd: Bash command used to submit jobs.
|
248 |
@param sub_script: script for the job submission.
|
249 |
@param stat_cmd: Bash command to check job status.
|
250 |
@param stat_dict: Dictionary with pairs of job status: r, p, f (ie. running
|
251 |
pending and finished) and the pattern it matches in the output of the
|
252 |
stat_cmd.
|
253 |
@param max_jobs: dict: Contains the maximum number of jobs to be both
|
254 |
running, pending/queued and pending+running. When the relevant maximum
|
255 |
is reached no jobs more are submitted.
|
256 |
@param name: name of the project.
|
257 |
"""
|
258 |
from shutil import copy |
259 |
from time import sleep |
260 |
from subprocess import PIPE, Popen |
261 |
from modules.utilities import _human_key |
262 |
subm_jobs = [] |
263 |
init_dir = os.getcwd() |
264 |
for conf in sorted(os.listdir(run_type), key=_human_key): |
265 |
i = conf.split('_')[1] |
266 |
while get_jobs_status(subm_jobs, stat_cmd, stat_dict).count("r") + \ |
267 |
get_jobs_status(subm_jobs, stat_cmd, stat_dict).count("p") \
|
268 |
>= max_jobs['rp']\
|
269 |
or get_jobs_status(subm_jobs, stat_cmd, stat_dict).count("r") \ |
270 |
>= max_jobs['r'] \
|
271 |
or get_jobs_status(subm_jobs, stat_cmd, stat_dict).count("p") \ |
272 |
>= max_jobs['p']:
|
273 |
sleep(30)
|
274 |
copy(sub_script, f"{run_type}/{conf}")
|
275 |
os.chdir(f"{run_type}/{conf}")
|
276 |
job_name = f'{name[:5]}{run_type[:3].capitalize()}{i}'
|
277 |
sub_order = sub_cmd % (job_name, sub_script) |
278 |
subm_msg = Popen(sub_order, shell=True, stdout=PIPE).communicate()[0] |
279 |
job_id = None
|
280 |
for word in subm_msg.decode("utf-8").split(): |
281 |
try:
|
282 |
job_id = int(word.replace('>', '').replace('<', '')) |
283 |
break
|
284 |
except ValueError: |
285 |
continue
|
286 |
subm_jobs.append(job_id) |
287 |
os.chdir(init_dir) |
288 |
|
289 |
logger.info('All jobs have been submitted, waiting for them to finish.')
|
290 |
while not all([stat == 'f' for stat in |
291 |
get_jobs_status(subm_jobs, stat_cmd, stat_dict)]): |
292 |
sleep(30)
|
293 |
logger.info('All jobs have finished.')
|
294 |
|
295 |
|
296 |
def run_calc(run_type, inp_vars, atms_list): |
297 |
"""Directs the calculation run according to the provided arguments.
|
298 |
|
299 |
@param run_type: Type of calculation. 'isolated', 'screening' or
|
300 |
'refinement'
|
301 |
@param inp_vars: Calculation parameters from input file.
|
302 |
@param atms_list: List of ase.Atoms objects containing the sets of atoms
|
303 |
aimed to run the calculations of.
|
304 |
"""
|
305 |
from modules.utilities import check_bak |
306 |
|
307 |
run_types = ['isolated', 'screening', 'refinement'] |
308 |
if not isinstance(run_type, str) or run_type.lower() not in run_types: |
309 |
run_type_err = f"'run_type' must be one of the following: {run_types}"
|
310 |
logger.error(run_type_err) |
311 |
raise ValueError(run_type_err) |
312 |
|
313 |
if inp_vars['batch_q_sys']: |
314 |
logger.info(f"Running {run_type} calculation with {inp_vars['code']} on"
|
315 |
f" {inp_vars['batch_q_sys']}.")
|
316 |
else:
|
317 |
logger.info(f"Doing a dry run of {run_type}.")
|
318 |
check_bak(run_type) |
319 |
os.mkdir(run_type) |
320 |
|
321 |
# Prepare directories and files for relevant code.
|
322 |
input_files = {'isolated': 'isol_inp_file', 'screening': 'screen_inp_file', |
323 |
'refinement': 'refine_inp_file', } |
324 |
if inp_vars['code'] == 'cp2k': |
325 |
prep_cp2k(inp_vars[input_files[run_type]], run_type, atms_list, |
326 |
inp_vars['project_name'])
|
327 |
elif inp_vars['code'] == "vasp": |
328 |
prep_vasp(inp_vars[input_files[run_type]], run_type, atms_list, |
329 |
inp_vars['project_name'], inp_vars['pbc_cell'], |
330 |
inp_vars['potcar_dir'])
|
331 |
# elif: inp_vars['code'] == 'Other codes here'
|
332 |
|
333 |
# Submit/run Jobs
|
334 |
if inp_vars['batch_q_sys'] == 'sge': |
335 |
stat_cmd = "qstat | grep %s | awk '{print $5}'"
|
336 |
stat_dict = {'r': 'r', 'p': 'qw', 'f': ''} |
337 |
submit_jobs(run_type, 'qsub -N %s %s', inp_vars['subm_script'], |
338 |
stat_cmd, stat_dict, inp_vars['max_jobs'],
|
339 |
inp_vars['project_name'])
|
340 |
elif inp_vars['batch_q_sys'] == 'lsf': |
341 |
stat_cmd = "bjobs -w | grep %s | awk '{print $3}'"
|
342 |
stat_dict = {'r': 'RUN', 'p': 'PEND', 'f': ''} |
343 |
submit_jobs(run_type, 'bsub -J %s < %s', inp_vars['subm_script'], |
344 |
stat_cmd, stat_dict, inp_vars['max_jobs'],
|
345 |
inp_vars['project_name'])
|
346 |
elif inp_vars['batch_q_sys'] == 'irene': |
347 |
stat_cmd = "ccc_mstat | grep %s | awk '{print $10}' | cut -c1"
|
348 |
stat_dict = {'r': 'R', 'p': 'P', 'f': ''} |
349 |
submit_jobs(run_type, 'ccc_msub -r %s %s', inp_vars['subm_script'], |
350 |
stat_cmd, stat_dict, inp_vars['max_jobs'],
|
351 |
inp_vars['project_name'])
|
352 |
|
353 |
elif inp_vars['batch_q_sys'] == 'local': |
354 |
pass # TODO implement local |
355 |
elif not inp_vars['batch_q_sys']: |
356 |
pass
|
357 |
else:
|
358 |
err_msg = "Unknown value for 'batch_q_sys'."
|
359 |
logger.error(err_msg) |
360 |
raise ValueError(err_msg) |