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
7 changes: 6 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -128,14 +128,19 @@ graphblas_algorithms.nxapi
│ ├── connectivity
│ │ └── average_degree_connectivity
│ ├── correlation
│ │ ├── attribute_assortativity_coefficient
│ │ ├── degree_assortativity_coefficient
│ │ └── degree_pearson_correlation_coefficient
│ │ ├── degree_pearson_correlation_coefficient
│ │ └── numeric_assortativity_coefficient
│ ├── mixing
│ │ ├── attribute_mixing_dict
│ │ ├── attribute_mixing_matrix
│ │ ├── degree_mixing_dict
│ │ └── degree_mixing_matrix
│ ├── neighbor_degree
│ │ └── average_neighbor_degree
│ └── pairs
│ ├── node_attribute_xy
│ └── node_degree_xy
├── boundary
│ ├── edge_boundary
Expand Down
10 changes: 10 additions & 0 deletions _nx_graphblas/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,9 @@ def get_info():
"all_pairs_bellman_ford_path_length",
"all_pairs_shortest_path_length",
"ancestors",
"attribute_assortativity_coefficient",
"attribute_mixing_dict",
"attribute_mixing_matrix",
"average_clustering",
"average_degree_connectivity",
"average_neighbor_degree",
Expand Down Expand Up @@ -130,6 +133,7 @@ def get_info():
"modularity_matrix",
"mutual_weight",
"negative_edge_cycle",
"node_attribute_xy",
"node_boundary",
"node_connected_component",
"node_degree_xy",
Expand All @@ -139,6 +143,7 @@ def get_info():
"number_connected_components",
"number_of_isolates",
"number_weakly_connected_components",
"numeric_assortativity_coefficient",
"onion_layers",
"out_degree_centrality",
"overall_reciprocity",
Expand Down Expand Up @@ -198,6 +203,9 @@ def get_info():
_additional_docs = {
# BEGIN: additional_docs
"all_pairs_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.",
"attribute_assortativity_coefficient": "Taken from the counted value pairs in float64; within rounding of NetworkX's.\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.",
"attribute_mixing_dict": "The keys come in another order than NetworkX's, which follows each node's adjacency.\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.",
"attribute_mixing_matrix": "Without `mapping`, NetworkX's numbering of the values is arbitrary; here they are\nnumbered in the order nodes first hold them, None for a missing value last.\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.",
"average_degree_connectivity": "Complex weights are left to NetworkX. Float weights are added in another order than\nNetworkX's, so a value may differ from NetworkX's in its last bits. Integer weights are\nleft to NetworkX where a node's weighted degree, or its sum of each weight times the\nneighbor's degree, could reach 2**63 (by the sum of the absolute values it adds).\nWith `weight`, an iterator `nodes` is left to NetworkX.",
"average_neighbor_degree": "`nodes` one node, which raises in NetworkX, is left to it.\nComplex weights are left to NetworkX. Float weights are added in another order than\nNetworkX's, so a value may differ from NetworkX's in its last bits. Integer weights are\nleft to NetworkX where a node's weighted degree, or its sum of each weight times the\nneighbor's degree, could reach 2**63 (by the sum of the absolute values it adds).",
"average_shortest_path_length": 'A `method` other than None, "unweighted", "dijkstra" and "bellman-ford" is left to\nNetworkX. Lengths are Bellman-Ford\'s, with `method="dijkstra"` too, so a negative edge\nwithout a negative cycle is answered where NetworkX\'s Dijkstra raises\n"Contradictory paths found".',
Expand Down Expand Up @@ -237,7 +245,9 @@ def get_info():
"k_truss": "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.",
"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": "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.",
"node_attribute_xy": "The pairs come edge by edge as the matrix stores them, not along each node's\nadjacency as in NetworkX.\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.",
"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.',
"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.",
Expand Down
31 changes: 31 additions & 0 deletions _nx_graphblas/core.py
Original file line number Diff line number Diff line change
Expand Up @@ -125,6 +125,13 @@
"degree may differ from NetworkX's in its last bits.\n" + _DEGREE_OVERFLOW
)

_NODE_ATTRIBUTE = (
"The values are read from the graph as NetworkX's mixing reads them, a node without the\n"
"attribute as None, and values a dict takes as one key are one value. Left to NetworkX:\n"
"a graph class with its own `adjacency` or `nodes`, an `attribute` that is None,\n"
"callable or unhashable, and values no dict can key."
)

# Prose NetworkX shows under a function's documentation, for behaviour its docstring does not
# describe.
_ADDITIONAL_DOCS = {
Expand All @@ -135,6 +142,19 @@
"without a negative cycle is answered where NetworkX's Dijkstra raises\n"
'"Contradictory paths found".'
),
"attribute_assortativity_coefficient": (
"Taken from the counted value pairs in float64; within rounding of NetworkX's.\n"
+ _NODE_ATTRIBUTE
),
"attribute_mixing_dict": (
"The keys come in another order than NetworkX's, which follows each node's adjacency.\n"
+ _NODE_ATTRIBUTE
),
"attribute_mixing_matrix": (
"Without `mapping`, NetworkX's numbering of the values is arbitrary; here they are\n"
"numbered in the order nodes first hold them, None for a missing value last.\n"
+ _NODE_ATTRIBUTE
),
"average_degree_connectivity": _NEIGHBOR_DEGREE_WEIGHTS
+ "\nWith `weight`, an iterator `nodes` is left to NetworkX.",
"average_neighbor_degree": "`nodes` one node, which raises in NetworkX, is left to it.\n"
Expand Down Expand Up @@ -227,12 +247,23 @@
"memory stays bounded."
),
"negative_edge_cycle": _PATH_OVERFLOW,
"node_attribute_xy": (
"The pairs come edge by edge as the matrix stores them, not along each node's\n"
"adjacency as in NetworkX.\n" + _NODE_ATTRIBUTE
),
"node_degree_xy": (
"The pairs come by edge, both ends in node order, not in NetworkX's adjacency order.\n"
"NetworkX's own `degree_mixing_dict` takes these degrees as keys.\n"
+ _DEGREE_TYPES
+ _DEGREES_AS_KEYS
),
"numeric_assortativity_coefficient": (
"The Pearson correlation of the pairs in float64, within rounding of NetworkX's. Where\n"
"NetworkX squares ints past about 3e9 in int64, which wraps, this gives the true\n"
"coefficient. Values that are not real numbers, an iterator `nodes`, which NetworkX\n"
"reads twice, and a node in `nodes` that is not in the graph are left to NetworkX; a\n"
"node without the attribute raises KeyError, as there.\n" + _NODE_ATTRIBUTE
),
"periphery": _ECCENTRICITY_BOUNDS,
"radius": _ECCENTRICITY_BOUNDS,
"schultz_index": 'A graph with a node named "weight" is left to NetworkX.\n'
Expand Down
36 changes: 30 additions & 6 deletions graphblas_algorithms/algorithms/assortativity/mixing.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
from ..exceptions import IntegerOverflowError

__all__ = [
"attribute_mixing_counts",
"check_int_sums",
"degree_mixing_counts",
"degree_pairs",
Expand Down Expand Up @@ -163,13 +164,36 @@ def degree_mixing_counts(G, xdeg, ydeg, ids=None):
if k == 0:
return values, Matrix(dtypes.INT64, 0, 0)
xcodes, ycodes = codes[: ids.size], codes[ids.size :]
Px = Matrix.from_coo(ids, xcodes, 1, dtype=dtypes.INT64, nrows=n, ncols=k)
Py = Matrix.from_coo(ids, ycodes, 1, dtype=dtypes.INT64, nrows=n, ncols=k)
# B[u, j]: the neighbors v of u in `ids` whose y-degree is values[j]. The rows of Px are
# the nodes in `ids`, so the second product keeps only edges that start there.
return values, _pair_counts(G, ids, xcodes, ids, ycodes, k)


def _pair_counts(G, xids, xcodes, yids, ycodes, k):
"""A k x k Matrix counting `(xcodes[u], ycodes[v])` over the stored edges `(u, v)`.

Only edges from a node in `xids` to a node in `yids` count; the codes are given by
position in those arrays.
"""
n = len(G)
Px = Matrix.from_coo(xids, xcodes, 1, dtype=dtypes.INT64, nrows=n, ncols=k)
Py = Matrix.from_coo(yids, ycodes, 1, dtype=dtypes.INT64, nrows=n, ncols=k)
# B[u, j]: the neighbors v of u in `yids` with code j. The rows of Px are the nodes in
# `xids`, so the second product keeps only edges that start there.
B = plus_pair[dtypes.INT64](G._A @ Py).new()
C = plus_second[dtypes.INT64](Px.T @ B).new()
return values, C
return plus_second[dtypes.INT64](Px.T @ B).new()


def attribute_mixing_counts(G, codes, k, ids=None):
"""Count the pairs `(codes[u], codes[v])` over the stored edges `(u, v)` with `u` in `ids`.

`codes` gives each node, by id, a code below `k`. Only an edge's first end must be in `ids`
(every node when None), as NetworkX's `node_attribute_xy` keeps them; an undirected edge is
stored both ways and a self-loop once, as it yields them. Returns a k x k Matrix of counts,
the code of the first end by row.
"""
every = np.arange(len(G), dtype=np.int64)
if ids is None:
ids = every
return _pair_counts(G, ids, codes[ids], every, codes, k)


def degree_pairs(G, xdeg, ydeg, ids=None):
Expand Down
76 changes: 76 additions & 0 deletions graphblas_algorithms/classes/_node_attributes.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,76 @@
"""What a graph converted from NetworkX carries for a name that reads a node attribute.

NetworkX's attribute mixing keys its counts by the values of a node attribute, and which
values are equal decides them. A matrix holds numbers, so a conversion for such a name carries
the values, read once from the NetworkX graph and numbered as a dict keys them.
"""

from collections import namedtuple
from itertools import chain

import numpy as np
from graphblas import Matrix, Vector, dtypes

__all__ = ["NodeAttribute", "from_networkx_adjacency", "read_node_attribute"]


class _Missing:
"""The value of a node that lacks the attribute."""

__slots__ = ()

def __repr__(self):
return "MISSING"


MISSING = _Missing()

# `codes`: a Vector with an entry for each node that has the attribute, the id of its value.
# `values`: the distinct values by id, as the first node in node order holding each holds it;
# two values are one when a dict takes them as one key (1, 1.0 and True; one NaN object).
# `objects`: each node's value as that node holds it, by node id, MISSING where it has none.
# `index`: the id of each value, as a dict looks it up.
NodeAttribute = namedtuple("NodeAttribute", ["codes", "values", "objects", "index"])


def from_networkx_adjacency(graph, key_to_id):
"""The structural matrix of `graph`, or None when it has no edges.

The matrix is the one `from_networkx(graph)` builds, read in one pass over `graph._adj`
rather than through scipy. With no edges, `from_networkx` gives a float matrix of no
entries.
"""
adj = graph._adj
n = len(key_to_id)
if len(adj) != n:
raise ValueError(f"the graph has {n} nodes but {len(adj)} adjacency rows")
dtype = np.int32 if n < 2**31 else np.int64
nbrs = list(adj.values())
lengths = np.fromiter(map(len, nbrs), np.int64, n)
count = int(lengths.sum())
rows = np.fromiter(map(key_to_id.__getitem__, adj), dtype, n)
neighbors = np.fromiter(map(key_to_id.__getitem__, chain.from_iterable(nbrs)), dtype, count)
if count == 0:
return None
return Matrix.from_coo(
np.repeat(rows, lengths), neighbors, 1, dtype=dtypes.INT64, nrows=n, ncols=n
)


def read_node_attribute(graph, attribute, n):
"""`attribute` of each node of `graph`, numbered as NetworkX's dicts would key it.

Raises TypeError for a value no dict can key (a list), as NetworkX's mixing raises.
"""
objects = [datadict.get(attribute, MISSING) for datadict in graph._node.values()]
if len(objects) != n:
raise ValueError(f"the graph has {n} nodes but {len(objects)} node data dicts")
index = {}
codes = np.fromiter(
(-1 if value is MISSING else index.setdefault(value, len(index)) for value in objects),
np.int64,
n,
)
present = np.flatnonzero(codes >= 0)
vector = Vector.from_coo(present, codes[present], dtype=dtypes.INT64, size=n)
return NodeAttribute(vector, list(index), objects, index)
2 changes: 2 additions & 0 deletions graphblas_algorithms/classes/digraph.py
Original file line number Diff line number Diff line change
Expand Up @@ -534,6 +534,8 @@ def __init__(self, incoming_graph_data=None, *, key_to_id=None, weight=None, **a
self._key_to_id = key_to_id
self._id_to_key = None
self._cache = {}
# What a conversion for a name that reads node attributes carries (`interface`).
self._node_attributes = {}

# Graphblas-specific methods
from_networkx = classmethod(_utils.from_networkx)
Expand Down
2 changes: 2 additions & 0 deletions graphblas_algorithms/classes/graph.py
Original file line number Diff line number Diff line change
Expand Up @@ -384,6 +384,8 @@ def __init__(self, incoming_graph_data=None, *, key_to_id=None, weight=None, **a
self._key_to_id = key_to_id
self._id_to_key = None
self._cache = {}
# What a conversion for a name that reads node attributes carries (`interface`).
self._node_attributes = {}

# Graphblas-specific methods
from_networkx = classmethod(_utils.from_networkx)
Expand Down
Loading
Loading