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

dockonsurf / modules / calculation.py @ 0d2f159a

Historique | Voir | Annoter | Télécharger (13,44 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
        elif np.linalg.det(conf.cell) == 0:
176
            err_msg = "Cell is not defined"
177
            logger.error(err_msg)
178
            raise ValueError(err_msg)
179
        conf.write(subdir+"POSCAR", format="vasp")
180

    
181

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

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

    
206

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

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

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

    
259

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

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

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

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

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

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

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