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

dockonsurf / modules / calculation.py @ c3cb279a

Historique | Voir | Annoter | Télécharger (3,97 ko)

1
import os
2
import logging
3

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

    
6

    
7
def check_bak(file_name):
8
    """Checks if a file already exists and backs it up if so.
9
    @param file_name: file to be checked if exists
10
    """
11
    new_name = file_name
12
    bak_num = 0
13
    while new_name in os.listdir("."):
14
        bak_num += 1
15
        new_name = new_name.split(".bak")[0] + f".bak{bak_num}"
16
    if bak_num > 0:
17
        os.rename(file_name, new_name)
18
        logger.warning(f"'{file_name}' already present. Backed it up to "
19
                       f"{new_name}")
20

    
21

    
22
def prep_cp2k(inp_file, run_type, atms_list):
23
    """Prepares the directories to run isolated calculation with CP2K.
24

25
    @param inp_file: CP2K Input file to run the calculations with.
26
    @param run_type: Type of calculation. 'isolated', 'screening' or
27
        'refinement'
28
    @param atms_list: list of ase.Atoms objects to run the calculation of.
29
    @return: None
30
    """
31
    from shutil import copy
32
    import ase.io
33
    from pycp2k import CP2K
34
    cp2k = CP2K()
35
    cp2k.parse(inp_file)
36
    force_eval = cp2k.CP2K_INPUT.FORCE_EVAL_list[0]
37
    coord_file = force_eval.SUBSYS.TOPOLOGY.Coord_file_name
38

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

    
45

    
46
def get_queued_jobs_sge(job_list):  # TODO more elegant
47
    """Returns a list of jobs that are in qw status from a list of all jobs.
48

49
    @param job_list: list of all jobs to be checked if are in qw status or not.
50
    @return: list of jobs that are in qw status.
51
    """
52
    from gridtk.tools import qstat
53
    chk = 'usage         1'
54
    return [job for job in job_list if chk not in qstat(job)
55
            and len(qstat(job)) > 0]
56

    
57

    
58
def submit(run_type, q_sys, sub_script, max_qw, name):
59
    """Submits jobs to the relevant queuing system with the provided script
60

61
    @param run_type: Type of calculation. 'isolated', 'screening' or
62
        'refinement'
63
    @param q_sys: Batch queuing system used
64
    @param sub_script: script for the job submission.
65
    @param max_qw: Maximum number of simultaneous jobs waiting to be executed.
66
    @param name: name of the project
67
    """
68
    from shutil import copy
69
    from time import sleep
70
    subm_jobs = []
71
    if q_sys == 'sge':
72
        from gridtk.tools import qsub
73
        for i, conf in enumerate(sorted(os.listdir(run_type))):
74
            while len(get_queued_jobs_sge(subm_jobs)) >= max_qw:
75
                sleep(30)
76
            copy(sub_script, f"{run_type}/{conf}")
77
            os.chdir(f"{run_type}/{conf}")
78
            job_name = f'{name[:6].capitalize()}{run_type[:3].capitalize()}{i}'
79
            subm_jobs.append(qsub(sub_script, name=job_name))
80

    
81

    
82
def run_calc(run_type, inp_vars, atms_list):
83
    """Directs the calculation run according to the provided arguments.
84

85
    @param run_type: Type of calculation. 'isolated', 'screening' or
86
    'refinement'
87
    @param inp_vars: Calculation parameters from input file.
88
    @param atms_list: List of ase.Atoms objects containing the sets of atoms
89
    aimed to run the calculations of.
90
    """
91
    run_types = ['isolated', 'screening', 'refinement']
92
    run_type_err = f"'run_type' should be one of the following: {run_types}"
93
    if not isinstance(run_type, str) or run_type.lower() not in run_types:
94
        logger.error(run_type_err)
95
        raise ValueError(run_type_err)
96

    
97
    logger.info(f"Running {run_type} calculation with {inp_vars['code']} on "
98
                f"{inp_vars['batch_q_sys']}")
99
    check_bak(run_type)
100
    os.mkdir(run_type)
101
    if run_type == 'isolated':
102
        if inp_vars['code'] == 'cp2k':
103
            prep_cp2k(inp_vars['isol_inp_file'], run_type, atms_list)
104
        # elif: inp_vars['code'] == 'Other codes here'
105
    # elif run_type == 'screening':
106
    # elif run_type == 'refinement':
107

    
108
    submit(run_type, inp_vars['batch_q_sys'], inp_vars['subm_script'],
109
           inp_vars['max_qw'], inp_vars['project_name'])