本文整理汇总了Python中networkx.empty_graph函数的典型用法代码示例。如果您正苦于以下问题:Python empty_graph函数的具体用法?Python empty_graph怎么用?Python empty_graph使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了empty_graph函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: test_generate_sparse6
def test_generate_sparse6(self):
# Checked against sage encoder
assert_equal(nx.generate_sparse6(nx.empty_graph(0)), '>>sparse6<<:?')
assert_equal(nx.generate_sparse6(nx.empty_graph(1)), '>>sparse6<<:@')
assert_equal(nx.generate_sparse6(nx.empty_graph(5)), '>>sparse6<<:D')
assert_equal(nx.generate_sparse6(nx.empty_graph(68)),
'>>sparse6<<:[email protected]')
assert_equal(nx.generate_sparse6(nx.empty_graph(258049)),
'>>sparse6<<:[email protected]')
G1 = nx.complete_graph(4)
assert_equal(nx.generate_sparse6(G1, header=True),
'>>sparse6<<:CcKI')
assert_equal(nx.generate_sparse6(G1, header=False), ':CcKI')
# Padding testing
assert_equal(nx.generate_sparse6(nx.path_graph(4), header=False),
':Cdv')
assert_equal(nx.generate_sparse6(nx.path_graph(5), header=False),
':DaYn')
assert_equal(nx.generate_sparse6(nx.path_graph(6), header=False),
':EaYnN')
assert_equal(nx.generate_sparse6(nx.path_graph(7), header=False),
':FaYnL')
assert_equal(nx.generate_sparse6(nx.path_graph(8), header=False),
':GaYnLz')
示例2: SBM
def SBM(nvec,block_probs, directed=True, seed=None):
"""Return a graph sampled from a stochastic block model
Parameters
----------
nvec : array [k,1]
The number of vertices per block; there are k blocks.
B : array [k,k] in (0,1)^{k x k}
Probability for edge creation for each block.
seed : int, optional
Seed for random number generator (default=None).
math
Notes
-----
loopy : bool, optional (default=True)
If True return a loopy graph
This algorithm iterates over pairs of blocks and then assigns edges uniformly at random
between nodes in each block
"""
if (block_probs<0).any():
raise ValueError('some probability is <0')
if (block_probs>1).any():
raise ValueError('some probability is >1')
if np.shape(block_probs)[0] != len(nvec):
raise ValueError('nvec must be of length equal to the number of columns/rows of block_probs')
if seed:
np.random.seed(seed)
Nvertices=nvec.sum() # total number of vertices
Nblocks=len(nvec) # number of groups
if directed:
G=nx.empty_graph(Nvertices,create_using=nx.DiGraph())
else:
G=nx.empty_graph(Nvertices,create_using=nx.Graph())
block_idx = np.append(0, nvec).cumsum()
block = np.zeros(Nvertices, dtype=np.int)
for ii in xrange(Nblocks):
nodes1 = np.arange(block_idx[ii],block_idx[ii+1])
block[block_idx[ii]:block_idx[ii+1]] = ii
if directed:
add_random_edges_between(G, nodes1, block_probs[ii,ii],nodes1)
else:
add_random_edges_between(G, nodes1, block_probs[ii,ii])
for jj in xrange(ii+1,Nblocks):
nodes2 = np.arange(block_idx[jj],block_idx[jj+1])
if directed:
add_random_edges_between(G, nodes1, block_probs[ii,jj],nodes2)
add_random_edges_between(G, nodes2, block_probs[jj,ii],nodes1)
else:
add_random_edges_between(G, nodes1, block_probs[ii,jj],nodes2)
nx.set_node_attributes(G, 'block', dict(zip(np.arange(Nvertices), block)))
return G
示例3: test_empty_subgraph
def test_empty_subgraph(self):
# Subgraph of an empty graph is an empty graph. test 1
nullgraph = nx.null_graph()
E5 = nx.empty_graph(5)
E10 = nx.empty_graph(10)
H = E10.subgraph([])
assert_true(nx.is_isomorphic(H, nullgraph))
H = E10.subgraph([1, 2, 3, 4, 5])
assert_true(nx.is_isomorphic(H, E5))
示例4: test_strong_product
def test_strong_product():
null=nx.null_graph()
empty1=nx.empty_graph(1)
empty10=nx.empty_graph(10)
K2=nx.complete_graph(2)
K3=nx.complete_graph(3)
K5=nx.complete_graph(5)
K10=nx.complete_graph(10)
P2=nx.path_graph(2)
P3=nx.path_graph(3)
P5=nx.path_graph(5)
P10=nx.path_graph(10)
# null graph
G=strong_product(null,null)
assert_true(nx.is_isomorphic(G,null))
# null_graph X anything = null_graph and v.v.
G=strong_product(null,empty10)
assert_true(nx.is_isomorphic(G,null))
G=strong_product(null,K3)
assert_true(nx.is_isomorphic(G,null))
G=strong_product(null,K10)
assert_true(nx.is_isomorphic(G,null))
G=strong_product(null,P3)
assert_true(nx.is_isomorphic(G,null))
G=strong_product(null,P10)
assert_true(nx.is_isomorphic(G,null))
G=strong_product(empty10,null)
assert_true(nx.is_isomorphic(G,null))
G=strong_product(K3,null)
assert_true(nx.is_isomorphic(G,null))
G=strong_product(K10,null)
assert_true(nx.is_isomorphic(G,null))
G=strong_product(P3,null)
assert_true(nx.is_isomorphic(G,null))
G=strong_product(P10,null)
assert_true(nx.is_isomorphic(G,null))
G=strong_product(P5,K3)
assert_equal(nx.number_of_nodes(G),5*3)
G=strong_product(K3,K5)
assert_equal(nx.number_of_nodes(G),3*5)
#No classic easily found classic results for strong product
G = nx.erdos_renyi_graph(10,2/10.)
H = nx.erdos_renyi_graph(10,2/10.)
GH = strong_product(G,H)
for (u_G,u_H) in GH.nodes_iter():
for (v_G,v_H) in GH.nodes_iter():
if (u_G==v_G and H.has_edge(u_H,v_H)) or \
(u_H==v_H and G.has_edge(u_G,v_G)) or \
(G.has_edge(u_G,v_G) and H.has_edge(u_H,v_H)):
assert_true(GH.has_edge((u_G,u_H),(v_G,v_H)))
else:
assert_true(not GH.has_edge((u_G,u_H),(v_G,v_H)))
示例5: extract_graph
def extract_graph(self):
graph = nx.Graph()
nx.empty_graph(self.n, graph)
for i in range(self.n):
graph.node[i] = self.agent[i].opinion
for j in range(self.agent[i].degree):
graph.add_edge(i, self.agent[i].neighbors[j])
return graph
示例6: __init__
def __init__(self, n, f, q, id_topology = 'Nan', nmm = 1, noise = 0.00):
nx.Graph.__init__(self)
nx.empty_graph(n, self)
self.init_agents(n, f, q)
self.init_mass_media(nmm, f, q)
if id_topology != 'Nan':
self.set_topology(id_topology)
self.noise = noise
示例7: test_generate_graph6
def test_generate_graph6(self):
assert_equal(nx.generate_graph6(nx.empty_graph(0)), '>>graph6<<?')
assert_equal(nx.generate_graph6(nx.empty_graph(1)), '>>graph6<<@')
G1 = nx.complete_graph(4)
assert_equal(nx.generate_graph6(G1, header=True), '>>graph6<<C~')
assert_equal(nx.generate_graph6(G1, header=False), 'C~')
G2 = nx.complete_bipartite_graph(6,9)
assert_equal(nx.generate_graph6(G2, header=False),
'N??F~z{~Fw^_~?~?^_?') # verified by Sage
G3 = nx.complete_graph(67)
assert_equal(nx.generate_graph6(G3, header=False),
'[email protected]' + '~' * 368 + 'w')
示例8: bipartite_alternating_havel_hakimi_graph
def bipartite_alternating_havel_hakimi_graph(aseq, bseq,
create_using=None,
):
"""
Return a bipartite graph from two given degree sequences
using a alternating Havel-Hakimi style construction.
:Parameters:
- `aseq`: degree sequence for node set A
- `bseq`: degree sequence for node set B
Nodes from the set A are connected to nodes in the set B by
connecting the highest degree nodes in set A to
alternatively the highest and the lowest degree nodes in set
B until all stubs are connected.
The sum of the two sequences must be equal: sum(aseq)=sum(bseq)
"""
if create_using==None:
create_using=NX.MultiGraph()
G=NX.empty_graph(0,create_using)
# length of the each sequence
naseq=len(aseq)
nbseq=len(bseq)
suma=sum(aseq)
sumb=sum(bseq)
if not suma==sumb:
raise NX.NetworkXError, \
'invalid degree sequences, sum(aseq)!=sum(bseq),%s,%s'\
%(suma,sumb)
G.add_nodes_from(range(0,naseq)) # one vertex type (a)
G.add_nodes_from(range(naseq,naseq+nbseq)) # the other type (b)
if max(aseq)==0: return G # done if no edges
# build list of degree-repeated vertex numbers
astubs=[[aseq[v],v] for v in range(0,naseq)]
bstubs=[[bseq[v-naseq],v] for v in range(naseq,naseq+nbseq)]
while astubs:
astubs.sort()
(degree,u)=astubs.pop() # take of largest degree node in the a set
if degree==0: break # done, all are zero
bstubs.sort()
small=bstubs[0:degree/2] # add these low degree targets
large=bstubs[(-degree+degree/2):] # and these high degree targets
stubs=[x for z in zip(large,small) for x in z] # combine, sorry
if len(stubs)<len(small)+len(large): # check for zip truncation
stubs.append(large.pop())
for target in stubs:
v=target[1]
G.add_edge(u,v)
target[0] -= 1 # note this updates bstubs too.
if target[0]==0:
bstubs.remove(target)
G.name="bipartite_alternating_havel_hakimi_graph"
return G
示例9: firstFitTopo
def firstFitTopo(self, jobs, reservations):
if len(jobs) != len(reservations):
raise IndexError("Length of jobs and reservations input lists do no match")
import networkx as nx
skeleton = nx.barabasi_albert_graph(780)
G = nx.empty_graph()
示例10: Gen2DLattice
def Gen2DLattice(size):
side = sqrt(size)
if not side.is_integer():
print("Error: the size of lattice is not perfect square!")
sys.exit()
G = nx.empty_graph(size)
for i in range(size):
r = i // side
c = i % side
# Now we have to add 4 edges to the neighbours of i_th node
# Adding edge to the neighbour: (r+1,c)
l = ((r+1) % side) * side + c
G.add_edge(i,l)
# Adding edge to the neighbour: (r-1,c)
l = ((r-1) % side) * side + c
G.add_edge(i,l)
# Adding edge to the neighbour: (r,c+1)
l = r * side + ((c+1) % side)
G.add_edge(i,l)
# Adding edge to the neighbour: (r,c-1)
l = r * side + ((c-1) % side)
G.add_edge(i,l)
return G
示例11: RGG
def RGG(n, beta, mean_degree):
G = nx.empty_graph(n)
powerLawArray = utils.powerLawArray(n, beta, mean_degree)
powerLawDegreeArray = np.array(powerLawArray, dtype = np.longlong)
sumOfDegrees = powerLawDegreeArray.sum()
delimiterArray = np.cumsum(powerLawDegreeArray)
delimiterArray = np.insert(delimiterArray, 0, 0)
delimiterArray = np.delete(delimiterArray, n)
someCounter = 0
while someCounter < sumOfDegrees/2:
G.add_edge(np.searchsorted(delimiterArray, rnd.randrange(sumOfDegrees)),
np.searchsorted(delimiterArray, rnd.randrange(sumOfDegrees)))
someCounter += 1
txtname = "generated/adj-%s-%s-%s-.txt" % (str(n), str(beta), str(mean_degree))
nx.write_adjlist(G, txtname)
degreeSequence=sorted(nx.degree(G).values(),reverse=True)
dmax=max(degreeSequence)
plt.clf()
plt.cla()
plt.loglog(degreeSequence,'b-',marker='o')
plt.title("Degree rank plot")
plt.ylabel("degree")
plt.xlabel("rank")
if n < 1000:
plt.axes([0.45,0.45,0.45,0.45])
plt.cla()
Gcc=nx.connected_component_subgraphs(G)[0]
pos=nx.spring_layout(Gcc)
plt.axis('off')
nx.draw_networkx_nodes(Gcc,pos,node_size=20)
nx.draw_networkx_edges(Gcc,pos,alpha=0.4)
pngname = "generated/graph-%s-%s-%s-.png" % (str(n), str(beta), str(mean_degree))
plt.savefig(pngname)
示例12: get_graph_of_cluster
def get_graph_of_cluster(self, grids):
# print '%%%%%%%%%%%%%%%%%%%%%is valid: ', self.is_valid_cluster(grids), ' %%%'
# print 'graph of cluster grids keys: ', grids.keys()
indices_list = grids.keys()
g = nx.empty_graph()
for i in range(len(indices_list)):
indices = indices_list[i]
# print 'indices: ', indices
for j in range(len(indices_list)):
other_indices = indices_list[j]
# print 'other_indices: ', other_indices
# print 'i, oi: ', indices, other_indices
if self.are_neighbors(indices, other_indices):
# print '***** ', indices, other_indices, ' ARE neighbors'
if g.has_edge(indices, other_indices) == False:
g.add_edge(indices, other_indices)
continue
g.add_node(other_indices)
if g.has_node(indices) == False:
g.add_node(indices)
# print 'g size {}'.format(g.size())
return g
示例13: random_tree
def random_tree(n, create_using=None,seed=None):
""" Returns a random tree of size n
Proceeds by creating nodes and selecting uniformly at random
an existing node to connect to.
Parameters:
-----------
n : int
Number of nodes
create_using: networkx graph
graph to determine type
seed: int
Random seed value
Returns:
--------
G: networkx Graph
A random tree
"""
if seed is not None:
random.seed(seed)
G = nx.empty_graph(0,create_using)
G.add_node(0)
for i in range(1,n):
u = random.choice(G.nodes())
G.add_node(i)
G.add_edge(i,u)
return G
示例14: binomial_tree
def binomial_tree(n):
"""Returns the Binomial Tree of order n.
The binomial tree of order 0 consists of a single vertex. A binomial tree of order k
is defined recursively by linking two binomial trees of order k-1: the root of one is
the leftmost child of the root of the other.
Parameters
----------
n : int
Order of the binomial tree.
Returns
-------
G : NetworkX graph
A binomial tree of $2^n$ vertices and $2^n - 1$ edges.
"""
G = nx.empty_graph(1)
N = 1
for i in range(n):
edges = [(u + N, v + N) for (u, v) in G.edges]
G.add_edges_from(edges)
G.add_edge(0,N)
N *= 2
return G
示例15: draw_graph
def draw_graph(label_flag=True, remove_isolated=True, different_size=True, iso_level=10, node_size=40):
G=build_graph(fb.get_friends_network())
betweenness=nx.betweenness_centrality(G)
degree=nx.degree_centrality(G)
degree_num=[ degree[v] for v in G]
maxdegree=max(degree_num);mindegree=min(degree_num);
print maxdegree,mindegree
clustering=nx.clustering(G)
print nx.transitivity(G)
# Judge whether remove the isolated point from graph
if remove_isolated is True:
H = nx.empty_graph()
for SG in nx.connected_component_subgraphs(G):
if SG.number_of_nodes() > iso_level:
H = nx.union(SG, H)
G = H
# Ajust graph for better presentation
if different_size is True:
L = nx.degree(G)
G.dot_size = {}
for k, v in L.items():
G.dot_size[k] = v
#node_size = [betweenness[v] *1000 for v in G]
node_size = [G.dot_size[v] * 10 for v in G]
node_color= [((degree[v]-mindegree))/(maxdegree-mindegree) for v in G]
#edge_width = [getcommonfriends(u,v) for u,v in G.edges()]
pos = nx.spring_layout(G, iterations=15)
nx.draw_networkx_edges(G, pos, alpha=0.05)
nx.draw_networkx_nodes(G, pos, node_size=node_size, node_color=node_color, vmin=0.0,vmax=1.0, alpha=0.3)
# Judge whether shows label
if label_flag is True:
nx.draw_networkx_labels(G, pos, font_size=6,alpha=0.1)
#nx.draw_graphviz(G)
plt.show()
return G