Exemplo n.º 1
1
    def test_paths(self):
        try:
            universe = tl.grid(8, 8)
            GraphSet.set_universe(universe, traversal='bfs')

            start = 1
            goal = 81
            paths = GraphSet.paths(start, goal)
            if len(paths) == 980466698:
                stderr.write("Warning: Graphillion requires 64-bit machines, though your machine might be 32-bit.\n")
            self.assertEqual(len(paths), 3266598486981642)

            key = 64
            treasure = 18
            paths_to_key = GraphSet.paths(start, key).excluding(treasure)
            treasure_paths = paths.including(paths_to_key).including(treasure)
            self.assertEqual(len(treasure_paths), 789438891932744)

            self.assertTrue(treasure_paths < paths)

            i = 0
            data = []
            for path in treasure_paths.rand_iter():
                data.append(tl.how_many_turns(path))
                if i == 100: break
                i += 1

            for path in treasure_paths.min_iter():
                min_turns = tl.how_many_turns(path)
                break
            self.assertEqual(min_turns, 5)
        except ImportError:
            pass
Exemplo n.º 2
0
    def test_forests(self):
        try:
            universe = tl.grid(8, 8, 0.37)
            GraphSet.set_universe(universe)

            generators = [1, 9, 73, 81]
            forests = GraphSet.forests(roots=generators, is_spanning=True)
            self.assertEqual(len(forests), 54060425088)

            too_large_trees = GraphSet()
            for substation in generators:
                too_large_trees |= GraphSet.trees(root=substation).larger(23)
            safe_forests = forests.excluding(too_large_trees)
            self.assertEqual(len(safe_forests), 294859080)

            closed_switches = (forests - safe_forests).choice()
            scores = {}
            for switch in universe:
                scores[switch] = 1 if switch in closed_switches else -1

            failures = safe_forests.blocking().minimal()
            self.assertEqual(len(failures), 1936)
            failure = failures.choice()
            for line in failure:
                safe_forests = safe_forests.excluding(line)
            self.assertEqual(len(safe_forests), 0)
        except ImportError:
            pass
Exemplo n.º 3
0
def setUniverse(input_graph):
    universe = []
    for i in range(0, N):
        for j in range(0, N):
            if (i < j and input_graph[i][j] == 1):
                universe.append((i, j))
    GraphSet.set_universe(universe)
Exemplo n.º 4
0
    def test_forests(self):
        try:
            universe = tl.grid(8, 8, 0.37)
            GraphSet.set_universe(universe)

            generators = [1, 9, 73, 81]
            forests = GraphSet.forests(roots=generators, is_spanning=True)
            self.assertEqual(len(forests), 54060425088)

            too_large_trees = GraphSet()
            for substation in generators:
                too_large_trees |= GraphSet.trees(root=substation).larger(23)
            safe_forests = forests.excluding(too_large_trees)
            self.assertEqual(len(safe_forests), 294859080)

            closed_switches = (forests - safe_forests).choice()
            scores = {}
            for switch in universe:
                scores[switch] = 1 if switch in closed_switches else -1

            failures = safe_forests.blocking().minimal()
            self.assertEqual(len(failures), 1936)
            failure = failures.choice()
            for line in failure:
                safe_forests = safe_forests.excluding(line)
            self.assertEqual(len(safe_forests), 0)
        except ImportError:
            pass
Exemplo n.º 5
0
    def test_paths(self):
        try:
            universe = tl.grid(8, 8)
            GraphSet.set_universe(universe, traversal='bfs')

            start = 1
            goal = 81
            paths = GraphSet.paths(start, goal)
            if len(paths) == 980466698:
                stderr.write(
                    "Warning: Graphillion requires 64-bit machines, though your machine might be 32-bit.\n"
                )
            self.assertEqual(len(paths), 3266598486981642)

            key = 64
            treasure = 18
            paths_to_key = GraphSet.paths(start, key).excluding(treasure)
            treasure_paths = paths.including(paths_to_key).including(treasure)
            self.assertEqual(len(treasure_paths), 789438891932744)

            self.assertTrue(treasure_paths < paths)

            i = 0
            data = []
            for path in treasure_paths.rand_iter():
                data.append(tl.how_many_turns(path))
                if i == 100: break
                i += 1

            for path in treasure_paths.min_iter():
                min_turns = tl.how_many_turns(path)
                break
            self.assertEqual(min_turns, 5)
        except ImportError:
            pass
Exemplo n.º 6
0
    def test_paths(self):
        try:
            universe = tl.grid(8, 8)
            GraphSet.set_universe(universe)

            start = 1
            goal = 81
            paths = GraphSet.paths(start, goal)
            self.assertEqual(len(paths), 3266598486981642)

            key = 64
            treasure = 18
            paths_to_key = GraphSet.paths(start, key).excluding(treasure)
            treasure_paths = paths.including(paths_to_key).including(treasure)
            self.assertEqual(len(treasure_paths), 789438891932744)

            self.assertTrue(treasure_paths < paths)

            i = 0
            data = []
            for path in treasure_paths.rand_iter():
                data.append(tl.how_many_turns(path))
                if i == 100: break
                i += 1

            for path in treasure_paths.min_iter():
                min_turns = tl.how_many_turns(path)
                break
            self.assertEqual(min_turns, 5)
        except ImportError:
            pass
Exemplo n.º 7
0
def countGridGraphSet(num):
    universe = tl.grid(num, num)
    GraphSet.set_universe(universe)
    start = 1
    goal = (num + 1)**2
    paths = GraphSet.paths(start, goal)
    return len(paths)
def makeZDD(haps):
    n = len(haps[1])
    ng = len(haps)
    
    universe = []
    
    for i in range(n):
      universe.append((i,i+1))
    
    GraphSet.set_universe(universe)
    
    g_univ = GraphSet({})
    
    g1 = []
    i = 1
    for i in range(ng):
      tmp = []
      for j in range(n):
        if haps[i][j] == 1:
          tmp.append(universe[j])
      if i == 0:
        g1 = [tmp]
      else :
        g1.append(tmp)
    
    G1 = GraphSet(g1)
    return G1
Exemplo n.º 9
0
    def test_forests(self):
        try:
            #universe = tl.grid(8, 8, 0.37)
            universe = [(1, 2), (1, 10), (2, 3), (2, 11), (3, 12), (4, 5), (5, 6), (5, 14), (6, 15), (7, 8), (8, 9), (8, 17), (9, 18), (10, 11), (11, 12), (11, 20), (13, 22), (14, 15), (14, 23), (16, 25), (17, 26), (18, 27), (19, 20), (19, 28), (20, 21), (21, 22), (21, 30), (22, 23), (22, 31), (23, 24), (24, 25), (25, 26), (26, 27), (26, 35), (27, 36), (28, 29), (28, 37), (29, 30), (29, 38), (30, 31), (31, 40), (32, 33), (32, 41), (33, 42), (34, 35), (37, 38), (37, 46), (38, 39), (40, 41), (41, 42), (41, 50), (42, 51), (43, 52), (44, 45), (45, 54), (46, 55), (47, 48), (47, 56), (48, 49), (49, 58), (50, 59), (51, 52), (51, 60), (52, 53), (53, 54), (53, 62), (55, 56), (56, 65), (57, 58), (57, 66), (59, 60), (59, 68), (61, 62), (61, 70), (62, 63), (64, 65), (64, 73), (65, 74), (66, 75), (67, 76), (68, 69), (69, 70), (69, 78), (70, 71), (70, 79), (71, 80), (72, 81), (74, 75), (75, 76), (76, 77), (80, 81)]
            GraphSet.set_universe(universe)

            generators = [1, 9, 73, 81]
            forests = GraphSet.forests(roots=generators, is_spanning=True)
            self.assertEqual(len(forests), 54060425088)

            too_large_trees = GraphSet()
            for substation in generators:
                too_large_trees |= GraphSet.trees(root=substation).larger(23)
            safe_forests = forests.excluding(too_large_trees)
            self.assertEqual(len(safe_forests), 294859080)

            closed_switches = (forests - safe_forests).choice()
            scores = {}
            for switch in universe:
                scores[switch] = 1 if switch in closed_switches else -1

            failures = safe_forests.blocking().minimal()
            self.assertEqual(len(failures), 1936)
            failure = failures.choice()
            for line in failure:
                safe_forests = safe_forests.excluding(line)
            self.assertEqual(len(safe_forests), 0)
        except ImportError:
            pass
Exemplo n.º 10
0
 def enumerate(self):
     GraphSet.set_universe(self.bond_universe)
     # 全域グラフのみ列挙
     self.paths = GraphSet.graphs(
         vertex_groups=[self.atm_no_list],
         degree_constraints=self.degree_constraints,
         no_loop=True)
     self.paths_num = len(self.paths)
Exemplo n.º 11
0
 def test_show_messages(self):
     a = GraphSet.show_messages()
     b = GraphSet.show_messages(True)
     self.assertTrue(b)
     c = GraphSet.show_messages(False)
     self.assertTrue(c)
     d = GraphSet.show_messages(a)
     self.assertFalse(d)
Exemplo n.º 12
0
 def test_show_messages(self):
     a = GraphSet.show_messages()
     b = GraphSet.show_messages(True)
     self.assertTrue(b)
     c = GraphSet.show_messages(False)
     self.assertTrue(c)
     d = GraphSet.show_messages(a)
     self.assertFalse(d)
Exemplo n.º 13
0
def test(file):
    pathList = readFile(file)
    GraphSet.set_universe(pathList)
    cycles = GraphSet.cycles()
    sizeList = sorted([len(cycle) / 2 for cycle in cycles])

    sizeList.reverse()
    print(sizeList)
Exemplo n.º 14
0
    def capacity(self):
        gs = GraphSet()
        self.assertFalse(gs)

        gs = GraphSet([g0, g12, g13])
        self.assertTrue(gs)

        self.assertEqual(len(gs), 3)
        self.assertEqual(gs.len(), 3)
Exemplo n.º 15
0
    def capacity(self):
        gs = GraphSet()
        self.assertFalse(gs)

        gs = GraphSet([g0, g12, g13])
        self.assertTrue(gs)

        self.assertEqual(len(gs), 3)
        self.assertEqual(gs.len(), 3)
Exemplo n.º 16
0
def findShortestPath(graph, sg):
    #graph=[(1,2),(1,3),(3,4),(2,4),(1,4)]
    #sg=[[2,3]]

    GraphSet.set_universe(graph)
    list1 = list()
    for sg1 in sg:
        roots = GraphSet.paths(sg1[0], sg1[1])
        list1.append(roots.min_iter().next())
        #print(" ".join(map(str,roots.min_iter().next())))
    return list1
Exemplo n.º 17
0
def main():
    """Create a structure that represents all paths going from a group of startpoints to a group of endpoints.

    The start point given by the user is the NE point of a group of 4 points
    The end point given by the user is the NE point of a group of 4 points
        The other 3 points are the ones that are one step W, one step S, and two steps SW.

    """


    if len(sys.argv) != 5:
        print "usage: %s [GRID-M] [GRID-N] [STARTPOINT] [ENDPOINT]" % sys.argv[0]
        exit(1)
    dim = (int(sys.argv[1]),int(sys.argv[2]))
    rows = dim[0]
    cols = dim[1]
    dimension = (dim[0]-1,dim[1]-1)
    startpoint = int(sys.argv[3])
    endpoint = int(sys.argv[4])

    starts = neighbors(startpoint, cols)
    ends = neighbors(endpoint, cols)

    from graphillion import GraphSet
    import graphillion.tutorial as tl

    universe = tl.grid(*dimension)
    GraphSet.set_universe(universe)

    paths = GraphSet()

    for start in starts:
        for end in ends:
            paths = GraphSet.union(paths,GraphSet.paths(start,end))

    print "number of paths: " + str(paths.len())
    
    """ AC: SAVE ZDD TO FILE """
    f = open("graphs/fixed_ends-%d-%d-%d-%d.zdd" % (dim[0],dim[1],startpoint,endpoint),"w")
    paths.dump(f)
    f.close()

    
    """ AC: SAVE GRAPH """
    nodes = [None] + [ (x,y) for x in xrange(dim[0]) for y in xrange(dim[1]) ]
    from collections import defaultdict
    graph = defaultdict(list)
    for index,edge in enumerate(paths.universe()):
        x,y = edge
        x,y = nodes[x],nodes[y]
        graph[x].append( (index+1,y) )
        graph[y].append( (index+1,x) )
    graph_filename = "graphs/fixed_ends-%d-%d-%d-%d.graph.pickle" % (dim[0],dim[1],startpoint,endpoint)

    # save to file
    import pickle
    with open(graph_filename,'wb') as output:
        pickle.dump(graph,output)
Exemplo n.º 18
0
    def test_comparison(self):
        gs = GraphSet([g12])
        self.assertEqual(gs, GraphSet([g12]))
        self.assertNotEqual(gs, GraphSet([g13]))

        # __nonzero__
        self.assertTrue(gs)
        self.assertFalse(GraphSet())

        v = [g0, g12, g13]
        gs = GraphSet(v)
        self.assertTrue(gs.isdisjoint(GraphSet([g1, g123])))
        self.assertFalse(gs.isdisjoint(GraphSet([g1, g12])))

        self.assertTrue(gs.issubset(GraphSet(v)))
        self.assertFalse(gs.issubset(GraphSet([g0, g12])))
        self.assertTrue(gs <= GraphSet(v))
        self.assertFalse(gs <= GraphSet([g0, g12]))
        self.assertTrue(gs < GraphSet([g0, g1, g12, g13]))
        self.assertFalse(gs < GraphSet(v))

        self.assertTrue(gs.issuperset(GraphSet(v)))
        self.assertFalse(gs.issuperset(GraphSet([g1, g12])))
        self.assertTrue(gs >= GraphSet(v))
        self.assertFalse(gs >= GraphSet([g1, g12]))
        self.assertTrue(gs > GraphSet([[], g12]))
        self.assertFalse(gs > GraphSet(v))
Exemplo n.º 19
0
    def test_large(self):
        try:
            import networkx as nx
        except ImportError:
            return

        try:
            GraphSet.converters['to_graph'] = nx.Graph
            GraphSet.converters['to_edges'] = nx.Graph.edges

            g = nx.grid_2d_graph(8, 8)
            v00, v01, v10 = (0, 0), (0, 1), (1, 0)

            GraphSet.set_universe(g)
            self.assertEqual(len(GraphSet.universe().edges()), 112)
            #            self.assertEqual(GraphSet.universe().edges()[:2], [(v00, v01), (v00, v10)])

            gs = GraphSet({})
            gs -= GraphSet(
                [nx.Graph([(v00, v01)]),
                 nx.Graph([(v00, v01), (v00, v10)])])
            self.assertEqual(gs.len(), 5192296858534827628530496329220094)

            i = 0
            for g in gs:
                if i > 100: break
                i += 1

            paths = GraphSet.paths((0, 0), (7, 7))
            self.assertEqual(len(paths), 789360053252)
        except:
            raise
        finally:
            GraphSet.converters['to_graph'] = lambda edges: edges
            GraphSet.converters['to_edges'] = lambda graph: graph
Exemplo n.º 20
0
def all_paths(dimension,dim):
    from graphillion import GraphSet
    import graphillion.tutorial as tl
    start,goal = 1,(dimension[0]+1)*(dimension[1]+1)
    
    universe = tl.grid(*dimension)
    GraphSet.set_universe(universe)
    paths = GraphSet()
    for i in range(start,goal):
        for j in range(i+1,goal+1):
            paths = GraphSet.union(paths,GraphSet.paths(i,j))

    f = open("graphs/general_ends-%d-%d.zdd" % (dim[0],dim[1]),"w")
    paths.dump(f)
    f.close()

    nodes = [None] + [ (x,y) for x in xrange(dim[0]) for y in xrange(dim[1]) ]
    from collections import defaultdict
    graph = defaultdict(list)
    for index,edge in enumerate(paths.universe()):
        x,y = edge
        x,y = nodes[x],nodes[y]
        graph[x].append( (index+1,y) )
        graph[y].append( (index+1,x) )
    graph_filename = "graphs/general_ends-%d-%d.graph.pickle" % (dim[0],dim[1])

    with open(graph_filename,'wb') as output:
        pickle.dump(graph,output)
Exemplo n.º 21
0
    def test_networkx(self):
        try:
            import networkx as nx
        except ImportError:
            return

        try:
            GraphSet.converters['to_graph'] = nx.Graph
            GraphSet.converters['to_edges'] = nx.Graph.edges

            g = nx.grid_2d_graph(3, 3)
            GraphSet.set_universe(g)
            g = GraphSet.universe()
            self.assertTrue(isinstance(g, nx.Graph))
            self.assertEqual(len(g.edges()), 12)

            v00, v01, v10 = (0, 0), (0, 1), (1, 0)
            e1, e2 = (v00, v01), (v00, v10)
            gs = GraphSet([nx.Graph([e1])])
            self.assertEqual(len(gs), 1)
            g = gs.pop()
            self.assertEqual(len(gs), 0)
            self.assertTrue(isinstance(g, nx.Graph))
            self.assertTrue(g.edges() == [(v00, v01)]
                            or g.edges() == [(v01, v00)])
            gs.add(nx.Graph([e2]))
            self.assertEqual(len(gs), 1)
        except:
            raise
        finally:
            GraphSet.converters['to_graph'] = lambda edges: edges
            GraphSet.converters['to_edges'] = lambda graph: graph
Exemplo n.º 22
0
 def _enumerate_trees(self, root):
     gs = GraphSet()
     if self._satisfies_electric_constraints(root, set()):
         sur_switches = self._find_surrounding_switches(root, set())
         gs = self._find_trees(set(), sur_switches)
     border_switches = self._find_border_switches(root)
     return gs | self._do_enumerate_trees(root, set(), border_switches)
Exemplo n.º 23
0
    def graph(self, g, wtd=None, n=None, universe=None):
        if not isinstance(g, nx.Graph):
            g = nx.Graph(list(g))
        if n is None:
            n = len(g)
        if universe is None:
            universe = GraphSet.universe()
        if not isinstance(universe, nx.Graph):
            universe = nx.Graph(list(universe))
        #ここまでで (g, universe) ともにnx.graphが定まった.

        m = n - 1
        pos = {}
        #position: optional {'vartex':(x, y)}
        pos[0] = (-1, 0)
        for v in range(1, m**2):
            pos[v] = ((v - 1) // m, (v - 1) % m)

        nx.draw(g, pos)
        if wtd is None:
            pass
        else:
            label = {}
            for s in g.edges():
                t = tuple(sorted(s))  # 辺が逆順で入力されてもソートできる
                label[t] = wtd[t]
            nx.draw_networkx_edge_labels(g, pos, edge_labels=label)

        plt.show()
Exemplo n.º 24
0
def calc_r(universe, graph, traffic_matrix, weight_list, cap_matrix):
    flow = np.zeros((N, N))
    failed_link = list(set(universe) - set(graph))
    # print("failed_link", failed_link)
    for s, d, traffic in tr:
        # print('({0},{1})'.format(s,d))
        all_paths = GraphSet.paths(s, d)
        if failed_link == []:
            paths = all_paths
        else:
            paths = all_paths.excluding(failed_link)
        # print("paths", len(paths))
        ospf_path_list = shortest_path(paths, weight_list)
        # print(ospf_path_list)

        ecmp_div = len(ospf_path_list)
        #print(ecmp_div)
        for ospf_path in ospf_path_list:
            for hop in ospf_path:
                flow[hop[0]][hop[1]] += traffic / ecmp_div
                # print('{0},{1},{2}'.format(hop[0],hop[1],traffic/ecmp_div))

    print(flow)
    congestion = flow / G_cap
    #print('------------')
    # print(congestion)
    cgn_s = int(np.argmax(congestion) / N)
    cgn_d = int(np.argmax(congestion) % N)
    r = np.amax(congestion)
    # print(r)
    # print((cgn_s,cgn_d))
    return cgn_s, cgn_d, r, congestion
Exemplo n.º 25
0
def draw_subgraph(subgraph=None, universe=None):
    if not universe:
        universe = GraphSet.universe()
    g = nx.Graph(sorted(universe))

    if not subgraph:
        subgraph = set([])
    else:
        subgraph = set(subgraph)

    pos = _graph2nx_layout(g)
    nx.draw_networkx_nodes(g, pos, node_color='#FFFFFF', edgecolors='#000000')
    edge_weights = []
    edge_colors = []
    for edge in g.edges():
        if edge in subgraph or (edge[1], edge[0]) in subgraph:
            edge_weights.append(5)
            edge_colors.append('#FF0000')
        else:
            edge_weights.append(1)
            edge_colors.append('#000000')

    nx.draw_networkx_labels(g, pos)
    nx.draw_networkx_edges(g, pos, edge_color=edge_colors, width=edge_weights)

    plt.show()
 def test_flatten_paths(self):
     paths = GraphSet.paths(1, 4)
     edges = []
     for path in paths:
         for edge in path:
             edges.append(edge)
     eq_(gu.flatten_paths(paths), edges)
Exemplo n.º 27
0
def bidirectional_disjoint_paths(paths, path):
    """
    パスのグラフセットから指定したパスの双方向link-disjoint pathを求める
    双方向にリンクが共有されないようにする
    つまり(i,j), (j,v), (v,i)と共有されないパス集合が返る

    arguments:
    * paths(GraphSet)
    * path(list)

    returns:
    * di_paths(GraphSet)
    """
    disjoint_elms = []
    v_nodes = virtual_nodes()
    v_table = virtual_node_table()
    for e in path:
        if e[0] in v_nodes:
            i, j = v_table[e[0]]
            disjoint_elms += [[(i, j)], [(e[0], i)], [(j, e[0])]]
        elif e[1] in v_nodes:
            j, i = v_table[e[1]]
            disjoint_elms += [[(i, j)], [(e[1], i)], [(j, e[1])]]
        else:
            disjoint_elms.append([e])
            i, j = e[0], e[1]
            v = virtual_node_expression(i, j)
            if v in v_nodes:
                disjoint_elms += [[(i, v)], [(v, j)]]
            else:
                v = virtual_node_expression(j, i)
                disjoint_elms += [[(i, v)], [(v, j)]]
    return paths.excluding(GraphSet(disjoint_elms))
Exemplo n.º 28
0
def directed_paths(start_node, target_node):
    """
    有向性を考慮したパスだけを含むグラフセットを返す

    arguments:
    * start_node(node label)
    * target_node(node label)

    returns:
    * di_paths(GraphSet)
      有効性を考慮したパスだけを含むグラフセット
    """
    elms = invalid_direction_elms(start_node, target_node)
    elms = GraphSet(elms)
    di_paths = GraphSet.paths(start_node, target_node)
    di_paths = di_paths.excluding(elms)
    return di_paths
Exemplo n.º 29
0
def directed_paths(DiGraph, start_node, target_node):
    """
    有向性を考慮したパスだけを含むグラフセットを返す

    arguments:
    * DiGraph(networkx directed Graph object)
    * start_node(start node label)
    * target_node(target node label)

    returns:
    * di_paths(graphillion.GraphSet)
      有向性を考慮したパスだけを含むグラフセット
    """
    di_paths = GraphSet.paths(start_node, target_node)
    elms = invalid_direction_elms(DiGraph, start_node)
    di_paths = di_paths.excluding(GraphSet(elms))
    return di_paths
Exemplo n.º 30
0
def external_edges(node):
    """
    nodeの流出リンクを返す

    arguments:
    * node(node label)

    returns:
    * external_edges(list)
      nodeの流出リンク
    """
    in_edges = internal_edges(node)
    ex_edges = [
        l for l in GraphSet({}).graph_size(1).including(node) -
        GraphSet(in_edges)
    ]
    return ex_edges
Exemplo n.º 31
0
    def test_forests(self):
        try:
            #universe = tl.grid(8, 8, 0.37)
            universe = [(1, 2), (1, 10), (2, 3), (2, 11), (3, 12), (4, 5),
                        (5, 6), (5, 14), (6, 15), (7, 8), (8, 9), (8, 17),
                        (9, 18), (10, 11), (11, 12), (11, 20), (13, 22),
                        (14, 15), (14, 23), (16, 25), (17, 26), (18, 27),
                        (19, 20), (19, 28), (20, 21), (21, 22), (21, 30),
                        (22, 23), (22, 31), (23, 24), (24, 25), (25, 26),
                        (26, 27), (26, 35), (27, 36), (28, 29), (28, 37),
                        (29, 30), (29, 38), (30, 31), (31, 40), (32, 33),
                        (32, 41), (33, 42), (34, 35), (37, 38), (37, 46),
                        (38, 39), (40, 41), (41, 42), (41, 50), (42, 51),
                        (43, 52), (44, 45), (45, 54), (46, 55), (47, 48),
                        (47, 56), (48, 49), (49, 58), (50, 59), (51, 52),
                        (51, 60), (52, 53), (53, 54), (53, 62), (55, 56),
                        (56, 65), (57, 58), (57, 66), (59, 60), (59, 68),
                        (61, 62), (61, 70), (62, 63), (64, 65), (64, 73),
                        (65, 74), (66, 75), (67, 76), (68, 69), (69, 70),
                        (69, 78), (70, 71), (70, 79), (71, 80), (72, 81),
                        (74, 75), (75, 76), (76, 77), (80, 81)]
            GraphSet.set_universe(universe)

            generators = [1, 9, 73, 81]
            forests = GraphSet.forests(roots=generators, is_spanning=True)
            self.assertEqual(len(forests), 54060425088)

            too_large_trees = GraphSet()
            for substation in generators:
                too_large_trees |= GraphSet.trees(root=substation).larger(23)
            safe_forests = forests.excluding(too_large_trees)
            self.assertEqual(len(safe_forests), 294859080)

            closed_switches = (forests - safe_forests).choice()
            scores = {}
            for switch in universe:
                scores[switch] = 1 if switch in closed_switches else -1

            failures = safe_forests.blocking().minimal()
            self.assertEqual(len(failures), 1936)
            failure = failures.choice()
            for line in failure:
                safe_forests = safe_forests.excluding(line)
            self.assertEqual(len(safe_forests), 0)
        except ImportError:
            pass
Exemplo n.º 32
0
    def test_networkx(self):
        try:
            import networkx as nx
        except ImportError:
            return

        try:
            if nx.__version__[0] == "1": # for NetworkX version 1.x
                GraphSet.converters['to_graph'] = nx.Graph
                GraphSet.converters['to_edges'] = nx.Graph.edges
            else: # for NetworkX version 2.x
                GraphSet.converters['to_graph'] = nx.from_edgelist
                GraphSet.converters['to_edges'] = nx.to_edgelist

            g = nx.grid_2d_graph(3, 3)
            GraphSet.set_universe(g)
            g = GraphSet.universe()
            self.assertTrue(isinstance(g, nx.Graph))
            self.assertEqual(len(g.edges()), 12)

            v00, v01, v10 = (0,0), (0,1), (1,0)
            e1, e2 = (v00, v01), (v00, v10)
            gs = GraphSet([nx.Graph([e1])])
            self.assertEqual(len(gs), 1)
            g = gs.pop()
            self.assertEqual(len(gs), 0)
            self.assertTrue(isinstance(g, nx.Graph))
            self.assertTrue(list(g.edges()) == [(v00, v01)] or list(g.edges()) == [(v01, v00)])
            gs.add(nx.Graph([e2]))
            self.assertEqual(len(gs), 1)
        except:
            raise
        finally:
            GraphSet.converters['to_graph'] = lambda edges: edges
            GraphSet.converters['to_edges'] = lambda graph: graph
Exemplo n.º 33
0
    def test_init(self):
        GraphSet.set_universe([('i', 'ii')])
        self.assertEqual(GraphSet.universe(), [('i', 'ii')])

        GraphSet.set_universe([e1 + (.3,), e2 + (-.2,), e3 + (-.2,), e4 + (.4,)])
        self.assertEqual(GraphSet.universe(),
                         [e1 + (.3,), e2 + (-.2,), e3 + (-.2,), e4 + (.4,)])

        GraphSet.set_universe([e1 + (.3,), e2 + (-.2,), e3 + (-.2,), e4 + (.4,)],
                              traversal='dfs', source=1)
        self.assertEqual(GraphSet.universe(),
                         [e2 + (-.2,), e4 + (.4,), e1 + (.3,), e3 + (-.2,)])

        self.assertRaises(KeyError, GraphSet.set_universe, [(1,2), (2,1)])
Exemplo n.º 34
0
 def GetLocalConstraintsForRoot(self, file_prefix):
     then_vtree_filename = "%s/%s_then_vtree.vtree" % (file_prefix,
                                                       self.name)
     then_sdd_filename = "%s/%s_then_sdd.sdd" % (file_prefix, self.name)
     constraint = {}
     constraint["then_vtree"] = then_vtree_filename
     constraint["then"] = [then_sdd_filename]
     universe = []
     # internal edges
     for sub_region_edge_tup in self.sub_region_edges:
         universe.append(sub_region_edge_tup)
     GraphSet.set_universe(universe)
     universe = GraphSet.universe()
     paths = GraphSet()
     child_names = self.children.keys()
     for (i, j) in itertools.combinations(child_names, 2):
         paths = paths.union(GraphSet.paths(i, j))
     name_to_sdd_index = {}
     zdd_to_sdd_index = [None]  # for generating sdd from graphset
     sdd_index = 0
     for child in child_names:
         sdd_index += 1
         name_to_sdd_index["c%s" % child] = sdd_index
     for sub_region_edge in universe:
         corresponding_network_edges = self.sub_region_edges[
             sub_region_edge]
         coresponding_network_edges_sdd_index = []
         for single_edge in corresponding_network_edges:
             sdd_index += 1
             name_to_sdd_index[str(single_edge)] = sdd_index
             coresponding_network_edges_sdd_index.append(sdd_index)
         zdd_to_sdd_index.append(coresponding_network_edges_sdd_index)
     constraint["then_variable_mapping"] = name_to_sdd_index
     rl_vtree = sdd.sdd_vtree_new(sdd_index, "right")
     sdd_manager = sdd.sdd_manager_new(rl_vtree)
     sdd.sdd_vtree_free(rl_vtree)
     sdd.sdd_manager_auto_gc_and_minimize_off(sdd_manager)
     # Construct simple path constraint
     simple_path_constraint = generate_sdd_from_graphset(
         paths, sdd_manager, zdd_to_sdd_index)
     # non empty path in this region map
     none_of_child = sdd.util.sdd_negative_term(
         sdd_manager,
         [name_to_sdd_index["c%s" % child] for child in self.children])
     case_one = sdd.sdd_conjoin(none_of_child, simple_path_constraint,
                                sdd_manager)
     # empty path in this region map
     exactly_one_child = sdd.util.sdd_exactly_one(
         sdd_manager,
         [name_to_sdd_index["c%s" % child] for child in self.children])
     empty_path_constraint = sdd.util.sdd_negative_term(
         sdd_manager, sum(zdd_to_sdd_index[1:], []))
     case_two = sdd.sdd_conjoin(exactly_one_child, empty_path_constraint,
                                sdd_manager)
     total_constraint = sdd.sdd_disjoin(case_one, case_two, sdd_manager)
     sdd.sdd_save(then_sdd_filename, total_constraint)
     sdd.sdd_vtree_save(then_vtree_filename,
                        sdd.sdd_manager_vtree(sdd_manager))
     sdd.sdd_manager_free(sdd_manager)
     return constraint
def root_calc(start, end, weights):
    paths = gs.paths(start, end)
    print(start, end)
    try:
        max_path = next(paths.max_iter(weights))
    except StopIteration:
        max_path = []
        print(start, end, "pass")
    return max_path
Exemplo n.º 36
0
    def test_lookup(self):
        gs1 = GraphSet([g1, g12])

        self.assertTrue(g12 in gs1)
        self.assertTrue(g2 not in gs1)
        self.assertTrue(e1 in gs1)
        self.assertTrue(e4 not in gs1)
        self.assertTrue(1 in gs1)
        self.assertTrue(4 not in gs1)
Exemplo n.º 37
0
def makeLoop(lists):
    r = GraphSet.paths(lists[len(lists) - 1], lists[0])
    if len(r) == 0:
        print("null")
    for i in range(1, len(lists) - 1):
        r = r.excluding(lists[i])
    if len(r) == 0:
        r = GraphSet.paths(lists[len(lists) - 1], lists[0])
    r1 = toRoute(r.min_iter().next())
    if (len(r1) < 3):
        return lists
    list1 = list(lists)
    if r1[0] != lists[len(lists) - 1]:
        r1.reverse()
    del r1[0]
    del r1[len(r1) - 1]
    list1.extend(r1)
    return list1
Exemplo n.º 38
0
 def _enumerate_forests(self, suspicious_cut):
     vg = [[r] for r in self.graph.roots]
     dc = {}
     l = len(self.graph.graph.nodes())
     for v in self.graph.graph.nodes():
         if   v in suspicious_cut:   dc[v] = 0
         elif v in self.graph.roots: dc[v] = xrange(l)
         else:                       dc[v] = xrange(1, l)
     return GraphSet.graphs(vertex_groups=vg, degree_constraints=dc,
                            no_loop=True)
Exemplo n.º 39
0
    def test_constructors(self):
        gs = GraphSet()
        self.assertTrue(isinstance(gs, GraphSet))
        self.assertEqual(len(gs), 0)

        gs = GraphSet([])
        self.assertEqual(len(gs), 0)

        gs = GraphSet([g1, [(3,1)]])
        self.assertEqual(len(gs), 2)
        self.assertTrue(g1 in gs)
        self.assertTrue(g2 in gs)

        gs = GraphSet({})
        self.assertEqual(len(gs), 2**4)

        gs = GraphSet({'include': [e1, e2], 'exclude': [(4,3)]})
        self.assertEqual(len(gs), 2)
        self.assertTrue(g12 in gs)
        self.assertTrue(g123 in gs)

        self.assertRaises(KeyError, GraphSet, [(1,4)])
        self.assertRaises(KeyError, GraphSet, [[(1,4)]])
        self.assertRaises(KeyError, GraphSet, {'include': [(1,4)]})

        # copy constructor
        gs1 = GraphSet([g0, g12, g13])
        gs2 = gs1.copy()
        self.assertTrue(isinstance(gs2, GraphSet))
        gs1.clear()
        self.assertEqual(gs1, GraphSet())
        self.assertEqual(gs2, GraphSet([g0, g12, g13]))

        # repr
        gs = GraphSet([g0, g12, g13])
        self.assertEqual(
            repr(gs),
            "GraphSet([[], [(1, 2), (1, 3)], [(1, 2), (2, 4)]])")

        gs = GraphSet({})
        self.assertEqual(
            repr(gs),
            "GraphSet([[], [(1, 2)], [(1, 3)], [(2, 4)], [(3, 4)], [(1, 2), (1, 3)], [(1, ...")
Exemplo n.º 40
0
    def _build_graph(self):
        graph = Graph()
        sorted_sections = []
        for s in self.switches:
            ns = set()
            for t in self._find_neighbors(s):
                if t in self.sections:
                    ns.add(t)
            neighbors = set()
            is_root = False
            for t in sorted(ns):
                junctions = set([t])
                for u in self._find_neighbors(t):
                    if u in self.sections:
                        junctions.add(u)
                    if u in self.sections and u < t:
                        t = u
                neighbors.add(t)
                if t not in sorted_sections:
                    sorted_sections.append(t)
                    v = sorted_sections.index(t) + 1
                    graph._section2vertex[t] = v
                    graph._vertex2sections[v] = tuple(junctions)
            e = tuple([sorted_sections.index(t) + 1 for t in sorted(neighbors)])
            assert len(e) == 2
            graph.edges.append(e)
            graph._switch2edge[s] = e
            graph._edge2switch[e] = s
        assert len(graph.edges) == len(self.switches)

        for s in self.sections:
            if self.sections[s]['substation']:
                for t in self._find_neighbors(s):
                    if t < s:
                        s = t
                graph.roots.add(sorted_sections.index(s) + 1)
        assert len(graph.roots) == len(self._get_root_sections())

        GraphSet.set_universe(graph.edges, traversal='as-is')
        graph.graph = nx.Graph(graph.edges)

        return graph
Exemplo n.º 41
0
    def test_large(self):
        try:
            import networkx as nx
        except ImportError:
            return

        try:
            GraphSet.converters['to_graph'] = nx.Graph
            GraphSet.converters['to_edges'] = nx.Graph.edges

            g = nx.grid_2d_graph(8, 8)
            v00, v01, v10 = (0,0), (0,1), (1,0)

            GraphSet.set_universe(g)
            self.assertEqual(len(GraphSet.universe().edges()), 112)
#            self.assertEqual(GraphSet.universe().edges()[:2], [(v00, v01), (v00, v10)])

            gs = GraphSet({});
            gs -= GraphSet([nx.Graph([(v00, v01)]),
                            nx.Graph([(v00, v01), (v00, v10)])])
            self.assertEqual(gs.len(), 5192296858534827628530496329220094)

            i = 0
            for g in gs:
                if i > 100: break
                i += 1

            paths = GraphSet.paths((0, 0), (7, 7))
            self.assertEqual(len(paths), 789360053252)
        except:
            raise
        finally:
            GraphSet.converters['to_graph'] = lambda edges: edges
            GraphSet.converters['to_edges'] = lambda graph: graph
Exemplo n.º 42
0
def degree(node):
    """
    nodeの字数を返す

    arguments:
    * node(node label)

    returns:
    * degree(int)
      nodeの次数
    """

    return len(GraphSet({}).including(node).graph_size(1))
Exemplo n.º 43
0
def disjoint_paths(paths, path):
    """
    パスのグラフセットから指定したパスのlink-disjoint pathを求める

    arguments:
    * paths(GraphSet)
    * path(list)

    returns:
    * di_paths(GraphSet)
    """
    disjoint_elms = [[e] for e in path]
    return paths.excluding(GraphSet(disjoint_elms))
Exemplo n.º 44
0
 def _do_enumerate_trees(self, root, closed_switches, fixed_switches):
     gs = GraphSet()
     sur_switches = self._find_surrounding_switches(root, closed_switches)
     unfixed_switches = sur_switches - fixed_switches
     if len(unfixed_switches) == 0:
         return gs
     s = sorted(unfixed_switches)[0]
     fixed_switches.add(s)
     gs |= self._do_enumerate_trees(root, closed_switches.copy(), fixed_switches.copy())
     closed_switches.add(s)
     if self._satisfies_electric_constraints(root, closed_switches):
         sur_switches = self._find_surrounding_switches(root, closed_switches)
         gs |= self._find_trees(closed_switches, sur_switches)
         gs |= self._do_enumerate_trees(root, closed_switches.copy(), fixed_switches.copy())
     return gs
Exemplo n.º 45
0
def draw(g, universe=None):
    import networkx as nx
    import matplotlib.pyplot as plt
    if not isinstance(g, nx.Graph):
        g = nx.Graph(list(g))
    if universe is None:
        universe = GraphSet.universe()
    if not isinstance(universe, nx.Graph):
        universe = nx.Graph(list(universe))
    n = sorted(universe[1].keys())[1] - 1
    m = universe.number_of_nodes() // n
    g.add_nodes_from(universe.nodes())
    pos = {}
    for v in range(1, m * n + 1):
        pos[v] = ((v - 1) % n, (m * n - v) // n)
    nx.draw(g, pos)
    plt.show()
Exemplo n.º 46
0
    def test_modifiers(self):
        v = [g0, g12, g13]
        gs = GraphSet(v)
        gs.add(g1)
        self.assertTrue(g1 in gs)

        gs.remove(g1)
        self.assertTrue(g1 not in gs)
        self.assertRaises(KeyError, gs.remove, g1)

        gs.add(g0)
        gs.discard(g0)
        self.assertTrue(g0 not in gs)
        gs.discard(g0)  # no exception raised

        gs = GraphSet(v)
        gs.add(e2)
        self.assertEqual(gs, GraphSet([g12, g123, g2]))

        gs = GraphSet(v)
        gs.remove(e2)
        self.assertEqual(gs, GraphSet([g0, g1, g13]))
        self.assertRaises(KeyError, gs.remove, e4)

        gs = GraphSet(v)
        gs.discard(e2)
        self.assertEqual(gs, GraphSet([g0, g1, g13]))
        gs.discard(e4)  # no exception raised

        v = [g1, g12, g13]
        gs = GraphSet(v)
        g = gs.pop()
        self.assertTrue(isinstance(g, list))
        self.assertTrue(g not in gs)
        self.assertEqual(gs | GraphSet([g]), GraphSet(v))

        self.assertTrue(gs)
        gs.clear()
        self.assertFalse(gs)

        self.assertRaises(KeyError, gs.pop)

        self.assertRaises(KeyError, gs.add, [(1,4)])
        self.assertRaises(KeyError, gs.remove, [(1,4)])
        self.assertRaises(KeyError, gs.discard, [(1,4)])

        self.assertRaises(KeyError, gs.add, (1,4))
        self.assertRaises(KeyError, gs.remove, (1,4))
        self.assertRaises(KeyError, gs.discard, (1,4))

        u = [g0, g1, g12, g123, g1234, g134, g14, g4]
        gs = GraphSet(u)
        gs.flip(e1)
        self.assertEqual(gs, GraphSet([g0, g1, g14, g2, g23, g234, g34, g4]))
Exemplo n.º 47
0
    def test_iterators(self):
        gs1 = GraphSet([g0, g12, g13])
        gs2 = GraphSet()
        for g in gs1:
            self.assertTrue(isinstance(g, list))
            gs2 = gs2 | GraphSet([g])
        self.assertEqual(gs1, GraphSet([g0, g12, g13]))
        self.assertEqual(gs1, gs2)

        gs2 = GraphSet()
        for g in gs1:
            self.assertTrue(isinstance(g, list))
            gs2 = gs2 | GraphSet([g])
        self.assertEqual(gs1, gs2)

        gs1 = GraphSet([g0, g12, g13])
        gs2 = GraphSet()
        for g in gs1.rand_iter():
            self.assertTrue(isinstance(g, list))
            gs2 = gs2 | GraphSet([g])
        self.assertEqual(gs1, gs2)

        gen = gs1.rand_iter()
        self.assertTrue(isinstance(next(gen), list))

        gs = GraphSet([g0, g1, g12, g123, g1234, g134, g14, g4])
        r = []
        for g in gs.max_iter():
            self.assertTrue(isinstance(g, list))
            r.append(g)
        self.assertEqual(len(r), 8)
        self.assertEqual(r[0], g14)
        self.assertEqual(r[1], g134)
        self.assertEqual(r[2], g4)

        r = []
        for g in gs.max_iter({e1: -.3, e2: .2, e3: .2, e4: -.4}):
            self.assertTrue(isinstance(g, list))
            r.append(g)
        self.assertEqual(len(r), 8)
        self.assertEqual(r[0], g123)
        self.assertEqual(r[1], g0)
        self.assertEqual(r[2], g12)

        r = []
        for g in gs.min_iter():
            self.assertTrue(isinstance(g, list))
            r.append(g)
        self.assertEqual(len(r), 8)
        self.assertEqual(r[0], g123)
        self.assertEqual(r[1], g0)
        self.assertEqual(r[2], g12)

        r = []
        for g in gs.min_iter({e1: -.3, e2: .2, e3: .2, e4: -.4}):
            self.assertTrue(isinstance(g, list))
            r.append(g)
        self.assertEqual(len(r), 8)
        self.assertEqual(r[0], g14)
        self.assertEqual(r[1], g134)
        self.assertEqual(r[2], g4)
Exemplo n.º 48
0
 def setUp(self):
     GraphSet.set_universe([e1 + (.3,), e2 + (-.2,), e3 + (-.2,), e4 + (.4,)],
                           traversal='bfs', source=1)
Exemplo n.º 49
0
    def test_binary_operators(self):
        u = [g0, g1, g12, g123, g1234, g134, g14, g4]
        v = [g12, g14, g23, g34]

        gs = GraphSet(u) | GraphSet(v)
        self.assertTrue(isinstance(gs, GraphSet))
        self.assertEqual(
            gs, GraphSet([g0, g1, g12, g123, g1234, g134, g14, g23, g34, g4]))
        gs = GraphSet(u).union(GraphSet(u), GraphSet(v))
        self.assertTrue(isinstance(gs, GraphSet))
        self.assertEqual(
            gs, GraphSet([g0, g1, g12, g123, g1234, g134, g14, g23, g34, g4]))

        gs = GraphSet(u)
        gs |= GraphSet(v)
        self.assertTrue(isinstance(gs, GraphSet))
        self.assertEqual(
            gs, GraphSet([g0, g1, g12, g123, g1234, g134, g14, g23, g34, g4]))
        gs = GraphSet(u)
        gs.update(GraphSet(u), GraphSet(v))
        self.assertTrue(isinstance(gs, GraphSet))
        self.assertEqual(
            gs, GraphSet([g0, g1, g12, g123, g1234, g134, g14, g23, g34, g4]))

        gs = GraphSet(u) & GraphSet(v)
        self.assertTrue(isinstance(gs, GraphSet))
        self.assertEqual(gs, GraphSet([g12, g14]))
        gs = GraphSet(u).intersection(GraphSet(u), GraphSet(v))
        self.assertTrue(isinstance(gs, GraphSet))
        self.assertEqual(gs, GraphSet([g12, g14]))

        gs = GraphSet(u)
        gs &= GraphSet(v)
        self.assertTrue(isinstance(gs, GraphSet))
        self.assertEqual(gs, GraphSet([g12, g14]))
        gs = GraphSet(u)
        gs.intersection_update(GraphSet(u), GraphSet(v))
        self.assertTrue(isinstance(gs, GraphSet))
        self.assertEqual(gs, GraphSet([g12, g14]))

        gs = GraphSet(u) - GraphSet(v)
        self.assertTrue(isinstance(gs, GraphSet))
        self.assertEqual(gs, GraphSet([g0, g1, g123, g1234, g134, g4]))
        gs = GraphSet(u).difference(GraphSet(), GraphSet(v))
        self.assertTrue(isinstance(gs, GraphSet))
        self.assertEqual(gs, GraphSet([g0, g1, g123, g1234, g134, g4]))

        gs = GraphSet(u)
        gs -= GraphSet(v)
        self.assertTrue(isinstance(gs, GraphSet))
        self.assertEqual(gs, GraphSet([g0, g1, g123, g1234, g134, g4]))
        gs = GraphSet(u)
        gs.difference_update(GraphSet(), GraphSet(v))
        self.assertTrue(isinstance(gs, GraphSet))
        self.assertEqual(gs, GraphSet([g0, g1, g123, g1234, g134, g4]))

        gs = GraphSet(u) ^ GraphSet(v)
        self.assertTrue(isinstance(gs, GraphSet))
        self.assertEqual(gs, GraphSet([g0, g1, g123, g1234, g134, g23, g34, g4]))
        gs = GraphSet(u).symmetric_difference(GraphSet(), GraphSet(v))
        self.assertTrue(isinstance(gs, GraphSet))
        self.assertEqual(gs, GraphSet([g0, g1, g123, g1234, g134, g23, g34, g4]))

        gs = GraphSet(u)
        gs ^= GraphSet(v)
        self.assertTrue(isinstance(gs, GraphSet))
        self.assertEqual(gs, GraphSet([g0, g1, g123, g1234, g134, g23, g34, g4]))
        gs = GraphSet(u)
        gs.symmetric_difference_update(GraphSet(), GraphSet(v))
        self.assertTrue(isinstance(gs, GraphSet))
        self.assertEqual(gs, GraphSet([g0, g1, g123, g1234, g134, g23, g34, g4]))

        v = [g12]
        gs = GraphSet(u) / GraphSet(v)
        self.assertTrue(isinstance(gs, GraphSet))
        self.assertEqual(gs, GraphSet([g0, g3, g34]))
        gs = GraphSet(u).quotient(GraphSet(v))
        self.assertTrue(isinstance(gs, GraphSet))
        self.assertEqual(gs, GraphSet([g0, g3, g34]))

        gs = GraphSet(u)
        gs /= GraphSet(v)
        self.assertTrue(isinstance(gs, GraphSet))
        self.assertEqual(gs, GraphSet([g0, g3, g34]))
        gs = GraphSet(u)
        gs.quotient_update(GraphSet(v))
        self.assertTrue(isinstance(gs, GraphSet))
        self.assertEqual(gs, GraphSet([g0, g3, g34]))

        gs = GraphSet(u) % GraphSet(v)
        self.assertTrue(isinstance(gs, GraphSet))
        self.assertEqual(gs, GraphSet([g0, g1, g134, g14, g4]))
        gs = GraphSet(u).remainder(GraphSet(v))
        self.assertTrue(isinstance(gs, GraphSet))
        self.assertEqual(gs, GraphSet([g0, g1, g134, g14, g4]))

        gs = GraphSet(u)
        gs %= GraphSet(v)
        self.assertTrue(isinstance(gs, GraphSet))
        self.assertEqual(gs, GraphSet([g0, g1, g134, g14, g4]))
        gs = GraphSet(u)
        gs.remainder_update(GraphSet(v))
        self.assertTrue(isinstance(gs, GraphSet))
        self.assertEqual(gs, GraphSet([g0, g1, g134, g14, g4]))

        gs = GraphSet(u).complement()
        self.assertEqual(gs, GraphSet([g0, g123, g1234, g2, g23, g234, g34, g4]))

        v = [g12, g14, g23, g34]
        gs = GraphSet(u).join(GraphSet(v))
        self.assertTrue(isinstance(gs, GraphSet))
        self.assertEqual(
            gs, GraphSet([g12, g123, g124, g1234, g134, g14, g23, g234, g34]))

        gs = GraphSet(u).meet(GraphSet(v))
        self.assertTrue(isinstance(gs, GraphSet))
        self.assertEqual(gs, GraphSet([g0, g1, g12, g14, g2, g23, g3, g34, g4]))

        v = [g12, g14, g23, g34]
        gs = GraphSet(u).subgraphs(GraphSet(v))
        self.assertTrue(isinstance(gs, GraphSet))
        self.assertEqual(gs, GraphSet([g0, g1, g12, g14, g4]))

        gs = GraphSet(u).supergraphs(GraphSet(v))
        self.assertTrue(isinstance(gs, GraphSet))
        self.assertEqual(gs, GraphSet([g12, g123, g1234, g134, g14]))

        gs = GraphSet(u).non_subgraphs(GraphSet(v))
        self.assertTrue(isinstance(gs, GraphSet))
        self.assertEqual(gs, GraphSet([g123, g1234, g134]))

        gs = GraphSet(u).non_supergraphs(GraphSet(v))
        self.assertTrue(isinstance(gs, GraphSet))
        self.assertEqual(gs, GraphSet([g0, g1, g4]))

        gs1 = GraphSet({}) - GraphSet([g1, g34])

        gs2 = gs1.including(GraphSet([g1, g2]))
        self.assertTrue(isinstance(gs2, GraphSet))
        self.assertEqual(len(gs2), 11)

        gs2 = gs1.including(g1)
        self.assertTrue(isinstance(gs2, GraphSet))
        self.assertEqual(len(gs2), 7)

        gs2 = gs1.including((2,1))
        self.assertTrue(isinstance(gs2, GraphSet))
        self.assertEqual(len(gs2), 7)

        gs2 = gs1.including(1)
        self.assertTrue(isinstance(gs2, GraphSet))
        self.assertEqual(len(gs2), 11)

        self.assertRaises(KeyError, gs1.including, (1, 4))
        self.assertRaises(KeyError, gs1.including, 5)

        gs2 = gs1.excluding(GraphSet([g1, g2]))
        self.assertTrue(isinstance(gs2, GraphSet))
        self.assertEqual(len(gs2), 3)

        gs2 = gs1.excluding(g1)
        self.assertTrue(isinstance(gs2, GraphSet))
        self.assertEqual(len(gs2), 7)

        gs2 = gs1.excluding(e2)
        self.assertTrue(isinstance(gs2, GraphSet))
        self.assertEqual(len(gs2), 6)

        gs2 = gs1.excluding(1)
        self.assertTrue(isinstance(gs2, GraphSet))
        self.assertEqual(len(gs2), 3)

        self.assertRaises(KeyError, gs1.excluding, (1, 4))
        self.assertRaises(KeyError, gs1.excluding, 5)

        v = [g12, g14, g23, g34]
        gs = GraphSet(u).included(GraphSet(v))
        self.assertTrue(isinstance(gs, GraphSet))
        self.assertEqual(gs, GraphSet([g0, g1, g12, g14, g4]))

        gs = GraphSet(u).included(g12)
        self.assertTrue(isinstance(gs, GraphSet))
        self.assertEqual(gs, GraphSet([g0, g1, g12]))
Exemplo n.º 50
0
# 41044208702632496804
# 1568758030464750013214100
# 182413291514248049241470885236 
if __name__ == '__main__':
    if len(sys.argv) != 4:
        print "usage: %s [GRID-M] [GRID-N] [MIDPOINT]" % sys.argv[0]
        exit(1)
    dim = (int(sys.argv[1]),int(sys.argv[2]))
    dimension = (dim[0]-1,dim[1]-1)
    midpoint = int(sys.argv[3])
    #dimension = (1,1)

    from graphillion import GraphSet
    import graphillion.tutorial as tl
    universe = tl.grid(*dimension)
    GraphSet.set_universe(universe)

    start,goal = 1,(dimension[0]+1)*(dimension[1]+1)
    #create an empty GraphSet
    paths = GraphSet()
    paths_no_mp = GraphSet()
    for i in range(start,goal):
        print i
        for j in range(i+1,goal+1):
            #paths = GraphSet.union(paths,GraphSet.paths(i,j))
            """Exclude midpoint"""
            if i != midpoint and j != midpoint:
                paths_no_mp = GraphSet.union(paths_no_mp,GraphSet.paths(i,j))
            paths = GraphSet.union(paths,GraphSet.paths(i,j))

    pathsThruMidpoint = paths.including(midpoint)
Exemplo n.º 51
0
    def test_linear_constraints(self):
        GraphSet.set_universe([(1, 2), (1, 4), (2, 3), (2, 5), (3, 6), (4, 5),
                               (5, 6)])

        gs = GraphSet.graphs(linear_constraints=[([(2, 3)], (2, 1))])
        self.assertEqual(gs, GraphSet())

        gs = GraphSet.graphs(linear_constraints=[([], (1, 2))])
        self.assertEqual(gs, GraphSet())

        gs = GraphSet.graphs(linear_constraints=[([(5, 6, -1.5)], (-1.5, 0))])
        self.assertEqual(gs, GraphSet.graphs())

        gs = GraphSet.graphs(linear_constraints=[([(1, 2, 3.14)], (0, float("inf")))])
        self.assertEqual(gs, GraphSet.graphs())

        gs = GraphSet.graphs(linear_constraints=[(GraphSet.universe(), (0, float("inf")))])
        self.assertEqual(gs, GraphSet.graphs())

        gs = GraphSet.graphs(linear_constraints=[(GraphSet.universe(), (7, 7))])
        self.assertEqual(gs, GraphSet([GraphSet.universe()]))

        gs = GraphSet.graphs(linear_constraints=[(GraphSet.universe(), (1, 7))])
        self.assertEqual(gs, GraphSet.graphs() - GraphSet([[]]))

        gs = GraphSet.graphs(linear_constraints=[([(2, 3, -1), (2, 5, 10), (4, 1),
                                                   (3, 6), (4, 5, -1), (5, 6)],
                                                  (10, 100))])
        self.assertEqual(len(gs), 52)

        gs = GraphSet.graphs(linear_constraints=[([(2, 3), (2, 5, -10), (4, 1, -1),
                                                   (3, 6, -1), (4, 5), (5, 6, -1)],
                                                  (-100, -10))])
        self.assertEqual(len(gs), 52)

        gs = GraphSet.graphs(linear_constraints=[([(1, 2)], (1, 1)),
                                                 ([(1, 4)], (1, 2)),
                                                 ([(2, 3)], (1, 3)),
                                                 ([(2, 5)], (1, 4)),
                                                 ([(4, 5)], (1, 6)),
                                                 ([(5, 6)], (1, 7))])
        self.assertEqual(len(gs), 2)
Exemplo n.º 52
0
    def test_graphs(self):
        GraphSet.set_universe([(1, 2), (1, 4), (2, 3), (2, 5), (3, 6), (4, 5),
                               (5, 6)])

        # any subgraph
        gs = GraphSet.graphs()
        self.assertTrue(isinstance(gs, GraphSet))
        self.assertEqual(len(gs), 2**7)
        self.assertTrue([(1, 2)] in gs)

        # subgraphs separating [1, 5] and [2]
        gs = GraphSet.graphs(vertex_groups=[[1, 5], [2]])
        self.assertEqual(len(gs), 6)
        self.assertTrue([(1, 4), (4, 5)] in gs)
        self.assertTrue([(1, 2), (1, 4), (4, 5)] not in gs)

        # matching
        dc = {}
        for v in range(1, 7):
            dc[v] = range(0, 2)
        gs = GraphSet.graphs(degree_constraints=dc)
        self.assertEqual(len(gs), 22)
        self.assertTrue([(1, 2), (3, 6)] in gs)
        self.assertTrue([(1, 2), (2, 3), (3, 6)] not in gs)
        for g in gs:
            self.assertTrue(len(g) < 4)

        # subgraphs with 1 or 2 edges
        gs = GraphSet.graphs(num_edges=range(1, 3))
        self.assertEqual(len(gs), 28)
        for g in gs:
            self.assertTrue(1 <= len(g) and len(g) < 3)

        # single connected component and vertex islands
        gs = GraphSet.graphs(vertex_groups=[[]])
        self.assertEqual(len(gs), 80)
        self.assertTrue([(1, 2), (2, 3)] in gs)
        self.assertTrue([(1, 2), (2, 3), (4, 5)] not in gs)

        # any forest
        gs = GraphSet.graphs(no_loop=True)
        self.assertEqual(len(gs), 112)
        self.assertTrue([(1, 2), (1, 4), (2, 5)] in gs)
        self.assertTrue([(1, 2), (1, 4), (2, 5), (4, 5)] not in gs)
        for g in gs:
            self.assertTrue(len(g) < 6)

        # constrained by GraphSet
        gs = GraphSet.graphs(no_loop=True)
        gs = gs.graphs(vertex_groups=[[]])
        self.assertEqual(len(gs), 66)
        self.assertTrue([(1, 2), (1, 4), (2, 5)] in gs)
        self.assertTrue([(1, 2), (1, 4), (2, 5), (4, 5)] not in gs)

        # single connected components across 1, 3, and 5
        gs = GraphSet.connected_components([1, 3, 5])
        self.assertEqual(len(gs), 35)
        self.assertTrue([(1, 2), (2, 3), (2, 5)] in gs)
        self.assertTrue([(1, 2), (2, 3), (5, 6)] not in gs)

        GraphSet.set_universe([(1, 2), (1, 3), (1, 4), (1, 5), (2, 3), (2, 4),
                               (2, 5), (3, 4), (3, 5), (4, 5)])

        # cliques with 4 vertices
        gs = GraphSet.cliques(4)
        self.assertEqual(len(gs), 5)
        self.assertTrue([(1, 2), (1, 3), (1, 4), (2, 3), (2, 4), (3, 4)] in gs)
        self.assertTrue([(1, 2), (1, 3), (1, 4), (2, 3), (2, 4), (3, 5)] not in gs)

        GraphSet.set_universe([(1, 2), (1, 4), (2, 3), (2, 5), (3, 6), (4, 5),
                               (5, 6)])

        # trees rooted at 1
        gs = GraphSet.trees(1)
        self.assertEqual(len(gs), 45)
        self.assertTrue([] in gs)
        self.assertTrue([(1, 2), (1, 4), (2, 5), (4, 5)] not in gs)

        # spanning trees
        gs = GraphSet.trees(is_spanning=True)
        self.assertEqual(len(gs), 15)
        self.assertTrue([(1, 2), (1, 4), (2, 3), (2, 5), (3, 6)] in gs)
        self.assertTrue([(1, 2), (1, 4), (2, 3), (2, 5), (4, 5)] not in gs)
        for g in gs:
            self.assertEqual(len(g), 5)

        # forests rooted at 1 and 3
        gs = GraphSet.forests([1, 3])
        self.assertEqual(len(gs), 54)
        self.assertTrue([] in gs)
        self.assertTrue([(1, 2), (2, 3)] not in gs)

        # spanning forests rooted at 1 and 3
        gs = GraphSet.forests([1, 3], is_spanning=True)
        self.assertEqual(len(gs), 20)
        self.assertTrue([(1, 2), (1, 4), (2, 5), (3, 6)] in gs)
        self.assertTrue([(1, 2), (1, 4), (2, 3), (2, 5)] not in gs)
        for g in gs:
            self.assertEqual(len(g), 4)

        # cycles
        gs = GraphSet.cycles()
        self.assertEqual(len(gs), 3)
        self.assertTrue([(1, 2), (1, 4), (2, 5), (4, 5)] in gs)
        self.assertTrue([] not in gs)

        # hamilton cycles
        gs = GraphSet.cycles(is_hamilton=True)
        self.assertEqual(len(gs), 1)
        self.assertTrue([(1, 2), (1, 4), (2, 3), (3, 6), (4, 5), (5, 6)] in gs)

        # paths between 1 and 6
        gs = GraphSet.paths(1, 6)
        self.assertEqual(len(gs), 4)
        self.assertTrue([(1, 2), (2, 3), (3, 6)] in gs)
        self.assertTrue([(1, 2), (2, 3), (5, 6)] not in gs)

        # hamilton paths between 1 and 6
        gs = GraphSet.paths(1, 6, is_hamilton=True)
        self.assertEqual(len(gs), 1)
        self.assertTrue([(1, 4), (2, 3), (2, 5), (3, 6), (4, 5)] in gs)

        # called as instance methods
        gs = GraphSet.graphs(no_loop=True)
        _ = gs.connected_components([1, 3, 5])
        _ = gs.cliques(4)
        _ = gs.trees(1)
        _ = gs.forests([1, 3])
        _ = gs.cycles()
        _ = gs.paths(1, 6)

        # exceptions
        self.assertRaises(KeyError, GraphSet.graphs, vertex_groups=[[7]])
        self.assertRaises(KeyError, GraphSet.graphs, degree_constraints={7: 1})
Exemplo n.º 53
0
#!/usr/bin/env python
# coding: UTF-8
from graphillion import GraphSet
import networkx as nx
import matplotlib.pyplot as plt
import csv
execfile ('eki.py')

if __name__ == '__main__':

	univ=[]
	csvfile=open("tokyo_mini.csv")
	for row in csv.render(csvfile):
		univ.append((row[0],row[1]))

	csvfile.close()
	print len(univ)
	GraphSet.set_universe(univ)
	ekiPlot(univ)

Exemplo n.º 54
0
    def test_probability(self):
        p = {e1: .9, e2: .8, e3: .7, e4: .6}

        gs = GraphSet()
        self.assertEqual(gs.probability(p), 0)

        gs = GraphSet([g0])
        self.assertAlmostEqual(gs.probability(p), .0024)

        gs = GraphSet([g1])
        self.assertAlmostEqual(gs.probability(p), .0216)

        gs = GraphSet([g2])
        self.assertAlmostEqual(gs.probability(p), .0096)

        gs = GraphSet([g12, g13])
        self.assertAlmostEqual(gs.probability(p), .1368)

        gs = GraphSet([g1234])
        self.assertAlmostEqual(gs.probability(p), .3024)

        gs = GraphSet([g0, g1, g2, g12, g13, g1234])
        self.assertAlmostEqual(gs.probability(p), .4728)
Exemplo n.º 55
0
    def test_io(self):
        gs = GraphSet()
        st = gs.dumps()
        self.assertEqual(st, "B\n.\n")
        gs = GraphSet.loads(st)
        self.assertEqual(gs, GraphSet())

        gs = GraphSet([g0])
        st = gs.dumps()
        self.assertEqual(st, "T\n.\n")
        gs = GraphSet.loads(st)
        self.assertEqual(gs, GraphSet([g0]))

        v = [g0, g1, g12, g123, g1234, g134, g14, g4]
        gs = GraphSet(v)
        st = gs.dumps()
        gs = GraphSet.loads(st)
        self.assertEqual(gs, GraphSet(v))

        # skip this test, becasue string is treated as an element
#        gs = GraphSet(st)
#        self.assertEqual(gs, GraphSet(v))

        with tempfile.TemporaryFile() as f:
            gs.dump(f)
            f.seek(0)
            gs = GraphSet.load(f)
            self.assertEqual(gs, GraphSet(v))
Exemplo n.º 56
0
    def test_unary_operators(self):
        gs = GraphSet([g0, g1, g12, g123, g1234, g134, g14, g4])

        self.assertTrue(isinstance(~gs, GraphSet))
        self.assertEqual(~gs, GraphSet([g124, g13, g2, g23, g234, g24, g3, g34]))

        self.assertTrue(isinstance(gs.smaller(3), GraphSet))
        self.assertEqual(gs.smaller(3), GraphSet([g0, g1, g12, g14, g4]))
        self.assertTrue(isinstance(gs.larger(3), GraphSet))
        self.assertEqual(gs.larger(3), GraphSet([g1234]))
        self.assertTrue(isinstance(gs.graph_size(3), GraphSet))
        self.assertEqual(gs.graph_size(3), GraphSet([g123, g134]))
        self.assertTrue(isinstance(gs.len(3), GraphSet))
        self.assertEqual(gs.len(3), GraphSet([g123, g134]))

        gs = GraphSet([g12, g123, g234])
        self.assertTrue(isinstance(gs.minimal(), GraphSet))
        self.assertEqual(gs.minimal(), GraphSet([g12, g234]))
        self.assertTrue(isinstance(gs.maximal(), GraphSet))
        self.assertEqual(gs.maximal(), GraphSet([g123, g234]))

        gs = GraphSet([g12, g14, g23, g34])
        self.assertTrue(isinstance(gs.blocking(), GraphSet))
        self.assertEqual(
            gs.blocking(), GraphSet([g123, g1234, g124, g13, g134, g234, g24]))
            sum += 1.0
    return sum

#m列n行の格子を左上から右下にあるくこととする
#下に移動する可能性をp,下に向かう可能性をqとする

m = 2 
n = 2
p = 0.2
q = 0.8

lp = math.log10(p)
lq = math.log10(q)
mn = m+n 
goal = (m+1)*(n+1)

universe= grid_prob(m, n, p=lp, q=lq)
GraphSet.set_universe(universe)

Gu = GraphSet({})
Gt = Gu.graph_size(mn)
Gs = Gt.paths(1, goal)
weight = prob_dict(universe)

for i in Gs.max_iter(weight):
    wt = sumWeight(i, weight)
    print 10**wt
    print i


# -*- coding: utf-8 -*-


from graphillion import GraphSet
import graphillion.tutorial as tl
n=15
m=10
nm = n+m
goal = (n+1)*(m+1)

universe=tl.grid(n,m)
GraphSet.set_universe(universe)

Gt=GraphSet.paths(1,goal)
Gs=Gt.graph_size(nm)

Guniv = GraphSet({})
Gss = Guniv.graph_size(nm)
Gs2 = Gss.paths(1,goal)

len(Gs)
len(Gs2)