def test_env_act(): """Progress group with environment actions""" ts = transys.AFTS() ts.owner = 'env' ts.sys_actions.add('sys_m0') ts.sys_actions.add('sys_m1') ts.env_actions.add('env_m0') ts.env_actions.add('env_m1') ts.states.add('s0') ts.states.add('s1') ts.transitions.add('s0', 's1', sys_actions='sys_m0', env_actions='env_m0') ts.transitions.add('s0', 's1', sys_actions='sys_m0', env_actions='env_m1') ts.transitions.add('s0', 's1', sys_actions='sys_m1', env_actions='env_m0') ts.transitions.add('s0', 's1', sys_actions='sys_m1', env_actions='env_m1') ts.transitions.add('s1', 's1', sys_actions='sys_m0', env_actions='env_m0') ts.transitions.add('s1', 's1', sys_actions='sys_m1', env_actions='env_m0') ts.transitions.add('s1', 's1', sys_actions='sys_m1', env_actions='env_m1') ts.transitions.add('s1', 's0', sys_actions='sys_m0', env_actions='env_m1') specs = spec.GRSpec(set(), set(), set(), set(), set(), set(), set(), 'eloc = "s0"') # without PG ctrl = synth.synthesize('gr1c', specs, env=ts, ignore_env_init=True) assert ctrl == None # with PG ts.set_progress_map({('env_m0', 'sys_m0'): ('s1', )}) ctrl = synth.synthesize('gr1c', specs, env=ts, ignore_env_init=True) assert ctrl != None
def test_env_act(): """Progress group with environment actions""" ts = transys.AFTS() ts.owner = 'env' ts.sys_actions.add('sys_m0') ts.sys_actions.add('sys_m1') ts.env_actions.add('env_m0') ts.env_actions.add('env_m1') ts.states.add('s0') ts.states.add('s1') ts.transitions.add('s0', 's1', sys_actions='sys_m0', env_actions = 'env_m0') ts.transitions.add('s0', 's1', sys_actions='sys_m0', env_actions = 'env_m1') ts.transitions.add('s0', 's1', sys_actions='sys_m1', env_actions = 'env_m0') ts.transitions.add('s0', 's1', sys_actions='sys_m1', env_actions = 'env_m1') ts.transitions.add('s1', 's1', sys_actions='sys_m0', env_actions = 'env_m0') ts.transitions.add('s1', 's1', sys_actions='sys_m1', env_actions = 'env_m0') ts.transitions.add('s1', 's1', sys_actions='sys_m1', env_actions = 'env_m1') ts.transitions.add('s1', 's0', sys_actions='sys_m0', env_actions = 'env_m1') specs = spec.GRSpec(set(), set(), set(), set(), set(), set(), set(), 'eloc = "s0"') # without PG ctrl = synth.synthesize('gr1c', specs, env=ts, ignore_env_init=True) assert ctrl == None # with PG ts.set_progress_map({('env_m0', 'sys_m0') : ( 's1', ) }) ctrl = synth.synthesize('gr1c', specs, env=ts, ignore_env_init=True) assert ctrl != None
def setUp(self): self.triv = spec.GRSpec(env_vars="x", sys_vars="y", env_init="x", env_prog="x", sys_init="y", sys_prog="y && x") self.triv_M = synth.synthesize("gr1c", self.triv) self.dcounter = spec.GRSpec(sys_vars={"y": (0, 5)}, sys_init=["y=0"], sys_prog=["y=0", "y=5"]) self.dcounter_M = synth.synthesize("gr1c", self.dcounter) self.enumf = spec.GRSpec(sys_vars={'y': ['a', 'b']}, sys_init=['y="a"'], sys_safety=['y = "a" -> X(y = "b")', 'y = "b" -> X(y = "a")']) self.enumf_M = synth.synthesize('gr1c', self.enumf)
def test_multi_pg(): """Multiple progress groups for same mode""" ts = transys.AFTS() ts.owner = 'env' ts.sys_actions.add('mode0') ts.sys_actions.add('mode1') ts.atomic_propositions.add_from(['goal']) ts.states.add('s0') ts.states.add('s1', ap = {'goal'}) ts.states.add('s2') ts.transitions.add('s0', 's0', sys_actions='mode0') ts.transitions.add('s0', 's1', sys_actions='mode0') ts.transitions.add('s2', 's1', sys_actions='mode0') ts.transitions.add('s2', 's2', sys_actions='mode0') ts.transitions.add('s1', 's2', sys_actions='mode1') ts.transitions.add('s1', 's0', sys_actions='mode1') ts.set_progress_map({'mode0' : [set(['s0']), set(['s1'])] }) specs = spec.GRSpec(set(), set(), set(), set(), set(), set(), set(), 'goal') ctrl = synth.synthesize('gr1c', specs, env=ts, ignore_env_init=True) assert ctrl != None
def test_multi_pg(): """Multiple progress groups for same mode""" ts = transys.AFTS() ts.owner = 'env' ts.sys_actions.add('mode0') ts.sys_actions.add('mode1') ts.atomic_propositions.add_from(['goal']) ts.states.add('s0') ts.states.add('s1', ap={'goal'}) ts.states.add('s2') ts.transitions.add('s0', 's0', sys_actions='mode0') ts.transitions.add('s0', 's1', sys_actions='mode0') ts.transitions.add('s2', 's1', sys_actions='mode0') ts.transitions.add('s2', 's2', sys_actions='mode0') ts.transitions.add('s1', 's2', sys_actions='mode1') ts.transitions.add('s1', 's0', sys_actions='mode1') ts.set_progress_map({'mode0': [set(['s0']), set(['s1'])]}) specs = spec.GRSpec(set(), set(), set(), set(), set(), set(), set(), 'goal') ctrl = synth.synthesize('gr1c', specs, env=ts, ignore_env_init=True) assert ctrl != None
def synth_ex(): sys = full_road_ex() variables = '' for i in range(0, len(sys.states())): #print sys.states()[i],i sys.atomic_propositions.add_from({'x' + str(i)}) sys.states[sys.states()[i]]['ap'].add('x' + str(i)) variables += ' && ((X (x' + str(i) + ')) <-> x' + str(i) + ')' variables = variables[4:] #print variables #sys.atomic_propositions.add_from({'home', 'lot'}) #sys.states.add('Xequal0spaceYequal0spacephiequal3', ap={'home'}) #sys.states.add('Xequal5spaceYequal5spacephiequal7', ap={'lot'}) sys.states.initial.add('Xequal0spaceYequal0spacephiequal3') env_vars = {'park', 'frontclear'} env_init = set() env_prog = {'frontclear'} env_safe = set() sys_vars = {'pReach'} sys_init = {'pReach'} sys_prog = {'x0', 'x10'} sys_safe = { '((X (pReach)) <-> ((pSpace) || (pReach && !park)))', '((!frontclear) -> (' + variables + '))' } sys_prog |= {'pReach'} specs = spec.GRSpec(env_vars, sys_vars, env_init, sys_init, env_safe, sys_safe, env_prog, sys_prog) specs.moore = True specs.qinit = '\E \A' ctrl = synth.synthesize('omega', specs, sys=sys) assert ctrl is not None, 'unrealizable' #ctrl.save('discrete.pdf') return sys, ctrl
def test_env_act_all(): """System action progress group with environment actions""" ts = transys.AFTS() ts.owner = 'env' ts.sys_actions.add('sys_m0') ts.sys_actions.add('sys_m1') ts.env_actions.add('env_m0') ts.env_actions.add('env_m1') ts.states.add('s0') ts.states.add('s1') ts.states.add('s2') # all s0 -> s1 ts.transitions.add('s0', 's1', sys_actions='sys_m0', env_actions = 'env_m0') ts.transitions.add('s0', 's1', sys_actions='sys_m0', env_actions = 'env_m1') ts.transitions.add('s0', 's1', sys_actions='sys_m1', env_actions = 'env_m0') ts.transitions.add('s0', 's1', sys_actions='sys_m1', env_actions = 'env_m1') # all s1 -> s2 ts.transitions.add('s1', 's2', sys_actions='sys_m0', env_actions = 'env_m0') ts.transitions.add('s1', 's2', sys_actions='sys_m0', env_actions = 'env_m1') ts.transitions.add('s1', 's2', sys_actions='sys_m1', env_actions = 'env_m0') ts.transitions.add('s1', 's2', sys_actions='sys_m1', env_actions = 'env_m1') ts.transitions.add('s2', 's0', sys_actions='sys_m0', env_actions = 'env_m0') ts.transitions.add('s2', 's1', sys_actions='sys_m1', env_actions = 'env_m0') ts.transitions.add('s2', 's1', sys_actions='sys_m1', env_actions = 'env_m1') ts.transitions.add('s2', 's1', sys_actions='sys_m0', env_actions = 'env_m1') specs = spec.GRSpec(set(), set(), set(), set(), set(), set(), set(), 'eloc = "s0"') # without PG ctrl = synth.synthesize('gr1c', specs, env=ts, ignore_env_init=True) assert ctrl == None # with PG that depends on env (env can change and prevent reach) ts.set_progress_map({('env_m0', 'sys_m0') : ( 's1', 's2' ) }) ctrl = synth.synthesize('gr1c', specs, env=ts, ignore_env_init=True) assert ctrl == None # with PG that does not depend on env ts.set_progress_map({'sys_m0' : ( 's1', 's2' ) }) ctrl = synth.synthesize('gr1c', specs, env=ts, ignore_env_init=True) assert ctrl != None
def test_env_act_all(): """System action progress group with environment actions""" ts = transys.AFTS() ts.owner = 'env' ts.sys_actions.add('sys_m0') ts.sys_actions.add('sys_m1') ts.env_actions.add('env_m0') ts.env_actions.add('env_m1') ts.states.add('s0') ts.states.add('s1') ts.states.add('s2') # all s0 -> s1 ts.transitions.add('s0', 's1', sys_actions='sys_m0', env_actions='env_m0') ts.transitions.add('s0', 's1', sys_actions='sys_m0', env_actions='env_m1') ts.transitions.add('s0', 's1', sys_actions='sys_m1', env_actions='env_m0') ts.transitions.add('s0', 's1', sys_actions='sys_m1', env_actions='env_m1') # all s1 -> s2 ts.transitions.add('s1', 's2', sys_actions='sys_m0', env_actions='env_m0') ts.transitions.add('s1', 's2', sys_actions='sys_m0', env_actions='env_m1') ts.transitions.add('s1', 's2', sys_actions='sys_m1', env_actions='env_m0') ts.transitions.add('s1', 's2', sys_actions='sys_m1', env_actions='env_m1') ts.transitions.add('s2', 's0', sys_actions='sys_m0', env_actions='env_m0') ts.transitions.add('s2', 's1', sys_actions='sys_m1', env_actions='env_m0') ts.transitions.add('s2', 's1', sys_actions='sys_m1', env_actions='env_m1') ts.transitions.add('s2', 's1', sys_actions='sys_m0', env_actions='env_m1') specs = spec.GRSpec(set(), set(), set(), set(), set(), set(), set(), 'eloc = "s0"') # without PG ctrl = synth.synthesize('gr1c', specs, env=ts, ignore_env_init=True) assert ctrl == None # with PG that depends on env (env can change and prevent reach) ts.set_progress_map({('env_m0', 'sys_m0'): ('s1', 's2')}) ctrl = synth.synthesize('gr1c', specs, env=ts, ignore_env_init=True) assert ctrl == None # with PG that does not depend on env ts.set_progress_map({'sys_m0': ('s1', 's2')}) ctrl = synth.synthesize('gr1c', specs, env=ts, ignore_env_init=True) assert ctrl != None
def setUp(self): self.triv = spec.GRSpec(env_vars="x", sys_vars="y", env_init="x & y", env_prog="x", sys_init="y", sys_prog="y && x") self.triv_M = synth.synthesize('omega', self.triv) self.dcounter = spec.GRSpec( sys_vars={"y": (0, 5)}, env_init=['y = 0'], sys_prog=["y=0", "y=5"]) self.dcounter_M = synth.synthesize('omega', self.dcounter) self.enumf = spec.GRSpec( sys_vars={'y': ['a', 'b']}, env_init=['y="a"'], sys_safety=['y = "a" -> X(y = "b")', 'y = "b" -> X(y = "a")']) self.enumf_M = synth.synthesize('omega', self.enumf)
def test_with_pg(self): self.env_sws.set_progress_map({'mode0' : ('s0', 's1', 's2', 's3'), 'mode1' : ('s0',) }) # eventually reach s4 sys_prog = {'exit'} specs = spec.GRSpec(set(), set(), set(), set(), set(), set(), set(), sys_prog) ctrl = synth.synthesize('gr1c', specs, env=self.env_sws, ignore_env_init=True) assert ctrl != None
def test_singleton(): """AFTS with one mode and one state""" ts = transys.AFTS() ts.owner = 'env' ts.sys_actions.add('mode0') ts.states.add('s0') ts.transitions.add('s0', 's0', sys_actions='mode0') specs = spec.GRSpec(set(), set(), set(), set(), set(), set(), set(), set()) ctrl = synth.synthesize('gr1c', specs, env=ts, ignore_env_init=True) assert ctrl != None
def setup_method(self): self.triv = spec.GRSpec(env_vars="x", sys_vars="y", env_init="x & y", env_prog="x", sys_init="y", sys_prog="y && x") self.triv.qinit = r'\E \A' self.triv_M = synth.synthesize(self.triv, solver='omega') self.dcounter = spec.GRSpec(sys_vars={"y": (0, 5)}, env_init=['y = 0'], sys_prog=["y=0", "y=5"]) self.dcounter_M = synth.synthesize(self.dcounter, solver='omega') self.enumf = spec.GRSpec( sys_vars={'y': ['a', 'b']}, env_init=['y="a"'], sys_safety=['y = "a" -> X(y = "b")', 'y = "b" -> X(y = "a")']) self.enumf_M = synth.synthesize(self.enumf, solver='omega')
def setUp(self): self.triv = spec.GRSpec(env_vars="x", sys_vars="y", env_init="x & y", env_prog="x", sys_init="y", sys_prog="y && x") self.triv_M = synth.synthesize( self.triv, solver='omega') self.dcounter = spec.GRSpec( sys_vars={"y": (0, 5)}, env_init=['y = 0'], sys_prog=["y=0", "y=5"]) self.dcounter_M = synth.synthesize( self.dcounter, solver='omega') self.enumf = spec.GRSpec( sys_vars={'y': ['a', 'b']}, env_init=['y="a"'], sys_safety=['y = "a" -> X(y = "b")', 'y = "b" -> X(y = "a")']) self.enumf_M = synth.synthesize( self.enumf, solver='omega')
def create_controller(self): self.handle_init_system() self.handle_static_obstacles() self.handle_allowed_moves() self.follow_targets() #self.no_collision() specs = spec.GRSpec({} ,self.sys_vars,set() , self.sys_init , set() , self.sys_safe , set() , self.sys_prog) #print specs.pretty() specs.moore = True specs.qinit = '\E \A' ctrl = synth.synthesize('gr1c' , specs) assert ctrl is not None, 'Unrealizable' dumpsmach.write_python_case(self.controller_name+'_controller.py', ctrl, classname=self.controller_name+'Controller')
def test_with_pg(self): self.env_sws.set_progress_map({ 'mode0': ('s0', 's1', 's2', 's3'), 'mode1': ('s0', ) }) # eventually reach s4 sys_prog = {'exit'} specs = spec.GRSpec(set(), set(), set(), set(), set(), set(), set(), sys_prog) ctrl = synth.synthesize('gr1c', specs, env=self.env_sws, ignore_env_init=True) assert ctrl != None
def design_C(env_vars, sys_vars, env_init, sys_init, env_safe, sys_safe, env_prog, sys_prog): logging.basicConfig(level=logging.WARNING) show = False # Constructing GR1spec from environment and systems specifications: specs = spec.GRSpec(env_vars, sys_vars, env_init, sys_init, env_safe, sys_safe, env_prog, sys_prog) specs.moore = True specs.qinit = '\E \A' # Synthesize ctrl = synth.synthesize(specs) assert ctrl is not None, 'unrealizable' return ctrl
def test_nopg(): """PG for one mode but not the other""" ts = transys.AFTS() ts.owner = 'env' ts.sys_actions.add('mode0') ts.sys_actions.add('mode1') ts.states.add_from({'s0', 's1', 's2'}) ts.transitions.add('s0', 's1', sys_actions='mode0') ts.transitions.add('s1', 's0', sys_actions='mode0') ts.transitions.add('s1', 's2', sys_actions='mode0') ts.transitions.add('s2', 's2', sys_actions='mode0') ts.set_progress_map({'mode0': ('s0', 's1')}) specs = spec.GRSpec(set(), set(), set(), set(), set(), set(), set(), {'eloc = "s1"', 'eloc = "s2"'}) ctrl = synth.synthesize('gr1c', specs, env=ts, ignore_env_init=True) assert ctrl != None
def test_nopg(): """PG for one mode but not the other""" ts = transys.AFTS() ts.owner = 'env' ts.sys_actions.add('mode0') ts.sys_actions.add('mode1') ts.states.add_from({'s0', 's1', 's2'}) ts.transitions.add('s0', 's1', sys_actions='mode0') ts.transitions.add('s1', 's0', sys_actions='mode0') ts.transitions.add('s1', 's2', sys_actions='mode0') ts.transitions.add('s2', 's2', sys_actions='mode0') ts.set_progress_map({'mode0' : ('s0', 's1')}) specs = spec.GRSpec(set(), set(), set(), set(), set(), set(), set(), {'eloc = "s1"', 'eloc = "s2"'}) ctrl = synth.synthesize('gr1c', specs, env=ts, ignore_env_init=True) assert ctrl != None
def tulip_synthesis(self): # call Tulip to synthesize a discrete controller sys = transys.FTS() sys.states.add_from(self.free_space.keys()) idx = self.determine_discrete_state() sys.states.initial.add(idx) for node in self.discrete_graph.edges.keys(): sys.transitions.add_comb(set([node]), set(self.discrete_graph.edges[node])) sys.atomic_propositions.add_from(set(self.ap.keys())) for state in self.label.keys(): sys.states.add(state,ap=set(self.label[state])) ctrl = synth.synthesize(self.Tulip_spec, sys=sys) if ctrl is None: pdb.set_trace() else: dumpsmach.write_python_case("discrete_ctrl.py", ctrl, classname="symb_ctrl") from discrete_ctrl import symb_ctrl self.discrete_controller = symb_ctrl() self.prior_discrete_graph = self.discrete_graph.copy() self.prior_label = self.label.copy()
sys_prog = {'home'} # []<>home sys_safe = {'(X (X0reach) <-> lot) || (X0reach && !park)'} sys_prog |= {'X0reach'} # @specs_setup_section_end@ # @specs_create_section@ # Create the specification specs = spec.GRSpec(env_vars, sys_vars, env_init, sys_init, env_safe, sys_safe, env_prog, sys_prog) # @specs_create_section_end@ # # Controller synthesis # # At this point we can synthesize the controller using one of the available # methods. Here we make use of gr1c. # # @synthesize@ ctrl = synth.synthesize('gr1c', specs, sys=sys) # @synthesize_end@ # # Generate a graphical representation of the controller for viewing, # or a textual representation if pydot is missing. # # @plot_print@ if not ctrl.save('discrete.png'): print(ctrl) # @plot_print_end@
# Create a GR(1) specification specs = spec.GRSpec(env_vars, sys_vars, env_init, sys_init, env_safe, sys_safe, env_prog, sys_prog) # # Controller synthesis # # The controller decides based on current variable values only, # without knowing yet the next values that environment variables take. # A controller with this information flow is known as Moore. specs.moore = True # Ask the synthesizer to find initial values for system variables # that, for each initial values that environment variables can # take and satisfy `env_init`, the initial state satisfies # `env_init /\ sys_init`. specs.qinit = '\E \A' # i.e., "there exist sys_vars: forall sys_vars" # At this point we can synthesize the controller # using one of the available methods. strategy = synth.synthesize(specs) assert strategy is not None, 'unrealizable' # Generate a graphical representation of the controller for viewing, # or a textual representation if pydot is missing. if not strategy.save('gr1.png'): print(strategy) # simulate print(strategy) machines.random_run(strategy, N=10)
env_vars = {'park'} env_init = set() # empty set env_prog = '!park' env_safe = set() # empty set # System variables and requirements sys_vars = {'X0reach'} sys_init = {'X0reach'} sys_prog = {'home'} # []<>home sys_safe = {'(X(X0reach) <-> lot) || (X0reach && !park)'} sys_prog |= {'X0reach'} # Create the specification specs = spec.GRSpec(env_vars, sys_vars, env_init, sys_init, env_safe, sys_safe, env_prog, sys_prog) specs.moore = False specs.qinit = '\A \E' specs.plus_one = False # @synthesize_section@ """Synthesize""" ctrl = synth.synthesize( specs, sys=disc_dynamics.ts, ignore_sys_init=True, solver='gr1c') # Unrealizable spec ? if ctrl is None: sys.exit() # Export Simulink Model tomatlab.export('robot_continuous.mat', ctrl, sys_dyn, disc_dynamics, disc_params)
$ ./solverand.py 3 5 """ from __future__ import print_function import sys import tulip.gridworld as gw from tulip import synth if len(sys.argv) > 3 or "-h" in sys.argv: print("Usage: solverand.py [H W]") sys.exit(1) if len(sys.argv) >= 3: (height, width) = (int(sys.argv[1]), int(sys.argv[2])) else: (height, width) = (5, 10) Z = gw.random_world((height, width), wall_density=0.2, num_init=1, num_goals=2) print(Z) spc = Z.spec() spc.moore = False spc.qinit = r'\A \E' if not synth.is_realizable(spc, solver='omega'): print("Not realizable.") else: ctrl = synth.synthesize(spc, solver='omega') if not ctrl.save('ctrl-solverand.svg'): print(ctrl)
sys_vars["stage"] = (xMinBound, xMaxBound) sys_prog = set() sys_safe = set() for i in range(1, xMaxBound): sys_safe |= {("((stage = " + str(i) + ") && right) -> (X (stage = " + str(i + 1) + "))")} sys_safe |= {("(stage = 4) -> (!(aL1 || aL2 || afarL2 || afarL1))")} sys_safe |= {("(stage = 1) -> (!(aR1 || afarR2 || afarR1|| aR2 ))")} for i in range(0, xMaxBound + 1): sys_safe |= {("((stage = " + str(i) + ") && stay) -> (X (stage = " + str(i) + "))")} for i in range(1, xMaxBound): sys_safe |= {("((stage = " + str(i) + ") && left) -> (X (stage = " + str(i - 1) + "))")} sys_safe |= specset specs = spec.GRSpec(env_vars, sys_vars, env_init, sys_init, env_safe, sys_safe, env_prog, sys_prog) start = time.clock() ctrl = synth.synthesize("gr1c", specs, sys=sys) # if not ctrl.save('discerete'+str(x)+'.png'): # print(ctrl) finish = time.clock() with open("Output1da.txt", "a") as text_file: text_file.write("{0}: {1} Size: {2}\n".format(x, finish - start, ctrl.size())) # ignore_env_init= True env = env1
You can configure it also directly in python, but rewriting or copy/pasting again and again the same base configuration is not very efficient. """ import logging.config import json import pprint fname = 'logging_config.json' with open(fname, 'r') as f: config = json.load(f) print('Your logging config is:\n{s}') pprint.pprint(config) logging.config.dictConfig(config) from tulip import transys, spec, synth sys = transys.FTS() sys.states.add_from({0, 1}) sys.states.initial.add(0) sys.add_edges_from([(0, 1), (1, 0)]) sys.atomic_propositions.add('p') sys.node[0]['ap'] = {'p'} specs = spec.GRSpec(sys_vars={'p'}, sys_prog={'p'}) mealy = synth.synthesize('gr1c', specs, sys=sys)
# Augment the environmental description to make it GR(1) #! TODO: create a function to convert this type of spec automatically # Define the specification #! NOTE: maybe "synthesize" should infer the atomic proposition from the # transition system? Or, we can declare the mode variable, and the values # of the mode variable are read from the transition system. sys_vars = {'X0reach'} sys_init = {'X0reach', 'sys_actions = "right"'} sys_prog = {'home'} # []<>home sys_safe = {'(X (X0reach) <-> lot) || (X0reach && !park)'} sys_prog |= {'X0reach'} # Create the specification specs = spec.GRSpec(env_vars, sys_vars, env_init, sys_init, env_safe, sys_safe, env_prog, sys_prog) specs.qinit = r'\E \A' # Controller synthesis # # At this point we can synthesize the controller using one of the available # methods. # ctrl = synth.synthesize(specs, env=env_sws) assert ctrl is not None, 'unrealizable' # Generate a graphical representation of the controller for viewing if not ctrl.save('only_mode_controlled.png'): print(ctrl)
# [](X (X0reach) <-> lot || (X0reach && !park)) # # Augment the environmental description to make it GR(1) #! TODO: create a function to convert this type of spec automatically # Define the specification #! NOTE: maybe "synthesize" should infer the atomic proposition from the # transition system? Or, we can declare the mode variable, and the values # of the mode variable are read from the transition system. sys_vars = {'X0reach'} sys_init = {'X0reach','sys_actions = "right"'} sys_prog = {'home'} # []<>home sys_safe = {'(X (X0reach) <-> lot) || (X0reach && !park)'} sys_prog |= {'X0reach'} # Create the specification specs = spec.GRSpec(env_vars, sys_vars, env_init, sys_init, env_safe, sys_safe, env_prog, sys_prog) # Controller synthesis # # At this point we can synthesize the controller using one of the available # methods. Here we make use of gr1c. # ctrl = synth.synthesize('gr1c', specs, env=env_sws) # Generate a graphical representation of the controller for viewing if not ctrl.save('only_mode_controlled.png'): print(ctrl)
sys_safe = {'vol_diff'} sys_prog = {'True'} #{'vol_diff2'} specs = spec.GRSpec(env_vars, sys_disc_vars, env_init, sys_init, env_safe, sys_safe, env_prog, sys_prog) print(specs.pretty()) """Synthesis""" print("Starting synthesis") if os.name == "posix": start = os.times()[2] ctrl = synth.synthesize( 'gr1c', specs, sys=sys_ts.ts, ignore_sys_init=True, #action_vars=('u_in', 'act') ) if os.name == "posix": end = os.times()[2] elapsed = (end - start) logger.info('Synthesis lasted: ' + str(elapsed)) logger.info(ctrl) ctrl.save(imgpath + 'double_tank.pdf') ax = plot_strategy(sys_ts, ctrl) ax.figure.savefig(imgpath + 'proj_mealy.pdf') """Simulate"" num_it = 25 init_state = {}
sys_vars = {'mem'} sys_init = {'mem'} sys_prog = {'home'} # one additional requirement: if in lot, # then stay there until park signal is turned off sys_safe = {'(X(mem) <-> lot) || (mem && !park)', '((lot && park) -> X(lot))'} sys_prog |= {'mem'} specs = spec.GRSpec(sys_vars=sys_vars, sys_init=sys_init, sys_safety=sys_safe, env_prog=env_prog, sys_prog=sys_prog) ctrl = synth.synthesize('gr1c', specs, sys=sys, env=env0) ctrl.save('sys_and_env_ts0.pdf') logger.info(ctrl) """Park as an env action """ env1 = transys.FTS() env1.states.add('e0') env1.states.initial.add('e0') env1.env_actions.add_from({'park', ''}) env1.transitions.add('e0', 'e0', env_actions='park') env1.transitions.add('e0', 'e0', env_actions='') logger.info(env1) specs = spec.GRSpec(sys_vars=sys_vars,
print(sys_swe) sys_swe.save('sys_swe.pdf') # (park & sun) & []<>!park && []<>sum env_vars = {'park'} env_init = {'park', 'sun'} env_prog = {'!park', 'sun'} env_safe = set() # (s0 & mem) & []<> home & [](park -> <>lot) sys_vars = {'mem'} sys_init = {'mem', 's0'} sys_prog = {'home'} # []<>home sys_safe = {'next(mem) <-> lot || (mem && !park)'} sys_prog |= {'mem'} # Create the specification specs = spec.GRSpec(env_vars, sys_vars, env_init, sys_init, env_safe, sys_safe, env_prog, sys_prog) # Controller synthesis ctrl = synth.synthesize('gr1c', specs, sys=sys_swe, ignore_sys_init=True, bool_actions=True) if not ctrl.save('switch.pdf'): print(ctrl)
env_prog = '!park' env_safe = set() # empty set # System variables and requirements sys_vars = {'X0reach'} sys_init = {'X0reach'} sys_prog = {'home'} # []<>home sys_safe = {'(X(X0reach) <-> lot) || (X0reach && !park)'} sys_prog |= {'X0reach'} # Create the specification specs = spec.GRSpec(env_vars, sys_vars, env_init, sys_init, env_safe, sys_safe, env_prog, sys_prog) specs.moore = False specs.qinit = r'\A \E' specs.plus_one = False # @synthesize_section@ """Synthesize""" ctrl = synth.synthesize(specs, sys=disc_dynamics.ts, ignore_sys_init=True, solver='gr1c') # Unrealizable spec ? if ctrl is None: sys.exit() # Export Simulink Model tomatlab.export('robot_continuous.mat', ctrl, sys_dyn, disc_dynamics, disc_params)
import sys import tulip.gridworld as gw from tulip import synth if len(sys.argv) > 3 or "-h" in sys.argv: print("Usage: solverand.py [H W]") sys.exit(1) if len(sys.argv) >= 3: (height, width) = (int(sys.argv[1]), int(sys.argv[2])) else: (height, width) = (5, 10) Z = gw.random_world((height, width), wall_density=0.2, num_init=1, num_goals=2) print(Z) spc = Z.spec() spc.moore = False spc.qinit = r'\A \E' if not synth.is_realizable(spc, solver='omega'): print("Not realizable.") else: ctrl = synth.synthesize(spc, solver='omega') if not ctrl.save('ctrl-solverand.svg'): print(ctrl)
'loc="d" -> next(loc="a" || loc="e")', 'loc="e" -> next(loc="d" || loc="b" || loc="foo")', 'loc="foo" -> next(loc="e" || loc="c")', } sys_vars['mem'] = 'boolean' sys_init |= {'mem'} sys_safe |= {'next(mem) <-> (loc="a") || (mem && !park)'} sys_prog = {'mem'} specs = spec.GRSpec(env_vars=env_vars, sys_vars=sys_vars, sys_init=sys_init, sys_safety=sys_safe, env_prog=env_prog, sys_prog=sys_prog) specs.moore = False specs.qinit = '\A \E' ctrl = synth.synthesize(specs) ctrl.save('gr1_arbitrary_set0.pdf') """ 2nd example """ sys = trs.FTS() states = {'a', 'b', 'c', 'd', 'e', 'foo'} sys.states.add_from(states) sys.states.initial.add('a') sys.transitions.add_from( [('a', x) for x in {'b', 'd'}] + [('b', x) for x in {'a', 'e', 'c'}] + [('c', x) for x in {'b', 'foo'}] +
'''(active_path = "up2" & driving') -> active_path' != "none" ''', '''goal -> active_path="none"''', } sys_prog = { 'goal | safe_stopped | emergency_stopped', '!driving', } # %% specs = spec.GRSpec(env_vars, sys_vars, env_init, sys_init, env_safe, sys_safe, env_prog, sys_prog) specs.qinit = '\E \A' specs.moore = False specs.plus_one = False # %% ctrl = synth.synthesize(specs, ignore_sys_init=False, ignore_env_init=False) # %% ctrl._transition_dot_label_format['separator'] = r'\n' ctrl.save('supervisor.pdf') # %% with open('synthesized_controller.pickle', 'wb') as f: pickle.dump(ctrl, f)
# of the mode variable are read from the transition system. sys_vars = {'X0reach'} sys_init = {'X0reach'} sys_prog = {'home'} # []<>home sys_safe = {'(X (X0reach) <-> lot) || (X0reach && !park)'} sys_prog |= {'X0reach'} # Possible additional specs # It is unsafe to "break" (switch to gear0) when road is slippery sys_safe |= { '(sys_actions = "gear1" && env_actions = "slippery") -> ' + 'X (sys_actions = "gear1")' } # to use int actions: # sys_safe |= {'((act = gear1) && (eact = slippery)) -> X (act = gear1)'} # Create the specification specs = spec.GRSpec(env_vars, sys_vars, env_init, sys_init, env_safe, sys_safe, env_prog, sys_prog) # Controller synthesis # # At this point we can synthesize the controller using one of the available # methods. Here we make use of gr1c. # ctrl = synth.synthesize('gr1c', specs, sys=sys_hyb, ignore_sys_init=True) if not ctrl.save('hybrid.png'): print(ctrl)
sys_safe = {'vol_diff'} sys_prog = {'True'} #{'vol_diff2'} specs = spec.GRSpec(env_vars, sys_disc_vars, env_init, sys_init, env_safe, sys_safe, env_prog, sys_prog) print(specs.pretty()) ## Synthesis print("Starting synthesis") if os.name == "posix": start = os.times()[2] ctrl = synth.synthesize( 'gr1c', specs, sys=sys_ts.ts, ignore_sys_init=True, #action_vars=('u_in', 'act') ) if os.name == "posix": end = os.times()[2] elapsed = (end - start) logger.info('Synthesis lasted: ' + str(elapsed)) logger.info(ctrl) ctrl.save(imgpath + 'double_tank.pdf') ax = plot_strategy(sys_ts, ctrl) ax.figure.savefig(imgpath + 'proj_mealy.pdf') ## Simulate
base configuration is not very efficient. """ from __future__ import print_function import logging.config import json import pprint fname = 'logging_config.json' with open(fname, 'r') as f: config = json.load(f) print('Your logging config is:\n{s}') pprint.pprint(config) logging.config.dictConfig(config) from tulip import transys, spec, synth sys = transys.FTS() sys.states.add_from({0, 1}) sys.states.initial.add(0) sys.add_edges_from([(0, 1), (1, 0)]) sys.atomic_propositions.add('p') sys.node[0]['ap'] = {'p'} specs = spec.GRSpec(sys_vars={'p'}, sys_prog={'p'}) mealy = synth.synthesize(specs, sys=sys, solver='gr1c')
# System variables and requirements sys_vars = {'X0reach'} # []<>home sys_prog = {'home'} # [](park -> <> lot) sys_init = {'X0reach'} sys_safe = {'X(X0reach) <-> lot || (X0reach && !park)'} sys_prog |= {'X0reach'} # Create the specification specs = spec.GRSpec(env_vars, sys_vars, env_init, sys_init, env_safe, sys_safe, env_prog, sys_prog) specs.moore = True specs.qinit = '\E \A' # Synthesize ctrl = synth.synthesize(specs, sys=disc_dynamics.ts, ignore_sys_init=True) assert ctrl is not None, 'unrealizable' if plotting: ax = plot_strategy(disc_dynamics, ctrl) ax.figure.savefig('pwa_proj_mealy.pdf') # Save graphical representation of controller for viewing if not ctrl.save('pwa.png'): print(ctrl) # Simulation
# [](X (X0reach) <-> lot || (X0reach && !park)) # # Augment the environmental description to make it GR(1) #! TODO: create a function to convert this type of spec automatically # Define the specification #! NOTE: maybe "synthesize" should infer the atomic proposition from the # transition system? Or, we can declare the mode variable, and the values # of the mode variable are read from the transition system. sys_vars = {'X0reach'} sys_init = {'X0reach','sys_actions = right'} sys_prog = {'home'} # []<>home sys_safe = {'(X (X0reach) <-> lot) || (X0reach && !park)'} sys_prog |= {'X0reach'} # Create the specification specs = spec.GRSpec(env_vars, sys_vars, env_init, sys_init, env_safe, sys_safe, env_prog, sys_prog) # Controller synthesis # # At this point we can synthesize the controller using one of the available # methods. Here we make use of JTLV. # ctrl = synth.synthesize('jtlv', specs, env=env_sws) # Generate a graphical representation of the controller for viewing if not ctrl.save('only_mode_controlled.png'): print(ctrl)
# Augment the environmental description to make it GR(1) #! TODO: create a function to convert this type of spec automatically # Define the specification #! NOTE: maybe "synthesize" should infer the atomic proposition from the # transition system? Or, we can declare the mode variable, and the values # of the mode variable are read from the transition system. sys_vars = {'X0reach'} sys_init = {'X0reach','sys_actions = "right"'} sys_prog = {'home'} # []<>home sys_safe = {'(X (X0reach) <-> lot) || (X0reach && !park)'} sys_prog |= {'X0reach'} # Create the specification specs = spec.GRSpec(env_vars, sys_vars, env_init, sys_init, env_safe, sys_safe, env_prog, sys_prog) specs.qinit = '\E \A' # Controller synthesis # # At this point we can synthesize the controller using one of the available # methods. # ctrl = synth.synthesize(specs, env=env_sws) assert ctrl is not None, 'unrealizable' # Generate a graphical representation of the controller for viewing if not ctrl.save('only_mode_controlled.png'): print(ctrl)
# # Augment the environmental description to make it GR(1) #! TODO: create a function to convert this type of spec automatically # Define the specification #! NOTE: maybe "synthesize" should infer the atomic proposition from the # transition system? Or, we can declare the mode variable, and the values # of the mode variable are read from the transition system. sys_vars = {'X0reach'} sys_init = {'X0reach'} sys_prog = {'home'} # []<>home sys_safe = {'(X (X0reach) <-> lot) || (X0reach && !park)'} sys_prog |= {'X0reach'} # Create the specification specs = spec.GRSpec(env_vars, sys_vars, env_init, sys_init, env_safe, sys_safe, env_prog, sys_prog) # Controller synthesis # # At this point we can synthesize the controller using one of the available # methods. Here we make use of gr1c. # ctrl = synth.synthesize('gr1c', specs, sys=sys_swe, ignore_sys_init=True) # @plot_print@ if not ctrl.save('environment_switching.png'): print(ctrl) # @plot_print_end@
sys_swe.states.add(states[0], ap={'home'}) sys_swe.states.add(states[1], ap={'lot'}) print(sys_swe) sys_swe.save('sys_swe.pdf') # (park & sun) & []<>!park && []<>sum env_vars = {'park'} env_init = {'park', 'sun'} env_prog = {'!park','sun'} env_safe = set() # (s0 & mem) & []<> home & [](park -> <>lot) sys_vars = {'mem'} sys_init = {'mem', 's0'} sys_prog = {'home'} # []<>home sys_safe = {'next(mem) <-> lot || (mem && !park)'} sys_prog |= {'mem'} # Create the specification specs = spec.GRSpec(env_vars, sys_vars, env_init, sys_init, env_safe, sys_safe, env_prog, sys_prog) # Controller synthesis ctrl = synth.synthesize('gr1c', specs, sys=sys_swe, ignore_sys_init=True, bool_actions=True) if not ctrl.save('switch.pdf'): print(ctrl)
# [](X (X0reach) <-> lot || (X0reach && !park)) # # Augment the environmental description to make it GR(1) #! TODO: create a function to convert this type of spec automatically # Define the specification #! NOTE: maybe "synthesize" should infer the atomic proposition from the # transition system? Or, we can declare the mode variable, and the values # of the mode variable are read from the transition system. sys_vars = {'X0reach'} sys_init = {'X0reach', 'sys_actions = right'} sys_prog = {'home'} # []<>home sys_safe = {'X (X0reach) <-> lot || (X0reach && !park)'} sys_prog |= {'X0reach'} # Create the specification specs = spec.GRSpec(env_vars, sys_vars, env_init, sys_init, env_safe, sys_safe, env_prog, sys_prog) # Controller synthesis # # At this point we can synthesize the controller using one of the available # methods. Here we make use of JTLV. # ctrl = synth.synthesize('jtlv', specs, sys=sys_sws) # Generate a graphical representation of the controller for viewing if not ctrl.save('controlled_switching.png'): print(ctrl)
sys_vars = {'mem'} sys_init = {'mem'} sys_prog = {'home'} # one additional requirement: if in lot, # then stay there until park signal is turned off sys_safe = {'(X(mem) <-> lot) || (mem && !park)', '((lot && park) -> X(lot))'} sys_prog |= {'mem'} specs = spec.GRSpec(sys_vars=sys_vars, sys_init=sys_init, sys_safety=sys_safe, env_prog=env_prog, sys_prog=sys_prog) specs.moore = False specs.qinit = '\A \E' ctrl = synth.synthesize(specs, sys=sys, env=env0) ctrl.save('sys_and_env_ts0.pdf') logger.info(ctrl) """Park as an env action """ env1 = transys.FTS() env1.owner = 'env' env1.states.add('e0') env1.states.initial.add('e0') env1.env_actions.add_from({'park', 'none'}) env1.transitions.add('e0', 'e0', env_actions='park') env1.transitions.add('e0', 'e0', env_actions='none') logger.info(env1)
sys_prog |= {'stage = 0'} sys_prog |= {'stage = 3'} sys_safe |= {('((stage = 0) && (sa'+str((2*x)-1)+')) -> X (stage = 1)')} sys_safe |= {('((stage = 0) && (!sa'+str((2*x)-1)+')) -> X (stage = 0)')} sys_safe |= {('((stage = 1) && (sa'+str(2*x)+')) -> X (stage = 2)')} sys_safe |= {('((stage = 1) && (!sa'+str(2*x)+')) -> X (stage = 1)')} sys_safe |= {('((stage = 2) && (sa'+str((x*y) - 1)+')) -> X (stage = 3)')} sys_safe |= {('((stage = 2) && (!sa'+str((x*y) - 1)+')) -> X (stage = 2)')} sys_safe |= {('((stage = 3) && (sa'+str(0)+')) -> X (stage = 0)')} sys_safe |= {('((stage = 3) && (!sa'+str(0)+')) -> X (stage = 3)')} sys_safe |= specset specs = spec.GRSpec(env_vars, sys_vars, env_init, sys_init, env_safe, sys_safe, env_prog, sys_prog) ctrl = synth.synthesize('gr1c',specs, sys=sys) finish = time.clock() print finish - start dumpsmach.write_python_case("gr1controller"+str(x)+".py", ctrl, classname="ExampleCtrl") finish = time.clock() print finish - start #finish = time.clock() #print finish - start #print specs.pretty() #if not ctrl.save('discerete2.png'): # print(ctrl) #finish = time.clock() #print finish - start
# Define the specification #! NOTE: maybe "synthesize" should infer the atomic proposition from the # transition system? Or, we can declare the mode variable, and the values # of the mode variable are read from the transition system. sys_vars = {'X0reach'} sys_init = {'X0reach'} sys_prog = {'home'} # []<>home sys_safe = {'next(X0reach) <-> lot || (X0reach && !park)'} sys_prog |= {'X0reach'} # Possible additional specs # It is unsafe to "break" (switch to gear0) when road is slippery sys_safe |= {'(gear1 && slippery) -> next(gear1)'} # to use int actions with gr1c: # sys_safe |= {'((act = gear1) && (eact = slippery)) -> next(act = gear1)'} # Create the specification specs = spec.GRSpec(env_vars, sys_vars, env_init, sys_init, env_safe, sys_safe, env_prog, sys_prog) # Controller synthesis # # At this point we can synthesize the controller using one of the available # methods. Here we make use of JTLV. # ctrl = synth.synthesize('jtlv', specs, sys=sys_hyb, ignore_sys_init=True) if not ctrl.save('hybrid.png'): print(ctrl)
"""Specifications""" # Environment variables and assumptions env_vars = {'park'} env_init = set() # empty set env_prog = '!park' env_safe = set() # empty set # System variables and requirements sys_vars = {'X0reach'} sys_init = {'X0reach'} sys_prog = {'home'} # []<>home sys_safe = {'(X(X0reach) <-> lot) || (X0reach && !park)'} sys_prog |= {'X0reach'} # Create the specification specs = spec.GRSpec(env_vars, sys_vars, env_init, sys_init, env_safe, sys_safe, env_prog, sys_prog) # @synthesize_section@ """Synthesize""" ctrl = synth.synthesize('jtlv', specs, sys=disc_dynamics.ts, ignore_sys_init=True) # Generate a graphical representation of the controller for viewing if not ctrl.save('continuous.png'): print(ctrl) # @synthesize_section_end@ # Simulation
sys_init = set() #sys_prog = {'LOW','HIGH'} sys_prog = set() sys_safe = {'!OUTSIDE'} specs = spec.GRSpec(env_vars, sys_vars, env_init, sys_init, env_safe, sys_safe, env_prog, sys_prog) """ work with only_mode_controlled.py - make a manual AOFTS from there. Send it to synth. Change env_augmented_open_fts2spec to call env_open_fts2spec and then append equil pts. Allow self_trans and see what controller happens Put !OUTSIDE inside env_spec. """ #jt_fts = synth.synthesize('jtlv', specs, env=abstMOS.ts, ignore_env_init=True, rm_deadends=False) gr_fts = synth.synthesize('gr1c', specs, env=abstMOS.ts, rm_deadends=True, ignore_env_init=True) #print (gr_fts) if not gr_fts.save('gr_fts.eps'): print(gr_fts) disc_dynamics = abstMOS ctrl = gr_fts Tc = [18.0] Th = [16.0] s0_part = find_discrete_state([Tc[0], Th[0]], disc_dynamics.ppp) #mach = synth.determinize_machine_init(ctrl,{'sys_actions':'on'}) # - to be used if we want a certain mode only sim_hor = 130 N = 1 # N = number of steps between each sampled transition
# Augment the system description to make it GR(1) sys_vars |= {'X0reach'} sys_init |= {'X0reach'} sys_safe |= {'(X (X0reach) <-> X0) || (X0reach && !park)'} sys_prog |= {'X0reach', 'X5'} # Create a GR(1) specification specs = spec.GRSpec(env_vars, sys_vars, env_init, sys_init, env_safe, sys_safe, env_prog, sys_prog) # # Controller synthesis # # At this point we can synthesize the controller # using one of the available methods. # Here we make use of jtlv. # ctrl = synth.synthesize('jtlv', specs) # Generate a graphical representation of the controller for viewing, # or a textual representation if pydot is missing. if not ctrl.save('gr1.png'): print(ctrl) # either select current state before simulation ctrl.states.current = [0] ctrl.simulate(inputs_sequence='random', iterations=10) # or pass it to simulate ctrl.simulate(inputs_sequence='random', iterations=10, current_state=0)
print specset env_vars = set() env_init = set() env_prog = set() env_safe = set() sys_vars = set() sys_init = set() sys_prog = set() sys_safe = specset specs = spec.GRSpec(env_vars, sys_vars, env_init, sys_init, env_safe, sys_safe, env_prog, sys_prog, ) start = time.clock() ctrl = synth.synthesize('gr1c',specs, sys=sys,env = env1) finish = time.clock() if not ctrl.save('disceretee'+str(q)+'.png'): print(ctrl) print finish - start with open("Output2d.txt", "a") as text_file: text_file.write("{0}: {1} Size: {2}\n".format(q,finish - start,ctrl.size()))
index_1 - 1] + ' && ' if index_2 == 0: new_sys_collision_2 += 'init' + str(other_r) + ' )' else: new_sys_collision_2 += env_vars_list[other_r - 1][index_2 - 1] + ' )' new_sys_collision_2 += ' -> (!go' + str( r) + ' || ' + '!go' + str(other_r) + ' )' sys_collision_2 |= {new_sys_collision_2} # sys_safe |= sys_collision_2 sys_col_simple = {'!(s1a2a1 && s2a2a1)'} sys_safe |= sys_col_simple # Create a GR(1) specification specs = spec.GRSpec(env_vars, sys_vars, env_init, sys_init, env_safe, sys_safe, env_prog, sys_prog) specs.qinit = '\A \E' # Moore initial condition synthesized too specs.moore = False specs.plus_one = False print('Start synthesis') ctrl = synth.synthesize(specs) print('End synthesis') assert ctrl is not None, 'unrealizable' # Generate a graphical representation of the controller for viewing if not ctrl.save('gr1_set_1111.png'): print(ctrl) machines.random_run(ctrl, N=30)
def create_w_specs_all_init_cond(current_horizon, x_goal_loc, y_goal_loc, w_part, transition_part, dimension_x, dimension_y): # Don't synthesize for corner w regions (i.e. w region that's only a corner) that can't be fulfilled (... so ugly) # Note: Better way of doing this would be to not add corner regions to w_part... if (w_part[current_horizon] == [(dimension_x, dimension_y, 1)] or w_part[current_horizon] == [(dimension_x, dimension_y, 2)] or w_part[current_horizon] == [(dimension_x, dimension_y, 3)] or w_part[current_horizon] == [(dimension_x, dimension_y, 4)] or w_part[current_horizon] == [(dimension_x, 1, 1)] or w_part[current_horizon] == [(dimension_x, 1, 2)] or w_part[current_horizon] == [(dimension_x, 1, 3)] or w_part[current_horizon] == [(dimension_x, 1, 4)] or w_part[current_horizon] == [(1, dimension_y, 1)] or w_part[current_horizon] == [(1, dimension_y, 2)] or w_part[current_horizon] == [(1, dimension_y, 3)] or w_part[current_horizon] == [(1, dimension_y, 4)] or w_part[current_horizon] == [(1, 1, 1)] or w_part[current_horizon] == [(1, 1, 2)] or w_part[current_horizon] == [(1, 1, 3)] or w_part[current_horizon] == [(1, 1, 4)]): return # Create FTS and actions sys_auto = transys.FTS() sys_auto.sys_actions.add_from({'Stop', 'Go'}) # Fake AP's to enable all specs related to base and goal position sys_auto.states.add_from(['FAKE']) sys_auto.atomic_propositions.add_from({'Base', 'GoalPos'}) sys_auto.states['FAKE']['ap'] |= {'Base', 'GoalPos'} # Add all AP's for the transition space, including those tied to 'Base' and 'GoalPos' if present in transition space for locat in transition_part[current_horizon]: add_ap_sub = 'Pos' + str(locat[0]) + '_' + str(locat[1]) + 'Ori' + str( locat[2]) sys_auto.states.add_from([add_ap_sub]) if locat[0] == 2 and locat[ 1] == 2: # TODO add some global indicator of the base location sys_auto.states[add_ap_sub]['ap'] |= {'Base'} if locat[0] == x_goal_loc and locat[1] == y_goal_loc: sys_auto.states[add_ap_sub]['ap'] |= {'GoalPos'} # Initial condition, empty set sys_auto_init = set() #print(transition_part[current_horizon]) #print(w_part[current_horizon]) #input('uhmmm...') # NOTE: that current_horizon is 1, 2, 3, ... # Create all transitions through brute force method of checking existence of locations in the transition region next # to every starting point, dependent on the orientation. This is ran on transition region and inclusion in w region # is checked in creating transitions. This is because all w regions are contained in the transition region, and # transitions from a w region are different than those form just transition regions for locat in transition_part[current_horizon]: init = 'Pos' + str(locat[0]) + '_' + str(locat[1]) + 'Ori' + str( locat[2]) if locat in w_part[current_horizon]: sys_auto.transitions.add_comb({init}, {init}, sys_actions="Stop") # Transitions allowed if orientation is up if locat[2] == 1: if (locat[0], locat[1] + 1, 1) in transition_part[current_horizon]: endloc = 'Pos' + str( locat[0]) + '_' + str(locat[1] + 1) + 'Ori' + str(1) sys_auto.transitions.add_comb({init}, {endloc}, sys_actions="Go") if (locat[0] + 1, locat[1] + 1, 2) in transition_part[current_horizon]: endloc = 'Pos' + str(locat[0] + 1) + '_' + str(locat[1] + 1) + 'Ori' + str(2) sys_auto.transitions.add_comb({init}, {endloc}, sys_actions="Go") if (locat[0] - 1, locat[1] + 1, 4) in transition_part[current_horizon]: endloc = 'Pos' + str(locat[0] - 1) + '_' + str(locat[1] + 1) + 'Ori' + str(4) sys_auto.transitions.add_comb({init}, {endloc}, sys_actions="Go") # Transitions allowed if orientation is right elif locat[2] == 2: if (locat[0] + 1, locat[1], 2) in transition_part[current_horizon]: endloc = 'Pos' + str(locat[0] + 1) + '_' + str( locat[1]) + 'Ori' + str(2) sys_auto.transitions.add_comb({init}, {endloc}, sys_actions="Go") if (locat[0] + 1, locat[1] + 1, 1) in transition_part[current_horizon]: endloc = 'Pos' + str(locat[0] + 1) + '_' + str(locat[1] + 1) + 'Ori' + str(1) sys_auto.transitions.add_comb({init}, {endloc}, sys_actions="Go") if (locat[0] + 1, locat[1] - 1, 3) in transition_part[current_horizon]: endloc = 'Pos' + str(locat[0] + 1) + '_' + str(locat[1] - 1) + 'Ori' + str(3) sys_auto.transitions.add_comb({init}, {endloc}, sys_actions="Go") # Transitions allowed if orientation is down elif locat[2] == 3: if (locat[0], locat[1] - 1, 3) in transition_part[current_horizon]: endloc = 'Pos' + str( locat[0]) + '_' + str(locat[1] - 1) + 'Ori' + str(3) sys_auto.transitions.add_comb({init}, {endloc}, sys_actions="Go") if (locat[0] + 1, locat[1] - 1, 2) in transition_part[current_horizon]: endloc = 'Pos' + str(locat[0] + 1) + '_' + str(locat[1] - 1) + 'Ori' + str(2) sys_auto.transitions.add_comb({init}, {endloc}, sys_actions="Go") if (locat[0] - 1, locat[1] - 1, 4) in transition_part[current_horizon]: endloc = 'Pos' + str(locat[0] - 1) + '_' + str(locat[1] - 1) + 'Ori' + str(4) sys_auto.transitions.add_comb({init}, {endloc}, sys_actions="Go") # Transitions allowed if orientation is left elif locat[2] == 4: if (locat[0] - 1, locat[1], 4) in transition_part[current_horizon]: endloc = 'Pos' + str(locat[0] - 1) + '_' + str( locat[1]) + 'Ori' + str(4) sys_auto.transitions.add_comb({init}, {endloc}, sys_actions="Go") if (locat[0] - 1, locat[1] + 1, 1) in transition_part[current_horizon]: endloc = 'Pos' + str(locat[0] - 1) + '_' + str(locat[1] + 1) + 'Ori' + str(1) sys_auto.transitions.add_comb({init}, {endloc}, sys_actions="Go") if (locat[0] - 1, locat[1] - 1, 3) in transition_part[current_horizon]: endloc = 'Pos' + str(locat[0] - 1) + '_' + str(locat[1] - 1) + 'Ori' + str(3) sys_auto.transitions.add_comb({init}, {endloc}, sys_actions="Go") # Create possible transitions for initial conditions in only the transition region. Only transitions are # staying still, assigned to both action groups. This works because in implementation the controllers will # switch to the next horizon here else: sys_auto.transitions.add_comb({init}, {init}, sys_actions="Stop") sys_auto.transitions.add_comb({init}, {init}, sys_actions="Go") # Begin generating the specifications!! # Create the additional environmental variables, including signal for w region next to goal env_auto_vars = {'StopSignal', 'Fire'} if current_horizon == 1: env_auto_vars |= {'SyncSignal'} # Create the environment specifications, including progress related to sync signal next to goal env_auto_safe = set() env_auto_init = {'!StopSignal', '!Fire'} env_auto_prog = {'!StopSignal', '!Fire'} if current_horizon == 1: env_auto_prog |= {'SyncSignal'} # System variables and safety specification empty sets sys_auto_vars = set() sys_auto_safe = set() # Create stop signal requirements # TODO This should be changed to present actions... sys_auto_safe |= {'(StopSignal&&!Fire)->(X(sys_actions = "Stop"))'} sys_auto_safe |= {'(!(StopSignal&&!Fire))->(X(sys_actions = "Go"))'} # Add relevant phi variables to safety (i.e. all phi contained within this region). Never enter phi locations phi = '' for locat in transition_part[current_horizon]: state = 'Pos' + str(locat[0]) + '_' + str(locat[1]) + 'Ori' + str( locat[2]) for names in phi_states: if state == names: phi = phi + '!(loc = "' + names + '")&&' phi = phi + 'True' sys_auto_safe |= {phi} # Empty initial progress sys_auto_prog = set() # Display progress statement to user print(('Beginning synthesis of W' + str(current_horizon) + ' for goal (' + str(x_goal_loc) + ',' + str(y_goal_loc) + ')!')) # Cycle through all initial conditions in this w region for synthesizing controller for idxn, locat in enumerate(w_part[current_horizon]): locat_sub = locat #if locat == (9, 8, 3): # print('here') # input('wait...') # Create checks to see if current position is viable initial condition current_state = 'Pos' + str(locat_sub[0]) + '_' + str( locat_sub[1]) + 'Ori' + str(locat_sub[2]) # Run through names in phi_states to check if it's included indicator = 0 for names in phi_states: if current_state == names: indicator = 1 # If current state passed, then add to initial condition and synthesize. Otherwise, move to next I.C. if indicator == 0: sys_auto_init = {'(loc = "' + current_state + '")'} else: continue # Create the progress statements and synthesize. Progress statements differ depending on current horizon # For horizon W1 if current_horizon == 1: # This section is the 'sync' version of specs, which is just the normal "correct" version print('Sync synthesis for ' + current_state) # Start timer for synthesis start_time = time.time() # Spec just states that the sync signal implies goal position is there sync_spec = '(SyncSignal)->GoalPos' sys_auto_prog = {sync_spec} # Create the GR spec for all the generated env and sys specs specs_final_sync = spec.GRSpec(env_auto_vars, sys_auto_vars, env_auto_init, sys_auto_init, env_auto_safe, sys_auto_safe, env_auto_prog, sys_auto_prog) # Synthesizer attributes specs_final_sync.moore = True option = 'omega' specs_final_sync.qinit = '\E \A' # synthesizer should find initial system values that satisfy # `env_init /\ sys_init` and work, for every environment variable # initial values that satisfy `env_init`. # SYNTHESIZE!!! ctrl_final_sync = synth.synthesize(option, specs_final_sync, env=None, sys=sys_auto, ignore_sys_init=True) # Failure results in adjustments to the horizon related to current I.C. if ctrl_final_sync is None: print('Failed to synthesize ' + current_state + ', moving to next w_part and transition_part') w_part[current_horizon + 1].append(locat) if locat not in transition_part[current_horizon + 1]: transition_part[current_horizon + 1].append(locat) w_part[current_horizon][idxn] = None transition_part[current_horizon].remove(locat) #if locat == (9, 8, 2): # print('here') # print(w_part[current_horizon]) # input('wait...') # Stopwatch and print synth_time = time.time() - start_time print(synth_time) # Write controller to relevant location if it synthesized filename = 'ctrls/Goal' + str(x_goal_loc) + '_' + str(y_goal_loc) + '/G' + str(x_goal_loc) + '_' + \ str(y_goal_loc) + current_state + '.py' #'_W' + str(current_horizon) + if ctrl_final_sync is not None: dumpsmach.write_python_case(filename, ctrl_final_sync) #if locat == (9, 8, 2): # print('here') # print(w_part[current_horizon]) # input('wait...') # All other horizons from the first one (>= W2) else: print('Synthesis for ' + current_state) # Start timer for synthesis start_time = time.time() # Generate progress to any area of transition region that aren't in the w region (inner layer) spec_inter = '((' for locat2 in transition_part[current_horizon]: if locat2 not in w_part[current_horizon]: locations = 'Pos' + str(locat2[0]) + '_' + str( locat2[1]) + 'Ori' + str(locat2[2]) spec_inter = spec_inter + 'loc = "' + locations + '")||(' # Finish tail end of progress spec (false is there to wrap up string generated by loop) spec_inter = spec_inter + 'False))' sys_auto_prog |= {spec_inter} # Create the GR spec for all the generated env and sys specs specs_inter = spec.GRSpec(env_auto_vars, sys_auto_vars, env_auto_init, sys_auto_init, env_auto_safe, sys_auto_safe, env_auto_prog, sys_auto_prog) # Synthesizer attributes specs_inter.moore = True option = 'omega' specs_inter.qinit = '\E \A' # synthesizer should find initial system values that satisfy # `env_init /\ sys_init` and work, for every environment variable # initial values that satisfy `env_init`. # SYNTHESIZE!!! ctrl_inter = synth.synthesize(option, specs_inter, sys=sys_auto, ignore_sys_init=True) # Failure results in adjustments to the horizon related to current I.C. if ctrl_inter is None: print('Failed to synthesize ' + current_state + ', moving to next w_part and transition_part') w_part[current_horizon + 1].append(locat) if locat not in transition_part[current_horizon + 1]: transition_part[current_horizon + 1].append(locat) w_part[current_horizon][idxn] = None transition_part[current_horizon].remove(locat) # Stopwatch and print synth_time = time.time() - start_time print(synth_time) # Write controller to relevant location if it synthesized filename = 'ctrls/Goal' + str(x_goal_loc) + '_' + str(y_goal_loc) + '/G' + str(x_goal_loc) + '_' + \ str(y_goal_loc) + current_state + '.py' #'_W' + str(current_horizon) + if ctrl_inter is not None: dumpsmach.write_python_case(filename, ctrl_inter)
sys_vars = {'mem'} sys_init = {'mem'} sys_prog = {'home'} # one additional requirement: if in lot, # then stay there until park signal is turned off sys_safe = {'(X(mem) <-> lot) || (mem && !park)', '((lot && park) -> X(lot))'} sys_prog |= {'mem'} specs = spec.GRSpec(sys_vars=sys_vars, sys_init=sys_init, sys_safety=sys_safe, env_prog=env_prog, sys_prog=sys_prog) ctrl = synth.synthesize('gr1c', specs, sys=sys, env=env0) ctrl.save('sys_and_env_ts0.pdf') logger.info(ctrl) """Park as an env action """ env1 = transys.FTS() env1.states.add('e0') env1.states.initial.add('e0') env1.env_actions.add_from({'park', ''}) env1.transitions.add('e0', 'e0', env_actions='park') env1.transitions.add('e0', 'e0', env_actions='') logger.info(env1)
# # Controller synthesis # # The controller decides based on current variable values only, # without knowing yet the next values that environment variables take. # A controller with this information flow is known as Moore. specs.moore = True # Ask the synthesizer to find initial values for system variables # that, for each initial values that environment variables can # take and satisfy `env_init`, the initial state satisfies # `env_init /\ sys_init`. specs.qinit = '\E \A' # i.e., "there exist sys_vars: forall sys_vars" # At this point we can synthesize the controller # using one of the available methods. strategy = synth.synthesize(specs) assert strategy is not None, 'unrealizable' # Generate a graphical representation of the controller for viewing, or a textual representation if pydot is missing. # if not strategy.save('test_eval_example_modified.png'): # print(strategy) # Writing strategy to file for elem in env_init: break elem = elem.strip('()').split() env0 = int(elem[2]) if (env0 == 2): print("2") dumpsmach.write_python_case("TE2_v2.py",
sys_safe |= {'X(temp) <-> (car_0 || car_1 || (temp && !req_0))'} sys_safe |= {'(car_0 || car_1) -> (req_0)'} sys_safe |= {'car_0_full -> X(!car_0)'} sys_safe |= {'car_1_full -> X(!car_1)'} # TODO: May be unnecessary # sys_safe |= {'(req_0 && car_0_full) -> (car_1_full || car_1)'} # sys_safe |= {'(req_0 && car_1_full) -> (car_0_full || car_0)'} # @sys_specs_section_end@ # Initialize GRspec specs = spec.GRSpec(env_vars, sys_vars, env_init, sys_init, env_safe, sys_safe, env_prog, sys_prog) ctrl = synth.synthesize('gr1c', specs) print(ctrl) #dumpsmach.write_python_case("dispatcher_controller.py", ctrl,classname="dispatcher_controller") #write_matlab_case("dispatcher_controller_3.m", ctrl, classname="dispatcher_controller_3") write_ROS_node(ctrl) #if not ctrl.save('dispatcher.png'): # print(ctrl) ctrl.states.current = ['Sinit'] ctrl.simulate(inputs_sequence='manual', iterations=50)
def specify_discretize_synthesize(): """Return PWA partition and controller, dump them to pickle files.""" # Problem parameters input_bound = 1.0 uncertainty = 0.01 # Continuous state space cont_state_space = box2poly([[0., 3.], [0., 2.]]) # Continuous dynamics A = np.array([[1.0, 0.], [0., 1.0]]) B = np.array([[0.1, 0.], [0., 0.1]]) E = np.array([[1., 0.], [0., 1.]]) # Available control, possible disturbances U = input_bound * np.array([[-1., 1.], [-1., 1.]]) W = uncertainty * np.array([[-1., 1.], [-1., 1.]]) # Convert to polyhedral representation U = box2poly(U) W = box2poly(W) # Construct the LTI system describing the dynamics sys_dyn = hybrid.LtiSysDyn(A, B, E, None, U, W, cont_state_space) # Define atomic propositions for relevant regions of state space cont_props = {} cont_props['home'] = box2poly([[0., 1.], [0., 1.]]) cont_props['lot'] = box2poly([[2., 3.], [1., 2.]]) # Compute proposition preserving partition of the continuous state space cont_partition = prop2part(cont_state_space, cont_props) pwa = discretize(cont_partition, sys_dyn, closed_loop=True, N=8, min_cell_volume=0.1, plotit=False) """Specifications""" # Environment variables and assumptions env_vars = {'park'} env_init = set() env_prog = '!park' env_safe = set() # System variables and requirements sys_vars = {'X0reach'} sys_init = {'X0reach'} sys_prog = {'home'} # []<>home sys_safe = {'(X(X0reach) <-> lot) || (X0reach && !park)'} sys_prog |= {'X0reach'} # Create the specification specs = spec.GRSpec(env_vars, sys_vars, env_init, sys_init, env_safe, sys_safe, env_prog, sys_prog) specs.qinit = '\A \E' specs.moore = False specs.plus_one = False """Synthesize""" ctrl = synth.synthesize(specs, sys=pwa.ts, ignore_sys_init=True, solver='gr1c') # store the result for future use if len(BUILDDIR) > 0 and not os.path.exists(BUILDDIR): os.mkdir(BUILDDIR) pickle.dump(ctrl, open(BUILDDIR + 'FSM.p', 'wb')) pickle.dump(pwa, open(BUILDDIR + 'AbstractPwa.p', 'wb')) return pwa, ctrl
sys_safe |= {'X(temp_2) <-> (loc=1 || (temp_2 && !seat_0=2 && !seat_1=2))'} sys_safe |= {'X(temp_3) <-> (loc=2 || (temp_3 && !seat_0=3 && !seat_1=3))'} #sys_safe |= {'(!hold_00 || !hold_10) -> <>loc=3'} sys_vars["temp_4"] = 'boolean' sys_init |= {'temp_4'} sys_prog |= {'temp_4'} sys_safe |= {'X(temp_4) <-> (loc=3 || (temp_4 && hold_0=0 && hold_1=0))'} # @sys_specs_section_end@ # Initialize GRspec specs = spec.GRSpec(env_vars, sys_vars, env_init, sys_init, env_safe, sys_safe, env_prog, sys_prog) ctrl = synth.synthesize('gr1c', specs) # dumpsmach.write_python_case("strategy_discrete.py", ctrl, classname="strategy") # write_matlab_case("strategy_discrete_3.m", ctrl, classname="strategy_discrete_3") # if not ctrl.save('taxi_planning_3person.png'): # print(ctrl) print(ctrl) # either select current state before simulation # ctrl.states.current = ['Sinit'] # ctrl.simulate(inputs_sequence='manual', iterations=50) # or pass it to simulate #ctrl.simulate(inputs_sequence='random', iterations=10, current_state=0)
# [](X (X0reach) <-> lot || (X0reach && !park)) # # Augment the environmental description to make it GR(1) #! TODO: create a function to convert this type of spec automatically # Define the specification #! NOTE: maybe "synthesize" should infer the atomic proposition from the # transition system? Or, we can declare the mode variable, and the values # of the mode variable are read from the transition system. sys_vars = {'X0reach'} sys_init = {'X0reach', 'sys_actions = "right"'} sys_prog = {'home'} # []<>home sys_safe = {'(X (X0reach) <-> lot) || (X0reach && !park)'} sys_prog |= {'X0reach'} # Create the specification specs = spec.GRSpec(env_vars, sys_vars, env_init, sys_init, env_safe, sys_safe, env_prog, sys_prog) # Controller synthesis # # At this point we can synthesize the controller using one of the available # methods. Here we make use of gr1c. # ctrl = synth.synthesize('gr1c', specs, env=env_sws) # Generate a graphical representation of the controller for viewing if not ctrl.save('only_mode_controlled.png'): print(ctrl)