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 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.º 4
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.º 5
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.º 6
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.º 7
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, )],
            traversal='bfs',
            source=1)
        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, )])

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

        self.assertRaises(KeyError, GraphSet.set_universe, [(1, 2), (2, 1)])

        GraphSet.set_universe([(1, 2), (3, 4)])  # disconnected graph
        self.assertEqual(GraphSet.universe(), [(1, 2), (3, 4)])
Exemplo n.º 8
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.º 9
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.º 10
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.º 11
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.º 12
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.º 13
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.º 14
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)
Exemplo n.º 15
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 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.º 17
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.º 18
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.º 19
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.º 20
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.º 21
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.º 22
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.º 23
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.º 24
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.º 25
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,)],
                              traversal='bfs', source=1)
        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,)])

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

        self.assertRaises(KeyError, GraphSet.set_universe, [(1,2), (2,1)])

        GraphSet.set_universe([(1,2), (3,4)])  # disconnected graph
        self.assertEqual(GraphSet.universe(), [(1,2), (3,4)])
Exemplo n.º 26
0
 def setUp(self):
     GraphSet.set_universe(
         [e1 + (.3, ), e2 + (-.2, ), e3 + (-.2, ), e4 + (.4, )])
Exemplo n.º 27
0
    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


if __name__ == "__main__":
    # 動作確認
    G = nx.DiGraph(data=[("a", "b"), ("a", "d"), ("b", "c"), (
        "b", "e"), ("d", "c"), ("d", "e"), ("e", "f"), ("f", "c")])
    GraphSet.set_universe(G.edges())
    print(internal_edges(G, "b"))
    print(two_internal_edges_subgraph(G, "c"))
    print(invalid_direction_elms(G, "b"))
    print(directed_paths(G, "b", "c"))
    print(
        "the following results are directed_paths of start node to target node"
    )
    for path in directed_paths(G, "b", "c"):
        print(path)
Exemplo n.º 28
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})
def set_graph(s_s, e_s, s_dict, file):
    univ = []
    weights = {}
    most_distance = Decimal("0.0")
    longest_root = ""
    start_number = ""
    end_number = ""
    with open(file) as f:
        for line in f:
            dat = line.split(",")
            dat[0] = s_dict[dat[0]]
            dat[1] = s_dict[dat[1]]
            edge = tuple(dat[0:2])
            univ.append(edge)
            weights[(dat[0],dat[1])] = float(dat[2].replace("\n", ""))
            del dat
            del edge
            gc.collect()
    f.close()
    del f
    gc.collect()
    gs.set_universe(univ)
    if s_s != "スタート" and e_s != "ゴール":
        s = s_dict[s_s]
        start_number = s
        e = s_dict[e_s]
        end_number = e
        longest_root = root_calc(s, e, weights)
        most_distance = calc_distance(longest_root, weights)
    elif s_s != "スタート":
        s = s_dict[s_s]
        start_number = s
        for e_key in s_dict:
            e = s_dict[e_key]
            if s == e:
                continue
            max_path = root_calc(s, e, weights)
            distance = calc_distance(max_path, weights)
            if most_distance < distance:
                most_distance = distance
                longest_root = max_path
                end_number = e
    elif e_s != "ゴール":
        e = s_dict[e_s]
        end_number = e
        for s_key in s_dict:
            s = s_dict[s_key]
            if s == e:
                continue
            max_path = root_calc(s, e, weights)
            distance = calc_distance(max_path, weights)
            if most_distance < distance:
                most_distance = distance
                longest_root = max_path
                start_number = s
    else:
        station_list = []
        for s_key in s_dict:
            s = s_dict[s_key]
            station_list.append(s)
            for e_key in s_dict:
                e = s_dict[e_key]
                if e in station_list:
                    continue
                max_path = root_calc(s, e, weights)
                if max_path == []:
                    continue
                distance = calc_distance(max_path, weights)
                if most_distance < distance:
                    most_distance = distance
                    longest_root = max_path
                    start_number = s
                    end_number = e
    return longest_root, most_distance, start_number, end_number
Exemplo n.º 30
0
for i in range(h):
  for j in range(w):
    if a[i][j] != 0:
      degs[cellId[i][j]] = 1
      if a[i][j] in clue:
        clue[a[i][j]].append(cellId[i][j])
      else:
        clue[a[i][j]] = [cellId[i][j]]
    else:
      degs[cellId[i][j]] = 2

grps = []
for _,p in clue.items():
  grps.append(p)

GraphSet.set_universe(edges)
sols = GraphSet.graphs(vertex_groups=grps,
                         degree_constraints=degs,
                         no_loop=True)

print('# of Solutions: %d' % sols.len())

def choose(gs):
  for g in gs.rand_iter():
    return g
sol = choose(sols)

def output(sol):
  sh,sw = h*2+1,w*4+1
  s = [[' ' for j in range(sw)] for i in range(sh)]
Exemplo n.º 31
0
    returns:
    * probability(float)
      pathの利用確率
    """
    conv_prob = convert_common_logarithm(probabilities)
    exponent = total_cost(conv_prob, path)
    return 10**exponent


if __name__ == "__main__":
    # 動作確認
    edgelist = [(1, 2, 10), (1, 3, 20), (2, 3, 30), (2, 4, 40), (3, 4, 50),
                (2, 1, 10), (3, 1, 20), (3, 2, 30), (4, 2, 40), (4, 3, 50)]

    read_edgelist(edgelist)
    GraphSet.set_universe(append_virtual_nodes())

    print("edges_table", edges_table())
    print("append_virtual_nodes", append_virtual_nodes())
    print("append_virtual_nodes2", append_virtual_nodes2())
    print("universe", GraphSet.universe())
    print("virtual_node_edges", virtual_node_edges())
    print("virtual_nodes", virtual_nodes())
    print("original_nodes", original_nodes())
    print("predecessor_nodes", predecessor_nodes(1))
    print("internal_edges", internal_edges(2100))
    print("neighbor_nodes", neighbor_nodes(1))
    print("external_edges", external_edges(4))
    print("two_internal_edges_subgraph", two_internal_edges_subgraph(2100))
    print("invalid_direction_elms", invalid_direction_elms(4, 3))
    di_paths_1_4 = directed_paths(1, 4)
# -*- 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)

Exemplo n.º 33
0
"""
動作確認
"""
import time
from graphillion import GraphSet
from lib.gridgraph import GridGraph
from lib.utils import *

m, n = 9, 9
s,t = 1, (m+1)*(n+1)
G = GridGraph(m, n)
# GraphSet.set_universe(G.graph.edges(), traversal='dfs')
GraphSet.set_universe(G.graph.edges(), traversal='bfs')
metric_table = create_metric_table(G.graph)
start = time.time()
GraphSet.paths(s,t)
elapsed = time.time()
print(elapsed - start)

# for i,path in enumerate(GraphSet.paths(s, t).min_iter(metric_table)):
#     G.draw(subgraph=path, edge_labels=metric_table)
#     if i == 0: break
 def setup(self):
     GraphSet.set_universe(self.edgelist)
Exemplo n.º 35
0
#!/usr/bin/env python
# coding: UTF-8
from graphillion import GraphSet
import networkx as nx
import matplotlib.pyplot as plt
import csv
import time
# started = time.time()


# print "arr=%s" % (arr)

if __name__ == '__main__':

	getcycle = []
	with open('circle.csv', 'r') as f:
		reader = csv.reader(f)

		for row in reader:
			getcycle.append((row[0],row[1]))


	GraphSet.set_universe(getcycle)
	gd = nx.Graph(list(getcycle))
	nx.draw(gd)
	plt.show()

# elapsed_time = time.time() - started
# print("elapsed_time:{0}".format(elapsed_time))
Exemplo n.º 36
0
 def GetLocalConstraintsForLeaveClusters(self, file_prefix):
     if_vtree_filename = "%s/%s_if_vtree.vtree" % (file_prefix, self.name)
     if_sdd_filename_prefix = "%s/%s_if_sdd" % (file_prefix, self.name)
     then_vtree_filename = "%s/%s_then_vtree.vtree" % (file_prefix,
                                                       self.name)
     then_sdd_filename_prefix = "%s/%s_then_sdd" % (file_prefix, self.name)
     ifs = []
     thens = []
     if_variable_mapping = {}
     if_sdd_index = 0
     if_sdd_index += 1
     if_variable_mapping[
         "c%s" %
         self.name] = if_sdd_index  # cluster indicator for current cluster
     for external_edge in self.external_edges:
         if_sdd_index += 1
         if_variable_mapping[str(external_edge)] = if_sdd_index
     then_variable_mapping = {}
     zdd_to_sdd_index = [None]
     universe = []
     node_pair_to_edges = {}
     for internal_edge in self.internal_edges:
         if (internal_edge.x, internal_edge.y) not in node_pair_to_edges:
             universe.append((internal_edge.x, internal_edge.y))
         node_pair_to_edges.setdefault((internal_edge.x, internal_edge.y),
                                       []).append(internal_edge)
     GraphSet.set_universe(universe)
     universe = GraphSet.universe()
     then_sdd_index = 0
     for node_pair in universe:
         correponding_sdd_indexes = []
         for internal_edge in node_pair_to_edges[node_pair]:
             then_sdd_index += 1
             then_variable_mapping[str(internal_edge)] = then_sdd_index
             correponding_sdd_indexes.append(then_sdd_index)
         zdd_to_sdd_index.append(correponding_sdd_indexes)
     if_vtree, then_vtree = sdd.sdd_vtree_new(if_sdd_index,
                                              "right"), sdd.sdd_vtree_new(
                                                  then_sdd_index, "right")
     if_manager, then_manager = sdd.sdd_manager_new(
         if_vtree), sdd.sdd_manager_new(then_vtree)
     sdd.sdd_manager_auto_gc_and_minimize_off(if_manager)
     sdd.sdd_manager_auto_gc_and_minimize_off(then_manager)
     sdd.sdd_vtree_free(if_vtree)
     sdd.sdd_vtree_free(then_vtree)
     #none of the external edges are used and cluster indicator is off
     case_index = 0
     case_one_if = sdd.util.sdd_negative_term(if_manager,
                                              range(1, if_sdd_index + 1))
     case_one_then = sdd.util.sdd_negative_term(
         then_manager, range(1, then_sdd_index + 1))
     sdd.sdd_save("%s_%s" % (if_sdd_filename_prefix, case_index),
                  case_one_if)
     sdd.sdd_save("%s_%s" % (then_sdd_filename_prefix, case_index),
                  case_one_then)
     ifs.append("%s_%s" % (if_sdd_filename_prefix, case_index))
     thens.append("%s_%s" % (then_sdd_filename_prefix, case_index))
     #none of the external edges are used and cluster indicator is on
     case_index += 1
     case_two_if = sdd.util.sdd_exactly_one_among(
         if_manager, [if_variable_mapping["c%s" % self.name]],
         range(1, if_sdd_index + 1))
     paths = GraphSet()
     for (i, j) in itertools.combinations(self.nodes, 2):
         paths = paths.union(GraphSet.paths(i, j))
     case_two_then = generate_sdd_from_graphset(paths, then_manager,
                                                zdd_to_sdd_index)
     sdd.sdd_save("%s_%s" % (if_sdd_filename_prefix, case_index),
                  case_two_if)
     sdd.sdd_save("%s_%s" % (then_sdd_filename_prefix, case_index),
                  case_two_then)
     ifs.append("%s_%s" % (if_sdd_filename_prefix, case_index))
     thens.append("%s_%s" % (then_sdd_filename_prefix, case_index))
     #exactly one of the external edge is used and cluster indicator is off
     aggregated_cases = {}
     for external_edge in self.external_edges:
         aggregated_cases.setdefault(self.external_edges[external_edge],
                                     []).append(external_edge)
     for entering_node in aggregated_cases:
         case_index += 1
         cur_case_if = sdd.util.sdd_exactly_one_among(
             if_manager, [
                 if_variable_mapping[str(e)]
                 for e in aggregated_cases[entering_node]
             ], range(1, if_sdd_index + 1))
         paths = GraphSet()
         for node in self.nodes:
             if node == entering_node:
                 continue
             paths = paths.union(GraphSet.paths(entering_node, node))
         cur_case_then = generate_sdd_from_graphset(paths, then_manager,
                                                    zdd_to_sdd_index)
         # disjoin the empty path
         cur_case_then = sdd.sdd_disjoin(
             cur_case_then,
             sdd.util.sdd_negative_term(then_manager,
                                        range(1, then_sdd_index + 1)),
             then_manager)
         sdd.sdd_save("%s_%s" % (if_sdd_filename_prefix, case_index),
                      cur_case_if)
         sdd.sdd_save("%s_%s" % (then_sdd_filename_prefix, case_index),
                      cur_case_then)
         ifs.append("%s_%s" % (if_sdd_filename_prefix, case_index))
         thens.append("%s_%s" % (then_sdd_filename_prefix, case_index))
     # exactly two of the external edge is used and cluster_indicator is off
     aggregated_cases = {}
     for (i, j) in itertools.combinations(self.external_edges.keys(), 2):
         entering_points = (self.external_edges[i], self.external_edges[j])
         entering_points = (max(entering_points), min(entering_points))
         aggregated_cases.setdefault(entering_points, []).append((i, j))
     for entering_points in aggregated_cases:
         case_index += 1
         entering_edges = aggregated_cases[entering_points]
         cur_case_if = generate_exactly_two_from_tuples(
             if_manager,
             [(if_variable_mapping[str(e1)], if_variable_mapping[str(e2)])
              for (e1, e2) in entering_edges], range(1, if_sdd_index + 1))
         if entering_points[0] == entering_points[1]:
             cur_case_then = sdd.util.sdd_negative_term(
                 then_manager, range(1, then_sdd_index + 1))
         else:
             paths = GraphSet.paths(entering_points[0], entering_points[1])
             cur_case_then = generate_sdd_from_graphset(
                 paths, then_manager, zdd_to_sdd_index)
         sdd.sdd_save("%s_%s" % (if_sdd_filename_prefix, case_index),
                      cur_case_if)
         sdd.sdd_save("%s_%s" % (then_sdd_filename_prefix, case_index),
                      cur_case_then)
         ifs.append("%s_%s" % (if_sdd_filename_prefix, case_index))
         thens.append("%s_%s" % (then_sdd_filename_prefix, case_index))
     sdd.sdd_vtree_save(if_vtree_filename,
                        sdd.sdd_manager_vtree(if_manager))
     sdd.sdd_vtree_save(then_vtree_filename,
                        sdd.sdd_manager_vtree(then_manager))
     sdd.sdd_manager_free(if_manager)
     sdd.sdd_manager_free(then_manager)
     constraint = {}
     constraint["if_vtree"] = if_vtree_filename
     constraint["if"] = ifs
     constraint["if_variable_mapping"] = if_variable_mapping
     constraint["then_vtree"] = then_vtree_filename
     constraint["then"] = thens
     constraint["then_variable_mapping"] = then_variable_mapping
     return constraint
Exemplo n.º 37
0
 def setup(self):
     dl.read_edgelist(self.edgelist)
     GraphSet.set_universe(dl.append_virtual_nodes())
Exemplo n.º 38
0
#G.has_edge() を弄った.

from graphillion import GraphSet
import graphillion.tutorial as tl
import networkx as nx
from tree_univ import MakeUniverse, DrawGraph, OperationtoTrees

n = 8
[wtd_tree, wtd] = MakeUniverse().tu_wtd(n)
GraphSet.set_universe(wtd_tree)

g = [(0, 1), (0, 2), (0, 3), (1, 8), (1, 9), (8, 15), (9, 16)]
G = nx.Graph(g)

# 与えられた辺がグラフに含まれているか判別する
x = (1, 4)
print(G.has_edge(*x))  # *はアンパック

# gに含まれている辺にTrue, 含まれていない辺にFalseを付けたKey=Value をメモ帳に送る
edgedistinct = {}
for k in range(n - 1):
    edgedistinct |= {
        str(x): G.has_edge(*x)
        for x in MakeUniverse().te_wtd(8, k)[0]
    }

filepath = "test.txt"
with open(filepath, mode='w') as f:
    f.write(str(edgedistinct))

# 深さk からk+1 への辺の総数を与える
Exemplo n.º 39
0
    rowList_a.extend(rowList2)


#print rowList_b[0]

df1 = pd.DataFrame({"1before" :rowList_b,
                    "2after" : rowList_a,
                   "3weight" : 1
                   })
#print df1
df1.to_csv("music_list_all.csv",index = False,encoding='utf-8',sep = "|")


#universe製作第2
#networkxからのアプローチ
"""
ai_net = nx.Graph()

for line in range(0,len(df1)):
    temp = df1.ix[line]
    #ai_net.add_edge(temp["1before"].encode('utf-8'),temp["2after"].encode('utf-8'),weight = temp["3weight"])
    ai_net.add_edge(temp["1before"],temp["2after"],weight = temp["3weight"])

for i in ai_net.nodes():
    print i

gs.converters['to_graph'] = nx.Graph
gs.converters['to_edges'] = nx.Graph.edges
#g = nx.Graph(ai_net)
gs.set_universe(ai_net)
Exemplo n.º 40
0
from graphillion import GraphSet
import graphillion.tutorial as tl
import sys

param = sys.argv

graph = [(1, 2), (2, 3), (4, 1), (3, 6), (4, 7), (6, 9), (7, 8), (8, 9)]
parts = [[1, 4, 7], [2, 3, 6], [8, 9]]
if (len(param) >= 3):
    graph = eval(param[1])
    parts = eval(param[2])

GraphSet.set_universe(graph)


def toRoute(taplelist):
    list1 = list()
    if len(taplelist) < 2:
        return list1
    arrived = [False] * len(taplelist)
    next = None
    for i in range(len(taplelist)):
        only1_0 = True
        only1_1 = True
        for j in range(len(taplelist)):
            if i == j:
                continue
            if (taplelist[i][0] == taplelist[j][0]
                    or taplelist[i][0] == taplelist[j][1]):
                only1_0 = False
            if (taplelist[i][1] == taplelist[j][0]
Exemplo n.º 41
0
        if (G_connect[i][j] == 1):
            G_cap[i][j] = np.random.randint(10 * U_c, 100 * U_c)
        else:
            G_cap[i][j] = delta

print('Network capacity')
print(G_cap)
print('\n')

# Set setUniverse
universe = []
for i in range(0, N):
    for j in range(0, N):
        if (i < j and G_connect[i][j] == 1):
            universe.append((i, j))
GraphSet.set_universe(universe)

gc = GraphSet.connected_components(range(N))  #Graphset with connectivity
#print(gc.len())
nk = Count_nk(gc)  #the number of non-connected failure pattern
print('The number of non-connected failure pattern')
print(nk)
print('\n')

num_fp = []
for i in range(0, E + 1):
    num_fp.append(int(comb(E, i) -
                      nk[i]))  #the number of connected failure pattern

print('The number of connected failure pattern')
print(num_fp)
Exemplo n.º 42
0
 def setUp(self):
     GraphSet.set_universe(
         [e1 + (.3, ), e2 + (-.2, ), e3 + (-.2, ), e4 + (.4, )],
         traversal='bfs',
         source=1)
Exemplo n.º 43
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.º 44
0
 def setUp(self):
     GraphSet.set_universe([e1 + (.3,), e2 + (-.2,), e3 + (-.2,), e4 + (.4,)])
Exemplo n.º 45
0
 def setUp(self):
     GraphSet.set_universe([e1 + (.3,), e2 + (-.2,), e3 + (-.2,), e4 + (.4,)],
                           traversal='bfs', source=1)
Exemplo n.º 46
0
func graph とその一般化func graph_wtd があったが,前者を消して後者の名前をgraphとした.
'''










from graphillion import GraphSet
import graphillion.tutorial as tl  # チュートリアルのためのヘルパー・モジュール

'''
universe = tl.grid(8, 8)
GraphSet.set_universe(universe)
tl.draw(universe)  # ユニバースをポップアップウィンドウで表示する
'''

import networkx as nx
import matplotlib.pyplot as plt

# memo.mdの「Graphillonについて」の検証
universe = [(1, 2), (1, 4), (1, 3), (2, 5), (3, 6), (4, 5), (5, 6)]
#GraphSet.set_universe(universe)
universe = nx.Graph(list(universe))
print(universe[1])
print(list(universe[1].keys()))
Exemplo n.º 47
0
 def GetLocalConstraintsForInternalClusters(self, file_prefix):
     if_vtree_filename = "%s/%s_if_vtree.vtree" % (file_prefix, self.name)
     if_sdd_filename_prefix = "%s/%s_if_sdd" % (file_prefix, self.name)
     then_vtree_filename = "%s/%s_then_vtree.vtree" % (file_prefix,
                                                       self.name)
     then_sdd_filename_prefix = "%s/%s_then_sdd" % (file_prefix, self.name)
     ifs = []
     thens = []
     if_variable_mapping = {}
     if_sdd_index = 0
     if_sdd_index += 1
     if_variable_mapping[
         "c%s" %
         self.name] = if_sdd_index  # cluster indicator for current cluster
     for external_edge in self.external_edges:
         if_sdd_index += 1
         if_variable_mapping[str(external_edge)] = if_sdd_index
     then_variable_mapping = {}
     # variables for the child clusters
     then_sdd_index = 0
     zdd_to_sdd_index = [None]
     for child in self.children:
         then_sdd_index += 1
         then_variable_mapping["c%s" % child] = then_sdd_index
     universe = self.sub_region_edges.keys()
     GraphSet.set_universe(universe)
     universe = GraphSet.universe()
     for node_pair in universe:
         correponding_sdd_indexes = []
         for internal_edge in self.sub_region_edges[node_pair]:
             then_sdd_index += 1
             then_variable_mapping[str(internal_edge)] = then_sdd_index
             correponding_sdd_indexes.append(then_sdd_index)
         zdd_to_sdd_index.append(correponding_sdd_indexes)
     if_vtree, then_vtree = sdd.sdd_vtree_new(if_sdd_index,
                                              "right"), sdd.sdd_vtree_new(
                                                  then_sdd_index, "right")
     if_manager, then_manager = sdd.sdd_manager_new(
         if_vtree), sdd.sdd_manager_new(then_vtree)
     sdd.sdd_manager_auto_gc_and_minimize_off(if_manager)
     sdd.sdd_manager_auto_gc_and_minimize_off(then_manager)
     sdd.sdd_vtree_free(if_vtree)
     sdd.sdd_vtree_free(then_vtree)
     #none of the external edges are used and cluster indicator is off
     case_index = 0
     case_one_if = sdd.util.sdd_negative_term(if_manager,
                                              range(1, if_sdd_index + 1))
     case_one_then = sdd.util.sdd_negative_term(
         then_manager, range(1, then_sdd_index + 1))
     sdd.sdd_save("%s_%s" % (if_sdd_filename_prefix, case_index),
                  case_one_if)
     sdd.sdd_save("%s_%s" % (then_sdd_filename_prefix, case_index),
                  case_one_then)
     ifs.append("%s_%s" % (if_sdd_filename_prefix, case_index))
     thens.append("%s_%s" % (then_sdd_filename_prefix, case_index))
     #none of the external edges are used and cluster indicator is on
     case_index += 1
     case_two_if = sdd.util.sdd_exactly_one_among(
         if_manager, [if_variable_mapping["c%s" % self.name]],
         range(1, if_sdd_index + 1))
     #***Non empty path in this region map
     none_of_child = sdd.util.sdd_negative_term(
         then_manager,
         [then_variable_mapping["c%s" % child] for child in self.children])
     paths = GraphSet()
     child_names = self.children.keys()
     for c1, c2 in itertools.combinations(child_names, 2):
         paths = paths.union(GraphSet.paths(c1, c2))
     simple_path_constraint = generate_sdd_from_graphset(
         paths, then_manager, zdd_to_sdd_index)
     case_one = sdd.sdd_conjoin(simple_path_constraint, none_of_child,
                                then_manager)
     #***Empty path in the region map
     exactly_one_chlid = sdd.util.sdd_exactly_one(
         then_manager,
         [then_variable_mapping["c%s" % child] for child in self.children])
     empty_path_constraint = sdd.util.sdd_negative_term(
         then_manager, sum(zdd_to_sdd_index[1:], []))
     case_two = sdd.sdd_conjoin(empty_path_constraint, exactly_one_chlid,
                                then_manager)
     case_two_then = sdd.sdd_disjoin(case_one, case_two, then_manager)
     sdd.sdd_save("%s_%s" % (if_sdd_filename_prefix, case_index),
                  case_two_if)
     sdd.sdd_save("%s_%s" % (then_sdd_filename_prefix, case_index),
                  case_two_then)
     ifs.append("%s_%s" % (if_sdd_filename_prefix, case_index))
     thens.append("%s_%s" % (then_sdd_filename_prefix, case_index))
     #Exactly one of the external edge is used and cluster_indicator is off
     aggregated_cases = {}
     for external_edge in self.external_edges:
         aggregated_cases.setdefault(self.external_edges[external_edge],
                                     []).append(external_edge)
     for entering_node in aggregated_cases:
         case_index += 1
         cur_case_if = sdd.util.sdd_exactly_one_among(
             if_manager, [
                 if_variable_mapping[str(e)]
                 for e in aggregated_cases[entering_node]
             ], range(1, if_sdd_index + 1))
         paths = GraphSet()
         for child in self.children:
             if child == entering_node:
                 continue
             paths = paths.union(GraphSet.paths(entering_node, child))
         cur_case_then = generate_sdd_from_graphset(paths, then_manager,
                                                    zdd_to_sdd_index)
         cur_case_then = sdd.sdd_disjoin(
             cur_case_then,
             sdd.util.sdd_negative_term(then_manager, [
                 then_variable_mapping[str(e)] for e in self.internal_edges
             ]), then_manager)
         #conjoin that all the child indicator is off
         cur_case_then = sdd.sdd_conjoin(
             cur_case_then,
             sdd.util.sdd_negative_term(then_manager, [
                 then_variable_mapping["c%s" % child]
                 for child in self.children
             ]), then_manager)
         sdd.sdd_save("%s_%s" % (if_sdd_filename_prefix, case_index),
                      cur_case_if)
         sdd.sdd_save("%s_%s" % (then_sdd_filename_prefix, case_index),
                      cur_case_then)
         ifs.append("%s_%s" % (if_sdd_filename_prefix, case_index))
         thens.append("%s_%s" % (then_sdd_filename_prefix, case_index))
     #Exactly two of the external edge is used and cluster_indicator is off
     aggregated_cases = {}
     for (i, j) in itertools.combinations(self.external_edges.keys(), 2):
         entering_points = (self.external_edges[i], self.external_edges[j])
         entering_points = (max(entering_points), min(entering_points))
         aggregated_cases.setdefault(entering_points, []).append((i, j))
     for entering_points in aggregated_cases:
         case_index += 1
         entering_edges = aggregated_cases[entering_points]
         cur_case_if = generate_exactly_two_from_tuples(
             if_manager,
             [(if_variable_mapping[str(e1)], if_variable_mapping[str(e2)])
              for (e1, e2) in entering_edges], range(1, if_sdd_index + 1))
         if entering_points[0] == entering_points[1]:
             cur_case_then = sdd.util.sdd_negative_term(
                 then_manager, range(1, then_sdd_index + 1))
         else:
             paths = GraphSet.paths(entering_points[0], entering_points[1])
             cur_case_then = generate_sdd_from_graphset(
                 paths, then_manager, zdd_to_sdd_index)
             cur_case_then = sdd.sdd_conjoin(
                 cur_case_then,
                 sdd.util.sdd_negative_term(then_manager, [
                     then_variable_mapping["c%s" % child]
                     for child in self.children
                 ]), then_manager)
         sdd.sdd_save("%s_%s" % (if_sdd_filename_prefix, case_index),
                      cur_case_if)
         sdd.sdd_save("%s_%s" % (then_sdd_filename_prefix, case_index),
                      cur_case_then)
         ifs.append("%s_%s" % (if_sdd_filename_prefix, case_index))
         thens.append("%s_%s" % (then_sdd_filename_prefix, case_index))
     sdd.sdd_vtree_save(if_vtree_filename,
                        sdd.sdd_manager_vtree(if_manager))
     sdd.sdd_vtree_save(then_vtree_filename,
                        sdd.sdd_manager_vtree(then_manager))
     sdd.sdd_manager_free(if_manager)
     sdd.sdd_manager_free(then_manager)
     constraint = {}
     constraint["if_vtree"] = if_vtree_filename
     constraint["if"] = ifs
     constraint["if_variable_mapping"] = if_variable_mapping
     constraint["then_vtree"] = then_vtree_filename
     constraint["then"] = thens
     constraint["then_variable_mapping"] = then_variable_mapping
     return constraint
Exemplo n.º 48
0
for i in range(h):
    for j in range(w):
        if a[i][j] != 0:
            degs[cellId[i][j]] = 1
            if a[i][j] in clue:
                clue[a[i][j]].append(cellId[i][j])
            else:
                clue[a[i][j]] = [cellId[i][j]]
        else:
            degs[cellId[i][j]] = 2

grps = []
for _, p in clue.items():
    grps.append(p)

GraphSet.set_universe(edges)
sols = GraphSet.graphs(vertex_groups=grps,
                       degree_constraints=degs,
                       no_loop=True)

print('# of Solutions: %d' % sols.len())


def choose(gs):
    for g in gs.rand_iter():
        return g


sol = choose(sols)