csv_generator.py 5.55 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
#!/usr/bin/env python3

import os
import glob
import csv
import re
import sys


def get_time(experiment, tool):
    """Returns the elapsed time of the experiment

    Parameters
    ----------
    experiment : str
        Path of the file containing the output of the experiment
    tool : str
        Name of the tool

    Returns
    -------
    time : int or None
        elapse time of the experiment
    truthy : str or None
        True if property is satisfied, False otherwise
    """
    regex_true = r''
    regex_false = r''
    regex_time = r''
    filename = ""

    name, extension = os.path.splitext(experiment)

    if (tool == 'pmc-sog'):
        filename = "{}.{}".format(name, 'out')

        regex_true = re.compile(r'Property is verified')
        regex_false = re.compile(r'Property is violated')
        regex_time = re.compile(r'Verification duration : (\d+(\.\d+)?)')
    elif (tool == 'pnml2lts-mc'):
        filename = "{}.{}".format(name, 'err')

        regex_true = re.compile(r'Empty product with LTL')
        regex_false = re.compile(r'Accepting cycle FOUND')
        regex_time = re.compile(r'Total exploration time (\d+(\.\d+)?)')
    else:
        print('{} does not exists'.format(tool))
        sys.exit()

    with open(filename, mode='r') as output_file:
        file_content = output_file.read()

        match_true = regex_true.search(file_content)
        match_false = regex_false.search(file_content)
        match_time = regex_time.search(file_content)

        # property verification
        verification = None
        if match_true:
            verification = 'T'
        elif match_false:
            verification = 'F'

        # get time
        time_s = None
        if match_time:
            time = float(match_time.group(1))
            time_s = time / 1000. if (tool == 'pmc-sog') else time

        return (time_s, verification)


def check_error(experiment):
    """Returns the error returned in the experiment

    Parameters
    ----------
    experiment: str
        Path of the file containing the output of the experiment

    Returns
    -------
    str
        Error code
    """
    regex = re.compile(
        r'(TIME LIMIT|Segmentation fault|terminate|Aborted|MDD|Invalid identifier)'
    )
    name, extension = os.path.splitext(experiment)
    error_file = '{}.err'.format(name)

    with open(error_file, mode='r') as output_file:
        file_content = output_file.read()
        match_error = regex.search(file_content)

        output = match_error.group(1).upper() if match_error else 'UNKNOWN'
        return output


def get_data(experiments):
    """Returns a list with all the experiments' results

    Parameters
    ----------
    experiments: list of str
        List with all the experiments paths

    Returns
    -------
    list of dict
        List of dictionaries with keys: "model", "tool", "strategy",
        "num_nodes", "num_threads", "formula", "time", "property", and "error"
    """
    results = []

    # Regex to find the # nodes, # threads and the formula id
    regex = re.compile(r'-n(\d+).*-th(\d+).*-f(\d+)')

    for experiment in experiments:
        tool, strategy, model_folder, model, out_file = experiment.split(
            '/')[-5:]
        strategy = '_'.join(strategy.split('_')[1:])

        num_nodes, num_threads, formula = regex.findall(out_file)[0]

        elapsed_time, property_check = get_time(experiment, tool)

        error = "OK"
        if ((elapsed_time is None) and (property_check is None)):
            error = check_error(experiment)

        results.append({
            "model": model,
            "formula": int(formula),
            "tool": tool,
            "strategy": strategy,
            "num_nodes": int(num_nodes),
            "num_threads": int(num_threads),
            "time": elapsed_time,
            "property": property_check,
            "error": error
        })

    return results


def write2csv(filename, header, values):
    """Writes results in a csv file

    Parameters
    ----------
    filename: str
        Filename of the csv output
    header: list of str
        fields of the csv header. Possible fields are "model", "tool",
        "strategy" "num_nodes", "num_threads", "formula", "time", "property",
        and "error"
    values: list of dict
        Values to be saved. Keys: "model", "tool", "strategy", "num_nodes",
        "num_threads", "formula", "time", "property", and "error"
    """
    with open(filename, mode='w') as csv_file:
        writer = csv.DictWriter(csv_file, fieldnames=header)
        writer.writeheader()

        # write to csv file
        writer.writerows(results)


if __name__ == '__main__':

    # Root folder
    PROJECT_FOLDER = os.path.abspath(
        os.path.join(os.path.dirname(os.path.realpath(__file__)), os.pardir))

    # Folder where are stored the results
    BASE_FOLDER = os.path.join(PROJECT_FOLDER, "results")

    # Get file containing the output of experiments
    EXPERIMENTS = glob.glob(os.path.join(BASE_FOLDER, '**/*.out'),
                            recursive=True)

    # csv file gathering all the results
    OUTPUT_CSV_FILE = os.path.join(BASE_FOLDER, 'output.csv')

    # structure of the csv file
    CSV_FIELDNAMES = [
        'model', 'formula', 'tool', 'strategy', 'num_nodes', 'num_threads',
        'time', 'property', 'error'
    ]

    # experiments' results
    results = sorted(get_data(EXPERIMENTS),
                     key=lambda k: (k['model'], k['formula'], k['tool'], k[
                         'strategy'], k['num_nodes'], k['num_threads']))

    # write results to csv file
    write2csv(OUTPUT_CSV_FILE, CSV_FIELDNAMES, results)