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

dockonsurf / modules / calculation.py @ 25e7e44b

Historique | Voir | Annoter | Télécharger (13,47 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
    import ase.io
17
    from modules.utilities import tail
18

    
19
    finished_calcs = []
20
    unfinished_calcs = []
21
    for conf in os.listdir(run_type):
22
        if not os.path.isdir(f'{run_type}/{conf}') or 'conf_' not in conf:
23
            continue
24
        if code == 'cp2k':
25
            out_file_list = glob(f"{run_type}/{conf}/*.out")
26
            restart_file_list = glob(f"{run_type}/{conf}/*-1.restart")
27
            if len(out_file_list) == 0 or len(restart_file_list) == 0:
28
                unfinished_calcs.append(conf)
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
                try:
56
                    ase.io.read(f"{run_type}/{conf}/OUTCAR")
57
                except ValueError:
58
                    unfinished_calcs.append(conf)
59
                    continue
60
                except IndexError:
61
                    unfinished_calcs.append(conf)
62
                    continue
63
                with open(f"{run_type}/{conf}/OUTCAR", 'rb') as out_fh:
64
                    if "General timing and accounting" not in tail(out_fh):
65
                        unfinished_calcs.append(conf)
66
                    else:
67
                        finished_calcs.append(conf)
68
        else:
69
            err_msg = f"Check not implemented for '{code}'."
70
            logger.error(err_msg)
71
            raise NotImplementedError(err_msg)
72
    return finished_calcs, unfinished_calcs
73

    
74

    
75
def prep_cp2k(inp_file: str, run_type: str, atms_list: list, proj_name: str):
76
    """Prepares the directories to run calculations with CP2K.
77

78
    @param inp_file: CP2K Input file to run the calculations with.
79
    @param run_type: Type of calculation. 'isolated', 'screening' or
80
        'refinement'
81
    @param atms_list: list of ase.Atoms objects to run the calculation of.
82
    @param proj_name: name of the project
83
    @return: None
84
    """
85
    from shutil import copy
86
    from pycp2k import CP2K
87
    from modules.utilities import check_bak
88
    if not isinstance(inp_file, str):
89
        err_msg = "'inp_file' must be a string with the path of the CP2K " \
90
                  "input file."
91
        logger.error(err_msg)
92
        raise ValueError(err_msg)
93
    cp2k = CP2K()
94
    cp2k.parse(inp_file)
95
    cp2k.CP2K_INPUT.GLOBAL.Project_name = proj_name+"_"+run_type
96
    force_eval = cp2k.CP2K_INPUT.FORCE_EVAL_list[0]
97
    if force_eval.SUBSYS.TOPOLOGY.Coord_file_name is None:
98
        logger.warning("'COORD_FILE_NAME' not specified on CP2K input. Using\n"
99
                       "'coord.xyz'. A new CP2K input file with "
100
                       "the 'COORD_FILE_NAME' variable is created.")
101
        force_eval.SUBSYS.TOPOLOGY.Coord_file_name = 'coord.xyz'
102
        check_bak(inp_file.split('/')[-1])
103
    cp2k.write_input_file(inp_file.split('/')[-1])
104

    
105
    coord_file = force_eval.SUBSYS.TOPOLOGY.Coord_file_name
106

    
107
    # Creating and setting up directories for every configuration.
108
    for i, conf in enumerate(atms_list):
109
        subdir = f'{run_type}/conf_{i}/'
110
        os.mkdir(subdir)
111
        copy(inp_file, subdir)
112
        conf.write(subdir + coord_file)
113

    
114

    
115
def prep_vasp(inp_files, run_type, atms_list, proj_name, cell):
116
    """Prepares the directories to run calculations with VASP.
117

118
    @param inp_files: VASP Input files to run the calculations with.
119
    @param run_type: Type of calculation. 'isolated', 'screening' or
120
        'refinement'
121
    @param atms_list: list of ase.Atoms objects to run the calculation of.
122
    @param proj_name: name of the project.
123
    @param cell: Cell for the Periodic Boundary Conditions.
124
    @return: None
125
    """
126
    from shutil import copy
127
    import os
128

    
129
    import numpy as np
130
    from pymatgen.io.vasp.inputs import Incar
131

    
132
    mand_files = ["INCAR", "KPOINTS", "POTCAR"]
133
    # Check that there are many specified files
134
    if not isinstance(inp_files, list) and all(isinstance(inp_file, str)
135
                                               for inp_file in inp_files):
136
        err_msg = "'inp_files' should be a list of file names/paths"
137
        logger.error(err_msg)
138
        ValueError(err_msg)
139
    # Check that all mandatory files are defined
140
    elif any(not any(mand_file in inp_file.split("/")[-1]
141
                     for inp_file in inp_files) for mand_file in mand_files):
142
        err_msg = f"At least one of the mandatory files {mand_files} was " \
143
                  "not specified."
144
        logger.error(err_msg)
145
        raise FileNotFoundError(err_msg)
146
    # Check that the defined files exist
147
    elif any(not os.path.isfile(inp_file) for inp_file in inp_files):
148
        err_msg = f"At least one of the mandatory files {mand_files} was " \
149
                  "not found."
150
        logger.error(err_msg)
151
        raise FileNotFoundError(err_msg)
152
    incar = ""
153
    for i, inp_file in enumerate(inp_files):
154
        file_name = inp_file.split("/")[-1]
155
        if "INCAR" in file_name:
156
            incar = Incar.from_file(inp_file)
157
            incar["SYSTEM"] = proj_name+"_"+run_type
158

    
159
    for c, conf in enumerate(atms_list):
160
        subdir = f'{run_type}/conf_{c}/'
161
        os.mkdir(subdir)
162
        for inp_file in inp_files:
163
            file_name = inp_file.split("/")[-1]
164
            if "INCAR" in file_name:
165
                incar.write_file(subdir+"INCAR")
166
            elif "KPOINTS" in file_name and "KPOINTS" != file_name:
167
                copy(inp_file, subdir+"KPOINTS")
168
            elif "POTCAR" in file_name and "POTCAR" != file_name:
169
                copy(inp_file, subdir+"POTCAR")
170
            else:
171
                copy(inp_file, subdir)
172
        if cell is not False and np.linalg.det(cell) != 0.0:
173
            conf.pbc = True
174
            conf.cell = cell
175
            conf.center()
176
        elif np.linalg.det(conf.cell) == 0:
177
            err_msg = "Cell is not defined"
178
            logger.error(err_msg)
179
            raise ValueError(err_msg)
180
        conf.write(subdir+"POSCAR", format="vasp")
181

    
182

    
183
def get_jobs_status(job_ids, stat_cmd, stat_dict):
184
    """Returns a list of job status for a list of job ids.
185

186
    @param job_ids: list of all jobs to be checked their status.
187
    @param stat_cmd: Command to check job status.
188
    @param stat_dict: Dictionary with pairs of job status (r, p, f) and the
189
        pattern it matches in the output of the stat_cmd.
190
    @return: list of status for every job.
191
    """
192
    from subprocess import PIPE, Popen
193
    status_list = []
194
    for job in job_ids:
195
        stat_msg = Popen(stat_cmd % job, shell=True,
196
                         stdout=PIPE).communicate()[0].decode('utf-8').strip()
197
        if stat_dict['r'] == stat_msg:
198
            status_list.append('r')
199
        elif stat_dict['p'] == stat_msg:
200
            status_list.append('p')
201
        elif stat_dict['f'] == stat_msg:
202
            status_list.append('f')
203
        else:
204
            logger.warning(f'Unrecognized job {job} status: {stat_msg}')
205
    return status_list
206

    
207

    
208
def submit_jobs(run_type, sub_cmd, sub_script, stat_cmd, stat_dict, max_jobs,
209
                name):
210
    """Submits jobs to a custom queuing system with the provided script
211

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

    
254
    logger.info('All jobs have been submitted, waiting for them to finish.')
255
    while not all([stat == 'f' for stat in
256
                   get_jobs_status(subm_jobs, stat_cmd, stat_dict)]):
257
        sleep(30)
258
    logger.info('All jobs have finished.')
259

    
260

    
261
def run_calc(run_type, inp_vars, atms_list):
262
    """Directs the calculation run according to the provided arguments.
263

264
    @param run_type: Type of calculation. 'isolated', 'screening' or
265
    'refinement'
266
    @param inp_vars: Calculation parameters from input file.
267
    @param atms_list: List of ase.Atoms objects containing the sets of atoms
268
    aimed to run the calculations of.
269
    """
270
    from modules.utilities import check_bak
271

    
272
    run_types = ['isolated', 'screening', 'refinement']
273
    if not isinstance(run_type, str) or run_type.lower() not in run_types:
274
        run_type_err = f"'run_type' must be one of the following: {run_types}"
275
        logger.error(run_type_err)
276
        raise ValueError(run_type_err)
277

    
278
    if inp_vars['batch_q_sys']:
279
        logger.info(f"Running {run_type} calculation with {inp_vars['code']} on"
280
                    f" {inp_vars['batch_q_sys']}.")
281
    else:
282
        logger.info(f"Doing a dry run of {run_type}.")
283
    check_bak(run_type)
284
    os.mkdir(run_type)
285

    
286
    # Prepare directories and files for relevant code.
287
    input_files = {'isolated': 'isol_inp_file', 'screening': 'screen_inp_file',
288
                   'refinement': 'refine_inp_file', }
289
    if inp_vars['code'] == 'cp2k':
290
        prep_cp2k(inp_vars[input_files[run_type]], run_type, atms_list,
291
                  inp_vars['project_name'])
292
    elif inp_vars['code'] == "vasp":
293
        prep_vasp(inp_vars[input_files[run_type]], run_type, atms_list,
294
                  inp_vars['project_name'], inp_vars['pbc_cell'])
295
    # elif: inp_vars['code'] == 'Other codes here'
296

    
297
    # Submit/run Jobs
298
    if inp_vars['batch_q_sys'] == 'sge':
299
        stat_cmd = "qstat | grep %s | awk '{print $5}'"
300
        stat_dict = {'r': 'r', 'p': 'qw', 'f': ''}
301
        submit_jobs(run_type, 'qsub -N %s %s', inp_vars['subm_script'],
302
                    stat_cmd, stat_dict, inp_vars['max_jobs'],
303
                    inp_vars['project_name'])
304
    elif inp_vars['batch_q_sys'] == 'lsf':
305
        stat_cmd = "bjobs -w | grep %s | awk '{print $3}'"
306
        stat_dict = {'r': 'RUN', 'p': 'PEND', 'f': ''}
307
        submit_jobs(run_type, 'bsub -J %s < %s', inp_vars['subm_script'],
308
                    stat_cmd, stat_dict, inp_vars['max_jobs'],
309
                    inp_vars['project_name'])
310
    elif inp_vars['batch_q_sys'] == 'irene':
311
        stat_cmd = "ccc_mstat | grep %s | awk '{print $10}' | cut -c1"
312
        stat_dict = {'r': 'R', 'p': 'P', 'f': ''}
313
        submit_jobs(run_type, 'ccc_msub -r %s %s', inp_vars['subm_script'],
314
                    stat_cmd, stat_dict, inp_vars['max_jobs'],
315
                    inp_vars['project_name'])
316

    
317
    elif inp_vars['batch_q_sys'] == 'local':
318
        pass  # TODO implement local
319
    elif not inp_vars['batch_q_sys']:
320
        pass
321
    else:
322
        err_msg = "Unknown value for 'batch_q_sys'."
323
        logger.error(err_msg)
324
        raise ValueError(err_msg)