def wrapper(jsonGraph, path): g = func(jsonGraph,path) colors = dict(mcolors.BASE_COLORS, **mcolors.CSS4_COLORS) G= Network(height="800px", width="70%", directed=True) data=[] for u,e,v in g[1]: data.append(e) label_encoder = LabelEncoder() integer_encoded = np.array(label_encoder.fit_transform(data), dtype='float') i=0 for src,e,dst in g[1]: src_cname_idx = str(src).count('/') if str(src).count('/') < len(cnames) else (len(cnames) - 1) src_size_idx = str(src).count('/') if str(src).count('/') < len(sizes) else (len(sizes) - 1) dst_cname_idx = str(dst).count('/') if str(dst).count('/') < len(cnames) else (len(cnames) - 1) dst_size_idx = str(dst).count('/') if str(dst).count('/') < len(sizes) else (len(sizes) - 1) G.add_node(src, title=src, physics=True,color=cnames[src_cname_idx], size=sizes[src_size_idx], shape="dot") G.add_node(dst, title=dst, physics=True,color=cnames[dst_cname_idx], size=sizes[dst_size_idx], shape="dot") G.add_edge(src,dst,width=0.5, title=data[i],physics=True) i+=1 G.hrepulsion(node_distance=120, central_gravity=0.0, spring_length=100, spring_strength=0.01, damping=0.09) G.show_buttons(filter_=['physics']) G.show("test.html") # for s,p,o in g[1]: # print((s,p,o)) return g
def pyvis_draw(self, graph, name): cnames = ['blue', 'green', 'red', 'cyan', 'orange', 'black', 'purple', 'purple', 'purple'] G = Network(height="800px", width="100%", directed=True) for src, edge, dst in graph: if edge == self.om.type and not self.config.show_url: continue src_type = [x for x in graph[src:self.om.type]] dst_type = [x for x in graph[dst:self.om.type]] if len(src_type): if str(Flavor.FUNCTION) == str(src_type[0]) or str(Flavor.METHOD) == str(src_type[0]): G.add_node(src, title=src, physics=True, color=cnames[0]) elif str(Flavor.CLASS) == str(src_type[0]) or str(Flavor.MODULE) == str(src_type[0]): G.add_node(src, title=src, physics=True, color=cnames[1]) else: G.add_node(src, title=src, physics=True, color=cnames[2]) else: G.add_node(src, title=src, physics=True, color=cnames[3]) if len(dst_type): if str(Flavor.FUNCTION) == str(dst_type[0]) or str(Flavor.METHOD) == str(dst_type[0]): G.add_node(dst, title=dst, physics=True, color=cnames[0]) elif str(Flavor.CLASS) == str(dst_type[0]) or str(Flavor.MODULE) == str(dst_type[0]): G.add_node(dst, title=dst, physics=True, color=cnames[1]) else: G.add_node(dst, title=dst, physics=True, color=cnames[2]) else: G.add_node(dst, title=dst, physics=True, color=cnames[3]) G.add_edge(src, dst, width=0.5, title=str(edge), physics=True) G.hrepulsion(node_distance=120, central_gravity=0.0, spring_length=100, spring_strength=0.01, damping=0.09) # G.show_buttons(filter_=['physics']) G.save_graph("%s.html" % name)
def show_connectivity_graph(cells, result_folder=None, file_name="conectivity_graph.html", height="100%", width="100%", bgcolor="#222222", font_color="white", stim_color="#f5ce42", cell_color="#80bfff", edge_excitatory_color="#7dd100", edge_inhibitory_color="#d12d00", is_excitatory_func=lambda pp: pp.hoc.e >= -20, is_show_edge_func=lambda pp: hasattr(pp.hoc, "e"), node_distance=100, spring_strength=0): """ Creates graph of connections between passed cells. It will create a HTML file presenting the graph in the result_folder as well as run the graph in your browser. It will create a file cell_graph_[DATE].html in the result_folder, where [DATE] is the current date with seconds, from the template: "%Y-%m-%d_%H-%M-%S". :param cells: All cells must be of type NetConCell or just Cell :param result_folder: Any folder where to put your graph, eg. "graphs". The default is None, meaning that the graph html file will be saved to the current working directory :param file_name: :param height: :param width: :param bgcolor: :param font_color: :param stim_color: :param cell_color: :param edge_excitatory_color: Color for the excitatory connection; By default it is default edge color :param edge_inhibitory_color: Color for the inhibitory connection :param is_excitatory_func: This is the default function: lambda point_process = point_process.hoc.e >= -20 If returns true - a particular connection is excitatory, otherwise inhibitory. :param is_show_edge_func: This is the default function: lambda point_process = hasattr(point_process.hoc, "e"), Define whether to show the edge. :param node_distance: :param spring_strength: """ g = Network(height=height, width=width, bgcolor=bgcolor, font_color=font_color, directed=True) nodes = [] for c in cells: nodes.append(c.name) g.add_node(c.name, color=cell_color) for nc in c.ncs: nc = cast(NetCon, nc) if "SpikeDetector" in nc.name: continue elif isinstance(nc.source, Seg): nc_node = nc.source.parent.cell.name node_color = cell_color elif nc.source is None: nc_node = "External Stim" node_color = stim_color else: nc_node = nc.source.name node_color = stim_color if nc_node not in nodes: nodes.append(nc_node) g.add_node(nc_node, color=node_color) if is_show_edge_func is not None and not is_show_edge_func( nc.target): continue g.add_edge(nc_node, c.name) if is_excitatory_func is None: g.edges[-1]['color'] = edge_excitatory_color else: if is_excitatory_func(nc.target): g.edges[-1]['color'] = edge_excitatory_color else: g.edges[-1]['color'] = edge_inhibitory_color g.show_buttons() g.hrepulsion(node_distance=node_distance, spring_strength=spring_strength) if result_folder: save_path = '%s/%s' % (result_folder, file_name) else: save_path = file_name if result_folder: os.makedirs(result_folder, exist_ok=True) g.show(save_path) print("Saved cell graph into: %s" % save_path)
# Create Network Graph/ ts_net = Network(height="100%", width="100%", bgcolor="#222222", font_color="white") # set the physics layout of the network # ts_net.repulsion(damping=0.9, spring_length=200, node_distance=350) if net_type == "atlas": ts_net.force_atlas_2based(gravity=-50, central_gravity=0.01, spring_length=100, spring_strength=0.08, damping=0.4, overlap=0) if net_type == "barnes": ts_net.barnes_hut(gravity=-80000, central_gravity=0.3, spring_length=25, spring_strength=0.001, damping=0.09, overlap=0) if net_type == "repulsion": ts_net.repulsion(damping=0.9, spring_length=200, node_distance=350) if net_type == "hrepulsion": ts_net.hrepulsion(node_distance=120, central_gravity=0.0, spring_length=100, spring_strength=0.01, damping=0.09) ts_data = pd.read_csv(key+".csv") # Call Columns in csv File by Column Names sources = ts_data['Source'] targets = ts_data['Target'] weights = ts_data['Weight'] edge_data = zip(sources, targets, weights) # add edge data for e in edge_data: src = e[0] dst = e[1]
def plot(self, output: str): """ Visualize a Bayesian Network. Result will be saved in parent directory in folder visualization_result. output: str name of output file """ if not output.endswith('.html'): logger_network.error("This version allows only html format.") return None G = nx.DiGraph() nodes = [node.name for node in self.nodes] G.add_nodes_from(nodes) G.add_edges_from(self.edges) network = Network(height="800px", width="100%", notebook=True, directed=nx.is_directed(G), layout='hierarchical') nodes_sorted = np.array(list(nx.topological_generations(G)), dtype=object) # Qualitative class of colormaps q_classes = [ 'Pastel1', 'Pastel2', 'Paired', 'Accent', 'Dark2', 'Set1', 'Set2', 'Set3', 'tab10', 'tab20', 'tab20b', 'tab20c' ] hex_colors = [] for cls in q_classes: rgb_colors = plt.get_cmap(cls).colors hex_colors.extend([ matplotlib.colors.rgb2hex(rgb_color) for rgb_color in rgb_colors ]) hex_colors = np.array(hex_colors) # Number_of_colors in matplotlib in Qualitative class = 144 class_number = len(set([node.type for node in self.nodes])) hex_colors_indexes = [ random.randint(0, len(hex_colors) - 1) for _ in range(class_number) ] hex_colors_picked = hex_colors[hex_colors_indexes] class2color = { cls: color for cls, color in zip(set([node.type for node in self.nodes]), hex_colors_picked) } name2class = {node.name: node.type for node in self.nodes} for level in range(len(nodes_sorted)): for node_i in range(len(nodes_sorted[level])): name = nodes_sorted[level][node_i] cls = name2class[name] color = class2color[cls] network.add_node(name, label=name, color=color, size=45, level=level, font={'size': 36}, title=f'Узел байесовской сети {name} ({cls})') for edge in G.edges: network.add_edge(edge[0], edge[1]) network.hrepulsion(node_distance=300, central_gravity=0.5) if not (os.path.exists('visualization_result')): os.mkdir("visualization_result") return network.show(f'visualization_result/' + output)
def plot(g, properties=None, selection=None, hlayout=True, scale=None, labels=None, height='800px', width='900px', **kwds): """Plot a MTG in the Jupyter Notebook""" G = Network(notebook=True, directed=True, layout=hlayout, heading="", height=height, width=width) if hlayout: G.hrepulsion() G.options.layout.hierarchical.direction = 'DU' G.options.layout.hierarchical.parentCentralization = True G.options.layout.hierarchical.levelSeparation = 150 else: G.repulsion() if scale is None: scale = g.max_scale() #Colors if cc is not None: colors = cc.glasbey_light else: colors = [ '#6e6efd', '#fb7e81', '#ad85e4', '#7be141', '#ffff00', '#ffa807', '#eb7df4', '#e6ffe3', '#d2e5ff', '#ffd1d9' ] #Data vids = g.vertices(scale=scale) edges = [(g.parent(vid), vid, 6 if g.edge_type(vid) == '<' else 1) for vid in vids if g.parent(vid) is not None ] #, 'black' if g.edge_type(vid) == '<' else None pos = g.property('position') #Level determination levels = {} root = next(g.component_roots_at_scale_iter(g.root, scale=scale)) for vid in traversal.pre_order(g, root): levels[vid] = 0 if g.parent(vid) is None else levels[g.parent(vid)] + 1 #Component roots component_roots = {} component_roots[root] = True for vid in traversal.pre_order(g, root): pid = g.parent(vid) if pid is None: component_roots[vid] = True elif g.complex(pid) != g.complex(vid): component_roots[vid] = True #Groups groups = {} for count, vid in enumerate(traversal.pre_order(g, g.complex(root))): nc = len(colors) groups[vid] = colors[count % nc] pid = g.parent(vid) if pid: if groups[vid] == groups[pid]: groups[vid] = colors[(1789 * count + 17) % nc] #Nodes adding for vid in vids: shape = 'box' if vid in component_roots else 'circle' if labels is None: label_node = g.label(vid) else: label_node = labels[vid] level = levels[vid] if selection is None: color = groups[g.complex(vid)] else: color = '#fb7e81' if vid in selection else '#97c2fc' title = dict2html(g[vid], properties=properties) #gap, mult = max(pos[1])-min(pos[1]), 20 #x = mult*pos[g.parent(vid)][0] if g.parent(vid) else pos[vid][0] # #y = mult*(gap - pos[vid][1]) #if g.parent(vid) else None #physics = False if ('edge_type' not in g[vid] or g[vid]['edge_type']=='<' or g.nb_children(vid)>0) else True G.add_node( vid, shape=shape, label=label_node, level=level, color=color, title=title, borderWidth=3, #x=x, #y=y, #physics=physics, ) #Cluster if False: for vid in traversal.pre_order(g, g.complex(root)): G.add_node(vid, hidden=True) if g.parent(vid): G.add_edge(g.parent(vid), vid, hidden=True) for cid in g.components(vid): G.add_edge(vid, cid, hidden=True) #Edges adding for edge in edges: label_edge = g.edge_type(edge[1]) G.add_edge(edge[0], edge[1], label=label_edge, width=edge[2]) return G.show('mtg.html')
def create_graph(reactions, reactants=None, height="100%", width="100%", bgcolor="#222222", font_color="white", node_distance=140, spring_strength=0.001): """ :param reactions: :param reactants: :param height: :param width: :param bgcolor: :param font_color: :param node_distance: :param spring_strength: :return: """ g = Network(height=height, width=width, bgcolor=bgcolor, font_color=font_color, directed=True) nodes = [] if reactants is None: reactants = [] for k, v in reactions.items(): fr = float(v['forward']) rr = float(v['reverse']) afinity_rate = fr / rr if rr != 0 else fr diffusion_rate = rr / fr if fr != 0 else rr if afinity_rate > diffusion_rate: edge_color = "#91db7b" # green - domination of forward reaction value = afinity_rate else: edge_color = "#ff9999" # red - domination of reverse reaction value = diffusion_rate edge_thick = value if edge_thick > 10000: edge_thick = 10000 for r in v['reactant']: for p in v['product']: if r not in nodes: nodes.append(r) g.add_node( r, color="#f5ce42" if r in reactants else "#80bfff") if p not in nodes: nodes.append(p) g.add_node( p, color="#f5ce42" if p in reactants else "#80bfff") if k not in nodes: nodes.append(k) g.add_node(n_id=k, shape="diamond", color="#969696", label="R", size=10, title=k) g.add_edge(r, k, color=edge_color, value=edge_thick, title=value) g.add_edge(k, p, color=edge_color, value=edge_thick, title=value) g.show_buttons(filter_=['physics']) g.hrepulsion(node_distance=node_distance, spring_strength=spring_strength) return g