def generate_independent_edges(graph, num_nodes, prob_edges, allow_loops=False): """ Generate an Erdos-Renyi random graph. Possible edges are added with a fixed probability. @type: graph: graph @param: graph: Graph. @type: num_nodes: number @param: num_nodes: Number of nodes. @type: prob_edges: number @param: prob_edges: Probability for adding a possible edge. @type: allow_loops: bool @param: allow_loops: If set to True, loops can be added. Defaults to False. """ # Discover if graph is directed or not directed = isinstance( graph, digraph ) # Nodes first nodes = xrange(num_nodes) graph.add_nodes(nodes) # Build a list of all possible edges edges = generate_possible_edges(nodes, directed, allow_loops) # Now do a random experiment for every edge and add it in case of success for each in edges: if random() < prob_edges: graph.add_edge(each[0], each[1])
def page_rank(self): #将图中没有出链的节点改为对所有节点有出链 for node in self.graph.nodes(): if len(self.graph.neighbors(node))==0: for node2 in self.graph.nodes(): graph.add_edge(self.graph,(node,node2)) nodes=self.graph.nodes() graph_size=len(nodes) if graph_size==0: return{} page_rank=dict.fromkeys(nodes,1.0/graph_size)#给每一个顶点赋予初始的PR值 damping_value=(1.0-self.damping_factor)/graph_size#公式中的(1-a)/N部分 flag=False for i in range(self.max_iterations): change=0 for node in nodes: rank=0 for incident_page in self.graph.neighbors(node): rank+=self.damping_factor*(page_rank[incident_page]/len(self.graph.neighbors(incident_page))) rank+=damping_value change+=abs(page_rank[node]-rank)#绝对值 page_rank[node]=rank print("This is No.%s iteration"%(i+1)) print(page_rank) if change<self.min_delta: flag=True break if flag: print("finished in %s iterations!"%node) else: print("finished out of 100 iterations!") return page_rank
def render_graph_color(graph_object,filename_str): import pydot node_list, adjacency_matrix = graph_object.labels, graph_object.adjacency_matrix if not (adjacency_matrix.shape[0] == adjacency_matrix.shape[1]): raise Exception("adjacency matrix should be square") if not (len(node_list) == adjacency_matrix.shape[0]): raise Exception("number of nodes is inconsistent with the number of available node labels") if is_directed(adjacency_matrix): graph = pydot.Dot(graph_type='digraph') else: graph = pydot.Dot(graph_type='graph') nodes_dot=[] for n in node_list: tmp = pydot.Node(n) nodes_dot.append(tmp) graph.add_node(tmp) for (i,j) in get_indices(adjacency_matrix): graph.add_edge(pydot.Edge(nodes_dot[i], nodes_dot[j], label=graph_object.property_str, labelfontcolor="#009933", fontsize="10.0", color=graph_object.edge_color)) name = "%s.png" % filename_str graph.write_png(name)
def AddNodeAndEdge(graph, nodeLst): for node in nodeLst: if not graph.has_node(node): graph.add_node(node) i = 0 while i < len(nodeLst)-1: if not graph.has_edge((nodeLst[i],nodeLst[i+1])): graph.add_edge((nodeLst[i],nodeLst[i+1])) i += 1
def co_occurence_edge(graph, window_size=2): window_start = 0 window_end = window_size while 1: window_words = tagged[window_start:window_end] if len(window_words) == 2: print window_words try: graph.add_edge((window_words[0][0], window_words[1][0])) except AdditionError, e: print 'already added %s, %s' % ((window_words[0][0], window_words[1][0])) else: break window_start += 1 window_end += 1
def render_multi_prop_graph(multi_prop_graph,filename_str): node_list, adjacency_matrix = multi_prop_graph.labels, multi_prop_graph.adjacency_matrix if not (adjacency_matrix.shape[0] == adjacency_matrix.shape[1]): raise Exception("adjacency matrix should be square") if not (len(node_list) == adjacency_matrix.shape[0]): raise Exception("number of nodes is inconsistent with the number of available node labels") if is_directed(adjacency_matrix): graph = pydot.Dot(graph_type='digraph') direction = 'forward' else: graph = pydot.Dot(graph_type='graph',compound='true',mindist='0',ranksep='0',nodesep='0') direction = 'none' nodes_dot=[] for n in node_list: tmp = pydot.Node(n) nodes_dot.append(tmp) graph.add_node(tmp) y = deepcopy(adjacency_matrix) for (i,j) in get_indices(y): if y[i][j] == 1: if y[j][i] ==1: y[j][i] =0 direction = 'none' graph.add_edge(pydot.Edge(nodes_dot[i], nodes_dot[j], label=multi_prop_graph.property_str, labelfontcolor="#009933", fontsize="10.0", dir=direction,color=multi_prop_graph.edge_colormap[node_list[i],node_list[j]])) if is_directed(adjacency_matrix) : direction = 'forward' name = "%s.png" % filename_str #graph = add_legend(graph, property_colormap) graph.write_png(name)
def drawGraphFromSM2(SM, names, outFile, Cut): graph = pydot.Dot(graph_type='graph') # THRESHOLD SM: nonZeroMean = np.mean(SM[SM.nonzero()]) if Cut: T = 5.0 * nonZeroMean else: T = 0.0; for i in range(SM.shape[0]): for j in range(SM.shape[0]): if SM[i,j] <= T: SM[i,j] = 0.0 else: SM[i,j] = 1.0 numOfConnections = sum(SM, axis = 0) #fig = plt.figure(1) #plot1 = plt.imshow(SM, origin='upper', cmap=cm.gray, interpolation='nearest') #plt.show() numOfConnections = 9*numOfConnections / max(numOfConnections) for i,f in enumerate(names): if sum(SM[i,:])>0: fillColorCurrent = "{0:d}".format(int(ceil(numOfConnections[i]))) # NOTE: SEE http://www.graphviz.org/doc/info/colors.html for color schemes node = pydot.Node(f, style="filled", fontsize="8", shape="egg", fillcolor=fillColorCurrent, colorscheme = "reds9") graph.add_node(node) for i in range(len(names)): for j in range(len(names)): if i<j: if SM[i][j] > 0: #gr.add_edge((names[i], names[j])) edge = pydot.Edge(names[i], names[j]) graph.add_edge(edge) graph.write_png(outFile)