sbatch_generator.py 12.6 KB
Newer Older
Jaime Arias's avatar
Jaime Arias committed
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
#!/usr/bin/env python3

import os
import sys
from itertools import product
from functools import reduce
from collections import ChainMap

sbatch_header = """\
#!/bin/bash
#
#SBATCH --job-name={experiment_name}_{model_name}_n{nodes}-th{threads}
#SBATCH --ntasks={nodes}
#SBATCH --cpus-per-task={threads}

# Load openmpi module
module load gcc/8.3.0/openmpi/3.1.4

# Experiments

"""


def create_folder(path):
    """Creates a folder if it does not exist

    Parameters
    ----------
    path : str
        Path of the new folder

    Examples
    --------

    >>> create_folder('./results')
    """
    if not os.path.exists(path):
        os.makedirs(path)


def generate_model_instance_path(model_name, model_instance, extension, paths):
    """Generates the absolute path of a model instance

    Parameters
    ----------
    model_name : str
        Name of the model
    model_instance : str
        Instance of the model
    extension : str
        File extension of the model instance
    paths : dict
        Dictionary with the paths of the project

    Returns
    -------
    str
        Absolute path of the model instance
    """
    name = f"{model_instance}.{extension}"
    model_path = os.path.join(paths["models"], model_name, name)
    return model_path


def generate_formula_path(identifier, extension, model_name, model_instance,
                          paths):
    """Generates  the absolute path of a formula

    Parameters
    ----------
    identifier : int
        Formula identifier
    extension : str
        Formula extension
    model_name : str
        Model that verifies the formula
    model_instance : str
        Instance of the model that verifies the formula
    paths : dict
        Dictionary with the paths of the project

    Returns
    -------
    str
        Formula path
    """
    name = f"{model_instance}-{identifier}.{extension}"
    formula_path = os.path.join(paths["formulas"], model_name, model_instance,
                                name)
    return formula_path


def pmcsog_run(parameters, threads, model_name, model_instance, formula,
               paths):
    """Generates the string with the command to execute pmc-sog

    Parameters
    ----------
    parameters : dict
        Dictionary with the parameters for pmc-sog
    threads : int
        Number of threads
    model_name : str
        Name of the model
    model_instance : str
        Name of the model instance
    formula : int
        Identifier of the the formula to be verified
    paths : dict
        Dictionary with the paths of the project

    Returns
    -------
    str
        Command to execute pmc-sog
    """
    formula = generate_formula_path(formula, 'ltl.reduced', model_name,
                                    model_instance, paths)
    model = generate_model_instance_path(model_name, model_instance, 'net',
                                         paths)
    tool = os.path.join(paths['tools'], 'pmc-sog')
    parallelisation = parameters['parallelisation']

    algorithm = parameters['strategy'].strip()
    algorithm = '"{}"'.format(algorithm) if algorithm != "default" else ''

    return f"{tool} {parallelisation} {threads} {model} {formula} {algorithm}"


def ltsmin_run(parameters, threads, model_name, model_instance, formula,
               paths):
    """Generates the string with the command to execute pnml2lts-mc

    Parameters
    ----------
    parameters : dict
        Dictionary with the parameters for pnml2lts-mc
    threads : int
        Number of threads
    model_name : str
        Name of the model
    model_instance : str
        Name of the model instance
    formula : int
        Identifier of the the formula to be verified
    paths : dict
        Dictionary with the paths of the project

    Returns
    -------
    str
        Command to execute pnml2lts-mc
    """
    tool = os.path.join(paths['tools'], 'pnml2lts-mc')
    formula = generate_formula_path(formula, 'ltl', model_name, model_instance,
                                    paths)
    model = generate_model_instance_path(model_name, model_instance, 'pnml',
                                         paths)

    strategy = parameters["strategy"]
    size = parameters["size"]

    return f"{tool} --strategy={strategy} --size={size} --threads={threads} --ltl={formula} {model}"


def tool_command(tool_dict, threads, model_name, model_instance, formula,
                 paths):
    """Factory method that returns the correct command depending on the tool

    Parameters
    ----------
    tool_dict : dict
        Dictionary containing the parameters of the tool
    threads : int
        Number of threads
    model_name : str
        Name of the model
    model_instance : str
        Name of the model instance
    formula : int
        Identifier of the formula
    paths : dict
        Dictionary with paths of the project

    Returns
    -------
    str
        Command of the tool
    """
    tool_name = tool_dict['name']
    tool_parameters = tool_dict['parameters']

    command = ""
    if (tool_name == "pmc-sog"):
        command = pmcsog_run(tool_parameters, threads, model_name,
                             model_instance, formula, paths)
    elif (tool_name == "pnml2lts-mc"):
        command = ltsmin_run(tool_parameters, threads, model_name,
                             model_instance, formula, paths)
    else:
        sys.exit("{} is not handled yet".format(tool_name))

    return command


def srun(command, nodes, threads, timeout, job_name, output_folder):
    """Generates the string to execute a task on the cluster

    Parameters
    ----------
    command : str
        Command to be executed
    nodes : int
        Number of nodes used to run the task
    threads : int
        Number of threads used to run the task
    job_name : str
        Name of the task
    output_folder : str
        absolute path where the logs will be saved

    Returns
    -------
    str
        SRUN command
    """
    error_file = f"{output_folder}/{job_name}.err"
    output_file = f"{output_folder}/{job_name}.out"
    return f"srun -n {nodes} --resv-ports --cpus-per-task={threads} --time={timeout} --output={output_file} --error={error_file} --job-name={job_name} {command}"


def generate_experiment_name(tool_dict):
    """Generate the name of the experiment"""
    tool_name = tool_dict["name"]

    tool_params_dict = tool_dict["parameters"]
    tool_parameters = tool_dict["parameters"][
        "parallelisation"] + "_" if tool_name == "pmc-sog" else ''
    tool_parameters += tool_params_dict["strategy"]
    tool_parameters = reduce(
        (lambda s, v: s.replace(*v)),
        [['(poprem)', '-default'], ['(poprem shy)', '-shy'], ['Cou', 'couv']],
        tool_parameters)

    return f"{tool_name}_{tool_parameters}"


def generate_sbatch(tool_dict, nodes, threads, model_dict, formulas_ids,
                    timeout, paths):
    """Generates a slurm batch of a experiment to be executed on the cluster

    Parameters
    ---------
    tool_dict : dict
        Dictionary with an instance of a tool
    nodes : int
        Number of nodes
    threads : int
        Number of threads
    model_dict : dict
        Dictionary with a model information
    formulas_ids : list of int
        List of ids of the formulas to be verified
    timeout : int
        Timeout of the experiment
    paths : dict
        Dictionary with the paths of the project
    """
    tool_name = tool_dict["name"]
    model_name = model_dict['name']
    model_instances = model_dict['instances']

    experiment_name = generate_experiment_name(tool_dict)

    header = sbatch_header.format(experiment_name=experiment_name,
                                  model_name=model_name,
                                  nodes=nodes,
                                  threads=threads)

Jaime Arias's avatar
Jaime Arias committed
280
281
    sbatch_folder = os.path.join(paths['slurm'], 'experiments', tool_name,
                                 experiment_name, model_name)
Jaime Arias's avatar
Jaime Arias committed
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
    create_folder(sbatch_folder)

    sbatch_name = f"n{nodes}-th{threads}.sbatch"
    sbatch_file = os.path.join(sbatch_folder, sbatch_name)
    with open(sbatch_file, 'w') as sbatch_file:
        sbatch_file.write(header)

        # print srun command for each model_instance
        for model_instance in model_instances:
            output_folder = os.path.join(paths['results'], tool_name,
                                         experiment_name, model_name,
                                         model_instance)
            create_folder(output_folder)

            for formula in formulas_ids:
                command = tool_command(tool_dict, threads, model_name,
                                       model_instance, formula, paths)

                job_name = f"{tool_name}_{model_instance}-n{nodes}-th{threads}-f{formula}"

                srun_command = srun(command, nodes, threads, timeout, job_name,
                                    output_folder)

                sbatch_file.write(srun_command)
                sbatch_file.write("\n\n")


def create_default_paths():
    """Create the default path for the project"""
    base_folder = os.path.abspath(
        os.path.join(os.path.dirname(os.path.realpath(__file__)), os.pardir))

    paths = {
        # Absolute path where are stored the formulas, models, and scripts
        'project': base_folder,
317
        # Folder where the formulas are saved
Jaime Arias's avatar
Jaime Arias committed
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
        'formulas': os.path.join(base_folder, "formulas"),
        # Folder where the models are saved
        'models': os.path.join(base_folder, "models"),
        # Folder where the results will be saved
        'results': os.path.join(base_folder, "results"),
        # Folder where the slurm batches will be saved
        'slurm': os.path.join(base_folder, "slurm"),
        # Folder where the tool are saved
        'tools': os.path.join(base_folder, "tools")
    }

    # Create paths if they don't exist
    for path in paths.values():
        create_folder(path)

    return paths


def explode_tool(tool):
    """Generates a tool dictionary for each parameter"""
    parameters = [[{
        name: value
    } for value in values] for name, values in tool["parameters"].items()]
    parameters = product(*parameters)

    result = [{
        "name": tool["name"],
        "parameters": dict(ChainMap(*parameter))
    } for parameter in parameters]

    return result


def generate_multiple_sbatchs(tools, models, formulas, nodes_list,
                              threads_list, timeout, paths):
    """Generates the slurm batch for several experiments

    Parameters
    ----------
    tools : dict
        Dictionary with all the tools and their parameters
    models : dict
        Dictionary with all the models and their instances
    formulas : list of int
        List with the formula identifiers to be verified
    nodes_list : list of int
        List with all the nodes to be used
    threads_list : list of int
        List with all the threads to be used
    timeout : int
        Time in minutes of each experiment
    paths : dict
        Dictionary with the paths of the project
    """
    for tool_dict in tools:
        tools_dict = explode_tool(tool_dict)
        for tool in tools_dict:
            print(tool)
            for model in models:
                for nodes in nodes_list:
                    for threads in threads_list:
                        generate_sbatch(tool, nodes, threads, model, formulas,
                                        timeout, paths)


if __name__ == '__main__':
    # Default paths
    paths = create_default_paths()

Jaime Arias's avatar
Jaime Arias committed
387
388
    # Timeout: 20 minutes
    timeout = 20
Jaime Arias's avatar
Jaime Arias committed
389
390

    # Number of nodes
Jaime Arias's avatar
Jaime Arias committed
391
    nodes = [4]
Jaime Arias's avatar
Jaime Arias committed
392
393

    # Number of threads
Jaime Arias's avatar
Jaime Arias committed
394
    threads = [4]
Jaime Arias's avatar
Jaime Arias committed
395
396
397
398
399
400
401

    # Formulas to be verified
    nb_formulas = 200
    formulas = [n for n in range(1, nb_formulas + 1)]

    # Models to be run
    models = [{
Jaime Arias's avatar
Jaime Arias committed
402
403
404
405
406
407
408
409
410
    #     "name": "philo",
    #     "instances": ["philo5", "philo10", "philo20"]
    # }, {
    #     "name": "train",
    #     "instances": ["train12", "train24", "train48", "train96"]
    # }, {
    #     "name": "tring",
    #     "instances": ["tring5", "tring10", "tring20"]
    # }, {
Jaime Arias's avatar
Jaime Arias committed
411
412
        "name":
        "robot",
Jaime Arias's avatar
Jaime Arias committed
413
414
415
416
        "instances": ["robot20"] #"robot20", "robot50", "robot2", "robot5", "robot10"]
    # }, {
    #   "name": "spool",
    #    "instances": ["spool4", "spool5"] #, "spool1", "spool2", "spool3"]
Jaime Arias's avatar
Jaime Arias committed
417
418
419
420
421
422
    }]

    # Tools to be compared
    tools = [{
        "name": "pmc-sog",
        "parameters": {
Jaime Arias's avatar
Jaime Arias committed
423
            "parallelisation": ['otf'],  # 'otfPR', 'otfP', 'otfC'
Jaime Arias's avatar
Jaime Arias committed
424
            "strategy": ['Cou99(poprem)', 'Cou99(poprem shy)'] #, 'default']
Jaime Arias's avatar
Jaime Arias committed
425
        }
Jaime Arias's avatar
Jaime Arias committed
426
427
428
429
430
431
#    }, {
#        "name": "pnml2lts-mc",
#        "parameters": {
#            "size": ["90%"],
#            "strategy": ['dfs', 'ndfs']
#        }
Jaime Arias's avatar
Jaime Arias committed
432
433
434
435
    }]

    generate_multiple_sbatchs(tools, models, formulas, nodes, threads, timeout,
                              paths)