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
6 changes: 4 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -149,8 +149,10 @@ graphblas_algorithms.nxapi
│ │ └── group_out_degree_centrality
│ ├── harmonic
│ │ └── harmonic_centrality
│ └── katz
│ └── katz_centrality
│ ├── katz
│ │ └── katz_centrality
│ └── laplacian
│ └── laplacian_centrality
├── cluster
│ ├── average_clustering
│ ├── clustering
Expand Down
2 changes: 2 additions & 0 deletions _nx_graphblas/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -116,6 +116,7 @@ def get_info():
"k_shell",
"k_truss",
"katz_centrality",
"laplacian_centrality",
"laplacian_matrix",
"local_efficiency",
"lowest_common_ancestor",
Expand Down Expand Up @@ -222,6 +223,7 @@ def get_info():
"k_crust": "A precomputed `core_number`, or a `k` that is not a real number, is left to NetworkX.\nEdge 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.",
"k_shell": "A precomputed `core_number`, or a `k` that is not a real number, is left to NetworkX.\nEdge 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.",
"k_truss": "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.",
"laplacian_centrality": "A directed graph is left to NetworkX, whose directed Laplacian is dense and built from\nan eigenvector it finds iteratively. So are a nodelist that is not a list of hashable\nnodes, a graph whose Laplacian energy is not finite, float weights of both signs whose\nsum is so near 0 that NetworkX's order of summation decides whether it raises\nZeroDivisionError, and complex weights.",
"local_efficiency": "The cost is the breadth-first levels times the chunks of walks, so a node whose\nneighbors induce long paths (the hub of a wheel) is no faster than in NetworkX; the\nmemory stays bounded.",
"negative_edge_cycle": "Raises 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.",
"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".\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.',
Expand Down
7 changes: 7 additions & 0 deletions _nx_graphblas/core.py
Original file line number Diff line number Diff line change
Expand Up @@ -165,6 +165,13 @@
"k_corona": _CORE_SUBGRAPH,
"k_crust": _CORE_SUBGRAPH,
"k_shell": _CORE_SUBGRAPH,
"laplacian_centrality": (
"A directed graph is left to NetworkX, whose directed Laplacian is dense and built from\n"
"an eigenvector it finds iteratively. So are a nodelist that is not a list of hashable\n"
"nodes, a graph whose Laplacian energy is not finite, float weights of both signs whose\n"
"sum is so near 0 that NetworkX's order of summation decides whether it raises\n"
"ZeroDivisionError, and complex weights."
),
"local_efficiency": (
"The cost is the breadth-first levels times the chunks of walks, so a node whose\n"
"neighbors induce long paths (the hub of a wheel) is no faster than in NetworkX; the\n"
Expand Down
1 change: 1 addition & 0 deletions graphblas_algorithms/algorithms/centrality/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,3 +6,4 @@
from .group import *
from .harmonic import *
from .katz import *
from .laplacian import *
56 changes: 56 additions & 0 deletions graphblas_algorithms/algorithms/centrality/laplacian.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
import math

import numpy as np
from graphblas import Vector, binary, monoid, select, unary
from graphblas.semiring import plus_times

from ..exceptions import GraphBlasAlgorithmException

__all__ = ["laplacian_centrality"]


def _energy_drops(G):
"""Each node's drop in Laplacian energy when it is removed, and the energy: (array, float).

For an undirected graph's Laplacian L = D - A, with d the diagonal, the energy (the sum of
the squared eigenvalues of the symmetric L) is the sum of the squares of L's entries:
sum(d**2) plus the squares of the edge weights off the diagonal. NetworkX removes node i
by dropping its row and column and taking |L[j, i]| off each other diagonal entry, so the
drop for i is d[i]**2 + 2 * sum_j |A[i, j]| * d[j] + sum_j A[i, j]**2 over j other than i.
A self-loop is in no entry of L: NetworkX's diagonal is the row sum less the self-loop.
"""
A = G._A
d = A.reduce_rowwise(monoid.plus[float]).new(name="d")
d(binary.minus) << A.diag()
off = select.offdiag(A).new(dtype=float, name="off_diagonal")
squares = binary.times(off & off).new(name="squares").reduce_rowwise(monoid.plus)
squares = squares.new(name="squared_weights").to_dense(fill_value=0.0)
if off.nvals > 0 and off.reduce_scalar(monoid.min).get() < 0:
off << unary.abs(off)
across = plus_times(off @ d).new(name="across").to_dense(fill_value=0.0)
d = d.to_dense(fill_value=0.0)
with np.errstate(over="ignore", invalid="ignore"): # a non-finite energy is the caller's
d *= d
energy = float(d.sum() + squares.sum())
across *= 2
d += across
d += squares
return d, energy


def laplacian_centrality(G, normalized=True, *, name="laplacian_centrality"):
"""Each node's drop in Laplacian energy when it is removed, as a fraction of the energy.

An undirected graph only. NaN for every node when `normalized` and the energy is 0, which
is NetworkX's 0 / 0: only self-loops carry weight. Raises GraphBlasAlgorithmException when
the energy is not finite.
"""
drops, energy = _energy_drops(G)
if not math.isfinite(energy):
raise GraphBlasAlgorithmException(f"the Laplacian energy is {energy}")
if normalized:
if energy == 0:
drops[:] = np.nan
else:
drops /= energy
return Vector.from_dense(drops, name=name)
1 change: 1 addition & 0 deletions graphblas_algorithms/interface.py
Original file line number Diff line number Diff line change
Expand Up @@ -255,6 +255,7 @@ class Dispatcher:
group_out_degree_centrality = mod.group.group_out_degree_centrality
harmonic_centrality = mod.harmonic.harmonic_centrality
katz_centrality = mod.katz.katz_centrality
laplacian_centrality = mod.laplacian.laplacian_centrality

mod = nxapi.cluster
# =================
Expand Down
1 change: 1 addition & 0 deletions graphblas_algorithms/nxapi/centrality/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,3 +6,4 @@
from .group import *
from .harmonic import *
from .katz import *
from .laplacian import *
119 changes: 119 additions & 0 deletions graphblas_algorithms/nxapi/centrality/laplacian.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,119 @@
import math

import numpy as np

from graphblas_algorithms import algorithms
from graphblas_algorithms.classes.digraph import to_graph

from .._utils import can_run
from ..exception import NetworkXError, NetworkXPointlessConcept

__all__ = ["laplacian_centrality"]


def _rule(bound):
G = bound["G"]
nodelist = bound["nodelist"]
if G.is_directed():
return (
"laplacian_centrality of a directed graph is NetworkX's dense directed Laplacian, "
"from an eigenvector it finds iteratively; networkx serves it"
)
if nodelist is None:
return None
if not isinstance(nodelist, list):
# NetworkX adds a list to it: a tuple raises TypeError, an array broadcasts.
return f"laplacian_centrality with a {type(nodelist).__name__} nodelist; networkx serves it"
for node in nodelist:
try:
hash(node)
except TypeError:
# NetworkX's nbunch_iter words this error.
return "laplacian_centrality with an unhashable node in nodelist; networkx serves it"
return None


def _weightless(G):
"""Whether NetworkX finds `G.size(weight)` to be 0; None when its order of summation decides.

NetworkX sums the weighted degrees: each weight twice, a self-loop's too. The order does not
matter for weights of one sign, nor for weights that are multiples of one power of 2 whose
sizes sum to less than 2**52 of it (integers, halves), as every partial sum is then exact.
Otherwise the sum is 0 in no order when its exact value is past the rounding that a sum of
these terms can make.
"""
A = G._A
if A.nvals == 0:
return True
terms = np.concatenate([A.to_coo(rows=False, columns=False)[2], A.diag().to_coo()[1]])
if terms.dtype == bool:
return not terms.any()
if terms.dtype.kind in "iu":
return sum(terms.tolist()) == 0
if not np.isfinite(terms).all():
return False # NaN or infinite: never 0
if not (terms > 0).any() or not (terms < 0).any():
return not terms.any()
magnitude = float(np.abs(terms).sum())
if not math.isfinite(magnitude):
return None # a partial sum may overflow
low = _lowest_bit(terms)
if 52 + low >= 1024 or magnitude < math.ldexp(1.0, 52 + low):
return float(terms.sum()) / 2 == 0 # NetworkX's size halves the sum
exact = math.fsum(terms.tolist())
if abs(exact) > 2 * terms.size * 2**-53 * magnitude + 2**-1000:
return False
return None


def _lowest_bit(values):
"""The exponent of the lowest bit set in any of the nonzero float `values`."""
mantissas, exponents = np.frexp(values[values != 0])
whole = (mantissas * 2.0**53).astype(np.int64) # exact: a mantissa has 53 bits
lowest = np.frexp((whole & -whole).astype(np.float64))[1] - 1
return int((exponents - 53 + lowest).min())


@can_run(_rule)
def laplacian_centrality(
G, normalized=True, nodelist=None, weight="weight", walk_type=None, alpha=0.95
):
# Again here: a direct call does not pass through `can_run`.
if (reason := _rule({"G": G, "nodelist": nodelist})) is not None:
raise NotImplementedError(reason)
G = to_graph(G, weight=weight)
if weight is not None and weight == G._weight and G._A.dtype.np_type.kind == "c":
# The kernel would read only the real parts. Refused by the converted matrix's type,
# which needs no pass over the edges and sees a cached or given graph as well.
raise NotImplementedError(
f"Edge attribute {weight!r} has complex values; networkx serves the call"
)
if len(G) == 0:
raise NetworkXPointlessConcept("null graph has no centrality defined")
weightless = _weightless(G)
if weightless is None:
raise NotImplementedError(
"laplacian_centrality on edge weights that nearly cancel: whether NetworkX finds "
"their sum to be 0 depends on its order of summation; networkx serves it"
)
if weightless:
if normalized:
raise ZeroDivisionError("graph with no edges has zero full energy")
return dict.fromkeys(G._key_to_id, 0)
key_to_id = G._key_to_id
if nodelist is not None:
present = {node for node in nodelist if node in key_to_id}
if len(present) != len(nodelist):
raise NetworkXError("nodelist has duplicate nodes or nodes not in G")
try:
result = algorithms.laplacian_centrality(G, normalized)
except algorithms.exceptions.GraphBlasAlgorithmException as e:
raise NotImplementedError(
f"laplacian_centrality where {e.args[0]} (a NaN or infinite weight, or a square "
"past the float range); networkx serves it"
) from e
result = result.to_dense()
if nodelist is None:
return dict(zip(key_to_id, result.tolist(), strict=True))
ids = [key_to_id[node] for node in nodelist]
return dict(zip(nodelist, result[ids].tolist(), strict=True))
Loading
Loading