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: 5 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -183,6 +183,7 @@ graphblas_algorithms.nxapi
│ ├── strongly_connected
│ │ ├── condensation
│ │ ├── is_strongly_connected
│ │ ├── kosaraju_strongly_connected_components
│ │ ├── number_strongly_connected_components
│ │ └── strongly_connected_components
│ └── weakly_connected
Expand All @@ -208,7 +209,8 @@ graphblas_algorithms.nxapi
│ └── volume
├── dag
│ ├── ancestors
│ └── descendants
│ ├── descendants
│ └── is_aperiodic
├── distance_measures
│ ├── center
│ ├── diameter
Expand All @@ -225,6 +227,8 @@ graphblas_algorithms.nxapi
├── generators
│ └── ego
│ └── ego_graph
├── hierarchy
│ └── flow_hierarchy
├── isolate
│ ├── is_isolate
│ ├── isolates
Expand Down
5 changes: 5 additions & 0 deletions _nx_graphblas/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -74,6 +74,7 @@ def get_info():
"eigenvector_centrality",
"fast_could_be_isomorphic",
"faster_could_be_isomorphic",
"flow_hierarchy",
"floyd_warshall",
"floyd_warshall_numpy",
"floyd_warshall_predecessor_and_distance",
Expand All @@ -95,6 +96,7 @@ def get_info():
"inter_community_edges",
"intersection",
"intra_community_edges",
"is_aperiodic",
"is_arborescence",
"is_attracting_component",
"is_branching",
Expand All @@ -121,6 +123,7 @@ def get_info():
"k_shell",
"k_truss",
"katz_centrality",
"kosaraju_strongly_connected_components",
"laplacian_matrix",
"local_efficiency",
"lowest_common_ancestor",
Expand Down Expand Up @@ -219,6 +222,7 @@ def get_info():
"edge_betweenness_centrality": "Unweighted: a call with `weight`, or with `k` short of every node, is left to NetworkX.\nThe edges come by their first ends in node order, then by their second ends in node\norder, which may differ from the order of `G.edges()`.",
"edge_betweenness_centrality_subset": "Unweighted: a call with `weight` is left to NetworkX. The edges come by their first ends\nin node order, then by their second ends in node order, which may differ from the order\nof `G.edges()`.",
"ego_graph": 'With `distance`, lengths are Bellman-Ford\'s, so a negative edge without a negative\ncycle is answered where NetworkX\'s Dijkstra raises "Contradictory paths found", and the\ncall raises OverflowError rather than add integer weights where the number of nodes\ntimes the heaviest absolute weight reaches 2**62, as a length could then pass 2**63.\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.',
"flow_hierarchy": "Integer weights, or none, give NetworkX's value exactly; float weights of one sign agree\nto within the rounding of their sums. Left to NetworkX: float weights of both signs,\nwhose sums can cancel; weights that sum to 0, where NetworkX raises ZeroDivisionError\nfor Python numbers and gives NaN for NumPy ones; float weights whose sum is past half\nthe float range; and complex weights.",
"floyd_warshall": "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.",
"floyd_warshall_predecessor_and_distance": "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.",
"group_closeness_centrality": "Unweighted: a call with `weight` is left to NetworkX.",
Expand All @@ -232,6 +236,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.",
"kosaraju_strongly_connected_components": "The components come by their first node, an order that may differ from NetworkX's. A `source` is left to NetworkX, whose versions differ on it.",
"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
9 changes: 9 additions & 0 deletions _nx_graphblas/core.py
Original file line number Diff line number Diff line change
Expand Up @@ -159,6 +159,13 @@
"call raises OverflowError rather than add integer weights where the number of nodes\n"
"times the heaviest absolute weight reaches 2**62, as a length could then pass 2**63."
),
"flow_hierarchy": (
"Integer weights, or none, give NetworkX's value exactly; float weights of one sign agree\n"
"to within the rounding of their sums. Left to NetworkX: float weights of both signs,\n"
"whose sums can cancel; weights that sum to 0, where NetworkX raises ZeroDivisionError\n"
"for Python numbers and gives NaN for NumPy ones; float weights whose sum is past half\n"
"the float range; and complex weights."
),
"floyd_warshall": _PATH_OVERFLOW,
"floyd_warshall_predecessor_and_distance": _PATH_OVERFLOW,
"group_closeness_centrality": "Unweighted: a call with `weight` is left to NetworkX.",
Expand All @@ -175,6 +182,8 @@
"k_corona": _CORE_SUBGRAPH,
"k_crust": _CORE_SUBGRAPH,
"k_shell": _CORE_SUBGRAPH,
"kosaraju_strongly_connected_components": _COMPONENT_ORDER
+ " A `source` is left to NetworkX, whose versions differ on it.",
"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/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
from .distance_measures import *
from .dominating import *
from .efficiency_measures import *
from .hierarchy import *
from .isolate import *
from .isomorphism import *
from .link_analysis import *
Expand Down
63 changes: 61 additions & 2 deletions graphblas_algorithms/algorithms/dag.py
Original file line number Diff line number Diff line change
@@ -1,9 +1,11 @@
import numpy as np
from graphblas import Vector, replace
from graphblas.semiring import any_pair

from ._bfs import _bfs_plain
from ._bfs import _adjacency, _bfs_plain, _visited
from .components.strongly_connected import _WALK_ROUND, _Budget

__all__ = ["ancestors", "descendants", "is_acyclic"]
__all__ = ["ancestors", "descendants", "is_acyclic", "is_aperiodic"]


def descendants(G, source):
Expand Down Expand Up @@ -44,3 +46,60 @@ def is_acyclic(G):
alive(~peel.S, replace) << alive
cache["is_acyclic"] = True
return True


def is_aperiodic(G):
"""Whether the lengths of the cycles of a strongly connected `G` have no common factor above 1.

In a strongly connected graph every walk from node 0 to a node `v` has the same length
modulo the period (the greatest common divisor of the cycle lengths), so with `level[v]`
the length of any one of them, the period divides `level[u] + 1 - level[v]` for every edge
`(u, v)`. And the gcd of that over the edges divides every cycle's length, the sum of it
around the cycle. So that gcd is the period; the edges of the walk's own tree give 0, and a
self-loop 1. `G` must be strongly connected and have a node.
"""
level = _levels(G)
rows, cols, _values = G._A.to_coo(values=False)
return int(np.gcd.reduce(level[rows] + 1 - level[cols])) == 1


def _levels(G):
"""Each node's depth in a breadth-first walk from node 0, which must reach every node.

A GraphBLAS round a level; a long thin walk, as around a cycle, goes to a walk in Python
instead, priced as `is_strongly_connected`'s walks are.
"""
A = _adjacency(G)
n = A.nrows
budget = _Budget(n + A.nvals)
level = _visited(Vector(np.int64, n, name="level"))
q = Vector(bool, n, name="q")
level[0] = 0
q[0] = True
depth = 0
budget.start()
while True:
q(~level.S, replace) << any_pair(q @ A)
if q.nvals == 0:
return level.to_dense()
if not budget.spend(_WALK_ROUND, q.nvals):
return _sequential_levels(A)
depth += 1
level(q.S) << depth


def _sequential_levels(A):
"""`_levels` by a queue in Python, for walks with many thin levels."""
indptr, indices, _values = A.to_csr()
indptr = indptr.tolist()
indices = indices.tolist()
level = [-1] * A.nrows
level[0] = 0
queue = [0]
for u in queue: # the queue grows as it is read
depth = level[u] + 1
for w in indices[indptr[u] : indptr[u + 1]]:
if level[w] < 0:
level[w] = depth
queue.append(w)
return np.array(level, np.int64)
14 changes: 14 additions & 0 deletions graphblas_algorithms/algorithms/hierarchy.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
from .components.strongly_connected import component_labels

__all__ = ["flow_hierarchy"]


def flow_hierarchy(G):
"""The values of `G`'s edges, as an array, and whether each lies on a cycle.

An edge lies on a cycle exactly when its ends are in one strongly connected component, as
a self-loop's are.
"""
labels = component_labels(G)
rows, cols, values = G._A.to_coo()
return values, labels[rows] == labels[cols]
8 changes: 8 additions & 0 deletions graphblas_algorithms/interface.py
Original file line number Diff line number Diff line change
Expand Up @@ -287,6 +287,9 @@ class Dispatcher:
is_semiconnected = mod.semiconnected.is_semiconnected
condensation = mod.strongly_connected.condensation
is_strongly_connected = mod.strongly_connected.is_strongly_connected
kosaraju_strongly_connected_components = (
mod.strongly_connected.kosaraju_strongly_connected_components
)
number_strongly_connected_components = (
mod.strongly_connected.number_strongly_connected_components
)
Expand Down Expand Up @@ -320,6 +323,7 @@ class Dispatcher:
# =============
ancestors = mod.ancestors
descendants = mod.descendants
is_aperiodic = mod.is_aperiodic

mod = nxapi.distance_measures
# ===========================
Expand All @@ -344,6 +348,10 @@ class Dispatcher:
# ====================
ego_graph = mod.ego.ego_graph

mod = nxapi.hierarchy
# ===================
flow_hierarchy = mod.flow_hierarchy

mod = nxapi.isolate
# =================
is_isolate = mod.is_isolate
Expand Down
1 change: 1 addition & 0 deletions graphblas_algorithms/nxapi/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
from .dominating import *
from .efficiency_measures import *
from .generators import *
from .hierarchy import *
from .isolate import *
from .isomorphism import fast_could_be_isomorphic, faster_could_be_isomorphic
from .linalg import *
Expand Down
21 changes: 21 additions & 0 deletions graphblas_algorithms/nxapi/components/strongly_connected.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@
__all__ = [
"condensation",
"is_strongly_connected",
"kosaraju_strongly_connected_components",
"number_strongly_connected_components",
"strongly_connected_components",
]
Expand All @@ -38,6 +39,26 @@ def strongly_connected_components(G):
yield from algorithms.strongly_connected_components(G)


def _no_source(bound):
if bound.get("source") is not None:
# NetworkX dev keeps the walk to the nodes that reach `source`; 3.7 and earlier step
# past them, so their sets depend on the order of the walk.
return (
"kosaraju_strongly_connected_components from a source differs between NetworkX "
"versions; networkx serves it"
)
return None


@can_run(_no_source)
@not_implemented_for("undirected")
def kosaraju_strongly_connected_components(G, source=None):
if (reason := _no_source({"source": source})) is not None:
raise NotImplementedError(reason)
G = to_directed_graph(G)
yield from algorithms.strongly_connected_components(G)


def _no_scc(bound):
if bound.get("scc") is not None:
return "condensation numbers its own components; networkx serves a given `scc`"
Expand Down
18 changes: 15 additions & 3 deletions graphblas_algorithms/nxapi/dag.py
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
from graphblas_algorithms import algorithms
from graphblas_algorithms.classes.digraph import to_graph
from graphblas_algorithms.classes.digraph import to_directed_graph, to_graph

from .exception import NetworkXError
from .exception import NetworkXError, NetworkXPointlessConcept

__all__ = ["ancestors", "descendants"]
__all__ = ["ancestors", "descendants", "is_aperiodic"]


def descendants(G, source):
Expand All @@ -24,3 +24,15 @@ def ancestors(G, source):
raise NetworkXError(*e.args) from e
else:
return G.vector_to_nodeset(result)


def is_aperiodic(G):
if not G.is_directed():
# NetworkX 3.6.1's words. Later versions refuse an undirected graph before dispatching.
raise NetworkXError("is_aperiodic not defined for undirected graphs")
G = to_directed_graph(G)
if len(G) == 0:
raise NetworkXPointlessConcept("Graph has no nodes.")
if not algorithms.is_strongly_connected(G):
raise NetworkXError("Graph is not strongly connected.")
return algorithms.is_aperiodic(G)
77 changes: 77 additions & 0 deletions graphblas_algorithms/nxapi/hierarchy.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,77 @@
import math

import numpy as np

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

from .exception import NetworkXError

__all__ = ["flow_hierarchy"]


def flow_hierarchy(G, weight=None):
"""1 less the share of the edges' weight that lies on cycles, as NetworkX finds it.

NetworkX sums each strongly connected component's subgraph size and divides by the graph's.
Integer weights, or none, give its value exactly: both sums are exact here, and so are
NetworkX's while they stay below 2**53, so both divide the same integers. Float weights of
one sign agree to within about `4 * m * 2**-53`, for `m` edges, the rounding of the sums.
"""
G = to_graph(G, weight=weight)
if G._A.nvals == 0:
raise NetworkXError("flow_hierarchy not applicable to empty graphs")
if not G.is_directed():
raise NetworkXError("G must be a digraph in flow_hierarchy")
reads_values = weight is not None and weight == G._weight
if reads_values and G._A.dtype.np_type.kind == "c":
raise NotImplementedError(
f"Edge attribute {weight!r} has complex values; networkx serves the call"
)
values, on_cycle = algorithms.flow_hierarchy(G)
if not reads_values:
# NetworkX's sizes are then ints, and so is its division's numerator.
return 1 - int(on_cycle.sum()) / len(values)
if values.dtype.kind == "f":
return _float_hierarchy(values, on_cycle)
total = _exact_sum(values)
if total == 0:
raise NotImplementedError(_ZERO)
return 1 - _exact_sum(values[on_cycle]) / total


_ZERO = (
"flow_hierarchy where the weights sum to 0: NetworkX raises ZeroDivisionError for Python "
"numbers and gives NaN for NumPy ones, which a conversion does not tell apart; networkx "
"serves it"
)


def _exact_sum(values):
"""The sum of integer (or bool) `values` as a Python int."""
if values.size == 0:
return 0
largest = max(abs(int(values.min())), abs(int(values.max())))
if largest * values.size < 2**63:
return int(values.sum(dtype=np.int64))
return sum(values.tolist())


def _float_hierarchy(values, on_cycle):
if np.isnan(values).any():
return math.nan # NetworkX's sums are NaN, and so is what it divides
if (values < 0).any() and (values > 0).any():
raise NotImplementedError(
"flow_hierarchy on float weights of both signs, whose sums can cancel to what "
"NetworkX's order of summation decides; networkx serves it"
)
finite = values[np.isfinite(values)]
if not float(np.abs(finite).sum()) < 2.0**1023:
# NetworkX sums each edge twice (once each way) before halving, and would overflow.
raise NotImplementedError(
"flow_hierarchy on weights whose sum is past half the float range; networkx serves it"
)
total = float(values.sum())
if total == 0:
raise NotImplementedError(_ZERO)
return 1 - float(values[on_cycle].sum()) / total
Loading
Loading