formula_generator.py 5.43 KB
Newer Older
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
#!/usr/bin/env python3

import os
import xml.etree.ElementTree as etree
import subprocess
import re


def execute_command(command):
    """Run a command in the shell"""
    output = None
    try:
        output = subprocess.check_output(
            command, shell=True, stderr=subprocess.STDOUT).decode("utf-8")
    except Exception as e:
        output = e.output.decode("utf-8")
    except KeyboardInterrupt:
        pass

    return output


def get_atomic_propositions(pnml_file):
    """Returns the atomic propositions from a PNML file"""
    xml_tree = etree.parse(pnml_file)
    root = xml_tree.getroot()
    ns = {'pnml': root.tag[1:].split("}")[0]}

    places = [p.get('id') for p in root.findall('.//pnml:place', ns)]
    transitions = [t.get('id') for t in root.findall('.//pnml:transition', ns)]

    return {'places': places, 'transitions': transitions}


def generate_spot_formulas(model_name, model_instance, n, paths):
    """Generates a number of formulas for a specific PNML model

    Parameters
    ----------
    model_name : str
        Name of model
    model_instance : str
        Instance of the model
    n : int
        Number of formulas to be generated
    paths : dict of str
        Paths of the project

    Returns
    -------
    list of str
        list with formulas
    """
    ignored_operators = "X=0,xor=0,W=0,M=0,R=0,U=0"

    pnml_file = os.path.join(paths['models'], model_name,
                             f'{model_instance}.pnml')

    atomic_propositions = get_atomic_propositions(pnml_file)
    atomic_propositions = '==1 '.join(atomic_propositions['places'])

    command = f'{paths["randltl"]} -L -s -p -n{n} --ltl-priorities="{ignored_operators}" {atomic_propositions}'

    output = execute_command(command)
    formulas = output.split('\n')[:-1]

    return formulas


def check_formula(model_name, model_instance, formula, timeout, paths):
    """Check whether a property is satisfied or not"""
    tool = paths['pnml2lts-mc']

    model_file = os.path.join(paths['models'], model_name,
                              f"{model_instance}.pnml")

    command = f'{tool} --strategy=ndfs --timeout={timeout} --ltl="{formula}" {model_file}'
    ltsmin_out = execute_command(command)

    # timeout or error found
    if (ltsmin_out is None):
        return None

    match_false = re.search(r'Accepting cycle FOUND', ltsmin_out)
    match_time = re.search(r'Total exploration time (\d+(\.\d+)?)', ltsmin_out)

    # ignore formulas with time zero
    if match_time:
        time = float(match_time.group(1))
        if (time > 0):
            print("* property: {}\n  - it is satisfied: {}\n  - time: {} s".
                  format(formula, not match_false, time))
            return not match_false

    return None


def get_default_paths():
    """Returns the default path of the project"""

    # Absolute path where are stored the formulas, models
    base_folder = os.path.abspath(
        os.path.join(os.path.dirname(os.path.realpath(__file__)), os.pardir))

    paths = {
        # randltl path: this tool generates random formulas
        "randltl": "randltl",
        # tool to verify the property
        'pnml2lts-mc': os.path.join(base_folder, "tools", "pnml2lts-mc"),
        # Folder where the models are saved
        'models': os.path.join(base_folder, "models"),
        # Folder where the formulas are saved
        'formulas': os.path.join(base_folder, "formulas"),
    }

    return paths


def generate_formulas(model_name, model_instance, n, timeout, paths):
    """Generates N satified and N violated formulas"""
    true_formulas = []
    false_formulas = []

    random_formulas = generate_spot_formulas(model_name, model_instance, 10000,
                                             paths)

    for f in random_formulas:
        if len(true_formulas) == n and len(false_formulas) == n:
            break

        is_satisfied = check_formula(model_name, model_instance, f, timeout,
                                     paths)

        # if timeout or error during the verification
        if (is_satisfied is None):
            continue

        # add to formulas satisfied
        if is_satisfied and len(true_formulas) < n:
            true_formulas.append(f)

        # add to formulas violated
        if not is_satisfied and len(false_formulas) < n:
            false_formulas.append(f)

    return {'satisfied': true_formulas, 'violated': true_formulas}


if __name__ == '__main__':
    # default paths of the project
    paths = get_default_paths()

    # number of formulas generated
    n_formulas = 100

    # timeout of verification (seconds)
    timeout = 180

    # Models to generate formulas
    models = [{
        "name": "philo",
        "instances": ["philo5", "philo10", "philo20"]
    }, {
        "name": "train",
        "instances": ["train12", "train24", "train48", "train96"]
    }, {
        "name": "tring",
        "instances": ["tring5", "tring10", "tring20"]
    }, {
        "name":
        "robot",
        "instances": ["robot2", "robot5", "robot10", "robot20", "robot50"]
    }, {
        "name": "spool",
        "instances": ["spool1", "spool2", "spool3", "spool4", "spool5"]
    }, {
        "name": "kanban",
        "instances": ["kanban5", "kanban10", "kanban20"]
    }, {
        "name":
        "cloud",
        "instances": ["cloud5by2", "cloud10by5", "cloud20by10", "cloud40by20"]
    }]

    f = generate_formulas('philo', 'philo10', 2, timeout, paths)
    print(f)

    # pmcsog_formulas = formulas.replace('==1', '').split('\n')[:-1]