Пример #1
0
 def test_create_using_keyword_arguments(self):
     assert_raises(networkx.exception.NetworkXError,
                   gn_graph,
                   100,
                   create_using=Graph())
     assert_raises(networkx.exception.NetworkXError,
                   gnr_graph,
                   100,
                   0.5,
                   create_using=Graph())
     assert_raises(networkx.exception.NetworkXError,
                   gnc_graph,
                   100,
                   create_using=Graph())
     assert_raises(networkx.exception.NetworkXError,
                   scale_free_graph,
                   100,
                   create_using=Graph())
     G = gn_graph(100, seed=1)
     MG = gn_graph(100, create_using=MultiDiGraph(), seed=1)
     assert_equal(sorted(G.edges()), sorted(MG.edges()))
     G = gnr_graph(100, 0.5, seed=1)
     MG = gnr_graph(100, 0.5, create_using=MultiDiGraph(), seed=1)
     assert_equal(sorted(G.edges()), sorted(MG.edges()))
     G = gnc_graph(100, seed=1)
     MG = gnc_graph(100, create_using=MultiDiGraph(), seed=1)
     assert_equal(sorted(G.edges()), sorted(MG.edges()))
Пример #2
0
    def test_create_using_keyword_arguments(self):
        assert_raises(nx.NetworkXError, gn_graph, 100, create_using=Graph())
        assert_raises(nx.NetworkXError,
                      gnr_graph,
                      100,
                      0.5,
                      create_using=Graph())
        assert_raises(nx.NetworkXError, gnc_graph, 100, create_using=Graph())
        assert_raises(nx.NetworkXError,
                      scale_free_graph,
                      100,
                      create_using=Graph())
        G = gn_graph(100, seed=1)
        MG = gn_graph(100, create_using=MultiDiGraph(), seed=1)
        assert_equal(sorted(G.edges()), sorted(MG.edges()))
        G = gnr_graph(100, 0.5, seed=1)
        MG = gnr_graph(100, 0.5, create_using=MultiDiGraph(), seed=1)
        assert_equal(sorted(G.edges()), sorted(MG.edges()))
        G = gnc_graph(100, seed=1)
        MG = gnc_graph(100, create_using=MultiDiGraph(), seed=1)
        assert_equal(sorted(G.edges()), sorted(MG.edges()))

        G = scale_free_graph(100,
                             alpha=0.3,
                             beta=0.4,
                             gamma=0.3,
                             delta_in=0.3,
                             delta_out=0.1,
                             create_using=MultiDiGraph,
                             seed=1)
        assert_raises(ValueError, scale_free_graph, 100, 0.5, 0.4, 0.3)
        assert_raises(ValueError, scale_free_graph, 100, alpha=-0.3)
        assert_raises(ValueError, scale_free_graph, 100, beta=-0.3)
        assert_raises(ValueError, scale_free_graph, 100, gamma=-0.3)
Пример #3
0
def get_geometry_cached(graph: MultiDiGraph, edge_tuple: tuple) -> LineString:
    """
    Cacheable
    Extract geometry of an edge from global graph object. If geometry doesn't exist set to straight line.

    :param graph: encodes road network, simplified and projected to UTM
    :param edge_tuple: (hashable for lru_cache), length = 3
        elements u, v, k
            u: int, edge start node
            v: int, edge end node
            k: int, edge key
    :return: edge geometry
    """

    # Extract edge data, in particular the geometry
    edge_data = graph.get_edge_data(edge_tuple[0], edge_tuple[1],
                                    edge_tuple[2])

    # If no geometry attribute, manually add straight line
    if 'geometry' in edge_data:
        edge_geom = edge_data['geometry']
    else:
        point_u = Point(
            (graph.nodes[edge_tuple[0]]['x'], graph.nodes[edge_tuple[0]]['y']))
        point_v = Point(
            (graph.nodes[edge_tuple[1]]['x'], graph.nodes[edge_tuple[1]]['y']))
        edge_geom = LineString([point_u, point_v])

    return edge_geom
Пример #4
0
def get_out_edges(graph: MultiDiGraph,
                  node: int) -> np.ndarray:
    """
    Extracts out edges from a given node
    :param graph: encodes road network, simplified and projected to UTM
    :param node: graph index to a single node
    :return: array with columns u, v, k with u = node
    """
    return np.atleast_2d([[u, v, k] for u, v, k in graph.out_edges(node, keys=True)])
Пример #5
0
def stochastic_graph(G, copy=True, weight='weight'):
    """Returns a right-stochastic representation of the directed graph
    ``G``.

    A right-stochastic graph is a weighted digraph in which for each
    node, the sum of the weights of all the out-edges of that node is
    1. If the graph is already weighted (for example, via a ``'weight'``
    edge attribute), the reweighting takes that into account.

    Parameters
    -----------
    G : NetworkX graph
        A :class:`~networkx.DiGraph` or :class:`~networkx.MultiDiGraph`.

    copy : boolean, optional
        If this is ``True``, then this function returns a new graph with
        the stochastic reweighting. Otherwise, the original graph is
        modified in-place (and also returned, for convenience).

    weight : edge attribute key (optional, default='weight')
        Edge attribute key used for reading the existing weight and
        setting the new weight.  If no attribute with this key is found
        for an edge, then the edge weight is assumed to be 1. If an edge
        has a weight, it must be a a positive number.

    """
    if copy:
        G = MultiDiGraph(G) if G.is_multigraph() else DiGraph(G)
    # There is a tradeoff here: the dictionary of node degrees may
    # require a lot of memory, whereas making a call to `G.out_degree`
    # inside the loop may be costly in computation time.
    degree = dict(G.out_degree(weight=weight))
    for u, v, d in G.edges(data=True):
        if degree[u] == 0:
            d[weight] = 0
        else:
            d[weight] = d.get(weight, 1) / degree[u]
    return G
Пример #6
0
def stochastic_graph(G, copy=True, weight='weight'):
    """Returns a right-stochastic representation of directed graph ``G``.

    A right-stochastic graph is a weighted digraph in which for each
    node, the sum of the weights of all the out-edges of that node is
    1. If the graph is already weighted (for example, via a ``'weight'``
    edge attribute), the reweighting takes that into account.

    Parameters
    ----------
    G : directed graph
        A :class:`~networkx.DiGraph` or :class:`~networkx.MultiDiGraph`.

    copy : boolean, optional
        If this is ``True``, then this function returns a new graph with
        the stochastic reweighting. Otherwise, the original graph is
        modified in-place (and also returned, for convenience).

    weight : edge attribute key (optional, default='weight')
        Edge attribute key used for reading the existing weight and
        setting the new weight.  If no attribute with this key is found
        for an edge, then the edge weight is assumed to be 1. If an edge
        has a weight, it must be a a positive number.

    """
    if copy:
        G = MultiDiGraph(G) if G.is_multigraph() else DiGraph(G)
    # There is a tradeoff here: the dictionary of node degrees may
    # require a lot of memory, whereas making a call to `G.out_degree`
    # inside the loop may be costly in computation time.
    degree = dict(G.out_degree(weight=weight))
    for u, v, d in G.edges(data=True):
        if degree[u] == 0:
            d[weight] = 0
        else:
            d[weight] = d.get(weight, 1) / degree[u]
    return G
Пример #7
0
def build_document(records):
    """
    Reconstruct provenance document from a collection of related records.

    :param collections.abc.Iterable(dict) records: collection of individual
        provenance records that together constitute a documents
    :return networkx.class.Digraph: directed graph representation of
        provenance document constructed from given records
    :raises TypeError: if records is null
    """

    records = iter(records)
    try:
        first_record = records.next()
    except StopIteration:
        return {}

    # For now, ignore "prefix" records.
    num_prefix_records = 0
    docid = first_record[DOCUMENT_KEY]

    graph = MultiDiGraph()

    for record in itertools.chain([first_record], records):

        if record[DOCTYPE_KEY] == PREFIX_TYPENAME:
            num_prefix_records += 1
            LOGGER.debug("Skipping prefix record %d", num_prefix_records)
            continue

        if record[DOCUMENT_KEY] != docid:
            raise DocumentMismatchException(docid, record[DOCUMENT_KEY])



    LOGGER.info("Skipped %d prefix records", num_prefix_records)