def generate_graph(arbre): got_net = Network(height="100%", width="100%", bgcolor="#222222", font_color="white") dico_couleur = {} for streamer in arbre.streamers: got_net.add_node(streamer.name, value=streamer.poids, shape='image', image=streamer.photo_profil, size=100) dico_couleur[streamer.name] = streamer.couleur for depart, arrivee in arbre.groupes_migrants: for viewer in arbre.groupes_migrants[depart, arrivee]: got_net.add_node(viewer, value=1, color=dico_couleur[depart]) got_net.add_edge(viewer, depart, color=dico_couleur[depart]) got_net.add_edge(viewer, arrivee, color=dico_couleur[arrivee]) got_net.show_buttons() got_net.set_edge_smooth(smooth_type='dynamic') got_net.force_atlas_2based(gravity=-200, central_gravity=0.01, spring_length=1, spring_strength=0.08, damping=0.4, overlap=0) got_net.save_graph("./graphs_v1/" + 'streamgame_v1_42' + ".html") return
class NetDisplay: def __init__(self, net, LinGen, name): self.net = net self.LinGen = LinGen self.Grafo = Network(height="600px", width="1000px") self.name = name self.Grafo.toggle_physics(False) self.Grafo.inherit_edge_colors_from(False) def nodesPlot(self): self.CalcNeuronsYpositions() for layer in self.net: neurons = layer.ReturnNeurons() y_positions = layer.NeuronYPosition for neuron, y_pos in zip(neurons, y_positions): self.Grafo.add_node( neuron, x=layer.number * 100, y=y_pos * 100) i = 0 for con in self.LinGen: if con.enable: if con.weight >= 0: color = 'blue' else: color = 'red' if con.recurrent: dashes = 'true' else: dashes = 'false' try: self.Grafo.add_edge( con.input, con.output, value=abs(con.weight)) self.Grafo.edges[i].update( {'color': color, 'arrows': 'to', 'arrowStrikethrough': 'false', 'title': 'IN: ' + str(con.innovation_number), 'dashes': dashes, 'shadow': dashes}) i += 1 except: pass self.Grafo.show_buttons() self.Grafo.set_edge_smooth('dynamic') self.Grafo.show(self.name + ".html") def CalcNeuronsYpositions(self): for layer in self.net: neuronsYposition = [] size = len(layer.ReturnNeurons()) if size % 2 == 0: for i in range(0, size // 2): neuronsYposition += [i + 0.5, -i - 0.5] else: neuronsYposition = [0] for i in range(1, size // 2 + 1): neuronsYposition += [i, -i] layer.NeuronYPosition = neuronsYposition
def _graph(self): try: counter = {} net = Network(height="100%", width="100%", bgcolor="white", font_color="white") net.force_atlas_2based(gravity=-250, central_gravity=0.005, spring_length=0, spring_strength=0, damping=1, overlap=1) exists = [] for entry in self.edge_data: src = entry['challenger_id'] pokemon = entry['challenger'] if src in exists: continue t = "00" if 'alolan' in pokemon.lower(): t = "61" my_img = '/static/icons/pokemon_icon_%s_%s.png' % (f'{src:03}', t) net.add_node(src, ' ', image=my_img, shape='circularImage', size=50, color={'highlight': {'border': entry['color']}}, borderWidthSelected=5) exists.append(src) fix_list = [346,26,82] for src in fix_list: my_img = '/static/icons/pokemon_icon_%s_%s.png' % (f'{src:03}', t) net.add_node(src, ' ', image=my_img, shape='circularImage', size=50, color={'highlight': {'border': entry['color']}}, borderWidthSelected=5) for entry in self.edge_data: src = entry['challenger_id'] pokemon = entry['challenger'] opponent = entry['opponent'] if opponent.lower() not in self.include: continue if pokemon.lower() not in self.include: continue dst = entry['opponent_id'] w = entry['weight']/10 net.add_edge(src, dst, value=w, arrows='to', arrowStrikethrough=False, smooth=True, color={"color": entry['color'], "highlight": entry['color'], "opacity": 0.05}, selfReferenceSize=50) net.set_edge_smooth('continuous') #net.show_buttons(filter_=['physics']) os.makedirs("/data/%s" % self.config['settings']['cup'], exist_ok=True) net.save_graph("/data/%s/%svs%s.html" % (self.config['settings']['cup'], self.config['settings']['my_shield'], self.config['settings']['op_shield'])) return True except Exception as e: traceback.print_exc() logging.info(e)
def draw_chart(): net = Network("1600px", "1600px", bgcolor="#22222") colors = { "3": "#ffee33", "2": "#00a152", "1": "#2979ff", "0": "#d500f9", } with open(os.path.join(OUTPUTS_DIR, "similarity.csv")) as f: reader = list(csv.reader(f)) reader.pop(0) count_map = defaultdict(int) sizes = [0] * (len(reader) + 1) for row in reader: index, title, cluster, *rows = row for idx, r in enumerate(rows, 1): if index != str(idx) and r != "0": count_map[idx] += 1 for index, value in count_map.items(): sizes[index] = value normalized = min_max_normalize(sizes) for row in reader: index, title, cluster, *rows = row color = colors[cluster] net.add_node( index, index, color=color, size=20 + (normalized[int(index)] * 100), ) for row in reader: index, title, cluster, *rows = row for idx, r in enumerate(rows, 1): if index != str(idx) and r != "0": end_color = colors[cluster] net.add_edge(index, str(idx), color=end_color, weight=float(r)) net.set_edge_smooth("dynamic") net.show_buttons(filter_=["physics"]) # net.show("nx.html") net.show("nx.html")
def show_relations_network_graph(novel_entities: NovelEntities) -> None: print('Displaying relations graph') graph = Network(directed=True, bgcolor="#222222", font_color="white") graph.barnes_hut() graph.set_edge_smooth('dynamic') nodes_dict = {} for named_entity in novel_entities.get_named_entities(): if not any(named_entity.get_kbp_relations()): continue nodes_dict[id(named_entity)] = named_entity value = sum(1 for _ in named_entity.get_as_subject_kbp_relations()) title = named_entity.name if isinstance(named_entity, Character) and named_entity.gender != "UNKNOWN": title += '<br>' + "Gender" + ': ' + named_entity.gender.capitalize( ) for ext_relation in named_entity.get_as_subject_kbp_relations(): relation_desc, _ = __get_relation_name_and_color( ext_relation.relation.relation_str) title += '<br>' + relation_desc.capitalize( ) + ': ' + ext_relation.object_named_entity.name graph.add_node(n_id=id(named_entity), label=named_entity.name, value=value, title=title) for named_entity in novel_entities.get_named_entities(): for ext_relation in named_entity.get_as_subject_kbp_relations(): relation_desc, relation_color = __get_relation_name_and_color( ext_relation.relation.relation_str) # relation_desc += " of" graph.add_edge(id(ext_relation.object_named_entity), id(ext_relation.subject_named_entity), arrowStrikethrough=True, physics=True, title=relation_desc, color=relation_color) graph.show("output/" + novel_entities.name + '.html')
def generate_topo(GlobalVariables, *args, **kwargs): nt = Network(height="490px", width="100%", bgcolor="#FFF", directed=True, notebook=True, heading="") size_multiplier = 1 if "scale" in kwargs: size_multiplier = kwargs["scale"] try: # NE1_IP NE_list = list() LK_list = list() Link_list = list() attr_list = dir(GlobalVariables) for attr in attr_list: if attr == "L3_Testset_IP": testset_label = GlobalVariables.L3_Testset_IP if attr.startswith("NE") or attr.startswith("PT"): chunks = attr.split("_") if len(chunks) == 2 and chunks[0].startswith( "NE") and chunks[1] == "IP": NE_list.append({ "type": "node", "type": "node", "id": chunks[0], "label": getattr(GlobalVariables, attr), "x": -300 + x1, "y": 100 + y1, "title": getattr(GlobalVariables, attr) }) x1 = x1 + 300 ne = ne + 1 elif len(chunks) == 2 and chunks[0].startswith( "PT") and chunks[1] == "IP": NE_list.append({ "type": "node", "id": chunks[0], "label": getattr(GlobalVariables, attr), "x": -150 + x2, "y": 400, "title": getattr(GlobalVariables, attr) }) x2 = x2 + 300 pt = pt + 1 else: if "#" not in getattr(GlobalVariables, attr): continue to = chunks[1] if chunks[1] == "UNI": to = "TS_" + chunks[0] NE_list.append({ "type": "ts", "id": to, "label": testset_label, "x": -300 + tsx, "y": -100, "title": getattr(GlobalVariables, attr) }) tsx += 300 Link_list.append({ "from": chunks[0], "to": to, "label_from": chunks[0] + " (" + getattr(GlobalVariables, attr).split("#")[0] + ")", "label_to": to + " (" + getattr(GlobalVariables, attr).split("#")[1] + ")" }) correction_y = 0 if ne > 2 and pt == 0: correction_y = 300 for NE in NE_list: if NE["type"] == "ts": color = "#1e4c1b" shape = "box" rel = NE["id"].split("_")[1] x_axis = NE["x"], y_axis = NE["y"], for ele in NE_list: if ele["id"] == rel: corr = 0 if int(ele['id'][2:]) % 2 == 0: corr = correction_y if ele["y"] == 100 and corr == 0: x_axis = ele["x"] y_axis = ele["y"] - 200 - corr else: x_axis = ele["x"] y_axis = ele["y"] + 200 + corr else: color = "#366dbf" shape = "box" x_axis = NE["x"] y_axis = NE["y"] if NE["id"].startswith("NE"): if int(NE['id'][2:]) % 2 == 0: y_axis = int(y_axis) + correction_y nt.add_node(NE["id"], shape=shape, color=color, label=f'\n{NE["id"]}\n{NE["label"]}\n', x=x_axis, y=y_axis, title=NE["id"], group=1) for link in Link_list: nt.add_edge(link["from"], link["to"], title=f"{link['label_from']}---{link['label_to']}", label=f"{link['label_from']}---{link['label_to']}" #color="#CDA" ) nt.set_edge_smooth('dynamic') nt.set_options(''' var options = { "autoResize": true, "nodes": { "physics":false, "borderWidth": 0, "borderWidthSelected": 2, "font": { "color": "white", "size": 14 } }, "edges": { "arrows": { "to": { "enabled": true, "scaleFactor": 0 } }, "arrowStrikethrough": true, "color": { "color": "#2f966b", "hover": "#2f966b", "highlight": "#2f966b", "inherit": false }, "font": { "color": "#000", "strokeWidth": 0, "size": 12, "align": "top" }, "hoverWidth": 1.1, "labelHighlightBold": true, "scaling": { "min": 0, "max": 0, "label": { "min": 4, "max": 27, "maxVisible": 44 } }, "selectionWidth": 1.3 }, "interaction": { "multiselect": true, "navigationButtons": true, "tooltipDelay": 75 }, "physics": { } } ''') file_time = str(time())[:10] file_time = "try" file_ref = f"/web/tomcat/webapps/SASFiles/LogFiles/{file_time}.html" file_iref = f"/SASFiles/LogFiles/{file_time}.html" file_iref1 = f"/web/tomcat/webapps/SASFiles/LogFiles/{file_time}.html" nt.show(file_ref) with open(file_iref1) as fp: content = fp.readlines() content = [x.strip() for x in content] data = "" for line in content: if not line.startswith("//"): data = f"{data}{line}" with open(file_iref1, "w") as fp: fp.write(data) os.remove(file_ref) #print(f"<iframe name=\"topology_class[]\" src=\"{file_iref}\" width=\"100%\" height=\"500px\" onfocusin=\"this.contentWindow.network.fit();\"></iframe>") print( f"<div style=\"width:100%;height:500px\"; onfocus=\"this.getElementById('mynetwork').fit()\" >{data}</div>" ) except Exception as e: print(f"Error occured while building topography:{e}")
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")
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": ts_net.set_edge_smooth("continuous") elif net_type == "discrete": ts_net.set_edge_smooth("discrete") # add neighbor data to node hover data
def create_and_return_flow_diagram(request_dict, path_to_reactions=path_to_reactions, path_to_template=path_to_template, csv_results_path=csv_results_path_default): global userSelectedMinMax global minAndMaxOfSelectedTimeFrame global previous_vals global csv_results_path_default logging.info("using csv_results_path: " + csv_results_path) csv_results_path_default = csv_results_path if (('maxMolval' in request_dict and 'minMolval' in request_dict) and (request_dict['maxMolval'] != '' and request_dict['minMolval'] != '') and (request_dict['maxMolval'] != 'NULL' and request_dict['minMolval'] != 'NULL')): userSelectedMinMax = [ float(request_dict["minMolval"]), float(request_dict["maxMolval"])] logging.info("new user selected min and max: " + str(userSelectedMinMax)) if 'startStep' not in request_dict: request_dict.update({'startStep': 1}) if 'maxArrowWidth' not in request_dict: request_dict.update({'maxArrowWidth': 10}) minAndMaxOfSelectedTimeFrame = [999999999999, -1] # load csv file csv = pd.read_csv(csv_results_path) start_step = int(request_dict['startStep']) end_step = int(request_dict['endStep']) # scale with correct scaling function scale_type = request_dict['arrowScalingType'] max_width = request_dict['maxArrowWidth'] previousMin = float(request_dict["currentMinValOfGraph"]) previousMax = float(request_dict["currentMaxValOfGraph"]) previous_vals = [previousMin, previousMax] isPhysicsEnabled = request_dict['isPhysicsEnabled'] if isPhysicsEnabled == 'true': max_width = 2 # change for max width with optimized performance # load species json and reactions json with open(path_to_reactions, 'r') as f: reactions_data = json.load(f) # completely new method of creating nodes and filtering elements selected_species = request_dict['includedSpecies'].split(',') blockedSpecies = request_dict['blockedSpecies'].split(',') (network_content, raw_yields, edgeColors, quantities, minVal, maxVal, raw_yield_values, species_colors, species_sizes, total_quantites, reaction_names_on_hover) = new_find_reactions_and_species( selected_species, reactions_data, blockedSpecies, csv, start_step, end_step, max_width, scale_type, csv_results_path) # add edges and nodes # force network to be 100% width and height before it's sent to page net = Network(height='100%', width='100%', directed=True) # make it so we can manually change arrow colors net.inherit_edge_colors(False) shouldMakeSmallNode = False if isPhysicsEnabled == "true": net.toggle_physics(False) net.force_atlas_2based() else: net.force_atlas_2based(gravity=-200, overlap=1) reac_nodes = network_content['reaction_nodes'] hover_names = reaction_names_on_hover names = [getReactName(hover_names, x) for x in reac_nodes] colors = [species_colors[x] for x in network_content['species_nodes']] if shouldMakeSmallNode: net.add_nodes(names, color=["#FF7F7F" for x in reac_nodes], size=[ 10 for x in list(reac_nodes)], title=names) net.add_nodes(network_content['species_nodes'], color=colors, size=[ 10 for x in list(network_content['species_nodes'])]) else: net.add_nodes(names, color=[ "#FF7F7F" for x in reac_nodes], title=names) net.add_nodes(network_content['species_nodes'], color=colors, size=[species_sizes[x] for x in list( network_content['species_nodes'])]) net.set_edge_smooth('dynamic') # add edges individually so we can modify contents i = 0 values = edgeColors for edge in network_content['edges']: unbeu1 = unbeautifyReaction(edge[0]) unbeu2 = unbeautifyReaction(edge[1]) val = unbeu1+"__TO__"+unbeu2 flux = str(raw_yields[unbeu1+"__TO__"+unbeu2]) colorVal = "" try: colorVal = values[val] except KeyError: colorVal = values[val.replace('->', '-')] if colorVal == "#e0e0e0": # don't allow blocked edge to show value on hover if "→" in edge[0]: be1 = beautifyReaction(reaction_names_on_hover[unbeu1]) net.add_edge(be1, edge[1], color=colorVal, width=edge[2]) elif "→" in edge[1]: try: be2 = beautifyReaction(reaction_names_on_hover[unbeu2]) net.add_edge(edge[0], be2, color=colorVal, width=edge[2]) except KeyError: be2 = beautifyReaction(unbeu2) net.add_edge(edge[0], be2, color=colorVal, width=edge[2]) else: net.add_edge(edge[0], edge[1], color=colorVal, width=edge[2]) else: # hover over arrow to show value for arrows within range # check if value is reaction by looking for arrow if "→" in edge[0]: be1 = beautifyReaction(reaction_names_on_hover[unbeu1]) net.add_edge(be1, edge[1], color=colorVal, width=float( edge[2]), title="flux: "+flux) elif "→" in edge[1]: try: be2 = beautifyReaction(reaction_names_on_hover[unbeu2]) net.add_edge(edge[0], be2, color=colorVal, width=float( edge[2]), title="flux: "+flux) except KeyError: be2 = beautifyReaction(unbeu2) net.add_edge(edge[0], be2, color=colorVal, width=float( edge[2]), title="flux: "+flux) else: net.add_edge(edge[0], edge[1], color=colorVal, width=float(edge[2]), title="flux: "+flux) i = i+1 net.show(path_to_template) if minAndMaxOfSelectedTimeFrame[0] == minAndMaxOfSelectedTimeFrame[1]: minAndMaxOfSelectedTimeFrame = [0, maxVal] with open(path_to_template, 'r+') as f: ############################################# # here we are going to replace the contents # ############################################# a = """<script> network.on("stabilizationIterationsDone", function () { network.setOptions( { physics: false } ); }); </script>""" logging.debug("((DEBUG)) [min,max] of selected time frame: " + str(minAndMaxOfSelectedTimeFrame)) logging.debug("((DEBUG)) [min,max] given by user: "******"""<script> parent.document.getElementById("flow-start-range2").value = "NULL"; parent.document.getElementById("flow-end-range2").value = "NULL"; console.log("inputting NULL");""" else: a = '<script>\ parent.document.getElementById("flow-start-range2").value = \ "'+formattedMinOfSelected+'";' a += 'parent.document.getElementById("flow-end-range2").value = \ "'+str( formattedMaxOfSelected)+'";' a += """ currentMinValOfGraph = """+formattedPrevMin+"""; currentMaxValOfGraph = """+formattedPrevMax+"""; """ if (str(formattedPrevMin) != str(formattedMinOfSelected) or str(formattedPrevMax) != str(formattedMaxOfSelected) or previousMax == 1): logging.debug("previousMin:" + str(formattedPrevMin) + "does not equal " + str(formattedMinOfSelected)) logging.debug("previousMax: " + str(formattedPrevMax) + " does not equal " + str(formattedMaxOfSelected)) logging.debug("previousMin: " + str(previousMin) + " equals 0") logging.debug("previousMax: " + str(previousMax) + " equals 1") a += 'parent.document.getElementById("flow-start-range2").value =\ "'+str(formattedMinOfSelected)+'";\ parent.document.getElementById("flow-end-range2").value =\ "'+str(formattedMaxOfSelected)+'";' a += ('parent.reloadSlider("'+str(formattedMinOfSelected)+'","' + str(formattedMaxOfSelected)+'", "'+str( formattedMinOfSelected)+'", "' + str(formattedMaxOfSelected)+'", '+str(get_step_length(csv_results_path))+');</script>') else: logging.debug("looks like min and max are the same") isNotDefaultMin = int(userSelectedMinMax[0]) != 999999999999 isNotDefaultmax = int(userSelectedMinMax[1]) != -1 block1 = 'parent.document.getElementById("flow-start-range2")' rangeId = block1+'.value = ' if isNotDefaultmax or isNotDefaultMin: a += (rangeId+str( formattedUserMin)+'"; \ '+rangeId+'"'+formattedUserMax+'";') block1 = 'parent.reloadSlider("' + formattedUserMin + '", "' fmos = str(formattedMinOfSelected) block2 = formattedUserMax + '", "' + fmos block3 = '", "' + formattedMaxOfSelected + '", '+str(get_step_length(csv_results_path))+');\ </script>' a += block1 + block2 + block3 else: fmos = formattedMinOfSelected block1 = 'parent.reloadSlider("' + fmos + '", "' block2 = formattedMaxOfSelected + '", "' + str(fmos) a += block1 + '", "' + formattedMaxOfSelected + '", '+str(get_step_length(csv_results_path))+');</script>' if isPhysicsEnabled == 'true': # add options to reduce text size a += \ """<script> var container = document.getElementById("mynetwork"); var options = {physics: false, nodes: { shape: "dot", size: 10, font: {size: 5} } }; var network = new vis.Network(container, data, options); </script>""" lines = f.readlines() for i, line in enumerate(lines): # find a pattern so that we can add next to that line if line.startswith('</script>'): lines[i] = lines[i]+a f.truncate() f.seek(0) # rewrite into the file for line in lines: f.write(line) f.close() # read from file and return the contents with open(path_to_template, 'r') as f: return f.read()
G = Network() G.add_nodes(tics, color =[_.hex_l for _ in colors]) tics_comb = combinations(tics, 2) # pandas dataframe for the similarity matrix M = pd.DataFrame(index=tics, columns=tics) W = pd.DataFrame(index=tics, columns=tics) for _ in tics_comb: d = textdistance.jaro.distance(profile_list[_[0]], profile_list[_[1]]) M[_[1]][_[0]] = M[_[0]][_[1]] = d if d > 0.25: s = 0.0 else: s = np.log(d) / np.log(1 - d) G.add_edge(_[0],_[1], value=s) W[_[1]][_[0]] = W[_[0]][_[1]] = s for _ in tics: W[_][_]=0.0 #G.show_buttons(filter_=['nodes', 'edges', 'layout', 'interaction', 'manipulation', 'physics', 'selection', 'renderer']) G.set_edge_smooth('continuous') G.show_buttons() G.show("G.html") print('done')