def check_realizable(spec): """Decide realizability of specification. Consult the documentation of L{synthesize} about parameters. @return: True if realizable, False if not, or an error occurs. """ logger.info('checking realizability...') _assert_gr1c() init_option = select_options(spec) s = translate(spec, 'gr1c') f = tempfile.TemporaryFile() try: f.write(bytes(s, 'utf-8')) except TypeError: # Try to be compatible with Python 2.7 f.write(bytes(s)) f.seek(0) logger.info('starting realizability check') p = subprocess.Popen([GR1C_BIN_PREFIX+"gr1c", "-n", init_option, "-r"], stdin=f, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, universal_newlines=True) p.wait() logger.info('gr1c input:\n' + s +_hl) if p.returncode == 0: return True else: logger.info(p.stdout.read() ) return False
def check_realizable(spec, init_option="ALL_ENV_EXIST_SYS_INIT"): """Decide realizability of specification. Consult the documentation of L{synthesize} about parameters. @return: True if realizable, False if not, or an error occurs. """ logger.info('checking realizability...') if init_option not in ("ALL_ENV_EXIST_SYS_INIT", "ALL_INIT", "ONE_SIDE_INIT"): raise ValueError("Unrecognized initial condition" + "interpretation (init_option)") s = translate(spec, 'gr1c') f = tempfile.TemporaryFile() f.write(s) f.seek(0) logger.info('starting realizability check') p = subprocess.Popen([GR1C_BIN_PREFIX+"gr1c", "-n", init_option, "-r"], stdin=f, stdout=subprocess.PIPE, stderr=subprocess.STDOUT) p.wait() logger.info('gr1c input:\n' + s +_hl) if p.returncode == 0: return True else: logger.info(p.stdout.read() ) return False
def synthesize(spec): """Synthesize strategy realizing the given specification. @type spec: L{GRSpec} @param spec: specification. Consult the U{documentation of gr1c <https://tulip-control.github.io/gr1c/md_spc_format.html#initconditions>} for a detailed description. @return: strategy as C{networkx.DiGraph}, or None if unrealizable or error occurs. """ _assert_gr1c() init_option = select_options(spec) try: p = subprocess.Popen( [GR1C_BIN_PREFIX + "gr1c", "-n", init_option, "-t", "json"], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, universal_newlines=True ) except OSError as e: if e.errno == os.errno.ENOENT: raise Exception('gr1c not found in path.') else: raise s = translate(spec, 'gr1c') logger.info('\n{hl}\n gr1c input:\n {s}\n{hl}'.format(s=s, hl=_hl)) # to make debugging by manually running gr1c easier fname = 'spec.gr1c' try: if logger.getEffectiveLevel() < logging.DEBUG: with open(fname, 'w') as f: f.write(s) logger.debug('wrote input to file "{f}"'.format(f=fname)) except: logger.error('failed to write auxiliary file: "{f}"'.format(f=fname)) (stdoutdata, stderrdata) = p.communicate(s) msg = ( ('{spaces} gr1c return code: {c}\n\n' '{spaces} gr1c stdout, stderr:\n {out}\n\n').format( c=p.returncode, out=stdoutdata, spaces=30 * ' ' ) ) if p.returncode == 0: logger.debug(msg) strategy = load_aut_json(stdoutdata) return strategy else: print(msg) return None
def _spec_to_gr1py(spec): if gr1py is None: raise ValueError('Import of gr1py interface failed.\n' 'Please verify installation of "gr1py".') s = translate(spec, 'gr1c') logger.info('\n{hl}\n gr1py input:\n {s}\n{hl}'.format(s=s, hl=_hl)) tsys, exprtab = gr1py.cli.loads(s) return tsys, exprtab
def synthesize(spec, symbolic=False): """Return strategy satisfying the specification C{spec}. @type spec: L{GRSpec} or C{str} in structured slugs syntax. @return: If realizable return synthesized strategy, otherwise C{None}. @rtype: C{networkx.DiGraph} """ if isinstance(spec, GRSpec): assert not spec.moore assert not spec.plus_one struct = translate(spec, 'slugs') else: struct = spec with tempfile.NamedTemporaryFile(delete=False) as fin: try: fin.write(bytes(struct, 'utf-8')) except TypeError: # Try to be compatible with Python 2.7 fin.write(bytes(struct)) realizable, out = _call_slugs(fin.name, synth=True, symbolic=symbolic) if not realizable: return None os.unlink(fin.name) # collect int vars vrs = dict(spec.sys_vars) vrs.update(spec.env_vars) dout = json.loads(out) g = nx.DiGraph() dvars = dout['variables'] for stru, d in dout['nodes'].items(): u = int(stru) state = dict(zip(dvars, d['state'])) g.add_node(u, state=state) for v in d['trans']: g.add_edge(u, v) h = nx.DiGraph() for u, d in g.nodes_iter(data=True): bit_state = d['state'] int_state = _bitfields_to_ints(bit_state, vrs) h.add_node(u, state=int_state) for u, v in g.edges_iter(): h.add_edge(u, v) logger.debug( ('loaded strategy with vertices:\n {v}\n' 'and edges:\n {e}\n').format( v='\n '.join(str(x) for x in h.nodes(data=True)), e=h.edges())) return h
def check_realizable(spec): """Decide realizability of specification. Consult the documentation of L{synthesize} about parameters. @return: True if realizable, False if not, or an error occurs. """ if isinstance(spec, GRSpec): assert not spec.moore assert not spec.plus_one struct = translate(spec, 'slugs') else: struct = spec with tempfile.NamedTemporaryFile(delete=False) as fin: fin.write(struct) realizable, out = _call_slugs(fin.name, synth=False) return realizable
def synthesize(spec, symbolic=False): """Return strategy satisfying the specification C{spec}. @type spec: L{GRSpec} or C{str} in structured slugs syntax. @return: If realizable return synthesized strategy, otherwise C{None}. @rtype: C{networkx.DiGraph} """ if isinstance(spec, GRSpec): assert not spec.moore assert not spec.plus_one struct = translate(spec, 'slugs') else: struct = spec with tempfile.NamedTemporaryFile(delete=False) as fin: try: fin.write(bytes(struct, 'utf-8')) except TypeError: # Try to be compatible with Python 2.7 fin.write(bytes(struct)) realizable, out = _call_slugs(fin.name, synth=True, symbolic=symbolic) if not realizable: return None os.unlink(fin.name) # collect int vars vrs = dict(spec.sys_vars) vrs.update(spec.env_vars) dout = json.loads(out) g = nx.DiGraph() dvars = dout['variables'] for stru, d in dout['nodes'].items(): u = int(stru) state = dict(zip(dvars, d['state'])) g.add_node(u, state=state) for v in d['trans']: g.add_edge(u, v) h = nx.DiGraph() for u, d in g.nodes(data=True): bit_state = d['state'] int_state = _bitfields_to_ints(bit_state, vrs) h.add_node(u, state=int_state) for u, v in g.edges(): h.add_edge(u, v) logger.debug(('loaded strategy with vertices:\n {v}\n' 'and edges:\n {e}\n').format(v='\n '.join( str(x) for x in h.nodes(data=True)), e=h.edges())) return h
def check_realizable(spec): """Decide realizability of specification. Consult the documentation of L{synthesize} about parameters. @return: True if realizable, False if not, or an error occurs. """ if isinstance(spec, GRSpec): struct = translate(spec, 'slugs') else: struct = spec s = slugs.convert_to_slugsin(struct, True) with tempfile.NamedTemporaryFile(delete=False) as fin: fin.write(s) logger.info('\n\n structured slugs:\n\n {struct}'.format( struct=struct) + '\n\n slugs in:\n\n {s}\n'.format(s=s)) realizable, out = _call_slugs(fin.name, synth=False) return realizable
def check_realizable(spec): """Decide realizability of specification. Consult the documentation of L{synthesize} about parameters. @return: True if realizable, False if not, or an error occurs. """ if isinstance(spec, GRSpec): struct = translate(spec, 'slugs') else: struct = spec s = slugs.convert_to_slugsin(struct, True) with tempfile.NamedTemporaryFile(delete=False) as fin: fin.write(s) logger.info('\n\n structured slugs:\n\n {struct}'.format(struct=struct) + '\n\n slugs in:\n\n {s}\n'.format(s=s)) realizable, out = _call_slugs(fin.name, synth=False) return realizable
def check_realizable(spec): """Decide realizability of specification. Consult the documentation of L{synthesize} about parameters. @return: True if realizable, False if not, or an error occurs. """ if isinstance(spec, GRSpec): assert not spec.moore assert not spec.plus_one struct = translate(spec, 'slugs') else: struct = spec with tempfile.NamedTemporaryFile(delete=False) as fin: try: fin.write(bytes(struct, 'utf-8')) except TypeError: # Try to be compatible with Python 2.7 fin.write(bytes(struct)) realizable, out = _call_slugs(fin.name, synth=False) return realizable
def test_to_gr1c(self): assert gr1c.check_syntax(translate(self.f_un, 'gr1c')) assert gr1c.check_syntax(translate(self.dcounter, 'gr1c'))
# []! ([1], 1) ltl_formula_1 = LTL_encoding.cltl_conversion_async(np.array([6, 7, 8]), 2, num_robots, num_cells, 1) # ltl_formula_1 = 'loc=69' sys_prog |= {ltl_formula_1} for i in range(num_robots): ltl_formula_2 = LTL_encoding.ltl_conversion_ap(np.array([2]), i, num_robots, num_cells) sys_prog |= {ltl_formula_2} ltl_formula_3 = LTL_encoding.ltl_negate( LTL_encoding.cltl_conversion(np.array([1]), 1, num_robots, num_cells)) sys_safe |= {ltl_formula_3} # 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 = '\E \A' # Moore initial condition synthesized too specs.moore = False specs.plus_one = False # ctrl = slugs.synthesize(specs) slugs_specs = spec.translate(specs, 'slugs') print(specs.sys_vars) print(slugs_specs, file=open("out.slugs", "w")) ctrl = synth.synthesize(specs, solver="slugs") assert ctrl is not None, 'unrealizable' # Generate a graphical representation of the controller for viewing #if not ctrl.save('gr1_set.png'): # print(ctrl) #machines.random_run(ctrl, N=30)
def synthesize(spec, init_option="ALL_ENV_EXIST_SYS_INIT"): """Synthesize strategy realizing the given specification. @type spec: L{GRSpec} @param spec: specification, which is incomplete without an interpretation of initial conditions (init_option). @type init_option: str @param init_option: string declaration of the initial condition interpretation to use. This parameter corresponds to that of the -n command-line flag of gr1c. It is one of: - "ALL_ENV_EXIST_SYS_INIT" (default) - For each initial valuation of environment variables that satisfies spec.env_init, the strategy must provide some valuation of system variables that satisfies spec.sys_init. Only environment variables (spec.env_vars) may appear in spec.env_init, and only system variables (spec.sys_vars) may appear in spec.sys_init. - "ALL_INIT" - Any state that satisfies the conjunction of spec.env_init an spec.sys_init can occur initially. - "ONE_SIDE_INIT" - At most one of spec.env_init and spec.sys_init is nonempty, and the nonempty one can include both environment and system variables (spec.env_vars and spec.sys_vars, respectively). Both being empty is equivalent to spec.env_init=["True"]. If spec.env_init is nonempty, then any state satisfying it is possible initially. If spec.sys_init is nonempty, then the strategy need only choose one initial state satisfying it. Consult the U{documentation of gr1c <http://slivingston.github.io/gr1c/md_spc_format.html#initconditions>} for detailed descriptions. @return: strategy as C{networkx.DiGraph}, or None if unrealizable or error occurs. """ if init_option not in ("ALL_ENV_EXIST_SYS_INIT", "ALL_INIT", "ONE_SIDE_INIT"): raise ValueError("Unrecognized initial condition" + "interpretation (init_option)") try: p = subprocess.Popen( [GR1C_BIN_PREFIX + "gr1c", "-n", init_option, "-t", "tulip"], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.STDOUT ) except OSError as e: if e.errno == os.errno.ENOENT: raise Exception('gr1c not found in path.') else: raise s = translate(spec, 'gr1c') logger.info('\n{hl}\n gr1c input:\n {s}\n{hl}'.format(s=s, hl=_hl)) # to make debugging by manually running gr1c easier fname = 'spec.gr1c' try: if logger.getEffectiveLevel() < logging.DEBUG: with open(fname, 'w') as f: f.write(s) logger.debug('wrote input to file "{f}"'.format(f=fname)) except: logger.error('failed to write auxiliary file: "{f}"'.format(f=fname)) (stdoutdata, stderrdata) = p.communicate(s) msg = ( ('{spaces} gr1c return code: {c}\n\n' '{spaces} gr1c stdout, stderr:\n {out}\n\n').format( c=p.returncode, out=stdoutdata, spaces=30 * ' ' ) ) if p.returncode == 0: logger.debug(msg) strategy = load_aut_xml(stdoutdata) return strategy else: print(msg) return None