当前位置: 首页>>代码示例>>Python>>正文


Python Graph.add_edges_from方法代码示例

本文整理汇总了Python中networkx.Graph.add_edges_from方法的典型用法代码示例。如果您正苦于以下问题:Python Graph.add_edges_from方法的具体用法?Python Graph.add_edges_from怎么用?Python Graph.add_edges_from使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在networkx.Graph的用法示例。


在下文中一共展示了Graph.add_edges_from方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: convert_local_tree_topology_to_graph

# 需要导入模块: from networkx import Graph [as 别名]
# 或者: from networkx.Graph import add_edges_from [as 别名]
def convert_local_tree_topology_to_graph(loc_tree_topo, tree_node_labeling):
    """ Creates a directed, acyclic NetworkX graph from a local tree topology

    Parameters
    ----------
    loc_tree_topo: array-like
        The local tree toplogy, where the root node element is -1

    tree_node_labeling: array-like
        The integer ids for each tree node

    Returns
    -------
    G : NetworkX graph

    """

    assert( loc_tree_topo[0] == -1 )

    G = Graph()
    G.add_nodes_from( tree_node_labeling )
    # build up graph connectivity
    con = vstack( (loc_tree_topo, range(len(loc_tree_topo))) )
    # prune root node connectivity
    con = con[:,1:]
    # update with correct labels
    con = tree_node_labeling[con]
    G.add_edges_from( zip(con[0,:], con[1,:]) )

    return G
开发者ID:unidesigner,项目名称:unidesign,代码行数:32,代码来源:tree.py

示例2: tuples_to_graph

# 需要导入模块: from networkx import Graph [as 别名]
# 或者: from networkx.Graph import add_edges_from [as 别名]
def tuples_to_graph(tuples):
    G = Graph()
    for node, attribute in tuples:
        print 'adding', node, attribute
        G.add_nodes_from(node, freq=attribute)
        G.add_edges_from(to_edges(node))
    return G
开发者ID:asvishen,项目名称:Factoid-Question-Answering,代码行数:9,代码来源:color.py

示例3: compute_molecule

# 需要导入模块: from networkx import Graph [as 别名]
# 或者: from networkx.Graph import add_edges_from [as 别名]
def compute_molecule(universe):
    '''
    Cluster atoms into molecules.

    The algorithm is to create a network graph containing every atom (in every
    frame as nodes and bonds as edges). Using this connectivity information,
    one can perform a (breadth first) traversal of the network graph to cluster
    all nodes (whose indices correspond to physical atoms).

    Args:
        universe (:class:`~exatomic.universe.Universe`): Atomic universe

    Returns:
        objs (tuple): Molecule indices (for atom dataframe(s)) and molecule dataframe

    Warning:
        This function will modify (in place) a few tables of the universe!
    '''
    if 'bond_count' not in universe.atom:    # The bond count is used to find single atoms;
        universe.compute_bond_count()        # single atoms are treated as molecules.
    b0 = None
    b1 = None
    bonded = universe.two[universe.two['bond'] == True]
    if universe.is_periodic:
        mapper = universe.projected_atom['atom']
        b0 = bonded['prjd_atom0'].map(mapper)
        b1 = bonded['prjd_atom1'].map(mapper)
    else:
        b0 = bonded['atom0']
        b1 = bonded['atom1']
    graph = Graph()
    graph.add_edges_from(zip(b0.values, b1.values))
    mapper = {}
    for i, molecule in enumerate(connected_components(graph)):
        for atom in molecule:
            mapper[atom] = i
    n = 1
    if len(mapper.values()) > 0:
        n += max(mapper.values())
    else:
        n -= 1
    idxs = universe.atom[universe.atom['bond_count'] == 0].index
    for i, index in enumerate(idxs):
        mapper[index] = i + n
    # Set the molecule indices
    universe.atom['molecule'] = universe.atom.index.map(lambda idx: mapper[idx])
    # Now compute molecule table
    universe.atom['mass'] = universe.atom['symbol'].map(symbol_to_element_mass)
    # The coordinates of visual_atom represent grouped molecules for
    # periodic calculations and absolute coordinates for free boundary conditions.
    molecules = universe.atom.groupby('molecule')
    molecule = molecules['symbol'].value_counts().unstack().fillna(0).astype(np.int64)
    molecule.columns.name = None
    molecule['frame'] = universe.atom.drop_duplicates('molecule').set_index('molecule')['frame']
    molecule['mass'] = molecules['mass'].sum()
    del universe.atom['mass']
    frame = universe.atom[['molecule', 'frame']].drop_duplicates('molecule')
    frame = frame.set_index('molecule')['frame'].astype(np.int64)
    molecule['frame'] = frame.astype('category')
    return Molecule(molecule)
开发者ID:gitter-badger,项目名称:exatomic,代码行数:62,代码来源:molecule.py

示例4: _update_unfit_groups_with_crossgroup_dist

# 需要导入模块: from networkx import Graph [as 别名]
# 或者: from networkx.Graph import add_edges_from [as 别名]
def _update_unfit_groups_with_crossgroup_dist(dist_metrics, fit_group, fit_pvals, unfit_group, buffer_group,
                                              user_ids, user_profiles, user_connections, ks_alpha=0.05):
    """ update members in unfit_group with cross-group distance. unfit members are kept in buffer_group
    """
    # to keep API consistant
    # restore user_profiles to DataFrame including
    user_graph = Graph()
    user_graph.add_edges_from(user_connections)

    unfit_group_copy = unfit_group.copy()
    for gg, gg_user_ids in unfit_group_copy.items():
        # extract cross-group distance metrics dictionary to avoid duplicate
        # tests with distance metrics associated with user's group
        other_group_keys = [group_key for group_key in dist_metrics.keys() if not group_key == gg]
        cross_group_dist_metrics = {key: dist_metrics[key] for key in other_group_keys}

        for ii, ii_user_id in enumerate(gg_user_ids):
            ii_new_group, ii_new_pval = find_fit_group(ii_user_id, cross_group_dist_metrics,
                                                       user_ids, user_profiles, user_graph, ks_alpha,
                                                       current_group=None, fit_rayleigh=False)
            # redistribute the user based on fit-tests
            if not ii_new_group is None:
                # remove member with fit from buffer_group
                if ii_new_group in fit_group:
                    fit_group[ii_new_group].append(ii_user_id)
                    fit_pvals[ii_new_group].append(ii_new_pval)
                else:
                    fit_group[ii_new_group] = [ii_user_id]
                    fit_pvals[ii_new_group] = [ii_new_pval]
            else:
                buffer_group.append(ii_user_id)

    return fit_group, fit_pvals, buffer_group
开发者ID:beingzy,项目名称:user_recommender_framework,代码行数:35,代码来源:groupwise_distance_learner.py

示例5: extract_colored_faces

# 需要导入模块: from networkx import Graph [as 别名]
# 或者: from networkx.Graph import add_edges_from [as 别名]
def extract_colored_faces(fname, colors):
    output = {color:[] for color in colors}
    vertices, faces = load_ply(fname)
    
    for color in colors:
        colored_vertices_indices = np.nonzero((vertices['color'] == color).all(axis=1))[0]
        colored_faces = np.nonzero(np.all((np.in1d(faces["indices"][:,0], colored_vertices_indices),
                                           np.in1d(faces["indices"][:,1], colored_vertices_indices),
                                           np.in1d(faces["indices"][:,2], colored_vertices_indices)), axis=0))[0]

        colored_faces_graph = Graph()
        colored_faces_graph.add_edges_from(faces['indices'][colored_faces][:,:2])
        colored_faces_graph.add_edges_from(faces['indices'][colored_faces][:,1:])
        colored_faces_graph.add_edges_from(faces['indices'][colored_faces][:,(0,2)])
        
        planes_vertices_indices = list(connected_components(colored_faces_graph))
        print len(planes_vertices_indices)
        for  plane_vertices_indices in planes_vertices_indices:
                colored_vertices = vertices["position"][list(plane_vertices_indices)]
                dipdir, dip = calc_sphere(*general_axis(colored_vertices, -1))
                X, Y, Z = colored_vertices.mean(axis=0)
                highest_vertex = colored_vertices[np.argmax(colored_vertices[:,2]),:]
                lowest_vertex = colored_vertices[np.argmin(colored_vertices[:,2]),:]
                trace = np.linalg.norm(highest_vertex - lowest_vertex)
                output[color].append((dipdir, dip, X, Y, Z, trace))
    return output
开发者ID:endarthur,项目名称:ply2atti-scanline,代码行数:28,代码来源:ply2atti-bin.py

示例6: _update_buffer_group

# 需要导入模块: from networkx import Graph [as 别名]
# 或者: from networkx.Graph import add_edges_from [as 别名]
def _update_buffer_group(dist_metrics, fit_group, fit_pvals, buffer_group,
                         user_ids, user_profiles, user_connections, ks_alpha=0.05):
    """ return fit_group, fit_pvals, buffer_group
        redistribute member in buffer group into fit_group if fit had been found
    """
    # to keep API consistant
    # restore user_profiles to DataFrame including
    user_graph = Graph()
    user_graph.add_edges_from(user_connections)

    buffer_group_copy = buffer_group.copy()
    if len(buffer_group_copy) > 0:
        for ii, ii_user_id in enumerate(buffer_group_copy):
            ii_new_group, ii_new_pval = find_fit_group(ii_user_id, dist_metrics,
                                                       user_ids, user_profiles, user_graph, ks_alpha,
                                                       current_group=None, fit_rayleigh=False)
            if not ii_new_group is None:
                # remove member with fit from buffer_group
                buffer_group.remove(ii_user_id)
                if ii_new_group in fit_group:
                    fit_group[ii_new_group].append(ii_user_id)
                    fit_pvals[ii_new_group].append(ii_new_pval)
                else:
                    fit_group[ii_new_group] = [ii_user_id]
                    fit_pvals[ii_new_group] = [ii_new_pval]

    return fit_group, fit_pvals, buffer_group
开发者ID:beingzy,项目名称:user_recommender_framework,代码行数:29,代码来源:groupwise_distance_learner.py

示例7: eliminate_node

# 需要导入模块: from networkx import Graph [as 别名]
# 或者: from networkx.Graph import add_edges_from [as 别名]
def eliminate_node(G, a):
    fillins = ()
    nb = frozenset(G.neighbors(a))
    for u in nb:
        for v in nb - frozenset((u,)):
            if not G.has_edge(v, u) and frozenset((u, v)) not in fillins:
                fillins += (frozenset((u, v)),)
    kill_edges = frozenset([(u, a) for u in nb] + [(a, u) for u in nb])
    H = Graph()
    H.add_nodes_from(list(frozenset(G.nodes()) - frozenset((a,))))
    H.add_edges_from(list((frozenset(G.edges()) - kill_edges) | frozenset(fillins)))
    return H
开发者ID:darabbt,项目名称:les,代码行数:14,代码来源:minfill.py

示例8: _build_authors_graph

# 需要导入模块: from networkx import Graph [as 别名]
# 或者: from networkx.Graph import add_edges_from [as 别名]
    def _build_authors_graph(self):
        """
        Build authors graph with each author name as nodes and the collaboration between them as edges.

        @author 1: CipherHat

        @rtype:   networkx.Graph()
        @return:  the Graph containing nodes and edges
        """
        all_data = self.get_network_data()
        # TODO refactor: revision on this part. whether to move the Graph code to its own class
        graph = Graph()
        # the nodes format will be {"id":int, "name":str}
        graph.add_nodes_from([(i, {"name": all_data[0][i][0]}) for i in range(len(all_data[0]))])
        graph.add_edges_from(all_data[1])
        return graph
开发者ID:JeffriesAgile,项目名称:comp61542-2014-lab,代码行数:18,代码来源:database.py

示例9: get_coauthor_graph_by_author_name

# 需要导入模块: from networkx import Graph [as 别名]
# 或者: from networkx.Graph import add_edges_from [as 别名]
    def get_coauthor_graph_by_author_name(self, name):
        coauthors = set()
        for p in self.publications:
            for a in p.authors:
                if a == self.author_idx[name]:
                    for a2 in p.authors:
                        if a != a2:
                            coauthors.add(a2)

        graph = Graph()
        # the nodes format will be {"id":int, "name":str}
        graph.add_node(self.author_idx[name], name = name)
        # graph.add_nodes_from([(i, {"name": all_data[0][i][0]}) for i in range(len(all_data[0]))])
        graph.add_nodes_from([(ca, {"name": self.authors[ca].name}) for ca in coauthors])
        graph.add_edges_from([(self.author_idx[name], ca) for ca in coauthors])

        return graph
开发者ID:JeffriesAgile,项目名称:comp61542-2014-lab,代码行数:19,代码来源:database.py

示例10: post_process

# 需要导入模块: from networkx import Graph [as 别名]
# 或者: from networkx.Graph import add_edges_from [as 别名]
    def post_process(self):
        trackings = self.parents['irit_harmo_tracking'].results['irit_harmo_tracking'].data_object.value

        graph = Graph()

        for t, h in [(track, track.harmo_link(trackings)) for track in trackings]:

            graph.add_node(t)

            if len(h) > 0:

                graph.add_edges_from([(t, o) for o in h])

        res = self.new_result(time_mode='global')
        res.data_object.value = [c2 for c in connected_components(graph) for c2 in Cluster(c).harmo_sub()]
        self.add_result(res)

        return
开发者ID:ANR-DIADEMS,项目名称:timeside-diadems,代码行数:20,代码来源:irit_harmo_cluster.py

示例11: test_two_communities

# 需要导入模块: from networkx import Graph [as 别名]
# 或者: from networkx.Graph import add_edges_from [as 别名]
def test_two_communities():
    test = Graph()

    # c1
    c1_edges = [(0, 2), (0, 3), (0, 4), (0, 5), (1, 2), (1, 4), (1, 7), (2, 4), (2, 5),\
                    (2, 6), (3, 7), (4, 10), (5, 7), (5, 11), (6, 7), (6, 11)]

    # c2
    c2_edges = [(8, 9), (8, 10), (8, 11), (8, 14), (8, 15), (9, 12), (9, 14), (10, 11),\
                    (10, 12), (10, 13), (10, 14), (11, 13)]
    test.add_edges_from(c1_edges + c2_edges)

    # ground truth
    ground_truth = set([frozenset([0, 1, 2, 3, 4, 5, 6, 7]),
                        frozenset([8, 9, 10, 11, 12, 13, 14, 15])])

    communities = asyn_lpa.asyn_lpa_communities(test)
    result = {frozenset(c) for c in communities}
    assert_equal(result, ground_truth)
开发者ID:pelegm,项目名称:networkx,代码行数:21,代码来源:test_asyn_lpa.py

示例12: build_cluster_graph

# 需要导入模块: from networkx import Graph [as 别名]
# 或者: from networkx.Graph import add_edges_from [as 别名]
def build_cluster_graph(sequences, threshold):
    '''
    sequence should be a tupple (id, array)
    threshold should exist in [0,1]
    '''
    #list to hold tuple associations
    tups_list = []
    #for each sequence in sequences
    for sequence in sequences:
        #find the corrcoef in relation to all other sequences
        for sec in [o_sec for o_sec in sequences if o_sec != sequence]:
            #if correlated within threshold bounds, ensure not already in list
            cor = corrcoef(sequence[1], sec[1])[0,1]
            if cor >= threshold and ([tup for tup in tups_list if sequence[0] and sec[0] in tup] == []):
                #if not already in list, append (_id1, _id2, corrcoef) tuple
                tups_list.append((sequence[0], sec[0], {'weight':cor}))
    #build graph from association list
    graph = Graph()
    graph.add_edges_from(tups_list)
    #return graph
    return graph
开发者ID:laegrim,项目名称:pycef,代码行数:23,代码来源:graph.py

示例13: merge_slices_to_events

# 需要导入模块: from networkx import Graph [as 别名]
# 或者: from networkx.Graph import add_edges_from [as 别名]
	def merge_slices_to_events(self, current_slices):
		"""
		Method merges DBSCAN-generated event slices with previously found events. 
		Bimodal network is used to find connections between events and slices,
		then slices are being merged with events, or transformed to new ones.
		Merged events are being deleted.

		Args:
			current_slices (Dict(List[Dict])): output of self.current_datapoints_dbscan method. Every item of dict is a slice cluster: list with dicts of messages from that cluster.
		"""
		slices_ids = set(current_slices.keys())
		events_ids = set(self.events.keys())
		edges = []
		for slice_id, event_slice in current_slices.items():
			slice_ids = {x['id'] for x in event_slice}
			for event in self.events.values():
				if event.is_successor(slice_ids):
					edges.append((slice_id, event.id))
		G = Graph()
		G.add_nodes_from(slices_ids.union(events_ids))
		G.add_edges_from(edges)
		events_to_delete = []
		for cluster in [x for x in connected_components(G) if x.intersection(slices_ids)]:
			unify_slices = cluster.intersection(slices_ids)
			unify_events = list(cluster.intersection(events_ids))
			meta_slice = [msg for i in unify_slices for msg in current_slices[i]]
			if not unify_events:
				new_event = Event(self.mysql, self.redis, self.tokenizer, self.morph, self.classifier, meta_slice)
				self.events[new_event.id] = new_event
			elif len(unify_events) == 1 and len(unify_slices) == 1 and set(self.events[unify_events[0]].messages.keys()) == {x['id'] for x in meta_slice}:
				continue
			else:
				if len(unify_events) > 1:
					for ancestor in unify_events[1:]:
						self.events[unify_events[0]].merge(self.events[ancestor])
						events_to_delete.append(ancestor)
				self.events[unify_events[0]].add_slice(meta_slice)
		for event in events_to_delete:
			del self.events[event]
			self.redis.delete("event:{}".format(event))
开发者ID:city-pulse,项目名称:mskpulse.backend,代码行数:42,代码来源:detector.py

示例14: solve_gfl

# 需要导入模块: from networkx import Graph [as 别名]
# 或者: from networkx.Graph import add_edges_from [as 别名]
def solve_gfl(data, edges, weights=None,
              minlam=0.2, maxlam=1000.0, numlam=30,
              alpha=0.2, inflate=2., converge=1e-6,
              maxsteps=1000000, lam=None, verbose=0):
    '''A very easy-to-use version of GFL solver that just requires the data and
    the edges.'''
    if verbose:
        print 'Decomposing graph into trails'

    ########### Setup the graph
    g = Graph()
    g.add_edges_from(edges)
    chains = decompose_graph(g, heuristic='greedy')
    ntrails, trails, breakpoints, edges = chains_to_trails(chains)

    if verbose:
        print 'Setting up trail solver'

    ########### Setup the solver
    solver = TrailSolver(alpha, inflate, maxsteps, converge)

    # Set the data and pre-cache any necessary structures
    solver.set_data(data, edges, ntrails, trails, breakpoints, weights=weights)

    if verbose:
        print 'Solving'

    ########### Run the solver
    if lam:
        # Fixed lambda
        beta = solver.solve(lam)
    else:
        # Grid search to find the best lambda
        beta = solver.solution_path(minlam, maxlam, numlam, verbose=max(0, verbose-1))['best']
    
    return beta
开发者ID:tansey,项目名称:gfl,代码行数:38,代码来源:easy.py

示例15: open

# 需要导入模块: from networkx import Graph [as 别名]
# 或者: from networkx.Graph import add_edges_from [as 别名]
    ips = {}
    # filter all relays in this consensus to those that
    # have a descriptor, are running, and are fast
    for relay in consensus.relays:
        if (relay in descriptors):
            sd = descriptors[relay] # server descriptor
            rse = consensus.relays[relay] # router status entry
            if "Running" in rse.flags and "Fast" in rse.flags:
                if relay not in ips: ips[relay] = []
                ips[relay].append(sd.address)
    # build edges between every relay that could have been
    # selected in a path together
    for r1 in ips:
        for r2 in ips:
            if r1 is r2: continue
            g.add_edges_from(product(ips[r1], ips[r2]))                    
    nsf_i += 1
    # check if we should do a checkpoint and save our progress
    if nsf_i == nsf_len or "01-00-00-00" in fname:
        chkpntstart = fname[0:10]
        with open("relaypairs.{0}--{1}.json".format(chkpntstart, chkpntend), 'wb') as f: json.dump(g.edges(), f)

print ""
print('Num addresses: {0}'.format(g.number_of_nodes()))
print('Num unique pairs: {0}'.format(g.number_of_edges()))

# write final graph to disk
with open(out_file, 'wb') as f: json.dump(g.edges(), f)
##########

开发者ID:00h-i-r-a00,项目名称:torps,代码行数:31,代码来源:aggregate_relays.py


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