def test_params1(a, b, c): phi = mtl.parse('G[a, b] x') assert {x.name for x in phi.params} == {'a', 'b'} phi2 = phi[{'a': a, 'b': b}] assert phi2.params == set() assert phi2 == mtl.parse(f'G[{a}, {b}](x)')
def __init__(self, cells, spec=None, seed=None, random_start=False): self.cells = cells self.height, self.width, _ = cells.shape self.agent_pos_list = [] for j in range(self.height): for i in range(self.width): if self.cells[j, i, 0] == 10: self.agent_pos_list.append( np.array([i, j, self.cells[j, i, 2]])) self.cells[j, i, :] = np.array([0, 0, 0]) super().__init__( height=self.height, width=self.width, max_steps=4 * (self.height + self.width), # Set this to True for maximum speed see_through_walls=False, seed=None) self.goal_reward = 1 self.failure_reward = 0 self.step_penalty = -0.01 self.reward_range = (self.max_steps * self.step_penalty + self.failure_reward, self.goal_reward) self.path = [] self.lavas = [] if spec: self.phi = mtl.parse(spec) self.reward_size = 2 else: self.phi = None self.reward_size = 1
def __init__(self, specification): mtl_specs = [mtl.parse(spec) for spec in specification] mtl_spec = mtl_specs[0] if len(mtl_specs) > 1: for spec in mtl_specs[1:]: mtl_spec = (mtl_spec & spec) super().__init__(mtl_spec)
def test_eval_regression_next_neg(): """From issue #219""" d = {"a": [(0, False), (1, True)]} f = mtl.parse("(a & (X (~a)))") v = f(d, quantitative=False, dt=1, time=None) assert not f(d, quantitative=False, dt=1) assert min(t for t, _ in v) >= 0
def test_eval_with_signal(): spec = mtl.parse('F(above_three)') raw_data = signal([(0, 1), (1, 2), (2, 3)], start=0, end=10, tag='a') processed = raw_data.map(lambda val: val['a'] > 3, tag="above_three") assert not spec(processed, quantitative=False) assert spec(processed, quantitative=True) == 0
def test_eval_regression_until_start(): """From issue #221""" x = { "ap1": [(0, True), (0.1, True), (0.2, False)], } phi = (mtl.parse("(X TRUE W X TRUE)")) phi(x, 0, quantitative=False)
def test_scope(): dt = 0.3 phi = mtl.parse('@ap1') assert utils.scope(phi, dt) == 0.3 phi = mtl.parse('(@@ap1 | ap2)') assert utils.scope(phi, dt) == 0.6 phi = mtl.parse('G[0.3, 1.2] F[0.6, 1.5] ap1') assert utils.scope(phi, dt) == 1.2 + 1.5 phi = mtl.parse('G[0.3, 1.2] F ap1') assert utils.scope(phi, dt) == float('inf') phi = mtl.parse('G[0.3, 1.2] (ap1 U ap2)') assert utils.scope(phi, dt) == float('inf')
def test_eval_regression_smoke1(): """From issue #215""" d2 = { 'a': [(0, True), (1, True), (3, True), (4, True), (5, False), (6, True)], 'b': [(0, False), (3, True)], } f2 = mtl.parse('(a U[0,3] b)') f2(d2, quantitative=False)
def test_eval_regression_timed_until(): """From issue #217""" x = { 'start': [(0, True), (200, False)], 'success': [(0, False), (300, True)] } phi = mtl.parse('(~start U[0,120] success)') assert phi(x, time=200, quantitative=False, dt=1) y = { 'start': [(0, True), (1, False), (5, True), (6, True)], 'success': [(0, False), (20, True)] } phi1 = mtl.parse('(start U[0,20] success)') assert phi1(y, time=6, quantitative=False, dt=1) z = { 'start': [(0, True), (200, False)], 'success': [(0, False), (300, True)] } phi2 = mtl.parse('F[0,120]success') assert phi2(z, time=181, quantitative=False, dt=1)
def test_eval_smoke_tests(phi): assert mtl.parse('~ap4')(x, 0, quantitative=False) assert mtl.parse('G[0.1, 0.03] ~ap4')(x, 0, quantitative=False) phi6 = mtl.parse('G[0.1, 0.03] ~ap5') assert phi6(x, 0, quantitative=False) assert phi6(x, 0.2, quantitative=False) assert mtl.parse('G ~ap4')(x, 0, quantitative=False) assert mtl.parse('F ap5')(x, 0, quantitative=False) assert mtl.parse('(ap1 U ap2)')(x, 0, quantitative=False) assert not mtl.parse('(ap2 U ap2)')(x, 0, quantitative=False)
def ParseMTL(pdict): if len(atompDict[list( atompDict.keys())[0]]) > 0: #判断原子命题字典中的第一个命题是否已经装入真值 phi = specificDict['phi'] phi_parse = mtl.parse(phi) ret = str(phi_parse(pdict)) else: ret = "?" #print(ret) return ret
def test_discretize(): dt = 0.3 phi = mtl.parse('@ ap1') assert utils.is_discretizable(phi, dt) phi2 = utils.discretize(phi, dt) phi3 = utils.discretize(phi2, dt) assert phi2 == phi3 phi = mtl.parse('G[0.3, 1.2] F[0.6, 1.5] ap1') assert utils.is_discretizable(phi, dt) phi2 = utils.discretize(phi, dt) phi3 = utils.discretize(phi2, dt) assert phi2 == phi3 phi = mtl.parse('G[0.3, 1.4] F[0.6, 1.5] ap1') assert not utils.is_discretizable(phi, dt) phi = mtl.parse('G[0.3, 1.2] F ap1') assert not utils.is_discretizable(phi, dt) phi = mtl.parse('G[0.3, 1.2] (ap1 U ap2)') assert not utils.is_discretizable(phi, dt) phi = mtl.parse('G[0.3, 0.6] ~F[0, 0.3] a') assert utils.is_discretizable(phi, dt) phi2 = utils.discretize(phi, dt, distribute=True) phi3 = utils.discretize(phi2, dt, distribute=True) assert phi2 == phi3 phi = mtl.TOP assert utils.is_discretizable(phi, dt) phi2 = utils.discretize(phi, dt) phi3 = utils.discretize(phi2, dt) assert phi2 == phi3 phi = mtl.BOT assert utils.is_discretizable(phi, dt) phi2 = utils.discretize(phi, dt) phi3 = utils.discretize(phi2, dt) assert phi2 == phi3
import mtl from mtl import utils from mtl import sugar from mtl.hypothesis import MetricTemporalLogicStrategy from hypothesis import given CONTEXT = { 'ap1': mtl.parse('x'), 'ap2': mtl.parse('(y U z)'), 'ap3': mtl.parse('x'), 'ap4': mtl.parse('(x -> y -> z)'), 'ap5': mtl.parse('(ap1 <-> y <-> z)'), } APS = set(CONTEXT.keys()) def test_inline_context_rigid(): phi = mtl.parse('G ap1') assert phi[CONTEXT] == mtl.parse('G x') phi = mtl.parse('G ap5') assert phi[CONTEXT] == mtl.parse('G(x <-> y <-> z)') @given(MetricTemporalLogicStrategy) def test_inline_context(phi): assert not (APS & phi[CONTEXT].atomic_predicates) @given(MetricTemporalLogicStrategy, MetricTemporalLogicStrategy)
import mtl import sys import json #from sys import argv s = set() for i in sys.argv[1:]: s.add(i) formula = sys.argv[1] a, b = mtl.parse('a'), mtl.parse('b') # Assumes piece wise constant interpolation. dataType = { 'a': [(0, True), (1, False), (3, False)], 'b': [(0, False), (0.2, True), (3, False)] } js = json.dumps(dataType) file = open('/test.txt', 'w') file.write(js) file.close() file = open('/test.txt', 'r') js = file.read() data = json.loads(js) #print(data) file.close() phi = mtl.parse(formula)
def test_walk(): phi = mtl.parse( '(([ ][0, 1] ap1 & < >[1,2] ap2) | (@ap1 U ap2))') assert len(list((~phi).walk())) == 19
dict_values = pickle.load(handle) return dict_values min_val = 20 max_val = 110 mmax = 299 interval = 0.5 times = np.arange(1, mmax, interval) Signals = [] Signals.append(pickle_load(path='data/TRf1.txt')) Signals.append(pickle_load(path='data/TRf2.txt')) Signals.append(pickle_load(path='data/TRf3.txt')) Signals.append(pickle_load(path='data/TRf4.txt')) Signals.append(pickle_load(path='data/TRf5.txt')) Signals.append(pickle_load(path='data/TRf6.txt')) Signals.append(pickle_load(path='data/TRf7.txt')) Signals.append(pickle_load(path='data/TRf8.txt')) for TR in Signals: #print(TR[0], TR[1], TR[2], TR[100], TR[200]) a = [(i, t - min_val) for i, t in zip(times, TR)] b = [(i, t - max_val) for i, t in zip(times, TR)] data = {'a': a, 'b': b} phi = mtl.parse('G(a & ~b)') r = phi(data, quantitative=True) #robustness = r print(r)
import mtl # Assumes piece wise constant interpolation. data = { 'a': [(0, True), (1, False), (3, False)], 'b': [(0, False), (0.2, True), (4, False)] } phi = mtl.parse('F(a | b)') print(phi(data, quantitative=False)) # output: True phi = mtl.parse('F(a | b)') print(phi(data)) # output: True # Note, quantitative parameter defaults to False # Evaluate at t=3. print(phi(data, time=3, quantitative=False)) # output: False # Compute sliding satisifaction. print(phi(data, time=None, quantitative=False)) # output: [(0, True), (0.2, True), (4, False)] # Evaluate with discrete time phi = mtl.parse('X b') print(phi(data, dt=0.2, quantitative=False)) # output: True
import hypothesis.strategies as st from hypothesis_cfg import ContextFreeGrammarStrategy import mtl GRAMMAR = { 'phi': (('Unary', 'phi'), ('(', 'phi', 'Binary', 'phi', ')'), ('AP', ), ('FALSE', ), ('TRUE', )), 'Unary': (('~', ), ('G', 'Interval'), ('F', 'Interval'), ('X', )), 'Interval': (('', ), ('[1, 3]', )), 'Binary': ( (' | ', ), (' & ', ), (' -> ', ), (' <-> ', ), (' ^ ', ), (' U ', ), ), 'AP': (('ap1', ), ('ap2', ), ('ap3', ), ('ap4', ), ('ap5', )), } MetricTemporalLogicStrategy = st.builds( lambda term: mtl.parse(''.join(term)), ContextFreeGrammarStrategy(GRAMMAR, max_length=14, start='phi'))
mmax = 299 interval = 0.5 min_val = 20 max_val = 160 times = np.arange(1, mmax, interval) # ================================== REQUIREMENT 1 ========================================= # ============== Check if signal is contained into defined limits: CONSTANT SIGNAL ============ print(" 1) Requirement: G( Tr(t) > 20 & Tr(t) < 160 )") phi1 = [(i, t - min_val) for i, t in zip(times, TR)] phi2 = [(i, t - max_val) for i, t in zip(times, TR)] data = {'phi1': phi1, 'phi2': phi2} phi3 = mtl.parse('G(phi1 & ~phi2)') out = phi3(data, time=None) robustness = phi3(data, quantitative=True) beta = phi3(data, quantitative=False) print("robustness = ", robustness) print("\n") # ================================== REQUIREMENT 2 ======================================== # 2) ============== Check if signal oscillations are contained: CONSTANT SIGNAL ============== print( " 2) Requirement: Eventually from a time between 0 and 100, the distance between the output\ and the real signal becomes smaller than 0.5 \nF[1,100] (G(|Tr(t) - constant_signal| < 0.5))" )
import mtl import sys from mtl import utils print(sys.argv[1]) #( XX p0 & ( p1 & p2 ) ) {'x5=0.0': 'p0', 'x3>10.0': 'p1', 'x2<20.0': 'p2'} # Assumes piece wise constant interpolation. (time, val) #phi1 = mtl.parse('((a & b & c) | d | e)') #phi2 = mtl.parse('(a -> b) & (~a -> c)') #phi3 = mtl.parse('(a -> b -> c)') #phi4 = mtl.parse('(a <-> b <-> c)') #phi5 = mtl.parse('(x ^ y ^ z)') # Eventually `x` will hold. phi1 = mtl.parse('F x') # `x & y` will always hold. phi2 = mtl.parse('G(x & y)') # `x` holds until `y` holds. # Note that since `U` is binary, it requires parens. phi3 = mtl.parse('(x U y)') # Weak until (`y` never has to hold). phi4 = mtl.parse('(x W y)') # Whenever `x` holds, then `y` holds in the next two time units. phi5 = mtl.parse('G(x -> F[0, 2] y)') # We also support timed until. phi6 = mtl.parse('(a U[0, 2] b)')
def test_sugar_smoke(): mtl.parse('(x <-> x)') mtl.parse('(x -> x)') mtl.parse('(x ^ x)')
def test_stablizing_repr(phi): for _ in range(10): phi, phi2 = mtl.parse(str(phi)), phi assert phi == phi2
def test_inline_context_rigid(): phi = mtl.parse('G ap1') assert phi[CONTEXT] == mtl.parse('G x') phi = mtl.parse('G ap5') assert phi[CONTEXT] == mtl.parse('G(x <-> y <-> z)')