def network_pyvis(self, df): G = nx.from_pandas_edgelist(df, edge_attr=True) net = Network(height="500px", width="100%", heading='') sources = df['source'] targets = df['target'] weights = df['weight'] edge_data = zip(sources, targets, weights) for e in edge_data: src = e[0] dst = e[1] w = e[2] net.add_node(src, src, title=src) net.add_node(dst, dst, title=dst) net.add_edge(src, dst, value=w) neighbor_map = net.get_adj_list() net.from_nx(G) net.write_html('tweets/temp.html') return net.html
def plotResult(file_in, file_out): got_net = Network(height="100%", width="100%", bgcolor="white", font_color="black") got_net.barnes_hut() got_data = pd.read_csv(file_in) sources = got_data['From'] targets = got_data['To'] weights = got_data['Weight'] x_array = got_data['x'] y_array = got_data['y'] highlight = got_data['Highlight'] edge_data = zip(sources, targets, weights, x_array, y_array, highlight) for e in edge_data: src = e[0] dst = e[1] w = e[2] x_array = e[3] y_array = e[4] h = e[5] v_color_dst = "#ADFF2F" #Green color image_url = 'cat.png' v_shape = 'dot' if (dst in ['central_concentrator'] or h == 1): image_url = 'cat.png' v_shape = 'circle' got_net.add_node(src, shape=v_shape, title=src, x=x_array, y=y_array, color="#ADFF2F") #Green color got_net.add_node(dst, shape=v_shape, title=dst, x=x_array, y=y_array, color=v_color_dst) got_net.add_edge(src, dst, value=h) neighbor_map = got_net.get_adj_list() # add neighbor data to node hover data for node in got_net.nodes: node["title"] += " Neighbors:<br>" + "<br>".join( neighbor_map[node["id"]]) node["value"] = len(neighbor_map[node["id"]]) got_net.set_options( 'var options = { "edges": { "arrows": { "middle": { "enabled": true } }, "color": { "inherit": "false"}, "smooth": false},"physics": {"enabled": true, "forceAtlas2Based":{ "gravitationalConstant": -500, "springLength": 100, "avoidOverlap": 1}, "minVelocity": 0.75, "solver": "forceAtlas2Based"}}' ) got_net.show(file_out)
def network_visualization(path='./socnetvis.html', alphabet=False): weights = {'best': 4, 'good': 2, 'friend': 1, 'acquaintance': 0.5} net = Network('100%', '100%', bgcolor='#222', font_color='white') net.barnes_hut() for name, node in nodes.items(): for connection_type in node['connections']: for partner in node['connections'][connection_type]: net.add_node(name, name, title=name) net.add_node(partner, partner, title=partner) net.add_edge(name, partner, value=weights[connection_type]) for net_node in net.nodes: node = nodes[net_node['id']] net_node['value'] = len(net.get_adj_list()[net_node['id']]) net_node['title'] += f"<br>{net_node['value']} Connections<br>" if node['notes']: net_node['title'] += f"<i>{node['notes']}</i><br>" for connection_type in node['connections']: if node['connections'][connection_type]: connections = node['connections'][connection_type] net_node['title'] += f"<br>{connection_type.capitalize()} " \ f"({len(connections)})<br>  " net_node['title'] += "<br>  ".join( sorted(connections) if alphabet else connections) + "<br>" if not os.path.isdir(os.path.dirname(path)): os.makedirs(os.path.dirname(path)) net.show(path)
def kyoki_word_network(): got_net = Network(height="1000px", width="95%", bgcolor="#FFFFFF", font_color="black", notebook=True) # set the physics layout of the network #got_net.barnes_hut() got_net.force_atlas_2based() got_data = pd.read_csv("kyoki.csv")[:150] sources = got_data['first'] #count targets = got_data['second'] #first weights = got_data['count'] #second edge_data = zip(sources, targets, weights) for e in edge_data: src = e[0] dst = e[1] w = e[2] got_net.add_node(src, src, title=src) got_net.add_node(dst, dst, title=dst) got_net.add_edge(src, dst, value=w) neighbor_map = got_net.get_adj_list() #add neighbor data to node hover data for node in got_net.nodes: node["title"] += " Neighbors:<br>" + "<br>".join( neighbor_map[node["id"]]) node["value"] = len(neighbor_map[node["id"]]) got_net.show_buttons(filter_=['physics']) return got_net
def pyvis(height): # Load Pyvis network got_net = Network(height="750px", width="100%", bgcolor="#222222", font_color="white") got_net.barnes_hut() got_data = pd.read_csv( "https://www.macalester.edu/~abeverid/data/stormofswords.csv") sources = got_data['Source'] targets = got_data['Target'] weights = got_data['Weight'] edge_data = zip(sources, targets, weights) for e in edge_data: src = e[0] dst = e[1] w = e[2] got_net.add_node(src, src, title=src) got_net.add_node(dst, dst, title=dst) got_net.add_edge(src, dst, value=w) neighbor_map = got_net.get_adj_list() for node in got_net.nodes: node["title"] += " Neighbors:<br>" + "<br>".join( neighbor_map[node["id"]]) node["value"] = len(neighbor_map[node["id"]]) got_net.write_html("gameofthrones.html") return got_net.html, height, "Pyvis Network"
def drawRscRscGraph_advanced(self, RscRscMatrix, weight_threshold, directed, encryption): rows, cols = np.where(RscRscMatrix > weight_threshold) weights = list(); for x in range(len(rows)): weights.append(RscRscMatrix[rows[x]][cols[x]]) #got_net = Network(height="750px", width="100%", bgcolor="white", font_color="#3de975", directed=directed) got_net = Network(height="750px", width="100%", bgcolor="white", font_color="black", directed=directed) ##f57b2b # set the physics layout of the network got_net.barnes_hut() edge_data = zip(rows, cols, weights) for e in edge_data: src = self.resourceList[e[0]] # convert ids to labels dst = self.resourceList[e[1]] w = e[2] if(encryption): src = Utilities.AES_ECB_Encrypt(self,src.encode('utf-8')) dst = Utilities.AES_ECB_Encrypt(self,dst.encode('utf-8')) # I have to add some options here, there is no parameter highlight = {'border': "#3de975", 'background': "#41e9df"} #color = {'border': "#000000", 'background': "#123456"} got_net.add_node(src, src, title=src, labelHighlightBold=True, color={'highlight': highlight}) got_net.add_node(dst, dst, title=dst , labelHighlightBold=True, color={'highlight': highlight}) got_net.add_edge(src, dst, value=w, title=w) neighbor_map = got_net.get_adj_list() dict = got_net.get_edges() self.getResourceList() # add neighbor data to node hover data for node in got_net.nodes: counter = 0 if(directed): node["title"] = "<h3>" + node["title"] + " Output Links: </h3>" else: node["title"] = "<h3>" + node["title"] + " Links: </h3>" for neighbor in neighbor_map[node["id"]]: if(counter % 10 == 0): node["title"] += "<br>::: " + neighbor else: node["title"] += " ::: " + neighbor node["value"] = len(neighbor_map[node["id"]]) counter += 1 got_net.show_buttons(filter_=['nodes', 'edges', 'physics']) got_net.show_buttons(filter_=['physics']) got_net.show("PMSocial.html")
def drawActivityResourceGraph_advanced(self, ActivityRscMatrix, weight_threshold, directed, splitted): rows, cols = np.where(ActivityRscMatrix > weight_threshold) weights = list(); for x in range(len(rows)): weights.append(ActivityRscMatrix[rows[x]][cols[x]]) got_net = Network(height="750px", width="100%", bgcolor="black", font_color="#f57b2b", directed= directed) # set the physics layout of the network got_net.barnes_hut() edge_data = zip(rows, cols, weights) counter = 1 for e in edge_data: src = self.activityList[e[0]] # convert ids to labels dst = self.resourceList[e[1]] w = e[2] # I have to add some options here, there is no parameter highlight = {'border': "#3de975", 'background': "#41e9df"} if(splitted): got_net.add_node(src, src, title=src, labelHighlightBold=True, color={'highlight': highlight},shape='square') got_net.add_node(dst+ "__" +str(counter) , dst , title=dst , labelHighlightBold=True, color={'border': "#dd4b39", 'background': "#dd4b39", 'highlight': highlight}) got_net.add_edge(src, dst+ "__" +str(counter), value=w, title=w) counter +=1 else: got_net.add_node(src, src, title=src, labelHighlightBold=True, color={'highlight': highlight},shape='square') got_net.add_node(dst , dst, title=dst , labelHighlightBold=True, color={'border': "#dd4b39", 'background': "#dd4b39", 'highlight': highlight}) got_net.add_edge(src, dst , value=w, title=w) neighbor_map = got_net.get_adj_list() dict = got_net.get_edges() self.getResourceList() # add neighbor data to node hover data for node in got_net.nodes: counter = 0 if(directed): node["title"] = "<h3>" + node["title"] + " Output Links: </h3>" else: node["title"] = "<h3>" + node["title"] + " Links: </h3>" for neighbor in neighbor_map[node["id"]]: if(counter % 10 == 0): node["title"] += "<br>::: " + neighbor else: node["title"] += " ::: " + neighbor node["value"] = len(neighbor_map[node["id"]]) counter += 1 got_net.show_buttons(filter_=['nodes', 'edges', 'physics']) got_net.show_buttons(filter_=['physics']) got_net.show("PMSocial.html")
def dynamic_netShow(gnetdata, filename, node_size=50, node_community='all', html_size=["500px", "1800px"], bgcolor="#222222", font_color="white", **kwarg): """ create a GRN html ------------------------------------------ :param gnetdata: Gnetdata object :param filename: str, save as filename :param node_size: int, default 50. :param node_community: str or list, default all. :param html_size: list, default ["1200px", "1600px"] :param font_color: string, default white :param bgcolor: string, default #222222 :return: None """ assert 'graph' in gnetdata.NetAttrs.keys(), 'graph is empty!' assert 'communities' in gnetdata.NetAttrs.keys(), 'node communities is empty!' node_group = gnetdata.NetAttrs['communities'] graph = gnetdata.NetAttrs['graph'] net = Network(html_size[0], html_size[1], bgcolor=bgcolor, font_color=font_color, **kwarg) edge_data = zip(list(graph.edges), list(graph[x[0]][x[1]]['weight'] for x in graph.edges)) colors = sns.color_palette().as_hex() + sns.color_palette('Paired', 100).as_hex() for e in edge_data: src = e[0][0] dst = e[0][1] w = e[1] if node_community == 'all': src_color = int(node_group[node_group['node'] == src]['group']) dst_color = int(node_group[node_group['node'] == dst]['group']) else: sub_node_group = node_group[node_group.group.isin(node_community)] src_color = int(sub_node_group[sub_node_group['node'] == src]['group']) if src in list( sub_node_group.node) else 'grey' dst_color = int(sub_node_group[sub_node_group['node'] == dst]['group']) if dst in list( sub_node_group.node) else 'grey' net.add_node(src, src, title=src, color='grey' if src_color == 'grey' else colors[src_color]) net.add_node(dst, dst, title=dst, color='grey' if dst_color == 'grey' else colors[dst_color]) net.add_edge(src, dst, value=w) neighbor_map = net.get_adj_list() # add neighbor data to node hover data for node in net.nodes: node["title"] += " Neighbors:<br>" + "<br>".join(neighbor_map[node["id"]]) node["value"] = len(neighbor_map[node["id"]]) node['size'] = node_size net.show_buttons(filter_='physics') net.show(filename) return None
def vis_graph(): """ using pyvis """ # https://pyvis.readthedocs.io/en/latest/tutorial.html#example-visualizing-a-game-of-thrones-character-network nt = Network(height="750px", width="100%", bgcolor="#222222", font_color="white") nt.barnes_hut() nt.from_nx(G) neighbor_map = nt.get_adj_list() for node in nt.nodes: node["title"] += " neighbors:<br>" + "<br>".join(neighbor_map[node["id"]]) node["value"] = len(neighbor_map[node["id"]]) nt.show("rappers.html")
def create_graph(messages: list, people: list, reacts: dict, freq: dict, config: dict): directed = config['graph']['directed'] if directed: reacts_g = nx.DiGraph() else: reacts_g = nx.Graph() reacts_g.add_nodes_from(people) threshold = config['graph']['pair_threshold'] for pair in itertools.combinations(people, 2): make_edge(pair[0], pair[1], reacts, directed, threshold, reacts_g) if directed: make_edge(pair[1], pair[0], reacts, directed, threshold, reacts_g) vis = Network(bgcolor='#222222', font_color="white", height="100%", width="100%", directed=directed) vis.from_nx(reacts_g) neighs = vis.get_adj_list() for edge in vis.edges: edge["value"] = get_pair_reacts(edge["from"], edge["to"], reacts, directed) for node in vis.nodes: neighbors = vis.neighbors(node['id']) n_metadata = [] for neighbor in neighbors: pair = (node['id'], neighbor) matching_edge = [ edge for edge in vis.edges if (edge["from"] in pair and edge["to"] in pair) ][0] n_metadata.append(f'{neighbor} ({matching_edge["value"]})') node['title'] = " Reacts:<br>" + "<br>".join(list(n_metadata)) if config['graph']['adjust_node_size']: node['size'] = config['graph']['base_size'] * log10( (freq[node['id']]) / 10) else: node['size'] = config['graph']['base_size'] return (vis)
def visualize(graph_nx, name='graph'): got_net = Network(height="750px", width="100%", bgcolor="#222222", font_color="white") # set the physics layout of the network got_net.barnes_hut() got_net.from_nx(graph_nx) # add neighbor data to node hover data neighbor_map = got_net.get_adj_list() for node in got_net.nodes: node["title"] += " Neighbors:<br>" + "<br>".join(neighbor_map[node["id"]]) node["value"] = len(neighbor_map[node["id"]]) got_net.show_buttons() got_net.show(f'{name}.html')
def visualize_graph(self): """ Generates visualization using Pyviz, a wrapper around visJS. The visualization can be found at datanet.html """ from pyvis.network import Network # type: ignore (PyLance) print("Generating visualizations...") data_net = Network(height='100%', width='100%', bgcolor='#222222', font_color='white') sources = self.df_edges["series_y"] targets = self.df_edges["series_x"] name_src = self.df_edges["modality_y"] name_tar = self.df_edges["modality_x"] patient_id = self.df_edges["patient_ID_x"] reference_ct = self.df_edges["reference_ct_y"] reference_rs = self.df_edges["reference_rs_y"] data_zip = zip(sources, targets, name_src, name_tar, patient_id, reference_ct, reference_rs) for i in data_zip: data_net.add_node(i[0], i[2], title=i[2], group=i[4]) data_net.add_node(i[1], i[3], title=i[3], group=i[4]) data_net.add_edge(i[0], i[1]) node = data_net.get_node(i[0]) node[ "title"] = "<br>Patient_id: {}<br>Series: {}<br>reference_ct: {}<br>reference_rs: {}".format( i[4], i[0], i[5], i[6]) node = data_net.get_node(i[1]) node[ "title"] = "<br>Patient_id: {}<br>Series: {}<br>reference_ct: {}<br>reference_rs: {}".format( i[4], i[1], i[5], i[6]) neigbour_map = data_net.get_adj_list() for node in data_net.nodes: node["title"] += "<br>Number of connections: {}".format( len(neigbour_map[node['id']])) node["value"] = len(neigbour_map[node['id']]) vis_path = pathlib.Path(os.path.dirname(self.edge_path), "datanet.html").as_posix() data_net.show(vis_path)
def netView_sat(nlp_data_dataframe, year): ''' Function to generate the network view. Input: Dataframe Output: Network chart ''' from pyvis.network import Network nlp_net = Network(height="750px", width="100%", bgcolor="#222222", font_color="white") # set the physics layout of the network nlp_net.force_atlas_2based() sources = nlp_data_dataframe.loc[:, 'Source'] targets = nlp_data_dataframe.loc[:, 'Target'] weights = nlp_data_dataframe['Weight'] edge_data = zip(sources, targets, weights) for e in edge_data: src = e[0] dst = e[1] w = e[2] nlp_net.add_node(src, src, title=src) nlp_net.add_node(dst, dst, title=dst) nlp_net.add_edge(src, dst, value=w) neighbor_map = nlp_net.get_adj_list() # add neighbor data to node hover data for node in nlp_net.nodes: node[ "title"] += "<br>Neighbors:<br><style>body{font-size:18px;}</style>" + "<br>".join( neighbor_map[node["id"]]) node["value"] = len(neighbor_map[node["id"]]) nlp_net.toggle_stabilization(True) nlp_net.show_buttons(filter_=['physics']) nlp_net.show("NLP-Enquete-Satisfied" + year + ".html")
def got_func(physics): got_net = Network(height="600px", width="100%", font_color="black", heading='Test Graph') # set the physics layout of the network got_net.barnes_hut() got_data = pd.read_csv( "https://www.macalester.edu/~abeverid/data/stormofswords.csv") # got_data = pd.read_csv("stormofswords.csv") # got_data.rename(index={0: "Source", 1: "Target", 2: "Weight"}) sources = got_data['Source'] targets = got_data['Target'] weights = got_data['Weight'] edge_data = zip(sources, targets, weights) for e in edge_data: src = e[0] dst = e[1] w = e[2] got_net.add_node(src, src, title=src) got_net.add_node(dst, dst, title=dst) got_net.add_edge(src, dst, value=w) neighbor_map = got_net.get_adj_list() # add neighbor data to node hover data for node in got_net.nodes: node["title"] += " Neighbors:<br>" + "<br>".join( neighbor_map[node["id"]]) node["value"] = len(neighbor_map[node["id"]]) if physics: got_net.show_buttons(filter_=['physics']) got_net.show("Test_2.html")
def generate_trustline_graph(data): ''' This function generates a network graph using pyvis module. The graph is saved in Analysis folder. Parameters ---------- data : Filtered transactions data. Returns ------- None. ''' graphNodeList=[] # creating empty nodes list for graph for acc in data.index: # adding data to graph nodes list graphNodeList.append(data['account'][acc]) # appending account graphNodeList.append(data['issuer'][acc]) # appending issuer graphNodeList=list(set(graphNodeList)) # filtering graph node list for unique node list graphEdgeList=[] # create graph's edge list for acc in data.index: # adding data to graph's edges if(data['value'][acc]!=0): # don't add edge if trustline is set to 0 graphEdgeList.append((data['account'][acc],data['issuer'][acc],data['currency'][acc],data['value'][acc])) # adding edge with account, issuer, currency and value nx_graph = Network(height="750px", width="100%", bgcolor="#222222", font_color="white",directed="true") # setting parameters for visualising the graph. for node in graphNodeList: # adding nodes to graph nx_graph.add_node(node, size=20, title=node) for edge in graphEdgeList: # adding edges to graph weigh= str(edge[3])+' '+str(edge[2]) nx_graph.add_edge(edge[0], edge[1], weight=weigh, title=weigh) # adding edge with weights to graph neighbor_map = nx_graph.get_adj_list() for node in nx_graph.nodes: node["title"] += " Trusted:<br>" + "<br>".join(neighbor_map[node["id"]]) # creating title for each node node["value"] = len(neighbor_map[node["id"]]) # setting value of node nx_graph.save_graph(r"../Analysis/TrustSetGraph.html") # saving the graph in HTML format nx_graph.show_buttons(filter_=['physics']) nx_graph.show("TrustSetGraph.html") # open the graph in browser
supervisors = data['Supervisor'] jobtype = data['Type'] color = {'PhD' : 'blueviolet' , 'postdoc' : 'magenta' , 'link' : 'turquoise'} all_people = set(list(people)+list(supervisors)) #node_size = Counter(supervisors) for person in all_people: net.add_node(person, title=person,size=5) #,shape='ellipse') for person, supervisor, job in zip(people,supervisors, jobtype): if job != 'link': net.add_edge(supervisor, person, arrow=True,color=color[job]) neighbor_map = net.get_adj_list() # add neighbor data to node hover data for node in net.nodes: supervised = [x for x in net.neighbors(node["id"])] num = len(supervised) if num > 0: node["title"] += " Students:<br>" + "<br>".join(neighbor_map[node["id"]]) node["value"] = num for person, supervisor, job in zip(people,supervisors, jobtype): if job == 'link': net.add_edge(supervisor, person, arrow=False,color=color[job],arrowStrikethrough=True) net.add_edge(person, supervisor, arrow=False,color=color[job],arrowStrikethrough=True) net.show("index.html")
for e in edge_data: #for every source and target after gliph src = e[0] #assign source to src dst = e[1] #assign target/destination to dst if src in cl18 and dst in cl18: #check if source and data are both present in convergencegroup (18) for i in range(0, x): #itterate over 0-35 for every HLA in HLAs if src in IDs[i]: #if source in one of the HLA lists.. klr_net.add_node( src, src, title=src ) #add source node to prob_net with color assigned to i for i in range(0, x): #itterate over 0-35 for every HLA in HLAs if dst in IDs[i]: #if target in one of the HLA lists.. klr_net.add_node( dst, dst, title=dst ) #add target node to prob_net with color assigned to i klr_net.add_edge(src, dst) #add edge between source and target neighbor_map = klr_net.get_adj_list() #create map with neighbours # add neighbor data to node hover data for node in klr_net.nodes: node["title"] += " Neighbors:<br>" + "<br>".join(neighbor_map[node["id"]]) node["value"] = len(neighbor_map[node["id"]]) #Make a dictionary containing the occurence of every HLA-type occ = {} for point in klr_net.nodes: #for every node for i in range( 0, x ): # create a loop over 35 numbers(enough to cover all HLAs in this case) if point["id"] in IDs[i]: #if node sequence in the list of HLA[i] name = IDs[i].split()[0] #assign the HLA-type to name if name in occ.keys(): #if name is present in occ as key
if new_asn != "": g.add_edge(new_asn, new_isp) new_countryname = entry['countryname'] new_countryname = '{}'.format(new_countryname) if new_countryname != "": g.add_node(new_countryname, color="#39af8e") if new_countryname != "": if new_isp != "": g.add_edge(new_countryname, new_isp) url_number += 1 #Checking for size/value of nodes neighbor_map = g.get_adj_list() for node in g.nodes: node["value"] = len(neighbor_map[node["id"]]) print("URLs: " + str(url_counter)) print("Nodes: " + str(g.num_nodes())) print("Edges: " + str(g.num_edges())) #g.show("network.html") g.show(column + "_" + compare + "_" + search + "_network.html") print("File generated: " + column + "_" + compare + "_" + search + "_network.html") #If you don't want to automatically open the current html file in your browser comment the 3 lines below new_tab = 2 file = "file://" + os.getcwd(
# add edge data for e in edge_data: src = e[0] dst = e[1] w = e[2] ts_net.add_node(src, src, title=src, shape="box", color="orange", shadow="true", selfReferenceSize=0) ts_net.add_node(dst, dst, title=dst, shape="dot", color=e_color) ts_net.add_edge(src, dst, value=w, arrows=a_direction, color="rgb(25,180,5)", selfReferenceSize=0, selectionWidth=0.1, shadow="true") # ts_net.show_buttons(filter_=['physics']) neighbor_map = ts_net.get_adj_list() # Set curve Type if edge_type == "curvedCW": ts_net.set_edge_smooth("CurvedCW") elif net_type == "curvedCCW": ts_net.set_edge_smooth("CurvedCCW") elif net_type == "cubicBezier": ts_net.set_edge_smooth("cubicBezier") elif net_type == "diagonalCross": ts_net.set_edge_smooth("diagonalCross") elif net_type == "straightCross": ts_net.set_edge_smooth("straightCross") elif net_type == "dynamic": ts_net.set_edge_smooth("dynamic") elif net_type == "continuous":
for e in edge_data: src = e[0] dst = e[1] w = e[2] print(src + " " + prvo) print(dst + " " + vtoro) if src==prvo and dst==vtoro and len(PAT)!=0: print("sdg") water_net.add_node(src, src, title=src, color="#00ff1e") water_net.add_node(dst, dst, title=dst, color="#00ff1e") water_net.add_edge(src, dst, value=w, color="#00ff1e") if len(PAT): prvo = PAT.pop() if len(PAT): vtoro = PAT.pop() else: water_net.add_node(src, src, title=src) water_net.add_node(dst, dst, title=dst) water_net.add_edge(src, dst, value=w) neighbor_map = water_net.get_adj_list() for node in water_net.nodes: node["title"] += " Neighbors:<br>" + "<br>".join(neighbor_map[node["id"]]) node["value"] = len(neighbor_map[node["id"]]) water_net.show("mygraph.html")
def apply(metric_values, parameters=None): """ Perform SNA visualization starting from the Matrix Container object and the Resource-Resource matrix Parameters ------------- metric_values Value of the metrics parameters Possible parameters of the algorithm, including: - Parameters.WEIGHT_THRESHOLD -> the weight threshold to use in displaying the graph Returns ------------- temp_file_name Name of a temporary file where the visualization is placed """ from pyvis.network import Network if parameters is None: parameters = {} weight_threshold = exec_utils.get_param_value(Parameters.WEIGHT_THRESHOLD, parameters, 0) directed = metric_values[2] temp_file_name = get_temp_file_name("html") rows, cols = np.where(metric_values[0] > weight_threshold) weights = list() for x in range(len(rows)): weights.append(metric_values[0][rows[x]][cols[x]]) got_net = Network(height="750px", width="100%", bgcolor="black", font_color="#3de975", directed=directed) # set the physics layout of the network got_net.barnes_hut() edge_data = zip(rows, cols, weights) for e in edge_data: src = metric_values[1][e[0]] # convert ids to labels dst = metric_values[1][e[1]] w = e[2] # I have to add some options here, there is no parameter highlight = {'border': "#3de975", 'background': "#41e9df"} # color = {'border': "#000000", 'background': "#123456"} got_net.add_node(src, src, title=src, labelHighlightBold=True, color={'highlight': highlight}) got_net.add_node(dst, dst, title=dst, labelHighlightBold=True, color={'highlight': highlight}) got_net.add_edge(src, dst, value=w, title=w) neighbor_map = got_net.get_adj_list() dict = got_net.get_edges() # add neighbor data to node hover data for node in got_net.nodes: counter = 0 if directed: node["title"] = "<h3>" + node["title"] + " Output Links: </h3>" else: node["title"] = "<h3>" + node["title"] + " Links: </h3>" for neighbor in neighbor_map[node["id"]]: if (counter % 10 == 0): node["title"] += "<br>::: " + neighbor else: node["title"] += " ::: " + neighbor node["value"] = len(neighbor_map[node["id"]]) counter += 1 got_net.show_buttons(filter_=['nodes', 'edges', 'physics']) got_net.write_html(temp_file_name) return temp_file_name
def CreateGraph(self, graph_type, overlaps): overlap_frame = pd.DataFrame( columns=['Source', 'Target', 'Type', 'Weight']) for overlap in overlaps: for sub_lap in overlaps[overlap]: overlap_frame = overlap_frame.append( { 'Source': overlap, 'Target': sub_lap[0], 'Type': 'directed', 'Weight': ((1 - sub_lap[1]) / 25) }, ignore_index=True) net = Network(height='100%', width='100%', directed=True) sources = overlap_frame['Source'] targets = overlap_frame['Target'] weights = overlap_frame['Weight'] edge_data = zip(sources, targets, weights) graph = nx.DiGraph() for index, e in enumerate(edge_data): src = e[0] dst = e[1] w = e[2] if (graph_type == 'NetworkX'): graph.add_node(src) graph.add_node(dst) graph.add_edge(src, dst, weights=w) else: net.add_node(src, src, title=src, physics=False, group=index, arrowStrikethrough=False) net.add_node(dst, dst, title=dst, physics=False, group=index, arrowStrikethrough=False) net.add_edge(src, dst, value=w, physics=False) if (graph_type == 'PyVis'): options = { 'layout': { 'hierarchical': { 'enabled': True, 'levelSeparation': 50, 'treeSpacing': 75, 'nodeSpacing': 500, 'edgeMinimization': False } } } net.options = options connections = net.get_adj_list() for node in net.nodes: node['size'] = len(connections[node['id']]) / 3 node['title'] += ' Neighbors: <br>' + '<br>'.join( connections[node['id']]) node['value'] = len(connections[node['id']]) net.from_nx(graph) net.show('SimilarityVisualizationGraph.html') else: degrees = [val * 10 for (node, val) in graph.degree()] pos = nx.circular_layout(graph) nx.draw(graph, pos, node_size=degrees, with_labels=True, font_size=8) plt.show()
nodes_bf = [(a, b) for a, b, c in selected_edges] #Flatten list of edges tuples to list of nodes nodes = list(itertools.chain(*nodes_bf)) #Remove duplicates from the list nodes_list = list(dict.fromkeys(nodes)) #Add nodes & edges to graph networkgraph.add_nodes(nodes_list, value=[10] * len(nodes_list), title=nodes_list, label=nodes_list) networkgraph.add_edges(selected_edges) #Show to which kinases each kinase is connected #Show to which kinases each kinase is connected kinases_map = networkgraph.get_adj_list() network_map = networkgraph.get_edges() for key, value in kinases_map.items(): kinases_map[key] = ([ functools.reduce(operator.add, ((x, str([(y["width"]) for y in network_map if x in y["from"] and key in y["to"] or x in y["to"] and key in y["from"]])))) for x in value ]) nodes_numerical = {nodes_all[n]: n for n in range(len(nodes_all))} nodes_names = dict(zip(list(nodes_numerical.values()), nodes_all)) edges_numerical = [(nodes_numerical[selected_edges[n][0]], nodes_numerical[selected_edges[n][1]],
def plot(source_csv, result_file_name, fist_line_is_header, settings_mode): got_net = Network(height="100%", width="100%", bgcolor="#222222", font_color="white") if settings_mode: got_net.show_buttons() got_net.set_options(''' var options = { "nodes": { "physics": false }, "edges": { "arrows": { "to": { "enabled": true, "scaleFactor": 0.75 } }, "color": { "inherit": true }, "physics": false, "smooth": false }, "layout": { "hierarchical": { "enabled": true } }, "configure": { "enabled": ''' + str(settings_mode).lower() + ''' }, "physics": { "enabled": false, "hierarchicalRepulsion": { "centralGravity": 0 }, "minVelocity": 0.75, "solver": "hierarchicalRepulsion" } }''') edge_data = extractDataFromCSV(source_csv, fist_line_is_header) for e in tqdm(edge_data, desc="Ectracting data"): src = e[0] dst = e[1] got_net.add_node(src, src, title="<strong>" + src) got_net.add_node(dst, dst, title="<strong>" + dst + "</strong>") got_net.add_edge(src, dst, color="red") neighbor_map = got_net.get_adj_list() # add neighbor data to node hover data for node in tqdm(got_net.nodes, desc="Parsing data"): node["title"] += " Neighbors:</strong><br><ul><li>" + "</li><li>".join( neighbor_map[node["id"]]) + "</li></ul>" node["value"] = len(neighbor_map[node["id"]]) got_net.show(str(result_file_name) + ".html")
def pass_net(df, height="800px", width="100%", name="team"): pass_net = Network( height=height, width=width, bgcolor="FFFFFF", font_color="black", directed=True, notebook=False, ) pass_net.barnes_hut() sources = df["playerName"] targets = df["recieverName"] weights = df["passes"] size = 2 * df["closeness centrality"] color = df["color"] edge_data = zip(sources, targets, weights, size, color) for e in edge_data: src = str(e[0]) dst = str(e[1]) w = e[2] s = e[3] c = e[4] pass_net.add_node(src, src, title=src, size=s, color=c) pass_net.add_node(dst, dst, title=dst, size=s, color=c) pass_net.add_edge(src, dst, value=w) neighbor_map = pass_net.get_adj_list() for node in pass_net.nodes: node["title"] += info_dic[node["title"]] node["value"] = len(neighbor_map[node["id"]]) pass_net.set_options(""" var options = { "nodes": { "borderWidth": 2, "color": { "highlight": { "background": "rgba(217,255,50,1)" } }, "font": { "size": 50, "face": "tahoma" } }, "edges": { "color": { "inherit": true }, "smooth": false }, "physics": { "barnesHut": { "gravitationalConstant": -80000, "springLength": 250, "springConstant": 0.001 }, "minVelocity": 0.75 } } """) pass_net.show("pass_network_" + name + ".html")
def print_graph_web( asssociation_rules , path , minconf ): from pyvis.network import Network import networkx as nx G = Network(height="900px", width="100%", bgcolor="#222222", font_color="white") G.support = {} node_list = [] count_threshold = 0 for gene in asssociation_rules.keys(): for gene_link in asssociation_rules[gene].keys(): if gene_link != 'support' : #le support est enregrister comme une clé dans le dico #remove too hight support """ if asssociation_rules[gene]['support'] > 0.9 or asssociation_rules[gene_link]['support'] > 0.9 : #printandlog( log ,gene, asssociation_rules[gene]['support'], gene_link, asssociation_rules[gene_link]['support']) continue""" if 'lift' in asssociation_rules[gene][gene_link].keys(): if asssociation_rules[gene][gene_link]['lift'] >= 1 and asssociation_rules[gene][gene_link]['confidence'] >= minconf : if gene not in node_list and gene_link not in node_list: G.add_node(gene, title=gene) G.add_node(gene_link, title=gene_link) G.support[gene] = asssociation_rules[gene]['support'] node_list.append( gene) G.add_edge(gene, gene_link, weight = asssociation_rules[gene][gene_link]['lift']) elif gene in node_list and gene_link not in node_list: G.add_node(gene_link, title=gene_link) G.support[gene_link] = asssociation_rules[gene_link]['support'] node_list.append( gene_link) G.add_edge(gene, gene_link, weight = asssociation_rules[gene][gene_link]['lift']) elif gene not in node_list and gene_link in node_list: G.add_node(gene, title=gene) G.support[gene] = asssociation_rules[gene_link]['support'] node_list.append( gene) G.add_edge(gene, gene_link, weight = asssociation_rules[gene][gene_link]['lift']) else: G.add_edge(gene, gene_link, weight = asssociation_rules[gene][gene_link]['lift']) else: count_threshold += 1 printandlog( log , "refused link : " , count_threshold) neighbor_map = G.get_adj_list() # add neighbor data to node hover data for node in G.nodes: node["title"] += " Neighbors:<br>" + "<br>".join(neighbor_map[node["id"]]) node["value"] = len(neighbor_map[node["id"]]) #node_color= [node["value"] for n in G.nodes] #edge_color= [d['weight']*20 for (u, v, d) in G.edges(data=True)] #width = [d['weight']/2 for (u, v, d) in G.edges(data=True)] #nx.draw( G , node_color= node_color , node_cmap=plt.cm.Spectral) #,edge_color=edge_color, edge_cmap=plt.cm.gray,, width = width , node_size=[G.support[n]*4 for n in G.nodes], with_labels=True , font_size=5 #G.show_buttons(filter_=['nodes', 'edges', 'physics']) G.set_options(""" var options = { "edges": { "color": { "inherit": true }, "smooth": false }, "physics": { "forceAtlas2Based": { "gravitationalConstant": -70, "springLength": 100 }, "minVelocity": 0.75, "solver": "forceAtlas2Based" } } """) G.show(path+"/graphSCRNA.html")
class Viewer: def __init__(self): self.file_name_html = "books_connection_viewer.html" self.net = Network(height="100%", width="100%", bgcolor="black", font_color="white") self.net.barnes_hut() self.threshold = 0 def load_data_form_csv_file(self, file_name): self.data = pd.read_csv(file_name, encoding='mac_roman') def set_threshold(self, threshold): self.threshold = threshold def generate_graph(self): sources = self.data['Source'] targets = self.data['Target'] weights = self.data['Weight'] edge_data = zip(sources, targets, weights) weight_dist = defaultdict(list) for edge in edge_data: source = edge[0] target = edge[1] weight = edge[2] if self.threshold < weight: self.net.add_node(source, source, title=f"<h4>{source}</h4>", shape="dot", value=weight) self.net.add_node(target, target, title=f"<h4>{target}</h4>", shape="dot", value=weight) self.net.add_edge(source, target, width=1) weight_dist[source].append(weight) neighbor_map = self.net.get_adj_list() for node in self.net.nodes: node["title"] += "<li>" + "</li><li>".join( '{} [{}]'.format(file, file_w) for file, file_w in zip( neighbor_map[node["id"]], [str("%.2f" % w) for w in weight_dist[node["id"]]])) node["value"] = len(neighbor_map[node["id"]]) def customize_graph(self): self.net.show_buttons(filter_=['physics']) # self.net.show_buttons(filter_=['edges']) # self.net.show_buttons(filter_=['nodes']) def show_graph(self): self.net.show(self.file_name_html) def customize_site_html(self): base = os.path.dirname(os.path.abspath(__file__)) html = open(os.path.join(base, self.file_name_html)) soup = BeautifulSoup(html, 'html.parser') soup.find('body')['style'] = "background-color:black;" soup.find('h1').replace_with('') with open(self.file_name_html, "wb") as f_output: f_output.write(soup.prettify("utf-8"))
def cooc_graph_html_plot(G,html_file,heading, cooc_html_param=None): # 3rd party import import networkx as nx from pyvis.network import Network # Local imports from .BiblioSpecificGlobals import COOC_HTML_PARAM if cooc_html_param==None: cooc_html_param=COOC_HTML_PARAM algo = COOC_HTML_PARAM['algo'] height = COOC_HTML_PARAM['height'] width = COOC_HTML_PARAM['width'] bgcolor = COOC_HTML_PARAM['bgcolor'] font_color = COOC_HTML_PARAM['algo'] def map_algs(g,alg='barnes'): if alg == 'barnes': g.barnes_hut() if alg == 'forced': g.force_atlas_2based() if alg == 'hr': g.hrepulsion() dic_tot_edges ={node:G.degree(node,'nbr_edges') for node in G.nodes} nt = Network(height=height, width=width, bgcolor=bgcolor, font_color=font_color,notebook=False,heading = heading) # populates the nodes and edges data structures nt.from_nx(G) dic_node_label = {str(node['id']):str(node['node_size'])+ '-'\ + node['label'] for node in nt.nodes} map_algs(nt,alg='barnes') for edge in nt.edges: edge['title'] = edge['nbr_edges'] edge['value'] = edge['nbr_edges'] for node in nt.nodes: node['title'] = node['label'] node['size'] = node['node_size'] node['tot_edges'] = dic_tot_edges[node['id']] node['nbr_edges_to'] = {} for edge in nt.edges: if edge['from'] == node['id']: node_to_label = dic_node_label[str(edge['to'])] node['nbr_edges_to'][node_to_label] = edge['nbr_edges'] if edge['to'] == node['id']: node_from_label = dic_node_label[str(edge['from'])] node['nbr_edges_to'][node_from_label]=edge['nbr_edges'] neighbor_map = nt.get_adj_list() dic_label_main = {node['id']: str(node['node_size']) + '-' \ + node['label'] + ' (' \ + str(node['tot_edges']) + ')' for node in nt.nodes} dic_label_neighbors = {} for node in nt.nodes: id = node['id'] dic_label_neighbors[id] = [] for key in node['nbr_edges_to'].keys(): dic_label_neighbors[id].append(key + ' (' + str(node['nbr_edges_to'][key]) + ')') # Sorting neighbors size neighbors_size = [int(dic_label_neighbors[id][i][:dic_label_neighbors[id][i].find('-')]) \ for i in range(len(dic_label_neighbors[id]))] sizes_tup = list(zip(neighbors_size,dic_label_neighbors[id])) sizes_tup = sorted(sizes_tup, key=lambda sizes_tup: sizes_tup[0], reverse=True) dic_label_neighbors[id] = [tup[1] for tup in sizes_tup] # add neighbor data to node hover data for node in nt.nodes: idd = node['id'] title = '<b>'+dic_label_main[idd] + '</b>'+ '<br>' +'<br>'\ .join([dic_label_neighbors[idd][i] for i in range(len(dic_label_neighbors[idd]))]) node['title'] = title nt.show_buttons(filter_=['physics']) nt.show(html_file)
bgcolor="#222222", font_color="white") # set the physics layout of the network got_net.barnes_hut() got_data = pd.read_csv("stormofswords.csv") sources = got_data['Source'] targets = got_data['Target'] weights = got_data['Weight'] edge_data = zip(sources, targets, weights) for e in edge_data: src = e[0] dst = e[1] w = e[2] got_net.add_node(src, src, title=src) got_net.add_node(dst, dst, title=dst) got_net.add_edge(src, dst, value=w) neighbor_map = got_net.get_adj_list() # add neighbor data to node hover data for node in got_net.nodes: node["title"] += " Neighbors:<br>" + "<br>".join(neighbor_map[node["id"]]) node["value"] = len(neighbor_map[node["id"]]) print(len(got_net.nodes)) got_net.show("gameofthrones.html")
class Networker: """ Python class for creating a network graph from the original dataframe. Parameters ---------- data: pandas.core.frame.DataFrame Original dataframe. """ def __init__(self, data): self.edges = data def init_graph(self): """ Initializes a new graph and sets its basic parameters. Returns ------- pyvis.network.Network """ self.nw_ = Network(height="1080px", width="100%", bgcolor="#272651", font_color="white", notebook=True) self.nw_.barnes_hut() self.nw_.set_edge_smooth(smooth_type="horizontal") self.nw_.toggle_hide_edges_on_drag(status=True) return self.nw_ def add_elements(self): """ Adds nodes and weighted edges to initial object. Returns ------- self """ for edge in self.edges: source = edge[0] dist = edge[1] weight = edge[2] self.nw_.add_node(source, source, title=source) self.nw_.add_node(dist, dist, title=dist) self.nw_.add_edge(source, dist, value=weight) return self def get_neighbors(self): """ Finds neighbors for each node in the original graph. Returns ------- pyvis.network.Network """ neighbor_map = self.nw_.get_adj_list() for node in self.nw_.nodes: node['title'] += ":<br>" + "<br>".\ join(neighbor_map[node['id']]) node['value'] = len(neighbor_map[node['id']]) return self def get_info(self): """ Prints basic information about the original graph. """ print("\n\U0001F310 Total nodes:", len(self.nw_.nodes)) print("\n\U0001F310 Total edges:", len(self.nw_.edges)) def show_graph(self): """ Saves an HTML static webpage containing the interactive plot of the obtained graph. Parameters ---------- name: string Name for the output HTML file. Returns ------- pyvis.network.Network """ return self.nw_.show("dp_last_graph.html")