-
Notifications
You must be signed in to change notification settings - Fork 0
/
mvmaude.py
396 lines (265 loc) · 10.5 KB
/
mvmaude.py
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
280
281
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
317
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
387
388
389
390
391
392
393
394
395
396
#
# MultiVeStA-Maude
#
import os
import random
import sys
from py4j.java_gateway import JavaGateway, GatewayParameters, CallbackServerParameters
import maude
def fatal_error(message):
"""Issue a fatal error and terminate the simulator"""
print(f'\x1b[31m{message}\x1b[0m', file=sys.stderr)
# sys.exit(0) puts the MultiVeSta in a blocked state, so we send a signal
# to the parent process to terminate its execution
import signal
os.kill(os.getppid(), signal.SIGTERM)
def collect_vars(term, varset):
"""Find a variable in the term"""
for arg in term.arguments():
if arg.isVariable():
varset.add(arg)
else:
collect_vars(arg, varset)
def parse_hole_term(module, term_str):
"""Parse a term with a single variable"""
term = module.parseTerm(term_str)
if term is None:
return None, None
# Collect all variables in the term
varset = set()
collect_vars(term, varset)
if len(varset) > 1:
print(f'\x1b[33mWarning (simulator): the observation "{term_str}"'
'contains more than one variable.\x1b[0m')
elif not varset:
return term, None
# We do not check whether the variable is in the appropriate kind
return term, varset.pop()
class BaseSimulator:
"""Base class for all Maude-based simulators"""
class Java:
implements = ['vesta.python.IPythonSimulatorWrapper']
def __init__(self, initial):
self.initial = initial
self.module = initial.symbol().getModule()
self.state = self.initial
self.time = 0
self.bool_sort = self.module.findSort('Bool')
self.true = self.module.parseTerm('true', self.bool_sort.kind())
self.obs_cache = {} # Cache of parsed observations
def setSimulatorForNewSimulation(self, random_seed):
"""Restart simulator"""
self.state = self.initial
self.time = 0
def performWholeSimulation(self):
"""Perform a complete simulation (until a normal form)"""
initial_time = -1
while initial_time < self.time:
initial_time = self.time
self.performOneStepOfSimulation()
def getTime(self):
"""Get simulation time (number of steps)"""
return float(self.time)
def rval(self, observation):
"""Evaluate observation on the current state of the simulation"""
t, var = self.obs_cache.get(observation, (None, None))
if not t:
t, var = parse_hole_term(self.module, observation)
self.obs_cache[observation] = (t, var)
subs = maude.Substitution({var: self.state})
t = subs.instantiate(t)
t.reduce()
return float(t == self.true) if t.getSort() == self.bool_sort else float(t)
class StrategyStepSimulator(BaseSimulator):
"""Simulator where a strategy is the step"""
def __init__(self, initial, strategy):
super().__init__(initial)
self.strategy = strategy
def setSimulatorForNewSimulation(self, random_seed):
"""Restart simulator and set the random seed"""
super().setSimulatorForNewSimulation(random_seed)
maude.setRandomSeed(random_seed)
def performOneStepOfSimulation(self):
"""Perform a step of the simulation"""
next_state, _ = next(self.state.srewrite(self.strategy), (None, None))
if next_state is not None:
self.state = next_state
self.time += 1
def performWholeSimulation(self):
"""Perform a complete simulation (until a normal form)"""
next_state, _ = next(self.state.srewrite(self.strategy), (None, None))
while next_state is not None:
self.state = next_state
self.time += 1
next_state, _ = next(self.state.srewrite(self.strategy), (None, None))
def all_children(graph, state):
"""All children of a state in a graph"""
children, next_state, index = [], graph.getNextState(state, 0), 0
while next_state != -1:
children.append(next_state)
index += 1
next_state = graph.getNextState(state, index)
return children
class UmaudemcSimulator(BaseSimulator):
"""Simulator that uses the probability assigners of umaudemc"""
def __init__(self, initial, strategy=None, assigner='uniform', opaque=()):
super().__init__(initial)
import umaudemc.probabilistic as pb
self.state_nr = 0
if strategy:
self.graph = pb.maude.StrategyRewriteGraph(initial, strategy, opaque)
else:
self.graph = pb.maude.RewriteGraph(initial)
self.graph.strategyControlled = strategy is not None
self.assigner, found = pb.get_local_assigner(initial.symbol().getModule(), assigner)
if self.assigner is None and not found:
fatal_error(f'Unknown probability assignment method {assigner}.')
def setSimulatorForNewSimulation(self, random_seed):
"""Restart simulator"""
super().setSimulatorForNewSimulation(random_seed)
self.state_nr = 0
def performOneStepOfSimulation(self):
"""Perform a step of the simulation"""
successors = all_children(self.graph, self.state_nr)
if successors:
probs = self.assigner(self.graph, self.state_nr, successors)
self.state_nr, = random.choices(successors, probs)
self.state = self.graph.getStateTerm(self.state_nr)
self.time += 1
class StrategyPathSimulator(BaseSimulator):
"""Simulator based on the strategy where steps are rewrites"""
def __init__(self, module, initial, strategy=None):
super().__init__(initial)
from umaudemc.pyslang import StratCompiler, RandomRunner
from umaudemc import usermsgs
ml = maude.getModule('META-LEVEL')
sc = StratCompiler(module, ml, use_notify=True, ignore_one=True)
p = sc.compile(ml.upStrategy(strategy))
self.runner = RandomRunner(p, initial)
self.runner.detect_nondeterminism(usermsgs)
def setSimulatorForNewSimulation(self, random_seed):
"""Restart simulator"""
super().setSimulatorForNewSimulation(random_seed)
self.runner.reset(self.initial)
def performOneStepOfSimulation(self):
"""Perform a step of the simulation"""
next_state = self.runner.run()
if next_state:
self.state = next_state
self.time += 1
class StrategyDTMCSimulator(BaseSimulator):
"""Simulator based on the strategy where steps are rewrites"""
def __init__(self, module, initial, strategy=None):
super().__init__(initial)
from umaudemc.pyslang import StratCompiler, MarkovRunner, BadProbStrategy
ml = maude.getModule('META-LEVEL')
sc = StratCompiler(module, ml, use_notify=True, ignore_one=True)
p = sc.compile(ml.upStrategy(strategy))
try:
self.graph = MarkovRunner(p, initial).run()
self.node = self.graph
except BadProbStrategy as bps:
fatal_error(bps)
def setSimulatorForNewSimulation(self, random_seed):
"""Restart simulator"""
super().setSimulatorForNewSimulation(random_seed)
self.node = self.graph
def performOneStepOfSimulation(self):
"""Perform a step of the simulation"""
nd_opts, qt_opts, next_node = len(self.node.children), len(self.node.child_choices), None
if nd_opts + qt_opts > 1:
print('\x1b[33mUnquantified nondeterministic choices are present in the strategy.\x1b[0m')
if nd_opts:
next_node, *_ = self.node.children
elif qt_opts:
choice, *_ = self.node.child_choices
next_node = random.choices(list(choice.keys()), choice.values())[0]
if next_node:
self.node = next_node
self.state = self.node.term
self.time += 1
class PMaudeSimulator(BaseSimulator):
"""Python-based PMaude simulator"""
def __init__(self, module, initial, strategy):
super().__init__(initial)
# Construct a PMAude simulator of umaudemc
from umaudemc.simulators import PMaudeSimulator as UmaudemcPMaude
self.simulator = UmaudemcPMaude.new(module, initial, strategy)
if self.simulator is None:
fatal_error('Error (simulator): the given specification does not adhere to the PMaude convention.')
# Delegate on the simulator from umaudemc
self.performOneStepOfSimulation = self.simulator.next_step
self.rval = self.simulator.rval
self.getTime = self.simulator.get_time
def setSimulatorForNewSimulation(self, random_seed):
"""Restart simulator"""
super().setSimulatorForNewSimulation(random_seed)
sim = self.simulator
# Here we do not delegate on self.simulator to obey the random seed
# but the code is essentially the same
if sim.random:
sim.random.copy().reduce()
maude.setRandomSeed(random_seed)
sim.state = sim.initial.copy()
sim.state.rewrite()
sim.step = 0
def getenv_required(name):
"""Get the value of an environment variable and terminate if it does not exists"""
value = os.getenv(name)
if value is None:
fatal_error(f'Error (simulator): missing required {name} environment variable.')
return value
def main():
"""Entry point"""
import argparse
parser = argparse.ArgumentParser(description='MultiVeSta interface to the Maude strategy language')
parser.add_argument('port', help='Port for the connection with Java', type=int)
parser.add_argument('cb_port', help='Port for the callback connection', type=int)
args = parser.parse_args()
print(f'Python engine: expecting connection with java on port: {args.port} '
f'and callback connection on port {args.cb_port}.')
gateway = JavaGateway(start_callback_server=True,
gateway_parameters=GatewayParameters(port=args.port),
callback_server_parameters=CallbackServerParameters(port=args.cb_port))
maude.init()
# The initial data of the problem has to be passed as environment variables
maude_file = getenv_required('MTVMD_FILE')
module_name = os.getenv('MTVMD_MODULE')
metamodule_text = os.getenv('MTVMD_METAMODULE')
initial_text = getenv_required('MTVMD_INITIAL')
strategy_text = getenv_required('MTVMD_STRATEGY')
method_text = getenv_required('MTVMD_METHOD')
opaque_text = os.getenv('MTVMD_OPAQUE')
maude.load(maude_file)
m = maude.getCurrentModule() if module_name is None else maude.getModule(module_name)
opaque = opaque_text.split(',') if opaque_text else ()
if m is None:
fatal_error(f'Error (simulator): no such module "{module_name}" exists.')
if metamodule_text is not None:
mt = m.parseTerm(metamodule_text)
m = mt.downModule()
if m is None:
fatal_error(f'Error (simulator): cannot use "{metamodule_text}" metamodule.')
t = m.parseTerm(initial_text)
if t is None:
fatal_error(f'Error (simulator): cannot parse term "{initial_text}".')
if strategy_text:
s = m.parseStrategy(strategy_text)
if s is None:
fatal_error(f'Error (simulator): cannot parse strategy "{strategy_text}".')
else:
s = None
# Select the simulator depending on the arguments
if method_text == 'step':
simulator = StrategyStepSimulator(t, s)
elif method_text == 'strategy-fast':
simulator = StrategyPathSimulator(m, t, s)
elif method_text == 'strategy':
simulator = StrategyDTMCSimulator(m, t, s)
elif method_text == 'pmaude':
simulator = PMaudeSimulator(m, t, strategy_text)
else:
simulator = UmaudemcSimulator(t, s, method_text, opaque=opaque)
gateway.entry_point.playWithState(simulator)
if __name__ == '__main__':
main()