def run_single_match(black_agent, white_agent, verbose=False): game=[] black_agent.sendCommand("clear_board") white_agent.sendCommand("clear_board") black_groups=unionfind() white_groups=unionfind() turn=0 gamestatus=-1 while gamestatus==-1: if turn==0: move = black_agent.genmove_black() if move == "resign": print("black resign") print(state_to_str(game)) return 1 white_agent.play_black(move) else: move=white_agent.genmove_white() if move=="resign": print("white resign") print(state_to_str(game)) return 0 black_agent.play_white(move) imove=raw_move_to_int(move) black_groups, white_groups=update_unionfind(imove, turn, game, black_groups, white_groups) gamestatus=winner(black_groups,white_groups) game.append(imove) if verbose: print(state_to_str(game)) turn=(turn+1)%2 sys.stdout.flush() print("gamestatus", gamestatus) print(state_to_str(game)) return gamestatus
def __init__(self, size): """ Initialize the game board and give white first turn. Also create our union find structures for win checking. """ self.size = size self.toplay = self.PLAYERS["black"] self.board = np.zeros((size, size)) self.white_groups = unionfind() self.black_groups = unionfind()
def __init__(self, gamesetting): """ Initialize the game board and give white first turn. Also create our union find structures for win checking. """ self.size = gamesetting.size #self.toplay = self.PLAYERS["white"] self.toplay = self.PLAYERS[gamesetting.P] self.board = np.zeros((gamesetting.size, gamesetting.size)) self.gamesetting = gamesetting self.white_groups = unionfind() self.black_groups = unionfind()
def __init__(self, gamesetting, keith_state=None): # Initialiserer HexState self.size = gamesetting.size if keith_state == None: self.toplay = self.PLAYERS[gamesetting.P] self.board = np.zeros((gamesetting.size, gamesetting.size)) else: keith_state = list(keith_state) self.board = np.reshape(keith_state[1:26], (5, 5)) players = {1: "white", 2: "black"} self.toplay = self.PLAYERS[players[keith_state[0]]] self.gamesetting = gamesetting self.white_groups = unionfind() self.black_groups = unionfind()
def __init__(self, size): """ Initialize the game board and give white first turn. Also create our union find structures for win checking. """ self.size = size # the number of cells in each row or column self.toplay = self.PLAYERS["white"] # the turn of player in each state self.board = np.zeros((size, size)) # board representation self.board = np.int_(self.board) self.white_groups = unionfind() # White zones self.black_groups = unionfind() # Black zones self.empty_cells = [] for y in range(self.size): for x in range(self.size): self.empty_cells.append((x, y))
def numIslands2(self, n, m, positions): ans = [] islands = unionfind() for p in map(tuple, positions): islands.add(p) for dp in (0, 1), (0, -1), (1, 0), (-1, 0): q = (p[0] + dp[0], dp[1] + dp[1]) if q in islands.parent: islands.union(p, q) ans += islands.count
def test_graph_1(): txs = [[1, 2, 3], [4, 5], [4, 6], [5, 7]] struct = unionfind(8) for tx in txs: parent = min(tx) for node in tx: struct.unite(parent, node) return struct.groups()
def con_tree1111(self, cvs, r, k): cvs.reverse() if r not in self.mw: #print(r) #print(cvs[0]) #self.Gr[cvs[0].id] self.mw[r] = self.Gr[cvs[0].id].vertex_p[r].minweight if r not in self.map: self.map[r] = {} self.mapr[r] = {} self.uf[r] = unionfind.unionfind(k * 25) for j in range(len(self.IT[r])): self.map[r][self.IT[r][j].minweight] = j for u in cvs: u = self.Gr[u.id] for v in self.Gr[u.id].getN(): v = self.Gr[v] try: v.vertex_p[r] except: continue if v.vertex_p[r].minweight < self.mw[r]: continue #Su = u.vertex_p[r].root Su = u.vertex_p[r] Su2 = self.map[r][Su.minweight] #Sv = v.vertex_p[r].root Sv = v.vertex_p[r] Sv2 = self.map[r][Sv.minweight] if not self.uf[r].issame(Su2, Sv2): if True: try: f = self.uf[r].find(Su2) Su = self.mapr[r][f] except: pass try: f = self.uf[r].find(Sv2) Sv = self.mapr[r][f] except: pass self.uf[r].unite(Su2, Sv2) Su.childs.append(Sv) Sv.parent = Su f = self.uf[r].find(Sv2) self.mapr[r][f] = Su #print("ebala paidi", Sv, 'sto ', Su) self.mw[r] = u.vertex_p[r].minweight
def kruskal(x,y,d,V,E): u = unionfind.unionfind(N+M) tmp_d=np.sort(d) x=x[np.argsort(d)] y=y[np.argsort(d)] res=0 for i in range(E): e=tmp_d[i] if (u.issame(x[i], y[i]+N)==False): u.unite(x[i], y[i]+N) res+=e return res
def kruskal(G): uf = unionfind(num_nodes) tot_cost, MST = 0, [] for each_edge in G: cost, to_node, from_node = each_edge[0], each_edge[1], each_edge[2] if not uf.issame(from_node - 1, to_node - 1): tot_cost += cost uf.unite(from_node - 1, to_node - 1) MST.extend([from_node, to_node]) return MST, tot_cost
def play_one_batch_games(self, sess, otherSess, thisLogit, otherLogit, data_node, batch_game_size, batch_reward): this_win_count=0 other_win_count=0 this_player=random.randint(0,1) other_player=1-this_player games=[] for ind in range(batch_game_size): self.board_tensor.fill(0) make_empty_board_tensor(self.board_tensor) currentplayer = 0 gamestatus = -1 black_group = unionfind() white_group = unionfind() count = 0 moves=[] while (gamestatus == -1): if (currentplayer == this_player): logit = sess.run(thisLogit, feed_dict={data_node: self.board_tensor}) else: logit = otherSess.run(otherLogit, feed_dict={data_node: self.board_tensor}) action = softmax_selection(logit, moves) update_tensor(self.board_tensor, currentplayer, action) black_group, white_group = update_unionfind(action, currentplayer, moves, black_group, white_group) currentplayer = other_player if currentplayer == this_player else this_player gamestatus = winner(black_group, white_group) moves.append(action) count += 1 #print(count, "action ", action) if(gamestatus==this_player): this_win_count += 1 else: other_win_count += 1 #print("steps ", count, "gamestatus ", gamestatus) R = 1.0/count if gamestatus == this_player else -1.0/count games.append([-1]+moves) #first hypothesisted action is -1 batch_reward[ind]=R print("this player win: ", this_win_count, "other player win: ", other_win_count) return (games, this_win_count, other_win_count)
def find_lines_poly(word_bb, im=None): """ Given the 2x4XN matrix of BB coordinates, merges the boxes into lines. """ if np.size(word_bb) == 0: return [], [] edge_thresh = 3.0 height_factor = 0.50 def f_dist(bb1, bb2): """ L2 distance b/w the center-point on the right-edge of BB1 to the center-point on the left-edge of BB2. """ bb1 = np.reshape(bb1, [2, 4]) bb2 = np.reshape(bb2, [2, 4]) o1, h1, w1, x1, y1 = bb_vitals(bb1) o2, h2, w2, x2, y2 = bb_vitals(bb2) min_h = min(h1, h2) # distance b/w the right-edge and the left-edge: p_bb1 = o1 + x1 * w1 + y1 * h1 / 2.0 p_bb2 = o2 + y2 * h2 / 2.0 d = point_axis_distance(p_bb1, x1, y1, p_bb2, edge_thresh * min_h, height_factor * min_h) edge_close = (d <= 1.0) return np.float(edge_close) # get all-pairs distances b/w the boxes: word_bb_flat = np.reshape(word_bb, [8, -1]) dists = ssd.cdist(word_bb_flat.T, word_bb_flat.T, f_dist) # create groups: n_bb = word_bb.shape[-1] U = unionfind(n_bb) for i in xrange(n_bb): for j in xrange(n_bb): if i == j: continue if dists[i, j] > 0: U.unite(i, j) # get the lines: lines = U.groups() # get the combined coordinates: line_rects = [] for l in lines: line_box_pts = word_bb[:, :, l] line_box_pts = np.reshape(line_box_pts, [2, -1]).T line_rects.append(find_rotated_rect(line_box_pts)) line_rects = np.transpose(np.array(line_rects), [1, 2, 0]) return line_rects, lines
def findSets(rtadj, n): groups = uf.unionfind(n) for i in range(len(rtadj)): if len(rtadj[i]) == 1: for j, edge in enumerate(rtadj): if rtadj[i] in edge: groups.unite(i, j) elif len(rtadj[i]) == 2: for j, edge in enumerate(rtadj): if rtadj[i][0] in edge or rtadj[i][1] in edge: groups.unite(i, j) return groups
def __init__(self, file, adjs=False, comps=False): self.wkeys = {} self.kwords = {} self.adjs = adjs self.comps = comps if (comps): self._uf = unionfind() self.edges = 0 self.vertices = 0 with open(file) as fin: for line in fin: self.addword(line.strip()) self.vertices += 1 if self.adjs: self.buildadjs() if self.comps: self.comps = self._uf.getsets()
def generate_maze(length, width): #generate edges edges = hf.generate_edges(length, width) #generate maze maze = hf.generate_blank_maze(length, width) sets = unionfind.unionfind(len(edges)) #shuffle edges random.shuffle(edges) while (edges): currentEdge = edges[-1] #get last element in list endRow, endCol = currentEdge['endLocation'] direction = currentEdge['direction'] prevRow, prevCol = { 'left': (endRow, endCol - 1), 'right': (endRow, endCol + 1), 'up': (endRow - 1, endCol), 'down': (endRow + 1, endCol) }[direction] #get unique number identifier for endRow,endCol end = hf.convert_to_number(endRow, endCol, width) #get unique number identifier for prevRow,prevCol prev = hf.convert_to_number(prevRow, prevCol, width) #if end and prev are not in same set, then remove wall between them and join set if not sets.issame(end, prev): #if direction is right #set prevlocation right to 1,endlocation left to 1 if direction == 'right': maze[endRow][endCol]['right'] = 1 maze[prevRow][prevCol]['left'] = 1 if direction == 'left': maze[endRow][endCol]['left'] = 1 maze[prevRow][prevCol]['right'] = 1 if direction == 'up': maze[endRow][endCol]['up'] = 1 maze[prevRow][prevCol]['down'] = 1 if direction == 'down': maze[endRow][endCol]['down'] = 1 maze[prevRow][prevCol]['up'] = 1 sets.unite(prev, end) #if in same set, remove edge from list else: edges.pop() maze[0][0]['up'] = 1 maze[length - 1][width - 1]['right'] = 1 hf.generate_image(maze, length, width)
def clusterPixels(pixels, mask, thresh): pixelMap = {tuple(pixels[i]) : i for i in range(len(pixels))} u = unionfind(len(pixels)) for i in range(mask.shape[0] - thresh): for j in range(mask.shape[1] - thresh): group = np.transpose(np.where(mask[i:i+thresh, j:j+thresh])) for k in range(len(group)): for l in range(k): try: u.unite(pixelMap[tuple(np.array([i,j]) + group[k])], pixelMap[tuple(np.array([i,j]) + group[l])]) except: pdb.set_trace() groups = u.groups() clusters = [[pixels[i,:] for i in group] for group in groups] return clusters
def kruskals(self): minS = [] vertices = self.adjacencyList.keys() uf = unionfind(len(vertices)) edges = [] for vertex in vertices: for (d, c) in self.adjacencyList[vertex]: edges.append((vertex, d, c)) edges = sorted(edges, key=lambda item: item[2]) for (s, d, c) in edges: sIndex = vertices.index(s) dIndex = vertices.index(d) if uf.find(sIndex) != uf.find(dIndex): uf.unite(sIndex, dIndex) minS.append((s, d, c)) return minS
def test(N, K, T, X, Y): ans = 0 u = unionfind.unionfind(3 * N) for i in range(K): t = T[i] x = X[i] - 1 y = Y[i] - 1 if t == 1: if (u.issame(x, y + N) or u.issame(x, y + N)) == True: ans += 1 else: u.unite(x, y) u.unite(x + N, y + N) u.unite(x + N * 2, y + N * 2) elif t == 2: if (u.issame(x, y) or u.issame(x, y + 2 * N)) == True: ans += 1 else: u.unite(x, y + N) u.unite(x + N, y + 2 * N) u.unite(x + N * 2, y) print(ans)
def product_clustering(list_pages_tot, values, sources, targets, global_matrix, day_selected): #compute each subgraphs ------------------------------------------------------------------- total_flow = sum(values) u = unionfind(len(list_pages_tot)) for i in range(0, len(sources)): u.unite(sources[i], targets[i]) subgraphs = u.groups() number_of_subgraphs = len(subgraphs) print(number_of_subgraphs) global list_subsources list_subsources = [] list_subvalues = [] list_subtargets = [] for graph in subgraphs: sub_sources = [] sub_values = [] sub_targets = [] for j in range(0, len(sources)): source = sources[j] if source in graph: sub_sources.append(source) sub_targets.append(targets[j]) sub_values.append(values[j]) list_subsources.append(sub_sources) list_subvalues.append(sub_values) list_subtargets.append(sub_targets) # data_traces = [0 for i in range(len(list_subsources))] value_share = [0 for i in range(len(list_subsources))] for i in range(0, len(list_subsources)): if list_subsources[i] != []: z = list_subvalues[i] value_share[i] = ((sum(z) * 1.0) / total_flow) * 100 #end of computation of the subgraphs : now working on the UI --------------------------------------- list_of_affinity_matrix = [[] for i in range(len(list_subsources))] sublists_pages = [[] for i in range(len(list_subsources))] list_of_links = [[] for i in range(len(list_subsources))] ###### define the function which creates one tab for each subgraph ############# def multiple_tabs(number, list_subsources=list_subsources): res = [] sublists_pages = [[] for i in range(len(list_subsources))] list_of_affinity_matrix = [[] for i in range(len(list_subsources))] for n in range(0, number): if value_share[n] >= 2: subgraph = (subgraphs[n], list_subsources[n], list_subtargets[n], list_subvalues[n]) list_pages = [list_pages_tot[x] for x in subgraph[0]] sublists_pages[n] = list_pages src = [ list_pages.index(list_pages_tot[x]) for x in subgraph[1] ] tar = [ list_pages.index(list_pages_tot[x]) for x in subgraph[2] ] list_of_links[n] = [(list_pages[src[j]], list_pages[tar[j]]) for j in range(len(src))] values = subgraph[3] list_of_affinity_matrix[n] = generate_sub_matrix( global_matrix, subgraph[0]) data_trace = dict(type='sankey', orientation="h", valueformat=".0f", valuesuffix=" logs", node=dict(pad=15, thickness=12, line=dict(color="black", width=0.5), label=list_pages), link=dict(source=src, target=tar, value=values, label=["" for x in values])) layout = dict( title= "Dynamique du traffic pertinent sur le site credit-agricole.fr le " + str(day_selected) + " - subgraph numéro " + str(i) + '<br>' + 'Proportion du traffic total : ' + str(value_share[n]) + '%', font=dict(size=10), width=1800, height=800) res.append( dcc.Tab( label='Sous-graphe numéro ' + str(n), children=[ dcc.Graph(id='Sankey' + str(n), figure={ 'data': [data_trace], 'layout': layout }), html.Div( [ html.Span("Slide to change cluster number", style={ "text-align": "center", 'padding': 10 }, className='row'), dcc.Slider(id='cluster-slider-' + str(n), min=2, max=len(list_pages), value=len(list_pages), marks={ str(i): str(i) for i in range( 2, len(list_pages) + 1, 2) }, step=None) ], style={ "display": "block", "margin-left": "auto", "margin-right": "auto", "width": "70%", "padding": 20 }) ])) return (res, sublists_pages, list_of_affinity_matrix) res, sublists_pages, list_of_affinity_matrix = multiple_tabs( len(list_subsources)) list_of_subgraph_indexes = [] for i in range(0, len(value_share)): if value_share[i] > 2: list_of_subgraph_indexes.append(i) INTERMEDIATE_RESULTS = [ sublists_pages, list_of_affinity_matrix, list_of_links, list_subsources, value_share, list_of_subgraph_indexes ] return res, json.dumps(INTERMEDIATE_RESULTS)
def enumic(self, keys, cvs): tt = time.time() #print("ENUM IC") #print(keys) #print(cvs) v2key = unionfind.unionfind(len(cvs)) sumtime = 0 ch = {} gp = {} map = {} mapk = {} IC = {} for i in range(len(cvs)): map[cvs[i].id] = i #print(map) p = len(cvs) - 1 #print(v2key.groups()) for u in reversed(keys): #print(u) ch[u.id] = set() gp[u.id] = set() while u.id != cvs[p].id: gp[u.id].add(cvs[p]) #print("prosthesa ", cvs[p].id) v2key.unite(map[u.id], map[cvs[p].id]) p += -1 gp[u.id].add(cvs[p]) #print("prosthesa ", cvs[p].id) p += -1 #print("DESOLE") for v in gp[u.id]: for w in v.getN(): #print(w, "aniki se ", u.id, v2key.issame(map[u.id], map[w])) if not v2key.issame(map[u.id], map[w]): v2key.unite(map[u.id], map[w]) temp = v2key.find(map[w]) ch[u.id].add(mapk[temp]) #ch[u.id].add(ch[w]) #print("ENOSA TA", u.id, w) #print(ch[u.id], '********///**********') mapk[v2key.find(map[u.id])] = u.id #print(v2key.parent) #print(ch) # print("new map", mapk) tttt = time.time() IC[u.id] = gp[u.id] for a in ch[u.id]: for x in IC[a]: IC[u.id].add(x) sumtime += time.time() - tttt #print("TIME TO ADD ", sumtime) #print(v2key.groups()) #print(IC) #print("ENUM TIME ", time.time() - tt) re = [ y for x, y in sorted( IC.items(), key=lambda kv: int(kv[0]), reverse=True) ] return re return IC.values()
print("Modularity of Girvan-Newman algorithm = %f" % girvanNewmanCommunity.q, "\n\n\n") mstTree = Graph.spanning_tree(inputGraph, weights=inputGraph.es['weight'], return_tree=True) plot(mstTree, "spanningTreeByPrim.png", **visual_style) mst = inputGraph.copy() mst.delete_edges(mst.es()) """ Running kruskal's algorithm """ priotrityQWeights = queue.PriorityQueue() unionDS = unionfind(inputGraph.vcount()) alreadyUsedEdges = [] for edge in inputGraph.es(): #print(type(edge)) weight = edge["weight"] priotrityQWeights.put(weight) #print(edge.tuple, "-------", edge['weight']) while not priotrityQWeights.empty(): weight = priotrityQWeights.get() #print(priotrityQWeights.qsize()) for e in inputGraph.es(): if (e['weight'] == weight and e not in alreadyUsedEdges): edge = e
def connectSets(adj, rtadj): InNodes = list(chain.from_iterable(rtadj)) # which nodes are involved? #find disjoint sets: union = uf.unionfind(10) for i in range(len(rtadj)): if len(rtadj[i]) == 1: for j, edge in enumerate(rtadj): if rtadj[i] in edge: union.unite(i, j) elif len(rtadj[i]) == 2: for j, edge in enumerate(rtadj): if rtadj[i][0] in edge or rtadj[i][1] in edge: union.unite(i, j) #gather pendants: pendants = [index for index, i in enumerate(rtadj) if len(i) == 1] #determine which sets the pendants appear in: groups = union.groups() PunionLoc = [] for i in range(len(pendants)): for index, j in enumerate(groups): if pendants[i] in j: PunionLoc += [index] #isolate deg 1 node in pendant from set containing pendant freeNodes = [] freeNeighbors = [] for i in pendants: freenode = 0 #freeNeighbor = 0 for index, j in enumerate(groups): if index in PunionLoc: for k in j: if adj[rtadj[i][0]][0] in adj[k] and i != k: freenode = adj[rtadj[i][0]][1] freeNeighbors += [adj[k]] break elif adj[rtadj[i][0]][1] in adj[k] and i != k: freenode = adj[rtadj[i][0]][0] freeNeighbors += [adj[k]] break freeNodes += [freenode] # gather possible edges from query nodes in independent sets: PosEdges = [] PosEdgeInd = [] for i in freeNodes: for index, g in enumerate(groups): if index not in PunionLoc: for p in g: Possible1 = [i, adj[p][0]] Possible2 = [i, adj[p][1]] if Possible1 not in PosEdges: PosEdges += [Possible1] PosEdgeInd += [p] elif Possible2 not in PosEdges: PosEdges += [Possible2] PosEdgeInd += [p] # for possible edges: find one in adj not in rtadj, and return its index. found = 0 newEdgeIndex = 0 for i in PosEdges: for ind, newEdge in enumerate(adj): #print(i, newEdge) if (i[0] in newEdge and i[1] in newEdge) and (ind not in InNodes) and ( freeNodes[0] in newEdge) != (freeNodes[1] in newEdge): found = 1 newEdgeIndex = ind break if found == 1: break # find the connecting node in newEdge not in freeNodes: connNodeInd = 0 midConnNode = 0 for ind, node in enumerate(newEdge): for i in freeNodes: if node not in adj[i]: connNodeInd = ind midConnNode = node break #find the edge in pendants to connect to intermediate new edge: # connect new Edge node to that pendant. for i in pendants: if midConnNode in adj[rtadj[i][0]]: connNode = rtadj[i][0] rtadj[i] += [newEdgeIndex] break #need to find edges to delete and to connect. #connect up midConnNode to disconnected set: #connect new edge to rtadj: node2Del = 0 for ind, g in enumerate(groups): if ind not in PunionLoc: for n in g: if midConnNode in adj[n]: #connCandidates += rtadj[n] delete = np.random.randint(1) node2Del = rtadj[n].pop(delete) rtadj[n] += [newEdgeIndex] for i in rtadj: if node2Del in i: i.remove(node2Del) return rtadj
def union_find(lis, n): u = unionfind.unionfind(n + 1) for pair in lis: u.unite(pair[0], pair[1]) #print "finish" return u.sizes(), u
def find_blocks_poly(line_bb, line_word_inds, im=None): """ Given a tensor of 2x4xN rotated rectangles of lines, groups the lines together that "touch". LINE_WORD_INDS: indices of the words, which form the lines. """ if np.size(line_bb) == 0: return [], [], [] def extend_bb(bb, up=True, f_h=2.0): """ extend the bounding-box, making the height bigger: """ o, h, w, x, y = bb_vitals(bb) c = np.mean(bb, axis=1) if up: f_u, f_d = f_h, 0.5 else: f_u, f_d = 0.5, f_h v = [ c - w / 2 * x - f_u * h * y, c + w / 2 * x - f_u * h * y, c + w / 2 * x + f_d * h * y, c - w / 2 * x + f_d * h * y ] return np.array(v).T def should_merge(bb1, bb2, area_intersection_thresh=0.30): """ Given two line BBs, determine, if they should be merged or not. """ c1, c2 = np.mean(bb1, axis=1), np.mean(bb2, axis=1) # make BB1 to be at the "top": if c1[1] > c2[1]: t = bb1 bb1 = bb2 bb2 = t # extend the boxes in the appropriate directions: bb1_ex, bb2_ex = extend_bb(bb1, up=False), extend_bb(bb2, up=True) bb1_p, bb2_p = sgm.Polygon(bb1_ex.T), sgm.Polygon(bb2_ex.T) # get the maximum area of the line: max_a = max(sgm.Polygon(bb1.T).area, sgm.Polygon(bb2.T).area) # get the area of intersection: int_a = bb1_p.intersection(bb2_p).area return np.float(int_a / (max_a + 0.0) >= area_intersection_thresh) n_bb = line_bb.shape[-1] U = unionfind(n_bb) for i in xrange(n_bb): for j in xrange(n_bb): if i == j: continue if should_merge(line_bb[:, :, i], line_bb[:, :, j], area_intersection_thresh=0.7): U.unite(i, j) # get the lines: blocks = U.groups() # get the combined coordinates: block_rects = [] block_word_inds = [] block_line_inds = [] for b in blocks: block_pts = line_bb[:, :, b] block_pts = np.reshape(block_pts, [2, -1]).T block_rects.append(find_rotated_rect(block_pts)) block_line_inds.append(b) b_ind = [] for ib in b: b_ind += line_word_inds[ib] block_word_inds.append(b_ind) block_rects = np.transpose(np.array(block_rects), [1, 2, 0]) return block_rects, block_word_inds, block_line_inds
def __construct_tree(self): map = [] mapr = [] for i in self.__IT: self.uf.append(unionfind.unionfind(len(i))) map.append({}) mapr.append({}) #print(self.uf) for i in range(len(self.__IT)): for j in range(len(self.__IT[i])): #print(j.minweight) map[i][self.__IT[i][j].minweight] = j #print(map) total = 0 maxc = 0 start_time = time.time() seen = [] for i in range(self.__max_core_num): seen.append(set()) for u_name, u in sorted(self.__g.items(), key=lambda kv: kv[1].weight, reverse=True): if int(u.id) % 1000 == 0: #print("Step ", u.id, u.degree, u.c) #print(total) total = 0 for i in range(u.c): Su = u.vertex_p[i] if Su not in seen[i]: self.__top_com[i].append(Su) seen[i].add(Su) for v_name in u.neighbours: if self.__g[v_name].weight <= u.weight: continue v = self.__g[v_name] for i in range(min(self.__g[v_name].c, u.c)): #startt = time.time() Su = u.vertex_p[i] Su2 = map[i][Su.minweight] #u.vertex_p[i].root = Su Sv = v.vertex_p[i] Sv2 = map[i][Sv.minweight] #v.vertex_p[i].root = Sv #total+= time.time() - startt #print("==", i) #print(Su, u) #print(Sv, v) #print(self.uf[i].issame(Su2, Sv2)) if not self.uf[i].issame(Su2, Sv2): try: f = self.uf[i].find(Su2) Su = mapr[i][f] except: pass try: f = self.uf[i].find(Sv2) Sv = mapr[i][f] except: pass self.uf[i].unite(Su2, Sv2) if Su.minweight < Sv.minweight: #print("kitso des me1") Su.childs.append(Sv) Sv.parent = Su f = self.uf[i].find(Sv2) mapr[i][f] = Su #print("ebala paidi", Sv, 'sto ', Su) if len(Sv.childs) == 0: self.__leafs[i].add(Sv) if Su in self.__leafs[i]: self.__leafs[i].remove(Su) else: #print("kitso des me2") Sv.childs.append(Su) Su.parent = Sv f = self.uf[i].find(Su2) mapr[i][f] = Sv #print("ebala paidi", Su, 'sto ', Sv) if len(Su.childs) == 0: self.__leafs[i].add(Su) if Sv in self.__leafs[i]: self.__leafs[i].remove(Sv) for i in range(len(self.__leafs)): self.__leafs[i] = sorted(self.__leafs[i], reverse=True) print("DONE constructing tree for icp index: ", (time.time() - start_time)) print("MAX bottom up path ", maxc)
# -*- coding: utf-8 -*- """ Created on Wed Mar 28 21:24:10 2018 @author: heyad """ import readin import unionfind graph = readin.Graph() graph.readin('cluster.txt') size = graph.size u = unionfind.unionfind(500) for i in range(size - 4): edge = graph.graph.get() v1 = edge.vertice1 v2 = edge.vertice2 u.unite(v1 - 1, v2 - 1)