Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 4 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -259,10 +259,13 @@ graphblas_algorithms.nxapi
│ └── pagerank
├── link_prediction
│ ├── adamic_adar_index
│ ├── cn_soundarajan_hopcroft
│ ├── common_neighbor_centrality
│ ├── jaccard_coefficient
│ ├── preferential_attachment
│ └── resource_allocation_index
│ ├── ra_index_soundarajan_hopcroft
│ ├── resource_allocation_index
│ └── within_inter_cluster
├── lowest_common_ancestors
│ └── lowest_common_ancestor
├── operators
Expand Down
6 changes: 6 additions & 0 deletions _nx_graphblas/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,7 @@ def get_info():
"center",
"closeness_centrality",
"clustering",
"cn_soundarajan_hopcroft",
"common_neighbor_centrality",
"complement",
"compose",
Expand Down Expand Up @@ -152,6 +153,7 @@ def get_info():
"partition_quality",
"periphery",
"preferential_attachment",
"ra_index_soundarajan_hopcroft",
"radius",
"reciprocity",
"resource_allocation_index",
Expand All @@ -171,6 +173,7 @@ def get_info():
"volume",
"weakly_connected_components",
"wiener_index",
"within_inter_cluster",
# END: functions
)

Expand Down Expand Up @@ -217,6 +220,7 @@ def get_info():
"bfs_successors": "The children in `bfs_edges`'s tree, which may differ from NetworkX's, as may the order.\n`sort_neighbors` is left to NetworkX.",
"center": '`usebounds` bounds the eccentricities on an undirected graph whose lengths are integers;\nelsewhere every one is computed. The null graph is left to NetworkX.\nLengths are Bellman-Ford\'s, so a negative edge without a negative cycle is answered where\nNetworkX\'s Dijkstra raises "Contradictory paths found".\nInteger weights are left to NetworkX where the number of nodes times the heaviest absolute\nweight reaches 2**62, as a length could then pass 2**63.',
"closeness_centrality": 'Lengths are Bellman-Ford\'s, so a negative edge without a negative cycle is answered where\nNetworkX\'s Dijkstra raises "Contradictory paths found".',
"cn_soundarajan_hopcroft": "The triples come in NetworkX's order. A node without the community raises\nNetworkXAlgorithmError when the pair that looks it up is reached, as there. Left to\nNetworkX: a `community` that is None, callable or unhashable; communities other than\nints, floats, complex numbers, strings, bytes, None and tuples or frozensets of them,\nnumpy's values among them; a graph class with its own `adjacency` or `nodes`; and a\nfirst failing pair with two or more common neighbors without the community, of which\nNetworkX names the first in its sets' order (with every non-edge, a node with a community\nand two or more neighbors without one).",
"common_neighbor_centrality": "An `alpha` other than a Python int or float, unless it equals 1, is left to NetworkX.",
"compose": "Edge weights come back in the one type their matrix holds: mixed ints and floats as\nfloats (1 as 1.0), bools mixed with numbers as numbers (True as 1 or 1.0), and NumPy\nscalars as Python numbers. Weights that would hold an int past 2**53 as a float, such as\none beside a float, or that are all ints held as floats, such as `np.uint64` beside a\nsigned int, are left to NetworkX.",
"cut_size": "Integer weights are left to NetworkX where their absolute values sum to 2**63 or more.\nWith `weight`, an iterator `S` or `T` is left to NetworkX.",
Expand Down Expand Up @@ -249,13 +253,15 @@ def get_info():
"node_degree_xy": 'The pairs come by edge, both ends in node order, not in NetworkX\'s adjacency order.\nNetworkX\'s own `degree_mixing_dict` takes these degrees as keys.\nA weighted degree is an int where the weights are all integers, and a float where any is\na float; NetworkX adds up an int for a node whose own weights are all integers, or that\nhas none, so there an equal float stands for its int.\nOn a directed graph, an `x` or `y` other than "in" or "out" is left to NetworkX, as are\ncomplex weights and float weights whose sums FP64 could round: the weighted degrees are\nkeys, so the weights must all be multiples of one power of two whose sums stay below\n2**52 of it, so that each weighted degree is NetworkX\'s, bit for bit.\nInteger weights are left to NetworkX where a weighted degree could reach 2**63: where the\nabsolute values one node adds (a self-loop\'s twice) sum to that.',
"numeric_assortativity_coefficient": "The Pearson correlation of the pairs in float64, within rounding of NetworkX's. Where\nNetworkX squares ints past about 3e9 in int64, which wraps, this gives the true\ncoefficient. Values that are not real numbers, an iterator `nodes`, which NetworkX\nreads twice, and a node in `nodes` that is not in the graph are left to NetworkX; a\nnode without the attribute raises KeyError, as there.\nThe values are read from the graph as NetworkX's mixing reads them, a node without the\nattribute as None, and values a dict takes as one key are one value. Left to NetworkX:\na graph class with its own `adjacency` or `nodes`, an `attribute` that is None,\ncallable or unhashable, and values no dict can key.",
"periphery": '`usebounds` bounds the eccentricities on an undirected graph whose lengths are integers;\nelsewhere every one is computed. The null graph is left to NetworkX.\nLengths are Bellman-Ford\'s, so a negative edge without a negative cycle is answered where\nNetworkX\'s Dijkstra raises "Contradictory paths found".\nInteger weights are left to NetworkX where the number of nodes times the heaviest absolute\nweight reaches 2**62, as a length could then pass 2**63.',
"ra_index_soundarajan_hopcroft": "The sums are added in another order than NetworkX's, so a score may differ from\nNetworkX's in its last bits.\nThe triples come in NetworkX's order. A node without the community raises\nNetworkXAlgorithmError when the pair that looks it up is reached, as there. Left to\nNetworkX: a `community` that is None, callable or unhashable; communities other than\nints, floats, complex numbers, strings, bytes, None and tuples or frozensets of them,\nnumpy's values among them; a graph class with its own `adjacency` or `nodes`; and a\nfirst failing pair with two or more common neighbors without the community, of which\nNetworkX names the first in its sets' order (with every non-edge, a node with a community\nand two or more neighbors without one).",
"radius": '`usebounds` bounds the eccentricities on an undirected graph whose lengths are integers;\nelsewhere every one is computed. The null graph is left to NetworkX.\nLengths are Bellman-Ford\'s, so a negative edge without a negative cycle is answered where\nNetworkX\'s Dijkstra raises "Contradictory paths found".\nInteger weights are left to NetworkX where the number of nodes times the heaviest absolute\nweight reaches 2**62, as a length could then pass 2**63.',
"reverse": "Edge weights come back in the one type their matrix holds: mixed ints and floats as\nfloats (1 as 1.0), bools mixed with numbers as numbers (True as 1 or 1.0), and NumPy\nscalars as Python numbers. Weights that would hold an int past 2**53 as a float, such as\none beside a float, or that are all ints held as floats, such as `np.uint64` beside a\nsigned int, are left to NetworkX.",
"schultz_index": 'A graph with a node named "weight" is left to NetworkX.\nInteger weights are left to NetworkX where the number of nodes times the heaviest absolute\nweight reaches 2**62, or where the sum over one node\'s targets could reach 2**63.',
"single_source_bellman_ford_path_length": "Integer weights are left to NetworkX where the number of nodes times the heaviest absolute\nweight reaches 2**62, as a length could then pass 2**63.",
"union": "Edge weights come back in the one type their matrix holds: mixed ints and floats as\nfloats (1 as 1.0), bools mixed with numbers as numbers (True as 1 or 1.0), and NumPy\nscalars as Python numbers. Weights that would hold an int past 2**53 as a float, such as\none beside a float, or that are all ints held as floats, such as `np.uint64` beside a\nsigned int, are left to NetworkX.",
"volume": "Integer weights are left to NetworkX where their absolute values sum to 2**63 or more, or to 2**63 over the most times `S` names one node.\nWith `weight`, an iterator `S` is left to NetworkX.",
"wiener_index": 'Lengths are Bellman-Ford\'s, so a negative edge without a negative cycle is answered where\nNetworkX\'s Dijkstra raises "Contradictory paths found".\nInteger weights are left to NetworkX where the number of nodes times the heaviest absolute\nweight reaches 2**62, or where the sum over one node\'s targets could reach 2**63.',
"within_inter_cluster": "The ratios are NetworkX's to the last bit. A `delta` other than a Python float or an\nint below 2**52 is left to NetworkX.\nThe triples come in NetworkX's order. A node without the community raises\nNetworkXAlgorithmError when the pair that looks it up is reached, as there. Left to\nNetworkX: a `community` that is None, callable or unhashable; communities other than\nints, floats, complex numbers, strings, bytes, None and tuples or frozensets of them,\nnumpy's values among them; a graph class with its own `adjacency` or `nodes`; and a\nfirst failing pair with two or more common neighbors without the community, of which\nNetworkX names the first in its sets' order (with every non-edge, a node with a community\nand two or more neighbors without one).",
# END: additional_docs
}
# fmt: on
Expand Down
20 changes: 20 additions & 0 deletions _nx_graphblas/core.py
Original file line number Diff line number Diff line change
Expand Up @@ -132,6 +132,17 @@
"callable or unhashable, and values no dict can key."
)

_COMMUNITY = (
"The triples come in NetworkX's order. A node without the community raises\n"
"NetworkXAlgorithmError when the pair that looks it up is reached, as there. Left to\n"
"NetworkX: a `community` that is None, callable or unhashable; communities other than\n"
"ints, floats, complex numbers, strings, bytes, None and tuples or frozensets of them,\n"
"numpy's values among them; a graph class with its own `adjacency` or `nodes`; and a\n"
"first failing pair with two or more common neighbors without the community, of which\n"
"NetworkX names the first in its sets' order (with every non-edge, a node with a community\n"
"and two or more neighbors without one)."
)

# Prose NetworkX shows under a function's documentation, for behaviour its docstring does not
# describe.
_ADDITIONAL_DOCS = {
Expand Down Expand Up @@ -176,6 +187,7 @@
),
"center": _ECCENTRICITY_BOUNDS,
"closeness_centrality": _NEGATIVE_EDGES,
"cn_soundarajan_hopcroft": _COMMUNITY,
"common_neighbor_centrality": (
"An `alpha` other than a Python int or float, unless it equals 1, is left to NetworkX."
),
Expand Down Expand Up @@ -265,13 +277,21 @@
"node without the attribute raises KeyError, as there.\n" + _NODE_ATTRIBUTE
),
"periphery": _ECCENTRICITY_BOUNDS,
"ra_index_soundarajan_hopcroft": (
"The sums are added in another order than NetworkX's, so a score may differ from\n"
"NetworkX's in its last bits.\n" + _COMMUNITY
),
"radius": _ECCENTRICITY_BOUNDS,
"schultz_index": 'A graph with a node named "weight" is left to NetworkX.\n'
+ _LENGTH_SUM_OVERFLOW,
"single_source_bellman_ford_path_length": _PATH_OVERFLOW,
"volume": _SUM_OVERFLOW + ", or to 2**63 over the most times `S` names one node.\n"
"With `weight`, an iterator `S` is left to NetworkX.",
"wiener_index": _NEGATIVE_EDGES + "\n" + _LENGTH_SUM_OVERFLOW,
"within_inter_cluster": (
"The ratios are NetworkX's to the last bit. A `delta` other than a Python float or an\n"
"int below 2**52 is left to NetworkX.\n" + _COMMUNITY
),
}

# A graph these names return is rebuilt from one matrix, which holds its values in one type.
Expand Down
103 changes: 101 additions & 2 deletions graphblas_algorithms/algorithms/link_prediction.py
Original file line number Diff line number Diff line change
@@ -1,18 +1,28 @@
from collections import namedtuple
from math import inf, log

import numpy as np
from graphblas import Matrix, Vector, binary
from graphblas import Matrix, Vector, binary, dtypes
from graphblas.semiring import any_second, plus_first, plus_pair

from ._bfs import _bfs_level
from .shortest_paths._distance_batches import distance_batches

__all__ = [
"Communities",
"adamic_adar_index",
"cn_soundarajan_hopcroft",
"common_neighbor_centrality",
"communities",
"community_misses",
"jaccard_coefficient",
"missing_common_neighbor",
"missing_neighbors",
"preferential_attachment",
"ra_index_soundarajan_hopcroft",
"resource_allocation_index",
"same_community",
"within_inter_cluster",
]

# Each function scores node pairs given by id: `u` and `v` are arrays of one length, or `u` is
Expand Down Expand Up @@ -67,7 +77,9 @@ def _pair_sums(G, u, v, weights=None, *, A=None):
"""For each pair, the common neighbors of its nodes: how many, or their total weight.

The pair's own nodes are not common neighbors unless `A`, an adjacency with the self-loops
on its diagonal, is given in place of the one without them. A pair with none scores 0.
on its diagonal, is given in place of the one without them; another symmetric `A`, such as
the edges within communities, counts the neighbors common along its edges. A pair with
none scores 0.
"""
if A is None:
A = G.get_property("offdiag")
Expand Down Expand Up @@ -180,3 +192,90 @@ def common_neighbor_centrality(G, u, v, alpha=0.8):
# NetworkX's order of operations, so that the result matches it to the last bit.
with np.errstate(divide="ignore", invalid="ignore"):
return alpha * shared + (1 - alpha) * len(G) / distances


# `codes`: each node's community by id, as a number: two nodes have equal numbers >= 0 when
# NetworkX takes their values as equal, -1 marks a node without the attribute, and -2 a value
# equal to nothing, itself included (NaN).
# `same`: the edges, self-loops left out, whose two ends have one community.
# `missing`: a Vector of 1.0 at each node without the attribute, or None when every node has it.
Communities = namedtuple("Communities", ["codes", "same", "missing"])


def communities(G, codes):
"""The `Communities` of the undirected `G` whose nodes have the community `codes`."""
n = len(G)
rows, cols, _ = G.get_property("offdiag").to_coo(values=False)
held = codes[rows]
keep = (held == codes[cols]) & (held >= 0)
same = Matrix.from_coo(rows[keep], cols[keep], 1, dtype=dtypes.INT64, nrows=n, ncols=n)
ids = np.flatnonzero(codes == -1)
missing = Vector.from_coo(ids, 1.0, size=n) if ids.size else None
return Communities(codes, same, missing)


def cn_soundarajan_hopcroft(G, u, v, communities):
"""The common neighbors, those in the pair's community counted twice."""
return _pair_sums(G, u, v) + _pair_sums(G, u, v, A=communities.same)


def ra_index_soundarajan_hopcroft(G, u, v, communities):
"""The sum of 1 / degree over the common neighbors in the pair's community; 0 for none.

A pair of two communities has no common neighbor in both.
"""
return _pair_sums(G, u, v, _neighbor_weights(G, "resource_allocation"), A=communities.same)


def within_inter_cluster(G, u, v, communities, delta):
"""Common neighbors in the pair's community over those outside it plus `delta`.

The counts are exact, and one addition and one division in float64 are NetworkX's, so the
ratio is NetworkX's to the last bit; where the pair's nodes are not of one community,
NetworkX gives 0 instead.
"""
within = _pair_sums(G, u, v, A=communities.same)
inter = _pair_sums(G, u, v) - within
with np.errstate(divide="ignore", invalid="ignore", over="ignore"):
return within / (inter + delta)


def same_community(communities, u, v):
"""Whether NetworkX takes the communities of each pair's nodes as equal."""
codes = communities.codes
held = codes[u]
return (held == codes[v]) & (held >= 0)


def community_misses(G, u, v, communities):
"""Where scoring each pair meets a node without a community, which NetworkX raises on.

0 where it meets none, -1 where `u` has none, -2 where `v` has none and `u` has one, and
otherwise, for a pair of one community, the number of its common neighbors without one,
each of which NetworkX looks up. None when every node has a community.
"""
if communities.missing is None:
return None
codes = communities.codes
shared = _pair_sums(G, u, v, communities.missing).astype(np.int64)
misses = np.where(same_community(communities, u, v), shared, 0)
misses = np.where(codes[v] == -1, -2, misses)
return np.where(codes[u] == -1, -1, misses)


def missing_neighbors(G, communities):
"""How many neighbors without a community each node with one has, by id."""
rv = np.zeros(len(G), np.int64)
if communities.missing is not None:
ids, counts = plus_pair(G.get_property("offdiag") @ communities.missing).new().to_coo()
rv[ids] = counts
rv[communities.codes < 0] = 0
return rv


def missing_common_neighbor(G, u, v, communities):
"""The id of the one common neighbor of `u` and `v`, not `u` or `v`, without a community."""
A = G.get_property("offdiag")
row = binary.first(A[int(u), :].new() & A[int(v), :].new()).new()
[rv] = binary.first(row & communities.missing).new().to_coo(values=False)[0].tolist()
return rv
3 changes: 3 additions & 0 deletions graphblas_algorithms/interface.py
Original file line number Diff line number Diff line change
Expand Up @@ -499,10 +499,13 @@ class Dispatcher:
mod = nxapi.link_prediction
# =========================
adamic_adar_index = mod.adamic_adar_index
cn_soundarajan_hopcroft = mod.cn_soundarajan_hopcroft
common_neighbor_centrality = mod.common_neighbor_centrality
jaccard_coefficient = mod.jaccard_coefficient
preferential_attachment = mod.preferential_attachment
ra_index_soundarajan_hopcroft = mod.ra_index_soundarajan_hopcroft
resource_allocation_index = mod.resource_allocation_index
within_inter_cluster = mod.within_inter_cluster

mod = nxapi.lowest_common_ancestors
# =================================
Expand Down
10 changes: 5 additions & 5 deletions graphblas_algorithms/nxapi/assortativity/mixing.py
Original file line number Diff line number Diff line change
Expand Up @@ -155,20 +155,20 @@ def degree_mixing_matrix(
return a


def node_attribute_rule(name, *, nodes_read_twice=False):
"""The `can_run` rule of the names that mix a node attribute along each edge."""
def node_attribute_rule(name, *, nodes_read_twice=False, param="attribute"):
"""The `can_run` rule of the names that read the node attribute their `param` names."""

def hook(bound):
import networkx as nx

attribute = bound["attribute"]
attribute = bound[param]
if attribute is None or callable(attribute):
# NetworkX's conversion then carries no attribute, or every one.
return f"{name} with `attribute` {attribute!r} is left to networkx"
return f"{name} with `{param}` {attribute!r} is left to networkx"
try:
hash(attribute)
except TypeError:
return f"{name} with an unhashable `attribute` raises in networkx"
return f"{name} with an unhashable `{param}` raises in networkx"
G = bound["G"]
cls = type(G)
if hasattr(G, "_adj") and (
Expand Down
Loading
Loading