本文整理汇总了Python中networkx.get_edge_attributes函数的典型用法代码示例。如果您正苦于以下问题:Python get_edge_attributes函数的具体用法?Python get_edge_attributes怎么用?Python get_edge_attributes使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了get_edge_attributes函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: remove_nodes
def remove_nodes(g):
"""
Modifies the INPUT graph by removing all nodes, whose degree is 2.
Is not used.
"""
g1 = g.copy()
nodes = []
le = nx.get_edge_attributes(g, 'length')
for i in g1.nodes():
if nx.degree(g1, i) == 2:
nodes = np.append(nodes, i)
for i in nodes:
i = int(i)
n = list(nx.neighbors(g, i))
le = nx.get_edge_attributes(g, 'length')
th = nx.get_edge_attributes(g, 'thick')
num = nx.get_edge_attributes(g, 'number')
if len(n)==1:
continue
else:
n1 = n[0]
n2 = n[1]
k1 = num[min(n1, i), max(i, n1), 0]
k2 = num[min(n2, i), max(i, n2), 0]
l = le[min(n1, i), max(i, n1), 0] + le[min(i, n2), max(i, n2), 0]
t = (th[min(n1, i), max(i, n1), 0] + th[min(i, n2), max(i, n2), 0])/2.
le.update({(min(n1, n2), max(n2, n1), 0): l})
th.update({(min(n1, n2), max(n2, n1), 0): t})
num.update({(min(n1, n2), max(n2, n1), 0): k1+k2})
g.remove_node(i)
g.add_edge(n1, n2, length = l, thick = t, number = k1 + k2)
return g
示例2: weight_reshuffling
def weight_reshuffling(G,weight_tag='weight'):
'''
Input:
G: an undirected weighted network
IR_weight_cutoff: threshold on the minimum weight to reach
Output:
E: an undirected weighted graph with the same connectivity of G, but
reshuffled weights.
'''
print('Begin creation of weight reshuffled graph...');
weight_dictionary=nx.get_edge_attributes(G,'weight');
weight_sequence=weight_dictionary.values();
#preliminary scan of edge weights to define filtration steps
print('Preliminary scan of edge weights to define filtration steps...');
edge_weights=list(set(nx.get_edge_attributes(G,weight_tag).values()));
edge_weights=sorted(edge_weights, reverse=True);
print('Preliminary scan and sorting completed.');
E=nx.Graph();
E.add_nodes_from(G.nodes(data=True));
E.add_edges_from(G.edges());
E.remove_edges_from(E.selfloop_edges());
weight_sequence_temp=weight_sequence;
rn.shuffle(weight_sequence_temp);
print('Setting new weights.');
for e in E.edges_iter():
E.edge[e[0]][e[1]]['weight']=weight_sequence_temp[0];
weight_sequence_temp=weight_sequence_temp[1:];
print('Weights setup completed.');
return E
示例3: _reproduce_sexually
def _reproduce_sexually(self, partner): # TODO: Broken.
"""Sexual reproduction between two networks"""
inherited_state = -1 # -1 would be most recent
network_props = ['num_nodes']
node_props = ['threshold', 'energy_consumption', 'spontaneity']
# node_props = ['threshold']
edge_props = ['weight']
child = copy.deepcopy(self)
partner.children.append(child)
# partner.reproductive_energy_cost = self.reproductive_energy_cost
child.parents, child.children = [self, partner], []
if np.random.randint(0, 2) == 1:
internal_net = copy.deepcopy(self.internal)
child._cloned_from, child._not_cloned_from = self, partner
else:
internal_net = copy.deepcopy(partner.internal)
child._cloned_from, child._not_cloned_from = partner, self
# print "Kin with %d neurons, copied from net with %d neurons" %(internal_net.simdata[-1].number_of_nodes(), self.internal.simdata[-1].number_of_nodes())
child.set_internal_network(copy.deepcopy(internal_net), t0=self.t)
child.internal.simdata[inherited_state] = copy.copy(internal_net.simdata[inherited_state])
choices = np.random.randint(2, size=(2, len(node_props))) # randomly choose attributes
for j, n in enumerate(node_props):
p1 = nx.get_node_attributes(self.internal.simdata[inherited_state], n)
p2 = nx.get_node_attributes(partner.internal.simdata[inherited_state], n)
# add/remove nodal information based on the inherited number of nodes
# chosen = self if choices[0][j] else partner
# print "Using %s(N%d) for %s" %(chosen.ind_id, chosen.internal.simdata[inherited_state].number_of_nodes(), n)
utils.set_node_attributes(child.internal.simdata[inherited_state], n, p1 if choices[0][j] else p2)
for j, e in enumerate(edge_props):
p1 = nx.get_edge_attributes(self.internal.simdata[inherited_state], e)
p2 = nx.get_edge_attributes(partner.internal.simdata[inherited_state], e)
utils.set_edge_attributes(child.internal.simdata[inherited_state], n, p1 if choices[1][j] else p2)
return child
示例4: short_branches
def short_branches():
"""
Visualization of short branches of the skeleton.
"""
data1_sk = glob.glob('/backup/yuliya/vsi05/skeletons_largdom/*.h5')
data1_sk.sort()
for i,j, k in zip(d[1][37:47], data1_sk[46:56], ell[1][37:47]):
g = nx.read_gpickle(i)
dat = tb.openFile(j)
skel = np.copy(dat.root.skel)
bra = np.copy(dat.root.branches)
mask = np.zeros_like(skel)
dat.close()
length = nx.get_edge_attributes(g, 'length')
number = nx.get_edge_attributes(g, 'number')
num_dict = {}
for m in number:
for v in number[m]:
num_dict.setdefault(v, []).append(m)
find_br = ndimage.find_objects(bra)
for l in list(length.keys()):
if length[l]<0.5*k: #Criteria
for b in number[l]:
mask[find_br[b-1]] = bra[find_br[b-1]]==b
mlab.figure(bgcolor=(1,1,1), size=(1200,1200))
mlab.contour3d(skel, colormap='hot')
mlab.contour3d(mask)
mlab.savefig('/backup/yuliya/vsi05/skeletons/short_bran/'+ i[42:-10] + '.png')
mlab.close()
示例5: _calc_attr_fuzzy_hist
def _calc_attr_fuzzy_hist(self, G, attr, fuzzy_intervals):
"""
Computes the fuzzy histogram for an attribute. Returns the
number of elements in each bin
Args:
G: nx.Graph
attr: Attribute name
fuzzy_intervals: list(list(a,b,c,d)) defining a traperzoidal fuzzy histogram
Returns:
list(elem_per_bin)
"""
fi = fuzzy_intervals
vals = nx.get_edge_attributes(G, attr) if nx.get_edge_attributes(G, attr) else nx.get_node_attributes(G, attr)
vec = [0.0]*len(fi)
for elem in vals:
val = vals[elem]
for i, interval in enumerate(fi):
if (val >= interval[0]) and (val < interval[1]):
vec[i] += (val-interval[0]) / (interval[1]-interval[0])
elif (val >= interval[1]) and (val <= interval[2]):
vec[i] += 1
elif (val > interval[2]) and (val <= interval[3]):
vec[i] += (val-interval[3]) / (interval[2]-interval[3])
else:
pass
return vec
示例6: length_distr_total
def length_distr_total():
"""
Length distribution total (all images). For all the branches and broken ones.
d1 : array of lists of pathes for the break-ups dictionaries.
d : array of lists of pathes for the graphs
ell : array of lists of length scales
pa : list of experiment names (pathes)
"""
for data, data1, path, el in zip(d, d1, pa, ell):
l1 = list() #all branches
l2 = list() #breaking branches
u = 0
for i,j,le in zip(data, data1, el):
g = nx.read_gpickle(i)
br = np.load(j).item()
length = nx.get_edge_attributes(g, 'length')
l_mean = np.mean(np.asarray(length.values()))
number = nx.get_edge_attributes(g, 'number')
num_dict = {}
for k in number:
for v in number[k]:
num_dict.setdefault(v, []).append(k)
for k in length.values():
l1.append(k/float(1))
for k in br.keys():
for l in num_dict[k]:
l2.append(length[l]/float(1))
u+=1
hist1, bins1 = np.histogram(l1, np.arange(0, max(l1)+1, 0.06))
hist2, bins2 = np.histogram(l2, np.arange(0, max(l1)+1, 0.06))
center1 = (bins1[:-1] + bins1[1:])/2
center2 = (bins2[:-1] + bins2[1:])/2
#save to file if necessary
#np.save('/home/yuliya/codes/lengths/' + path + '/total_lno_all_len.npy', center1)
#np.save('/home/yuliya/codes/lengths/' + path + '/total_lno_break_len.npy', center2)
#np.save('/home/yuliya/codes/lengths/' + path + '/total_lno_all.npy', hist1/float(len(l1)))
#np.save('/home/yuliya/codes/lengths/' + path + '/total_lno_break.npy', hist2/float(len(l1)))
#Plot it
##plt.figure(2)
#hist1, bins1 = np.histogram(l1, np.arange(0, max(l1)+1, 0.06))
#hist2, bins2 = np.histogram(l2, np.arange(0, max(l2)+1, 0.06))
#center1 = (bins1[:-1] + bins1[1:])/2
#center2 = (bins2[:-1] + bins2[1:])/2
#plt.plot(center1, hist1/float(len(l1)), '.', color='red', label = 'all branches')
#plt.plot(center2, hist2/float(len(l1)), '.', color='blue', label = 'breaking branches')
#
"""
Probability as a function of length.
"""
hist1, bins1 = np.histogram(l1, np.arange(0, max(l1)+1, 0.1))
hist2, bins2 = np.histogram(l2, np.arange(0, max(l2)+1, 0.1))
center1 = (bins1[:-1] + bins1[1:])/2
plt.plot(center1, hist2/hist1.astype('float32'), '.', color='green', label = 'v35')
示例7: no_paralleling_set
def no_paralleling_set(name_tups, G):
nodes_number = G.nodes()
edge_type_data = nx.get_edge_attributes(G,'type')
node_name_data = nx.get_node_attributes(G,'name')
edge_name_data = nx.get_edge_attributes(G,'name')
num_tups = []
for i in range(0, len(name_tups)):
for j in range(0, len(nodes_number)):
x = nodes_number[j]
if node_name_data[x] == name_tups[i]:
num_tups.append(x)
#check if there's invalid input component
if j == len(nodes_number):
print 'Error: Component ' + e_bus_list[i] + ' Not Found'
exit()
specs_assert = ''
for i in range(0, len(num_tups)-1):
for j in range(i+1, len(num_tups)):
tups = list(nx.all_simple_paths(G, num_tups[i], num_tups[j]))
clause = '(assert (not'
if len(tups)>1: clause += ' (or'
if tups != []:
for k in range(0,len(tups)):
clause += ' (and'
one_path = tups[k]
for x in range(0,len(one_path)-1):
if edge_type_data[(one_path[x],one_path[x+1])]=='contactor':
clause += ' ' + edge_name_data[(one_path[x],one_path[x+1])]
clause += ')'
if len(tups)>1: clause += ')))\n'
else: clause += '))\n'
specs_assert += clause
return specs_assert
示例8: no_paralleling
def no_paralleling(node1, node2, G):
nodes_number = G.nodes()
edge_type_data = nx.get_edge_attributes(G,'type')
node_name_data = nx.get_node_attributes(G,'name')
edge_name_data = nx.get_edge_attributes(G,'name')
num1 = num2 = 0
for i in range(0, len(nodes_number)):
x = nodes_number[i]
if node_name_data[x] == node1:
num1 = x
elif node_name_data[x] == node2:
num2 = x
#check if components are valid
if num1 == 0:
print 'Error: ' + node1 + ' Not Found'
exit()
if num2 == 0:
print 'Error: ' + node2 + ' Not Found'
exit()
tups = list(nx.all_simple_paths(G, num1, num2))
clause = '(assert (not'
if len(tups)>1: clause += ' (or'
if tups != []:
for k in range(0,len(tups)):
clause += ' (and'
one_path = tups[k]
for x in range(0,len(one_path)-1):
if edge_type_data[(one_path[x],one_path[x+1])]=='contactor':
clause += ' ' + edge_name_data[(one_path[x],one_path[x+1])]
clause += ')'
if len(tups)>1: clause += ')))\n'
else: clause += '))\n'
return clause
示例9: test_clear_delays
def test_clear_delays(self):
topo = fnss.star_topology(12)
fnss.set_delays_constant(topo, 1, 'ms', None)
self.assertEqual(topo.number_of_edges(),
len(nx.get_edge_attributes(topo, 'delay')))
fnss.clear_delays(topo)
self.assertEqual(0, len(nx.get_edge_attributes(topo, 'delay')))
示例10: compare_list
def compare_list(self, graph_list, types, h, D):
"""
Compute the all-pairs kernel values for a list of graph representations of verification tasks
"""
all_graphs_number_of_nodes = 0
node_labels = [0] * (h+1)
node_depth = [0] * len(graph_list)
edge_types = [0] * len(graph_list)
edge_truth = [0] * len(graph_list)
for it in range(h+1):
node_labels[it] = [0] * len(graph_list)
for i, g in enumerate(graph_list):
node_labels[0][i] = {key: self._compress(value)
for key, value in nx.get_node_attributes(g, 'label').items()}
node_depth[i] = nx.get_node_attributes(g, 'depth')
edge_types[i] = nx.get_edge_attributes(g, 'type')
edge_truth[i] = nx.get_edge_attributes(g, 'truth')
all_graphs_number_of_nodes += len([node for node in nx.nodes_iter(g) if node_depth[i][node] <= D])
# if i == 0:
# self._graph_to_dot(g, node_labels[0][i], "graph{}.dot".format(i))
# all_graphs_number_of_nodes is upper bound for number of possible edge labels
phi = np.zeros((all_graphs_number_of_nodes, len(graph_list)), dtype=np.uint64)
# h = 0
for i, g in enumerate(graph_list):
for node in g.nodes_iter():
if node_depth[i][node] <= D:
label = node_labels[0][i][node]
phi[self._compress(label), i] += 1
K = np.dot(phi.transpose(), phi)
# h > 0
for it in range(1, h+1):
# Todo check if the shape fits in all cases
phi = np.zeros((2*all_graphs_number_of_nodes, len(graph_list)), dtype=np.uint64)
print('Updating node labels of graphs in iteration {}'.format(it), flush=True)
# for each graph update edge labels
for i, g in tqdm(list(enumerate(graph_list))):
node_labels[it][i] = {}
for node in g.nodes_iter():
if node_depth[i][node] <= D:
label_collection = self._collect_labels(node, i, g, it-1, node_labels, node_depth, types, D, edge_types, edge_truth)
long_label = "_".join(str(x) for x in [np.concatenate([np.array([node_labels[it-1][i][node]]),
np.sort(label_collection)])])
node_labels[it][i][node] = self._compress(long_label)
phi[self._compress(long_label), i] += 1
# node_labels[it][i][node] = long_label
# phi[self._compress(long_label), i] += 1
# if i == 0:
# self._graph_to_dot(g, node_labels[it][i], "graph{}_it{}.dot".format(i, it))
K += np.dot(phi.transpose(), phi)
return K
示例11: build
def build(self):
'''
Produce a ``circuit``.
'''
g = self._g
voltages = nx.get_edge_attributes(g, '_voltage')
resistances = nx.get_edge_attributes(g, '_resistance')
sources = nx.get_edge_attributes(g, '_source')
# class invariant of CircuitBuilder; no attribute ever appears without the other two
assert set(voltages) == set(resistances) == set(sources)
# this covers edges present in the initial graph (passed into the constructor)
# which were not addressed via make_resistor and friends
missing_edges = [e for e in g.edges() if (e not in voltages) and (e[::-1] not in voltages)]
for e in missing_edges:
voltages[e] = self._DEFAULT_VOLTAGE
resistances[e] = self._DEFAULT_RESISTANCE
sources[e] = e[0]
copy = _copy_graph_without_attributes(g)
nx.set_edge_attributes(copy, EATTR_VOLTAGE, voltages)
nx.set_edge_attributes(copy, EATTR_RESISTANCE, resistances)
nx.set_edge_attributes(copy, EATTR_SOURCE, sources)
assert validate_circuit(copy)
return copy
示例12: normDAGl2Test
def normDAGl2Test(G_test, power):
kern = nx.get_edge_attributes(G_test, 'kern_unnorm')
tran = nx.get_edge_attributes(G_test, 'tran')
kern = OrderedDict(sorted(kern.items(), key=lambda t: t[0]))
val = kern.values()
key = kern.keys()
tran = OrderedDict(sorted(tran.items(), key=lambda t: t[0]))
tran = tran.values()
val = np.asarray(val, dtype=float)
tran = np.asarray(tran, dtype=float)
tran = np.log(1/tran) # logarithm weighting
tran[tran == np.inf] = 0
tran[np.isnan(tran)] = 0
if power == 2:
tran = np.square(tran)
if len(val.shape) == 2:
# kern = val/tran[:, None]
kern = val*tran[:, None] # avoid numeric problems when using logarithm weighting
kern = normalize(kern, norm='l2', axis=0)
else:
kern = val*tran
kern = kern/np.linalg.norm(kern)
kern = dict(zip(key, kern))
nx.set_edge_attributes(G_test, 'kern', kern)
return G_test
示例13: init
def init(G, uncon_comp_tups, contactor_tups):
nodes_number = G.nodes()
edges_number = G.edges()
node_name_data = nx.get_node_attributes(G, 'name')
edge_name_data = nx.get_edge_attributes(G, 'name')
edge_type_data = nx.get_edge_attributes(G, 'type')
node_type_data = nx.get_node_attributes(G, 'type')
declaration = '(set-option :print-success false)\n'
declaration += '(set-option :produce-models true)\n(set-logic QF_UF)\n'
for i in range(0, len(nodes_number)):
x = nodes_number[i]
node_type = node_type_data[x]
if node_type != 'dummy':
clause = '(declare-fun ' + node_name_data[x] + ' () Bool)\n'
if node_type == 'generator' or node_type=='APU' or node_type == 'rectifier_dc':
uncon_comp_tups.append(node_name_data[x])
declaration += clause
for i in range(0, len(edges_number)):
idx = edges_number[i]
edge_type = edge_type_data[idx]
if edge_type == 'contactor':
edge_name = edge_name_data[idx]
flag = 0
for j in range(0, len(contactor_tups)):
if edge_name == contactor_tups[j]:
flag = 1
break
if flag == 0: contactor_tups.append(edge_name)
for i in range(0, len(contactor_tups)):
clause = '(declare-fun ' + contactor_tups[i] + ' () Bool)\n'
declaration += clause
return declaration
示例14: aspect_rat_distr_total
def aspect_rat_distr_total():
"""
Aspect ratio distribution.
d1 : list of pathes for the break-ups dictionaries. Used here for the
estimation of the necessary number of pairs.
d : list of pathes for the graphs
ell : list of length scales
pa : array of the pathes to the experiments folder (to save data)
"""
for data, data1, path, el in zip(d, d1, pa, ell):
l1 = list() #all branches
l2 = list() #breaking branches
u = 0
for i,j in zip(data, data1):
g = nx.read_gpickle(i)
br = np.load(j).item()
thick = nx.get_edge_attributes(g, 'thick')
m_th = np.mean(np.asarray(thick.values()))
length = nx.get_edge_attributes(g, 'length')
m_le = np.mean(np.asarray(length.values()))
number = nx.get_edge_attributes(g, 'number')
num_dict = {}
for k in number:
for v in number[k]:
num_dict.setdefault(v, []).append(k)
for k,l in zip(thick.values(), length.values()):
l1.append(float(l)*m_th/(m_le * k))
for k in br.keys():
for l in num_dict[k]:
l2.append(float(length[l] * m_th)/(m_le * thick[l]))
u+=1
hist1, bins1 = np.histogram(l1, np.arange(0, max(l1)+1, 0.3))
hist2, bins2 = np.histogram(l2, np.arange(0, max(l1)+1, 0.3))
center1 = (bins1[:-1] + bins1[1:])/2
center2 = (bins2[:-1] + bins2[1:])/2
# np.save('/home/yuliya/codes/lengths/' + path + '/total_arm_all_len.npy', center1)
# np.save('/home/yuliya/codes/lengths/' + path + '/total_arm_break_len.npy', center2)
# np.save('/home/yuliya/codes/lengths/' + path + '/total_arm_all.npy', hist1/float(len(l1)))
# np.save('/home/yuliya/codes/lengths/' + path + '/total_arm_break.npy', hist2/float(len(l1)))
plt.plot(center1, hist1/float(len(l1)), '.', color='red', label = 'all branches')
plt.plot(center2, hist2/float(len(l1)), '.', color='blue', label = 'breaking branches')
plt.legend()
plt.xlabel('l / d', fontsize=18)
plt.ylabel('P(l/d)', fontsize = 18)
"""
Probability as a function of aspect ratio.
"""
hist1, bins1 = np.histogram(l1, np.arange(0, max(l1)+1, 0.3))
hist2, bins2 = np.histogram(l2, np.arange(0, max(l1)+1, 0.3))
center1 = (bins1[:-1] + bins1[1:])/2
plt.plot(center1, hist2/hist1.astype('float32'), '.', color='red', label = 'v34')
plt.legend()
plt.xlabel('d / l', fontsize = 18)
plt.ylabel('Breakup Probability', fontsize = 18)
示例15: test_clear_weights
def test_clear_weights(self):
# create new topology to avoid parameters pollution
G = fnss.star_topology(12)
fnss.set_weights_constant(G, 3, None)
self.assertEqual(G.number_of_edges(),
len(nx.get_edge_attributes(G, 'weight')))
fnss.clear_weights(G)
self.assertEqual(0, len(nx.get_edge_attributes(G, 'weight')))