Statistiques
| Branche: | Tag: | Révision :

dockonsurf / modules / calculation.py @ ffa1b366

Historique | Voir | Annoter | Télécharger (14,13 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):
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
    @return: None
141
    """
142
    from shutil import copy
143
    import os
144

    
145
    import numpy as np
146
    from pymatgen.io.vasp.inputs import Incar
147

    
148
    mand_files = ["INCAR", "KPOINTS", "POTCAR"]
149
    # Check that there are many specified files
150
    if not isinstance(inp_files, list) and all(isinstance(inp_file, str)
151
                                               for inp_file in inp_files):
152
        err_msg = "'inp_files' should be a list of file names/paths"
153
        logger.error(err_msg)
154
        ValueError(err_msg)
155
    # Check that all mandatory files are defined
156
    elif any(not any(mand_file in inp_file.split("/")[-1]
157
                     for inp_file in inp_files) for mand_file in mand_files):
158
        err_msg = f"At least one of the mandatory files {mand_files} was " \
159
                  "not specified."
160
        logger.error(err_msg)
161
        raise FileNotFoundError(err_msg)
162
    # Check that the defined files exist
163
    elif any(not os.path.isfile(inp_file) for inp_file in inp_files):
164
        err_msg = f"At least one of the mandatory files {mand_files} was " \
165
                  "not found."
166
        logger.error(err_msg)
167
        raise FileNotFoundError(err_msg)
168
    incar = ""
169
    for i, inp_file in enumerate(inp_files):
170
        file_name = inp_file.split("/")[-1]
171
        if "INCAR" in file_name:
172
            incar = Incar.from_file(inp_file)
173
            incar["SYSTEM"] = proj_name+"_"+run_type
174

    
175
    for c, conf in enumerate(atms_list):
176
        subdir = f'{run_type}/conf_{c}/'
177
        os.mkdir(subdir)
178
        for inp_file in inp_files:
179
            file_name = inp_file.split("/")[-1]
180
            if "INCAR" in file_name:
181
                incar.write_file(subdir+"INCAR")
182
            elif "KPOINTS" in file_name and "KPOINTS" != file_name:
183
                copy(inp_file, subdir+"KPOINTS")
184
            elif "POTCAR" in file_name and "POTCAR" != file_name:
185
                copy(inp_file, subdir+"POTCAR")
186
            else:
187
                copy(inp_file, subdir)
188
        if cell is not False and np.linalg.det(cell) != 0.0:
189
            conf.pbc = True
190
            conf.cell = cell
191
            conf.center()
192
        elif np.linalg.det(conf.cell) == 0:
193
            err_msg = "Cell is not defined"
194
            logger.error(err_msg)
195
            raise ValueError(err_msg)
196
        conf.write(subdir+"POSCAR", format="vasp")
197

    
198

    
199
def get_jobs_status(job_ids, stat_cmd, stat_dict):
200
    """Returns a list of job status for a list of job ids.
201

202
    @param job_ids: list of all jobs to be checked their status.
203
    @param stat_cmd: Command to check job status.
204
    @param stat_dict: Dictionary with pairs of job status (r, p, f) and the
205
        pattern it matches in the output of the stat_cmd.
206
    @return: list of status for every job.
207
    """
208
    from subprocess import PIPE, Popen
209
    status_list = []
210
    for job in job_ids:
211
        stat_msg = Popen(stat_cmd % job, shell=True,
212
                         stdout=PIPE).communicate()[0].decode('utf-8').strip()
213
        if stat_dict['r'] == stat_msg:
214
            status_list.append('r')
215
        elif stat_dict['p'] == stat_msg:
216
            status_list.append('p')
217
        elif stat_dict['f'] == stat_msg:
218
            status_list.append('f')
219
        else:
220
            logger.warning(f'Unrecognized job {job} status: {stat_msg}')
221
    return status_list
222

    
223

    
224
def submit_jobs(run_type, sub_cmd, sub_script, stat_cmd, stat_dict, max_jobs,
225
                name):
226
    """Submits jobs to a custom queuing system with the provided script
227

228
    @param run_type: Type of calculation. 'isolated', 'screening', 'refinement'
229
    @param sub_cmd: Bash command used to submit jobs.
230
    @param sub_script: script for the job submission.
231
    @param stat_cmd: Bash command to check job status.
232
    @param stat_dict: Dictionary with pairs of job status: r, p, f (ie. running
233
        pending and finished) and the pattern it matches in the output of the
234
        stat_cmd.
235
    @param max_jobs: dict: Contains the maximum number of jobs to be both
236
        running, pending/queued and pending+running. When the relevant maximum
237
        is reached no jobs more are submitted.
238
    @param name: name of the project.
239
    """
240
    from shutil import copy
241
    from time import sleep
242
    from subprocess import PIPE, Popen
243
    from modules.utilities import _human_key
244
    subm_jobs = []
245
    init_dir = os.getcwd()
246
    for conf in sorted(os.listdir(run_type), key=_human_key):
247
        i = conf.split('_')[1]
248
        while get_jobs_status(subm_jobs, stat_cmd, stat_dict).count("r") + \
249
                get_jobs_status(subm_jobs, stat_cmd, stat_dict).count("p") \
250
                >= max_jobs['rp']\
251
                or get_jobs_status(subm_jobs, stat_cmd, stat_dict).count("r") \
252
                >= max_jobs['r'] \
253
                or get_jobs_status(subm_jobs, stat_cmd, stat_dict).count("p") \
254
                >= max_jobs['p']:
255
            sleep(30)
256
        copy(sub_script, f"{run_type}/{conf}")
257
        os.chdir(f"{run_type}/{conf}")
258
        job_name = f'{name[:5]}{run_type[:3].capitalize()}{i}'
259
        sub_order = sub_cmd % (job_name, sub_script)
260
        subm_msg = Popen(sub_order, shell=True, stdout=PIPE).communicate()[0]
261
        job_id = None
262
        for word in subm_msg.decode("utf-8").split():
263
            try:
264
                job_id = int(word.replace('>', '').replace('<', ''))
265
                break
266
            except ValueError:
267
                continue
268
        subm_jobs.append(job_id)
269
        os.chdir(init_dir)
270

    
271
    logger.info('All jobs have been submitted, waiting for them to finish.')
272
    while not all([stat == 'f' for stat in
273
                   get_jobs_status(subm_jobs, stat_cmd, stat_dict)]):
274
        sleep(30)
275
    logger.info('All jobs have finished.')
276

    
277

    
278
def run_calc(run_type, inp_vars, atms_list):
279
    """Directs the calculation run according to the provided arguments.
280

281
    @param run_type: Type of calculation. 'isolated', 'screening' or
282
    'refinement'
283
    @param inp_vars: Calculation parameters from input file.
284
    @param atms_list: List of ase.Atoms objects containing the sets of atoms
285
    aimed to run the calculations of.
286
    """
287
    from modules.utilities import check_bak
288

    
289
    run_types = ['isolated', 'screening', 'refinement']
290
    if not isinstance(run_type, str) or run_type.lower() not in run_types:
291
        run_type_err = f"'run_type' must be one of the following: {run_types}"
292
        logger.error(run_type_err)
293
        raise ValueError(run_type_err)
294

    
295
    if inp_vars['batch_q_sys']:
296
        logger.info(f"Running {run_type} calculation with {inp_vars['code']} on"
297
                    f" {inp_vars['batch_q_sys']}.")
298
    else:
299
        logger.info(f"Doing a dry run of {run_type}.")
300
    check_bak(run_type)
301
    os.mkdir(run_type)
302

    
303
    # Prepare directories and files for relevant code.
304
    input_files = {'isolated': 'isol_inp_file', 'screening': 'screen_inp_file',
305
                   'refinement': 'refine_inp_file', }
306
    if inp_vars['code'] == 'cp2k':
307
        prep_cp2k(inp_vars[input_files[run_type]], run_type, atms_list,
308
                  inp_vars['project_name'])
309
    elif inp_vars['code'] == "vasp":
310
        prep_vasp(inp_vars[input_files[run_type]], run_type, atms_list,
311
                  inp_vars['project_name'], inp_vars['pbc_cell'])
312
    # elif: inp_vars['code'] == 'Other codes here'
313

    
314
    # Submit/run Jobs
315
    if inp_vars['batch_q_sys'] == 'sge':
316
        stat_cmd = "qstat | grep %s | awk '{print $5}'"
317
        stat_dict = {'r': 'r', 'p': 'qw', 'f': ''}
318
        submit_jobs(run_type, 'qsub -N %s %s', inp_vars['subm_script'],
319
                    stat_cmd, stat_dict, inp_vars['max_jobs'],
320
                    inp_vars['project_name'])
321
    elif inp_vars['batch_q_sys'] == 'lsf':
322
        stat_cmd = "bjobs -w | grep %s | awk '{print $3}'"
323
        stat_dict = {'r': 'RUN', 'p': 'PEND', 'f': ''}
324
        submit_jobs(run_type, 'bsub -J %s < %s', inp_vars['subm_script'],
325
                    stat_cmd, stat_dict, inp_vars['max_jobs'],
326
                    inp_vars['project_name'])
327
    elif inp_vars['batch_q_sys'] == 'irene':
328
        stat_cmd = "ccc_mstat | grep %s | awk '{print $10}' | cut -c1"
329
        stat_dict = {'r': 'R', 'p': 'P', 'f': ''}
330
        submit_jobs(run_type, 'ccc_msub -r %s %s', inp_vars['subm_script'],
331
                    stat_cmd, stat_dict, inp_vars['max_jobs'],
332
                    inp_vars['project_name'])
333

    
334
    elif inp_vars['batch_q_sys'] == 'local':
335
        pass  # TODO implement local
336
    elif not inp_vars['batch_q_sys']:
337
        pass
338
    else:
339
        err_msg = "Unknown value for 'batch_q_sys'."
340
        logger.error(err_msg)
341
        raise ValueError(err_msg)