• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

Python networkx.get_edge_attributes函数代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了Python中networkx.get_edge_attributes函数的典型用法代码示例。如果您正苦于以下问题:Python get_edge_attributes函数的具体用法?Python get_edge_attributes怎么用?Python get_edge_attributes使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。



在下文中一共展示了get_edge_attributes函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的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
开发者ID:YuliyaKar,项目名称:Skeleton_to_graph-labeling-,代码行数:32,代码来源:graph_vis.py


示例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
开发者ID:ISIMathLab,项目名称:Holes,代码行数:34,代码来源:randomization.py


示例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
开发者ID:hurtb,项目名称:pyBrainNetSim,代码行数:35,代码来源:world.py


示例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()
开发者ID:YuliyaKar,项目名称:Skeleton_to_graph-labeling-,代码行数:32,代码来源:graph_analisys.py


示例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
开发者ID:mmabrouk,项目名称:fmge,代码行数:26,代码来源:fmge.py


示例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')
开发者ID:YuliyaKar,项目名称:Skeleton_to_graph-labeling-,代码行数:60,代码来源:graph_analisys.py


示例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
开发者ID:EPS-Con,项目名称:eps-reconfig,代码行数:33,代码来源:specs.py


示例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
开发者ID:EPS-Con,项目名称:eps-reconfig,代码行数:33,代码来源:specs.py


示例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')))
开发者ID:brucespang,项目名称:fnss,代码行数:7,代码来源:test_delays.py


示例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
开发者ID:zenscr,项目名称:PyPRSVT,代码行数:60,代码来源:GK_WL.py


示例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
开发者ID:ExpHP,项目名称:defect,代码行数:26,代码来源:circuit.py


示例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
开发者ID:YuxinSun,项目名称:Dynamic-Programming-LPBoost-for-TcR-Classification,代码行数:32,代码来源:RootKernel.py


示例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
开发者ID:EPS-Con,项目名称:eps-reconfig,代码行数:32,代码来源:specs.py


示例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)
开发者ID:YuliyaKar,项目名称:Skeleton_to_graph-labeling-,代码行数:59,代码来源:graph_analisys.py


示例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')))
开发者ID:brucespang,项目名称:fnss,代码行数:8,代码来源:test_weights.py


示例16: populate_internal_edges

 def populate_internal_edges(self):
     for block in self.blocks:
         weight = nx.get_edge_attributes(block, "weight")
         capacity = nx.get_edge_attributes(block, "capacity")
         for edge in block.edges():
             self.add_edge(edge[0], edge[1],
                           weight=weight[edge],
                           capacity=capacity[edge])
开发者ID:PaulGilmartin,项目名称:alloa,代码行数:8,代码来源:graph.py


示例17: local_standard_weight_clique_rank_filtration

def local_standard_weight_clique_rank_filtration(G,IR_weight_cutoff=None,verbose=False):
    
    if IR_weight_cutoff==None:
        IR_weight_cutoff=np.min(nx.get_edge_attributes(G,'weight').values());

    print('Preliminary scan of edge weights to define filtration steps...');
    edge_weights=nx.get_edge_attributes(G,'weight');
    weight_edge = {}
    for e,w in edge_weights.items():
        if w not in weight_edge:
            weight_edge[w] = []
        weight_edge[w].append(e);

    edge_weights=list(set(edge_weights.values()));
    edge_weights=sorted(edge_weights, reverse=True);
    max_index=len(edge_weights);
        
    # Define the clique dictionary
    Clique_dictionary={};
    print('Constructing filtration...');
    #Beginning of filtration construction
    G_supplementary=nx.Graph();

    #the max index will be used for the persistent homology computation 
    max_index=0; 
    current_nodes = []
    
    for index,thr in enumerate(edge_weights):
        new_nodes = [];
        if thr>=IR_weight_cutoff:
            G_supplementary.add_edges_from(weight_edge[thr]);
            [new_nodes.extend(edge) for edge in weight_edge[thr]];
            new_nodes = list(set(new_nodes));

            ## clique detection in partial graph, where there cliques are found only on the
            ## new nodes.
            relevant_nodes = []
            [relevant_nodes.extend(G_supplementary.neighbors(n)) for n in new_nodes];
            relevant_nodes = list(set(relevant_nodes));
            G_supp_supp = nx.subgraph(G_supplementary,relevant_nodes);
            cliques=nx.find_cliques_recursive(G_supp_supp);
            # adding cliques to the filtration
            for clique in cliques: #loop on new clique
                clique.sort();

                for k in range(1,len(clique)+1): #loop on clique dimension to find missed faces of simplex
                    for subclique in itertools.combinations(clique,k):
                        if str(list(subclique)) not in Clique_dictionary:
                            Clique_dictionary[str(list(subclique))]=[];
                            Clique_dictionary[str(list(subclique))].append(str(index));
                            Clique_dictionary[str(list(subclique))].append(str(thr))
                            max_index=index;

    print('Max filtration value: '+str(max_index));              
    print('Clique dictionary created.');
    return Clique_dictionary;
开发者ID:lordgrilo,项目名称:Holes,代码行数:56,代码来源:filtrations.py


示例18: IsUnassigned

def IsUnassigned(G, node1, node2):
    for key in nx.get_edge_attributes(G, 'value').keys():
        if(key[0] == node1 and key[1] == node2):
            if (nx.get_edge_attributes(G, 'value')[key] == 'x'):
                return True
            else:
                "Do nothing"
        else:
            "Continue search"
    return False
开发者ID:abhowmick22,项目名称:atpg-PODEM,代码行数:10,代码来源:atpg_combinational_5valued.py


示例19: populate_internal_edges

 def populate_internal_edges(self):
     """
     Adds in each block in block list to the allocation graph. Blocks remain disjoint at this point.
     """
     for block in self.blocks:
         weight = nx.get_edge_attributes(block, "weight")  # {edge: edge attribute for edge in block.edges()}
         capacity = nx.get_edge_attributes(block, "capacity")
         for edge in block.edges():
             self.add_edge(edge[0], edge[1],
                           weight=weight[edge],
                           capacity=capacity[edge])
开发者ID:PaulGilmartin,项目名称:alloa,代码行数:11,代码来源:mygraph.py


示例20: read_network_from_file

def read_network_from_file(edge_file, node_file):
    """"""

    '''
    Get edge list, thresholds and nodes from file

    Arguments:
        edge_file [csv delimited .dat file]
            format:
            source_node [str] , target_node [str] , weight [bool]

        node_file [csv delimited .dat file]
            format:
            node [str] , state [bool]

    Outputs:
        G [networkx Graph object]


    NOTES:
        weight = 1 if edge is inductive
        weight = 0 if edge is inhibiting

        state = 1 if expressed
        state = 0 if not expressed 

        weight and state are boolean, but MUST be 0 or 1.
        DO NOT USE 'True' and 'False'. 
        They will not be evaluated correctly.
    '''

    ## read edge list with its weight from edge_file
    G = nx.read_edgelist(edge_file, create_using=nx.DiGraph(), delimiter=',', nodetype=str, data=(('weight', int),))
    ## Raise error if weight is not a 0 or 1
    for edge in nx.get_edge_attributes(G,'weight'):
        weight = nx.get_edge_attributes(G,'weight')[edge]
        if weight != 0 and weight != 1:
            raise ValueError("All weights must be boolean, represented as either 0 or 1")

    ## read node list with its state from node_file
    for line in open(node_file, 'r').readlines():
        items = [x.strip() for x in line.rstrip().split(',')]
        # print items
        if line[0] == '#' or line=='':
            continue
        G.add_node(items[0], state=int(items[1]))
    ## Raise error if state is not a 0 or 1
    for node in nx.get_node_attributes(G,'state'):
        state = nx.get_node_attributes(G,'state')[node]
        if state != 0 and state != 1:
            raise ValueError("All states must be boolean, represented as either 0 or 1")

    return G
开发者ID:SES591,项目名称:cortical_network,代码行数:53,代码来源:input_net.py



注:本文中的networkx.get_edge_attributes函数示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Python networkx.get_node_attributes函数代码示例发布时间:2022-05-27
下一篇:
Python networkx.generate_gml函数代码示例发布时间:2022-05-27
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap