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
3 changes: 3 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -164,6 +164,7 @@ graphblas_algorithms.nxapi
│ │ └── is_partition
│ └── quality
│ ├── inter_community_edges
│ ├── inter_community_non_edges
│ ├── intra_community_edges
│ ├── modularity
│ ├── overlapping_modularity
Expand Down Expand Up @@ -247,6 +248,8 @@ graphblas_algorithms.nxapi
│ └── resource_allocation_index
├── lowest_common_ancestors
│ └── lowest_common_ancestor
├── moral
│ └── moral_graph
├── operators
│ ├── binary
│ │ ├── compose
Expand Down
5 changes: 5 additions & 0 deletions _nx_graphblas/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -91,6 +91,7 @@ def get_info():
"hyper_wiener_index",
"in_degree_centrality",
"inter_community_edges",
"inter_community_non_edges",
"intersection",
"intra_community_edges",
"is_arborescence",
Expand Down Expand Up @@ -126,6 +127,7 @@ def get_info():
"mixing_expansion",
"modularity",
"modularity_matrix",
"moral_graph",
"mutual_weight",
"negative_edge_cycle",
"node_boundary",
Expand Down Expand Up @@ -221,6 +223,8 @@ def get_info():
"harmonic_diameter": 'A precomputed `sp` 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".',
"hits": 'A graph with nodes and no edges gets 0.0 for every node, where NetworkX\'s power\niteration does not converge. `method="svd"` is left to NetworkX.',
"hyper_wiener_index": "Raises OverflowError rather than add integer weights where the number of nodes times the\nheaviest absolute weight reaches 2**62, or where the sum over one node's targets could\nreach 2**63.",
"inter_community_edges": "A `partition` given as a function, or as an iterator, is left to NetworkX.",
"inter_community_non_edges": "A `partition` given as a function, or as an iterator, is left to NetworkX.",
"k_core": "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_corona": "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_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.",
Expand All @@ -231,6 +235,7 @@ def get_info():
"maximum_spanning_tree": 'Where weights tie, the forest may differ from NetworkX\'s whichever `algorithm` is named;\nits total weight is the same. Equal weights are taken by their ends in node order, on\nevery platform; Kruskal takes them in `G.edges()` order, so its forest is the same where\neach node\'s neighbors were added in node order. Left to NetworkX: an int past 2**53 held\nas a float that ties another weight, complex weights, an infinite weight with Boruvka\n(which leaves such an edge out), and a NaN self-loop with `algorithm="prim"`.\nAlso left to NetworkX: a graph whose edges carry more than one attribute, or the weight\non some edges only, and one of fewer than 800000 edges, where NetworkX is faster.',
"minimum_spanning_edges": 'Where weights tie, the forest may differ from NetworkX\'s whichever `algorithm` is named;\nits total weight is the same. Equal weights are taken by their ends in node order, on\nevery platform; Kruskal takes them in `G.edges()` order, so its forest is the same where\neach node\'s neighbors were added in node order. Left to NetworkX: an int past 2**53 held\nas a float that ties another weight, complex weights, an infinite weight with Boruvka\n(which leaves such an edge out), and a NaN self-loop with `algorithm="prim"`.\nThe edges come lightest first (heaviest first for the maximum), and a NaN weight raises\nwhen they are first asked for, naming one NaN edge. With `data=True`, also left to\nNetworkX: a graph whose edges carry more than one attribute, or the weight on some edges\nonly, and one of fewer than 800000 edges (200000 with `data=False`), where NetworkX is\nfaster.',
"minimum_spanning_tree": 'Where weights tie, the forest may differ from NetworkX\'s whichever `algorithm` is named;\nits total weight is the same. Equal weights are taken by their ends in node order, on\nevery platform; Kruskal takes them in `G.edges()` order, so its forest is the same where\neach node\'s neighbors were added in node order. Left to NetworkX: an int past 2**53 held\nas a float that ties another weight, complex weights, an infinite weight with Boruvka\n(which leaves such an edge out), and a NaN self-loop with `algorithm="prim"`.\nAlso left to NetworkX: a graph whose edges carry more than one attribute, or the weight\non some edges only, and one of fewer than 800000 edges, where NetworkX is faster.',
"moral_graph": "Built from the NetworkX graph given, as NetworkX builds it, so it keeps that graph's\ndata; most of the time goes to building it. A graph of this backend's own, or a\nconversion that was copied or unpickled, is left to NetworkX, as is a graph with fewer\nthan 5 pairs of parents (two predecessors of one node) for each edge, where NetworkX\nis faster.",
"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.',
"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".\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
11 changes: 11 additions & 0 deletions _nx_graphblas/core.py
Original file line number Diff line number Diff line change
Expand Up @@ -118,6 +118,8 @@
"faster."
)

_PARTITION_READ = "A `partition` given as a function, or as an iterator, is left to NetworkX."

# Prose NetworkX shows under a function's documentation, for behaviour its docstring does not
# describe.
_ADDITIONAL_DOCS = {
Expand Down Expand Up @@ -182,6 +184,8 @@
'iteration does not converge. `method="svd"` is left to NetworkX.'
),
"hyper_wiener_index": _LENGTH_SUM_OVERFLOW,
"inter_community_edges": _PARTITION_READ,
"inter_community_non_edges": _PARTITION_READ,
"k_core": _CORE_SUBGRAPH,
"k_corona": _CORE_SUBGRAPH,
"k_crust": _CORE_SUBGRAPH,
Expand All @@ -195,6 +199,13 @@
"maximum_spanning_tree": _SPANNING + "\n" + _SPANNING_DATA,
"minimum_spanning_edges": _SPANNING + "\n" + _SPANNING_EDGES,
"minimum_spanning_tree": _SPANNING + "\n" + _SPANNING_DATA,
"moral_graph": (
"Built from the NetworkX graph given, as NetworkX builds it, so it keeps that graph's\n"
"data; most of the time goes to building it. A graph of this backend's own, or a\n"
"conversion that was copied or unpickled, is left to NetworkX, as is a graph with fewer\n"
"than 5 pairs of parents (two predecessors of one node) for each edge, where NetworkX\n"
"is faster."
),
"negative_edge_cycle": _PATH_OVERFLOW,
"periphery": _ECCENTRICITY_BOUNDS,
"radius": _ECCENTRICITY_BOUNDS,
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 @@ -15,6 +15,7 @@
from .link_analysis import *
from .link_prediction import *
from .lowest_common_ancestors import *
from .moral import *
from .operators import *
from .reciprocity import *
from .regular import *
Expand Down
23 changes: 23 additions & 0 deletions graphblas_algorithms/algorithms/community/quality.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@

__all__ = [
"inter_community_edges",
"inter_community_non_edges",
"intra_community_edges",
"modularity",
"overlapping_modularity",
Expand Down Expand Up @@ -40,6 +41,28 @@ def inter_community_edges(G, partition):
return count


def inter_community_non_edges(G, S):
"""The pairs of nodes in different blocks of a partition that `G` does not join.

`S` is node by block, with a 1 for each node in its block; a node no block holds is not
counted. Ordered pairs in a directed graph, unordered in an undirected one.
"""
A = G._A
sizes = S.reduce_columnwise(monoid.plus).new()
held = int(sizes.reduce(monoid.plus).get(0))
across = held * held - int(sizes.ewise_mult(sizes, binary.times).reduce(monoid.plus).get(0))
# Each node's neighbors in each block. A held node's neighbors in other blocks are its
# edges across, and a self-loop is counted in both sums.
T = plus_pair(A @ S).new()
held_nodes = S.reduce_rowwise(monoid.any).new()
reached = int(T.reduce_rowwise(monoid.plus).new(mask=held_nodes.S).reduce(monoid.plus).get(0))
inside = int(T.dup(mask=S.S).reduce_scalar(monoid.plus).get(0))
count = across - (reached - inside)
if not G.is_directed():
count //= 2 # an edge is stored at both ends and a pair counted from both
return count


def _inside(A, S, weighted):
"""The values of `A` between members of one community, each weighed by `S` at both ends.

Expand Down
36 changes: 36 additions & 0 deletions graphblas_algorithms/algorithms/moral.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
from graphblas import Matrix, binary, select
from graphblas.semiring import any_pair

from graphblas_algorithms import Graph

__all__ = ["co_parents", "moral_graph"]


def co_parents(G):
"""The pairs of nodes that share a child and that `G` does not join, either way.

A Matrix of the node ids, each pair once as `(i, j)` with `i < j`. A child's parents are
its column of `A`, so `A @ A.T` pairs them; the mask leaves out the pairs `A` already
joins, and a node's pair with itself.
"""
A = G._A
AT = G.get_property("AT")
joined = Matrix(bool, A.nrows, A.ncols)
joined(A.S) << True
joined(AT.S) << True
pairs = any_pair[bool](A @ AT).new(mask=~joined.S)
return select.triu(pairs, 1).new()


def moral_graph(G):
"""`G` without directions, with each pair of nodes that share a child joined.

An undirected graph of the structure alone: its values are all True, and name no attribute.
"""
A = G._A
pairs = co_parents(G)
M = Matrix(bool, A.nrows, A.ncols)
for edges in (A, G.get_property("AT"), pairs):
M(edges.S) << True
M(binary.any) << pairs.T
return Graph(M, key_to_id=G._key_to_id, weight=None)
9 changes: 7 additions & 2 deletions graphblas_algorithms/interface.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@

# Graph-returning names whose result is built from the NetworkX graph a conversion came from,
# so that it keeps that graph's own data, nodes' included; the matrix gives only the weights.
_BUILT_FROM_SOURCE = frozenset({"maximum_spanning_tree", "minimum_spanning_tree"})
_BUILT_FROM_SOURCE = frozenset({"maximum_spanning_tree", "minimum_spanning_tree", "moral_graph"})


@functools.cache
Expand Down Expand Up @@ -56,7 +56,7 @@ def _declared(name):
if name == "ego_graph":
# It keeps every edge attribute, so it declares none, yet `distance` names one.
attribute_parameters = ("distance",)
elif name in _BUILT_FROM_SOURCE:
elif name in {"maximum_spanning_tree", "minimum_spanning_tree"}:
attribute_parameters = ("weight",) # the same: they keep every attribute, read one
# NetworkX before 3.7 declares no preserve flags for `reverse`, whose result keeps its data.
rebuilds_input = (
Expand Down Expand Up @@ -282,6 +282,7 @@ class Dispatcher:
is_cover = mod.community_utils.is_cover
is_partition = mod.community_utils.is_partition
inter_community_edges = mod.quality.inter_community_edges
inter_community_non_edges = mod.quality.inter_community_non_edges
intra_community_edges = mod.quality.intra_community_edges
modularity = mod.quality.modularity
overlapping_modularity = mod.quality.overlapping_modularity
Expand Down Expand Up @@ -384,6 +385,10 @@ class Dispatcher:
# =================================
lowest_common_ancestor = mod.lowest_common_ancestor

mod = nxapi.moral
# ===============
moral_graph = mod.moral_graph

mod = nxapi.operators
# ===================
compose = mod.binary.compose
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 @@ -16,6 +16,7 @@
from .link_analysis import *
from .link_prediction import *
from .lowest_common_ancestors import *
from .moral import *
from .operators import *
from .reciprocity import *
from .regular import *
Expand Down
52 changes: 44 additions & 8 deletions graphblas_algorithms/nxapi/community/quality.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,10 @@
from collections.abc import Iterator

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

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

# is_cover and is_partition are found here too, as in NetworkX
Expand All @@ -16,20 +19,53 @@ def intra_community_edges(G, partition):
return algorithms.intra_community_edges(G, partition)


def inter_community_edges(G, partition):
G = to_graph(G)
# NetworkX counts on the graph restricted to the union of the blocks, which must then be
# split exactly: no node twice, and none the graph does not have
def _blocks_as_read(bound):
"""Leave to NetworkX a `partition` that its `quotient_graph` reads as no list of blocks.

A function is an equivalence relation, whose classes NetworkX finds. An iterator is read
twice there, once to find the nodes and once to check them, so the second reading finds
it empty, and NetworkX raises for nearly any graph.
"""
partition = bound["partition"]
if callable(partition):
return "A `partition` given as a relation is left to NetworkX; networkx serves it"
if isinstance(partition, Iterator):
return "NetworkX reads `partition` twice, and an iterator once; networkx serves it"
return None


def _blocks(G, partition):
"""The blocks of `partition`, as NetworkX's `quotient_graph` reads them.

A dict's blocks are its values. NetworkX counts on the graph restricted to the union of
the blocks, which must then be split exactly: no node twice, and none the graph does not
have. Its check is followed step by step, as it reads each block twice and takes the
blocks' lengths last, so a block that is a generator fails where it fails there.
"""
if isinstance(partition, dict):
partition = partition.values()
partition = list(partition)
covered = set().union(*partition)
if sum(len(block) for block in partition) != len(covered) or any(
node not in G for node in covered
):
size = len(G) if len(covered) == len(G) else sum(node in G for node in covered)
named = {node for block in partition for node in block if node in G}
if not size == len(named) == sum(len(block) for block in partition):
raise NetworkXException("each node must be in exactly one part of `partition`")
partition = [G.set_to_vector(block) for block in partition]
return partition


@can_run(_blocks_as_read)
def inter_community_edges(G, partition):
G = to_graph(G)
partition = [G.set_to_vector(block) for block in _blocks(G, partition)]
return algorithms.inter_community_edges(G, partition)


@can_run(_blocks_as_read)
def inter_community_non_edges(G, partition):
G = to_graph(G)
return algorithms.inter_community_non_edges(G, _memberships(G, _blocks(G, partition)))


def _not_a_partition(G, communities):
try:
from networkx.algorithms.community.quality import NotAPartition
Expand Down
85 changes: 85 additions & 0 deletions graphblas_algorithms/nxapi/moral.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,85 @@
import numpy as np

from graphblas_algorithms import algorithms
from graphblas_algorithms.classes._utils import source_of
from graphblas_algorithms.classes.digraph import to_directed_graph
from graphblas_algorithms.utils import not_implemented_for

from ._utils import should_run

__all__ = ["moral_graph"]

# Below this many pairs of parents (two predecessors of one node) for each edge, NetworkX's loop
# over the pairs costs less than converting the graph does; the two cross between 4 and 5 on
# random graphs of 1e4 to 6e5 edges (Indicative).
_FEWEST_PARENT_PAIRS_PER_EDGE = 5


def _decline(reason):
raise NotImplementedError(f"{reason}; networkx serves it")


def _few_parent_pairs(bound):
pred = getattr(bound["G"], "_pred", None)
if pred is None:
return None
# NetworkX's loop takes every pair of each node's predecessors, as here.
indegree = np.fromiter(map(len, pred.values()), np.int64)
pairs = int((indegree * (indegree - 1) // 2).sum())
if pairs < _FEWEST_PARENT_PAIRS_PER_EDGE * int(indegree.sum()):
return (
f"networkx is faster below {_FEWEST_PARENT_PAIRS_PER_EDGE} pairs of parents for each "
"edge, with no conversion to pay"
)
return None


def _join(adj, rows, cols, data, id_to_key):
"""Give each node `rows[k]` the neighbor `cols[k]` with the data dict `data[k]`.

`rows` is sorted, so each node's new neighbors go in with one `dict.update`.
"""
nbrs = [id_to_key[col] for col in cols.tolist()]
bounds = np.append(np.flatnonzero(np.diff(rows, prepend=-1)), len(rows)).tolist()
starts = bounds[:-1]
for row, start, stop in zip(rows[starts].tolist(), starts, bounds[1:], strict=True):
adj[id_to_key[row]].update(zip(nbrs[start:stop], data[start:stop], strict=True))


@should_run(_few_parent_pairs)
@not_implemented_for("undirected")
def moral_graph(G):
import networkx as nx

if G.is_multigraph():
_decline("graphblas-algorithms does not support multigraphs")
# NetworkX's answer is its graph's `to_undirected()`, which copies the graph's, nodes' and
# edges' data, with the pairs that share a child joined where they were not. The matrix
# holds none of that data, so the answer starts from the NetworkX graph itself: a direct
# call's, or the one the conversion was made from.
source = G if isinstance(G, nx.Graph) else source_of(G)
if source is None:
_decline(
"The moral graph carries the data of the NetworkX graph it is taken from, and this "
"graph was not converted from one that is still alive"
)
G = to_directed_graph(G)
rows, cols, _ = algorithms.co_parents(G).to_coo(values=False)
H = source.to_undirected()
if type(H) is not nx.Graph:
# A subclass may build its edges its own way, so it is asked to.
id_to_key = G.id_to_key
us = [id_to_key[row] for row in rows.tolist()]
H.add_edges_from(zip(us, [id_to_key[col] for col in cols.tolist()], strict=True))
return H
# As `add_edges_from` joins them: an empty dict for each new edge, the same in both
# directions. Each node is reached in both passes, as a row in one of them.
data = [{} for _ in range(len(rows))]
order = np.argsort(cols, kind="stable") # by column, and by row within one
try:
_join(H._adj, rows, cols, data, G.id_to_key)
_join(H._adj, cols[order], rows[order], [data[k] for k in order.tolist()], G.id_to_key)
except KeyError:
# A view's conversion is not dropped when a node leaves the graph under it.
_decline("The graph has changed since it was converted")
return H
Loading
Loading