Beispiel #1
0
def _visit(graph: DiGraph, node: T, order: List[T]) -> None:
    if graph.nodes[node].get("visited", False):
        return
    graph.nodes[node]["visited"] = True
    for n in graph.neighbors(node):
        _visit(graph, n, order)
    order.append(node)
Beispiel #2
0
    def __init__(self, incoming_graph_data=None, **attr):
        """Initialize a graph with edges, name, or graph attributes.

        Parameters
        ----------
        incoming_graph_data : input graph
            Data to initialize graph.  If incoming_graph_data=None (default)
            an empty graph is created.  The data can be an edge list, or any
            NetworkX graph object.  If the corresponding optional Python
            packages are installed the data can also be a NumPy matrix
            or 2d ndarray, a SciPy sparse matrix, or a PyGraphviz graph.

        attr : keyword arguments, optional (default= no attributes)
            Attributes to add to graph as key=value pairs.

        See Also
        --------
        convert

        Examples
        --------
        >>> G = nx.Graph()  # or DiGraph, MultiGraph, MultiDiGraph, etc
        >>> G = nx.Graph(name="my graph")
        >>> e = [(1, 2), (2, 3), (3, 4)]  # list of edges
        >>> G = nx.Graph(e)

        Arbitrary graph attribute pairs (key=value) may be assigned

        >>> G = nx.Graph(e, day="Friday")
        >>> G.graph
        {'day': 'Friday'}

        """
        self.edge_key_dict_factory = self.edge_key_dict_factory
        DiGraph.__init__(self, incoming_graph_data, **attr)
Beispiel #3
0
    def __init__(self):
        self.androGuardObjects = []

        self.nodes = {}
        self.nodes_id = {}
        self.entry_nodes = []
        self.G = DiGraph()
Beispiel #4
0
    def __init__(self, n_robot, acpt, ts, buchi_graph, init, seg, step_size,
                 no):
        """
        :param acpt:  accepting state
        :param ts: transition system
        :param buchi_graph:  Buchi graph
        :param init: product initial state
        """
        self.robot = n_robot
        self.acpt = acpt
        self.goals = []
        self.ts = ts
        self.buchi_graph = buchi_graph
        self.init = init
        self.seg = seg
        self.step_size = step_size
        self.dim = len(self.ts['workspace'])
        uni_ball = [
            1, 2, 3.142, 4.189, 4.935, 5.264, 5.168, 4.725, 4.059, 3.299, 2.550
        ]
        self.gamma = np.ceil(
            4 * np.power(1 / uni_ball[self.robot * self.dim], 1. /
                         (self.dim * self.robot)))  # unit workspace
        self.tree = DiGraph(type='PBA', init=init)

        label = []
        for i in range(self.robot):
            l = self.label(init[0][i])
            # exists one sampled point lies within obstacles
            if l != '':
                l = l + '_' + str(i + 1)
            label.append(l)

        self.tree.add_node(init, cost=0, label=label)
        self.no = no
Beispiel #5
0
 def __init__(self, mot_fts, act_model):
     DiGraph.__init__(self,
                      region=mot_fts,
                      action=act_model,
                      initial=set(),
                      type='MotActModel')
     self.build_full()
def get_example_3():
    """get a binarized example, whose original graph is
    more complicated than the above example
    """
    g = DiGraph()
    g.add_nodes_from(range(1, 10))
    g.add_edges_from([(1, 2), (1, 3), (1, 7), (2, 4), (2, 5), (2, 6), (2, 7),
                      (3, 8), (3, 9)])
    rewards = range(1, 10)
    for r, n in zip(rewards, g.nodes()):
        g.node[n]['r'] = r

    # all edges have cost 2 except 1 -> 2 and 1 -> 3(cost 1)
    for s, t in g.edges():
        g[s][t]['c'] = 2
    g[1][2]['c'] = 1
    g[1][3]['c'] = 1

    g = binarize_dag(g,
                     vertex_weight_key='r',
                     edge_weight_key='c',
                     dummy_node_name_prefix='d_')

    # parameters and expected output
    U = [0, 2, 3, 4, 100]
    expected_edges_set = [
        [],
        [(1, 7)],
        [(1, 'd_1'), ('d_1', 3), (3, 9)],
        [(1, 'd_1'), ('d_1', 3), (3, 9), ('d_1', 2)],
        # (1, 7) removed to make it a tree
        list(set(g.edges()) - set([(1, 7)]))
    ]

    return (g, U, expected_edges_set)
Beispiel #7
0
class MockSimpleGraphDB\
(
    Generic[MockVertexData],
    PartiallyStatefulDirectedGraphInterface[SimpleGraphKey, MockVertexData]
):
    '''
    Type for mocking a simple database.
    '''

    data: DiGraph

    def __init__(self) -> None:
        self.data = DiGraph()

    def write_stateful_vertex_(self, label: SimpleGraphKey,
                               data: MockVertexData, *args: Any,
                               **kwargs: Any) -> None:
        self.data.add_node(node_for_adding=label,
                           memento=data)  # type: ignore unkonwn

    def write_stateless_directed_edge_(self, source: SimpleGraphKey,
                                       destination: SimpleGraphKey, *args: Any,
                                       **kwargs: Any) -> None:
        self.data.add_edge(
            u_of_edge=source,
            v_of_edge=destination)  # type: ignore unkonwn member
Beispiel #8
0
    def __init__(self, incoming_graph_data=None, **attr):
        """Initialize a graph with edges, name, or graph attributes.

        Parameters
        ----------
        incoming_graph_data : input graph
            Data to initialize graph.  If incoming_graph_data=None (default)
            an empty graph is created.  The data can be an edge list, or any
            NetworkX graph object.  If the corresponding optional Python
            packages are installed the data can also be a NumPy matrix
            or 2d ndarray, a SciPy sparse matrix, or a PyGraphviz graph.

        attr : keyword arguments, optional (default= no attributes)
            Attributes to add to graph as key=value pairs.

        See Also
        --------
        convert

        Examples
        --------
        >>> G = nx.Graph()   # or DiGraph, MultiGraph, MultiDiGraph, etc
        >>> G = nx.Graph(name='my graph')
        >>> e = [(1, 2), (2, 3), (3, 4)] # list of edges
        >>> G = nx.Graph(e)

        Arbitrary graph attribute pairs (key=value) may be assigned

        >>> G = nx.Graph(e, day="Friday")
        >>> G.graph
        {'day': 'Friday'}

        """
        self.edge_key_dict_factory = self.edge_key_dict_factory
        DiGraph.__init__(self, incoming_graph_data, **attr)
Beispiel #9
0
class buchi_graph(object):
    """ construct buchi automaton graph
    Parameter:
        formula: LTL formula specifying task
    """
    def __init__(self, formula):
        self.formula = formula

    def formulaParser(self):
        """replace letter with symbol
        """
        indicator = 'FG'

        if [True for i in indicator if i in self.formula]:
            self.formula.replace('F', '<>').replace('G', '[]')

    def execLtl2ba(self):
        """ given formula, exectute the ltl2ba
        Parameter:
            buchi_str: output string of program ltl2ba  (utf-8 format)
        """

        dirname = os.path.dirname(__file__)
        self.buchi_str = subprocess.check_output(dirname + "/./ltl2ba -f \"" +
                                                 self.formula + "\"",
                                                 shell=True).decode("utf-8")

    def buchiGraph(self):
        """parse the output of ltl2ba
        Parameter:
            buchi_graph: Graph of buchi automaton
        """
        # find all states
        state_re = re.compile(r'\n(\w+):\n\t')
        state_group = re.findall(state_re, self.buchi_str)

        # find initial and accepting states
        init = [s for s in state_group if 'init' in s]
        accep = [s for s in state_group if 'accept' in s]
        """
        Format:
            buchi_graph.node = NodeView(('T0_init', 'T1_S1', 'accept_S1'))
            buchi_graph.edges = OutEdgeView([('T0_init', 'T0_init'), ('T0_init', 'T1_S1'),....])
            buchi_graph.succ = AdjacencyView({'T0_init': {'T0_init': {'label': '1'}, 'T1_S1': {'label': 'r3'}}})
        """
        self.buchi_graph = DiGraph(type='buchi', init=init, accept=accep)
        for state in state_group:
            # for each state, find transition relation
            # add node
            self.buchi_graph.add_node(state)
            state_if_fi = re.findall(state + r':\n\tif(.*?)fi', self.buchi_str,
                                     re.DOTALL)
            if state_if_fi:
                relation_group = re.findall(r':: \((.*?)\) -> goto (\w+)\n\t',
                                            state_if_fi[0])
                for (label, state_dest) in relation_group:
                    # add edge
                    self.buchi_graph.add_edge(state, state_dest, label=label)

        return self.buchi_graph
Beispiel #10
0
    def __init__(self, ts, buchi_graph, init, final, seg, env):
        """
        :param ts: transition system
        :param buchi_graph:  Buchi graph
        :param init: product initial state
        """
        self.robot = 1
        self.goals = []
        self.ts = ts
        self.buchi_graph = buchi_graph
        self.init = init
        self.dim = len(self.ts['workspace'])
        self.tree = DiGraph(type='PBA', init=init)
        label = self.label(init[0])
        if label != '':
            label = label + '_' + str(1)
        self.tree.add_node(init, cost=0, label=label)

        self.group = dict()
        self.add_group(init)

        self.b_final = final
        self.seg = seg

        self.p = 0.9

        self.env = env
Beispiel #11
0
    def buchiGraph(self):
        """parse the output of ltl2ba
        Parameter:
            buchi_graph: Graph of buchi automaton
        """
        # find all states
        state_re = re.compile(r'\n(\w+):\n\t')
        state_group = re.findall(state_re, self.buchi_str)

        # find initial and accepting states
        init = [s for s in state_group if 'init' in s]
        accep = [s for s in state_group if 'accept' in s]
        """
        Format:
            buchi_graph.node = NodeView(('T0_init', 'T1_S1', 'accept_S1'))
            buchi_graph.edges = OutEdgeView([('T0_init', 'T0_init'), ('T0_init', 'T1_S1'),....])
            buchi_graph.succ = AdjacencyView({'T0_init': {'T0_init': {'label': '1'}, 'T1_S1': {'label': 'r3'}}})
        """
        self.buchi_graph = DiGraph(type='buchi', init=init, accept=accep)
        for state in state_group:
            # for each state, find transition relation
            # add node
            self.buchi_graph.add_node(state)
            state_if_fi = re.findall(state + r':\n\tif(.*?)fi', self.buchi_str,
                                     re.DOTALL)
            if state_if_fi:
                relation_group = re.findall(r':: \((.*?)\) -> goto (\w+)\n\t',
                                            state_if_fi[0])
                for (label, state_dest) in relation_group:
                    # add edge
                    self.buchi_graph.add_edge(state, state_dest, label=label)

        return self.buchi_graph
Beispiel #12
0
    def __init__(self, *args: Any, **kwargs: Any) -> None:
        '''
        Sets up a `networkx.DiGraph` structure for writing stateful vertices and stateless direWcted edges.
        '''
        self.__graph = DiGraph()

        return None
Beispiel #13
0
    def __init__(self, ts, buchi_graph, init, step_size, base=1e3):
        """
        :param ts: transition system
        :param buchi_graph:  Buchi graph
        :param init: product initial state
        """
        self.robot = 1
        self.goals = []
        self.ts = ts
        self.buchi_graph = buchi_graph
        self.init = init
        self.step_size = step_size
        self.dim = len(self.ts['workspace'])
        uni_v = np.power(np.pi, self.robot * self.dim /
                         2) / math.gamma(self.robot * self.dim / 2 + 1)
        self.gamma = np.ceil(
            4 * np.power(1 / uni_v, 1. /
                         (self.dim * self.robot)))  # unit workspace
        self.tree = DiGraph(type='PBA', init=init)
        label = self.label(init[0])
        if label != '':
            label = label + '_' + str(1)
        # accepting state before current node
        acc = set()
        if 'accept' in init[1]:
            acc.add(init)
        self.tree.add_node(init, cost=0, label=label, acc=acc)
        self.search_goal(init, label, acc)

        # already used skilles
        self.used = set()
        self.base = base
Beispiel #14
0
	def _congruence_graph(self):
		"""Form a graph whose vertex set is the QNF basis. The edges store the information which makes two vertices congruent."""
		from networkx.classes.digraph import DiGraph
		basis = self.quasinormal_basis
		min_exp = basis.minimal_expansion_for(self)
		terminal, initial = self.semi_infinite_end_points()
		endpts = sorted(terminal + initial)
		G = DiGraph()
		orbit_generators = set(min_exp)
		orbit_generators.update(endpts)
		
		#1. Add an edge for every direct congruence relationship.
		for gen in orbit_generators:
			type, images, _ = self.orbit_type(gen, basis)
			for power, img in images.items():
				images[power] = basis.test_above(img)
			
			congruent_pairs = permutations(images.items(), 2)
			for (pow1, (head1, tail1)), (pow2, (head2, tail2)) in congruent_pairs:
				if head1 == head2:
					continue
				data = dict(start_tail = tail1, power = pow2 - pow1, end_tail = tail2)
				G.add_edge(head1, head2, data)
				assert self.repeated_image(head1.extend(tail1), pow2 - pow1) == head2.extend(tail2)
		return G
Beispiel #15
0
    def __init__(self, ts, buchi_graph, init, base=1e3, seg='pre'):
        """
        :param ts: transition system
        :param buchi_graph:  Buchi graph
        :param init: product initial state
        """
        self.robot = 1
        self.goals = []
        self.ts = ts
        self.buchi_graph = buchi_graph
        self.init = init
        self.dim = len(self.ts['workspace'])
        self.tree = DiGraph(type='PBA', init=init)
        label = self.label(init[0])
        if label != '':
            label = label + '_' + str(1)
        # accepting state before current node
        acc = set()
        if 'accept' in init[1]:
            acc.add(init)
        self.tree.add_node(init, cost=0, label=label, acc=acc)

        # already used skilles
        self.used = set()
        self.base = base
        self.seg = seg
        self.found = 10
Beispiel #16
0
    def __init__(self, n_robot, acpt, ts, buchi_graph, init, seg, step_size,
                 no):
        """
        :param acpt:  accepting state
        :param ts: transition system
        :param buchi_graph:  Buchi graph
        :param init: product initial state
        """
        self.robot = n_robot
        self.acpt = acpt
        self.goals = []
        self.ts = ts
        self.buchi_graph = buchi_graph
        self.init = init
        self.seg = seg
        self.step_size = step_size
        self.dim = len(self.ts['workspace'])
        uni_ball = [
            1, 2, 3.142, 4.189, 4.935, 5.264, 5.168, 4.725, 4.059, 3.299, 2.550
        ]
        # uni_v = uni_ball[self.robot*self.dim]
        uni_v = np.power(np.pi, self.robot * self.dim /
                         2) / math.gamma(self.robot * self.dim / 2 + 1)
        self.gamma = np.ceil(
            4 * np.power(1 / uni_v, 1. /
                         (self.dim * self.robot)))  # unit workspace
        self.tree = DiGraph(type='PBA', init=init)
        self.group = dict()
        label = []
        for i in range(self.robot):
            l = self.label(init[0][i])
            # exists one sampled point lies within obstacles
            if l != '':
                l = l + '_' + str(i + 1)
            label.append(l)

        self.tree.add_node(init, cost=0, label=label)
        self.add_group(init)
        # probability
        self.p = 0.9
        # threshold for collision avoidance
        self.threshold = 0.02
        # polygon obstacle
        polys = [[
            vg.Point(0.4, 1.0),
            vg.Point(0.4, 0.7),
            vg.Point(0.6, 0.7),
            vg.Point(0.6, 1.0)
        ],
                 [
                     vg.Point(0.3, 0.2),
                     vg.Point(0.3, 0.0),
                     vg.Point(0.7, 0.0),
                     vg.Point(0.7, 0.2)
                 ]]
        self.g = vg.VisGraph()
        self.g.build(polys, status=False)
        # region that has ! preceding it
        self.no = no
Beispiel #17
0
 def __init__(self, node_dict, edge_dict, U, initial_node, initial_label):
     DiGraph.__init__(self, name='motion_mdp', init_state=initial_node, init_label=initial_label)
     for (n, prob_label) in node_dict.iteritems():
         self.add_node(n, label = prob_label, act = set())
     print "-------Motion MDP Initialized-------"
     self.add_edges(edge_dict, U)
     print "%s states and %s edges" %(str(len(self.nodes())), str(len(self.edges())))
     self.unify_mdp()
Beispiel #18
0
 def __init__(self, ts, buchi, alpha=100):
     DiGraph.__init__(self,
                      ts=ts,
                      buchi=buchi,
                      alpha=alpha,
                      initial=set(),
                      accept=set(),
                      type='ProdAut')
Beispiel #19
0
 def __init__(self, algo_id, *args, **kwargs):
     DiGraph.__init__(self, args, kwargs)
     self.id = algo_id
     self.scan_count = 0
     self.input_data = []
     self.output_data =[]
     self.data_id_dict = {}  # internal dictionary for lookups of data nodes by id
     self.scan_rate = kwargs.pop('scan_rate')  # rate at which module should be scanned
Beispiel #20
0
def load_graph(file_or_path:FileOrPath, ext:str=None) -> DiGraph:
  graph = DiGraph()
  for adj in load_jsonl(text_file_for(file_or_path)):
    src = adj[0]
    graph.add_node(src)
    for dst in adj[1:]:
      graph.add_edge(src, dst)
  return graph
Beispiel #21
0
    def MVDict_to_WDiGraph(mvd: multivalued_dict) -> 'DirectedGraph':
        from collections import Counter

        WDG = DiGraph()
        for _out_node, _value_list in mvd.items():
            WDG.add_weighted_edges_from(
                (_out_node, _in_node, _weight)
                for _in_node, _weight in Counter(_value_list).items())
        return WDG
Beispiel #22
0
def containing_bags(G: DiGraph, col: str) -> int:
    return_val: int = 1

    neighbor: str
    for neighbor in G.neighbors(col):
        return_val += containing_bags(G, neighbor) * \
            G.get_edge_data(col, neighbor)["weight"]

    return return_val
Beispiel #23
0
 def delete_node(self, n):
     try:
         if len(self.succ[n])+len(self.pred[n])==1: # allowed for leaf node
             DiGraph.delete_node(self,n) # deletes adjacent edge too
         else:
             raise NetworkXError( \
           "deleting interior node %s not allowed in tree"%(n))
     except KeyError: # NetworkXError if n not in self
         raise NetworkXError, "node %s not in graph"%n
Beispiel #24
0
 def __init__(self, algo_id, *args, **kwargs):
     DiGraph.__init__(self, args, kwargs)
     self.id = algo_id
     self.scan_count = 0
     self.input_data = []
     self.output_data = []
     self.data_id_dict = {
     }  # internal dictionary for lookups of data nodes by id
     self.scan_rate = kwargs.pop(
         'scan_rate')  # rate at which module should be scanned
Beispiel #25
0
 def delete_node(self, n):
     try:
         if len(self.succ[n]) + len(
                 self.pred[n]) == 1:  # allowed for leaf node
             DiGraph.delete_node(self, n)  # deletes adjacent edge too
         else:
             raise NetworkXError( \
           "deleting interior node %s not allowed in tree"%(n))
     except KeyError:  # NetworkXError if n not in self
         raise NetworkXError, "node %s not in graph" % n
Beispiel #26
0
 def __init__(self, task, workspace):
     """
     initialization
     :param task: task specified in LTL
     """
     # task specified in LTL
     self.formula = task.formula
     self.type_num = workspace.type_num
     # graph of buchi automaton
     self.buchi_graph = DiGraph(type='buchi', init=[], accept=[])
Beispiel #27
0
 def __init__(self, mdp, dra):
     DiGraph.__init__(self,
                      mdp=mdp,
                      dra=dra,
                      initial=set(),
                      accept=[],
                      name='Product_Dra')
     self.graph['U'] = mdp.graph['U']
     print "-------Prod DRA Initialized-------"
     self.build_full()
Beispiel #28
0
    def __init__(self,
                 NodesPos=None,
                 Edges=None,
                 Radii=None,
                 data=None,
                 Types=None):
        DiG.__init__(self, data)

        # attributes to be stored
        self.SetGeomGraph(NodesPos, Edges, Radii, Types)
        self.Area = 0
Beispiel #29
0
 def build_static(self):
     for agent_index in range(len(
             self.graph['agent_prod_array'])):  #对每一个机器人的product自动机
         for other_agent in range(len(self.graph['agent_prod_array'])):
             if agent_index == other_agent:
                 continue
             else:
                 #no collative task
                 if len(self.graph['colla_ap'][other_agent]) == 0:
                     continue
                 else:
                     for ap_index in range(
                             len(self.graph['colla_ap'][other_agent])):
                         #zai region zhong zhao dao suo you yu ap dui ying de qu yu dian
                         cor_pos_list = self.find_region(
                             self.graph['colla_ap'][other_agent][ap_index],
                             self.graph['region_array'][other_agent])
                         #zai fts zhao dao mei ge qu yu dian de qian ji yi ji cost, qu zui xiao de cun xia lai
                         cost_static = float('inf')
                         fts_digraph = DiGraph()
                         fts_digraph.add_edges_from(
                             self.graph['agent_fts_array']
                             [other_agent].edges())
                         for pos in cor_pos_list:
                             if len(pos) != 3:
                                 continue
                             for pre_pos in fts_digraph.predecessors(pos):
                                 if pre_pos == pos:  #pai chu yuan di bu dong de qing kuang
                                     continue
                                 cost_buf = distance(pos, pre_pos)
                                 if cost_buf < cost_static:
                                     cost_static = cost_buf
                         #zai ben ji qi ren de product zhong jia bian ,ju ti jia fa an guomeng zhi qian gou jian product zi dong ji de fang fa
                         for static_edge in self.graph['static_list'][
                                 agent_index]:  #shu ju jie guo de tong yi
                             #yao qiu colla_ap gei chu dui ying de dong zuo,bi ru door dui ying open,zhe ge ke yi tong guo ren wu de sheng ming fang shi jin xing zi dong shi bie?
                             if self.graph['colla_ap'][agent_index][
                                     ap_index] in static_edge[2]:
                                 cost_local = distance(
                                     static_edge[0][0], static_edge[1][0])
                                 #print(static_edge[0])
                                 self.graph['agent_prod_array'][
                                     agent_index].add_edge(
                                         static_edge[0],
                                         static_edge[1],
                                         weight=cost_static + cost_local)
                                 self.req_edges[(static_edge[0][0],
                                                 static_edge[1][0])] = [
                                                     agent_index,
                                                     other_agent,
                                                     static_edge[2]
                                                 ]  #chuan ap?
Beispiel #30
0
class SimpleGraphDB\
(
    Generic[SimpleVertexLabel, VertexData], 
    PartiallyStatefulDirectedGraphInterface[SimpleVertexLabel, VertexData],
    StatefulVertexGraphLoaderInterface[SimpleVertexLabel, VertexData]
):
    '''
    Class that can write stateful vertices and stateless directed edges into a graph-like structure.
    '''

    __graph: DiGraph

    '''
    Property and dunder methods
    '''

    def __init__(self, *args: Any, **kwargs: Any) -> None:
        '''
        Sets up a `networkx.DiGraph` structure for writing stateful vertices and stateless direWcted edges.
        '''
        self.__graph = DiGraph()

        return None

    @property
    def _graph(self) -> DiGraph: return self.__graph

    '''
    ABC extensions.
    '''

    def write_stateful_vertex_(self, label: SimpleVertexLabel, data: VertexData, *args: Any, **kwargs: Any) -> None:
        '''
        Writes a vertex with this `label` associated with this `data` into a `networkx.DiGraph` object.
        '''
        self.__graph.add_node(node_for_adding = label, data = data)

        return None

    def write_stateless_directed_edge_(self, source: SimpleVertexLabel, destination: SimpleVertexLabel, *args: Any, **kwargs: Any) -> None:
        '''
        Writes an unlabelled edge between a vertex with this `source` label and one with this `destination` label into a `networkx.DiGraph` object.
        '''
        self.__graph.add_edge(u_of_edge = source, v_of_edge = destination)

        return None

    def load_stateful_vertex(self, label: SimpleVertexLabel, *args: Any, **kwargs: Any) -> VertexData:
        '''
        Loads the `VertexData` associated with this `label` from a `networkx.DiGraph` object.
        '''
        return self.__graph.nodes[label].get('data')
Beispiel #31
0
def buchi_from_ltl(formula,Type):
    promela_string = run_ltl2ba(formula)
    symbols = find_symbols(formula)
    edges = parse_ltl(promela_string)
    (states, initials, accepts) = find_states(edges)
    buchi = DiGraph(type=Type, initial=initials, accept=accepts, symbols=symbols)
    for state in states:
        buchi.add_node(state)
    for (ef,et) in edges.keys():
        guard_formula = edges[(ef,et)]
        guard_expr = parse_guard(guard_formula)
        buchi.add_edge(ef, et, guard=guard_expr, guard_formula=guard_formula)
    return buchi
Beispiel #32
0
 def __init__(self, region_array, agent_prod_array, agent_fts_array,
              colla_ap, static_list):
     DiGraph.__init__(self,
                      region_array=region_array,
                      agent_prod_array=agent_prod_array,
                      agent_fts_array=agent_fts_array,
                      colla_ap=colla_ap,
                      static_list=static_list,
                      initial=set(),
                      accept=set(),
                      type='multi_prod')
     #structure: {(edge):[require_robot_index,responde_robot_index,require_position]}
     self.req_edges = {}
Beispiel #33
0
    def get_predicate_deps_graph(self):
        if self.predicate_deps_graph != None:
            return self.predicate_deps_graph

        self.predicate_deps_graph = DiGraph()
        # add a node for each Predicate
        self.predicate_deps_graph.add_nodes_from(self.get_predicate_names())
        for predicate_name in self.get_predicate_names():
            for rule in self.get_rules_for_predicate(predicate_name):
                for literal in rule.get_literals():
                    self.predicate_deps_graph.add_edge(literal.atom.name,
                                                       predicate_name)
        return self.predicate_deps_graph
Beispiel #34
0
 def add_edge(self, u, v=None):  
     if v is None: (u,v)=u  # no v given, assume u is an edge tuple
     if self.has_edge(u,v): return # no parallel edges
     elif u in self and v in self:
         raise NetworkXError, "adding edge %s-%s not allowed in tree"%(u,v)
     elif u in self or v in self:
         DiGraph.add_edge(self,u,v) # u->v
         return
     elif len(self.adj)==0: # first leaf
         DiGraph.add_edge(self,u,v) # u->v           
         return
     else:
         raise NetworkXError("adding edge %s-%s not allowed in tree"%(u,v))
Beispiel #35
0
    def load_from_graphml(path):
        """
        :type path: str
        :rtype: networkx.classes.graph.Graph
        """
        #: :type : networkx.classes.graph.Graph
        g1 = nx.read_graphml(path)
        #: :type graph: networkx.classes.digraph.DiGraph
        g2 = DiGraph()

        typetest = re.compile(r"([a-zA-z]+)(\d*)")

        max_qualifiers = dict(crossing=0, poi=0, plcs=0)
        node_mapping = dict()

        for node, data in g1.nodes_iter(data=True):

            m = typetest.match(data["label"])
            if m is None:
                raise(SALMAException("Wrong label format for node {}!".format(node)))

            loctype = m.group(1)
            if loctype in ["c"]:
                loctype = "crossing"
            elif loctype in ["p"]:
                loctype = "poi"
            elif loctype in ["pl"]:
                loctype = "plcs"
            if loctype not in ["poi", "plcs", "crossing"]:
                raise(SALMAException("Wrong loctype for node {}: {}".format(node, loctype)))
            qualifier = m.group(2)
            if len(qualifier) == 0:
                qualifier = max_qualifiers[loctype] + 1
                nid = data["label"] + str(qualifier)
            else:
                nid = data["label"]
            max_qualifiers[loctype] = max(max_qualifiers[loctype], qualifier)

            pos = (round(float(data["x"])), round(float(data["y"])))

            g2.add_node(nid, pos=pos, scaled_pos=pos, loctype=loctype)
            node_mapping[node] = nid

        for u, v in g1.edges_iter():
            n1 = node_mapping[u]
            n2 = node_mapping[v]
            g2.add_edge(n1, n2)
            g2.add_edge(n2, n1)

        MapGenerator.__add_roadlengths(g2)
        return g2
Beispiel #36
0
    def buchiGraph(self):
        """parse the output of ltl2ba
        Parameter:
            buchi_graph: Graph of buchi automaton
        """
        # find all states
        state_re = re.compile(r'\n(\w+):\n\t')
        state_group = re.findall(state_re, self.buchi_str)

        # find initial and accepting states
        init = [s for s in state_group if 'init' in s]
        accep = [s for s in state_group if 'accept' in s]
        """
        Format:
            buchi_graph.node = NodeView(('T0_init', 'T1_S1', 'accept_S1'))
            buchi_graph.edges = OutEdgeView([('T0_init', 'T0_init'), ('T0_init', 'T1_S1'),....])
            buchi_graph.succ = AdjacencyView({'T0_init': {'T0_init': {'label': '1'}, 'T1_S1': {'label': 'r3'}}})
        """
        self.buchi_graph = DiGraph(type='buchi', init=init, accept=accep)
        order_key = list(self.formula_comp.keys())
        order_key.sort(reverse=True)
        for state in state_group:
            # for each state, find transition relation
            # add node
            self.buchi_graph.add_node(state)
            state_if_fi = re.findall(state + r':\n\tif(.*?)fi', self.buchi_str,
                                     re.DOTALL)
            if state_if_fi:
                relation_group = re.findall(r':: (\(.*?\)) -> goto (\w+)\n\t',
                                            state_if_fi[0])
                for (labell, state_dest) in relation_group:
                    # whether the edge is feasible in terms of unit atomic proposition
                    label = self.InitialDelInfesEdge(labell)
                    if not label or label.isspace():
                        continue
                    # add edge
                    for k in order_key:
                        if k >= 10:
                            label = label.replace('e_{0}'.format(k),
                                                  self.formula_comp[k])
                        else:
                            label = label.replace('e{0}'.format(k),
                                                  self.formula_comp[k])
                    # if '!' in label:
                    #     label = self.PutNotInside(label)
                    label = label.replace('||',
                                          '|').replace('&&',
                                                       '&').replace('!', '~')
                    self.buchi_graph.add_edge(state, state_dest, label=label)

        return self.buchi_graph
Beispiel #37
0
 def __init__(self, mdp, dra, gamma):
     DiGraph.__init__(self,
                      mdp=mdp,
                      dra=dra,
                      initial=set(),
                      accept=[],
                      name='Product_Dra',
                      gamma=[0, 0])
     self.graph['U'] = mdp.graph['U']
     print "-------Prod DRA Initialized-------"
     self.graph['dirichlet'] = None
     self.graph['gamma'] = gamma
     self.graph['home'] = set()
     self.build_full()
Beispiel #38
0
    def __init__(self, task):
        """
        initialization
        :param task: task specified in LTL
        """
        # task specified in LTL
        self.formula = task.formula
        self.subformula = task.subformula
        self.number_of_robots = task.number_of_robots
        # graph of buchi automaton
        self.buchi_graph = DiGraph(type='buchi', init=[], accept=[])

        # minimal length (in terms of number of transitions) between a pair of nodes
        self.min_length = dict()
Beispiel #39
0
	def create_fair_graph(self,system):
		G = DiGraph()
		G.add_edges_from(self.edges(data=True))
		controls = nx.get_edge_attributes(self,'control')
		unfair_cycles = []
		for cycle in nx.simple_cycles(G):
			edges = [(cycle[i],cycle[(i+1)%len(cycle)]) for i in range(len(cycle))]
			trace = [(c[0],controls[c].values()) for c in edges]
			nbre_controls = [range(len(t[1])) for t in trace]
			control_configuration = itertools.product(*nbre_controls)
			for conf in control_configuration:
				current_trace = [(t[0],t[1][conf[i]]) for i,t in enumerate(trace)]
				if not self.is_cycle_fair(system,current_trace):
					unfair_cycles.append(current_trace)
		print "Unfair cycles ",unfair_cycles
Beispiel #40
0
 def __init__(self, formula):
     #----call ltl2dra executable----
     ltl2dra_output = run_ltl2dra(formula)
     #----parse the output----
     statenum, init, edges, aps, acc = parse_dra(ltl2dra_output)
     #------
     DiGraph.__init__(self, type='DRA', initial=set([init,]), accept=acc, symbols=aps)
     print "-------DRA Initialized-------"
     for state in xrange(0,statenum):
         self.add_node(state)
     for (ef,et) in edges.keys():
         guard_string = edges[(ef,et)]
         self.add_edge(ef, et, guard_string=guard_string)
     print "-------DRA Constructed-------"
     print "%s states, %s edges and %s accepting pairs" %(str(len(self.nodes())), str(len(self.edges())), str(len(acc)))
Beispiel #41
0
def make_test_graph():
    '''     (4)  6
             ^   ^
             | X |
            (3)  5
             ^   ^
              \ /
              [2]
               ^
               |
              (1)
    '''
    web = DiGraph()
    web.add_edges_from([(1,2), (2,3), (3,4), (2,5), (3,6), (5,6), (5,4)])
    return web
Beispiel #42
0
 def __init__(self):
     self.androGuardObjects = []
     
     self.nodes = {}
     self.nodes_id = {}
     self.entry_nodes = []
     self.G = DiGraph()
Beispiel #43
0
def get_example_1():
    # input
    g = DiGraph()
    g.add_edges_from([[1, 2], [1, 3], [2, 4], [3, 4]])

    g.node[1]['r'] = 1
    g.node[2]['r'] = 1
    g.node[3]['r'] = 1.5
    g.node[4]['r'] = 1

    g[1][2]['c'] = 2
    g[1][3]['c'] = 1
    g[2][4]['c'] = 1
    g[3][4]['c'] = 3

    U = range(6)  # 0...5
    
    expected_edge_list = [
        [],
        [(1, 3)],
        [(1, 3)],  # DiGraph([(1, 2)])
        [(1, 2), (1, 3)],
        [(1, 2), (1, 3), (2, 4)],
        [(1, 2), (1, 3), (2, 4)]
    ]
    return g, U, expected_edge_list
Beispiel #44
0
def get_example_2():
    # input
    g = DiGraph()
    g.add_edges_from([[1, 2], [1, 3], [2, 4], [3, 4]])
    
    g.node[1]['r'] = 1
    g.node[2]['r'] = 1
    g.node[3]['r'] = 1.5
    g.node[4]['r'] = 1
    
    g[1][2]['c'] = 0.021
    g[1][3]['c'] = 0.011
    g[2][4]['c'] = 0.009
    g[3][4]['c'] = 0.03

    U = [float(i) / 100 for i in xrange(6)]  # 0...5

    # expected value
    expected_edge_list = [
        [],
        [(1, 3)],
        [(1, 3)],
        [(1, 2), (1, 3)],
        [(1, 2), (1, 3), (2, 4)],
        [(1, 2), (1, 3), (2, 4)]
    ]

    return (g, U, expected_edge_list)
Beispiel #45
0
    def __init__(self, data=None, params=None, **attr):
        # self.reaction_graph.graph['node'] = {'fontname': 'Courier new'}
        # self.reaction_graph.graph['edge'] = {'fontname': 'Arial',
        #                                      'fontsize': 10.0, # labelfontsize
        #                                      'len': 4.0}
        DiGraph.__init__(self, data, **attr)
        if params is None:
            params = {}
        self.params = params  # or "config" ?
        if 'reaction_graph_default_attrs' in params:
            self.graph.update(params['reaction_graph_default_attrs'])

        # A reaction can have multiple end-state when a complex is being split up:
        # (edge_attrs should be the same for edges belonging to the same reaction for intracomplex reactions
        self.endstates_by_reaction = {}  # [startstate][(reaction_spec_pair, reaction_attr)] = [list of endstates]
        self.endstates_by_reaction[0] = defaultdict(list) # Also adding the "null" node
        self.reverse_reaction_key = {} # get reaction edge key for the opposite direction.
        self.tau_cum_max = 0
        # self.reverse_reaction[(rx_spec_pair, rx_attr)] = (rev_rx_spec_pair, rev_rx_attr)
        # used to be a dict {edge_key => target} but we can have multiple targets for a single reaction.
        self.reaction_graph_complexes_directory = params.get("reaction_graph_complexes_directory")
        if self.reaction_graph_complexes_directory is not None:
            if not os.path.exists(self.reaction_graph_complexes_directory):
                print("Creating directory for complex files:", self.reaction_graph_complexes_directory)
                os.makedirs(self.reaction_graph_complexes_directory)
            assert os.path.isdir(self.reaction_graph_complexes_directory)

        self.dispatchers = []
        # File with changes to the reaction graph, e.g. new nodes/edges and node/edge updates:
        self.reaction_graph_events_file = params.get('reaction_graph_events_file')
        if self.reaction_graph_events_file is None and self.reaction_graph_complexes_directory is not None:
            self.reaction_graph_events_file = os.path.join(self.reaction_graph_complexes_directory,
                                                           "reaction_graph_eventstream.json")

        if self.reaction_graph_events_file:
            #self.reaction_graph_delta_file = open(self.reaction_graph_delta_file, 'a')
            #self.open_files.append(self.reaction_graph_delta_file)
            gs_file_dispatcher = GraphStreamFileDispatcher(self.reaction_graph_events_file)
            gs_file_dispatcher.writer.write("# New reaction graph initialized at %s\n" % datetime.now())
            print("\n\nWriting reaction_graph event stream to file: %s\n" % self.reaction_graph_events_file)
            self.dispatchers.append(gs_file_dispatcher)
        else:
            # raise ValueError("self.reaction_graph_events_file not given: ", self.reaction_graph_events_file)
            print("self.reaction_graph_events_file (%s) not given: Graph events will not be available." %
                  self.reaction_graph_events_file)
Beispiel #46
0
 def add_node(self, n, attr_dict=None, dHdS=(0, 0), **attr):
     """ Add state node n to reaction graph. """
     assert n not in self.adj   # edge-attrs dict, {src: {tgt1: {edge1_attrs}, ...}}
     # print("ReactionGraph.add_node(%s, %s, %s, %s)" % (n, attr_dict, dHdS, attr))
     if attr_dict is None:
         attr_dict = attr
     elif attr:
         attr_dict.update(attr)
     # First dispatch
     attr_dict['dHdS'] = dHdS
     attr_dict['encounters'] = 1
     for dispatcher in self.dispatchers:
         dispatcher.add_node(n, attr_dict)
     attr_dict['dHdS_count'] = {dHdS: 1}
     # MultiGraph, with edges keyed by (reacted_spec_pair, reaction_attr):
     # reaction_graph.adj[source][target][(reacted_spec_pair, reaction_attr)] = eattr
     #self.reaction_graph.add_node(target_state, node_attrs)
     DiGraph.add_node(self, n, attr_dict)
Beispiel #47
0
class BoardGraph(object):
    def walk(self, board, size_limit=maxint):
        pending_nodes = []
        self.graph = DiGraph()
        self.start = board.display(cropped=True)
        self.graph.add_node(self.start)
        pending_nodes.append(self.start)
        self.min_domino_count = len(board.dominoes)
        while pending_nodes:
            if len(self.graph) >= size_limit:
                raise GraphLimitExceeded(size_limit)
            state = pending_nodes.pop()
            board = Board.create(state, border=1)
            dominoes = set(board.dominoes)
            self.min_domino_count = min(self.min_domino_count, len(dominoes))
            for domino in dominoes:
                dx, dy = domino.direction
                self.try_move(state, domino, dx, dy, pending_nodes)
                self.try_move(state, domino, -dx, -dy, pending_nodes)
        self.last = state
        return set(self.graph.nodes())

    def try_move(self, old_state, domino, dx, dy, pending_states):
        try:
            new_state = self.move(domino, dx, dy)
            move = domino.describe_move(dx, dy)
            if not self.graph.has_node(new_state):
                # new node
                self.graph.add_node(new_state)
                pending_states.append(new_state)
            self.graph.add_edge(old_state, new_state, move=move)
        except BoardError:
            pass

    def move(self, domino, dx, dy):
        """ Move a domino and calculate the new board state.

        Afterward, put the board back in its original state.
        @return: the new board state
        @raise BoardError: if the move is illegal
        """
        domino.move(dx, dy)
        try:
            board = domino.head.board
            if not board.isConnected():
                raise BoardError('Board is not connected.')
            if board.hasLoner():
                raise BoardError('Board has a lonely domino.')
            return board.display(cropped=True)
        finally:
            domino.move(-dx, -dy)
Beispiel #48
0
    def test_find_connecting_nodes_good_sourceDep(self):
        '''     (4)  6
                 ^   ^
                 | X |
                (3)  5
                 ^   ^
                  \ /
                  [2]
                   ^
                   |
                  (1)
        '''
        web = DiGraph()
        web.add_edges_from([(1,2), (2,3), (3,4), (2,5), (3,6), (5,6), (5,4)])

        inp = (1, 3, 4)
        out = (2,)
        (_, _, cn_nodes, _) = _research_calculation_routes(web, inp, out)
        all_out = {1,4,3}
        all_in = {2,5,6}
        self.assertTrue(cn_nodes - all_out == cn_nodes, cn_nodes)
        self.assertTrue(all_in & cn_nodes == all_in, cn_nodes)
Beispiel #49
0
def test_variance_based_cost():
    D = {'u': {}, 'v': {10: {'x', 'dum'}}, 'w': {12: {'y'}}}
    G = DiGraph()
    G.add_edges_from([('u', 'v'),
                      ('u', 'w'),
                      ('v', 'dum'),
                      ('dum', 'x'),
                      ('w', 'y')])
    G.node['dum']['dummy'] = True
    reprs = np.array([[0, 1],
                      [1, 0],
                      [0, 1],
                      [1, 1],
                      [0, 0]])
    real_nodes = ['u', 'v', 'w', 'x', 'y']
    for r, n in zip(reprs, real_nodes):
        G.node[n]['r'] = r
    n = 'u'
    children = [(10, 'v'),
                (12, 'w')]

    actual = get_all_nodes(G, n, D, children, ignore_dummy=True)
    expected = real_nodes
    assert_equal(sorted(expected), sorted(actual))

    cost_func = make_variance_cost_func(euclidean, 'r')
    
    actual = cost_func(n, D, G,
                       children)
    mean_vec = np.mean(reprs, axis=0)
    expected = np.sum([euclidean(mean_vec, v)
                       for v in reprs])
    np.testing.assert_almost_equal(expected, actual)

    # with fixed_point
    cost_func_fp = make_variance_cost_func(euclidean, 'r', fixed_point=2)
    actual = cost_func_fp(n, D, G,
                          children)
    assert_equal(int(expected*100), actual)
Beispiel #50
0
def get_example_5():
    g = DiGraph()
    g.add_edges_from([(0, 1), (0, 2), (1, 3), (1, 4),
                      (2, 4), (2, 5), (2, 6)])
    for s, t in g.edges():
        g[s][t]['c'] = 1
    g[1][4]['c'] = 0
    g[2][4]['c'] = 0
    g[2][6]['c'] = 3
    for n in g.nodes():
        g.node[n]['r'] = 1
    g.node[3]['r'] = 10
    g.node[4]['r'] = 100
    g.node[5]['r'] = 11

    U = [10]
    # sub-optimal answer actually
    expected_edge_set = [[(0, 2), (2, 4), (2, 5), (2, 6)]]
    return (g, U, expected_edge_set)
Beispiel #51
0
 def delete_edge(self, u, v=None): 
     if v is None: (u,v)=u
     if self.degree(u)==1 or self.degree(v)==1:
         DiGraph.delete_edge(self,u,v)
     else:
         raise NetworkXError(
               "deleting interior edge %s-%s not allowed in tree"%(u,v))
     if self.degree(u)==0: DiGraph.delete_node(self,u)
     if self.degree(v)==0: DiGraph.delete_node(self,v)
Beispiel #52
0
def get_example_6():
    # IN-OPTIMAL CASE
    g = DiGraph()
    g.add_edges_from([(0, 1), (0, 2), (1, 3),
                      (1, 4), (2, 4), (2, 5)])
    for s, t in g.edges():
        g[s][t]['c'] = 0
    g[1][3]['c'] = 4
    g[1][4]['c'] = 4
    g[2][4]['c'] = 2
    g[2][5]['c'] = 1
    for n in g.nodes():
        g.node[n]['r'] = 0
    g.node[3]['r'] = 1
    g.node[4]['r'] = 100
    g.node[5]['r'] = 1

    U = [7]
    # sub-optimal answer actually
    expected_edge_set = [[(0, 2), (2, 4), (2, 5)]]
    return (g, U, expected_edge_set)
Beispiel #53
0
def DuoBA_from_ltls(hard_spec, soft_spec):
    hard_buchi = buchi_from_ltl(hard_spec, 'hard_buchi')
    soft_buchi = buchi_from_ltl(soft_spec, 'soft_buchi')
    hard_symbols = hard_buchi.graph['symbols']
    soft_symbols = soft_buchi.graph['symbols']
    symbols = set(hard_symbols).union(set(soft_symbols))
    DuoBA = DiGraph(type='safe_buchi', hard=hard_buchi, soft=soft_buchi, symols=symbols)
    initial = set()
    accept = set()
    for (h_node, s_node, l) in cartesian_product(hard_buchi.nodes(), soft_buchi.nodes(), [1, 2]):
        DuoNode = (h_node, s_node, l)
        DuoBA.add_node(DuoNode,hard=h_node, soft=s_node, level=l)
        if (h_node in hard_buchi.graph['initial'] and 
            s_node in soft_buchi.graph['initial'] and l == 1):
            initial.add(DuoNode)
        if (h_node in hard_buchi.graph['accept'] and l == 1):
            accept.add(DuoNode)
    DuoBA.graph['accept'] = accept
    DuoBA.graph['initial'] = initial
    for f_duonode in DuoBA.nodes():
        for t_duonode in DuoBA.nodes():
            f_h_node, f_s_node, f_level = check_duo_attr(DuoBA, f_duonode)
            t_h_node, t_s_node, t_level = check_duo_attr(DuoBA, t_duonode)
            if (t_h_node not in DuoBA.graph['hard'].neighbors(f_h_node) or 
                t_s_node not in DuoBA.graph['soft'].neighbors(f_s_node)):
                continue
                # relaxed because no common input alphabets are enabled
            hardguard = DuoBA.graph['hard'].edges[f_h_node,t_h_node]['guard']
            softguard = DuoBA.graph['soft'].edges[f_s_node,t_s_node]['guard']
            if ((f_h_node not in DuoBA.graph['hard'].graph['accept'] and 
                f_level == 1 and t_level == 1) or 
                (f_h_node in DuoBA.graph['hard'].graph['accept'] and 
                f_level == 1 and t_level == 2) or 
                (f_s_node not in DuoBA.graph['soft'].graph['accept'] and 
                f_level == 2 and t_level == 2) or 
                (f_s_node in DuoBA.graph['soft'].graph['accept'] and 
                f_level == 2 and t_level == 1)):
                DuoBA.add_edge(f_duonode, t_duonode, hardguard=hardguard, softguard=softguard)
    return DuoBA
Beispiel #54
0
    def __init__(self,data=None,**kwds):
        DiGraph.__init__(self,**kwds)
        if data is not None:

            try: # build a rooted tree
                D=DiGraph()
                for (child,parent) in data.par.iteritems():
                    D.add_edge(parent,child)
            except AttributeError: 
                D=DiGraph(data)
            except: # else nothing we can do
                raise NetworkXError, "Data %s is not a rooted tree:"%data
                    
            if D.order()==D.size()+1:
                self.pred=D.pred.copy()
                self.succ=D.succ.copy()
                self.adj=self.succ
                del D
            else: # not a tree
                raise NetworkXError, "Data %s is not a rooted tree:"%data
Beispiel #55
0
def get_example_3():
    """get a binarized example, whose original graph is
    more complicated than the above example
    """
    g = DiGraph()
    g.add_nodes_from(range(1, 10))
    g.add_edges_from([(1, 2), (1, 3), (1, 7),
                      (2, 4), (2, 5), (2, 6),
                      (2, 7), (3, 8), (3, 9)])
    rewards = range(1, 10)
    for r, n in zip(rewards, g.nodes()):
        g.node[n]['r'] = r
        
    # all edges have cost 2 except 1 -> 2 and 1 -> 3(cost 1)
    for s, t in g.edges():
        g[s][t]['c'] = 2
    g[1][2]['c'] = 1
    g[1][3]['c'] = 1
    
    g = binarize_dag(g,
                     vertex_weight_key='r',
                     edge_weight_key='c',
                     dummy_node_name_prefix='d_')
    
    # parameters and expected output
    U = [0, 2, 3, 4, 100]
    expected_edges_set = [
        [],
        [(1, 7)],
        [(1, 'd_1'), ('d_1', 3), (3, 9)],
        [(1, 'd_1'), ('d_1', 3), (3, 9), ('d_1', 2)],
        # (1, 7) removed to make it a tree
        list(set(g.edges()) - set([(1, 7)]))
    ]
    
    return (g, U, expected_edges_set)
Beispiel #56
0
def get_variance_example_1():
    g = DiGraph()
    g.add_edges_from([
        (0, 1), (0, 2),
        (2, 3), (3, 4),
        (2, 'dummy'),
        ('dummy', 5)
    ])
    g.node['dummy']['dummy'] = True

    for n in (0, 1, 2, 5):  # topic 1
        g.node[n]['repr'] = np.array([0, 0])
    for n in (3, 4):  # topic 2
        g.node[n]['repr'] = np.array([1, 1])
    for n in g.nodes_iter():
        g.node[n]['r'] = 1

    # correct is (0, 1, 2, 5) for cost 0
    U = [0, 42]
    expected_edge_set = [
        set(g.edges()) - {(2, 3), (3, 4)},
        set(g.edges())
    ]
    return (g, U, expected_edge_set)
Beispiel #57
0
 def walk(self, board, size_limit=maxint):
     pending_nodes = []
     self.graph = DiGraph()
     self.start = board.display(cropped=True)
     self.graph.add_node(self.start)
     pending_nodes.append(self.start)
     self.min_domino_count = len(board.dominoes)
     while pending_nodes:
         if len(self.graph) >= size_limit:
             raise GraphLimitExceeded(size_limit)
         state = pending_nodes.pop()
         board = Board.create(state, border=1)
         dominoes = set(board.dominoes)
         self.min_domino_count = min(self.min_domino_count, len(dominoes))
         for domino in dominoes:
             dx, dy = domino.direction
             self.try_move(state, domino, dx, dy, pending_nodes)
             self.try_move(state, domino, -dx, -dy, pending_nodes)
     self.last = state
     return set(self.graph.nodes())
Beispiel #58
0
def get_example_4():
    g = DiGraph()
    g.add_edges_from([(0, 1), (1, 2), (2, 3), (2, 14),  # tree 1
                      (2, 15), (3, 16), (3, 17),
                      (0, 4), (4, 5), (4, 6),  # tree 2
                      (5, 11), (6, 11), (6, 12), (6, 13),
                      (0, 7), (7, 8), (7, 9),  # tree 3
                      (8, 10), (8, 11), (9, 12), (9, 13)])
    for s, t in g.edges():
        g[s][t]['c'] = 1
    for n in g.nodes():
        g.node[n]['r'] = 1
    g.node[10]['r'] = 2

    U = [7]
    expected_edge_set = [
        [(0, 7), (7, 8), (7, 9),  # tree 3
         (8, 10), (8, 11), (9, 12), (9, 13)]
    ]
    return (g, U, expected_edge_set)
Beispiel #59
0
def find_SCCs(mdp, Sneg):
    #----simply find strongly connected components----
    print 'Remaining states size', len(Sneg)
    SCC  = set()
    simple_digraph = DiGraph()
    A = dict()
    for s in mdp.nodes():
        A[s] = mdp.node[s]['act'].copy()
    for s_f in Sneg:
        if s_f not in simple_digraph:
            simple_digraph.add_node(s_f)
        for s_t in mdp.successors_iter(s_f):
            if s_t in Sneg:
                simple_digraph.add_edge(s_f,s_t)
    print "SubGraph of one Sf: %s states and %s edges" %(str(len(simple_digraph.nodes())), str(len(simple_digraph.edges())))
    sccs = strongly_connected_component_subgraphs(simple_digraph)
    for scc in sccs:
        SCC.add(frozenset(scc.nodes()))    
    return SCC, A