def visualize_original_graph_by_netwulf(graph: Graph): G = nx.Graph() G.add_nodes_from(graph.nodes) G.add_edges_from(graph.edges) visualize(G, config={ 'zoom': 2.5, 'display_node_labels': True, 'link_distance': 30, 'node_gravity': 0 })
def visualise_song_graph(song_graph, uri_map): # Make the pretty song map if it doesn't exist already # Usually invoked if this is run as main if uri_map == None: uri_map = {} create_uri_mapping(uri_map, song_graph) # Transform the graph G = nx.Graph(song_graph) H = nx.relabel_nodes(G, uri_map) # Visualise visualize(H)
def test_filtering(self): """Test whether filtering works the way it should.""" G = _get_test_network() weights = [10,100] for e, (u, v) in enumerate(G.edges()): G[u][v]['foo'] = weights[e] G[u][v]['bar'] = weights[(e+1)%2] grp = {u: 'AB'[i%2] for i, u in enumerate(G.nodes()) } new_G = get_filtered_network(G,edge_weight_key='foo') visualize(new_G,is_test=True,config=_get_test_config()) nx.set_node_attributes(G, grp, 'wum') new_G = get_filtered_network(G,edge_weight_key='bar',node_group_key='wum') visualize(new_G,is_test=True,config=_get_test_config())
def visualize_network(G=None): if G is None: # purely for exemplification purposes G = nx.Graph() G.add_node(1) G.add_nodes_from([2, 3]) G.add_edge(2, 4) G.add_edges_from([(1, 2), (1, 3), (1, 4), (3, 4)]) G.remove_edge(1, 3) print(list(G.nodes)) print(list(G.edges)) return visualize(G)
def test_reproducibility(self): """Test whether a restarted network visualization with binded positions results in the same visualization.""" G = _get_test_network() props, config = visualize(G,config=_get_test_config(),is_test=True) bind_properties_to_network(G, props) newprops, newconfig = visualize(G, config=config,is_test=True) # test if node positions are close within 1% and subsequently # round all positional values to the 2nd positon (e.g. 451 => 450) _assert_positions_within_one_percent(props,newprops) _drastically_round_positions(props) _drastically_round_positions(newprops) # the second visualization should have frozen the nodes assert(newconfig['freeze_nodes']) # change it so the dictionary-equal-assertion doesnt fail newconfig['freeze_nodes'] = False self.assertDictEqual(props, newprops) self.assertDictEqual(config, newconfig)
def visualize_coloured_graph_by_netwulf(graph: Graph, colours: []): # we first standardize the graph graph = standardize_graph(graph) # build networkx graph G = nx.Graph() G.add_nodes_from(graph.nodes) G.add_edges_from(graph.edges) # add group for nodes for k, v in G.nodes(data=True): v['group'] = colours[k - 1] network = visualize(G, config={ 'zoom': 2.5, 'display_node_labels': True, 'link_distance': 30, 'node_gravity': 0 })
def test_io(self): G = _get_test_network() props, config = visualize(G,config=_get_test_config(),is_test=True) fn = ".test.json" save(fn,props,config,G=None) props, config, G = load(fn) assert(G is None) save(fn,props,config,G) props, config, G = load(fn) fig, ax = draw_netwulf(props) pl.show(block=False) pl.pause(2) pl.close() # remove test file pathlib.Path(fn).unlink()
def test_config_adaption(self): """Test whether config values are properly adapted.""" config = { # Input/output 'zoom':4, # Physics 'node_charge': -70, 'node_gravity': 0.5, 'link_distance': 15, 'link_distance_variation': 2, 'node_collision': True, 'wiggle_nodes': True, 'freeze_nodes': False, # Nodes 'node_fill_color': '#79aa00', 'node_stroke_color': '#ffffff', 'node_label_color': '#888888', 'display_node_labels': True, 'scale_node_size_by_strength': True, 'node_size': 5, 'node_stroke_width': 1, 'node_size_variation': 0.7, # Links 'link_color': '#758000', 'link_width': 10, 'link_alpha': 0.2, 'link_width_variation': 0.7, # Thresholding 'display_singleton_nodes': False, 'min_link_weight_percentile': 0.1, 'max_link_weight_percentile': 0.9, } G = _get_test_network() _, newconfig = visualize(G,config=config,is_test=True) self.assertDictEqual(config, newconfig)
B = 10 L = 3 N = B**L k = 12 mus = [-1, -.5, -.05, 1] for imu, mu in enumerate(mus): path = Path('data') / ('kleinberg_1d_imu_{}.json'.format(imu)) if not path.exists(): G = sixd.to_networkx_graph( *sixd.random_geometric_kleinberg_network(N, k, mu)) nw, cfg = wulf.visualize(G, config={ 'node_fill_color': '#efefef', 'node_collision': False, 'wiggle_nodes': False, 'scale_node_size_by_strength': True, 'node_size': 8, 'node_stroke_width': 2, 'node_stroke_color': '#000000', }) wulf.save(str(path), nw, cfg, G) else: nw, cfg, G = wulf.load(str(path)) plt.figure() fig, ax = wulf.draw_netwulf(nw) plt.show()
import numpy as np import networkx as nx import netwulf as nw import cMHRN # load edges from txt file and construct Graph object N, edges = cMHRN.fast_mhrn(8,3,7,0.18,True) G = nx.Graph() G.add_edges_from(edges) # visualize and save visualization network, config = nw.visualize(G) nw.save("MHRN.json",network,config)
import networkx as nx from netwulf import visualize import json G = nx.barabasi_albert_graph(1000, 2) props, config = visualize(G, config={ 'Node size by strength': True, 'Collision': True, 'Node size': 25 }) with open('BA_network_properties.json', 'w') as outfile: json.dump(props, outfile)
import networkx as nx from netwulf import visualize G = nx.barabasi_albert_graph(100, m=1) visualize(G)
import matplotlib as matplotlib matplotlib.use("Agg", force=True) import networkx as nx import netwulf as wulf import matplotlib.pyplot as plt g = nx.read_graphml("g") stylized_network, config = wulf.visualize(g) fig, ax = wulf.draw_netwulf(stylized_network) plt.show()
from netwulf.tools import bind_positions_to_network import networkx as nx if __name__ == "__main__": import pprint pp = pprint.PrettyPrinter(indent=4) G = nx.Graph() G.add_nodes_from(range(10)) G.add_nodes_from("abcde") G.add_edges_from([("a", "b")]) from netwulf import visualize props, config = visualize(G) config['Zoom'] = 0.666 pp.pprint(props) pp.pprint(config) bind_positions_to_network(G, props) visualize(G, config=config)
def main(): parser = OptionParser() parser.add_option( "-m", "--model", type="string", dest="ntype", help="Possible network types: 'ring', 'random', 'ws', 'ba'.") parser.add_option("-n", "--nodes", type="int", dest="N", help="Number of nodes in the network.") parser.add_option("-p", "--prob", type="float", dest="p", help="Probability used in generating models.") parser.add_option("--m0", type="int", dest="m0", help="Starting connected nodes for BA model.") parser.add_option("-a", "--advanced", action="store_true", dest="a", default=False, help="Add policymakers and journalists to the model.") parser.add_option( "-s", "--scilinks", type="float", dest="s", help="Percentage of the scientists connected with the other nodes.") (options, args) = parser.parse_args() default_config = { # Input/output 'zoom': 2, # Physics 'node_charge': -45, 'node_gravity': 0.1, 'link_distance': 15, 'link_distance_variation': 0, 'node_collision': True, 'wiggle_nodes': True, 'freeze_nodes': False, # Nodes 'node_fill_color': '#4e4fd4', 'node_stroke_color': '#555555', 'node_label_color': '#000000', 'display_node_labels': True, 'scale_node_size_by_strength': True, 'node_size': 8, 'node_stroke_width': 1.5, 'node_size_variation': 0.8, # Links 'link_color': '#7c7c7c', 'link_width': 2, 'link_alpha': 0.5, 'link_width_variation': 0.5, # Thresholding 'display_singleton_nodes': True, 'min_link_weight_percentile': 0, 'max_link_weight_percentile': 1 } if VERBOSE: print(options) # Sanity check working fine # sanity_check() # Default values p = 0.11 N = 20 m0 = 2 s = 0.25 if options.p: p = options.p if options.N: N = options.N if options.m0: m0 = options.m0 if options.s: s = options.s # Scientists only simulation if options.ntype and not options.a: if options.ntype == 'ring': # Ring Lattice nodes, G, config = generate_ring_lattice(N=N) _network, _ = visualize(G, config=default_config, plot_in_cell_below=False) fig, ax = draw_netwulf(_network) plt.savefig( f"results/{EXPERIMENT}_{options.ntype}_{N}_{p}_{m0}.png") filename = f"{EXPERIMENT}_{options.ntype}_{N}_{p}_{m0}_graph" run_simulation(filename, nodes) if options.ntype == 'random': # Random Network nodes, G, config = generate_random_network(N=N, p=p) _network, _ = visualize(G, config=default_config, plot_in_cell_below=False) fig, ax = draw_netwulf(_network) plt.savefig( f"results/{EXPERIMENT}_{options.ntype}_{N}_{p}_{m0}.png") filename = f"{EXPERIMENT}_{options.ntype}_{N}_{p}_{m0}_graph" run_simulation(filename, nodes) if options.ntype == 'ws': # Watts-Strogatz Network nodes, G, config = generate_watts_strogatz_network(N=N, p=p) _network, _ = visualize(G, config=default_config, plot_in_cell_below=False) fig, ax = draw_netwulf(_network) plt.savefig( f"results/{EXPERIMENT}_{options.ntype}_{N}_{p}_{m0}.png") filename = f"{EXPERIMENT}_{options.ntype}_{N}_{p}_{m0}_graph" run_simulation(filename, nodes) if options.ntype == 'ba': # Barabasi-Albert Network nodes, G, config = generate_barabasi_albert_network(N=N, m0=m0, m=m0) # visualize(G, config=default_config) _network, _ = visualize(G, config=default_config, plot_in_cell_below=False) # fig, ax = draw_netwulf(_network, figsize=(10, 10)) fig, ax = draw_netwulf(_network) # plt.show() plt.savefig( f"results/{EXPERIMENT}_{options.ntype}_{N}_{p}_{m0}.png") filename = f"{EXPERIMENT}_{options.ntype}_{N}_{p}_{m0}_graph" run_simulation(filename, nodes) ################################################### # Advanced simulation: Policymakers and Journalists if options.ntype and options.a: if options.ntype == 'ring': # Ring Lattice nodes, G, config = generate_ring_lattice(N=N) nodes, G = add_policymaker_journalist(nodes, G, s) _network, _ = visualize(G, config=default_config, plot_in_cell_below=False) fig, ax = draw_netwulf(_network) plt.savefig( f"results/{EXPERIMENT}_{options.ntype}_{N}_{p}_{m0}_{s}.png") filename = f"{EXPERIMENT}_{options.ntype}_{N}_{p}_{m0}_{s}_graph" run_simulation(filename, nodes, advanced=True) if options.ntype == 'random': # Random Network nodes, G, config = generate_random_network(N=N, p=p) nodes, G = add_policymaker_journalist(nodes, G, s) _network, _ = visualize(G, config=default_config, plot_in_cell_below=False) fig, ax = draw_netwulf(_network) plt.savefig( f"results/{EXPERIMENT}_{options.ntype}_{N}_{p}_{m0}_{s}.png") filename = f"{EXPERIMENT}_{options.ntype}_{N}_{p}_{m0}_{s}_graph" run_simulation(filename, nodes, advanced=True) if options.ntype == 'ws': # Watts-Strogatz Network nodes, G, config = generate_watts_strogatz_network(N=N, p=p) nodes, G = add_policymaker_journalist(nodes, G, s) _network, _ = visualize(G, config=default_config, plot_in_cell_below=False) fig, ax = draw_netwulf(_network) plt.savefig( f"results/{EXPERIMENT}_{options.ntype}_{N}_{p}_{m0}_{s}.png") filename = f"{EXPERIMENT}_{options.ntype}_{N}_{p}_{m0}_{s}_graph" run_simulation(filename, nodes, advanced=True) if options.ntype == 'ba': # Barabasi-Albert Network nodes, G, config = generate_barabasi_albert_network(N=N, m0=m0, m=m0) nodes, G = add_policymaker_journalist(nodes, G, s) _network, _ = visualize(G, config=default_config, plot_in_cell_below=False) fig, ax = draw_netwulf(_network) plt.savefig( f"results/{EXPERIMENT}_{options.ntype}_{N}_{p}_{m0}_{s}.png") filename = f"{EXPERIMENT}_{options.ntype}_{N}_{p}_{m0}_{s}_graph" run_simulation(filename, nodes, advanced=True)
def sanity_check(): G = nx.Graph() s1 = ScientistNode(1) s2 = ScientistNode(2) s3 = ScientistNode(3) s4 = ScientistNode(4) p1 = PolicymakerNode(5) j1 = JournalistNode(6) # Belief stays the same after 25 iterations # s1.set_belief(0.49360896462333026) # s2.set_belief(0.42888114975493140) # s3.set_belief(0.22176380692356368) # Belief does not converge in 25 iterations # s1.set_belief(0.001) # s2.set_belief(0.0002) # s3.set_belief(0.5) # Interesting test -> The policy maker still converges s1.set_belief(0.55) s2.set_belief(0.6) s3.set_belief(0.1) s4.set_belief(0.1) s1.define_neighbours([s4, s2]) s2.define_neighbours([s1, s3]) s3.define_neighbours([s2, s4]) s4.define_neighbours([s3, s1]) G.add_edge(1, 2) G.add_edge(1, 4) G.add_edge(2, 3) G.add_edge(3, 4) p1.define_neighbours([s3, j1]) j1.define_neighbours([s3, s4]) G.add_edge(5, 3) G.add_edge(5, 1) G.add_edge(6, 3) G.add_edge(6, 4) # group colors for k, v in list(G.nodes(data=True))[:-2]: v['group'] = "blue" list(G.nodes(data=True))[-2][1]['group'] = "green" list(G.nodes(data=True))[-1][1]['group'] = "red" visualize(G) for n_ in [s1, s2, s3, s4, p1, j1]: print(n_) average_beliefs = [] average_beliefs.append({ "label": "Aggregated Avg Belief", "values": [np.mean([s.belief for s in [s1, s2, s3, s4, p1, j1]])] }) average_beliefs.append({ "label": "Scientists Avg Belief", "values": [np.mean([s.belief for s in [s1, s2, s3, s4]])] }) average_beliefs.append({ "label": "Policymakers Avg Belief", "values": [p1.belief] }) average_beliefs.append({ "label": "Journalist Avg Belief", "values": [j1.belief] }) timesteps = [0] for t_ in range(25): for s in [s1, s2, s3, s4, j1]: # print(s) s.act() for s in [s1, s2, s3, s4, j1, p1]: # print(s) s.update_belief() average_beliefs[0]["values"].append( np.mean([s.belief for s in [s1, s2, s3, s4, p1, j1]])) average_beliefs[1]["values"].append( np.mean([s.belief for s in [s1, s2, s3, s4]])) average_beliefs[2]["values"].append(p1.belief) average_beliefs[3]["values"].append(j1.belief) timesteps.append(t_ + 1) for n_ in [s1, s2, s3, s4, p1, j1]: print(n_) generate_belief_graph('Convergence of average belief', timesteps, *average_beliefs)
import sixdegrees as sixd import netwulf as wulf from pathlib import Path import matplotlib.pyplot as plt B = 10 L = 3 N = B**L k = 12 mus = [-1, -.5, -.15, 1] for imu, mu in enumerate(mus): path = Path('data') / ('modular_hierarchical_imu_{}.json'.format(imu)) if not path.exists(): G = sixd.to_networkx_graph( *sixd.modular_hierarchical_network(B, L, k, mu)) nw, cfg = wulf.visualize(G, config={'node_color': '#dddddd'}) wulf.save(str(path), nw, cfg, G) else: nw, cfg, G = wulf.load(str(path)) plt.figure() fig, ax = wulf.draw_netwulf(nw) plt.show()
def Plague(G=None, Gtype='erdos', erdosval=0.15, node_num=50, mode='Game', ethics='Good', difficulty='Brutal', starttype='random', starters=None, numstarters=4, vaccines='on', quarantines='on', antivax=0, vaxcost=100, startermoney=500, allowance=200, quarantinecost=300, beta=0.6, gamma=0.3, curechance=0, icost=50, dcost=50, ccost=300, zcost=400, betainc=0.02, gammadec=0.02, campchance=0.1): turnNum = 0 money = startermoney gameOver = False if ((mode != 'Game' and mode != 'Simulation') or (Gtype != 'erdos') or (difficulty != 'Baby' and difficulty != 'Custom' and difficulty != 'Normal' and difficulty != 'Brutal' and difficulty != 'Mega Brutal' and difficulty != 'Impossible') or (starttype != 'random' and starttype != 'choice' and starttype != 'high degree') or (vaccines != 'on' and vaccines != 'off') or (quarantines != 'on' and quarantines != 'off')): raise Exception("Something is wrong with your inputs. ") if (starters != None): numstarters = len(starters) if (difficulty == 'Baby'): if (ethics == 'Good'): startermoney = 600 allowance = 300 vaxcost = 100 quarantinecost = 300 beta = 0.5 gamma = 0.5 if (ethics == 'Evil'): G = nx.erdos_renyi_graph(30, 0.25) startermoney = 600 allowance = 300 if (difficulty == 'Normal'): if (ethics == 'Good'): startermoney = 500 allowance = 250 beta = 0.5 gamma = 0.25 if (ethics == 'Evil'): G = nx.erdos_renyi_graph(40, 0.15) startermoney = 500 allowance = 150 if (difficulty == 'Brutal'): if (ethics == 'Good'): startermoney = 500 allowance = 150 beta = 0.6 gamma = 0.25 if (ethics == 'Evil'): G = nx.erdos_renyi_graph(40, 0.05) startermoney = 500 allowance = 100 if (G == None): G = nx.erdos_renyi_graph(node_num, erdosval) if (difficulty == 'Mega Brutal'): if (ethics == 'Good'): G = nx.erdos_renyi_graph(70, 0.08) startermoney = 500 allowance = 100 vaxcost = 100 quarantinecost = 300 beta = 0.75 gamma = 0.1 antivax = 0.2 numstarters = 4 starttype = 'random' campchance = 0.1 # 4 random starters if (ethics == 'Evil'): G = nx.erdos_renyi_graph(70, 0.05) startermoney = 400 allowance = 100 icost = 50 dcost = 50 ccost = 300 zcost = 400 betainc = 0.02 gammadec = 0.02 numstarters = 3 starttype = 'random' if (difficulty == 'Impossible'): if (ethics == 'Good'): G = nx.erdos_renyi_graph(70, 0.15) startermoney = 200 allowance = 50 vaxcost = 100 quarantinecost = 300 beta = 1 gamma = 0.1 antivax = 0.4 numstarters = 6 starttype = 'high degree' campchance = 0.1 if (ethics == 'Evil'): G = nx.erdos_renyi_graph(70, 0.02) startermoney = 200 allowance = 50 icost = 50 dcost = 50 ccost = 300 zcost = 400 betainc = 0.02 gammadec = 0.02 numstarters = 1 starttype = 'random' if (mode == 'Simulation'): vaccines = 'off' quarantines = 'off' ethics = 'Good' # numstarters z = np.zeros(G.number_of_nodes()) # Tested all start types. Works. if (starttype == 'random'): #initialize z randomly a = random.sample(range(0, G.number_of_nodes()), numstarters) for i in a: z[i] = 1 #print(z) elif (starttype == 'high degree'): count = copy.deepcopy(numstarters) finals = [] eye = [] jay = [] for i in G.nodes(): eye.append(i) jay.append(G.degree[i]) #print(jay) while (count != 0): loc = jay.index(max(jay)) finals.append(loc) #print(loc[0]) jay[loc] = -1 count -= 1 #print(count) #print(jay) for i in finals: #print(i) z[i] = 1 #print(z) #print(jay) elif (starttype == 'choice'): for i in starters: z[i] = 1 #print(z) def Menu(): if (ethics == 'Good'): print('Turn number - ' + str(turnNum)) print('Money - ' + str(money)) print('\nCommands: ') print('N - Visualize netwulf representation') if (quarantines == 'on'): print('Q - Quarantine a node') if (vaccines == 'on'): print('V - Vaccinate a node') print('P - Progress to the next turn') print('H - View the help menu') print('E - Exit the game') elif (ethics == 'Evil'): print('Turn number - ' + str(turnNum)) print('Money - ' + str(money)) print('\nCommands: ') print('N - Visualize netwulf representation') print('I - Make your disease more infectious') print('D - Make your disease less deadly') print('C - Create an anti-vaxx marketing campaign') print('Z - Infect a node') print('P - Progress to the next turn') print('H - View the help menu') print('E - Exit the game') else: raise Exception("ethics is not correctly specified.") inp = input() return (inp) while (gameOver == False): #start of a turn #print("are you looping") turnNum += 1 money += allowance turnOver = False while (turnOver == False): inp = Menu() if (inp == 'N'): netwulf.visualize(zToG(G, z)) elif (inp == 'P'): turnOver = True elif (inp == 'E'): raise Exception("You are a quitter.") elif (inp == 'H'): print("A few tips:") print( "In the netwulf interface, press 'post to python' to exit. Otherwise it might glitch." ) print( "Green nodes are susceptible, yellow nodes are infected, and red nodes are dead." ) print( "Blue nodes are immune, black nodes are quarantined, and pink nodes are anti-vaxx." ) print("Quarantined nodes update at the end of each turn.") print( "More information can be found on the github page: https://github.com/thekadenh/betternx/" ) if (ethics == 'Good'): if (inp == 'Q'): yn = input( str("Do you want to quarantine a node for $" + str(quarantinecost) + "? (y/n)")) if (yn == 'y'): if (money >= quarantinecost): money -= quarantinecost q = input("Which node do you want to quarantine? ") q = int(q) zq = z[q] if (zq == 2): print( str(q) + " is literally dead. You're quarantining a dead person. Nice one." ) if (zq == 3): print( str(q) + " can't get the virus. No idea why you're quarantining it but you do you." ) if (zq == 4): print( "I mean... technically you CAN quarantine " + str(q) + " twice... It's not against the rules or anything..." ) if (zq == 5): print("Excellent choice") z[q] = 4 else: z[q] = 4 else: print("Sorry, you're too poor") elif (inp == 'V'): yn = input( str("Do you want to vaccinate a node for $" + str(vaxcost) + "? (y/n)")) if (yn == 'y'): if (money >= vaxcost): money -= vaxcost q = input("Which node do you want to vaccinate? ") q = int(q) zq = z[q] if (zq == 1): print( str(q) + " is already infected, dummy. Vaccination doesn't do anything at this point." ) elif (zq == 2): print(str(q) + "... They're dead.") elif (zq == 3): print("You make... questionable... decisions.") elif (zq == 4): print("They're quarantined.") elif (zq == 5): print( "They refuse, citing the 100% true nonrefutable fact that vaccinations cause autism." ) else: z[q] = 3 else: print("Sorry, you're too poor") elif (ethics == 'Evil'): if (inp == 'I'): yn = input( str("Do you want to increase beta by " + str(betainc) + " for $" + str(icost) + "? (y/n)")) if (yn == 'y'): if (money >= icost): beta = beta + betainc money -= icost else: print("Sorry, you're too poor") elif (inp == 'D'): yn = input( str("Do you want to decrease gamma by " + str(gammadec) + " for $" + str(dcost) + "? (y/n)")) if (yn == 'y'): if (money >= dcost): gamma = gamma - gammadec money -= dcost else: print("Sorry, you're too poor") elif (inp == 'C'): yn = input( str("Do you want to fund an anti-vax campaign for $" + str(ccost) + "? (y/n)")) if (yn == 'y'): if (money >= ccost): money -= ccost for i in G.nodes(): if (z[i] == 0): if (random.random() < campchance): z[i] == 5 else: print("Sorry, you're too poor") elif (inp == 'Z'): yn = input( str("Do you want to infect ANY node for $" + str(zcost) + "? (y/n)")) if (yn == 'y'): if (money >= zcost): money -= zcost nod = input( str("Which node would you like to infect?")) nod = int(nod) znod = z[nod] if (znod == 2): print( "You brought back node " + str(nod) + " from the dead. The zombie apocalypse is imminent!" ) z[nod] = 1 if (znod == 3): print( "You used voodoo magic to anti-vaccinate node " + str(nod) + ".") z[nod] = 1 if (znod == 4): print("You successfully broke node " + str(nod) + " out of the quarantine!") z[nod] = 1 if (znod == 5): print( "I mean... node " + str(nod) + " basically wanted to get infected anyway") z[nod] = 1 else: z[nod] = 1 else: print("Sorry, you're too poor") # at the end of the turn cycle through the quarantined ones and separate the edges. # bunch=[(1,2),(2,3)] # G.remove_edges_from(ebunch) if (turnOver == True): for i, j in enumerate(z): if (j == 4): for k in G.nodes(): G.remove_edges_from([(i, k)]) #Then, run a cycle of the thingy z2 = copy.deepcopy(z) for i, j in enumerate(z): if (j == 1): # it's infected, time to spread! for k in G.edges(i): if (z[k[1]] == 0 or z[k[1]] == 5): if (random.random() < beta): z2[k[1]] = 1 if (random.random() < gamma): z2[i] = 2 z = z2 if not 1 in z: gameOver = True #drawGz(G, z) sus = 0 dead = 0 recovered = 0 qud = 0 antvd = 0 for i in z: if (i == 0): sus += 1 if (i == 2): dead += 1 if (i == 3): recovered += 1 if (i == 4): qud += 1 if (i == 5): antvd += 1 print("Game over! Thanks for playing.") print( "I'm not going to tell you how well you did. That's for you to decide." ) print("However, these stats may offer some insight.\n") print("# Susceptible: " + str(sus)) print("# Dead: " + str(dead)) print("# Vaccinated or recovered: " + str(recovered)) print("# Quarantined: " + str(qud)) print("# Alive Anti-vaxxers: " + str(antvd))
def runCharikar(self): print('Start Charikar') #outputDirectoryPath=self.parameters['outputfolder'] outputDirectoryPath = os.getcwd() alignmentGraphPickle = outputDirectoryPath + "alignmentGraph.gz2" # Compressed Pickle file of the DCS graph dcsGraphPickle = outputDirectoryPath + "dcs.gz2" # Txt file of the DCS graph GraphAlignment = outputDirectoryPath + "alignment.txt" dcsGraphTxt = outputDirectoryPath + "dcs.txt" #try: extra_window = tk.Toplevel(self.topwindow) extra_window.title("Visualizer") label2 = tk.Label(extra_window, text="""Charikar""") label2.pack() # STEP ONE: build the graphs # Builds the weighted graph W print(datetime.now(), " --> build weighted graph W...") W = buildGraph(self.parameters['pathconceptualfile'], skipLines=0, splitSep=" ", weightedEdges=True) print(datetime.now(), " --> W: nodes ", len(W.nodes()), " edges: ", len(W.edges())) visualize(W) # Stores the weighted graph in a pickle file # nx.write_gpickle(W, weightedGraphPickle) # UNCOMMENT this line if you want to save a graph # Builds the unweighted graph U print(datetime.now(), " --> build unweighted graph U...") print(self.parameters['pathphysicalfile']) U = buildGraph(self.parameters['pathphysicalfile'], skipLines=0, splitSep=" ", weightedEdges=False) print(datetime.now(), " --> U: nodes ", len(U.nodes()), " edges: ", len(U.edges())) visualize(U) # Stores the unweighted graph in a pickle file # nx.write_gpickle(U, unweightedGraphPickle) # UNCOMMENT this line if you want to save a graph # STEP TWO # Builds the alignment graph A print(datetime.now(), " --> build alignment graph A...") A = pairwiseAlignment(U, W, k=5, simTxt=self.parameters['pathsimilarityfile'], skipLines=0, splitSep="-") print(datetime.now(), " --> alignGraph A: nodes ", len(A.nodes()), " edges: ", len(A.edges())) # Stores the alignment graph in a pickle file #nx.write_gpickle(A, alignmentGraphPickle) # COMMENT this line if you don't want to save a graph # LAST STEP # Extracts the DCS from the alignment graph print(datetime.now(), " --> Search DCS in alignment graph...") dcsA = extractDCS(A) # Stores the DCS graph of A in a pickle file nx.write_gpickle(dcsA, dcsGraphPickle) dcsnx = nx.Graph(dcsA) visualize(dcsnx) # Stores the DCS graph of A in a text file print(A) #with open(GraphAlignment,"w") as txt: # for edg1, edg2 in A.nodes: # print(edg1+" "+edg2+" "+str(A[edg1][edg2]['weight'])) #print(edg1) #txt.write(edg1+" "+edg2+" "+str(A[edg1][edg2]['weight'])+"\n") print(GraphAlignment) nx.write_weighted_edgelist(A, GraphAlignment) #except: print('Error') return
def test_dict(self): props, config = visualize({'nodes':[{'id':0},{'id':1},{'id':2},{'id':3}],'links':[{'source':0, 'target':1}]},is_test=True) assert(props is not None)
def test_posting(self): """Test whether results are sucessfully posted to Python.""" G = _get_test_network() visualize(G,is_test=True,config=_get_test_config())
def getGraphRepresentation(): masters = ["pgmaster{}".format(i) for i in range(N_MASTERS)] main_slaves = ["pgslave{}-0".format(i) for i in range(N_REPLICAS)] master_links = [("pgmaster{}".format(i % N_MASTERS), "pgslave{}-0".format(i)) for i in range(N_REPLICAS)] utilities = ["pgpool", "barman"] utilities_links = [("pgmaster0", "barman")] + [ ("pgpool", "pgmaster{}".format(i)) for i in range(N_MASTERS) ] pgpool_links = [("pgpool", "pgslave{}-0".format(i)) for i in range(N_REPLICAS)] secondary_slaves = [] secondary_links = [] for rep_group_id in range(0, N_REPLICAS): for slave_id in range(1, REPLICA_SIZE): secondary_slaves.append("pgslave{}-{}".format( rep_group_id, slave_id)) secondary_links.append( ("pgslave{}-0".format(rep_group_id), "pgslave{}-{}".format(rep_group_id, slave_id))) pgpool_links.append( ("pgpool", "pgslave{}-{}".format(rep_group_id, slave_id))) G = nx.DiGraph() G.add_nodes_from(masters, size=18) G.add_nodes_from(utilities, size=18) G.add_nodes_from(main_slaves, size=8) G.add_nodes_from(secondary_slaves, size=2) G.add_edges_from(master_links, weight=4) G.add_edges_from(secondary_links, weight=2) G.add_edges_from(utilities_links, weight=1) G.add_edges_from(pgpool_links, weight=1) # nx.draw(G, with_labels=True, pos=nx.spring_layout(G, k=0.25, iterations=50)) pos = nx.spring_layout(G, iterations=43) nx.draw_networkx_nodes(G, pos, nodelist=masters, cmap=plt.get_cmap('jet'), node_color='#0064a5', node_size=1000) nx.draw_networkx_nodes(G, pos, nodelist=utilities, cmap=plt.get_cmap('jet'), node_color='#336791', node_size=[1500, 700]) nx.draw_networkx_nodes(G, pos, nodelist=main_slaves, cmap=plt.get_cmap('jet'), node_color='#008bb9', node_size=500) nx.draw_networkx_nodes(G, pos, nodelist=secondary_slaves, cmap=plt.get_cmap('jet'), node_color='#005996', node_size=200) nx.draw_networkx_labels(G, pos) nx.draw_networkx_edges(G, pos, edgelist=master_links, arrows=False, style='dashed') nx.draw_networkx_edges(G, pos, edgelist=secondary_links, arrows=True) nx.draw_networkx_edges(G, pos, edgelist=utilities_links, arrows=True) nx.draw_networkx_edges(G, pos, edgelist=pgpool_links, arrows=True) nw.visualize(G)
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Fri Mar 20 10:08:09 2020 @author: f """ #%% Importaciones import networkx as nx from datos_metro import bruto from funciones_propias_redes import crea_red import netwulf #%% G=crea_red(bruto, nx) netwulf.visualize(G,is_test=True) # Si no le digo que es un test, peta y no vuelve xD
def prepare_graph(): for i in range(df_size): movie = get_title_from_index(i) if not MG.has_node(movie): MG.add_node(movie, group='movie') MG.add_node(get_similar(movie), group='movie') MG.add_edge(movie, get_similar(movie), group='edge') print(movie + " -> " + get_similar(movie)) cast = credits[credits.id == int(row_to_id[i])]['cast'][i] res = ast.literal_eval(cast) cast_mem = [] for j in range(len(res)): if (j > 2): break cast_mem.append(res[j]['name']) all_cast.extend(cast_mem) for k in range(len(cast_mem)): if not MG.has_node(cast_mem[k]): MG.add_node(cast_mem[k], group='actor') MG.add_edge(cast_mem[k], movie, group='edge') if __name__ == '__main__': calculate_ids() cosine_sim = calc_cosine_sim() prepare_graph() print(MG) visualize(MG)
import networkx as nx from netwulf import visualize from netwulf import get_filtered_network import numpy as np G = nx.barabasi_albert_graph(100, 2) for u, v in G.edges(): G[u][v]['foo'] = np.random.rand() G[u][v]['bar'] = np.random.rand() grp = {u: 'ABCDE'[u % 5] for u in G.nodes()} new_G = get_filtered_network(G, edge_weight_key='foo') visualize(new_G) nx.set_node_attributes(G, grp, 'wum') new_G = get_filtered_network(G, edge_weight_key='bar', node_group_key='wum') visualize(new_G)
def make_model_network(combined_analysis_output_dir, adj_mat_dir, drop_eqless=0.00, colour_by_motif=False, use_nearest_neighbour=False, use_adjacent_neighbour=False): if use_nearest_neighbour: output_name = "nearest_neighbour_vis.pdf" elif use_adjacent_neighbour: output_name = "adjacent_neighbour_vis.pdf" if use_nearest_neighbour and use_adjacent_neighbour: print("use only one of nearest or adjacent neighbour") exit() model_space_report_path = combined_analysis_output_dir + "combined_model_space_report_with_motifs.csv" adj_matrix_path_template = adj_mat_dir + "model_#REF#_adj_mat.csv" model_space_report_df = pd.read_csv(model_space_report_path) model_space_report_df = model_space_report_df.sort_values('model_idx') model_idxs = model_space_report_df['model_idx'].values model_marginals = model_space_report_df['model_marginal_mean'].values flat_adj_mats = [] # Load and flatten all adj mats for m_idx in model_idxs: model_self_limiting_count = 0 adj_mat_path = adj_matrix_path_template.replace("#REF#", str(m_idx)) adj_mat_df = pd.read_csv(adj_mat_path, index_col=0) flat_adj_mats.append(adj_mat_df.values.flatten()) model_connectivity = np.zeros(shape=(len(flat_adj_mats), len(flat_adj_mats))) for m_idx in model_idxs: if use_nearest_neighbour: neighbours = find_nearest_neighbours(flat_adj_mats[m_idx], flat_adj_mats) elif use_adjacent_neighbour: neighbours = find_adjacent_neighbours(flat_adj_mats[m_idx], flat_adj_mats) for n in neighbours: model_connectivity[m_idx, n] = 1 graph = nx.convert_matrix.from_numpy_matrix(model_connectivity) max_marginal = np.max(model_marginals) min_marginal = 0 scale_max = 50 scale_min = 10 node_sizes = [ min_max_scaling(scale_min, scale_max, min_marginal, max_marginal, x) for x in model_marginals ] if colour_by_motif: col_blue = '#1d71b8' # SL blue col_red = '#ac182b' # OL red col_grey = '#706f6f' # Mixed grey model_space_report_df = make_model_motif_colours(model_space_report_df, col_SL_only=col_blue, col_OL_only=col_red, col_mixed=col_grey) node_colours = model_space_report_df['node_type'].values else: node_colours = ['#73ba65' for _ in model_idxs] # #1d71b8 # #ac182b - OL red # #706f6f - grey for n, data in graph.nodes(data=True): data['size'] = node_sizes[n] data['color'] = node_colours[n] print(data) vis_config = two_species_vis_parameters() graph, config = netwulf.visualize(graph, config=vis_config, plot_in_cell_below=False, is_test=False) if colour_by_motif: output_name = output_name + "_col" output_name = output_name + ".pdf" output_path = combined_analysis_output_dir + output_name print("plotting network... ") fig, ax = netwulf.draw_netwulf(graph, figsize=15.0) fig.tight_layout() plt.savefig(output_path)