本文整理汇总了Python中graph_tool.Graph.num_vertices方法的典型用法代码示例。如果您正苦于以下问题:Python Graph.num_vertices方法的具体用法?Python Graph.num_vertices怎么用?Python Graph.num_vertices使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类graph_tool.Graph
的用法示例。
在下文中一共展示了Graph.num_vertices方法的7个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: RoadMap
# 需要导入模块: from graph_tool import Graph [as 别名]
# 或者: from graph_tool.Graph import num_vertices [as 别名]
class RoadMap(object):
def __init__(self, mapfile):
self._mapfile = mapfile
self.DIRECTION_index = 6
self.PATHCLASS_index = 20
self.g = Graph()
self.g.edge_properties["length"] = self.g.new_edge_property("double")
self.g.edge_properties["level"] = self.g.new_edge_property("int")
self.g.vertex_properties["pos"] = self.g.new_vertex_property("vector<double>")
self.cross_pos_index = {}
def load(self):
if self._mapfile[-3:] != 'shp':
self.g = load_graph(self._mapfile)
return
try:
sf = shapefile.Reader(self._mapfile)
except Exception as e:
print(str(e))
return False
roads_records = sf.shapeRecords() # 获取路段信息'
for road_record in roads_records:
cross_s_index = self.add_cross(road_record.shape.points[0])
cross_e_index = self.add_cross(road_record.shape.points[-1])
self.add_road_edge(cross_s_index, cross_e_index, road_record)
if int(road_record.record[self.DIRECTION_index]) == 0: # 若路段是双向车道
self.add_road_edge(cross_e_index, cross_s_index, road_record)
return True
def has_edge(self, s_vertex, e_vertex):
if self.g.num_vertices() >= max(s_vertex, e_vertex):
return self.g.edge(s_vertex, e_vertex)
else:
return None
def add_cross(self, cross_pos):
if cross_pos in self.cross_pos_index:
return self.cross_pos_index.get(cross_pos)
else:
cross_index = self.g.add_vertex()
self.g.vp.pos[cross_index] = cross_pos
self.cross_pos_index[cross_pos] = cross_index
return cross_index
def add_road_edge(self, s_vertex, e_vertex, road):
if self.has_edge(s_vertex, e_vertex):
return self.g.edge(s_vertex, e_vertex)
else:
edge = self.g.add_edge(s_vertex, e_vertex)
self.g.ep.level[edge] = int(road.record[self.PATHCLASS_index])
self.g.ep.length[edge] = self.road_length(road)
return edge
@staticmethod
def road_length(road):
length = 0
for sub_road in zip(road.shape.points[:-1], road.shape.points[1:]):
length += distance.euclidean(sub_road[0], sub_road[1])
return length
示例2: __init__
# 需要导入模块: from graph_tool import Graph [as 别名]
# 或者: from graph_tool.Graph import num_vertices [as 别名]
#.........这里部分代码省略.........
self.dicProperties["Name"] = name
else:
strName = self.dicProperties["Type"]
tplUse = ("Nodes", "Edges", "Distribution")
for key,value in self.dicProperties.items():
if key in tplUse and (value.__class__ != dict):
strName += '_' + key[0] + str(value)
if key == "Clustering":
strName += '_' + key[0] + str(around(value,4))
self.dicProperties["Name"] = strName
print(self.dicProperties["Name"])
def update_prop(self, lstProp=[]):
''' update part or all of the graph properties '''
if lstProp:
for strPropName in lstProp:
if strPropName in self.dicGetProp.keys():
self.dicProperties[strPropName] = self.dicGetProp[strPropName](self.__graph)
else:
print("Ignoring unknown property '{}'".format(strPropName))
else:
self.dicProperties.update({ strPropName: self.dicGetProp[strPropName](self.__graph) for strPropName in self.dicGetProp.keys() })
self.bPropToDate = True
#---------------#
# Get functions #
#---------------#
## basic properties
def get_name(self):
return self.dicProperties["Name"]
def num_vertices(self):
return self.__graph.num_vertices()
def num_edges(self):
return self.__graph.num_edges()
def get_density(self):
return self.__graph.num_edges()/float(self.__graph.num_vertices()**2)
def is_weighted(self):
return self.dicProperties["Weighted"]
## graph and adjacency matrix
def get_graph(self):
self.bPropToDate = False
self.bBetwToDate = False
self.wBetweeness = False
return self.__graph
def get_mat_adjacency(self):
return adjacency(self.__graph, self.get_weights())
## complex properties
def get_prop(self, strPropName):
if strPropName in self.dicProperties.keys():
if not self.bPropToDate:
self.dicProperties[strPropName] = self.dicGetProp[strPropName](self.__graph)
return self.dicProperties[strPropName]
else:
print("Ignoring request for unknown property '{}'".format(strPropName))
示例3: makeGraph
# 需要导入模块: from graph_tool import Graph [as 别名]
# 或者: from graph_tool.Graph import num_vertices [as 别名]
#.........这里部分代码省略.........
percent=(float(cccc)/float(ss[1]))*100
if percentOld+10< percent:
print str(np.round(percent,1))+'%'
percentOld=percent
nodeNumber1 = (float(i)*yScale,float(j)*xScale)
if gu.find_vertex(G, vprop, {'imgIdx':(j,i),'coord':nodeNumber1, 'nrOfPaths':0, 'diameter':float(dia[j][i])*avgScale}):
v1=gu.find_vertex(G, vprop, {'imgIdx':(j,i),'coord':nodeNumber1, 'nrOfPaths':0, 'diameter':float(dia[j][i])*avgScale})[0]
else:
v1=G.add_vertex()
vprop[G.vertex(v1)]={'imgIdx':(j,i),'coord':nodeNumber1, 'nrOfPaths':0, 'diameter':float(dia[j][i])*avgScale}
try:
if img[j,i+1] == True:
nodeNumber2 = (float(i+1)*yScale,float(j)*xScale)
if gu.find_vertex(G, vprop, {'imgIdx':(j,i+1),'coord':nodeNumber2, 'nrOfPaths':0, 'diameter':float(dia[j][i+1])*avgScale}):
v2=gu.find_vertex(G, vprop, {'imgIdx':(j,i+1),'coord':nodeNumber2, 'nrOfPaths':0, 'diameter':float(dia[j][i+1])*avgScale})[0]
if gu.find_edge(G, eprop, {'coord1':vprop[v2]['coord'], 'coord2':vprop[v1]['coord'],'weight':((vprop[v1]['diameter']+vprop[v2]['diameter'])/2)**4,'RTP':False}):
pass
else:
e = G.add_edge(v1, v2)
epropW[e]=(((vprop[v1]['diameter']+vprop[v2]['diameter'])/2)/avgScale)**4
eprop[e]={'coord1':vprop[v1]['coord'], 'coord2':vprop[v2]['coord'],'weight':((vprop[v1]['diameter']+vprop[v2]['diameter'])/2)**4,'RTP':False}
else:
v2=G.add_vertex()
vprop[G.vertex(v2)]={'imgIdx':(j,i+1),'coord':nodeNumber2, 'nrOfPaths':0, 'diameter':float(dia[j][i+1])*avgScale}
e = G.add_edge(v1, v2)
epropW[e]=(((vprop[v1]['diameter']+vprop[v2]['diameter'])/2)/avgScale)**4
eprop[e]={'coord1':vprop[v1]['coord'], 'coord2':vprop[v2]['coord'],'weight':((vprop[v1]['diameter']+vprop[v2]['diameter'])/2)**4,'RTP':False}
except:
pass
try:
if img[j,i-1] == True:
nodeNumber2 = (float(i-1)*yScale,float(j)*xScale)
if gu.find_vertex(G, vprop, {'imgIdx':(j,i-1),'coord':nodeNumber2, 'nrOfPaths':0, 'diameter':float(dia[j][i-1])*avgScale}):
v2=gu.find_vertex(G, vprop, {'imgIdx':(j,i-1),'coord':nodeNumber2, 'nrOfPaths':0, 'diameter':float(dia[j][i-1])*avgScale})[0]
if gu.find_edge(G, eprop, {'coord1':vprop[v2]['coord'], 'coord2':vprop[v1]['coord'],'weight':((vprop[v1]['diameter']+vprop[v2]['diameter'])/2)**4,'RTP':False}):
pass
else:
e = G.add_edge(v1, v2)
epropW[e]=(((vprop[v1]['diameter']+vprop[v2]['diameter'])/2)/avgScale)**4
eprop[e]={'coord1':vprop[v1]['coord'], 'coord2':vprop[v2]['coord'],'weight':((vprop[v1]['diameter']+vprop[v2]['diameter'])/2)**4,'RTP':False}
else:
v2=G.add_vertex()
vprop[G.vertex(v2)]={'imgIdx':(j,i-1),'coord':nodeNumber2, 'nrOfPaths':0, 'diameter':float(dia[j][i-1])*avgScale}
e = G.add_edge(v1, v2)
epropW[e]=(((vprop[v1]['diameter']+vprop[v2]['diameter'])/2)/avgScale)**4
eprop[e]={'coord1':vprop[v1]['coord'], 'coord2':vprop[v2]['coord'],'weight':((vprop[v1]['diameter']+vprop[v2]['diameter'])/2)**4,'RTP':False}
except:pass
try:
if img[j + 1,i] == True:
nodeNumber2 = (float(i)*yScale,float(j+1)*xScale)
if gu.find_vertex(G, vprop, {'imgIdx':(j+1,i),'coord':nodeNumber2, 'nrOfPaths':0, 'diameter':float(dia[j+1][i])*avgScale}):
v2=gu.find_vertex(G, vprop, {'imgIdx':(j+1,i),'coord':nodeNumber2, 'nrOfPaths':0, 'diameter':float(dia[j+1][i])*avgScale})[0]
if gu.find_edge(G, eprop, {'coord1':vprop[v2]['coord'], 'coord2':vprop[v1]['coord'],'weight':((vprop[v1]['diameter']+vprop[v2]['diameter'])/2)**4,'RTP':False}):
pass
else:
e = G.add_edge(v1, v2)
epropW[e]=(((vprop[v1]['diameter']+vprop[v2]['diameter'])/2)/avgScale)**4
eprop[e]={'coord1':vprop[v1]['coord'], 'coord2':vprop[v2]['coord'],'weight':((vprop[v1]['diameter']+vprop[v2]['diameter'])/2)**4,'RTP':False}
else:
v2=G.add_vertex()
vprop[G.vertex(v2)]={'imgIdx':(j+1,i),'coord':nodeNumber2, 'nrOfPaths':0, 'diameter':float(dia[j+1][i])*avgScale}
e = G.add_edge(v1, v2)
epropW[e]=(((vprop[v1]['diameter']+vprop[v2]['diameter'])/2)/avgScale)**4
eprop[e]={'coord1':vprop[v1]['coord'], 'coord2':vprop[v2]['coord'],'weight':((vprop[v1]['diameter']+vprop[v2]['diameter'])/2)**4,'RTP':False}
except:pass
try:
if img[j - 1,i] == True:
nodeNumber2 = (float(i)*yScale,float(j-1)*xScale)
if gu.find_vertex(G, vprop, {'imgIdx':(j-1,i),'coord':nodeNumber2, 'nrOfPaths':0, 'diameter':float(dia[j-1][i])*avgScale}):
v2=gu.find_vertex(G, vprop, {'imgIdx':(j-1,i),'coord':nodeNumber2, 'nrOfPaths':0, 'diameter':float(dia[j-1][i])*avgScale})[0]
if gu.find_edge(G, eprop, {'coord1':vprop[v2]['coord'], 'coord2':vprop[v1]['coord'],'weight':((vprop[v1]['diameter']+vprop[v2]['diameter'])/2)**4,'RTP':False}):
pass
else:
e = G.add_edge(v1, v2)
epropW[e]=(((vprop[v1]['diameter']+vprop[v2]['diameter'])/2)/avgScale)**4
eprop[e]={'coord1':vprop[v1]['coord'], 'coord2':vprop[v2]['coord'],'weight':((vprop[v1]['diameter']+vprop[v2]['diameter'])/2)**4,'RTP':False}
else:
v2=G.add_vertex()
vprop[G.vertex(v2)]={'imgIdx':(j-1,i),'coord':nodeNumber2, 'nrOfPaths':0, 'diameter':float(dia[j-1][i])*avgScale}
e = G.add_edge(v1, v2)
epropW[e]=(((vprop[v1]['diameter']+vprop[v2]['diameter'])/2)/avgScale)**4
eprop[e]={'coord1':vprop[v1]['coord'], 'coord2':vprop[v2]['coord'],'weight':((vprop[v1]['diameter']+vprop[v2]['diameter'])/2)**4,'RTP':False}
except: pass
#
print '100.0%'
print 'selecting largest connected component'
G.edge_properties["ep"] = eprop
G.edge_properties["w"] = epropW
G.vertex_properties["vp"] = vprop
l = gt.label_largest_component(G)
print(l.a)
u = gt.GraphView(G, vfilt=l)
print '# vertices'
print(u.num_vertices())
print(G.num_vertices())
print '# edges'
print(u.num_edges())
print 'building graph finished in: '+str(time.time()-start)+'s'
return u
示例4: makeGraphFast
# 需要导入模块: from graph_tool import Graph [as 别名]
# 或者: from graph_tool.Graph import num_vertices [as 别名]
#.........这里部分代码省略.........
vList=vListLine2+list(vL)
else: vList=vListLine2+[vL]
line1=addedVerticesLine2+list(line1)
for jdx,j in enumerate(line1):
vprop[vList[jdx]]={'imgIdx':(j,idx),'coord': (float(j)*xScale,float(idx)*yScale), 'nrOfPaths':0, 'diameter':float(dia[idx][j])*avgScale}
'''
keep order of the inserted vertices
'''
sumAddVertices+=len(line1)
addedVerticesLine2=[]
vListLine2=[]
'''
Connect foreground indices to neighbours in the next line
'''
for v1 in line1:
va=vList[line1.index(v1)]
diagonalLeft = diagonalRight = True
try:
if img[idx][v1-1]==True:
diagonalLeft=False
vb=vList[line1.index(v1-1)]
e=G.add_edge(va,vb)
eprop[e]={'coord1':vprop[va]['coord'], 'coord2':vprop[vb]['coord'],'weight':((vprop[va]['diameter']+vprop[vb]['diameter'])/2),'RTP':False}
epropW[e]=2./(eprop[e]['weight']**2)
except:
print 'Boundary vertex at: '+str([v1,idx-1])+' image size: '+ str([w,h])
pass
try:
if img[idx][v1+1]==True:
diagonalRight=False
vb=vList[line1.index(v1+1)]
e=G.add_edge(va,vb)
eprop[e]={'coord1':vprop[va]['coord'], 'coord2':vprop[vb]['coord'],'weight':((vprop[va]['diameter']+vprop[vb]['diameter'])/2),'RTP':False}
epropW[e]=2./(eprop[e]['weight']**2)
except:
print 'Boundary vertex at: '+str([v1+1,idx])+' image size: '+ str([w,h])
pass # just if we are out of bounds
try:
if img[idx+1][v1]==True:
diagonalRight=False
diagonalLeft=False
vNew=G.add_vertex()
vprop[vNew]={'imgIdx':(v1,idx+1),'coord': (float(v1)*xScale,float(idx+1)*yScale), 'nrOfPaths':0, 'diameter':float(dia[idx+1][v1])*avgScale}
vListLine2.append(vNew)
e=G.add_edge(vList[line1.index(v1)],vNew)
eprop[e]={'coord1':vprop[va]['coord'], 'coord2':vprop[vNew]['coord'],'weight':((vprop[va]['diameter']+vprop[vNew]['diameter'])/2),'RTP':False}
epropW[e]=1./(eprop[e]['weight']**2)
if v1 not in addedVerticesLine2: addedVerticesLine2.append(v1)
except:
print 'Boundary vertex at: '+str([v1,idx+1])+' image size: '+ str([w,h])
pass
try:
if diagonalRight == True and img[idx+1][v1+1]==True:
vNew=G.add_vertex()
vprop[vNew]={'imgIdx':(v1+1,idx+1),'coord': (float(v1+1)*xScale,float(idx+1)*yScale), 'nrOfPaths':0, 'diameter':float(dia[idx+1][v1+1])*avgScale}
vListLine2.append(vNew)
e=G.add_edge(vList[line1.index(v1)],vNew)
eprop[e]={'coord1':vprop[va]['coord'], 'coord2':vprop[vNew]['coord'],'weight':((vprop[va]['diameter']+vprop[vNew]['diameter'])/2),'RTP':False}
epropW[e]=1.41/(eprop[e]['weight']**2)
if v1+1 not in addedVerticesLine2: addedVerticesLine2.append(v1+1)
except:
print 'Boundary vertex at: '+str([v1+1,idx+1])+' image size: '+ str([w,h])
pass
try:
if diagonalLeft == True and img[idx+1][v1-1]==True:
vNew=G.add_vertex()
vprop[vNew]={'imgIdx':(v1-1,idx+1),'coord': (float(v1-1)*xScale,float(idx+1)*yScale), 'nrOfPaths':0, 'diameter':float(dia[idx+1][v1-1])*avgScale}
vListLine2.append(vNew)
e=G.add_edge(vList[line1.index(v1)],vNew)
eprop[e]={'coord1':vprop[va]['coord'], 'coord2':vprop[vNew]['coord'],'weight':((vprop[va]['diameter']+vprop[vNew]['diameter'])/2),'RTP':False}
epropW[e]=1.41/(eprop[e]['weight']**2)
if v1-1 not in addedVerticesLine2: addedVerticesLine2.append(v1-1)
except:
print 'Boundary vertex at: '+str([v1-1,idx+1])+' image size: '+ str([w,h])
pass
try:
if img[idx][v1+1]==False and img[idx][v1-1]==False and img[idx+1][v1]==False and diagonalLeft==False and diagonalRight==False:
print 'tip detected'
if img[idx-1][v1-1]==False and img[idx-1][v1+1]==False and img[idx-1][v1]==False:
print 'floating pixel'
except:
pass
print'done!'
G.edge_properties["ep"] = eprop
G.edge_properties["w"] = epropW
G.vertex_properties["vp"] = vprop
print 'graph build in '+str(time.time()-start)
l = gt.label_largest_component(G)
u = gt.GraphView(G, vfilt=l)
print '# vertices'
print(u.num_vertices())
print(G.num_vertices())
if u.num_vertices()!=G.num_vertices(): self.__fail=float((G.num_vertices()-u.num_vertices()))/float(G.num_vertices())
return u,u.num_vertices()
示例5: BoardGraphGraphtool
# 需要导入模块: from graph_tool import Graph [as 别名]
# 或者: from graph_tool.Graph import num_vertices [as 别名]
class BoardGraphGraphtool(BoardGraphBase):
def __init__(self, number_of_vertices, graph_type):
super().__init__(number_of_vertices, graph_type)
# Graph tool creates directed multigraph by default.
self._graph = Graph()
self._graph.add_vertex(number_of_vertices)
self._graph.vertex_properties["cell"] = self._graph.new_vertex_property(
"object", number_of_vertices * [BoardCell()]
)
self._graph.edge_properties["direction"
] = self._graph.new_edge_property("object")
self._graph.edge_properties["weight"
] = self._graph.new_edge_property("int")
def __getitem__(self, position):
return self._graph.vp.cell[self._graph.vertex(position)]
def __setitem__(self, position, board_cell):
self._graph.vp.cell[self._graph.vertex(position)] = board_cell
def __contains__(self, position):
return position in range(0, self.vertices_count())
def vertices_count(self):
return self._graph.num_vertices()
def edges_count(self):
return self._graph.num_edges()
def has_edge(self, source_vertice, target_vertice, direction):
for e in self._graph.vertex(source_vertice).out_edges():
if (
int(e.target()) == target_vertice and
self._graph.ep.direction[e] == direction
):
return True
return False
def out_edges_count(self, source_vertice, target_vertice):
return len([
1 for e in self._graph.vertex(source_vertice).out_edges()
if int(e.target()) == target_vertice
])
def reconfigure_edges(self, width, height, tessellation):
"""
Uses tessellation object to create all edges in graph.
"""
self._graph.clear_edges()
for source_vertice in self._graph.vertices():
for direction in tessellation.legal_directions:
neighbor_vertice = tessellation.neighbor_position(
int(source_vertice),
direction,
board_width=width,
board_height=height
)
if neighbor_vertice is not None:
e = self._graph.add_edge(
source_vertice, neighbor_vertice, add_missing=False
)
self._graph.ep.direction[e] = direction
# TODO: Faster version?
# def reconfigure_edges(self, width, height, tessellation):
# """
# Uses tessellation object to create all edges in graph.
# """
# self._graph.clear_edges()
# edges_to_add = []
# directions_to_add = dict()
# for source_vertice in self._graph.vertices():
# for direction in tessellation.legal_directions:
# neighbor_vertice = tessellation.neighbor_position(
# int(source_vertice), direction,
# board_width=width, board_height=height
# )
# if neighbor_vertice is not None:
# edge = (int(source_vertice), neighbor_vertice,)
# edges_to_add.append(edge)
# if edge not in directions_to_add:
# directions_to_add[edge] = deque()
# directions_to_add[edge].append(direction)
# self._graph.add_edge_list(edges_to_add) if edges_to_add else None
# for e in edges_to_add:
# e_descriptors = self._graph.edge(
# s = self._graph.vertex(e[0]),
# t = self._graph.vertex(e[1]),
# all_edges = True
# )
# for e_descriptor in e_descriptors:
# if len(directions_to_add[e]) > 0:
# self._graph.ep.direction[e_descriptor] = directions_to_add[e][0]
#.........这里部分代码省略.........
示例6: gen_fs
# 需要导入模块: from graph_tool import Graph [as 别名]
# 或者: from graph_tool.Graph import num_vertices [as 别名]
#.........这里部分代码省略.........
dicProperties["Density"] = rDens
else:
rDens = dicProperties["Density"]
nEdges = int(np.floor(rDens*nNodes**2))
dicProperties["Edges"] = nEdges
else:
nEdges = dicProperties["Edges"]
rDens = dicProperties["Density"]
nNodes = int(np.floor(np.sqrt(nEdges/rDens)))
graphFS.add_vertex(nNodes)
dicProperties["Nodes"] = nNodes
# on définit le nombre d'arcs à créer
nArcs = int(np.floor(rDens*nNodes**2)/(1+rFracRecip))
# on définit les paramètres fonctions de probabilité associées F(x) = A x^{-tau}
Ai = nArcs*(rInDeg-1)/(nNodes)
Ao = nArcs*(rOutDeg-1)/(nNodes)
# on définit les moyennes des distributions de pareto 2 = lomax
rMi = 1/(rInDeg-2.)
rMo = 1/(rOutDeg-2.)
# on définit les trois listes contenant les degrés sortant/entrant/bidirectionnels associés aux noeuds i in range(nNodes)
lstInDeg = np.random.pareto(rInDeg,nNodes)+1
lstOutDeg = np.random.pareto(rOutDeg,nNodes)+1
lstInDeg = np.floor(np.multiply(Ai/np.mean(lstInDeg), lstInDeg)).astype(int)
lstOutDeg = np.floor(np.multiply(Ao/np.mean(lstOutDeg), lstOutDeg)).astype(int)
# on génère les stubs qui vont être nécessaires et on les compte
nInStubs = int(np.sum(lstInDeg))
nOutStubs = int(np.sum(lstOutDeg))
lstInStubs = np.zeros(np.sum(lstInDeg))
lstOutStubs = np.zeros(np.sum(lstOutDeg))
nStartIn = 0
nStartOut = 0
for vert in range(nNodes):
nInDegVert = lstInDeg[vert]
nOutDegVert = lstOutDeg[vert]
for j in range(np.max([nInDegVert,nOutDegVert])):
if j < nInDegVert:
lstInStubs[nStartIn+j] += vert
if j < nOutDegVert:
lstOutStubs[nStartOut+j] += vert
nStartOut+=nOutDegVert
nStartIn+=nInDegVert
# on vérifie qu'on a à peu près le nombre voulu d'edges
while nInStubs*(1+rFracRecip)/float(nArcs) < 0.95 :
vert = np.random.randint(0,nNodes)
nAddInStubs = int(np.floor(Ai/rMi*(np.random.pareto(rInDeg)+1)))
lstInStubs = np.append(lstInStubs,np.repeat(vert,nAddInStubs)).astype(int)
nInStubs+=nAddInStubs
while nOutStubs*(1+rFracRecip)/float(nArcs) < 0.95 :
nAddOutStubs = int(np.floor(Ao/rMo*(np.random.pareto(rOutDeg)+1)))
lstOutStubs = np.append(lstOutStubs,np.repeat(vert,nAddOutStubs)).astype(int)
nOutStubs+=nAddOutStubs
# on s'assure d'avoir le même nombre de in et out stubs (1.13 is an experimental correction)
nMaxStubs = int(1.13*(2.0*nArcs)/(2*(1+rFracRecip)))
if nInStubs > nMaxStubs and nOutStubs > nMaxStubs:
np.random.shuffle(lstInStubs)
np.random.shuffle(lstOutStubs)
lstOutStubs.resize(nMaxStubs)
lstInStubs.resize(nMaxStubs)
nOutStubs = nInStubs = nMaxStubs
elif nInStubs < nOutStubs:
np.random.shuffle(lstOutStubs)
lstOutStubs.resize(nInStubs)
nOutStubs = nInStubs
else:
np.random.shuffle(lstInStubs)
lstInStubs.resize(nOutStubs)
nInStubs = nOutStubs
# on crée le graphe, les noeuds et les stubs
nRecip = int(np.floor(nInStubs*rFracRecip))
nEdges = nInStubs + nRecip +1
# les stubs réciproques
np.random.shuffle(lstInStubs)
np.random.shuffle(lstOutStubs)
lstInRecip = lstInStubs[0:nRecip]
lstOutRecip = lstOutStubs[0:nRecip]
lstEdges = np.array([np.concatenate((lstOutStubs,lstInRecip)),np.concatenate((lstInStubs,lstOutRecip))]).astype(int)
# add edges
graphFS.add_edge_list(np.transpose(lstEdges))
remove_self_loops(graphFS)
remove_parallel_edges(graphFS)
lstIsolatedVert = find_vertex(graphFS, graphFS.degree_property_map("total"), 0)
graphFS.remove_vertex(lstIsolatedVert)
graphFS.reindex_edges()
nNodes = graphFS.num_vertices()
nEdges = graphFS.num_edges()
rDens = nEdges / float(nNodes**2)
# generate types
rInhibFrac = dicProperties["InhibFrac"]
lstTypesGen = np.random.uniform(0,1,nEdges)
lstTypeLimit = np.full(nEdges,rInhibFrac)
lstIsExcitatory = np.greater(lstTypesGen,lstTypeLimit)
nExc = np.count_nonzero(lstIsExcitatory)
epropType = graphFS.new_edge_property("int",np.multiply(2,lstIsExcitatory)-np.repeat(1,nEdges)) # excitatory (True) or inhibitory (False)
graphFS.edge_properties["type"] = epropType
# and weights
if dicProperties["Weighted"]:
lstWeights = dicGenWeights[dicProperties["Distribution"]](graphFS,dicProperties,nEdges,nExc) # generate the weights
epropW = graphFS.new_edge_property("double",lstWeights) # crée la propriété pour stocker les poids
graphFS.edge_properties["weight"] = epropW
return graphFS
示例7: build_graph
# 需要导入模块: from graph_tool import Graph [as 别名]
# 或者: from graph_tool.Graph import num_vertices [as 别名]
#.........这里部分代码省略.........
function data_processing.get_sa_data().
sens : str, optional
A string with the name of the sensitivity that you would
like to use for the vertices ('ST' or 'S1').
top : int, optional
An integer specifying the number of vertices to display (
the top sensitivity values).
min_sens : float, optional
A float with the minimum sensitivity to allow in the graph.
edge_cutoff : float, optional
A float specifying the minimum second order sensitivity to
show as an edge in the graph.
Returns
--------
g : graph-tool object
a graph-tool graph object of the network described above. Each
vertex has properties 'param', 'sensitivity', and 'confidence'
corresponding to the name of the parameter, value of the sensitivity
index, and it's confidence interval. The only edge property is
'second_sens', the second order sensitivity index for the
interaction between the two vertices it connects.
"""
# get the first/total index dataframe and second order dataframe
df = df_list[0]
df2 = df_list[1]
# Make sure sens is ST or S1
if sens not in set(['ST', 'S1']):
raise ValueError('sens must be ST or S1')
# Make sure that there is a second order index dataframe
try:
if not df2:
raise Exception('Missing second order dataframe!')
except:
pass
# slice the dataframes so the resulting graph will only include the top
# 'top' values of 'sens' greater than 'min_sens'.
df = df.sort_values(sens, ascending=False)
df = df.ix[df[sens] > min_sens, :].head(top)
df = df.reset_index()
# initialize a graph
g = Graph()
vprop_sens = g.new_vertex_property('double')
vprop_conf = g.new_vertex_property('double')
vprop_name = g.new_vertex_property('string')
eprop_sens = g.new_edge_property('double')
g.vertex_properties['param'] = vprop_name
g.vertex_properties['sensitivity'] = vprop_sens
g.vertex_properties['confidence'] = vprop_conf
g.edge_properties['second_sens'] = eprop_sens
# keep a list of all the vertices
v_list = []
# Add the vertices to the graph
for i, param in enumerate(df['Parameter']):
v = g.add_vertex()
vprop_sens[v] = df.ix[i, sens]
vprop_conf[v] = 1 + df.ix[i, '%s_conf' % sens] / df.ix[i, sens]
vprop_name[v] = param
v_list.append(v)
# Make two new columns in second order dataframe that point to the vertices
# connected on each row.
df2['vertex1'] = -999
df2['vertex2'] = -999
for vertex in v_list:
param = g.vp.param[vertex]
df2.ix[df2['Parameter_1'] == param, 'vertex1'] = vertex
df2.ix[df2['Parameter_2'] == param, 'vertex2'] = vertex
# Only allow edges for vertices that we've defined
df_edges = df2[(df2['vertex1'] != -999) & (df2['vertex2'] != -999)]
# eliminate edges below a certain cutoff value
pruned = df_edges[df_edges['S2'] > edge_cutoff]
pruned.reset_index(inplace=True)
# Add the edges for the graph
for i, sensitivity in enumerate(pruned['S2']):
v1 = pruned.ix[i, 'vertex1']
v2 = pruned.ix[i, 'vertex2']
e = g.add_edge(v1, v2)
# multiply by a number to make the lines visible on the plot
eprop_sens[e] = sensitivity * 150
# These are ways you can reference properties of vertices or edges
# g.vp.param[g.vertex(77)]
# g.vp.param[v_list[0]]
print ('Created a graph with %s vertices and %s edges.\nVertices are the '
'top %s %s values greater than %s.\nOnly S2 values (edges) '
'greater than %s are included.' %
(g.num_vertices(), g.num_edges(), top, sens, min_sens, edge_cutoff))
return g