Python networkx 模块,set_edge_attributes() 实例源码

我们从Python开源项目中,提取了以下12个代码示例,用于说明如何使用networkx.set_edge_attributes()

项目:policosm    作者:ComplexCity    | 项目源码 | 文件源码
def addMetricDistanceToEdges(graph, epsgCode):
    # we assume initial epsg is wsg84 (merctor projection)
    metricDistance = {}

    if epsgCode != 4326:
        sourceProjection = osr.SpatialReference()
        sourceProjection.ImportFromEPSG(4326)
        destinationProjection = osr.SpatialReference()
        destinationProjection.ImportFromEPSG(epsgCode) # https://epsg.io/2154
        coordTrans = osr.CoordinateTransformation(sourceProjection, destinationProjection)

    for edge in graph.edges():
        node1, node2 =  edge
        line = ogr.Geometry(ogr.wkbLineString)
        line.AddPoint(graph.node[node1]['longitude'], graph.node[node1]['latitude'])
        line.AddPoint(graph.node[node2]['longitude'], graph.node[node2]['latitude'])
        if epsgCode != 4326:
            line.Transform(coordTrans)
        length = line.Length()
        metricDistance[edge] = length
    nx.set_edge_attributes(graph, 'length', metricDistance)

    return graph
项目:policosm    作者:ComplexCity    | 项目源码 | 文件源码
def addMetricDistanceToEdges(graph, epsgCode):
    # we assume initial epsg is wsg84 (merctor projection)
    metricDistance = {}

    if epsgCode != 4326:
        sourceProjection = osr.SpatialReference()
        sourceProjection.ImportFromEPSG(4326)
        destinationProjection = osr.SpatialReference()
        destinationProjection.ImportFromEPSG(epsgCode) # https://epsg.io/2154
        coordTrans = osr.CoordinateTransformation(sourceProjection, destinationProjection)

    for edge in graph.edges():
        node1, node2 =  edge
        line = ogr.Geometry(ogr.wkbLineString)
        line.AddPoint(graph.node[node1]['longitude'], graph.node[node1]['latitude'])
        line.AddPoint(graph.node[node2]['longitude'], graph.node[node2]['latitude'])
        if epsgCode != 4326:
            line.Transform(coordTrans)
        length = line.Length()
        metricDistance[edge] = length
    nx.set_edge_attributes(graph, 'length', metricDistance)

    return graph
项目:osmnx    作者:gboeing    | 项目源码 | 文件源码
def add_edge_lengths(G):
    """
    Add length (meters) attribute to each edge by great circle distance between
    nodes u and v.

    Parameters
    ----------
    G : networkx multidigraph

    Returns
    -------
    G : networkx multidigraph
    """

    start_time = time.time()

    # first load all the edges' origin and destination coordinates as a
    # dataframe indexed by u, v, key
    coords = np.array([[u, v, k, G.nodes[u]['y'], G.nodes[u]['x'], G.nodes[v]['y'], G.nodes[v]['x']] for u, v, k in G.edges(keys=True)])
    df_coords = pd.DataFrame(coords, columns=['u', 'v', 'k', 'u_y', 'u_x', 'v_y', 'v_x'])
    df_coords[['u', 'v', 'k']] = df_coords[['u', 'v', 'k']].astype(np.int64)
    df_coords = df_coords.set_index(['u', 'v', 'k'])

    # then calculate the great circle distance with the vectorized function
    gc_distances = great_circle_vec(lat1=df_coords['u_y'],
                                    lng1=df_coords['u_x'],
                                    lat2=df_coords['v_y'],
                                    lng2=df_coords['v_x'])

    gc_distances = gc_distances.fillna(value=0)
    nx.set_edge_attributes(G, name='length', values=gc_distances.to_dict())

    log('Added edge lengths to graph in {:,.2f} seconds'.format(time.time()-start_time))
    return G
项目:policosm    作者:ComplexCity    | 项目源码 | 文件源码
def addTimeTraveltoEdges(graph, transportation=['pedestrian, motorist']):
    print 'motorist in transportation', 'motorist' in transportation
    if 'pedestrian' in transportation:
        nx.set_edge_attributes(graph, 'pedestrian', pedestrianTime(graph))
    if 'motorist' in transportation:
        nx.set_edge_attributes(graph, 'motorist', motoristTime(graph))
    if 'publicTransportation' in transportation:
        nx.set_edge_attributes(graph, 'publicTransportation', motoristTime(graph))

    return graph
项目:policosm    作者:ComplexCity    | 项目源码 | 文件源码
def addTimeTraveltoEdges(graph, transportation=['pedestrian, motorist']):
    print 'motorist in transportation', 'motorist' in transportation
    if 'pedestrian' in transportation:
        nx.set_edge_attributes(graph, 'pedestrian', pedestrianTime(graph))
    if 'motorist' in transportation:
        nx.set_edge_attributes(graph, 'motorist', motoristTime(graph))
    if 'publicTransportation' in transportation:
        nx.set_edge_attributes(graph, 'publicTransportation', motoristTime(graph))

    return graph
项目:binet    作者:crisjf    | 项目源码 | 文件源码
def set_edge_attributes(self,name,values):
        """Set edge attributes from dictionary of edge tuples and values.

        Parameters
        ----------
        name : string
            Attribute name
        values : dict
            Dictionary of attribute values keyed by edge (tuple). 
            The keys must be tuples of the form (u, v). 
            If values is not a dictionary, then it is treated as a single attribute value that is then applied to every edge.
        """
        set_edge_attributes(self,name,values)
项目:binet    作者:crisjf    | 项目源码 | 文件源码
def build_net(self,RCA=True,th=1.,xth=0.):
        '''
        Builds the bipartite network with the given data.
        Warning: If RCA is False then th should be provided.

        Parameters
        ----------
        RCA      : boolean (True)
            Whether to use RCA filtering or regular filtering.
        th       : float (default=1)
            Threshold to use. If RCA=True is the RCA threshold, if RCA=False is the flow threshold.
        '''
        self.P[self.c] = None
        self.P[self.p] = None
        self.remove_edges_from(self.edges())
        header = '' if self.name == '' else self.name + ': '
        if 'RCA' not in self.data.columns.values:
            self._calculate_RCA()
        if RCA:
            net = self.data[(self.data['RCA']>=th)&(self.data['x']>=xth)][[self.c,self.p,'RCA','x']]
        else:
            print 'Warning: th should be provided.'
            net = self.data[self.data['x']>=th][[self.c,self.p,'RCA','x']]
        self.add_edges_from(zip(net[self.c].values,net[self.p].values))
        self.set_edge_attributes('RCA',dict(zip(zip(net[self.c].values,net[self.p].values),net['RCA'].values)))
        self.set_edge_attributes('x',dict(zip(zip(net[self.c].values,net[self.p].values),net['x'].values)))
项目:WNTR    作者:USEPA    | 项目源码 | 文件源码
def add_pump(self, name, start_node_name, end_node_name, info_type='POWER', info_value=50.0,
                 speed=1.0, pattern=None):
        """
        Adds a pump to the water network model.

        Parameters
        ----------
        name : string
            Name of the pump.
        start_node_name : string
             Name of the start node.
        end_node_name : string
             Name of the end node.
        info_type : string, optional
            Type of information provided for a pump. Options are 'POWER' or 'HEAD'.
        info_value : float or Curve object, optional
            Float value of power in KW. Head curve object.
        speed: float
            Relative speed setting (1.0 is normal speed)
        pattern: str or Pattern
            ID of pattern for speed setting

        """
        if info_value and isinstance(info_value, six.string_types):
            info_value = self.get_curve(info_value)
        pump = Pump(name, start_node_name, end_node_name, info_type, info_value, speed, pattern)
        self._links[name] = pump
        self._pumps[name] = pump
        self._graph.add_edge(start_node_name, end_node_name, key=name)
        nx.set_edge_attributes(self._graph, name='type', values={(start_node_name, end_node_name, name):'pump'})
        self._num_pumps += 1
项目:WNTR    作者:USEPA    | 项目源码 | 文件源码
def add_valve(self, name, start_node_name, end_node_name,
                 diameter=0.3048, valve_type='PRV', minor_loss=0.0, setting=0.0):
        """
        Adds a valve to the water network model.

        Parameters
        ----------
        name : string
            Name of the valve.
        start_node_name : string
             Name of the start node.
        end_node_name : string
             Name of the end node.
        diameter : float, optional
            Diameter of the valve.
        valve_type : string, optional
            Type of valve. Options are 'PRV', etc.
        minor_loss : float, optional
            Pipe minor loss coefficient.
        setting : float or string, optional
            pressure setting for PRV, PSV, or PBV,
            flow setting for FCV,
            loss coefficient for TCV,
            name of headloss curve for GPV.

        """
        start_node = self.get_node(start_node_name)
        end_node = self.get_node(end_node_name)
        if type(start_node)==Tank or type(end_node)==Tank:
            logger.warn('Valves should not be connected to tanks! Please add a pipe between the tank and valve. Note that this will be an error in the next release.')

        valve = Valve(name, start_node_name, end_node_name,
                      diameter, valve_type, minor_loss, setting)
        self._links[name] = valve
        self._valves[name] = valve
        self._graph.add_edge(start_node_name, end_node_name, key=name)
        nx.set_edge_attributes(self._graph, name='type', values={(start_node_name, end_node_name, name):'valve'})
        self._num_valves += 1
项目:exfi    作者:jlanga    | 项目源码 | 文件源码
def build_splicegraph(exon_index):
    """Build the splicegraph from a dict of SeqRecords

    Splicegraph is a directed graph, whose nodes
        - are exon_ids,
        - attributes are
            - coordinates [(transcript1, start, end), ..., (transcriptN, start, end)]
            - sequence in str format
    and whose edges
        - are connected exons in any way
        - attributes are the overlap between them:
            - positive means there is an overlap of that number of bases
            - zero means no overlap
            - negative means a gap of that number of bases
    """
    # Initialize grpah
    splice_graph = nx.DiGraph()

    # Add nodes
    splice_graph.add_nodes_from(exon_index.keys())
    nx.set_node_attributes(
        G=splice_graph,
        name='coordinates',
        values= exon_to_coordinates(exon_index)
    )
    nx.set_node_attributes(
        G=splice_graph,
        name='sequence',
        values={exon.id : str(exon.seq) for exon in exon_index.values()}
    )

    # Edges
    transcript2path = transcript_to_path(exons_to_df(exon_index))
    for path in transcript2path.values():
        splice_graph.add_path(path)

    nx.set_edge_attributes(
        G=splice_graph,
        name='overlap',
        values = compute_edge_overlaps(splice_graph)
    )

    return splice_graph
项目:WNTR    作者:USEPA    | 项目源码 | 文件源码
def add_pipe(self, name, start_node_name, end_node_name, length=304.8,
                 diameter=0.3048, roughness=100, minor_loss=0.0, status='OPEN', check_valve_flag=False):
        """
        Adds a pipe to the water network model.

        Parameters
        ----------
        name : string
            Name of the pipe.
        start_node_name : string
             Name of the start node.
        end_node_name : string
             Name of the end node.
        length : float, optional
            Length of the pipe.
        diameter : float, optional
            Diameter of the pipe.
        roughness : float, optional
            Pipe roughness coefficient.
        minor_loss : float, optional
            Pipe minor loss coefficient.
        status : string, optional
            Pipe status. Options are 'Open' or 'Closed'.
        check_valve_flag : bool, optional
            True if the pipe has a check valve.
            False if the pipe does not have a check valve.

        """
        length = float(length)
        diameter = float(diameter)
        roughness = float(roughness)
        minor_loss = float(minor_loss)
        if isinstance(status, str):
            status = LinkStatus[status]
        pipe = Pipe(name, start_node_name, end_node_name, length,
                    diameter, roughness, minor_loss, status, check_valve_flag)
        # Add to list of cv
        if check_valve_flag:
            self._check_valves.append(name)

        self._links[name] = pipe
        self._pipes[name] = pipe
        self._graph.add_edge(start_node_name, end_node_name, key=name)
        nx.set_edge_attributes(self._graph, name='type', values={(start_node_name, end_node_name, name):'pipe'})
        self._num_pipes += 1
项目:WNTR    作者:USEPA    | 项目源码 | 文件源码
def weight_graph(self, node_attribute={}, link_attribute={}):
        """
        Return a weighted graph based on node and link attributes.
        The weighted graph changes the direction of the original link if the weight is negative.

        Parameters
        ----------
        G : graph
            A networkx graph
        node_attribute :  dict or pandas Series
            node attributes
        link_attribues : dict or pandas Series
            link attributes


        Returns
        -------
        G : weighted graph
            A networkx weighted graph
        """

        for node_name in self.nodes():
            try:
                value = node_attribute[node_name]

                nx.set_node_attributes(self, name='weight', values={node_name: value})
            except:
                pass

        for (node1, node2, link_name) in list(self.edges(keys=True)):
            try:
                value = link_attribute[link_name]

                if value < 0: # change the direction of the link and value
                    link_type = self[node1][node2][link_name]['type'] # 'type' should be the only other attribute on G.edge
                    self.remove_edge(node1, node2, link_name)
                    self.add_edge(node2, node1, link_name)
                    nx.set_edge_attributes(self, name='type', values={(node2, node1, link_name): link_type})
                    nx.set_edge_attributes(self, name='weight', values={(node2, node1, link_name): -value})
                else:
                    nx.set_edge_attributes(self, name='weight', values={(node1, node2, link_name): value})
            except:
                    pass