Beispiel #1
0
    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)
Beispiel #2
0
    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)
Beispiel #3
0
 def __init__(self, mot_fts, act_model):
     DiGraph.__init__(self,
                      region=mot_fts,
                      action=act_model,
                      initial=set(),
                      type='MotActModel')
     self.build_full()
Beispiel #4
0
 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
Beispiel #5
0
 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()
Beispiel #6
0
 def __init__(self, ts, buchi, alpha=100):
     DiGraph.__init__(self,
                      ts=ts,
                      buchi=buchi,
                      alpha=alpha,
                      initial=set(),
                      accept=set(),
                      type='ProdAut')
Beispiel #7
0
 def __init__(self, mdp, dra):
     DiGraph.__init__(self,
                      mdp=mdp,
                      dra=dra,
                      initial=set(),
                      accept=[],
                      name='Product_Dra')
     self.graph['U'] = mdp.graph['U']
     print "-------Prod DRA Initialized-------"
     self.build_full()
Beispiel #8
0
 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
Beispiel #9
0
    def __init__(self,
                 NodesPos=None,
                 Edges=None,
                 Radii=None,
                 data=None,
                 Types=None):
        DiG.__init__(self, data)

        # attributes to be stored
        self.SetGeomGraph(NodesPos, Edges, Radii, Types)
        self.Area = 0
Beispiel #10
0
 def __init__(self, region_array, agent_prod_array, agent_fts_array,
              colla_ap, static_list):
     DiGraph.__init__(self,
                      region_array=region_array,
                      agent_prod_array=agent_prod_array,
                      agent_fts_array=agent_fts_array,
                      colla_ap=colla_ap,
                      static_list=static_list,
                      initial=set(),
                      accept=set(),
                      type='multi_prod')
     #structure: {(edge):[require_robot_index,responde_robot_index,require_position]}
     self.req_edges = {}
Beispiel #11
0
 def __init__(self, mdp, dra, gamma):
     DiGraph.__init__(self,
                      mdp=mdp,
                      dra=dra,
                      initial=set(),
                      accept=[],
                      name='Product_Dra',
                      gamma=[0, 0])
     self.graph['U'] = mdp.graph['U']
     print "-------Prod DRA Initialized-------"
     self.graph['dirichlet'] = None
     self.graph['gamma'] = gamma
     self.graph['home'] = set()
     self.build_full()
Beispiel #12
0
 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)))
Beispiel #13
0
    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)
Beispiel #14
0
    def __init__(self, data=None, **kwds):
        DiGraph.__init__(self, **kwds)
        if data is not None:

            try:  # build a rooted tree
                D = DiGraph()
                for (child, parent) in data.par.iteritems():
                    D.add_edge(parent, child)
            except AttributeError:
                D = DiGraph(data)
            except:  # else nothing we can do
                raise NetworkXError, "Data %s is not a rooted tree:" % data

            if D.order() == D.size() + 1:
                self.pred = D.pred.copy()
                self.succ = D.succ.copy()
                self.adj = self.succ
                del D
            else:  # not a tree
                raise NetworkXError, "Data %s is not a rooted tree:" % data
Beispiel #15
0
    def __init__(self,data=None,**kwds):
        DiGraph.__init__(self,**kwds)
        if data is not None:

            try: # build a rooted tree
                D=DiGraph()
                for (child,parent) in data.par.iteritems():
                    D.add_edge(parent,child)
            except AttributeError: 
                D=DiGraph(data)
            except: # else nothing we can do
                raise NetworkXError, "Data %s is not a rooted tree:"%data
                    
            if D.order()==D.size()+1:
                self.pred=D.pred.copy()
                self.succ=D.succ.copy()
                self.adj=self.succ
                del D
            else: # not a tree
                raise NetworkXError, "Data %s is not a rooted tree:"%data
Beispiel #16
0
 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)))
Beispiel #17
0
 def __init__(self, node_dict, symbols, ts_type):
     DiGraph.__init__(self, symbols=symbols, type=ts_type, initial=set())
     for (n, label) in node_dict.iteritems():
         self.add_node(n, label=label, status='confirmed')
Beispiel #18
0
 def __init__(self, data=None, **attr):
     self.edge_key_dict_factory = self.edge_key_dict_factory
     DiGraph.__init__(self, data, **attr)
Beispiel #19
0
	def __init__(self,*args,**kargs):
		DiGraph.__init__(self,*args,**kargs)
Beispiel #20
0
 def __init__(self, data=None, **attr):
     self.edge_key_dict_factory = self.edge_key_dict_factory
     DiGraph.__init__(self, data, **attr)
Beispiel #21
0
    def __init__(self, config=None):
        """fill out the link data from the csv file"""

        DiGraph.__init__(self)

        self.config = config

        if config is not None:

            infile = open(config['link_file'])
            reader = csv.reader(infile)

            data = []
            names = []

            for row in reader:
                if row[0] == 'A': names = row
                else: data.append(row)

            M = len(data)
            N = len(names)

            if 'perform_transformation' in config:

                if config['perform_transformation']:

                    #create wrong way links
                    if config['create_ww_links']:
                        names.append(config['ww_exist_alias'][1])
                        for i in range(M):
                            if int(data[i][names.index(
                                    config['ww_exist_alias'][0])]) == 1:
                                new_row = data[i] + [1]
                                if len(new_row) < len(names):
                                    print 'A'
                                    raise Exception
                                for var in config['ww_change']:
                                    idx = names.index(var)
                                    stmt = "new_row[idx]=float(new_row[idx])" + config[
                                        'ww_change'][var][
                                            0] + "config['ww_change'][var][1]"
                                    ###print names
                                    ###print data[i]
                                    exec(stmt)
                                if len(new_row) < len(names):
                                    print 'B'
                                    raise Exception
                                data.append(new_row)

                            data[i].append(0)

                    M = len(data)
                    N = len(names)

                    #transform variables
                    for var in config['variable_transforms']:
                        names.append(var)
                        for i in range(M):
                            if type(config['variable_transforms'][var]
                                    [1]) == type({}):
                                stmt = "data[i].append(config['variable_transforms'][var][1][" + config[
                                    'variable_transforms'][var][
                                        2] + "(data[i][names.index(config['variable_transforms'][var][0])])])"
                                exec(stmt)
                            else:
                                if type(config['variable_transforms'][var]
                                        [1]) == type((1, 2)):
                                    stmt = "data[i].append(" + config[
                                        'variable_transforms'][var][1][
                                            0] + "(" + config[
                                                'variable_transforms'][var][
                                                    2] + "(data[i][names.index(config['variable_transforms'][var][0])]),config['variable_transforms'][var][1][1]))"
                                    exec(stmt)
                                else:
                                    print 'D'
                                    raise Exception

            M = len(data)
            N = len(names)

            if 'relevant_variables' in config:
                to_keep = []
                for var in config['relevant_variables']:
                    to_keep.append(names.index(var))
            else:
                to_keep = range(2, N)

            for i in range(M):
                edge_data = {}
                for j in to_keep:
                    try:
                        edge_data[names[j]] = float(data[i][j])
                    except IndexError:
                        print names
                        print j
                        print data[i]
                        print i
                        print to_keep
                        print len(names)
                        print len(data[i])
                        raise Exception
                self.add_edge(int(data[i][0]), int(data[i][1]), edge_data)

            infile.close()

            if 'node_file' in config:
                self.create_node_xy_from_csv(config)

        self.orig_network = None
Beispiel #22
0
 def __init__(self, algo_id, *args, **kwargs):
     self.id = algo_id
     self.active_states = []
     self.state_id_dict = {
     }  # dictionary of state.id aliases for convenient node/edge lookups
     DiGraph.__init__(self, args, kwargs)
Beispiel #23
0
    def __init__(self, config=None):
        """fill out the link data from the csv file"""

        DiGraph.__init__(self)

        self.config = config

        if config is not None:

            infile = open(config["link_file"])
            reader = csv.reader(infile)

            data = []
            names = []

            for row in reader:
                if row[0] == "A":
                    names = row
                else:
                    data.append(row)

            M = len(data)
            N = len(names)

            if "perform_transformation" in config:

                if config["perform_transformation"]:

                    # create wrong way links
                    if config["create_ww_links"]:
                        names.append(config["ww_exist_alias"][1])
                        for i in range(M):
                            if int(data[i][names.index(config["ww_exist_alias"][0])]) == 1:
                                new_row = data[i] + [1]
                                if len(new_row) < len(names):
                                    print "A"
                                    raise Exception
                                for var in config["ww_change"]:
                                    idx = names.index(var)
                                    stmt = (
                                        "new_row[idx]=float(new_row[idx])"
                                        + config["ww_change"][var][0]
                                        + "config['ww_change'][var][1]"
                                    )
                                    ###print names
                                    ###print data[i]
                                    exec (stmt)
                                if len(new_row) < len(names):
                                    print "B"
                                    raise Exception
                                data.append(new_row)

                            data[i].append(0)

                    M = len(data)
                    N = len(names)

                    # transform variables
                    for var in config["variable_transforms"]:
                        names.append(var)
                        for i in range(M):
                            if type(config["variable_transforms"][var][1]) == type({}):
                                stmt = (
                                    "data[i].append(config['variable_transforms'][var][1]["
                                    + config["variable_transforms"][var][2]
                                    + "(data[i][names.index(config['variable_transforms'][var][0])])])"
                                )
                                exec (stmt)
                            else:
                                if type(config["variable_transforms"][var][1]) == type((1, 2)):
                                    stmt = (
                                        "data[i].append("
                                        + config["variable_transforms"][var][1][0]
                                        + "("
                                        + config["variable_transforms"][var][2]
                                        + "(data[i][names.index(config['variable_transforms'][var][0])]),config['variable_transforms'][var][1][1]))"
                                    )
                                    exec (stmt)
                                else:
                                    print "D"
                                    raise Exception

            M = len(data)
            N = len(names)

            if "relevant_variables" in config:
                to_keep = []
                for var in config["relevant_variables"]:
                    to_keep.append(names.index(var))
            else:
                to_keep = range(2, N)

            for i in range(M):
                edge_data = {}
                for j in to_keep:
                    try:
                        edge_data[names[j]] = float(data[i][j])
                    except IndexError:
                        print names
                        print j
                        print data[i]
                        print i
                        print to_keep
                        print len(names)
                        print len(data[i])
                        raise Exception
                self.add_edge(int(data[i][0]), int(data[i][1]), edge_data)

            infile.close()

            if "node_file" in config:
                self.create_node_xy_from_csv(config)

        self.orig_network = None
Beispiel #24
0
	def __init__(self, ts, buchi, alpha=100):
		DiGraph.__init__(self, ts=ts, buchi=buchi, alpha=alpha, initial=set(), accept=set(), type='ProdAut')
Beispiel #25
0
    def __init__(self,
                 incoming_graph_data=None,
                 multigraph_input=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.

        multigraph_input : bool or None (default None)
            Note: Only used when `incoming_graph_data` is a dict.
            If True, `incoming_graph_data` is assumed to be a
            dict-of-dict-of-dict-of-dict structure keyed by
            node to neighbor to edge keys to edge data for multi-edges.
            A NetworkXError is raised if this is not the case.
            If False, :func:`to_networkx_graph` is used to try to determine
            the dict's graph data structure as either a dict-of-dict-of-dict
            keyed by node to neighbor to edge data, or a dict-of-iterable
            keyed by node to neighbors.
            If None, the treatment for True is tried, but if it fails,
            the treatment for False is tried.

        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
        # multigraph_input can be None/True/False. So check "is not False"
        if isinstance(incoming_graph_data,
                      dict) and multigraph_input is not False:
            DiGraph.__init__(self)
            try:
                convert.from_dict_of_dicts(incoming_graph_data,
                                           create_using=self,
                                           multigraph_input=True)
                self.graph.update(attr)
            except Exception as e:
                if multigraph_input is True:
                    raise nx.NetworkXError(
                        f"converting multigraph_input raised:\n{type(e)}: {e}")
                DiGraph.__init__(self, incoming_graph_data, **attr)
        else:
            DiGraph.__init__(self, incoming_graph_data, **attr)
Beispiel #26
0
	def __init__(self, mdp, dra):
		DiGraph.__init__(self, mdp=mdp, dra=dra, initial=set(), accept=[], name='Product_Dra')
                self.graph['U'] = mdp.graph['U']
                print "-------Prod DRA Initialized-------"
                self.build_full()
Beispiel #27
0
 def __init__(self, mot_fts, act_model):
     DiGraph.__init__(self, region=mot_fts, action=act_model, initial=set(), type='MotActModel')
Beispiel #28
0
 def __init__(self, algo_id, *args, **kwargs):
     self.id = algo_id
     self.active_states = []
     self.state_id_dict = {}        # dictionary of state.id aliases for convenient node/edge lookups
     DiGraph.__init__(self, args, kwargs)