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


Python networkx.cycle_basis函数代码示例

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


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

示例1: remove

 def remove(G, loops=None):
   if loops is None:
     loops = nx.cycle_basis(G)
   for l in loops:
     s1, s2 = l[0], l[1]
     if (s1, s2) in G.edges():
       G.remove_edge(s1, s2)
     elif (s2, s1) in G.edges():
       G.remove_edge(s2, s1)
   loops2 = nx.cycle_basis(G)
   print('New graph has %i loops' %len(loops2))
   return G
开发者ID:CosmoJG,项目名称:quantifying-morphology,代码行数:12,代码来源:pyramidal_nxRemoveLoops.py

示例2: correctLoops

def correctLoops(code, loops_graph, charge_type):
    while nx.cycle_basis(loops_graph) != []:
        cycle = nx.cycle_basis(loops_graph)[0]
        loop = path.Path(cycle)
        for data in code.Primal.nodes():
            if loop.contains_points([data]) == [True]:
                charge = code.Primal.node[data]['charge'][charge_type]
                code.Primal.node[data]['charge'][charge_type] = (charge + 1)%2

        l = len(cycle)
        for i in range(l):
            n1, n2 = cycle[i], cycle[(i+1)%l]
            loops_graph.remove_edge(*(n1,n2))

    return code, loops_graph
开发者ID:jacobmarks,项目名称:QTop,代码行数:15,代码来源:dsp.py

示例3: cycle_space

def cycle_space (T,C):
  """Return a list of cycle graphs representing the fundamental cycles of the
     spanning tree T extended by the chords edges of the graph C

  Parameters
  ----------
  T: a tree graph
     A NetworkX graph.
  C: graph representing chords for the tree T.
    A NetworkX (multidi)graph.

  Returns
  -------
  Z : a list of cycles

  """
  Z     = list ();
  edges = C.edges_iter ();

  for idx,e in enumerate (edges):
    if T.has_edge(*e) or T.has_edge(*e[::-1]):
      Z.append (list (e))
    else:
      T.add_edge (*e)
      Z.append (nx.cycle_basis (nx.Graph(T))[0])
      T.remove_edge (*e)

  return Z
开发者ID:kakila,项目名称:cycle_space,代码行数:28,代码来源:cycle_space.py

示例4: main

def main(prog, argv):
	parser = argparse.ArgumentParser(prog=prog)
	parser.add_argument('rows', metavar='LENGTH', type=int)
	parser.add_argument('cols', metavar='WIDTH', type=int)
	parser.add_argument('--verbose', '-v', action='store_true')
	parser.add_argument('--output-cb', '-C', metavar='PATH', type=str, help='generate .cyclebasis file')
	parser.add_argument('--output', '-o', type=str, required=True, help='.gpickle output file')

	args = parser.parse_args(argv)

	cellrows, cellcols = args.rows, args.cols

	if args.verbose:
		print('Generating graph and attributes')
	g = make_circuit(cellrows, cellcols)
	xys = full_xy_dict(cellrows, cellcols)
	measured_edge = battery_vertices()

	if args.verbose:
		print('Saving circuit')
	save_output(args.output, g, xys, measured_edge)

	if args.output_cb is not None:
		if args.verbose:
			print('Collecting desirable cycles')
		good = collect_good_cycles(g, cellrows, cellcols)

		assert validate_paths(g, good)

		if args.verbose:
			print('Generating fallback cycles')
		fallback = nx.cycle_basis(g)

		cyclebasis = build_cyclebasis_terminal(good, fallback, thorough=False, verbose=args.verbose)
		fileio.cycles.write_cycles(cyclebasis, args.output_cb)
开发者ID:ExpHP,项目名称:defect,代码行数:35,代码来源:mos2.py

示例5: order_tables

def order_tables(dbdir_str):
    """
    Sorts tables in constraint order, primary tables first

    Constructs a constraint graph for the tables in the supplied directory,
    sorts it in topological order, and returns the table names in that
    order in a list.
    """

    graph = nx.DiGraph()

    for file_str in os.listdir(dbdir_str):
        if file_str.endswith(".table"):
            add_table_to_graph(dbdir_str, file_str, graph)

    ordered_tables = None
    try:
        ordered_tables = nx.topological_sort(graph)
    except nx.NetworkXUnfeasible:
        print >> sys.stderr, "Tables and their constraints do not form a DAG"
        # The NetworkX package does not include a function that finds cycles
        # in a directed graph.  Lacking that, report the undirected cycles.
        # Since our tables currently contain no cycles other than self-loops,
        # no need to implement a directed cycle finder.
        cycles = nx.cycle_basis(nx.Graph(graph))
        print >> sys.stderr, "Found possible cycles:"
        print >> sys.stderr, cycles
        sys.exit(1)

    return ordered_tables
开发者ID:Ankuratgithub,项目名称:eden,代码行数:30,代码来源:topo.py

示例6: find_sidechains

def find_sidechains(molecule_graph):
    # Identify chiral atoms
    atoms = molecule_graph.atoms
    chiral_centres = chir.get_chiral_sets(atoms)
    # Identify sidechains (Ca-Cb-X), apart from proline and glycine.
    sidechains = {}
    # Detection of sidechains requires the multiple bonds be present in the atom graph.
    chir.multi_bonds(atoms)
    for k, v in chiral_centres.items():
        carbons = [atom for atom in v if atom.element == "C"]
        amides = [
            carbon
            for carbon in carbons
            if any([type(nb) == chir.GhostAtom and nb.element == "O" for nb in nx.neighbors(atoms, carbon)])
            and any([nb.element == "N" or nb.element == "O" for nb in nx.neighbors(atoms, carbon)])
        ]
        nbs_n = [nb for nb in v if nb.element == "N"]
        if amides and nbs_n:
            amide_bond = (k, amides[0])
            n_bond = (k, nbs_n[0])
            h_bond = (k, [h for h in nx.neighbors(atoms, k) if h.element == "H"][0])
            # Now find sidechains by cutting the Ca-C, Ca-N and Ca-H bonds
            atoms.remove_edges_from([amide_bond, n_bond, h_bond])
            sidechain_atoms = [
                atom
                for atom in [comp for comp in nx.connected_components(atoms) if k in comp][0]
                if type(atom) != chir.GhostAtom
            ]
            atoms.add_edges_from([amide_bond, n_bond, h_bond])
            if not any([k in cycle for cycle in nx.cycle_basis(atoms.subgraph(sidechain_atoms))]):
                sidechains[k] = atoms.subgraph(sidechain_atoms)
    chir.remove_ghost_atoms(atoms)
    return sidechains
开发者ID:khs26,项目名称:rotamer_library,代码行数:33,代码来源:identify_residue.py

示例7: hardy_cross

def hardy_cross(G, n, init_guess=None):
    cycles = nx.cycle_basis(G)
    cycles = np.array([[tuple([cycles[j][i], cycles[j][i+1]]) if (i < len(cycles[j])-1) else tuple([cycles[j][i], cycles[j][0]]) for i in range(len(cycles[j]))] for j in range(len(cycles))])

    L = [G.node[i]['demand'] for i in G.node.keys()]
    edges = np.array(G.edges())
    edge_idx = np.full((len(G), len(G)), 9999, dtype=int)
    edge_idx[edges[:,0], edges[:,1]] = np.arange(len(G.edges()))
    edge_idx[edges[:,1], edges[:,0]] = np.arange(len(G.edges()))
    
    edge_dir = np.zeros((len(G), len(G)), dtype=int)
    edge_dir[edges[:,0], edges[:,1]] = 1
    edge_dir[edges[:,1], edges[:,0]] = -1

    if init_guess == None:
        init_guess = np.linalg.lstsq(nx.incidence_matrix(G, oriented=True).toarray(), L)[0]
    A = init_guess.copy().astype(float)
    for i in range(n):
        for u in cycles:
            R = np.array([G[j[0]][j[1]]['weight'] for j in u])
            D = np.array(edge_dir[u[:,0], u[:,1]])
            C = np.array(A[edge_idx[u[:,0], u[:,1]]])
            C = C*D
            dV = (R*C).sum()
            di = dV/R.sum()
	    C = (C - di)*D
	    A[edge_idx[u[:,0], u[:,1]]] = C
    return A
开发者ID:btgorman,项目名称:RIPS,代码行数:28,代码来源:hardy_cross.py

示例8: main

def main():

    g = nx.Graph()

    g.add_cycle(range(5))
    g.add_cycle(range(5, 10))
    g.add_node(20)

    # 循環しているノードのリストを返す
    print(nx.cycle_basis(g)) #=> [[1, 2, 3, 4, 0], [9, 8, 7, 6, 5]]

    # もう一つ循環を作ってみる
    g.add_edges_from([(0, 5), (3, 8)])

    # 循環しているノードが一つ増えている
    print(nx.cycle_basis(g)) #=> [[9, 8, 7, 6, 5],
开发者ID:Machi427,项目名称:python,代码行数:16,代码来源:nx5.py

示例9: prune_graph

def prune_graph(G):
    """
        Return a graph describing the loopy part of G, which is
        implicitly described by the list of cycles.
        The loopy part does not contain any

        (a) tree subgraphs of G
        (b) bridges of G

        Thus pruning may disconnect the graph into several 
        connected components.
    """
    cycles = nx.cycle_basis(G)
    pruned = G.copy()
    cycle_nodes = set(chain.from_iterable(cycles))
    cycle_edges = []

    for c in cycles:
        cycle = c + [c[0]]
        a, b = tee(cycle)
        next(b, None)
        edges = izip(a, b)

        cycle_edges.append(edges)
    
    all_cycle_edges = set(tuple(sorted(e)) \
            for e in chain.from_iterable(cycle_edges))
    # remove treelike components and bridges by removing all
    # edges not belonging to loops and then all nodes not
    # belonging to loops.
    pruned.remove_edges_from(e for e in G.edges_iter() \
            if (not tuple(sorted(e)) in all_cycle_edges))
    pruned.remove_nodes_from(n for n in G if not n in cycle_nodes)

    return pruned
开发者ID:hronellenfitsch,项目名称:nesting,代码行数:35,代码来源:decomposer.py

示例10: is_tree

def is_tree(graph):
	"""
	Checks whether graph is a tree.

	A graph is a tree if it is 
		(i) undirected - always, in our setting 
		(ii) connected, and 
		(iii) contains no cycles.

	Args:
		graph: networkx.Graph instance

	Return a boolean that indicates whether this graph is a tree.
	"""

	if len(graph.nodes()) == 0:
		return True

	if not nx.is_connected(graph):
		return False

	if len(nx.cycle_basis(graph)) > 0:
		return False

	return True
开发者ID:mmathioudakis,项目名称:bump_hunting,代码行数:25,代码来源:graph_utils.py

示例11: order_tables

    def order_tables(self):
        """ Sorts tables in constraint order, least constrained tables first

        Constructs a constraint graph for the tables in the supplied database
        or databases directory, sorts it in topological order with the least
        constained tables first, and returns the table names in that order in
        a list.
        """

        self.add_all_tables_to_graph()

        # With NetworkX v1.3, topological_sort raises NetworkXUnfeasible if
        # the graph is not acyclic.  With v1.2, it returns None.
        ordered_tables = None
        try:
            ordered_tables = nx.topological_sort(self.graph)
        except:
            ordered_tables = None
        if not ordered_tables:
            # Fails only if the graph has cycles.
            # The NetworkX package does not include a function that finds
            # cycles in a directed graph.  Lacking that, report the undirected
            # cycles.  Since our tables currently contain no cycles other than
            # self-loops, no need to implement a directed cycle finder.
            # @ToDo: Add a warning to the wiki about not putting cycles in
            # table relationships.  It's never necessary -- show a proper
            # relationship hierarchy.
            cycles = nx.cycle_basis(nx.Graph(self.graph))
            errmsg = "Tables and their constraints do not form a DAG.\n" + \
                     "Found possible cycles:\n" + str(cycles)
            raise ValueError, errmsg

        return ordered_tables
开发者ID:Akanksha18,项目名称:eden,代码行数:33,代码来源:topo.py

示例12: __init__

    def __init__(self, graph):

        edges = {}
        vertices = {}
        faces = {}
        half_edges = {}

        cycles = nx.cycle_basis(graph)
        fi = 0
        for cycle in cycles:
            n = len(cycle)
            for i in range(n-1):
                e = (cycle[i], cycle[i+1])
                if e not in edges:
                    edges[e] = fi
                    twin_a = e[0], e[1]
                    twin_b = e[1], e[0]
                    if twin_a not in half_edges:
                        half_edges[twin_a] = fi
                    if twin_b not in half_edges:
                        half_edges[twin_b] = None
            e = cycle[n-1], cycle[0]
            if e not in edges:
                edges[e] = fi
            faces[fi] = e


            fi += 1

        self.edges = edges
        self.faces = faces
        self.half_edges = half_edges
开发者ID:PepSalehi,项目名称:pysal,代码行数:32,代码来源:dcel.py

示例13: VizualizeGraph

def VizualizeGraph(G, param):
    import os

    try:
        import matplotlib

        matplotlib.use("Agg")

        try:
            os.mkdir(param.output_directory + "/graph_regions" + str(int(param.mean_ins_size)))
        except OSError:
            # directory is already created
            pass
        # CB = nx.connected_component_subgraphs(G)
        CB = nx.cycle_basis(G)
        print "NR of SubG: ", len(CB)
        counter = 1
        for cycle in CB:
            if len(cycle) >= 6:  # at leats 6 nodes if proper cycle (haplotypic region)
                subgraph = nx.Graph()
                subgraph.add_cycle(cycle)
                nx.draw(subgraph)
                matplotlib.pyplot.savefig(
                    param.output_directory
                    + "graph_regions"
                    + str(int(param.mean_ins_size))
                    + "/"
                    + str(counter)
                    + ".png"
                )
                matplotlib.pyplot.clf()
                counter += 1
    except ImportError:
        pass
    return ()
开发者ID:ksahlin,项目名称:BESST_RNA,代码行数:35,代码来源:MakeScaffolds.py

示例14: _get_foot_graph

 def _get_foot_graph(self):
     radius = self.distance/2.
     G = nx.Graph()
     query = ("""
         WITH origin AS
             (SELECT point
                 FROM rnodes_intersections
                 WHERE id = '%d')
         SELECT end1, end2, distance, run_score
             FROM routing_edges_latlon, origin
             WHERE
                 ST_Dwithin(origin.point::geography, point1::geography, %f) OR
                 ST_Dwithin(origin.point::geography, point2::geography, %f);"""
              % (self.start_node, radius, radius))
     self._cur.execute(query)
     G.add_edges_from([[int(node[0]), int(node[1]),
                        {'dist': node[2], 'run_score': node[3]}]
                       for node in self._cur.fetchall()])
     G_cycles = nx.Graph()
     for cycle in nx.cycle_basis(G):
         G_cycles.add_cycle(cycle)
     for edge in G.edges():
         if not G_cycles.has_edge(*edge):
             G.remove_edge(*edge)
     return G
开发者ID:cequencer,项目名称:runsmartr,代码行数:25,代码来源:runrouter_data.py

示例15: findPath

def findPath(schema_graph):
	'''Determines if the schema contains a closed curve.'''
	cycles = nx.cycle_basis(schema_graph)
	if len(cycles) > 0:
		return cycles
	else:
		raise nx.exception.NetworkXNoCycle('No closed cycle found.')
开发者ID:BBischof,项目名称:quoting2DGeometries,代码行数:7,代码来源:geomCalc.py


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