本文整理汇总了Python中igraph.Graph.vcount方法的典型用法代码示例。如果您正苦于以下问题:Python Graph.vcount方法的具体用法?Python Graph.vcount怎么用?Python Graph.vcount使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类igraph.Graph
的用法示例。
在下文中一共展示了Graph.vcount方法的9个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: testBug128
# 需要导入模块: from igraph import Graph [as 别名]
# 或者: from igraph.Graph import vcount [as 别名]
def testBug128(self):
y = [1, 4, 9]
g = Graph(n=len(y), directed=True, vertex_attrs={'y': y})
self.assertEquals(3, g.vcount())
g.add_vertices(1)
# Bug #128 would prevent us from reaching the next statement
# because an exception would have been thrown here
self.assertEquals(4, g.vcount())
示例2: generate_seed_graph
# 需要导入模块: from igraph import Graph [as 别名]
# 或者: from igraph.Graph import vcount [as 别名]
def generate_seed_graph(g, k):
vcounts = g.vcount()
init_seed = random.randint(0, vcounts)
seed_graph = Graph(directed=False)
seed_graph.add_vertex(g.vs[init_seed]['name'], degree=g.degree(init_seed))
while seed_graph.vcount() != k:
choiced_vertex = random.choice(seed_graph.vs)
choiced_vertex_index = g.vs.find(name=choiced_vertex['name'])
choiced_neighor = g.vs[random.choice(g.neighbors(choiced_vertex_index))]
if choiced_neighor['name'] in seed_graph.vs['name']:
continue
seed_graph.add_vertex(choiced_neighor['name'], degree=g.degree(choiced_neighor['name']))
choiced_neighor_neighor = g.neighbors(choiced_neighor.index)
choiced_neighor_neighor_name = [g.vs[i]['name'] for i in choiced_neighor_neighor]
existed_nodes = set(choiced_neighor_neighor_name) & set(seed_graph.vs['name'])
for node in existed_nodes:
choiced_neighor_id = seed_graph.vs.find(name=choiced_neighor['name']).index
node_id = seed_graph.vs.find(name=node).index
seed_graph.add_edge(choiced_neighor_id, node_id)
return seed_graph
示例3: generate
# 需要导入模块: from igraph import Graph [as 别名]
# 或者: from igraph.Graph import vcount [as 别名]
def generate(caplinkbase=10000,k=6,capacity=50):
#Create Core
g = Graph(directed = False)
add_vertices_with_attrs(g, (k/2)*2, {"type":"core","cap":0,"color":"black"})
#Create Pods
cnt=g.vcount()-1
for p in range(1,k):
##Create Aggregation
add_vertices_with_attrs(g, (k/2), {"type":"aggregation","cap":0,"color":"black"})
links=[]
c=0
for l in range(1,(k/2)*2):
c=c+1
a= int(ceil(l/(k/2.0)))
links = links + [cnt+a,c]
add_edges_with_attrs(g, group(links,2),{"capacity":caplinkbase*(k/2)*(k/2)})
cnt=g.vcount()-1
##Create edge nodes
add_vertices_with_attrs(g, (k/2), {"type":"edge","cap":0,"color":"black","hyperedge":1})
links=[]
c=0
for i in range(1,(k/2)):
e=cnt+i
for j in range(1,(k/2)):
a=(cnt-k/2)+j
links = links + [e,a]
add_edges_with_attrs(g, group(links,2),{"capacity":caplinkbase*(k/2)})
cnt=g.vcount()-1
##Create Servers
add_vertices_with_attrs(g, (k/2), {"type":"server","cap":sample(range(1,capacity),1),"color":"red"})
links= []
c=0
for i in range(1,(k/2)*2):
s=cnt+i
e=cnt-(k/2)+ int(i/(k/2))
links = links + [s,e]
print group(links,2)
add_edges_with_attrs(g, group(links,2),{"capacity":caplinkbase})
cnt=g.vcount()-1
plot(g)
示例4: read_graph
# 需要导入模块: from igraph import Graph [as 别名]
# 或者: from igraph.Graph import vcount [as 别名]
def read_graph(file_name):
# Input edge list file name and output igraph representation
df = pd.read_csv(file_name, sep=" ", names=["Edge1", "Edge2"])
n_vertex, n_edge = df.irow(0)
df = df.drop(0)
graph = Graph(edges=[(x[1]["Edge1"], x[1]["Edge2"])
for x in df.iterrows()], directed=False)
assert(graph.vcount() == n_vertex)
assert(graph.ecount() == n_edge)
return preprocess_graph(graph)
示例5: outputDOT
# 需要导入模块: from igraph import Graph [as 别名]
# 或者: from igraph.Graph import vcount [as 别名]
def outputDOT(self, tree, filename):
root = tree.getroot()
g = Graph(0)
names = list()
self.__drawTree__(root, g, -1, names)
g.vs["label"] = names
layout = g.layout("tree")
visual_style = {}
visual_style["vertex_size"] = [20] * g.vcount()
visual_style["vertex_color"] = ["white"] * g.vcount()
visual_style["vertex_label"] = g.vs["label"]
visual_style["edge_width"] = [1] * g.vcount()
visual_style["layout"] = layout
visual_style["bbox"] = (2000, 900)
visual_style["margin"] = 50
visual_style["vertex_label_angle"] = [3 * math.pi / 2] * g.vcount()
visual_style["vertex_label_size"] = [10] * g.vcount()
g.write_dot(filename)
示例6: Pathway
# 需要导入模块: from igraph import Graph [as 别名]
# 或者: from igraph.Graph import vcount [as 别名]
class Pathway(object):
""" Pathway object """
def __init__(self, name):
"""
Initializes the variables of the object.
Name is needed, all other variables will be initialized later if needed.
"""
self.name = name
self.commname = ''
self.rlst = [] #list of principal reactions, aligned with primlst
self.elst = [] #list of enzymes catalyzing the pathway
self.srlst = []
self.rnlst = []
self.primlst = [] #list of (inel,outel), where inel/outel are list of strings themselves
self.sclst = []
self.splst = []
self.todo = []
self.substrates = [] #counted with multiplicities
self.byproducts = [] #counted with multiplicities
self.finished = False
self.primgraph = Graph(0,directed = True)
self.totgraph = Graph(0,directed = True)
def dependence(self, dic):
""" initializes the variables substrates, byproducts and elst: the dependence of the pathway """
for (j,prim) in enumerate(self.primlst):
r = self.rlst[j]
if prim[0][0] in r.inels:
self.substrates.extend(r.inels)
self.byproducts.extend(r.outels)
else:
self.substrates.extend(r.outels)
self.byproducts.extend(r.inels)
self.elst.extend(r.elst)
def appendr(self,r,prim):
""" append reaction and its primaries to the corresponding lists """
self.rlst.append(r)
self.primlst.append(prim)
def create_primgraph(self, filterlst):
""" initializes the self.primgraph variable: the primary component graph of the pathway p """
for (j,prim) in enumerate(self.primlst):
r = self.rlst[j]
vsearch(self.primgraph,r.name)
for i in prim[0]:
vsearch(self.primgraph,i.name)
self.primgraph.add_edges([(i.name,r.name)])
for o in prim[1]:
vsearch(self.primgraph,o.name)
self.primgraph.add_edges([(r.name,o.name)])
if self.primgraph.vcount() != 0:
vn = [v for v in self.primgraph.vs['name'][:] if v in filterlst]
if vn != []:
self.primgraph.delete_vertices(vn)
def create_totgraph(self, filterlst):
""" initializes the self.totgraph variable: the total graph of the pathway p """
for r in self.srlst:
vsearch(self.totgraph,r.name)
for i in r.innames:
vsearch(self.totgraph,i)
self.totgraph.add_edges([(i,r.name)])
for o in r.outnames:
vsearch(self.totgraph,o)
self.totgraph.add_edges([(r.name,o)])
if r.reversible == True:
vsearch(self.totgraph,r.name+'_r')
for i in r.innames:
self.totgraph.add_edges([(r.name+'_r',i)])
for o in r.outnames:
self.totgraph.add_edges([(o,r.name+'_r')])
if self.totgraph.vcount() != 0:
for vn in filterlst:
if vn in self.totgraph.vs['name'][:]:
self.totgraph.delete_vertices([vn])
inprimlst = [1 if name in self.primgraph.vs['name'][:] or name[0:len(name)-2] in self.primgraph.vs['name'][:] else 0 for name in self.totgraph.vs['name']]
self.totgraph.vs['inprim'] = inprimlst
pnamelst = [self.name if int(i) == 1 else '' for i in inprimlst]
self.totgraph.vs['pnamelst'] = pnamelst
示例7: ReactDic
# 需要导入模块: from igraph import Graph [as 别名]
# 或者: from igraph.Graph import vcount [as 别名]
#.........这里部分代码省略.........
for p in self.plst:
p.srlst = list(set(p.rlst))
for r in p.srlst:
#print r
#print r.__dict__
r.plst.append(p)
for prim in p.primlst:
for i in range(2):
for c in prim[i]:
if c not in p.sclst:
p.sclst.append(c)
c.cplst.append(p)
def create_dgraph(self):
""" initializes self.graph: the total directed graph of reactions. It ereases any preceding graph. """
self.dgraph = Graph(0,directed = True)
cnlst = []
rnlst = []
rlinks = []
for rct in self.rlst:
rnlst.append(rct.name)
for i in rct.innames:
cnlst.append(i)
rlinks.append((i,rct.name))
for o in rct.outnames:
cnlst.append(o)
rlinks.append((rct.name,o))
if rct.reversible == True:
rnlst.append(rct.name+'_r')
for o in rct.innames:
rlinks.append((rct.name+'_r',o))
for i in rct.outnames:
rlinks.append((i,rct.name+'_r'))
cnlst = list(set(cnlst))
cinpathlst = [self.gsearch(cn).inpath if self.gsearch(cn) != None else [] for cn in cnlst]
rnlst = list(set(rnlst))
rinpathlst = [self.rsearch(rn).inpath if '_r' not in rn else self.rsearch(rn[0:len(rn)-2]) for rn in rnlst]
cnlst.extend(rnlst)
cinpathlst.extend(rinpathlst)
self.dgraph.add_vertices(cnlst)
self.dgraph.add_edges(rlinks)
self.dgraph.vs['inpath'] = cinpathlst
#print rlinks[len(rlinks)-3000:len(rlinks)-1]
print self.dgraph.summary()
def create_pgraphs(self,filterlst):
""" create the graphs of all the pathways and initialize the corresponding variable """
for p in self.plst:
p.dependence(self)
print '\nprimgraph'
for p in self.plst:
p.create_primgraph(filterlst)
print '\ntotgraph\n'
for p in self.plst:
p.create_totgraph(filterlst)
def create_filterlst(self,threshold):
""" create a filtering list nlst containing all the vertex in dgraph that have a degree higher than threshold """
lst = []
nlst = []
for v in range(self.dgraph.vcount()):
if self.dgraph.degree(v) > threshold:
lst.append(v)
nlst.append(self.dgraph.vs['name'][v])
print 'NUMBER OF ELEMENTS TO FILTER: '+str(len(lst))
print nlst
return nlst
def stoichmat(self):
""" outputs the full stoichiometric matrix of the system """
smat = []
clst = []
rlst = []
rev = []
for r in self.rlst:
if r.nobalance == False:
if r.name not in rlst:
rlst.append(r.name)
rev.append(r.reversible)
else:
print 'error in STOICHMAT: reaction\t',r.name,'\talready present!'
for cname in union(r.innames[:],r.outnames[:]):
if cname not in clst:
clst.append(cname)
for r in self.rlst:
if r.nobalance == False:
#create the stoichiometric vector
rclst = r.innames[:]
rclst.extend(r.outnames[:])
sv = [r.slst[[i for i,b in enumerate(rclst) if b == cname][0]] if cname in rclst else 0 for cname in clst]
smat.append(sv)
return [smat,clst,rlst,rev]
示例8: DAGApp
# 需要导入模块: from igraph import Graph [as 别名]
# 或者: from igraph.Graph import vcount [as 别名]
#.........这里部分代码省略.........
return [self._length[idx_] for idx_ in self._g.vs.indices]
def get_kernel_length(self, kernel_idx):
"""Get the length of a kernel, indicated by kernel_idx
Parameters
----------
kernel_idx : int
The kernel index.
Returns
-------
float
the length of the kernel
"""
return self._length[kernel_idx]
def _add_kernel(self, kerobj, len_):
"""Add a kernel into application.
Parameters
----------
kerobj : :class:`~lumos.model.workload.kernel.Kernel`
The kernel object to be added
len_ : float
The run length of a kernel executed on a single base line core
(BCE).
Returns
-------
int
kernel index
"""
kernel_idx = self._g.vcount()
self._g.add_vertex(name=kerobj.name, depth=1)
self._kernels[kernel_idx] = kerobj
self._length[kernel_idx] = len_
self._num_kernels += 1
return kernel_idx
def _add_dependence(self, from_, to_):
"""Add kernel dependence between two kernels.
Parameters
----------
from\_, to\_: kernel index
Precedent kernel (from\_) and the dependent kernel (to\_)
expressed by kernel index
"""
self._g.add_edge(from_, to_)
self._g.vs[to_]['depth'] = max(self._g.vs[from_]['depth'] + 1,
self._g.vs[to_]['depth'])
self._max_depth = max(self._g.vs[to_]['depth'], self._max_depth)
def get_all_kernels(self, mode='index'):
"""get all kernels
Parameters
----------
mode : str
The mode of return value. It could be either 'index' or
'object'. If 'index', kernel indexes will be returned. If
'object', kernel objects will be returned.
Returns
-------
示例9: SampleGenerator
# 需要导入模块: from igraph import Graph [as 别名]
# 或者: from igraph.Graph import vcount [as 别名]
#.........这里部分代码省略.........
self.sprdgr = Graph(tot_s, list(edges), directed=True,
vertex_attrs={NID:list("%04d" % i for i in xrange(0, tot_s)), "label":[len(com) for com in self.comm]})
g = self.sprdgr
LOG.info("%s db: generated producer graph" % name)
# generate content arcs between producers
def run_r(nsid):
prod = self.pgdb[nsid]
if prod.state != P_ARC:
rprod = g.vs.select(g.successors(id_p[nsid]))[NID]
pmap = dict((rnsid, ProducerRelation(None,
*self.inferProdArc(prod, self.pgdb[rnsid], show_tag=True))) for rnsid in rprod)
prod.initProdArcs(pmap, has_tags=True)
self.pgdb[nsid] = prod
self.pgsb[nsid] = prod.state
exec_unique(self.pgdb.iterkeys(), lambda nsid: self.pgsb[nsid] >= P_ARC, run_r, None,
"%s db: relations" % name, LOG.info, steps=0x10000)
def generateCommunities(self):
"""
Generates a bunch of communities using various community detection
algorithms on the underlying producer graph, and selects the non-tiny
ones.
"""
comm = set()
# aggregate communities using "label propagation" algorithm.
# without aggregation, multiple runs will generate a lot of similar
# (ie. redundant) communities with size in the midrange
labels = zip(*(self.prodgr.community_label_propagation().membership for i in xrange(0, 4)))
ddd = dict((o, i) for i, o in enumerate(set(labels)))
mem = self.prodgr.community_label_propagation(initial=[ddd[o] for o in labels],
fixed=[False]*self.prodgr.vcount()).membership # fixed=[False]*V workaround igraph bug #570902
comm.update(frozenset(community) for community in invert_seq(mem).itervalues())
# TODO repeat this several times?
# select communities from dendrograms generated by a bunch of algorithms
dgrams = [
undirect_and_simplify(self.prodgr).community_fastgreedy(),
#self.prodgr.community_edge_betweenness(directed=True), # this has atrocious performance
]
gg = undirect_and_simplify(self.prodgr)
gg.delete_vertices(gg.vs.select(_degree=0)) # walktrap impl can't handle islands
dgrams.append(gg.community_walktrap())
def int_unique(flseq):
"""
Turns a sorted list of floats into a sorted list of unique ints
"""
it = iter(flseq)
o = round(it.next())
yield int(o)
while True:
i = round(it.next())
if i != o:
yield int(i)
o = i
from igraph.core import InternalError
from igraph.statistics import power_law_fit
ratio = power_law_fit([prod.size() for prod in self.phdb.itervalues()], 6)
for vxd in dgrams:
default_cut = len(vxd)