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


Python networkx.simple_cycles函数代码示例

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


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

示例1: _check_graph

    def _check_graph(self, ebunch=None, delete_graph=False):
        """
        Checks for self loops and cycles in the graph.
        If finds any, reverts the graph to previous state or
        in case when called from __init__ deletes the graph.
        """
        if delete_graph:
            if ebunch is not None:
                for edge in ebunch:
                    if edge[0] == edge[1]:
                        del self
                        raise ValueError("Self Loops are not allowed",
                                         edge)

            simple_cycles = [loop for loop in nx.simple_cycles(self)]
            if simple_cycles:
                del self
                raise ValueError("Cycles are not allowed",
                                 simple_cycles)
            return True
        else:
            for edge in ebunch:
                if edge[0] == edge[1]:
                    raise ValueError("Self loops are not allowed", edge)

            import copy
            test_G = copy.deepcopy(self)
            nx.DiGraph.add_edges_from(test_G, ebunch)
            simple_cycles = [loop for loop in nx.simple_cycles(test_G)]
            if simple_cycles:
                del test_G
                raise ValueError("Cycles are not allowed", simple_cycles)
            return True
开发者ID:infoburp,项目名称:pgmpy,代码行数:33,代码来源:BayesianModel.py

示例2: undo_cycles

    def undo_cycles(self):
        vertices = self.states_df.columns
        nx_graph = self.new_filled_nx_graph()
        dir_edge_to_freq = {}

        bad_dir_edges = []
        cycles = list(nx.simple_cycles(nx_graph))
        num_cyc = len(cycles)
        while num_cyc > 0:
            for cyc in cycles:
                for dir_edge in cyc:
                    if dir_edge not in dir_edge_to_freq.keys:
                        dir_edge_to_freq[dir_edge] = 1
                    else:
                        dir_edge_to_freq[dir_edge] += 1
            max_freq_edge = max(dir_edge_to_freq,
                                key=dir_edge_to_freq.get)
            bad_dir_edges.append(max_freq_edge)
            beg_vtx, end_vtx = max_freq_edge
            self.vtx_to_parents[end_vtx].remove(beg_vtx)
            nx_graph.remove_edge(beg_vtx, end_vtx)
            cycles = list(nx.simple_cycles(nx_graph))
            num_cyc = len(cycles)
        for (beg_vtx, end_vtx) in reversed(bad_dir_edges):
            self.vtx_to_parents[beg_vtx].append(end_vtx)
开发者ID:artiste-qb-net,项目名称:bob-sandbox,代码行数:25,代码来源:MB_BasedLner.py

示例3: test_simple_cycles_small

 def test_simple_cycles_small(self):
     G = nx.DiGraph()
     G.add_path([1, 2, 3, 1])
     c = sorted(nx.simple_cycles(G))
     assert_equal(c, [[1, 2, 3, 1]])
     G.add_path([10, 20, 30, 10])
     c = sorted(nx.simple_cycles(G))
     assert_equal(c, [[1, 2, 3, 1], [10, 20, 30, 10]])
开发者ID:rainest,项目名称:dance-partner-matching,代码行数:8,代码来源:test_cycles.py

示例4: follow_path

    def follow_path(self, node):
        """Given a head node, follow_path will parse through all connecting nodes and translate the path into the
           execution portion of the script. """
        #declare variables
        temp_script3 = ""    
        var = 1
        original_node = node
        cycle_element_used = set()

        while var == 1:
            #check for edges that have been traversed and ignore them
            original_walked = [self.graph.edge[j][k]['walked'] for j,k in self.graph.out_edges(original_node)]
            edges = self.graph.out_edges(node)
            for j,k in edges:
                if self.graph.edge[j][k]['walked'] == True:
                    edges.remove((j,k))
                #if a loop is detected, parse through and translate everything into a for loop for the script
                if len(nx.simple_cycles(self.graph)) > 0:
                    cycles_list = nx.simple_cycles(self.graph)[0]
                    if j in cycles_list and not cycle_element_used:
                        temp_script3 = temp_script3 + "for n in range(10):\n"
                        
                        #cycles_list.pop(), this was commented out due to the fact that the order of the cycle was incorrect
                        cycles_list.remove(cycles_list[0])
                        for i in range(len(cycles_list)):
                            temp_script3 = temp_script3 + "    " + cycles_list[i].add_calc(cycles_list[i-1].var, self.graph.edge[cycles_list[i-1]][cycles_list[i]]['msname']) + '\n'                             
                        cycle_element_used.add(j)
                        cycle_element_used.add(k)
  
            #move to the next node and add any lines of code that have not already been included in the script
            walk_list = {self.graph.edge[j][k]['walk_value']:(j,k) for j,k in edges}
            if len(walk_list) > 0:
                x,y =  walk_list[min(walk_list)]
                self.graph.edge[x][y]['walked'] = True
                if y.add_calc(x.var, self.graph.edge[x][y]['msname']) not in temp_script3:
                    temp_script3 = temp_script3 + y.add_calc(x.var, self.graph.edge[x][y]['msname']) + '\n'

                #if there are more than one edges branching off of a node, take the one with the lowest walk_value
                #else:simply take the edge and follow it to the next node
                if len(self.graph.successors(node)) > 1:
                    node = y
                else:
                    node = self.graph.successors(node)[0]
            
            #if all edges down one path has been traveres, check the head node for any other paths and follow the one
            #with the next least walk_value
            else:
                node = original_node
        
            #if everything has been traversed, reset all walked values to False to ensure that the next runthrough 
            #succeeds
            if False not in original_walked:
                for j,k in self.graph.out_edges():
                    self.graph.edge[j][k]['walked'] = False
                break

        #apply changes to the execution portion of the script
        self.script_execution = temp_script3
开发者ID:bartonfriedland,项目名称:bright,代码行数:58,代码来源:fuel_cycle_model.py

示例5: test_simple_cycles_small

 def test_simple_cycles_small(self):
     G = nx.DiGraph()
     G.add_path([1,2,3,1])
     c=sorted(nx.simple_cycles(G))
     assert_equal(c,[[1,2,3,1]])
     G.add_path([10,20,30,10])
     c=sorted(nx.simple_cycles(G))
     ca=[[1,2,3,1],[10,20,30,10]]
     for (a,b) in zip(c,ca):
         assert_true(self.is_cyclic_permuatation(a[:-1],b[:-1]))
开发者ID:Bludge0n,项目名称:AREsoft,代码行数:10,代码来源:test_cycles.py

示例6: test_simple_cycles_small

 def test_simple_cycles_small(self):
     G = nx.DiGraph()
     G.add_cycle([1,2,3])
     c=sorted(nx.simple_cycles(G))
     assert_equal(len(c),1)
     assert_true(self.is_cyclic_permutation(c[0],[1,2,3]))
     G.add_cycle([10,20,30])
     cc=sorted(nx.simple_cycles(G))
     ca=[[1,2,3],[10,20,30]]
     for c in cc:
         assert_true(any(self.is_cyclic_permutation(c,rc) for rc in ca))
开发者ID:AlistairNWard,项目名称:configurationClass,代码行数:11,代码来源:test_cycles.py

示例7: _validate

def _validate(G):
    '''
    Validates dependency graph to ensure it has no missing or cyclic dependencies
    '''
    for name in G.nodes():
        if 'value' not in G.node[name] and 'template' not in G.node[name]:
            msg = 'Dependency unsatisfied in variable "%s"' % name
            raise ParamException(msg)

    if not nx.is_directed_acyclic_graph(G):
        graph_cycles = nx.simple_cycles(G)

        variable_names = []
        for cycle in graph_cycles:
            try:
                variable_name = cycle[0]
            except IndexError:
                continue

            variable_names.append(variable_name)

        variable_names = ', '.join(sorted(variable_names))
        msg = ('Cyclic dependency found in the following variables: %s. Likely the variable is '
               'referencing itself' % (variable_names))
        raise ParamException(msg)
开发者ID:StackStorm,项目名称:st2,代码行数:25,代码来源:param.py

示例8: find_most_repeated_cycles

def find_most_repeated_cycles(di_graph):
    """
    Returns a list filled with this format for each element: [edge : amount_of_appearances].

    Args:
        di_graph : nx.DiGraph()
            A networkx DiGraph class for representing DAG

    Returns:
        MATRIX[[TUPLE, INT], [TUPLE, INT], [TUPLE, INT], ...]
            If we have at least one edge with one appearance
        MATRIX[]
            If we don't have edges
    """
    list_all_cycles = []
    cycles = list(nx.simple_cycles(di_graph))
    for i in range(0, len(cycles)):
        list_all_cycles.append(find_cycle_edges(cycles[i], di_graph.edges(cycles[i])))
    flatted_edges = sum(list_all_cycles, [])  # This flattens the nested list of edges

    # This list contains a list of edges and their appearances on the list, but only appearances bigger than 0
    checked_edges = []
    while len(flatted_edges) > 0:
        cont = flatted_edges.count(flatted_edges[0])
        if cont > 0:  # Amount of appearances bigger than 1
            checked_edges.append([flatted_edges[0], cont])
        # This remove a value from a list
        flatted_edges[:] = (value for value in flatted_edges if value != flatted_edges[0])
    return checked_edges
开发者ID:keme040994,项目名称:CGA_Project,代码行数:29,代码来源:repair_functions.py

示例9: analyse_cycles

def analyse_cycles(sdfg):
    vectors = core.check_consistency( sdfg )
    s = vectors['s']
    q = vectors['q']
    print("HSDF graph size: {}".format( sum(q.values()) ))
    par = {}
    for cycle in nx.simple_cycles( sdfg ):
        edges = [ (cycle[i - 1], cycle[i]) for i in range(len(cycle)) ]
        wtsum = 0
        multiple = 1
        z = {}
        for v, w in edges:
            data = sdfg.get_edge_data( v, w )
            tokens = data.get('tokens', 0)
            prates = data.get('production', core.cyclic(1))

            wtsum += s[ (v, w) ] * tokens
            z[v] = prates.sum() * s[ (v, w) ]
            multiple = core.lcm( multiple, z[v] )

        if wtsum % multiple == 0:
            for v in cycle:
                parv = wtsum // z[ v ]
                par[v] = parv if v not in par else min(par[v], parv)

        print("Cycle {}: tokens = {:.3f}, integral: {}".format( cycle, wtsum / multiple, wtsum % multiple == 0 ))

    for v in par:
        if q[v] % par[v] == 0:
            q[v] = q[v] // par[v]
        elif par[v] % q[v] == 0:
            q[v] = 1
    
    print("New HSDF graph size: {}".format( sum(q.values()) ))
开发者ID:polca-project,项目名称:polca-toolbox,代码行数:34,代码来源:parallelism.py

示例10: get_all_substance_combinations_with_cycles

def get_all_substance_combinations_with_cycles(alpha, beta):
    try:
        import numpy
        alpha = numpy.array(alpha)
        beta = numpy.array(beta)
    except ImportError:
        print('This method requires that alpha and beta are NumPy arrays.'
              'NumPy does not appear to be installed. Please install NumPy.')
        raise

    # alpha, beta are stoichiometry matrices as used throughout code

    # number of reactions = number of columns of alpha
    no_rxn = alpha.shape[1]
    # number of substance = number of rows of alpha
    no_sub = alpha.shape[0]

    # check
    if no_rxn != beta.shape[1] or no_sub != beta.shape[0]:
        raise

    # get substance adjacency matrix
    subs_adj = get_substance_adjacency(alpha, beta)

    # get directed substance graph
    subs_G = nx.from_numpy_matrix(subs_adj, create_using=nx.DiGraph())

    # get cycles in substance graph
    subs_cycles  = nx.simple_cycles(subs_G)
    # remove substance index repetitions
    for c_i in range(len(subs_cycles)):
        subs_cycles[c_i] = list(set(subs_cycles[c_i]))
开发者ID:gratelpy,项目名称:gratelpy,代码行数:32,代码来源:fragments.py

示例11: dependency_list

    def dependency_list(self):
        r'''
        Returns a list of dependencies in the order with which they should be
        called to ensure data is calculated by one model before it's asked for
        by another.

        Notes
        -----
        This raises an exception if the graph has cycles which means the
        dependencies are unresolvable (i.e. there is no order which the
        models can be called that will work).  In this case it is possible
        to visually inspect the graph using ``dependency_graph``.

        See Also
        --------
        dependency_graph
        dependency_map

        '''
        dtree = self.dependency_graph()
        cycles = list(nx.simple_cycles(dtree))
        if cycles:
            raise Exception('Cyclic dependency found: ' + ' -> '.join(
                            cycles[0] + [cycles[0][0]]))
        d = nx.algorithms.dag.lexicographical_topological_sort(dtree, sorted)
        return list(d)
开发者ID:PMEAL,项目名称:OpenPNM,代码行数:26,代码来源:ModelsMixin.py

示例12: comb_fas

def comb_fas( graph):
    '''@param: graph, a nx.DiGraph obj
    '''
    assert isinstance( graph, nx.DiGraph)
    origin_weight = nx.get_edge_attributes( graph, 'weight')
    weight = origin_weight.copy()

    assert len(weight) == graph.number_of_edges(), "Some edge doesnot has a weight attr."
    fas = []
    while( not nx.is_directed_acyclic_graph(graph) ):
        c = list( nx.simple_cycles(graph) )[0]
        mini_weight = min( [ weight[edge] for edge in get_edges(c)] )

        cycle_edges_weight = {edge:weight[edge] for edge in get_edges(c) }
        for eachEdge in cycle_edges_weight.keys():
            cycle_edges_weight[eachEdge] -= mini_weight
            weight[eachEdge ] -= mini_weight
            if cycle_edges_weight[eachEdge] == 0:
                fas.append( eachEdge )
                graph.remove_edge( eachEdge[0], eachEdge[1] )

    for eachEdge in copy.copy(fas):
        graph.add_edge( eachEdge[0], eachEdge[1], {'weight' : origin_weight[eachEdge]} )
        if nx.is_directed_acyclic_graph( graph):
            fas.remove(eachEdge)
            continue
        else:
            graph.remove_edge( eachEdge[0], eachEdge[1] )

    return fas
开发者ID:litaotju,项目名称:netlistx,代码行数:30,代码来源:fas.py

示例13: cycles

def cycles(request, graph):
    offset, limit = _getPaging(request)

    icycles = nx.simple_cycles(graph)
    icycles = islice(icycles, offset, offset + limit)

    request.respondJson({'cycles': tuple(icycles)})
开发者ID:petrushev,项目名称:graphx,代码行数:7,代码来源:paths.py

示例14: _solve_bff

    def _solve_bff(self, bff_str):
        # Construct the directed graph
        bffs = [int(e.strip()) for e in bff_str.split(' ')]
        nodes = [i+1 for i in xrange(len(bffs))]
        gr = nx.DiGraph()
        gr.add_nodes_from(nodes)
        gr.add_edges_from([e for e in zip(nodes, bffs)])

        max_length = 0
        tree = self._build_tree(bffs)
        paths = []
        # For each simple cycles in the graph
        for cycle in nx.simple_cycles(gr):
            if len(cycle) == 2:
                # If cycle length is two, we can add more nodes to form a path
                path_length = self._find_path_length(cycle, tree)
                # All the paths can be chained to form a circle
                paths.append(path_length)
            elif len(cycle) > max_length:
                # If cycle length is three, we cannot add more nodes
                max_length = len(cycle)

        total_path_length = sum(paths)
        if total_path_length > max_length:
            max_length = total_path_length

        return max_length
开发者ID:tdongsi,项目名称:python,代码行数:27,代码来源:codejam.py

示例15: check

    def check(self):
        if not self.graph.is_acyclic():
            err = "Graph cannot be processed because it contains cycles in it:"
            # FIXME(mattymo): GraphSolver cannot be used to call this method
            err += ', '.join(six.moves.map(str,
                                           nx.simple_cycles(
                                               nx.DiGraph(self.graph))))
            err += '\n'
            raise errors.InvalidData(err)

        non_existing_tasks = []
        invalid_tasks = []

        for node_key, node_value in six.iteritems(self.graph.node):
            if not node_value.get('id'):
                successors = self.graph.successors(node_key)
                predecessors = self.graph.predecessors(node_key)

                neighbors = successors + predecessors

                non_existing_tasks.append(node_key)
                invalid_tasks.extend(neighbors)

        if non_existing_tasks:
            raise errors.InvalidData(
                "Tasks '{non_existing_tasks}' can't be in requires"
                "|required_for|groups|tasks for [{invalid_tasks}]"
                " because they don't exist in the graph".format(
                    non_existing_tasks=', '.join(
                        str(x) for x in sorted(non_existing_tasks)),
                    invalid_tasks=', '.join(
                        str(x) for x in sorted(set(invalid_tasks)))))
开发者ID:jiaolongsun,项目名称:fuel-web,代码行数:32,代码来源:orchestrator_graph.py


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