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


Python digraph.DiGraph类代码示例

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


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

示例1: _congruence_graph

	def _congruence_graph(self):
		"""Form a graph whose vertex set is the QNF basis. The edges store the information which makes two vertices congruent."""
		from networkx.classes.digraph import DiGraph
		basis = self.quasinormal_basis
		min_exp = basis.minimal_expansion_for(self)
		terminal, initial = self.semi_infinite_end_points()
		endpts = sorted(terminal + initial)
		G = DiGraph()
		orbit_generators = set(min_exp)
		orbit_generators.update(endpts)
		
		#1. Add an edge for every direct congruence relationship.
		for gen in orbit_generators:
			type, images, _ = self.orbit_type(gen, basis)
			for power, img in images.items():
				images[power] = basis.test_above(img)
			
			congruent_pairs = permutations(images.items(), 2)
			for (pow1, (head1, tail1)), (pow2, (head2, tail2)) in congruent_pairs:
				if head1 == head2:
					continue
				data = dict(start_tail = tail1, power = pow2 - pow1, end_tail = tail2)
				G.add_edge(head1, head2, data)
				assert self.repeated_image(head1.extend(tail1), pow2 - pow1) == head2.extend(tail2)
		return G
开发者ID:DMRobertson,项目名称:thompsons_v,代码行数:25,代码来源:infinite.py

示例2: __init__

    def __init__(self, incoming_graph_data=None, **attr):
        """Initialize a graph with edges, name, or graph attributes.

        Parameters
        ----------
        incoming_graph_data : input graph
            Data to initialize graph.  If incoming_graph_data=None (default)
            an empty graph is created.  The data can be an edge list, or any
            NetworkX graph object.  If the corresponding optional Python
            packages are installed the data can also be a NumPy matrix
            or 2d ndarray, a SciPy sparse matrix, or a PyGraphviz graph.

        attr : keyword arguments, optional (default= no attributes)
            Attributes to add to graph as key=value pairs.

        See Also
        --------
        convert

        Examples
        --------
        >>> G = nx.Graph()   # or DiGraph, MultiGraph, MultiDiGraph, etc
        >>> G = nx.Graph(name='my graph')
        >>> e = [(1, 2), (2, 3), (3, 4)] # list of edges
        >>> G = nx.Graph(e)

        Arbitrary graph attribute pairs (key=value) may be assigned

        >>> G = nx.Graph(e, day="Friday")
        >>> G.graph
        {'day': 'Friday'}

        """
        self.edge_key_dict_factory = self.edge_key_dict_factory
        DiGraph.__init__(self, incoming_graph_data, **attr)
开发者ID:kalyi,项目名称:networkx,代码行数:35,代码来源:multidigraph.py

示例3: __init__

 def __init__(self, node_dict, edge_dict, U, initial_node, initial_label):
     DiGraph.__init__(self, name='motion_mdp', init_state=initial_node, init_label=initial_label)
     for (n, prob_label) in node_dict.iteritems():
         self.add_node(n, label = prob_label, act = set())
     print "-------Motion MDP Initialized-------"
     self.add_edges(edge_dict, U)
     print "%s states and %s edges" %(str(len(self.nodes())), str(len(self.edges())))
     self.unify_mdp()
开发者ID:MengGuo,项目名称:P_MDP_TG,代码行数:8,代码来源:mdp.py

示例4: __init__

 def __init__(self, algo_id, *args, **kwargs):
     DiGraph.__init__(self, args, kwargs)
     self.id = algo_id
     self.scan_count = 0
     self.input_data = []
     self.output_data =[]
     self.data_id_dict = {}  # internal dictionary for lookups of data nodes by id
     self.scan_rate = kwargs.pop('scan_rate')  # rate at which module should be scanned
开发者ID:pengtianyue,项目名称:Solvay_test,代码行数:8,代码来源:ScannedAlgo.py

示例5: load_graph

def load_graph(file_or_path:FileOrPath, ext:str=None) -> DiGraph:
  graph = DiGraph()
  for adj in load_jsonl(text_file_for(file_or_path)):
    src = adj[0]
    graph.add_node(src)
    for dst in adj[1:]:
      graph.add_edge(src, dst)
  return graph
开发者ID:gwk,项目名称:english-dictionary,代码行数:8,代码来源:graphs.py

示例6: delete_node

 def delete_node(self, n):
     try:
         if len(self.succ[n])+len(self.pred[n])==1: # allowed for leaf node
             DiGraph.delete_node(self,n) # deletes adjacent edge too
         else:
             raise NetworkXError( \
           "deleting interior node %s not allowed in tree"%(n))
     except KeyError: # NetworkXError if n not in self
         raise NetworkXError, "node %s not in graph"%n
开发者ID:conerade67,项目名称:biana,代码行数:9,代码来源:tree.py

示例7: buchi_from_ltl

def buchi_from_ltl(formula,Type):
    promela_string = run_ltl2ba(formula)
    symbols = find_symbols(formula)
    edges = parse_ltl(promela_string)
    (states, initials, accepts) = find_states(edges)
    buchi = DiGraph(type=Type, initial=initials, accept=accepts, symbols=symbols)
    for state in states:
        buchi.add_node(state)
    for (ef,et) in edges.keys():
        guard_formula = edges[(ef,et)]
        guard_expr = parse_guard(guard_formula)
        buchi.add_edge(ef, et, guard=guard_expr, guard_formula=guard_formula)
    return buchi
开发者ID:MengGuo,项目名称:P_MAS_TG,代码行数:13,代码来源:buchi.py

示例8: add_edge

 def add_edge(self, u, v=None):  
     if v is None: (u,v)=u  # no v given, assume u is an edge tuple
     if self.has_edge(u,v): return # no parallel edges
     elif u in self and v in self:
         raise NetworkXError, "adding edge %s-%s not allowed in tree"%(u,v)
     elif u in self or v in self:
         DiGraph.add_edge(self,u,v) # u->v
         return
     elif len(self.adj)==0: # first leaf
         DiGraph.add_edge(self,u,v) # u->v           
         return
     else:
         raise NetworkXError("adding edge %s-%s not allowed in tree"%(u,v))
开发者ID:conerade67,项目名称:biana,代码行数:13,代码来源:tree.py

示例9: load_from_graphml

    def load_from_graphml(path):
        """
        :type path: str
        :rtype: networkx.classes.graph.Graph
        """
        #: :type : networkx.classes.graph.Graph
        g1 = nx.read_graphml(path)
        #: :type graph: networkx.classes.digraph.DiGraph
        g2 = DiGraph()

        typetest = re.compile(r"([a-zA-z]+)(\d*)")

        max_qualifiers = dict(crossing=0, poi=0, plcs=0)
        node_mapping = dict()

        for node, data in g1.nodes_iter(data=True):

            m = typetest.match(data["label"])
            if m is None:
                raise(SALMAException("Wrong label format for node {}!".format(node)))

            loctype = m.group(1)
            if loctype in ["c"]:
                loctype = "crossing"
            elif loctype in ["p"]:
                loctype = "poi"
            elif loctype in ["pl"]:
                loctype = "plcs"
            if loctype not in ["poi", "plcs", "crossing"]:
                raise(SALMAException("Wrong loctype for node {}: {}".format(node, loctype)))
            qualifier = m.group(2)
            if len(qualifier) == 0:
                qualifier = max_qualifiers[loctype] + 1
                nid = data["label"] + str(qualifier)
            else:
                nid = data["label"]
            max_qualifiers[loctype] = max(max_qualifiers[loctype], qualifier)

            pos = (round(float(data["x"])), round(float(data["y"])))

            g2.add_node(nid, pos=pos, scaled_pos=pos, loctype=loctype)
            node_mapping[node] = nid

        for u, v in g1.edges_iter():
            n1 = node_mapping[u]
            n2 = node_mapping[v]
            g2.add_edge(n1, n2)
            g2.add_edge(n2, n1)

        MapGenerator.__add_roadlengths(g2)
        return g2
开发者ID:salmatoolkit,项目名称:salma,代码行数:51,代码来源:map_generator.py

示例10: create_fair_graph

	def create_fair_graph(self,system):
		G = DiGraph()
		G.add_edges_from(self.edges(data=True))
		controls = nx.get_edge_attributes(self,'control')
		unfair_cycles = []
		for cycle in nx.simple_cycles(G):
			edges = [(cycle[i],cycle[(i+1)%len(cycle)]) for i in range(len(cycle))]
			trace = [(c[0],controls[c].values()) for c in edges]
			nbre_controls = [range(len(t[1])) for t in trace]
			control_configuration = itertools.product(*nbre_controls)
			for conf in control_configuration:
				current_trace = [(t[0],t[1][conf[i]]) for i,t in enumerate(trace)]
				if not self.is_cycle_fair(system,current_trace):
					unfair_cycles.append(current_trace)
		print "Unfair cycles ",unfair_cycles
开发者ID:roussePaul,项目名称:pwa,代码行数:15,代码来源:automata.py

示例11: __init__

 def __init__(self, formula):
     #----call ltl2dra executable----
     ltl2dra_output = run_ltl2dra(formula)
     #----parse the output----
     statenum, init, edges, aps, acc = parse_dra(ltl2dra_output)
     #------
     DiGraph.__init__(self, type='DRA', initial=set([init,]), accept=acc, symbols=aps)
     print "-------DRA Initialized-------"
     for state in xrange(0,statenum):
         self.add_node(state)
     for (ef,et) in edges.keys():
         guard_string = edges[(ef,et)]
         self.add_edge(ef, et, guard_string=guard_string)
     print "-------DRA Constructed-------"
     print "%s states, %s edges and %s accepting pairs" %(str(len(self.nodes())), str(len(self.edges())), str(len(acc)))
开发者ID:MengGuo,项目名称:P_MDP_TG,代码行数:15,代码来源:dra.py

示例12: make_test_graph

def make_test_graph():
    '''     (4)  6
             ^   ^
             | X |
            (3)  5
             ^   ^
              \ /
              [2]
               ^
               |
              (1)
    '''
    web = DiGraph()
    web.add_edges_from([(1,2), (2,3), (3,4), (2,5), (3,6), (5,6), (5,4)])
    return web
开发者ID:gfon,项目名称:fuefit,代码行数:15,代码来源:Dependencies_plan_test.py

示例13: __init__

 def __init__(self):
     self.androGuardObjects = []
     
     self.nodes = {}
     self.nodes_id = {}
     self.entry_nodes = []
     self.G = DiGraph()
开发者ID:tempbottle,项目名称:StaDynA,代码行数:7,代码来源:method_call_graph.py

示例14: __init__

    def __init__(self, data=None, params=None, **attr):
        # self.reaction_graph.graph['node'] = {'fontname': 'Courier new'}
        # self.reaction_graph.graph['edge'] = {'fontname': 'Arial',
        #                                      'fontsize': 10.0, # labelfontsize
        #                                      'len': 4.0}
        DiGraph.__init__(self, data, **attr)
        if params is None:
            params = {}
        self.params = params  # or "config" ?
        if 'reaction_graph_default_attrs' in params:
            self.graph.update(params['reaction_graph_default_attrs'])

        # A reaction can have multiple end-state when a complex is being split up:
        # (edge_attrs should be the same for edges belonging to the same reaction for intracomplex reactions
        self.endstates_by_reaction = {}  # [startstate][(reaction_spec_pair, reaction_attr)] = [list of endstates]
        self.endstates_by_reaction[0] = defaultdict(list) # Also adding the "null" node
        self.reverse_reaction_key = {} # get reaction edge key for the opposite direction.
        self.tau_cum_max = 0
        # self.reverse_reaction[(rx_spec_pair, rx_attr)] = (rev_rx_spec_pair, rev_rx_attr)
        # used to be a dict {edge_key => target} but we can have multiple targets for a single reaction.
        self.reaction_graph_complexes_directory = params.get("reaction_graph_complexes_directory")
        if self.reaction_graph_complexes_directory is not None:
            if not os.path.exists(self.reaction_graph_complexes_directory):
                print("Creating directory for complex files:", self.reaction_graph_complexes_directory)
                os.makedirs(self.reaction_graph_complexes_directory)
            assert os.path.isdir(self.reaction_graph_complexes_directory)

        self.dispatchers = []
        # File with changes to the reaction graph, e.g. new nodes/edges and node/edge updates:
        self.reaction_graph_events_file = params.get('reaction_graph_events_file')
        if self.reaction_graph_events_file is None and self.reaction_graph_complexes_directory is not None:
            self.reaction_graph_events_file = os.path.join(self.reaction_graph_complexes_directory,
                                                           "reaction_graph_eventstream.json")

        if self.reaction_graph_events_file:
            #self.reaction_graph_delta_file = open(self.reaction_graph_delta_file, 'a')
            #self.open_files.append(self.reaction_graph_delta_file)
            gs_file_dispatcher = GraphStreamFileDispatcher(self.reaction_graph_events_file)
            gs_file_dispatcher.writer.write("# New reaction graph initialized at %s\n" % datetime.now())
            print("\n\nWriting reaction_graph event stream to file: %s\n" % self.reaction_graph_events_file)
            self.dispatchers.append(gs_file_dispatcher)
        else:
            # raise ValueError("self.reaction_graph_events_file not given: ", self.reaction_graph_events_file)
            print("self.reaction_graph_events_file (%s) not given: Graph events will not be available." %
                  self.reaction_graph_events_file)
开发者ID:scholer,项目名称:nascent,代码行数:45,代码来源:reaction_graph.py

示例15: get_example_1

def get_example_1():
    # input
    g = DiGraph()
    g.add_edges_from([[1, 2], [1, 3], [2, 4], [3, 4]])

    g.node[1]['r'] = 1
    g.node[2]['r'] = 1
    g.node[3]['r'] = 1.5
    g.node[4]['r'] = 1

    g[1][2]['c'] = 2
    g[1][3]['c'] = 1
    g[2][4]['c'] = 1
    g[3][4]['c'] = 3

    U = range(6)  # 0...5
    
    expected_edge_list = [
        [],
        [(1, 3)],
        [(1, 3)],  # DiGraph([(1, 2)])
        [(1, 2), (1, 3)],
        [(1, 2), (1, 3), (2, 4)],
        [(1, 2), (1, 3), (2, 4)]
    ]
    return g, U, expected_edge_list
开发者ID:xiaohan2012,项目名称:lst,代码行数:26,代码来源:test_lst_dag.py


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