def intranode_distance(): #choose a random leaf print('process the graph') elected = soma while elected.out_degree() != 0: elected = random.choice(list(tree.vertices())) #measure distance for all the resting leaves for node in tree.vertices(): if node.out_degree() == 0: distanceNode[node] = distance(name[elected], name[node]) else: distanceNode[node] = 1 #diffuse tubuline demand proportional respect the elected leaf distance tubuline.a = 2**(0.01 * distanceNode.a) cent_order.a = 1000 / (cent_order.a + 1) size = draw.prop_to_size(cent_order) #plot it to understand pos = draw.sfdp_layout(tree) draw.graph_draw(tree, pos=pos, vertex_fill_color=tubuline, vertex_size=size) draw.graph_draw(tree, pos=pos, vertex_fill_color=tubuline, vertex_text=distanceNode)
def plot_graph(G,node_color={},node_shape={},edge_width={},ax=None,name="graph",save=False): nodes = G.nodes() nN = len(nodes) index = {nodes[i]:i for i in range(nN)} #graph for plotting G0 = gt.Graph(directed=False) v_id = G0.new_vertex_property("int") #node ID v_co = G0.new_vertex_property("int") #node color if node_color == {}: color = {n:0 for n in nodes} else: color = node_color v_sh = G0.new_vertex_property("int") #node shape if node_shape == {}: shape = {n:0 for n in nodes} else: shape = node_shape vlist = [] e_w = G0.new_edge_property("float") #edge weight if edge_width == {}: width = {e:1 for e in G.edges()} else: width = edge_width for n in nodes: v = G0.add_vertex() v_id[v] = n v_co[v] = color[n] v_sh[v] = shape[n] vlist.append(v) for n,p in G.edges(): i,j = index[n],index[p] e = G0.add_edge(vlist[i],vlist[j]) e_w[e] = width[(n,p)] # G0.vertex_properties["ID"] = v_id # G0.vertex_properties["Shape"] = v_ta # G0.vertex_properties["Color"] = v_gp # G0.edge_properties["Weight"] = e_w if save: G0.save(name+".xml.gz") #plot graph pos = sfdp_layout(G0,eweight=e_w) if ax == None: graph_draw(G0,pos,output_size=(1000,1000), vertex_fill_color=v_co, vertex_shape=v_sh, vertex_size=15, edge_pen_width=e_w, bg_color=[1., 1., 1., 1.], output=name+".png" ) else: graph_draw(G0,pos,output_size=(1000,1000), vertex_fill_color=v_co, vertex_shape=v_sh, vertex_size=15, edge_pen_width=e_w, bg_color=[1., 1., 1., 1.], mplfig=ax )
def draw_similarity_graph(g): state = minimize_blockmodel_dl(g) b = state.b pos = sfdp_layout(g, eweight=g.edge_properties['sim']) graph_draw(g, pos, output_size=(1000, 1000), vertex_color=[1, 1, 1, 0], vertex_size=g.vertex_properties['freq'], edge_pen_width=1.2, vcmap=matplotlib.cm.gist_heat_r, output="word_similarity.png") state = minimize_blockmodel_dl(g) graph_draw(g, pos=pos, vertex_fill_color=b, vertex_shape=b, output="blocks_mdl.png")
def init_graph_viz(self): pos = sfdp_layout(self.g) if 'pos' in self.graph_viz_params: pos = self.graph_viz_params['pos'] self.graph_viz_params.__delitem__('pos') self.win = GraphWindow(self.g, pos, **self.graph_viz_params) self.win.connect("delete_event", Gtk.main_quit) GObject.idle_add(self.simulate) self.win.show_all()
def draw_game_flow(self, model: GameModel): self.log.debug('drawing game flow for model {0}'.format(model.name)) TMPUTILS.clear_container(self.game_flow_panel) all_phases = [ phase for pt in [model.table_type] + model.player_types for phase in pt.phases ] phase_phase = {} for phase in all_phases: phase_phase[phase] = list(TMPUTILS.end_phases(phase)) graph = Graph() graph.vp.name = graph.new_vertex_property('string') graph.vp.color = graph.new_vertex_property('string') graph.vp.text_pos = graph.new_vertex_property('float') graph.vp.text_off = graph.new_vertex_property('vector<float>') phase_vertex = {} for phase in all_phases: vertex = graph.add_vertex() phase_vertex[phase] = vertex text = phase.name graph.vp.name[vertex] = text if phase is model.start_phase: color = self.config.start_game_color() elif phase is model.end_phase: color = self.config.end_game_color() elif phase in model.table_type.phases: color = self.config.table_color() else: number = model.player_types.index( model.get_player_type_for_phase(phase)) color = self.config.player_color(number) graph.vp.color[vertex] = color graph.vp.text_pos[vertex] = 0 graph.vp.text_off[vertex] = [0, 0] for phase in all_phases: for other in phase_phase[phase]: graph.add_edge(phase_vertex[phase], phase_vertex[other]) pos = sfdp_layout(graph) vprops = { 'text': graph.vp.name, 'fill_color': graph.vp.color, 'text_position': graph.vp.text_pos, 'text_offset': graph.vp.text_off } graph_widget = GraphWidget(graph, pos, vprops=vprops, vertex_size=50) self.game_flow_panel.pack_start(Gtk.Label('gameflow'), False, False, 0) self.game_flow_panel.pack_start(graph_widget, True, True, 0) self.show_all()
def create_graph_visualizations(self, dur='week'): gc = Graph_Creator(dur) d = 'weekly' if dur == 'day': d = 'daily' graphs = gc.create_culumative_graphs() sorted_dates = sorted(graphs.iterkeys()) for i, date in enumerate(sorted_dates): pos = gtdraw.sfdp_layout(graphs[date]) gtdraw.graph_draw(graphs[date], pos=pos, output=project_folder + 'outputs/' + d + '/' + str(i) + '.png')
def plot_graph(self, fname, g=None, size=1000, fsize=16, vsize=8, ptype="pdf", method='arf'): """ plot the grap (needs more tuning options :Parameter: - fname : filename (will write filename.pdf) - size : outputsize will be (size, size) in px [default 800] - fsize : font size [default 10] - method : placement method to draw graph, can be one of arf frucht radtree sfdp random """ if g: draw_g = g else: draw_g = self.molg import graph_tool.draw import graph_tool.draw as gt g = draw_g if method == 'arf': pos = graph_tool.draw.arf_layout(draw_g, max_iter=0) elif method == 'frucht': pos = graph_tool.draw.fruchterman_reingold_layout(draw_g, n_iter=1000) elif method == 'radtree': pos = gt.radial_tree_layout(g, g.vertex(0)) elif method == 'sfdp': pos = gt.sfdp_layout(g) elif method == 'sfdp': pos = gt.random_layout(g) else: pos = None from graph_tool.draw import graph_draw graph_draw(draw_g,pos=pos, vertex_text=draw_g.vp.type, vertex_font_size=fsize, vertex_size=vsize, \ output_size=(size, size), output=fname+"."+ptype, bg_color=[1,1,1,1]) return
def draw_clustering(graph, filename=None, pos=None, vmore=None, emore=None, show_filling=False, curved=False, cluster_index_name='cluster', osize=800): # graph.set_edge_filter(graph.ep['fake'], inverted=True) pos = pos or gtdraw.sfdp_layout(graph) vertex_options = {'pen_width': 0} vertex_options.update(add_cluster_name_and_color(graph, cluster_index_name)) name = graph.new_vertex_property('string') for i, v in enumerate(graph.vertices()): name[v] = str(i) if np.unique(graph.vp[cluster_index_name].a).size < 2: vertex_options['text'] = name if vmore: vertex_options.update(vmore) # d = count_disagreements(graph, alt_index=cluster_index_name) # if not show_filling: # graph.set_edge_filter(graph.ep['fake'], inverted=True) # print(str(d.a.sum().ravel()[0]) + ' disagreements') if not show_filling: edge_options = {'pen_width': 2} else: edge_width = graph.new_edge_property('float') for e in graph.edges(): if not graph.ep['fake'][e]: edge_width[e] = 6 else: edge_width[e] = 3 # if graph.ep['sign'][e] else 1 edge_options = {'pen_width': edge_width} edge_options.update(add_edge_sign_color(graph)) # edge_options.update(add_edge_disagreement_size(graph, d)) if emore: edge_options.update(emore) more_opts = {} if curved: from math import sqrt control = graph.new_edge_property("vector<double>") for e in graph.edges(): d = sqrt(sum((pos[e.source()].a - pos[e.target()].a) ** 2)) / 5 control[e] = [0.3, d, 0.7, .5*d] more_opts['edge_control_points'] = control gtdraw.graph_draw(graph, pos=pos, vprops=vertex_options, eprops=edge_options, output=filename, fit_view=True, output_size=(osize, int(0.7*osize)), inline=True, **more_opts)
def planted_clusters(ball_size=12, nb_balls=5, pos=False, p=0.07): new_graph() true_cluster = {} balls = [make_ball(true_cluster, ball_size) for _ in range(nb_balls-1)] filling = int(1.1*ball_size*nb_balls) - len(redensify.G) if filling > 0: balls.append(make_ball(true_cluster, filling, exact=True)) if pos: from graph_tool import draw as gtdraw redensify.EDGES_ORIG = list(redensify.EDGES_SIGN.keys()) redensify.N = len(redensify.G) k = to_graph_tool() pos = gtdraw.sfdp_layout(k).get_2d_array([0, 1]) for b1, b2 in combinations(balls, 2): link_balls(b1, b2) flip_random_edges(p) finalize_graph() return true_cluster, pos
def visualize(self, graph_view, outfile, drawing_props): g = graph_view props = self.process_drawing_properties(g, drawing_props) out = os.path.join( self.results_path, 'sfdp_' + drawing_props['props_type'] + '_' + outfile + '.' + props['fmt']) os.makedirs(os.path.dirname(out), exist_ok=True) pos = sfdp_layout(g) try: if len(list(g.vertices())) > 0: graph_draw(g, pos, vprops=props['vprops'], eprops=props['eprops'], output_size=(props['output_width'], props['output_height']), output=out) except Exception as e: print(e)
def build_model(vkapi: vk.API, user_for_analyse: dict): friend_list, friend_links = __prepare_data(vkapi, user_for_analyse) graph = Graph(directed=False) vmap = graph.add_edge_list(friend_links.values, hashed=True) state = minimize_blockmodel_dl(graph) layout = sfdp_layout(graph, groups=state.b) state.draw(pos=layout, vertex_text=vmap, vertex_font_size=3, vertex_size=3, vertex_color=[128, 128, 128, 1], output_size=(2000, 2000), output="graph.svg") with open("graph.svg", 'r') as source: graph_image = source.read() os.remove("graph.svg") return graph_image
def plot(self, output_file_with_extension: Optional[str] = None): """ To return a graph image :param output_file_with_extension: the output file name with extension :return: str """ self._logger.info("Graph to image") pos = sfdp_layout(self) graph_draw( self, pos=pos, vertex_shape="circle", vertex_size=3, vertex_anchor=0, vertex_color="white", vertex_fill_color=(0, 0, 0, 1), # normalized values vertex_pen_width=1, edge_color=(1, 0, 0, 1), bg_color=(0, 0, 0, 1), output_size=[1024, 1024], output=output_file_with_extension, )
def plotg(g, layout='sfdp', pos=True): gg = lg2gt(g) if not pos: if layout == 'fr': pos = gtd.fruchterman_reingold_layout(gg) else: pos = gtd.sfdp_layout(gg) else: pos = gg.new_vertex_property("vector<double>") n = gg.num_vertices() s = 2.0 * np.pi / n for v in range(gg.num_vertices()): idx = int(gg.vertex_properties['label'][gg.vertex(v)]) - 1 pos[gg.vertex(v)] = (n * np.cos(s * idx), n * np.sin(s * idx)) gtd.graph_draw(gg, pos, vertex_text=gg.vertex_properties['label'], vertex_font_size=32, edge_pen_width=1, edge_marker_size=15, vertex_pen_width=1, vertex_fill_color=[0.62109375, 0.875, 0.23828125, 1])
def step_layout(self, dt): sfdp_layout(self.G, pos=self.G.vp.pos, pin=self.G.vp.pinned, **SFDP_SETTINGS)
def main(): options = parse_arguments() clusters_enabled = options["mapping_location"] is not None if options["should_merge"] and not clusters_enabled: raise "You need to provide a mapping to use merged view.`" # Get the string containing the input matrix form a file/pipe if options["matrix_location"] is not None: with open(options["matrix_location"], 'r') as file: matrix_string = file.read().strip().split("\n") else: matrix_string = sys.stdin # Parse the input matrix string height, width, matrix = parse_matrix(matrix_string, options["has_size"]) # Get the string containing the mapping if specified if clusters_enabled: with open(options["mapping_location"], 'r') as file: mapping_string = file.read().strip() mapping = parse_mapping(mapping_string, options["has_size"]) else: mapping = None if options["should_merge"]: height, width, matrix, mapping = merge_clusters(matrix, mapping) graph = Graph() graph.add_vertex(height + width) shape = graph.new_vertex_property("string") color = graph.new_vertex_property("string") index = graph.new_vertex_property("string") for i in range(height): v = graph.vertex(i) shape[v] = "square" color[v] = "red" index[v] = str(i) for i in range(width): v = graph.vertex(height + i) shape[v] = "circle" if clusters_enabled: color[v] = COLORS[mapping[i] % len(COLORS)] else: color[v] = COLORS[0] index[v] = str(i) for i in range(height): for j in range(width): if abs(matrix[i][j]) < EPSILON: continue graph.add_edge(graph.vertex(i), graph.vertex(height + j)) graph.set_directed(False) if clusters_enabled: groups = graph.new_vertex_property("int") for i in range(width): v = graph.vertex(height + i) groups[v] = mapping[i] position = sfdp_layout(graph, groups=groups) else: position = None graph_draw(graph, pos=position, vertex_text=index, vertex_shape=shape, vertex_fill_color=color, vertex_pen_width=1.2, vertex_color="black", edge_pen_width=3.4, fit_view=True, bg_color=(255, 255, 255, 1), output=options["output_file"])
def draw_for(self, phase: Phase, model: GameModel): self.log.debug('drawing phase flow {0}'.format(phase.name)) TMPUTILS.clear_container(self.main_panel) top = Gtk.HBox() name = Gtk.Label(phase.name) top.pack_start(name, True, True, 0) refresh_button = Gtk.Button('Refresh') refresh_button.connect('clicked', lambda w: self.draw_for(phase, model)) top.pack_start(refresh_button, True, True, 0) self.main_panel.pack_start(top, False, False, 0) #TMPUTILS.start_rule_color = TMPUTILS.rule_color #start = phase.rules[0] #start = Rule('Początek {0}'.format(phase.name)) start = Rule('Start {0}'.format(phase.name)) start.next = phase.rules phase.rules = [start] rules_set = phase.all_rules_set() phase.rules = start.next graph = Graph() graph.vp.name = graph.new_vertex_property('string') graph.vp.fullname = graph.new_vertex_property('string') graph.vp.color = graph.new_vertex_property('string') graph.vp.shape = graph.new_vertex_property('string') graph.vp.rotation = graph.new_vertex_property('float') graph.vp.text_pos = graph.new_vertex_property('float') graph.vp.text_rotation = graph.new_vertex_property('float') graph.ep.text = graph.new_edge_property('string') graph.ep.text_color = graph.new_edge_property('string') rule_vertex = {} self.vertex_rule = {} for rule in rules_set: vertex = graph.add_vertex() rule_vertex[rule] = vertex self.vertex_rule[vertex] = rule graph.vp.name[vertex] = rule.verticle_name() graph.vp.fullname[vertex] = rule.name if rule is start: color = self.config.start_rule_color() elif issubclass(rule.__class__, ChangePhase): color = TMPUTILS.end_rule_color(rule, model) elif len([r for k, v in rule.rules_dict().items() for r in v]) == 0: color = self.config.wrong_rule_color() else: color = TMPUTILS.rule_color() graph.vp.color[vertex] = color #graph.vp.shape[vertex] = 'square' if issubclass(rule.__class__, If) else 'circle' graph.vp.shape[vertex] = self.config.rule_shape(rule) #graph.vp.rotation[vertex] = pi / 4 if issubclass(rule.__class__, If) else 0 graph.vp.rotation[vertex] = self.config.rule_rotation(rule) graph.vp.text_pos[vertex] = 0 #graph.vp.text_rotation[vertex] = - pi / 4 if issubclass(rule.__class__, If) else 0 graph.vp.text_rotation[vertex] = self.config.rule_text_rotation(rule) for rule in rules_set: for next_text, next_rule_list in rule.rules_dict().items(): for next_rule in next_rule_list: edge = graph.add_edge(rule_vertex[rule], rule_vertex[next_rule]) #as_polish = {'No': "Nie", 'Yes': "Tak"} #graph.ep.text[edge] = as_polish[next_text] if next_text in as_polish else next_text graph.ep.text[edge] = next_text graph.ep.text_color[edge] = TMPUTILS.text_color(next_text) pos = sfdp_layout(graph) vprops = { 'text': graph.vp.name, 'fill_color': graph.vp.color, 'shape': graph.vp.shape, 'rotation': graph.vp.rotation, 'text_position': graph.vp.text_pos, 'text_rotation': graph.vp.text_rotation } eprops = { 'text': graph.ep.text, 'text_color': graph.ep.text_color } self.graph_widget = GraphWidget(graph, pos, display_props=[graph.vp.fullname], vprops=vprops, eprops=eprops, vertex_size=50) #jest cos takiego jak GraphWidget.key_press_callback ale u mnie nie dziala... self.graph_widget.connect('button-release-event', self.on_vertex_clicked) self.main_panel.pack_start(self.graph_widget, True, True, 0) self.show_all()
def draw_for(self, sender, model: GameModel): self.log.debug('drawing place map for model {0}'.format(model.name)) TMPUTILS.clear_container(self.main_panel) refresh_button = Gtk.Button('Refresh') refresh_button.connect('clicked', lambda w: self.draw_for(sender, model)) self.main_panel.pack_start(refresh_button, False, False, 0) all_places = set() for player_type in model.player_types + [model.table_type]: for place in player_type.places: all_places.add(place) place_vertex = {} graph = Graph() graph.vp.name = graph.new_vertex_property('string') graph.vp.color = graph.new_vertex_property('string') graph.vp.text_pos = graph.new_vertex_property('float') graph.ep.color = graph.new_edge_property('vector<float>') for place in all_places: vertex = graph.add_vertex() place_vertex[place] = vertex graph.vp.name[vertex] = place.name graph.vp.color[vertex] = TMPUTILS.table_color( ) if place in model.table_type.places else TMPUTILS.player_color() graph.vp.text_pos[vertex] = 0 self.graph = graph self.place_vertex = place_vertex self.rule_edge = {} for phase in model.all_phases(): for source, target, rule in self.edge_info_for_phase(phase): edge = graph.add_edge(place_vertex[source], place_vertex[target]) if rule not in self.rule_edge: self.rule_edge[rule] = [] self.rule_edge[rule].append(edge) graph.ep.color[edge] = [0.179, 0.203, 0.210, 0.8] pos = sfdp_layout(graph) vprops = { 'text': graph.vp.name, 'fill_color': graph.vp.color, 'text_position': graph.vp.text_pos, } eprops = {'color': graph.ep.color} self.graph_widget = GraphWidget(graph, pos, vprops=vprops, eprops=eprops, vertex_size=50) self.main_panel.pack_start(self.graph_widget, True, True, 0) self.show_all()
def render_graph(g, path='graph/{}.pdf'): # the simplest way arg_map = dict( g = g, output = path.format('1-1-random-simplest'), ) graph_draw(**arg_map) # use constants arg_map.update(dict( output = path.format('1-2-random-constant'), output_size = (SIZE, SIZE), vertex_size = MA_V_SIZE, edge_pen_width = MA_E_PWIDTH, )) graph_draw(**arg_map) # use prop_to_size v_count_p = g.vp['count'] e_count_p = g.ep['count'] v_size_by_count_p = prop_to_size(v_count_p, MI_V_SIZE, MA_V_SIZE) e_pwidth_by_count_p = prop_to_size(e_count_p, MI_E_PWIDTH, MA_E_PWIDTH) arg_map.update(dict( output = path.format('1-3-random-size'), vertex_size = v_size_by_count_p, edge_pen_width = e_pwidth_by_count_p, )) graph_draw(**arg_map) # use fill_color debug('v_count_p.a : {}', v_count_p.a) v_color_by_count_p = prop_to_size(v_count_p, 0, 1) debug('v_color_by_count_p.a: {}', v_color_by_count_p.a) arg_map.update(dict( output = path.format('1-4-random-color'), vertex_fill_color = v_color_by_count_p, )) graph_draw(**arg_map) # use closeness v_closeness_p = g.vp['closeness'] v_color_by_closeness_p = prop_to_size(v_closeness_p, 0, 1) #closeness_arg_map = arg_map.copy() #closeness_arg_map.update(dict( # output = path.format('1-5-random-closeness'), # vertex_fill_color = v_color_by_closeness_p, #)) arg_map.update(dict( output = path.format('1-5-random-closeness'), vertex_fill_color = v_color_by_closeness_p, )) graph_draw(**arg_map) # sfdp_layout arg_map.update(dict( output = path.format('2-1-sfdp'), pos = sfdp_layout(g), )) graph_draw(**arg_map) # sfdp_layout with only edge's weight arg_map.update(dict( output = path.format('2-2-sfdp-edge-weight'), pos = sfdp_layout(g, eweight=e_count_p), )) graph_draw(**arg_map) # sfdp_layout with both edge and vertex's weight arg_map.update(dict( output = path.format('2-3-sfdp-both-weight'), pos = sfdp_layout(g, eweight=e_count_p, vweight=v_count_p), )) graph_draw(**arg_map) # fruchterman_reingold_layout arg_map.update(dict( output = path.format('3-1-fr'), pos = fruchterman_reingold_layout(g), )) graph_draw(**arg_map) # fruchterman_reingold_layout with edge's weight arg_map.update(dict( output = path.format('3-2-fp-edge-weight'), pos = fruchterman_reingold_layout(g, weight=e_count_p), )) graph_draw(**arg_map) # arf_layout arg_map.update(dict( output = path.format('4-1-arf'), pos = arf_layout(g), )) graph_draw(**arg_map) # arf_layout with edge's weight arg_map.update(dict( output = path.format('4-2-arf-edge-weight'), pos = arf_layout(g, weight=e_count_p), )) graph_draw(**arg_map)
def visualisation(g, subtree_height=2): from cc_pivot import draw_clustering import draw_utils as du from graph_tool import draw as gdraw import graph_tool as gt import numpy as np import seaborn as sns G, E = cexp.redensify.G, cexp.redensify.EDGES_SIGN root = 16 Gbfs, parents, tree = initial_spanning_tree(G, root) ecol, esize = du.color_graph(g, tree) tmap = du.map_from_list_of_edges(g, tree) g.set_edge_filter(tmap) tpos = gdraw.sfdp_layout(g) g.set_edge_filter(None) ecol, esize = du.color_graph(g, tree) g_halo = g.new_vertex_property('bool') g_halo.a[root] = True draw_clustering(g, pos=tpos, vmore={'size': 22, 'halo': g_halo}, emore={'pen_width': esize, 'color': ecol, }, osize=900) Bparent = deepcopy(parents) Bg = deepcopy(Gbfs) for u in Bg: p = Bparent[u] Bg[u].discard(p) dtree, height, strees = dfs_of_a_tree(Bg, root, Bparent, subtree_height) cols = sns.color_palette('rainbow', len(strees)) random.shuffle(cols) ecol, esize = du.color_graph(g, tree) for e in tree: ge = g.edge(*e) ecol[ge] = du.light_gray # [.25,.25,.25,.8] esize[ge] = 1.5 for st, c in zip(strees, cols): for u, v in ((u, v) for u, v in st.items() if v is not None): ge = g.edge(u, v) ecol[ge] = c esize[ge] = 3 draw_clustering(g, pos=tpos, vmore={'size': 22}, emore={'pen_width': esize, 'color': ecol}, osize=900) tree_membership = {u: i for i, st in enumerate(strees) for u in st} tree_root = [[k for k, v in t.items() if v is None][0] for t in strees] support_tree = [] for st in strees: support_tree.append({(u, v) if u < v else (v, u) for u, v in st.items() if v is not None}) within_tree, across_trees = bipartition_edges(E, strees, tree_membership, support_tree) Gt = {i: set() for i, u in enumerate(strees)} Et = {e: random.choice(list(candidates)) for e, candidates in across_trees.items()} for e, n in Et.items(): add_edge(Gt, *e) k = gt.Graph(directed=False) k.add_vertex(len(strees)) names = k.new_vertex_property('string') vcols = k.new_vertex_property('vector<double>') etext = k.new_edge_property('string') prev_pos = tpos.get_2d_array((0, 1)) new_pos = np.zeros((2, len(strees))) stpos = k.new_vertex_property('vector<double>') for i, (stree_prt, root) in enumerate(zip(strees, tree_root)): v = k.vertex(i) members = sorted(stree_prt.keys()) mpos = prev_pos[:, members] new_pos[:, i] = mpos.mean(1) stpos[v] = prev_pos[:, root] # mpos.mean(1) names[v] = str(root) vcols[v] = list(cols[i]) + [.9, ] for e, n in Et.items(): ke = k.add_edge(*e) etext[ke] = str(n) gdraw.graph_draw(k, stpos, eprops={'text': etext}, output_size=(800, 800), vprops={'pen_width': 0, 'text': names, 'fill_color': vcols, 'size': 24}) stars, _, star_membership = extract_stars(Gt) within_star, across_stars = bipartition_edges(Et, stars, star_membership) scols, ssize = k.new_edge_property('vector<double>'), k.new_edge_property('double') cols_s = sns.color_palette('Set1', len(stars)) star_halo = k.new_vertex_property('bool') star_halo.a = np.zeros(k.num_vertices()) for s in stars: star_halo[g.vertex(s.center)] = True for e in k.edges(): u, v = int(e.source()), int(e.target()) su, sv = star_membership[u], star_membership[v] if su == sv and stars[su].center in [u, v]: scols[e], ssize[e] = list(cols_s[su]) + [.9, ], 3 else: scols[e], ssize[e] = [.2, .2, .2, .8], 1 stext = k.new_edge_property('string') vs_cols = k.new_vertex_property('vector<double>') for u in k.vertices(): vs_cols[u] = list(cols_s[star_membership[int(u)]]) + [.9] for candidates in across_stars.values(): chosen = sorted(candidates)[0] ke = k.edge(*chosen) ssize[ke] = 3 stext[ke] = str(Et[chosen]) scols[ke] = du.black gdraw.graph_draw(k, stpos, vprops={'pen_width': 0, 'text': names, 'fill_color': vs_cols, 'size': 24, 'halo': star_halo}, eprops={'pen_width': ssize, 'color': scols, 'text': stext}, output_size=(800, 800))
def draw_network(network, nsize="total-degree", ncolor="group", nshape="o", nborder_color="k", nborder_width=0.5, esize=1., ecolor="k", spatial=True, size=(600, 600), dpi=75): ''' Draw a given graph/network. Parameters ---------- network : :class:`~nngt.Graph` or subclass The graph/network to plot. nsize : float, array of floats or string, optional (default: "total-degree") Size of the nodes; if a number, percentage of the canvas length, otherwize a string that correlates the size to a node attribute among "in/out/total-degree", "betweenness". ncolor : float, array of floats or string, optional (default: 0.5) Color of the nodes; if a float in [0, 1], position of the color in the current palette, otherwise a string that correlates the color to a node attribute among "in/out/total-degree", "betweenness" or "group". nshape : char or array of chars, optional (default: "o") Shape of the nodes (see `Matplotlib markers <http://matplotlib.org/api/markers_api.html?highlight=marker#module-matplotlib.markers>`_). nborder_color : char, array of char, float or array of float, optional (default: "k") Color of the node's border using predefined `Matplotlib colors <http://matplotlib.org/api/colors_api.html?highlight=color#module-matplotlib.colors>`_). or floats in [0, 1] defining the position in the palette. nborder_width : float or array of floats, optional (default: 0.5) Width of the border in percent of canvas size. esize : float or array of floats, optional (default: 0.5) Width of the edges in percent of canvas size. ecolor : char, array of char, float or array of float, optional (default: "k") Edge color. spatial : bool, optional (default: True) If True, use the neurons' positions to draw them. size : tuple of ints, optional (default: (600,600)) (width, height) tuple for the canvas size (in px). dpi : int, optional (default: 75) Resolution (dot per inch). ''' pos, layout = None, None n = network.node_nb() e = network.edge_nb() # compute properties if issubclass(str, nsize.__class__): if e: nsize = _node_size(network, nsize) nsize.a *= 0.01 * size[0] elif issubclass(float, nsize.__class__): nsize = np.repeat(nsize, n) if issubclass(str, esize.__class__): if e: esize = _edge_size(network, esize) esize.a *= 0.01 * size[0] elif issubclass(float, esize.__class__): esize = np.repeat(esize, e) esize = network.new_edge_property("double", esize) ncolor = _node_color(network, ncolor) if issubclass(float, nborder_color.__class__): nborder_color = np.repeat(nborder_color, n) if issubclass(float, ecolor.__class__): ecolor = np.repeat(ecolor, e) # draw pos = np.zeros((n, 2)) if not e: nsize = 0.02 * size[0] esize = 0.01 * size[0] if spatial and network.is_spatial(): pos = network[POS] else: pos[:, 0] = size[0] * (np.random.uniform(size=n) - 0.5) pos[:, 1] = size[1] * (np.random.uniform(size=n) - 0.5) elif spatial and network.is_spatial(): pos = network.position.T pos = network.new_vertex_property("vector<double>", pos) else: ebetw = network.betweenness_list(as_prop=True)[1] pos = gplot.sfdp_layout(network, eweight=ebetw) if not e: size_inches = (size[0] / float(dpi), size[1] / float(dpi)) fig = plt.figure(facecolor='white', figsize=size_inches, dpi=dpi) ax = fig.add_subplot(111, frameon=0, aspect=1) fig.facecolor = "white" fig.figsize = size ax.set_axis_off() if hasattr(network, "population"): for group in network.population.itervalues(): idx = group.id_list ax.scatter(pos[idx, 0], pos[idx, 1], s=nsize, color=palette(ncolor[idx[0]])) else: ax.scatter(pos[:, 0], pos[:, 1], s=nsize) ax.set_xlim([-0.51 * size[0], 0.51 * size[0]]) ax.set_ylim([-0.51 * size[1], 0.51 * size[1]]) plt.show() elif spatial and network.is_spatial(): gplot.graph_draw(network, pos=pos, vertex_color=nborder_color, vertex_fill_color=ncolor, vertex_size=nsize, edge_color=ecolor, edge_pen_width=esize, output_size=size) else: gplot.graph_draw(network, pos=pos, vertex_color=nborder_color, vertex_fill_color=ncolor, vertex_size=nsize, edge_color=ecolor, edge_pen_width=esize, output_size=size)
def _test(): import numpy as np import ClearMap.Tests.Files as tf import ClearMap.Analysis.Graphs.GraphProcessing as gp #reload(gp) skeleton = tf.source('skeleton'); #import ClearMap.Visualization.Plot3d as p3d #p3d.plot(skeleton) #reload(gp) g = gp.graph_from_skeleton(skeleton) g.vertex_coordinates() s = gp.graph_to_skeleton(g) assert np.all(s==skeleton) gc = gp.clean_graph(g, verbose=True) gr = gp.reduce_graph(gc, verbose=True) gr2 = gr.copy(); gr2.set_edge_geometry_type('edge') l = gr.edge_geometry_lengths(); print(l) g = gp.ggt.Graph(n_vertices=10); g.add_edge(np.array([[7,8],[7,9],[1,2],[2,3],[3,1],[1,4],[4,5],[2,6],[6,7]])); g.set_vertex_coordinates(np.array([[10,10,10],[0,0,0],[1,1,1],[1,1,0],[5,0,0],[8,0,1],[0,7,1],[0,10,2],[0,12,3],[3,7,7]], dtype=float)); import ClearMap.Visualization.Plot3d as p3d p3d.plot_graph_line(g) gc = gp.clean_graph(g, verbose=True); p3d.plot_graph_line(gc) gr = gp.reduce_graph(gc, edge_geometry=True, verbose=True) #gr.set_edge_geometry(0.1*np.ones(gr.edge_geometry(as_list=False).shape[0]), 'radii') import ClearMap.Visualization.Plot3d as p3d vertex_colors = np.random.rand(g.n_vertices, 4); vertex_colors[:,3] = 1; p3d.plot_graph_mesh(gr, default_radius=1, vertex_colors=vertex_colors) eg = gr.edge_geometry(as_list=False); egs = 0.5 * eg; gr.set_edge_geometry(name='coordinates', values=egs) #tracing import numpy as np import ClearMap.Visualization.Plot3d as p3d import ClearMap.Analysis.Graphs.GraphProcessing as gp g = gp.ggt.Graph(n_vertices=10); g.add_edge(np.array([[0,1],[1,2],[2,3],[3,4],[4,0],[0,5],[5,6],[6,7],[0,8],[8,9],[9,0]])); g.set_vertex_coordinates(np.array([[0,0,0],[1,0,0],[2,0,0],[2,2,0],[0,1,0],[0,0,1],[0,0,2],[0,0,3],[0,-1,0],[0,-1,-1]], dtype=float)); g.set_vertex_radii(np.array([10,6,4,6,7,4,2,2,5,5]) * 0.02) vertex_colors = np.array([g.vertex_radii()]*4).T; vertex_colors = vertex_colors / vertex_colors.max(); vertex_colors[:,3] = 1; p3d.plot_graph_mesh(g, default_radius=1, vertex_colors=vertex_colors) def condition(graph, vertex): r = graph.vertex_radii(vertex=vertex); print('condition, vertex=%d, radius=%r' % (vertex,r)) return r >= 5 * 0.02; label = np.zeros(g.n_vertices, dtype=bool); label[0] = True; traced = gp.trace_vertex_label(g, label, condition=condition, steps=1) print(traced) vertex_colors = np.array([[1,0,0,1],[1,1,1,1]])[np.asarray(traced, dtype=int)] p3d.plot_graph_mesh(g, default_radius=1, vertex_colors=vertex_colors) from importlib import reload; reload(gp) # edge tracing import ClearMap.Analysis.Graphs.GraphGt as ggt edges = [[0,1],[1,2],[2,3],[4,5],[5,6],[1,7]]; g = ggt.Graph(edges=edges) l,m = g.edge_graph(return_edge_map=True); import numpy as np label = np.zeros(len(edges), dtype=bool); label[1] = True; import ClearMap.Analysis.Graphs.GraphProcessing as gp def condition(graph, edge): print('condition, edge=%d' % (edge,)) return True; traced = gp.trace_edge_label(g, label, condition=condition); print(traced) # expansion of edge lengths import numpy as np import ClearMap.Tests.Files as tf import ClearMap.Analysis.Graphs.GraphProcessing as gp graph = gp.ggt.Graph(n_vertices=5); graph.add_edge([[0,1],[0,2],[0,3],[2,3],[2,1],[0,4]]); graph.add_edge_property('length', np.array([0,1,2,3,4,5])+2); e, m = gp.expand_graph_length(graph, 'length', True) import graph_tool.draw as gd pos = gp.ggt.vertex_property_map_to_python(gd.sfdp_layout(e.base)) import matplotlib.pyplot as plt plt.figure(1); plt.clf(); import matplotlib.collections as mc import ClearMap.Visualization.Color as col colors = np.array([col.color(c) for c in ['red', 'blue', 'green', 'black', 'purple', 'orange']]) ec = e.edge_connectivity(); lines = pos[ec]; cols = colors[m]; lc = mc.LineCollection(lines, linewidths=1, color=cols); ax = plt.gca(); ax.add_collection(lc) ax.autoscale() ax.margins(0.1) plt.scatter(pos[:,0], pos[:,1]) p =pos[:graph.n_vertices] plt.scatter(p[:,0],p[:,1], color='red')
gtg = g.return_gt_graph() g.v['deg'] = gtg.degree_property_map('total').a # how many "actors" are there per layer? g.v[g.v.deg != 0].groupby('layer').size() # In[12]: # create graph_tool graph for layout import graph_tool.draw as gtd gtg = g.return_gt_graph() gtg.set_directed(False) # get sfdp layout postitions pos = gtd.sfdp_layout(gtg, gamma=.5) pos = pos.get_2d_array([0, 1]) g.v['x'] = pos[0] g.v['y'] = pos[1] # configure nodes kwds_scatter = {'s': 1, 'c': 'k'} # configure edges kwds_quiver = {'headwidth': 1, 'alpha': .3, 'cmap': 'prism'} # color by type C = g.e.groupby('type').grouper.group_info[0]
from Orange.data import Table matplotlib.use('Agg') from graph_tool.draw import sfdp_layout, graph_draw from induce_graph import induce_graph, cutoff iris = Table('iris') graph = induce_graph(iris) graph_1 = cutoff(graph, 0.1) graph_2 = cutoff(graph, 0.2) graph_3 = cutoff(graph, 0.3) vertex_layout = sfdp_layout(graph_2) rgb_colors = ([[70, 190, 250]] * 50) + ([[237, 70, 47]] * 50) + ([[170, 242, 43]] * 50) rgb_colors = [[r / 255, g / 255, b / 255] for r, g, b in rgb_colors] colors = graph_1.new_vertex_property('vector<double>') for node, color in zip(graph_1.vertices(), rgb_colors): colors[node] = color graph_draw(graph_1, vertex_layout, vertex_fill_color=colors, output='iris_threshold_01.png', output_size=(600, 400)) graph_draw(graph_2,
''' Plot the graph ''' if nngt.get_config("with_plot"): import matplotlib.pyplot as plt colors = np.zeros(num_nodes) colors[500:] = 1 if nngt.get_config("backend") == "graph-tool": from graph_tool.draw import graph_draw, prop_to_size, sfdp_layout pm = net.new_vertex_property("int", colors) size = net.new_vertex_property("double", val=5.) pos = sfdp_layout(net, groups=pm, C=1., K=20, gamma=5, mu=20) graph_draw(net, pos=pos, vertex_fill_color=pm, vertex_color=pm, vertex_size=size, nodesfirst=True, edge_color=[0.179, 0.203,0.210, 0.3]) elif nngt.get_config("backend") == "networkx": import networkx as nx plt.figure() init_pos = {i: np.random.uniform(-1000., -900, 2) for i in range(500)} init_pos.update( {i: np.random.uniform(900., 1000, 2) for i in range(500, 1000)}) layout = nx.spring_layout(net, k=20, pos=init_pos) nx.draw(net, pos=layout, node_color=colors, node_size=20) elif nngt.get_config("backend") == "igraph": import igraph as ig colors = [(1, 0, 0) for _ in range(500)] colors.extend([(0, 0, 1) for _ in range(500)])
def mydraw(): pos = draw.sfdp_layout(tree) draw.graph_draw(tree, pos=pos, vertex_fill_color=tubuline) draw.graph_hist, bins = np.histogram(samples, bins=50)
# append degree gtg = g.return_gt_graph() g.v['deg'] = gtg.degree_property_map('total').a # how many "actors" are there per layer? g.v[g.v.deg != 0].groupby('layer').size() # In[12]: # create graph_tool graph for layout import graph_tool.draw as gtd gtg = g.return_gt_graph() gtg.set_directed(False) # get sfdp layout postitions pos = gtd.sfdp_layout(gtg, gamma=.5) pos = pos.get_2d_array([0, 1]) g.v['x'] = pos[0] g.v['y'] = pos[1] # configure nodes kwds_scatter = {'s': 1, 'c': 'k'} # configure edges kwds_quiver = {'headwidth': 1, 'alpha': .3, 'cmap': 'prism'} # color by type C = g.e.groupby('type').grouper.group_info[0] # plot fig, ax = plt.subplots(1, 2, figsize=(15, 7)) g.plot_2d('x',
def draw_network(network, nsize="total-degree", ncolor="group", nshape="o", nborder_color="k", nborder_width=0.5, esize=1., ecolor="k", spatial=True, size=(600,600), dpi=75): ''' Draw a given graph/network. Parameters ---------- network : :class:`~nngt.Graph` or subclass The graph/network to plot. nsize : float, array of floats or string, optional (default: "total-degree") Size of the nodes; if a number, percentage of the canvas length, otherwize a string that correlates the size to a node attribute among "in/out/total-degree", "betweenness". ncolor : float, array of floats or string, optional (default: 0.5) Color of the nodes; if a float in [0, 1], position of the color in the current palette, otherwise a string that correlates the color to a node attribute among "in/out/total-degree", "betweenness" or "group". nshape : char or array of chars, optional (default: "o") Shape of the nodes (see `Matplotlib markers <http://matplotlib.org/api/markers_api.html?highlight=marker#module-matplotlib.markers>`_). nborder_color : char, array of char, float or array of float, optional (default: "k") Color of the node's border using predefined `Matplotlib colors <http://matplotlib.org/api/colors_api.html?highlight=color#module-matplotlib.colors>`_). or floats in [0, 1] defining the position in the palette. nborder_width : float or array of floats, optional (default: 0.5) Width of the border in percent of canvas size. esize : float or array of floats, optional (default: 0.5) Width of the edges in percent of canvas size. ecolor : char, array of char, float or array of float, optional (default: "k") Edge color. spatial : bool, optional (default: True) If True, use the neurons' positions to draw them. size : tuple of ints, optional (default: (600,600)) (width, height) tuple for the canvas size (in px). dpi : int, optional (default: 75) Resolution (dot per inch). ''' pos,layout = None,None n = network.node_nb() e = network.edge_nb() # compute properties if issubclass(str,nsize.__class__): if e: nsize = _node_size(network, nsize) nsize.a *= 0.01*size[0] elif issubclass(float, nsize.__class__): nsize = np.repeat(nsize, n) if issubclass(str,esize.__class__): if e: esize = _edge_size(network, esize) esize.a *= 0.01*size[0] elif issubclass(float, esize.__class__): esize = np.repeat(esize, e) esize = network.graph.new_edge_property("double",esize) ncolor = _node_color(network, ncolor) if issubclass(float, nborder_color.__class__): nborder_color = np.repeat(nborder_color, n) if issubclass(float, ecolor.__class__): ecolor = np.repeat(ecolor, e) # draw pos = np.zeros((n,2)) if not e: nsize = 0.02*size[0] esize = 0.01*size[0] if spatial and network.is_spatial(): pos = network[POS] else: pos[:,0] = size[0]*(np.random.uniform(size=n)-0.5) pos[:,1] = size[1]*(np.random.uniform(size=n)-0.5) elif spatial and network.is_spatial(): pos = network[POS] pos = network.graph.new_vertex_property("vector<double>",pos) else: ebetw = network.graph.betweenness_list(as_prop=True)[1] pos = gplot.sfdp_layout(network.graph, eweight=ebetw) if not e: size_inches = (size[0]/float(dpi),size[1]/float(dpi)) fig = plt.figure(facecolor='white', figsize=size_inches, dpi=dpi) ax = fig.add_subplot(111, frameon=0, aspect=1) fig.facecolor = "white" fig.figsize=size ax.set_axis_off() if hasattr(network, "population"): for group in network.population.itervalues(): idx = group.id_list ax.scatter(pos[idx,0], pos[idx,1], s=nsize, color=palette(ncolor[idx[0]])) else: ax.scatter(pos[:,0], pos[:,1], s=nsize) ax.set_xlim([-0.51*size[0],0.51*size[0]]) ax.set_ylim([-0.51*size[1],0.51*size[1]]) plt.show() elif spatial and network.is_spatial(): gplot.graph_draw(network.graph, pos=pos, vertex_color=nborder_color, vertex_fill_color=ncolor, vertex_size=nsize, edge_color=ecolor, edge_pen_width=esize, output_size=size) else: gplot.graph_draw(network.graph, pos=pos, vertex_color=nborder_color, vertex_fill_color=ncolor, vertex_size=nsize, edge_color=ecolor, edge_pen_width=esize, output_size=size)