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

dockonsurf / modules / calculation.py @ 1a66fb88

Historique | Voir | Annoter | Télécharger (8,9 ko)

1
import os
2
import logging
3

    
4
logger = logging.getLogger('DockOnSurf')
5

    
6

    
7
def prep_cp2k(inp_file, run_type, atms_list):  # TODO name to PROJECT_NAME
8
    """Prepares the directories to run isolated calculation with CP2K.
9

10
    @param inp_file: CP2K Input file to run the calculations with.
11
    @param run_type: Type of calculation. 'isolated', 'screening' or
12
        'refinement'
13
    @param atms_list: list of ase.Atoms objects to run the calculation of.
14
    @return: None
15
    """
16
    from shutil import copy
17
    import ase.io
18
    from pycp2k import CP2K
19
    from modules.utilities import check_bak
20
    cp2k = CP2K()
21
    cp2k.parse(inp_file)
22
    force_eval = cp2k.CP2K_INPUT.FORCE_EVAL_list[0]
23
    if force_eval.SUBSYS.TOPOLOGY.Coord_file_name is None:
24
        logger.warning("'COORD_FILE_NAME' not specified on CP2K input. Using\n"
25
                       "default name 'coord.xyz'. A new CP2K input file with "
26
                       "the 'COORD_FILE_NAME' variable is created. If there\n"
27
                       "is a name conflict the old file will be backed up.")
28
        force_eval.SUBSYS.TOPOLOGY.Coord_file_name = 'coord.xyz'
29
        print(inp_file.split('/')[-1])
30
        check_bak(inp_file.split('/')[-1])
31
        cp2k.write_input_file(inp_file.split('/')[-1])
32

    
33
    coord_file = force_eval.SUBSYS.TOPOLOGY.Coord_file_name
34

    
35
    # Creating and setting up directories for every configuration.
36
    for i, conf in enumerate(atms_list):
37
        os.mkdir(f'{run_type}/conf_{i}')
38
        copy(inp_file, f'{run_type}/conf_{i}/')
39
        ase.io.write(f'{run_type}/conf_{i}/{coord_file}', conf)
40

    
41

    
42
def get_jobs_status(job_ids, stat_cmd, stat_dict):
43
    """Returns a list of job status for a list of job ids.
44

45
    @param job_ids: list of all jobs to be checked their status.
46
    @param stat_cmd: Command to check job status.
47
    @param stat_dict: Dictionary with pairs of job status (r, p, f) and the
48
        pattern it matches in the output of the stat_cmd.
49
    @return: list of status for every job.
50
    """
51
    from subprocess import PIPE, Popen
52
    status_list = []
53
    for job in job_ids:
54
        stat_order = stat_cmd % job
55
        stat_msg = Popen(stat_order, shell=True,
56
                         stdout=PIPE).communicate()[0].decode('utf-8').strip()
57
        if stat_dict['r'] == stat_msg:
58
            status_list.append('r')
59
        elif stat_dict['p'] == stat_msg:
60
            status_list.append('p')
61
        elif stat_dict['f'] == stat_msg:
62
            status_list.append('f')
63
        else:
64
            logger.warning(f'Unrecognized job status: {job}')
65
    return status_list
66

    
67

    
68
def submit_jobs(run_type, sub_cmd, sub_script, stat_cmd, stat_dict, max_jobs,
69
                type_max, name):
70
    """Submits jobs to a custom queuing system with the provided script
71

72
    @param run_type: Type of calculation. 'isolated', 'screening', 'refinement'
73
    @param sub_cmd: The command used to submit jobs.
74
    @param sub_script: script for the job submission.
75
    @param stat_cmd: Command to check job status.
76
    @param stat_dict: Dictionary with pairs of job status (r, p, f) and the
77
        pattern it matches in the output of the stat_cmd.
78
    @param max_jobs: Maximum number of simultaneous jobs waiting to be executed.
79
    @param type_max: If the maximum number of jobs should be running jobs or
80
        pending to be run.
81
    @param name: name of the project.
82
    """
83
    from shutil import copy
84
    from time import sleep
85
    from subprocess import PIPE, Popen
86
    subm_jobs = []
87
    init_dir = os.getcwd()
88
    for conf in os.listdir(run_type):
89
        i = conf.split('_')[1]
90
        while get_jobs_status(subm_jobs, stat_cmd, stat_dict).count(type_max) \
91
                >= max_jobs:
92
            sleep(30)
93
        copy(sub_script, f"{run_type}/{conf}")
94
        os.chdir(f"{run_type}/{conf}")
95
        job_name = f'{name[:5].capitalize()}{run_type[:3].capitalize()}{i}'
96
        sub_order = sub_cmd % (job_name, sub_script)
97
        subm_msg = Popen(sub_order, shell=True, stdout=PIPE).communicate()[0]
98
        job_id = None
99
        for word in subm_msg.decode("utf-8").split():
100
            try:
101
                job_id = int(word)
102
                break
103
            except ValueError:
104
                continue
105
        subm_jobs.append(job_id)
106
        os.chdir(init_dir)
107

    
108
    logger.info('All jobs have been submitted, waiting for them to finish.')
109
    while not all([stat == 'f' for stat in
110
                   get_jobs_status(subm_jobs, stat_cmd, stat_dict)]):
111
        sleep(30)
112
    logger.info('All jobs have finished.')
113

    
114

    
115
def check_finished_calcs(run_type, code):
116
    """Returns two lists of calculations finished normally and abnormally.
117

118
    @param run_type: The type of calculation to check.
119
    @param code: The code used for the specified job.
120
    @return finished_calcs: List of calculations that have finished normally.
121
    @return unfinished_calcs: List of calculations that have finished abnormally
122
    """
123
    from glob import glob
124
    from modules.utilities import tail
125

    
126
    finished_calcs = []
127
    unfinished_calcs = []
128
    for conf in os.listdir(run_type):
129
        if not os.path.isdir(f'{run_type}/{conf}') or 'conf_' not in conf:
130
            continue
131
        if code == 'cp2k':
132
            out_file_list = glob(f"{run_type}/{conf}/*.out")
133
            restart_file_list = glob(f"{run_type}/{conf}/*-1.restart")
134
            if len(out_file_list) == 0 or len(restart_file_list) == 0:
135
                unfinished_calcs.append(conf)  # TODO specify separetely out and
136
                                               # TODO restart
137
            elif len(out_file_list) > 1 or len(restart_file_list) > 1:
138
                warn_msg = f'There is more than one file matching the {code} ' \
139
                           f'pattern for finished calculation (*.out / ' \
140
                           f'*-1.restart) in {run_type}/{conf}: ' \
141
                           f'{out_file_list, restart_file_list}. ' \
142
                           f'Skipping directory.'
143
                logger.warning(warn_msg)
144
                unfinished_calcs.append(conf)
145
            else:
146
                with open(out_file_list[0], 'rb') as out_fh:
147
                    if "PROGRAM STOPPED IN" not in tail(out_fh):
148
                        unfinished_calcs.append(conf)
149
                    else:
150
                        finished_calcs.append(conf)
151
    return finished_calcs, unfinished_calcs
152

    
153

    
154
def run_calc(run_type, inp_vars, atms_list):
155
    """Directs the calculation run according to the provided arguments.
156

157
    @param run_type: Type of calculation. 'isolated', 'screening' or
158
    'refinement'
159
    @param inp_vars: Calculation parameters from input file.
160
    @param atms_list: List of ase.Atoms objects containing the sets of atoms
161
    aimed to run the calculations of.
162
    """
163
    from modules.utilities import check_bak
164
    run_types = ['isolated', 'screening', 'refinement']
165
    if not isinstance(run_type, str) or run_type.lower() not in run_types:
166
        run_type_err = f"'run_type' must be one of the following: {run_types}"
167
        logger.error(run_type_err)
168
        raise ValueError(run_type_err)
169

    
170
    if inp_vars['batch_q_sys']:
171
        logger.info(f"Running {run_type} calculation with {inp_vars['code']} on"
172
                    f" {inp_vars['batch_q_sys']}.")
173
    else:
174
        logger.info(f"Doing a dry run of {run_type}.")
175
    check_bak(run_type)
176
    os.mkdir(run_type)
177

    
178
    # Prepare directories and files for relevant code.
179
    if inp_vars['code'] == 'cp2k':
180
        if run_type == 'isolated':
181
            prep_cp2k(inp_vars['isol_inp_file'], run_type, atms_list)
182
        elif run_type == 'screening':
183
            prep_cp2k(inp_vars['screen_inp_file'], run_type, atms_list)
184
        elif run_type == 'refinement':
185
            prep_cp2k(inp_vars['refine_inp_file'], run_type, atms_list)
186
    # elif: inp_vars['code'] == 'Other codes here'
187

    
188
    # Submit/run Jobs
189
    if inp_vars['batch_q_sys'] == 'sge':
190
        stat_cmd = "qstat | grep %s | awk '{print $5}'"
191
        stat_dict = {'r': 'r', 'p': 'qw', 'f': ''}
192
        submit_jobs(run_type, 'qsub -N %s %s', inp_vars['subm_script'],
193
                    stat_cmd, stat_dict, inp_vars['max_jobs'],
194
                    inp_vars['type_max'], inp_vars['project_name'])
195
    elif inp_vars['batch_q_sys'] == 'lsf':
196
        stat_cmd = "bjobs -w | grep %s | awk '{print $5}'"  # TODO Adapt to
197
        stat_dict = {'r': 'r', 'p': 'qw', 'f': ''}  # TODO actual command
198
        submit_jobs(run_type, 'bsub -J %s %s', inp_vars['subm_script'],
199
                    stat_cmd, stat_dict, inp_vars['max_jobs'],
200
                    inp_vars['type_max'], inp_vars['project_name'])
201
    elif inp_vars['batch_q_sys'] == 'irene':
202
        stat_cmd = "ccc_mstat | grep %s | awk '{print $10}' | cut -c1"
203
        stat_dict = {'r': 'R', 'p': 'P', 'f': ''}
204
        submit_jobs(run_type, 'ccc_msub -r %s %s', inp_vars['subm_script'],
205
                    stat_cmd, stat_dict, inp_vars['max_jobs'],
206
                    inp_vars['type_max'], inp_vars['project_name'])
207

    
208
    elif inp_vars['batch_q_sys'] == 'local':  # TODO implement local
209
        pass  # run_local
210
    elif inp_vars['batch_q_sys'] == 'none':
211
        pass