def dist_between(x, a, b):
""" Returns the geodesic distance between nodes in nanometers.
Parameters
----------
x : {CatmaidNeuron, CatmaidNeuronList}
Neuron containing the nodes
a, b : treenode IDs
Treenodes to check.
Returns
-------
int
distance in nm
See Also
--------
:func:`~pymaid.distal_to`
Check if a node A is distal to node B.
:func:`~pymaid.geodesic_matrix`
Get all-by-all geodesic distance matrix.
"""
if isinstance( x, core.CatmaidNeuronList ):
if len(x) == 1:
x = x[0]
else:
raise ValueError('Need a single CatmaidNeuron')
elif isinstance( x, core.CatmaidNeuron ):
pass
else:
raise ValueError('Unable to process data of type {0}'.format(type(x)))
try:
_ = int(a)
_ = int(b)
except:
raise ValueError('a, b need to be treenode IDs')
return int( nx.algorithms.shortest_path_length( g.to_undirected(as_view=True),
a, b,
weight='weight') )
python类shortest_path_length()的实例源码
def sp_kernel(g1, g2=None):
if g2 is not None:
graphs = []
for g in g1:
graphs.append(g)
for g in g2:
graphs.append(g)
else:
graphs = g1
sp_lengths = []
for graph in graphs:
sp_lengths.append(nx.shortest_path_length(graph))
N = len(graphs)
all_paths = {}
sp_counts = {}
for i in range(N):
sp_counts[i] = {}
nodes = graphs[i].nodes()
for v1 in nodes:
for v2 in nodes:
if v2 in sp_lengths[i][v1]:
label = sp_lengths[i][v1][v2]
if label in sp_counts[i]:
sp_counts[i][label] += 1
else:
sp_counts[i][label] = 1
if label not in all_paths:
all_paths[label] = len(all_paths)
phi = np.zeros((N, len(all_paths)))
for i in range(N):
for label in sp_counts[i]:
phi[i, all_paths[label]] = sp_counts[i][label]
if g2 is not None:
K = np.dot(phi[:len(g1), :], phi[len(g1):, :].T)
else:
K = np.dot(phi, phi.T)
return K
graph_kernels_labeled.py 文件源码
项目:TextAsGraphClassification
作者: NightmareNyx
项目源码
文件源码
阅读 28
收藏 0
点赞 0
评论 0
def sp_kernel(g1, g2=None):
with Timer("SP kernel"):
if g2 is not None:
graphs = []
for g in g1:
graphs.append(g)
for g in g2:
graphs.append(g)
else:
graphs = g1
sp_lengths = []
for graph in graphs:
sp_lengths.append(nx.shortest_path_length(graph))
N = len(graphs)
all_paths = {}
sp_counts = {}
for i in range(N):
sp_counts[i] = {}
nodes = graphs[i].nodes()
for v1 in nodes:
for v2 in nodes:
if v2 in sp_lengths[i][v1]:
label = tuple(
sorted([graphs[i].node[v1]['label'], graphs[i].node[v2]['label']]) + [
sp_lengths[i][v1][v2]])
if label in sp_counts[i]:
sp_counts[i][label] += 1
else:
sp_counts[i][label] = 1
if label not in all_paths:
all_paths[label] = len(all_paths)
phi = lil_matrix((N, len(all_paths)))
for i in range(N):
for label in sp_counts[i]:
phi[i, all_paths[label]] = sp_counts[i][label]
if g2 is not None:
K = np.dot(phi[:len(g1), :], phi[len(g1):, :].T)
else:
K = np.dot(phi, phi.T)
return K.todense()