Beispiel #1
0
    def map_path_to_element_sequence(self, edge2element, element2edge,
                                     pruned_subgraph, paths):
        element_sequences = []
        # put all path that share the same set of elements into one group
        for path in paths:
            element_sequence = []
            for i in range(len(path) - 1):
                element_sequence.append(edge2element[(path[i], path[i + 1])])
            is_added = False
            for i in range(len(element_sequences)):
                if set(element_sequences[i][0]) == set(element_sequence):
                    element_sequences[i].append(element_sequence)
                    is_added = True
                    break
            if not is_added:
                element_sequences.append([element_sequence])

        graph_with_maximum_width = DiGraph()
        width = 0
        height = 0
        # for each group, find one poset
        for ele_seq in element_sequences:
            # all pairs of elements from the first element
            linear_order = []
            for i in range(len(ele_seq[0])):
                for j in range(i + 1, len(ele_seq[0])):
                    linear_order.append((ele_seq[0][i], ele_seq[0][j]))
            # remove contradictive pairs
            for i in range(1, len(ele_seq)):
                for j in range(len(ele_seq[1]) - 1):
                    if (ele_seq[i][j + 1], ele_seq[i][j]) in linear_order:
                        linear_order.remove((ele_seq[i][j + 1], ele_seq[i][j]))
            # hasse diagram
            hasse = DiGraph()
            hasse.add_nodes_from(ele_seq[0])
            hasse.add_edges_from(linear_order)
            self.prune_subgraph(hasse)
            try:
                w = max([len(o) for o in nx.antichains(hasse)])
            except nx.exception.NetworkXUnfeasible:
                print(hasse.edges)
            # h = nx.dag_longest_path_length(hasse)
            h = len([
                e for e in hasse.nodes
                if pruned_subgraph.nodes[element2edge[e][0]]['label'] != '1'
            ])
            if w > width or (w == width and h > height):
                graph_with_maximum_width = hasse
                width = w
                height = h
        # print(height)
        return {edge for edge in graph_with_maximum_width.edges}, list(graph_with_maximum_width.nodes), \
                            graph_with_maximum_width
Beispiel #2
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
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)
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)
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 #6
0
def build_crm(roadmap_dir='./build_roadmap/roadmap_2D.p',
              wsn_rate_dir='./wsn_routing/rate_map.p',
              ws_img_dir='./build_roadmap/ws_img.p'):
    '''
    build combined roadmap, crm
    via load roadmap and merge in wsn_rate info
    '''
    roadmap_edges = pickle.load(open(roadmap_dir, 'rb'))
    wsn_rate, wifis_loc, sink_loc = pickle.load(open(wsn_rate_dir, 'rb'))
    img = pickle.load(open(ws_img_dir, 'rb'))
    crm = DiGraph(name='combined_model',
                  ws_img=img,
                  wifis=wifis_loc,
                  sink=sink_loc)
    for e in roadmap_edges:
        (f_node, t_node) = e
        near_f_node = min(wsn_rate.keys(), key=lambda p: dist_2D(p, f_node))
        f_node_rate = wsn_rate[near_f_node]
        crm.add_node(f_node, rate=f_node_rate)
        near_t_node = min(wsn_rate.keys(), key=lambda p: dist_2D(p, t_node))
        t_node_rate = wsn_rate[near_t_node]
        crm.add_node(t_node, rate=t_node_rate)
        # interpolation
        dist_e = dist_2D(f_node, t_node)
        f_t_rate = intp_rate(f_node_rate, t_node_rate)
        crm.add_edge(f_node, t_node, rate=f_t_rate, dist=dist_e)
        t_f_rate = intp_rate(t_node_rate, f_node_rate)
        crm.add_edge(t_node, f_node, rate=t_f_rate, dist=dist_e)
    print '---crm constructed from %s and %s, %d nodes, %d edges---' % (
        roadmap_dir, wsn_rate_dir, len(crm.nodes()), len(crm.edges()))
    return crm
Beispiel #7
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 #8
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 #9
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 #10
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 #11
0
    def setUp(self):
        graph = DiGraph()
        graph.add_cycle([1, 2, 3, 4])
        graph.add_cycle([5, 6, 7, 8])
        graph.add_node(0)
        graph.add_edge(9, 10)
        self.graph_1 = graph

        graph = DiGraph()
        graph.add_cycle([1, 2, 3, 4])
        graph.add_cycle([5, 6, 7, 8])
        graph.add_node(0)
        graph.add_edge(9, 10)
        graph.add_edge(3, 9)
        graph.add_edge(10, 7)
        self.graph_2 = graph
Beispiel #12
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 #13
0
    def __init__(self):
        self.androGuardObjects = []

        self.nodes = {}
        self.nodes_id = {}
        self.entry_nodes = []
        self.G = DiGraph()
Beispiel #14
0
 def remove_low_frequency_label(
         community_label_list_for_nodes: multivalued_dict) -> DiGraph:
     from sklearn.ensemble import IsolationForest
     digraph_of_node_labels_and_frequencies = DiGraph()
     for graph_of_node, label_list_of_nodes in community_label_list_for_nodes.items(
     ):
         digraph_of_node_labels_and_frequencies.add_node(graph_of_node)
         label_set = set(label_list_of_nodes)
         dict_of_frequency_of_label = dict(
             sorted([(label_list_of_nodes.count(label_item), label_item)
                     for label_item in label_set],
                    key=lambda frequency_and_label: frequency_and_label[0],
                    reverse=True))
         dict_of_sn_and_frequency = dict([
             (sequence_number, frequency_of_label)
             for sequence_number, frequency_of_label in enumerate(
                 dict_of_frequency_of_label.keys(), 1)
         ])
         list_of_mapping_points = []
         for sequence_number, frequency_of_label in dict_of_sn_and_frequency.items(
         ):
             list_of_mapping_points.extend([[sequence_number]] *
                                           frequency_of_label)
         clf = IsolationForest(n_estimators=120, contamination='auto')
         clf.fit(list_of_mapping_points)
         for sequence_number, frequency_of_label in dict_of_sn_and_frequency.items(
         ):
             if clf.predict([[sequence_number]])[0] == 1:
                 label_item = dict_of_frequency_of_label.__getitem__(
                     frequency_of_label)
                 digraph_of_node_labels_and_frequencies.add_edge(
                     graph_of_node, label_item, weight=frequency_of_label)
     return digraph_of_node_labels_and_frequencies
Beispiel #15
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
def processEdgeList(file):
    with open(file, 'rb') as edgelist:
        G = read_edgelist(edgelist,
                          create_using=DiGraph(),
                          data=(('weight', float), ))

    df = to_pandas_adjacency(G)
    return df
Beispiel #17
0
 def _digraph(self, index):
     g = DiGraph()
     g.add_node(index[self])
     for _, (fun, _) in self.calls:
         g.add_node(index[fun])
         g.add_edge(index[fun], index[self])
         g = networkx.compose(g, fun._digraph(index))
     return g
Beispiel #18
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 #19
0
def hoftask(init, buchi_graph, regions):
    h_task = DiGraph(type='subtask')
    try:
        label = to_dnf(
            buchi_graph.edges[(buchi_graph.graph['init'][0],
                               buchi_graph.graph['init'][0])]['label'], True)
    except KeyError:
        # no self loop
        label = to_dnf('0')
    init_node = State((init, buchi_graph.graph['init'][0]), label)
    h_task.add_node(init_node)
    open_set = list()
    open_set.append(init_node)
    explore_set = list()

    while open_set:
        curr = open_set.pop(0)

        # assume co-safe
        # if curr.q in buchi_graph.graph['accept']:
        #     continue
        # print(curr)
        for q_b in buchi_graph.succ[curr.q]:

            try:
                label = to_dnf(buchi_graph.edges[(q_b, q_b)]['label'], True)
            except KeyError:
                # no self loop
                label = to_dnf('0')
            if q_b != curr.q:  # and q_b not in buchi_graph.graph['accept']:
                # region corresponding to the label/word
                edge_label = (buchi_graph.edges[(curr.q, q_b)]['label'])
                if edge_label == '(1)':
                    x_set = [curr.x]
                else:
                    x_set = target(to_dnf(edge_label), regions)
                if x_set:
                    for x in x_set:
                        cand = State((x, q_b), label)
                        # print(cand)
                        if cand not in open_set and cand not in explore_set:
                            open_set.append(cand)
                            # check the match with each subtask in h_task
                            if not match(h_task, curr, cand):
                                # print(cand)
                                h_task.add_node(cand)
                                h_task.add_edge(curr, cand)
                                # continue
                            # roots for accepting states
                            # if q_b in buchi_graph.graph['accept']:
                            #     h_task.add_edge(curr, cand)

        explore_set.append(curr)
    # for x in h_task.nodes:
    #     print(x)
    return h_task
Beispiel #20
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 #21
0
    def _build_ast(cls, rpn_expression):
        """build an AST from an Excel formula

        :param rpn_expression: a string formula or the result of parse_to_rpn()
        :return: AST which can be used to generate code
        """

        # use a directed graph to store the syntax tree
        tree = DiGraph()

        # production stack
        stack = []

        for node in rpn_expression:
            # The graph does not maintain the order of adding nodes/edges, so
            # add an attribute 'pos' so we can always sort to the correct order

            node.ast = tree
            if isinstance(node, OperatorNode):
                if node.token.type == node.token.OP_IN:
                    try:
                        arg2 = stack.pop()
                        arg1 = stack.pop()
                    except IndexError:
                        raise FormulaParserError(
                            "'{}' operator missing operand".format(
                                node.token.value))
                    tree.add_node(arg1, pos=0)
                    tree.add_node(arg2, pos=1)
                    tree.add_edge(arg1, node)
                    tree.add_edge(arg2, node)
                else:
                    try:
                        arg1 = stack.pop()
                    except IndexError:
                        raise FormulaParserError(
                            "'{}' operator missing operand".format(
                                node.token.value))
                    tree.add_node(arg1, pos=1)
                    tree.add_edge(arg1, node)

            elif isinstance(node, FunctionNode):
                if node.num_args:
                    args = stack[-node.num_args:]
                    del stack[-node.num_args:]
                    for i, a in enumerate(args):
                        tree.add_node(a, pos=i)
                        tree.add_edge(a, node)
            else:
                tree.add_node(node, pos=0)

            stack.append(node)

        assert 1 == len(stack)
        return stack[0]
Beispiel #22
0
def _transition_graph():
    expected_graph = DiGraph()
    expected_graph.add_node('85',
                            coords=(-3.8347478, -38.592189),
                            datetime=['2017-09-02 22:00:27'],
                            freq_source=1,
                            freq_target=0)
    expected_graph.add_node('673',
                            coords=(-3.8235834, -38.590389),
                            datetime=['2017-09-02 22:01:36'],
                            freq_source=0,
                            freq_target=0)
    expected_graph.add_node('394',
                            coords=(-3.813889, -38.5904445),
                            datetime=['2017-09-02 22:03:08'],
                            freq_source=0,
                            freq_target=0)
    expected_graph.add_node('263',
                            coords=(-3.9067654, -38.5907723),
                            datetime=['2017-09-02 22:03:46'],
                            freq_source=0,
                            freq_target=0)
    expected_graph.add_node('224',
                            coords=(-3.8857223, -38.5928892),
                            datetime=['2017-09-02 22:07:19'],
                            freq_source=0,
                            freq_target=0)
    expected_graph.add_node('623',
                            coords=(-3.8828723, -38.5929789),
                            datetime=['2017-09-02 22:07:40'],
                            freq_source=0,
                            freq_target=1)
    expected_graph.add_edge('85',
                            '673',
                            weight=1,
                            mean_times='0 days 00:01:09')
    expected_graph.add_edge('673',
                            '394',
                            weight=1,
                            mean_times='0 days 00:01:32')
    expected_graph.add_edge('394',
                            '263',
                            weight=1,
                            mean_times='0 days 00:00:38')
    expected_graph.add_edge('263',
                            '224',
                            weight=1,
                            mean_times='0 days 00:03:33')
    expected_graph.add_edge('224',
                            '623',
                            weight=1,
                            mean_times='0 days 00:00:21')

    return expected_graph
Beispiel #23
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 #24
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 #25
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 #26
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 #27
0
    def add_snapshot(self,
                     ebunch=None,
                     graph=None,
                     start=None,
                     end=None,
                     time=None,
                     multi=False):
        """Add a snapshot with a bunch of edge values.

        Parameters
        ----------

        ebunch : container of edges, optional (default= None)
            Each edge in the ebunch list will be included to all added graphs.
        graph : networkx graph object, optional (default= None)
            networkx graph to be inserted into snapshot graph.
        start: start timestamp, inclusive
        end: end timestamp, exclusive
        time: timestamp for impulses, cannot be used together with (start, end)
        multi : boolean, optional (default= False)
            Determines if type of graphs in snapshot are DiGraphs for MultiDiGraphs

        Returns
        -------
        None

        Examples
        --------
        >>> G = dnx.SnapshotGraph()
        >>> G.add_snapshot([(1, 4), (1, 3)])
        """
        if not graph:
            if multi is True:
                g = MultiDiGraph()
            else:
                g = DiGraph()
            g.add_edges_from(ebunch)
        else:
            g = graph

        if time is not None and (start or end):
            raise ValueError(
                'Time and (start or end) cannot both be specified.')
        elif time is not None:
            self.insert(g, time=time)
        elif (start is None and end is not None) or (start is not None
                                                     and end is None):
            raise ValueError(
                'Start and end must both be specified for intervals.')
        else:
            self.insert(g, start=start, end=end)
Beispiel #28
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 #29
0
def build_ast(expression, debug=False):
    """build an AST from an Excel formula expression in reverse polish notation"""
    #use a directed graph to store the tree
    G = DiGraph()
    stack = []

    for n in expression:
        # Since the graph does not maintain the order of adding nodes/edges
        # add an extra attribute 'pos' so we can always sort to the correct order
        if isinstance(n, OperatorNode):
            if n.ttype == "operator-infix":
                arg2 = stack.pop()
                arg1 = stack.pop()
                # Hack to write the name of sheet in 2argument address
                if (n.tvalue == ':'):
                    if '!' in arg1.tvalue and arg2.ttype == 'operand' and '!' not in arg2.tvalue:
                        arg2.tvalue = arg1.tvalue.split(
                            '!')[0] + '!' + arg2.tvalue

                G.add_node(arg1, {'pos': 1})
                G.add_node(arg2, {'pos': 2})
                G.add_edge(arg1, n)
                G.add_edge(arg2, n)
            else:
                arg1 = stack.pop()
                G.add_node(arg1, {'pos': 1})
                G.add_edge(arg1, n)

        elif isinstance(n, FunctionNode):
            args = []
            for _ in range(n.num_args):
                try:
                    args.append(stack.pop())
                except:
                    raise Exception()
            #try:
            # args = [stack.pop() for _ in range(n.num_args)]
            #except:
            #        print 'STACK', stack, type(n)
            #        raise Exception('prut')
            args.reverse()
            for i, a in enumerate(args):
                G.add_node(a, {'pos': i})
                G.add_edge(a, n)

        else:
            G.add_node(n, {'pos': 0})

        stack.append(n)

    return G, stack.pop()
Beispiel #30
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()