本文整理汇总了Python中graph_tool.Graph.new_edge_property方法的典型用法代码示例。如果您正苦于以下问题:Python Graph.new_edge_property方法的具体用法?Python Graph.new_edge_property怎么用?Python Graph.new_edge_property使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类graph_tool.Graph
的用法示例。
在下文中一共展示了Graph.new_edge_property方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: RoadMap
# 需要导入模块: from graph_tool import Graph [as 别名]
# 或者: from graph_tool.Graph import new_edge_property [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: compose_graph
# 需要导入模块: from graph_tool import Graph [as 别名]
# 或者: from graph_tool.Graph import new_edge_property [as 别名]
def compose_graph(uid_pid_pairs):
# set up graph
g = Graph()
g.vp['pid'] = v_pid_p = g.new_vertex_property('string')
g.vp['count'] = v_count_p = g.new_vertex_property('int')
g.ep['count'] = e_count_p = g.new_edge_property('int')
pid_v_map = {}
uid_last_v_map = {}
vv_e_map = {}
for uid, pid in uid_pid_pairs:
# vertex
v = pid_v_map.get(pid)
if v is None:
v = g.add_vertex()
v_pid_p[v] = pid
v_count_p[v] = 0
pid_v_map[pid] = v
v_count_p[v] += 1
# edge
last_v = uid_last_v_map.get(uid)
uid_last_v_map[uid] = v
if last_v is None:
continue
vv = (last_v, v)
e = vv_e_map.get(vv)
if e is None:
e = g.add_edge(*vv)
e_count_p[e] = 0
vv_e_map[vv] = e
e_count_p[e] += 1
# calculate closeness
g.vp['closeness'] = v_closeness_p = g.new_vertex_property('float')
e_inverse_count_p = g.new_edge_property('int')
e_inverse_count_p.a = e_count_p.a.max()-e_count_p.a
debug('e_inverse_count_p.a: {}', e_inverse_count_p.a)
closeness(g, weight=e_inverse_count_p, vprop=v_closeness_p)
debug('v_closeness_p.a : {}', v_closeness_p.a)
v_closeness_p.a = nan_to_num(v_closeness_p.a)
debug('v_closeness_p.a : {}', v_closeness_p.a)
# fillter
g.vp['picked'] = v_picked_p = g.new_vertex_property('bool')
debug('v_count_p.a.mean() : {}', v_count_p.a.mean())
v_picked_p.a = v_count_p.a > v_count_p.a.mean()
debug('v_picked_p.a : {}', v_picked_p.a)
g.set_vertex_filter(v_picked_p)
g.set_vertex_filter(None)
return g
示例3: gen_er
# 需要导入模块: from graph_tool import Graph [as 别名]
# 或者: from graph_tool.Graph import new_edge_property [as 别名]
def gen_er(dicProperties):
np.random.seed()
# initialize graph
graphER = Graph()
nNodes = 0
nEdges = 0
rDens = 0.0
if "Nodes" in dicProperties.keys():
nNodes = dicProperties["Nodes"]
graphER.add_vertex(nNodes)
if "Edges" in dicProperties.keys():
nEdges = dicProperties["Edges"]
rDens = nEdges / float(nNodes**2)
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)))
graphER.add_vertex(nNodes)
dicProperties["Nodes"] = nNodes
# generate edges
numTest,numCurrentEdges = 0,0
while numCurrentEdges != nEdges and numTest < n_MAXTESTS:
lstEdges = np.random.randint(0,nNodes,(nEdges-numCurrentEdges,2))
graphER.add_edge_list(lstEdges)
# remove loops and duplicate edges
remove_self_loops(graphER)
remove_parallel_edges(graphER)
numCurrentEdges = graphER.num_edges()
numTest += 1
graphER.reindex_edges()
nEdges = graphER.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 = graphER.new_edge_property("int",np.multiply(2,lstIsExcitatory)-np.repeat(1,nEdges)) # excitatory (True) or inhibitory (False)
graphER.edge_properties["type"] = epropType
# and weights
if dicProperties["Weighted"]:
lstWeights = dicGenWeights[dicProperties["Distribution"]](graphER,dicProperties,nEdges,nExc) # generate the weights
epropW = graphER.new_edge_property("double",lstWeights) # crée la propriété pour stocker les poids
graphER.edge_properties["weight"] = epropW
return graphER
示例4: build_minimum_tree
# 需要导入模块: from graph_tool import Graph [as 别名]
# 或者: from graph_tool.Graph import new_edge_property [as 别名]
def build_minimum_tree(g, root, terminals, edges, directed=True):
"""remove redundant edges from `edges` so that root can reach each node in terminals
"""
# build the tree
t = Graph(directed=directed)
for _ in range(g.num_vertices()):
t.add_vertex()
for (u, v) in edges:
t.add_edge(u, v)
# mask out redundant edges
vis = init_visitor(t, root)
pbfs_search(t, source=root, terminals=list(terminals), visitor=vis)
minimum_edges = {e
for u in terminals
for e in extract_edges_from_pred(t, root, u, vis.pred)}
# print(minimum_edges)
efilt = t.new_edge_property('bool')
efilt.a = False
for u, v in minimum_edges:
efilt[u, v] = True
t.set_edge_filter(efilt)
return filter_nodes_by_edges(t, minimum_edges)
示例5: graph_from_dataframes
# 需要导入模块: from graph_tool import Graph [as 别名]
# 或者: from graph_tool.Graph import new_edge_property [as 别名]
def graph_from_dataframes(vertex_df, edge_df):
'''Re-creates a Graph object with PropertyMaps taken
from the vertex_df and edge_df DataFrames
Paramters:
==========
verex_df: a DataFrame with an index named 'vertex_index'
edge_df: a DataFrame with a multi-index named ('source', 'target')
Returns:
========
graph: a grah-tool Graph with PropertyMaps copied
from the columns of the input DataFrames
'''
graph = Graph(directed=True)
vertex_index = vertex_df.index.get_level_values(level='vertex_index')
vertices = graph.add_vertex(n=vertex_index.shape[0])
for col in vertex_df.columns:
in_type = vertex_df[col].dtype.name
try:
dtype = ALIASES[in_type]
except KeyError:
log.info('Data type {} not supported'.format(in_type))
continue
prop = graph.new_vertex_property(dtype)
prop.fa = vertex_df[col]
graph.vertex_properties[col] = prop
src = edge_df.index.names.index('source')
trgt = edge_df.index.names.index('target')
### TODO: use the list edge creation
for tup in edge_df.index:
source, target = tup[src], tup[trgt]
try:
edge = graph.add_edge(source, target)
except ValueError:
log.info('Invalid vertex in (source: {}, target: {})'.format(source, target))
for col in edge_df.columns:
in_type = edge_df[col].dtype.name
try:
dtype = ALIASES[in_type]
except KeyError:
log.info('Data type {} not supported'.format(in_type))
continue
prop = graph.new_edge_property(dtype)
prop.fa = edge_df[col]
graph.edge_properties[col] = prop
return graph
示例6: load_graph
# 需要导入模块: from graph_tool import Graph [as 别名]
# 或者: from graph_tool.Graph import new_edge_property [as 别名]
def load_graph(infile):
inmatrix = np.loadtxt(infile, dtype=np.dtype('uint32'), delimiter=" ")
numv = np.amax(inmatrix[:,0:2])
#print numv, inmatrix[:,0:2]
g = Graph(directed=False)
edge_weights = g.new_edge_property("double")
g.edge_properties["weights"] = edge_weights
vlist = list(g.add_vertex(numv))
for i in inmatrix:
edge = g.add_edge(vlist[i[0]-1], vlist[i[1]-1]) # need to convert from 1-based index in file to 0-based
edge_weights[edge] = i[2]
remove_parallel_edges(g)
return g
示例7: user_network
# 需要导入模块: from graph_tool import Graph [as 别名]
# 或者: from graph_tool.Graph import new_edge_property [as 别名]
def user_network(storage, track, session):
g = Graph()
users = defaultdict(g.add_vertex)
g.graph_properties["track"] = g.new_graph_property("string", track)
g.graph_properties["session"] = g.new_graph_property("string", session)
g.edge_properties["created_at"] = g.new_edge_property("int64_t")
for tweet in storage:
tweeter_id = tweet["user__id_str"]
origin_id = tweet["retweeted_status__user__id_str"]
created_at = arrow.get(tweet["created_at"], DATE_FORMAT).timestamp
if origin_id:
edge = g.add_edge(users[tweeter_id], users[origin_id])
g.edge_properties["created_at"][edge] = created_at
return g
示例8: graph_from_dataframes
# 需要导入模块: from graph_tool import Graph [as 别名]
# 或者: from graph_tool.Graph import new_edge_property [as 别名]
def graph_from_dataframes(vertex_df, edge_df):
'''Re-creates a Graph object with PropertyMaps taken
from the vertex_df and edge_df DataFrames
Paramters:
==========
verex_df: a DataFrame with an index named 'vertex_index'
edge_df: a DataFrame with a multi-index named ('source', 'target')
Returns:
========
graph: a grah-tool Graph with PropertyMaps copied
from the columns of the input DataFrames
'''
graph = Graph(directed=True)
vertex_index = vertex_df.index.get_level_values(level='vertex_index')
vertices = graph.add_vertex(n=vertex_index.shape[0])
for col in vertex_df.columns:
dtype = ALIASES[vertex_df[col].dtype.name]
prop = graph.new_vertex_property(dtype)
prop.a = vertex_df[col]
graph.vertex_properties[col] = prop
src = edge_df.index.names.index('source')
trgt = edge_df.index.names.index('target')
### TODO: use the list edge creation
for tup in edge_df.index:
source, target = tup[src], tup[trgt]
edge = graph.add_edge(source, target)
for col in edge_df.columns:
dtype = ALIASES[edge_df[col].dtype.name]
prop = graph.new_edge_property(dtype)
prop.a = edge_df[col]
graph.edge_properties[col] = prop
return graph
示例9: build_closure
# 需要导入模块: from graph_tool import Graph [as 别名]
# 或者: from graph_tool.Graph import new_edge_property [as 别名]
def build_closure(g, terminals,
debug=False,
verbose=False):
terminals = list(terminals)
# build closure
gc = Graph(directed=False)
for _ in range(g.num_vertices()):
gc.add_vertex()
edges_with_weight = set()
r2pred = {}
for r in terminals:
if debug:
print('root {}'.format(r))
vis = init_visitor(g, r)
pbfs_search(g, source=r, terminals=terminals, visitor=vis)
new_edges = set(get_edges(vis.dist, r, terminals))
if debug:
print('new edges {}'.format(new_edges))
edges_with_weight |= new_edges
r2pred[r] = vis.pred
for u, v, c in edges_with_weight:
gc.add_edge(u, v)
eweight = gc.new_edge_property('int')
weights = np.array([c for _, _, c in edges_with_weight])
eweight.set_2d_array(weights)
vfilt = gc.new_vertex_property('bool')
vfilt.a = False
for v in terminals:
vfilt[v] = True
gc.set_vertex_filter(vfilt)
return gc, eweight, r2pred
示例10: SkeletonData
# 需要导入模块: from graph_tool import Graph [as 别名]
# 或者: from graph_tool.Graph import new_edge_property [as 别名]
#.........这里部分代码省略.........
for v in self.skel_graph.vertices():
if v.out_degree() == 2 :
continue
elif v.out_degree() == 1 :
terminal_index.append(int(v))
elif v.out_degree() > 2 :
junction_index.append(int(v))
self.terminal = self.verts[terminal_index]
self.junction = self.verts[junction_index]
self.terminal_index = terminal_index
self.junction_index = junction_index
self.feature_node_index = junction_index + terminal_index
self.feature_node = self.verts[self.feature_node_index]
"""
edge_vert_index = self.edges.flatten()
print 'edge vertex index dtype', edge_vert_index.dtype
if 0 in edge_vert_index:
print 'vertex start from 0'
else:
print 'vertex start from 1'
print 'skeleton vertex num', self.skel_graph.num_vertices()
print 'skeleton edge num', self.skel_graph.num_edges()
"""
def _calc_edge_length(self):
"""
calc edge length and make it edge property map in graph-tool
"""
vec = self.verts[self.edges[:,0]] - self.verts[self.edges[:,1]]
edge_length = np.sqrt(np.sum(vec**2, axis=-1))
self.edge_length_map = self.skel_graph.new_edge_property("double")
self.edge_length_map.a = edge_length
def calc_node_centricity(self):
"""
calc node centricity of feature nodes(terminal and junction nodes)
T1 in Oscar's EG 2010 paper
"""
self._calc_edge_length()
node_centricity = []
for n_idx in self.feature_node_index:
dist = topology.shortest_distance(self.skel_graph, source=self.skel_graph.vertex(n_idx), weights=self.edge_length_map)
node_centricity.append(dist.a.mean())
node_centricity = np.array(node_centricity)
self.node_centricity = node_centricity / np.max(node_centricity)
def calc_skel_radius(self, mesh_name=None, dim=3):
"""
calc nearest mesh vertex of skeleton vertex
"""
if mesh_name != None:
self.mesh_name = mesh_name
if self.mesh_name == None:
print 'please set mesh_name before calc_skel_radius'
elif os.path.isfile(self.mesh_name):
mesh = om.TriMesh()
assert om.read_mesh(mesh, self.mesh_name)
mesh_vertices = np.zeros((mesh.n_vertices(), dim), dtype=float)
for n, vh in enumerate(mesh.vertices()):
示例11: str
# 需要导入模块: from graph_tool import Graph [as 别名]
# 或者: from graph_tool.Graph import new_edge_property [as 别名]
e2015 = child_graph.add_edge(child_graph.vertex_index[20], child_graph.vertex_index[15])
e2115 = child_graph.add_edge(child_graph.vertex_index[21], child_graph.vertex_index[15])
e1716 = child_graph.add_edge(child_graph.vertex_index[17], child_graph.vertex_index[16])
e2116 = child_graph.add_edge(child_graph.vertex_index[21], child_graph.vertex_index[16])
e2216 = child_graph.add_edge(child_graph.vertex_index[22], child_graph.vertex_index[16])
e2317 = child_graph.add_edge(child_graph.vertex_index[23], child_graph.vertex_index[17])
e1918 = child_graph.add_edge(child_graph.vertex_index[19], child_graph.vertex_index[18])
e2019 = child_graph.add_edge(child_graph.vertex_index[20], child_graph.vertex_index[19])
e2120 = child_graph.add_edge(child_graph.vertex_index[21], child_graph.vertex_index[20])
e2221 = child_graph.add_edge(child_graph.vertex_index[22], child_graph.vertex_index[21])
e2322 = child_graph.add_edge(child_graph.vertex_index[23], child_graph.vertex_index[22])
## Property definition
graph_name = child_graph.new_graph_property("string")
layer_capacities = child_graph.new_edge_property("int")
layer_res_capacity = child_graph.new_edge_property("int")
layer_flow = child_graph.new_edge_property("int")
alternate_path = child_graph.new_edge_property("int")
flag_path = child_graph.new_edge_property("int")
## Property Assignment
child_graph.gp.layer_name = graph_name
child_graph.ep.edge_capacity = layer_capacities
child_graph.ep.residual_capacity = layer_res_capacity
child_graph.ep.edge_flow = layer_flow
child_graph.ep.shared_path = alternate_path
child_graph.ep.path_flag = flag_path
## Setting the name of the graph
child_graph.gp.layer_name = "Layer_" + str(i)
示例12: main
# 需要导入模块: from graph_tool import Graph [as 别名]
# 或者: from graph_tool.Graph import new_edge_property [as 别名]
def main():
conn = serial_interface.connect()
cur_track = track.init_tracka()
g = Graph()
g.add_vertex(len(cur_track))
for (vi, node) in enumerate(cur_track): node.i = vi
n_title = g.new_vertex_property("string")
n_color = g.new_vertex_property("string")
n_pos = g.new_vertex_property("vector<double>")
e_title = g.new_edge_property("string")
e_dist = g.new_edge_property("double")
for node in cur_track:
v = g.vertex(node.i)
n_title[v] = node.name
if node.typ == track.NODE_EXIT:
# Invert points to match our ASCII display.
n_pos[v] = (-node.reverse.coord_x, -node.reverse.coord_y)
else:
n_pos[v] = (-node.coord_x, -node.coord_y)
e = g.add_edge(g.vertex(node.i), g.vertex(node.reverse.i))
if node.typ == track.NODE_SENSOR: n_color[v] = "blue"
elif node.typ == track.NODE_BRANCH: n_color[v] = "orange"
elif node.typ == track.NODE_MERGE: n_color[v] = "yellow"
elif node.typ == track.NODE_ENTER: n_color[v] = "green"
elif node.typ == track.NODE_EXIT: n_color[v] = "red"
else: n_color[v] = "white"
for edge in node.edge:
if edge.src is None: continue
e = g.add_edge(g.vertex(edge.src.i), g.vertex(edge.dest.i))
e_dist[e] = edge.dist
e_title[e] = "%.2f" % (edge.dist)
win = graph_tool.draw.GraphWindow(g, n_pos, (640, 480), edge_text=e_title, vertex_fill_color=n_color, vertex_text=n_title)
win.show_all()
def destroy_callback(*args, **kwargs):
win.destroy()
Gtk.main_quit()
def set_switch(sw, d):
for node in cur_track:
if node.typ == track.NODE_BRANCH and node.num == sw:
node.switch_direction = d
return
print "WARN: Could not find switch %d" % sw
class Train():
num = -1
vel = 0.
speed = 0.
edge = cur_track[0].edge[0]
edge_dist = 0
SPEEDX = 1.
def __init__(self, num):
self.num = num
def update(self):
# Super shitty deacceleration model
self.vel = self.vel + (0.018/self.SPEEDX)*(self.speed - self.vel)
self.edge_dist += self.vel
while True:
e = self.e()
if self.edge_dist < e_dist[e]: break
if self.edge.dest.typ == track.NODE_SENSOR:
conn.set_sensor_tripped(self.edge.dest.num)
self.edge = self.edge.dest.edge[self.edge.dest.switch_direction]
self.edge_dist -= e_dist[e]
def draw(self, n_pos, da, cr):
e = self.e()
start, end = np.array(n_pos[e.source()]), np.array(n_pos[e.target()])
alpha = self.edge_dist / e_dist[e]
pos = start + alpha*(end - start)
dp = win.graph.pos_to_device(pos) # dp: device position
cr.rectangle(dp[0]-10, dp[1]-10, 20, 20)
cr.set_source_rgb(102. / 256, 102. / 256, 102. / 256)
cr.fill()
cr.move_to(dp[0]-10, dp[1] + 10 - 12./2)
cr.set_source_rgb(1., 1., 1.)
cr.set_font_size(12)
cr.show_text("%d" % self.num)
cr.fill()
def e(self): return g.edge(self.edge.src.i, self.edge.dest.i)
def set_speed(self, speed): self.speed = speed/self.SPEEDX
def toggle_reverse(self):
self.edge = self.edge.reverse
self.edge_dist = e_dist[self.e()] - self.edge_dist
def find_train(train_number):
for train in trains:
if train.num == train_number:
return train
train = Train(train_number)
trains.append(train)
return train
trains = [Train(12)]
#.........这里部分代码省略.........
示例13: makeGraphFast
# 需要导入模块: from graph_tool import Graph [as 别名]
# 或者: from graph_tool.Graph import new_edge_property [as 别名]
def makeGraphFast(self,img,dia,xScale,yScale):
print('Building Graph Data Structure'),
start=time.time()
G = Graph(directed=False)
sumAddVertices=0
vprop=G.new_vertex_property('object')
eprop=G.new_edge_property('object')
epropW=G.new_edge_property("float")
h, w = np.shape(img)
if xScale>0 and yScale>0: avgScale=(xScale+yScale)/2
else:
avgScale=1.
xScale=1.
yScale=1.
addedVerticesLine2=[]
vListLine2=[]
percentOld=0
counter=0
'''
Sweep over each line in the image except the last line
'''
for idx,i in enumerate(img[:len(img)-2]):
'''
Get foreground indices in the current line of the image and make vertices
'''
counter+=1
percent=(float(counter)/float(h))*100
if percentOld+10< percent:
print (str(np.round(percent,1))+'% '),
percentOld=percent
line1=np.where(i==True)
if len(line1[0])>0:
line1=set(line1[0]).difference(set(addedVerticesLine2))
vL=G.add_vertex(len(list(line1)))
if len(line1)>1 :
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)
#.........这里部分代码省略.........
示例14: makeGraph
# 需要导入模块: from graph_tool import Graph [as 别名]
# 或者: from graph_tool.Graph import new_edge_property [as 别名]
def makeGraph(self,img,dia,xScale,yScale):
print 'Building Graph Data Structure'
start=time.time()
G = Graph(directed=False)
vprop=G.new_vertex_property('object')
eprop=G.new_edge_property('object')
epropW=G.new_edge_property("int32_t")
avgScale=(xScale+yScale)/2
test=np.where(img==True)
ss = np.shape(test)
cccc=0
percentOld=0.0
print str(np.round(percentOld,1))+'%'
for (i,j) in zip(test[1],test[0]):
cccc+=1
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
#.........这里部分代码省略.........
示例15: gen_fs
# 需要导入模块: from graph_tool import Graph [as 别名]
# 或者: from graph_tool.Graph import new_edge_property [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