예제 #1
0
def bfs_edges(G, source, reverse=False, depth_limit=None):
    # FIXME: reverse not support.
    pg = G.project_to_simple()
    ctx = AppAssets(algo="bfs_generic")(pg,
                                        source,
                                        depth_limit,
                                        format="edges")
    return ctx.to_numpy("r", axis=0).tolist()
def degree_assortativity_coefficient(graph, x="out", y="in", weight=None):
    """Compute degree assortativity of graph.

    Assortativity measures the similarity of connections
    in the graph with respect to the node degree.

    Parameters
    ----------
    graph (:class:`graphscope.Graph`): A simple graph.

    x: string ('in','out')
       The degree type for source node (directed graphs only).

    y: string ('in','out')
       The degree type for target node (directed graphs only).

    weighted: bool (True, False)
        weighted graph or unweighted graph

    Returns
    -------
    r : float
       Assortativity of graph by degree.

    Examples

    .. code:: python

        >>> import graphscope
        >>> from graphscope.dataset import load_modern_graph
        >>> sess = graphscope.session(cluster_type="hosts", mode="eager")
        >>> g = load_modern_graph(sess)
        >>> g.schema
        >>> c = graphscope.degree_assortativity_coefficient(g, weight="weight")
        >>> sess.close()

    Notes
    -----
    This computes Eq. (21) in Ref. [1]_ , where e is the joint
    probability distribution (mixing matrix) of the degrees.  If G is
    directed than the matrix e is the joint probability of the
    user-specified degree type for the source and target.

    References
    ----------
    .. [1] M. E. J. Newman, Mixing patterns in networks,
       Physical Review E, 67 026126, 2003
    .. [2] Foster, J.G., Foster, D.V., Grassberger, P. & Paczuski, M.
       Edge direction and the structure of networks, PNAS 107, 10815-20 (2010).
    """
    weighted = False if weight is None else True
    ctx = AppAssets(algo="degree_assortativity_coefficient", context="tensor")(
        graph,
        source_degree_type=x,
        target_degree_type=y,
        weighted=weighted,
    )
    return ctx.to_numpy("r", axis=0)[0]
예제 #3
0
 def _node_boundary(G, nbunch1, nbunch2=None):
     n1json = json.dumps(list(nbunch1))
     if nbunch2 is not None:
         n2json = json.dumps(list(nbunch2))
     else:
         n2json = ""
     ctx = AppAssets(algo="node_boundary", context="tensor")(G, n1json,
                                                             n2json)
     return set(ctx.to_numpy("r", axis=0).tolist())
예제 #4
0
 def _boundary(G, nbunch1, nbunch2=None):
     n1json = json.dumps(list(nbunch1))
     if nbunch2:
         n2json = json.dumps(list(nbunch2))
     else:
         n2json = ""
     ctx = AppAssets(algo="edge_boundary", context="tensor")(G, n1json,
                                                             n2json)
     ret = ctx.to_numpy("r", axis=0).tolist()
     for e in ret:
         yield (e[0], e[1])
def numeric_assortativity_coefficient(graph, attribute):
    """Compute assortativity for numerical node attributes.

    Assortativity measures the similarity of connections
    in the graph with respect to the given numeric attribute.

    Args:
        graph (:class:`graphscope.Graph`): A simple graph.
        attribute (str): Node attribute key.

    Returns:
        r (float): Assortativity of graph for given attribute

    Examples
    --------
    .. code:: python

        >>> import graphscope
        >>> from graphscope.dataset import load_modern_graph
        >>> sess = graphscope.session(cluster_type="hosts", mode="eager")
        >>> g = load_modern_graph(sess)
        >>> g.schema
        >>> c = graphscope.numeric_assortativity_coefficient(g, attribute="name")
        >>> sess.close()

    Notes
    -----
    This computes Eq. (21) in Ref. [1]_ , for the mixing matrix
    of the specified attribute.

    References
    ----------
    .. [1] M. E. J. Newman, Mixing patterns in networks
           Physical Review E, 67 026126, 2003
    """

    ctx = AppAssets(algo="attribute_assortativity_coefficient",
                    context="tensor")(graph, True)
    return ctx.to_numpy("r", axis=0)[0]
def average_shortest_path_length(graph, weight=None):
    r"""Compute the average shortest path length.

    The average shortest path length is

    .. math::

       a =\sum_{s,t \in V} \frac{d(s, t)}{n(n-1)}

    where `V` is the set of nodes in `G`, `d(s, t)` is the shortest path from `s` to `t`,
    and `n` is the number of nodes in `G`.

    Parameters
    ----------
    graph : (:class:`graphscope.Graph`): A simple graph.
    weight: (str, optional): The edge data key corresponding to the edge weight.
        Note that property under multiple labels should have the consistent index.
        Defaults to None.

    Returns
    -------
    r : float
        The average shortest path length.

    Examples
    --------
    .. code:: python

        >>> import graphscope
        >>> from graphscope.dataset import load_modern_graph
        >>> sess = graphscope.session(cluster_type="hosts", mode="eager")
        >>> g = load_modern_graph(sess)
        >>> g.schema
        >>> c = graphscope.average_shortest_path_length(g, weight="weight")
        >>> sess.close()
    """
    ctx = AppAssets(algo="sssp_average_length", context="tensor")(graph)
    return ctx.to_numpy("r", axis=0)[0]
예제 #7
0
def bfs_edges(G, source, depth_limit=None):
    """edges in a breadth-first-search starting at source.

    Parameters
    ----------
    G : networkx graph

    source : node
       Specify starting node for breadth-first search; this function
       iterates over only those edges in the component reachable from
       this node.

    depth_limit : int, optional(default=len(G))
        Specify the maximum search depth

    Returns
    -------
    edges: list
       A list of edges in the breadth-first-search.

    Examples
    --------
    To get the edges in a breadth-first search::

        >>> G = nx.path_graph(3)
        >>> list(nx.bfs_edges(G, 0))
        [(0, 1), (1, 2)]
        >>> list(nx.bfs_edges(G, source=0, depth_limit=1))
        [(0, 1)]

    """
    # FIXME: reverse not support.
    depth_limit = -1 if depth_limit is None else depth_limit
    ctx = AppAssets(algo="bfs_generic", context="tensor")(G,
                                                          source,
                                                          depth_limit,
                                                          format="edges")
    return ctx.to_numpy("r", axis=0).tolist()
def attribute_assortativity_coefficient(graph, attribute):
    """Compute assortativity for node attributes.

    Assortativity measures the similarity of connections in the graph with
    respect to the given attribute.

    Args:
        graph (:class:`graphscope.Graph`): A simple graph.
        attribute (str): Node attribute key.

    Returns:
        r (float): Assortativity of graph for given attribute

    Notes:
        This computes Eq. (2) in Ref. [1]_ , (trace(M)-sum(M^2))/(1-sum(M^2)),
        where M is the joint probability distribution (mixing matrix)
        of the specified attribute.

    References:
        [1] M. E. J. Newman, Mixing patterns in networks, Physical Review E, 67 026126, 2003

    Examples:

    .. code:: python

        >>> import graphscope
        >>> from graphscope.dataset import load_modern_graph
        >>> sess = graphscope.session(cluster_type="hosts", mode="eager")
        >>> g = load_modern_graph(sess)
        >>> g.schema
        >>> c = graphscope.attribute_assortativity_coefficient(g, attribute="name")
        >>> sess.close()
    """
    ctx = AppAssets(algo="attribute_assortativity_coefficient",
                    context="tensor")(graph, False)
    return ctx.to_numpy("r", axis=0)[0]
def average_degree_connectivity(graph,
                                source="in+out",
                                target="in+out",
                                weight=None):
    """Compute the average degree connectivity of graph.

    The average degree connectivity is the average nearest neighbor degree of
    nodes with degree k. For weighted graphs, an analogous measure can
    be computed using the weighted average neighbors degree defined in
    [1]_, for a node `i`, as

    .. math::

        k_{nn,i}^{w} = \frac{1}{s_i} sum_{j in N(i)} w_{ij} k_j

    where `s_i` is the weighted degree of node `i`,
    `w_{ij}` is the weight of the edge that links `i` and `j`,
    and `N(i)` are the neighbors of node `i`.

    Parameters
    ----------
    graph : (:class:`graphscope.Graph`): A simple graph.

    source :  "in"|"out"|"in+out" (default:"in+out")
       Directed graphs only. Use "in"- or "out"-degree for source node.

    target : "in"|"out"|"in+out" (default:"in+out"
       Directed graphs only. Use "in"- or "out"-degree for target node.

    weight : string or None, optional (default=None)
       The edge attribute that holds the numerical value used as a weight.
       If None, then each edge has weight 1.

    Returns
    -------
    d : dict
       A dictionary keyed by degree k with the value of average connectivity.

    Raises
    ------
    ValueError
        If either `source` or `target` are not one of 'in',
        'out', or 'in+out'.

    Examples
    --------
    .. code:: python

        >>> import graphscope
        >>> from graphscope.dataset import load_modern_graph
        >>> sess = graphscope.session(cluster_type="hosts", mode="eager")
        >>> g = load_modern_graph(sess)
        >>> g.schema
        >>> c = graphscope.average_degree_connectivity(g, weight="weight")
        >>> sess.close()

    References
    ----------
    .. [1] A. Barrat, M. Barthélemy, R. Pastor-Satorras, and A. Vespignani,
       "The architecture of complex weighted networks".
       PNAS 101 (11): 3747–3752 (2004).
    """
    if graph.is_directed():
        if source not in ("in", "out", "in+out"):
            raise ValueError('source must be one of "in", "out", or "in+out"')
        if target not in ("in", "out", "in+out"):
            raise ValueError('target must be one of "in", "out", or "in+out"')
    ctx = AppAssets(algo="average_degree_connectivity",
                    context="tensor")(graph, source, target)
    res_list = ctx.to_numpy("r", axis=0).tolist()
    res_list = [i for item in res_list for i in item]
    degree = [int(i) for i in res_list[0::2]]
    degree_connectivity = res_list[1::2]
    res = dict(zip(degree, degree_connectivity))
    return res
예제 #10
0
def average_clustering(G, nodes=None, weight=None, count_zeros=True):
    # FIXME: nodes, weight, count_zeros not support.
    pg = G.project_to_simple()
    ctx = AppAssets(algo="avg_clustering")(pg)
    return ctx.to_numpy("r")[0]
예제 #11
0
def average_shortest_path_length(G, weight=None):
    pg = G.project_to_simple(e_prop=weight)
    ctx = AppAssets(algo="sssp_average_length")(pg, weight=True)
    return ctx.to_numpy("r", axis=0)[0]
예제 #12
0
def is_simple_path(graph, nodes):
    """Returns True if and only if `nodes` form a simple path in `G`.

    A *simple path* in a graph is a nonempty sequence of nodes in which
    no node appears more than once in the sequence, and each adjacent
    pair of nodes in the sequence is adjacent in the graph.

    Parameters
    ----------
    graph (:class:`graphscope.Graph`): A simple graph.
    nodes : list
        A list of one or more nodes in the graph `G`.

    Returns
    -------
    bool
        Whether the given list of nodes represents a simple path in `G`.

    Notes
    -----
    An empty list of nodes is not a path but a list of one node is a
    path. Here's an explanation why.

    This function operates on *node paths*. One could also consider
    *edge paths*. There is a bijection between node paths and edge
    paths.

    The *length of a path* is the number of edges in the path, so a list
    of nodes of length *n* corresponds to a path of length *n* - 1.
    Thus the smallest edge path would be a list of zero edges, the empty
    path. This corresponds to a list of one node.

    To convert between a node path and an edge path, you can use code
    like the following::

        >>> from networkx.utils import pairwise
        >>> nodes = [0, 1, 2, 3]
        >>> edges = list(pairwise(nodes))
        >>> edges
        [(0, 1), (1, 2), (2, 3)]
        >>> nodes = [edges[0][0]] + [v for u, v in edges]
        >>> nodes
        [0, 1, 2, 3]

    Examples
    --------
    .. code:: python

        >>> import graphscope
        >>> from graphscope.dataset import load_p2p_network
        >>> sess = graphscope.session(cluster_type="hosts", mode="eager")
        >>> g = load_p2p_network(sess)
        >>> # project to a simple graph (if needed)
        >>> pg = g.project(vertices={"host": ["id"]}, edges={"connect": ["dist"]})
        >>> c = graphscope.is_simple_path(pg, [2, 3, 8])
        >>> print(c)
        >>> sess.close()
    """
    if isinstance(nodes, list):
        n1json = json.dumps(nodes)
        ctx = AppAssets(algo="is_simple_path", context="tensor")(graph, n1json)
        return ctx.to_numpy("r", axis=0)[0]
    raise ValueError("input nodes is not a list object!")
예제 #13
0
 def _average_clustering(G):
     ctx = AppAssets(algo="avg_clustering", context="tensor")(G)
     return ctx.to_numpy("r")[0]
예제 #14
0
def transitivity(G):
    ctx = AppAssets(algo="transitivity", context="tensor")(G)
    return ctx.to_numpy("r")[0]
예제 #15
0
def has_path(G, source, target):
    ctx = AppAssets(algo="sssp_has_path", context="tensor")(G, source, target)
    return ctx.to_numpy("r", axis=0)[0]