Beispiel #1
0
 def testReingoldTilford(self):
     g = Graph.Barabasi(100)
     lo = g.layout("rt")
     ys = [coord[1] for coord in lo]
     root = ys.index(0.0)
     self.assertEqual(ys, g.shortest_paths(root)[0])
     g = Graph.Barabasi(100) + Graph.Barabasi(50)
     lo = g.layout("rt", root=[0, 100])
     self.assertEqual(lo[100][1] - lo[0][1], 0)
     lo = g.layout("rt", root=[0, 100], rootlevel=[2, 10])
     self.assertEqual(lo[100][1] - lo[0][1], 8)
Beispiel #2
0
    def testFruchtermanReingold(self):
        g = Graph.Barabasi(100)

        lo = g.layout("fr")
        self.assertTrue(isinstance(lo, Layout))

        lo = g.layout("fr", miny=range(100))
        self.assertTrue(isinstance(lo, Layout))
        self.assertTrue(all(lo[i][1] >= i for i in xrange(100)))

        lo = g.layout("fr", miny=range(100), maxy=range(100))
        self.assertTrue(isinstance(lo, Layout))
        self.assertTrue(all(lo[i][1] == i for i in xrange(100)))

        lo = g.layout("fr",
                      miny=[2] * 100,
                      maxy=[3] * 100,
                      minx=[4] * 100,
                      maxx=[6] * 100)
        self.assertTrue(isinstance(lo, Layout))
        bbox = lo.bounding_box()
        self.assertTrue(bbox.top >= 2)
        self.assertTrue(bbox.bottom <= 3)
        self.assertTrue(bbox.left >= 4)
        self.assertTrue(bbox.right <= 6)
Beispiel #3
0
 def testKamadaKawai(self):
     g = Graph.Barabasi(100)
     lo = g.layout("kk", miny=[2]*100, maxy=[3]*100, minx=[4]*100, maxx=[6]*100)
     self.assertTrue(isinstance(lo, Layout))
     bbox = lo.bounding_box()
     self.assertTrue(bbox.top >= 2)
     self.assertTrue(bbox.bottom <= 3)
     self.assertTrue(bbox.left >= 4)
     self.assertTrue(bbox.right <= 6)
Beispiel #4
0
    def __preprocess(self):
        for i in range(self.__num_graph):
            self.__graph_stream[i] = Graph.Barabasi(self.__graph_size,
                                                    self.__out_degree)

        self.__structural_information_distances = np.zeros(self.__num_graph -
                                                           1)
        self.__von_Neumann_distances = np.zeros(self.__num_graph - 1)
        self.__veo_distances = np.zeros(self.__num_graph - 1)
        self.__delta_con_distances = np.zeros(self.__num_graph - 1)
Beispiel #5
0
 def testIsDAG(self):
     g = Graph(5, [(0, 1), (0, 2), (1, 2), (1, 3), (2, 3)], directed=True)
     self.assertTrue(g.is_dag())
     g.to_undirected()
     self.assertFalse(g.is_dag())
     g = Graph.Barabasi(1000, 2, directed=True)
     self.assertTrue(g.is_dag())
     g = Graph.GRG(100, 0.2)
     self.assertFalse(g.is_dag())
     g = Graph.Ring(10, directed=True, mutual=False)
     self.assertFalse(g.is_dag())
def make_g(t):
    if t == 1:
        ws1, ws2, ws3, ws4 = 1, randrange(50, 250), randrange(2, 10), random()
        b = Graph.Watts_Strogatz(ws1, ws2, ws3, ws4)
        name = 'WS_' + '_'.join(map(str, [ws1, ws2, ws3, ws4]))
    if t == 2:
        bar1 = randrange(500, 1000)
        bar2 = int(round(bar1 * 0.01 * random())) + 1
        b = Graph.Barabasi(bar1, [randrange(bar2) for i in range(bar1)])
        name = 'BAR_' + '_'.join(map(str, [bar1, bar2]))
    if t == 3:
        er1 = randrange(50, 500)
        er2 = randrange(er1, 1000)
        b = Graph.Erdos_Renyi(n=er1, m=er2, directed=False, loops=False)
        name = 'ER_' + '_'.join(map(str, [er1, er2]))
    if t == 4:
        nnn = randrange(50, 500)
        gamma = randrange(200, 300) / 100.0
        ok = 'no'
        while ok == 'no':
            try:
                b = config(nnn, gamma)
                ok = 'yes'
            except:
                pass
        if gamma > 2.5:
            name = 'CONF1_' + '_'.join(map(str, [nnn, gamma]))
        else:
            name = 'CONF2_' + '_'.join(map(str, [nnn, gamma]))


#		la1,la2,la3=randrange(5,25),randrange(5,25),randrange(1,5)
#		b=Graph.Lattice([la1,la2], nei=la3, directed=True, mutual=True, circular=True)
#		name='LAT_'+'_'.join(map(str,[la1,la2,la3]))
    if t != 4:
        g = [list(i.tuple) for i in b.es]
    else:
        g = [list(i) for i in b.edges()]
    #print len(g)
    rec = round(random(), 1)
    gg = make_rec(g, rec)
    b = Graph.TupleList(gg, directed=True)
    vvv, eee, diam, clust = b.vcount(), b.ecount(), b.diameter(
    ), b.transitivity_undirected()
    eig = GH(b)
    rob, rob_max = R_pr(g)
    return g, name.split('_')[0], '_'.join(name.split('_')[1:]), float(
        eig), vvv, eee, diam, clust, rob, rob_max, rec
Beispiel #7
0
def plot_ba():
    """Plots a visualization of an B-A scale-free graph"""
    g = Graph.Barabasi(n=150)
    visual_style = {
        "bbox": (3000, 3000),
        "margin": 100,
        "vertex_color": 'blue',
        "vertex_size": 50,
        "vertex_label_size": 10,
        "edge_curved": False,
        "edge_color": 'black',
        "edge_width": 7
    }
    layout = g.layout("fr")
    visual_style["layout"] = layout
    save_name = f'ba_layout.png'
    plot(g, SAVE_PATH + save_name, **visual_style)
Beispiel #8
0
 def testFruchtermanReingold(self):
     g = Graph.Barabasi(100)
     lo = g.layout("fr")
     self.failUnless(isinstance(lo, Layout))
     lo = g.layout("fr", miny=range(100))
     self.failUnless(isinstance(lo, Layout))
     lo = g.layout("fr", miny=range(100), maxy=range(100))
     self.failUnless(isinstance(lo, Layout))
     lo = g.layout("fr",
                   miny=[2] * 100,
                   maxy=[3] * 100,
                   minx=[4] * 100,
                   maxx=[6] * 100)
     self.failUnless(isinstance(lo, Layout))
     bbox = lo.bounding_box()
     self.failUnless(bbox.top >= 2)
     self.failUnless(bbox.bottom <= 3)
     self.failUnless(bbox.left >= 4)
     self.failUnless(bbox.right >= 6)
    def testAuto(self):
        def layout_test(graph, test_with_dims=(2, 3)):
            lo = graph.layout("auto")
            self.assertTrue(isinstance(lo, Layout))
            self.assertEqual(len(lo[0]), 2)
            for dim in test_with_dims:
                lo = graph.layout("auto", dim=dim)
                self.assertTrue(isinstance(lo, Layout))
                self.assertEqual(len(lo[0]), dim)
            return lo

        g = Graph.Barabasi(10)
        layout_test(g)

        g = Graph.GRG(101, 0.2)
        del g.vs["x"]
        del g.vs["y"]
        layout_test(g)

        g = Graph.Full(10) * 2
        layout_test(g)

        g["layout"] = "graphopt"
        layout_test(g, test_with_dims=())

        g.vs["x"] = list(range(20))
        g.vs["y"] = list(range(20, 40))
        layout_test(g, test_with_dims=())

        del g["layout"]
        lo = layout_test(g, test_with_dims=(2,))
        self.assertEqual(
            [tuple(item) for item in lo],
            list(zip(list(range(20)), list(range(20, 40)))),
        )

        g.vs["z"] = list(range(40, 60))
        lo = layout_test(g)
        self.assertEqual(
            [tuple(item) for item in lo],
            list(zip(list(range(20)), list(range(20, 40)), list(range(40, 60)))),
        )
def known_graphs():
	iters = 100
	pc_rc = []
	deg_rc = []
	for i in range(iters):
		while True:
			# graph=Graph.Watts_Strogatz(1,1000,3,0.25)
			graph = Graph.Barabasi(1000,3,implementation="psumtree")
			graph.es["weight"] = np.ones(graph.ecount())
			if graph.is_connected() == True:
				break
		n_nodes = graph.vcount()
		vc = brain_graphs.brain_graph(graph.community_fastgreedy().as_clustering())
		pc = vc.pc
		pc[np.isnan(pc)] = 0.0
		pc_emperical_phis = RC(graph,scores=pc).phis()
		pc_average_randomized_phis = np.nanmean([RC(preserve_strength(graph,randomize_topology=True),scores=pc).phis() for i in range(5)],axis=0)
		pc_normalized_phis = pc_emperical_phis/pc_average_randomized_phis
		degree_emperical_phis = RC(graph, scores=graph.strength(weights='weight')).phis()
		average_randomized_phis = np.nanmean([RC(preserve_strength(graph,randomize_topology=True),scores=graph.strength(weights='weight')).phis() for i in range(5)],axis=0)
		degree_normalized_phis = degree_emperical_phis/average_randomized_phis
		pc_rc.append(np.nanmean(pc_normalized_phis[int(n_nodes*.75):int(n_nodes*.9)]))
		deg_rc.append(np.nanmean(degree_normalized_phis[int(n_nodes*.75):int(n_nodes*.9)]))
		print scipy.stats.ttest_ind(pc_rc,deg_rc)
            out["global clustering"] = g.transitivity_undirected()
            out["local clustering"] = g.transitivity_avglocal_undirected()
    return out


def igraph_path(g, nodes, labels=None, desc=None):
    """Display edge directions in path of nodes"""
    return " ".join("[{node}] {arrow}".format(node=u if labels is None else (
        labels[u] if desc is None else desc[labels[u]]),
                                              arrow="->" if g[u, v] else (
                                                  "<-" if g[v, u] else ""))
                    for u, v in zip(nodes, nodes[1:] + nodes[:1]))


if False:  # randomly explore igraph
    import igraph
    p = igraph.plot(Graph.Famous("petersen"))
    p.show()
    Graph.show(Graph.Famous("petersen"))

    _colors = [
        'darkred', 'darkgreen', 'darkblue', 'indigo', 'red', 'lime', 'blue',
        'blueviolet', 'salmon', 'lawngreen', 'slateblue', 'mediumpurple',
        'chocolate', 'forestgreen', 'cyan', 'magenta', 'orange', 'teal'
    ]
    g = Graph.Barabasi(n=20, m=1)
    i = g.community_infomap()
    pal = igraph.drawing.colors.ClusterColoringPalette(len(i))
    g.vs['color'] = pal.get_many(i.membership)
    plot(g)
Beispiel #12
0
                                 mode=r_mode,
                                 swaplike='yes')
            sc_trade = perturbation_score_adj_list(al, al_0)
            sc_swap = perturbation_score_adj_list(al_swap, al_0)
            out.write(','.join(map(str, [step * 100, sc_trade, sc_swap])) +
                      '\n')
        print r_mode, rep
    out.close()

#barabasi

for r_mode in ['d', 'u']:
    out = open(r_mode + '_ba.csv', 'w')
    for rep in range(100):
        nodes = randrange(100, 1000)
        g = Graph.Barabasi(nodes)
        ba_net = [list(i.tuple) for i in g.es]
        net_0 = deepcopy(ba_net)
        al = edgelist_2_adjlist(ba_net, mode=r_mode)
        al_0 = deepcopy(al)
        al_swap = deepcopy(al)
        out.write(','.join(map(str, [0, 0.0, 0.0])) + '\n')
        for step in range(1, 250):
            al = curveballs(al, reps_n=100, mode=r_mode)
            al_swap = curveballs(al_swap,
                                 reps_n=100,
                                 mode=r_mode,
                                 swaplike='yes')
            sc_trade = perturbation_score_adj_list(al, al_0)
            sc_swap = perturbation_score_adj_list(al_swap, al_0)
            out.write(','.join(map(str, [step * 100, sc_trade, sc_swap])) +
 def __experiment(self):
     for m in self.__mrange:
         self.__graph = Graph.Barabasi(self.__vcount, int(m))
         self.__analyze()
Beispiel #14
0
 def testFruchtermanReingoldGrid(self):
     g = Graph.Barabasi(100)
     for grid_opt in ["grid", "nogrid", "auto", True, False]:
         lo = g.layout("fr", miny=range(100), grid=grid_opt)
         self.assertTrue(isinstance(lo, Layout))
         self.assertTrue(all(lo[i][1] >= i for i in xrange(100)))
for i in g.es:
	s,t = i.tuple
	print g.vs['label'][s]+','+g.vs['label'][t]


m = g.get_adjacency()
for i in m:
	print i





###Node degree
name = 'degree.png'
g = Graph.Barabasi(10,1.5,directed=False)
g = g.simplify()
g.vs['size'] = 50
g.vs['color'] = 'white'
g.es['color'] = 'black'
g.vs['label'] = g.degree()
g.vs['label_size']=40

lay = g.layout_fruchterman_reingold()
plot(g,'./images/'+name,layout = lay,dpi = 300,bbox = (500,500),margin=50)


for i in g.es:
	s,t = i.tuple
	print g.vs['label'][s]+','+g.vs['label'][t]
Beispiel #16
0
 def testDavidsonHarel(self):
     # Quick smoke testing only
     g = Graph.Barabasi(100)
     lo = g.layout("dh")
     self.assertTrue(isinstance(lo, Layout))
Beispiel #17
0
# In[23]:

print "Ratio of the DOR for the real network to random networks:", DOR_ratio
print "Ratio of the DOR in Shen-Orr et al., Nature Genetis, 2002:", 203 / (
    57.0)

# Q8. Does this suggest that Shen-Orr's actual network randomization procedure is possibly not consistent with their description in the Methods section of their paper, i.e., that it may have had some kind of error? Both FFL and DOR's Z-scores and ratios are not consistent with Shen-Orr's results, and it may happen due to wrong random network generation and motif enumeration methods, according to the paper by Konagurthu and Lesk.

# (Bonus Question) Write a program that generates a 20-vertex directed graph using the Barabasi-Albert model in igraph (with m = 2 edges per step), and then count the number of appearances of each type of connected three-vertex motif (note: there are five connected three-vertex digraph isomorphism classes that do not contain any double-arrows). Your program should print out the count of each of the five connected isomorphism classes.

# Step 1. Generates a 20-vertex directed graph using the Barabasi-Albert model in igraph (with m = 2 edges)

# In[15]:

v_num = 20
g = Graph.Barabasi(v_num, 2, directed=True)
summary(g)

# Step 2. Plot the 20-vertex directed graph

# In[16]:

i = 0
for v in g.vs:
    v["label"] = i
    i = i + 1
plot(g, layout=g.layout("kk"), vertex_color="pink", bbox=(300, 300))

# Step 3. Store each classe's indegree and outdegree in one list to distinguish motifs

# In[17]: