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