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
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
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
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)
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)
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
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 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 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
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
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)
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
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
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
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
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
import itertools problem_spec_file = sys.argv[1] with open(problem_spec_file, "r") as fp: problem_spec = json.load(fp) edge_list = problem_spec["graph"] terminal_nodes = problem_spec["terminal_nodes"] non_terminal_nodes = problem_spec["non_terminal_nodes"] universe = ConvertEdgesToUniverse(edge_list) GraphSet.set_universe(universe) universe = GraphSet.universe() nodes = NodesInEdges(edge_list) terminal_path = {} non_terminal_path = {} path_cache = {} for i, j in itertools.combinations(nodes, 2): path_cache[(min(i, j), max(i, j))] = GraphSet.paths(i, j) internal_path = GraphSet() for path in path_cache.values(): internal_path = internal_path.union(path) for node in terminal_nodes: cur_path = GraphSet() for other_node in nodes: if other_node == node: continue node_key = (min(node, other_node), max(node, other_node)) cur_path = cur_path.union(path_cache[node_key]) terminal_path[node] = cur_path result = {} result["internal_path"] = DumpToStr(internal_path) for node in terminal_nodes: result["terminal_%s" % node] = DumpToStr(terminal_path[node])
def cal(start, goal): paths = GraphSet.paths(start, goal) return len(paths)
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})
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) pathsNoMidpoint = paths_no_mp.including(midpoint) #tl.draw(pathsThruMidpoint.choice()) print "number of paths through midpoint: " + str(pathsThruMidpoint.len()) print "number of paths without stopping at midpoint: " + str(pathsNoMidpoint.len()) print_edge_numbering(paths.universe(),dim[0],dim[1]) #print paths.universe() #for p in pathsThruMidpoint: # print p #dim = (dimension[0]+1,dimension[1]+1) #""" AC: SAVE ZDD TO FILE
from graphillion import GraphSet import graphillion.tutorial as tl n = 8 universe = tl.grid(n, n) GraphSet.set_universe(universe) tl.draw(universe) start = 1 goal = (n + 1)**2 paths = GraphSet.paths(start, goal) print(len(paths))
if len(parts) == 0: print("null") sys.exit() if len(parts) == 1: print(" ".join(map(str, makeLoop(parts[0])))) sys.exit() master = parts[0] del parts[0] for aaa in range(0, len(parts)): route = None min = -1 for i in range(0, len(parts)): p = parts[i] r1 = GraphSet.paths(master[len(master) - 1], p[0]) r2 = GraphSet.paths(master[len(master) - 1], p[len(p) - 1]) r1 = r1.excluding(master[0]) r2 = r2.excluding(master[0]) if (len(r1) == 0 and len(r2) == 0): continue if min == -1: if (len(r2) == 0): min = i * 2 route = r1.min_iter().next() continue if (len(r1) == 0): min = i * 2 + 1 route = r2.min_iter().next() continue t1 = r1.min_iter().next()
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
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
def max_hop(terminal): """ 2頂点間を結ぶパスの最大ホップ数を求める """ return len(next(GraphSet.paths(terminal[0], terminal[1]).max_iter()))
universe = [] PATH_LEN = 2 * STRENGTH + (len(input) - STRENGTH) # Calculate distance n-tuple(n=STRENGTH) print("path length", PATH_LEN) CANDIDATE = 5 # default = 5 LEN_INPUT = len(input) start = time.time() for num_testcase, value in enumerate(input): # set universe for num_param in range(1, value + 1): universe.append((str(num_testcase + 1), (str(num_testcase + 1) + "." + str(num_param)))) universe.append(((str(num_testcase + 1) + "." + str(num_param)), str(num_testcase + 2))) universe.append((str(num_testcase + 1), str(num_testcase + 2))) print(universe) GraphSet.set_universe(universe) paths = GraphSet.paths(str(1), str(len(input) + 1)) tuple_paths = paths.graph_size(PATH_LEN) # enumerate All n-tuples # Create first test cases test_case = [] temp = list(range(len(input))) def initial(t): for i in range(input[t - 1]): temp[t - 1] = i + 1 if(t == 1): for k in range(STRENGTH, len(input)): temp[k] = random.randint(1, input[k]) test_case.append(copy.deepcopy(temp)) # testcase # print (temp) else: initial(t - 1)
# -*- coding: utf-8 -*- from graphillion import GraphSet import graphillion.tutorial as tl n=6 m=6 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) GsSP = GsS.paths(1,goal) print len(GsS) print len(GsSP) Gss = [] GsSP = [] GsP = Guniv.paths(1,goal) GsPS = GsP.graph_size(nm) print len(GsP) print len(GsPS)
# -*- 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)
#!/usr/bin/env python # -*- coding: utf-8 -*- from graphillion import GraphSet import graphillion.tutorial as tl import sys args = sys.argv f = open(args[1], 'r') cnt = 0 universe = [] for row in f: if cnt == 0: n = int(row) else: u, v = map(int, row.split(" ")) universe.append((u, v)) cnt += 1 GraphSet.set_universe(universe) paths = GraphSet.paths(1, n) cycles = GraphSet.cycles() print "the num of paths: " + str(len(paths)) # print paths print "the num of cycles: " + str(len(cycles)) # print cycles
""" 動作確認 """ 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 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})
from graphillion import GraphSet as gs import pandas as pd df = pd.read_csv("") #ここでCSVファイルを読み込み univ = [] weight = {} for i, v in df.iterrows(): egde = (v["start"], v["end"]) univ.append(edge) weight[edge] = v["kiro"] gs.set_universe(univ) path = gs.paths("", "") #始点と終点を入力 max_path = next(path.max_iter(weight)) print(max_path)