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
2 changes: 2 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -307,6 +307,8 @@ graphblas_algorithms.nxapi
│ └── is_tree
├── triads
│ └── is_triad
├── vitality
│ └── closeness_vitality
└── wiener
├── gutman_index
├── hyper_wiener_index
Expand Down
2 changes: 2 additions & 0 deletions _nx_graphblas/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,7 @@ def get_info():
"boundary_expansion",
"center",
"closeness_centrality",
"closeness_vitality",
"clustering",
"common_neighbor_centrality",
"complement",
Expand Down Expand Up @@ -200,6 +201,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".\nRaises OverflowError rather than add integer weights where the number of nodes times the\nheaviest absolute weight 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".',
"closeness_vitality": "A Wiener index is infinite unless every node reaches every node, so a node whose\nremoval disconnects the rest gets -inf, and on a disconnected graph inf or nan, as in\nNetworkX. Weights are served when Python ints or floats, at least 0, and not NaN on an\nedge between two nodes; inf is added as NetworkX adds it, and other weights are left\nto NetworkX. Integer weights raise OverflowError where the number of nodes cubed\ntimes the largest could reach 2**63. With ints mixed with floats a value is a float\nwhere NetworkX's can be an int (3.0 for 3). A graph of fewer than two nodes is left to\nNetworkX.",
"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, or\n`np.uint64` beside signed ints, as floats (1 as 1.0), bools mixed with numbers as\nnumbers (True as 1 or 1.0), and NumPy scalars as Python numbers. A mix that would\nchange a value, such as an int past 2**53 beside a float, is left to NetworkX.",
"cut_size": "Raises OverflowError rather than add integer weights whose absolute values sum to 2**63\nor more.",
Expand Down
10 changes: 10 additions & 0 deletions _nx_graphblas/core.py
Original file line number Diff line number Diff line change
Expand Up @@ -124,6 +124,16 @@
),
"center": _ECCENTRICITY_BOUNDS,
"closeness_centrality": _NEGATIVE_EDGES,
"closeness_vitality": (
"A Wiener index is infinite unless every node reaches every node, so a node whose\n"
"removal disconnects the rest gets -inf, and on a disconnected graph inf or nan, as in\n"
"NetworkX. Weights are served when Python ints or floats, at least 0, and not NaN on an\n"
"edge between two nodes; inf is added as NetworkX adds it, and other weights are left\n"
"to NetworkX. Integer weights raise OverflowError where the number of nodes cubed\n"
"times the largest could reach 2**63. With ints mixed with floats a value is a float\n"
"where NetworkX's can be an int (3.0 for 3). A graph of fewer than two nodes is left to\n"
"NetworkX."
),
"common_neighbor_centrality": (
"An `alpha` other than a Python int or float, unless it equals 1, is left to NetworkX."
),
Expand Down
1 change: 1 addition & 0 deletions graphblas_algorithms/algorithms/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,4 +26,5 @@
from .traversal import *
from .tree import *
from .triads import *
from .vitality import *
from .wiener import *
338 changes: 338 additions & 0 deletions graphblas_algorithms/algorithms/vitality.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,338 @@
"""Closeness vitality: the Wiener index less that of the graph without each node in turn."""

import math

import numpy as np
from graphblas import Matrix, agg, binary, monoid, replace, select, unary
from graphblas.semiring import any_pair, min_plus

from ._bfs import _visited
from ._helpers import _ADVICE

__all__ = ["closeness_vitality"]

# The memory a batch of rows may take. A row is a search from one source, with at most one node
# taken out, and peaks at about `_ROW_NODE_BYTES` per node of the graph; a row of the first pass
# also counts the parents of every edge, at about `_ROW_EDGE_BYTES` per edge.
_BATCH_BUDGET = 2**30
_ROW_NODE_BYTES = 64
_ROW_EDGE_BYTES = 48


def _rows_per_batch(n, m=0):
return max(1, _BATCH_BUDGET // (_ROW_NODE_BYTES * n + _ROW_EDGE_BYTES * m))


def closeness_vitality(G, node=None, wiener_index=None):
"""`wiener_index` less the Wiener index of `G` without `node`, or a dict over every node.

`wiener_index` defaults to that of `G`. The Wiener index of a graph is infinite unless every
node reaches every node, so a node whose removal disconnects the rest gets `-inf`, and on a
disconnected graph `inf` or `nan`. The subtraction is Python's, with the Wiener indices as
NetworkX gives them: an int on a directed graph of integer lengths, else a float.
"""
lengths = _Lengths(G)
if node is not None:
whole = None
if wiener_index is None:
wiener_index = whole = lengths.wiener(*lengths.totals())
if node in G:
after = lengths.wiener(*lengths.totals(G._key_to_id[node]))
else:
after = whole if whole is not None else lengths.wiener(*lengths.totals())
return wiener_index - after
whole, afters = lengths.every_removal()
if wiener_index is None:
wiener_index = whole
return {key: wiener_index - afters[index] for key, index in G._key_to_id.items()}


class _Lengths:
"""Lengths between nodes: hops times the one value every edge holds, or Bellman-Ford's.

Hops are exact and give each node its parents in one breadth-first level; Bellman-Ford rows
are used only when the values differ or are infinite.
"""

def __init__(self, G):
A = G.get_property("offdiag")
self.A = A
self.n = n = A.nrows
self.directed = G.is_directed()
self.scale = _one_value(A)
self.rows = _hop_rows if self.scale is not None else _length_rows
if A.dtype.np_type.kind in "iu" and A.nvals > 0:
heaviest = 1 if self.scale is not None else A.reduce_scalar(monoid.max).get()
# A per-node total adds up to `n` row sums of up to `n` lengths of up to `n - 1` edges.
if n * n * (n - 1) * max(heaviest, 1) >= 2**63:
raise OverflowError(
f"integer weights up to {heaviest} between {n} nodes could make a sum of "
f"lengths reach 2**63, {_ADVICE}"
)

def wiener(self, total, infinite, connected):
"""The Wiener index from the sum of finite lengths over ordered pairs, as NetworkX's."""
if not connected or infinite:
return math.inf
if self.scale is not None:
total *= self.scale
return total if self.directed else total / 2

def totals(self, removed=None):
"""`(sum of finite lengths, number infinite, every pair reached)` over ordered pairs.

Without node id `removed`, when given.
"""
n = self.n
sources = np.arange(n, dtype=np.uint64)
if removed is not None:
sources = sources[sources != removed]
total, infinite, reached = 0, 0, 0
size = _rows_per_batch(n)
for start in range(0, len(sources), size):
batch = sources[start : start + size]
gone = None if removed is None else np.full(len(batch), removed, np.uint64)
sums, infs, counts = self.stats(batch, gone)
total += _python_sum(sums)
infinite += int(infs.sum())
reached += int(counts.sum())
return total, infinite, reached == len(sources) ** 2

def every_removal(self):
"""The Wiener index of the graph, and a list of it without each node by node id.

Removing `v` changes the lengths from a source `s` only where `v` is the one parent of
a node in the shortest paths from `s`: otherwise, by induction on the length, every
other node keeps a shortest path that avoids `v`. So one pass over all sources gives
each source's sum of lengths and the nodes that matter to it, and a row is searched
again without `v` only for those pairs, and only when the graph stays connected
without `v`.
"""
n = self.n
connected_without = self._connected_without()
integer = self.A.dtype.np_type.kind in "iu" or self.scale is not None
acc = np.int64 if integer else np.float64
row_sums = np.zeros(n, acc)
row_infs = np.zeros(n, np.int64)
column_sums = np.zeros(n, acc)
column_infs = np.zeros(n, np.int64)
changed_sums = np.zeros(n, acc)
changed_infs = np.zeros(n, np.int64)
reached = 0
p, c, w = self.A.to_coo()
if self.scale is not None:
w = np.ones_like(p, dtype=np.int64)
size = _rows_per_batch(n, len(p))
for start in range(0, n, size):
sources = np.arange(start, min(start + size, n), dtype=np.uint64)
D = self.rows(self.A, sources)
sums, infs, counts = _row_stats(D)
row_sums[sources] = sums
row_infs[sources] = infs
reached += int(counts.sum())
lengths, finite, infinite = _dense(D)
finite_lengths = np.where(finite, lengths, 0)
column_sums += finite_lengths.sum(axis=0)
column_infs += infinite.sum(axis=0)
matters = _sole_parents(lengths, finite | infinite, sources, p, c, w)
matters &= connected_without
rows, removed = np.nonzero(matters)
# What each such row adds to the total without `v` if no length changed.
kept_sums = sums[rows] - finite_lengths[rows, removed]
kept_infs = infs[rows] - infinite[rows, removed]
again = sources[rows]
removed = removed.astype(np.uint64)
# The batch's rows are no longer needed while rows are searched again.
del D, lengths, finite, infinite, finite_lengths, matters, rows
step = _rows_per_batch(n)
for at in range(0, len(again), step):
part = slice(at, at + step)
new_sums, new_infs, _ = self.stats(again[part], removed[part])
np.add.at(changed_sums, removed[part], new_sums - kept_sums[part])
np.add.at(changed_infs, removed[part], new_infs - kept_infs[part])
total = _python_sum(row_sums)
infinite = int(row_infs.sum())
whole = self.wiener(total, infinite, reached == n * n)
afters = []
for v, (own, column, changed, own_inf, column_inf, changed_inf) in enumerate(
zip(
*map(np.ndarray.tolist, (row_sums, column_sums, changed_sums)),
*map(np.ndarray.tolist, (row_infs, column_infs, changed_infs)),
strict=True,
)
):
if not connected_without[v]:
afters.append(math.inf)
continue
after = total - own - column + changed
afters.append(self.wiener(after, infinite - own_inf - column_inf + changed_inf, True))
return whole, afters

def stats(self, sources, removed=None):
"""`_row_stats` of the rows from `sources`, row `i` without node `removed[i]`."""
if self.scale is not None:
return _hop_stats(self.A, sources, removed)
return _row_stats(_length_rows(self.A, sources, removed))

def _connected_without(self):
"""For each node id, whether every other node reaches every other without it."""
n = self.n
ids = np.arange(n, dtype=np.uint64)
sources = np.where(ids == 0, 1, 0).astype(np.uint64)
connected = np.empty(n, bool)
size = _rows_per_batch(n)
for start in range(0, n, size):
part = slice(start, start + size)
ok = _hop_stats(self.A, sources[part], ids[part])[2] == n - 1
if self.directed:
ok &= _hop_stats(self.A.T, sources[part], ids[part])[2] == n - 1
connected[part] = ok
return connected


def _one_value(A):
"""The value every edge holds, as a Python number, when there is one and it is finite."""
if A.nvals == 0:
return 1
least = A.reduce_scalar(monoid.min).get()
if least == A.reduce_scalar(monoid.max).get() and math.isfinite(least):
return least
return None


def _start(sources, ncols, value, dtype):
rows = np.arange(len(sources), dtype=np.uint64)
return Matrix.from_coo(rows, sources, value, dtype, nrows=len(sources), ncols=ncols)


def _hop_rows(A, sources, removed=None):
"""Hops from each source, a row each; row `i` never enters node `removed[i]`."""
n = A.nrows
D = _visited(_start(sources, n, 0, np.int64))
seen = _visited(_start(sources, n, True, bool))
if removed is not None:
seen(binary.lor) << _start(removed, n, True, bool)
F = _start(sources, n, True, bool)
depth = 0
while F.nvals > 0:
depth += 1
F(~seen.S, replace) << any_pair[bool](F @ A)
seen(F.S) << True
D(F.S) << depth
return D


def _hop_stats(A, sources, removed=None):
"""`_row_stats` of `_hop_rows`, added up a level at a time without holding the lengths."""
n = A.nrows
seen = _visited(_start(sources, n, True, bool))
if removed is not None:
seen(binary.lor) << _start(removed, n, True, bool)
F = _start(sources, n, True, bool)
sums = np.zeros(len(sources), np.int64)
counts = np.ones(len(sources), np.int64)
depth = 0
while F.nvals > 0:
depth += 1
F(~seen.S, replace) << any_pair[bool](F @ A)
seen(F.S) << True
level = F.reduce_rowwise(agg.count).new().to_dense(fill_value=0)
sums += depth * level
counts += level
return sums, np.zeros(len(sources), np.int64), counts


def _length_rows(A, sources, removed=None):
"""Least sums of values from each source, a row each, as `_hop_rows`; values at least 0.

Bellman-Ford that walks on only from lengths that changed; an infinite length is stored.
"""
n = A.nrows
dtype = A.dtype
D = _visited(_start(sources, n, 0, dtype))
F = D.dup()
gone = None if removed is None else _start(removed, n, True, bool)
Mask = _visited(Matrix(bool, len(sources), n))
one = unary.one[bool]
while F.nvals > 0:
F << min_plus[dtype](F @ A)
if gone is not None:
F(~gone.S, replace) << F
Mask << one(F)
Mask(binary.second) << binary.lt(F & D)
F(Mask.V, replace) << F
D(F.S) << F
return D


def _row_stats(D):
"""Per row: the sum of finite lengths, the number of infinite ones, the number reached."""
counts = D.reduce_rowwise(agg.count).new().to_dense(fill_value=0)
if D.dtype.np_type.kind != "f" or D.reduce_scalar(monoid.max).get(0) < math.inf:
return _row_sums(D), np.zeros(D.nrows, np.int64), counts
infinite = select.valueeq(D, math.inf).new()
infs = infinite.reduce_rowwise(agg.count).new().to_dense(fill_value=0)
del infinite
return _row_sums(select.valuene(D, math.inf).new()), infs, counts


def _row_sums(M):
return M.reduce_rowwise(monoid.plus).new().to_dense(fill_value=0)


def _dense(D):
"""`D` as a dense array, with where it holds a finite and an infinite length."""
rows, columns, values = D.to_coo()
lengths = np.zeros(D.shape, values.dtype)
lengths[rows, columns] = values
finite = np.zeros(D.shape, bool)
infinite = np.zeros(D.shape, bool)
if values.dtype.kind == "f":
is_inf = np.isinf(values)
finite[rows[~is_inf], columns[~is_inf]] = True
infinite[rows[is_inf], columns[is_inf]] = True
else:
finite[rows, columns] = True
return lengths, finite, infinite


def _sole_parents(lengths, reached, sources, p, c, w):
"""Per row, the nodes that are the one parent of a node, or every node a row reaches.

`p -> c` with value `w` is a parent edge where `length(p) + w == length(c)` and
`length(p) < length(c)`; strictness makes the parent order well founded, so a node with a
parent other than `v` keeps a path of its length without `v` (an infinite length stays
infinite). A reached node other than the source with no strict parent, as a zero or
infinite weight can make, leaves the row's lengths unexplained, and the row then counts
every node it reaches.
"""
b = len(sources)
rows = np.arange(b)
tail = lengths[:, p]
head = lengths[:, c]
strict = reached[:, p] & reached[:, c] & (tail + w == head) & (tail < head)
del tail, head
order = np.argsort(c, kind="stable")
heads = c[order]
if len(heads) > 0:
starts = np.flatnonzero(np.r_[True, heads[1:] != heads[:-1]])
counts = np.zeros(reached.shape, np.int32)
counts[:, heads[starts]] = np.add.reduceat(strict[:, order], starts, axis=1, dtype=np.int32)
else:
counts = np.zeros(reached.shape, np.int32)
sole = strict & (counts[:, c] == 1)
del strict
matters = np.zeros(reached.shape, bool)
r, e = np.nonzero(sole)
matters[r, p[e]] = True
unexplained = reached & (counts == 0)
unexplained[rows, sources] = False
whole = unexplained.any(axis=1)
matters[whole] = reached[whole]
matters[rows, sources] = False
return matters


def _python_sum(values):
"""The exact sum, as a Python int for integers."""
return sum(values.tolist())
4 changes: 4 additions & 0 deletions graphblas_algorithms/interface.py
Original file line number Diff line number Diff line change
Expand Up @@ -446,6 +446,10 @@ class Dispatcher:
# ================
is_triad = mod.is_triad

mod = nxapi.vitality
# ==================
closeness_vitality = mod.closeness_vitality

mod = nxapi.wiener
# ================
gutman_index = mod.gutman_index
Expand Down
Loading
Loading