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
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -197,6 +197,7 @@ graphblas_algorithms.nxapi
│ └── volume
├── dag
│ ├── ancestors
│ ├── dag_longest_path
│ ├── dag_longest_path_length
│ ├── descendants
│ ├── has_cycle
Expand Down
4 changes: 3 additions & 1 deletion _nx_graphblas/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,7 @@ def get_info():
"connected_components",
"core_number",
"cut_size",
"dag_longest_path",
"dag_longest_path_length",
"degree_centrality",
"descendants",
Expand Down Expand Up @@ -208,7 +209,8 @@ def get_info():
"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.",
"dag_longest_path_length": "A graph whose class has its own `neighbors`, `successors`, `predecessors`, `in_degree`,\n`adjacency` or `__getitem__` is left to NetworkX, which reads its edges through them.",
"dag_longest_path": "Where several paths are longest, the one given may differ from NetworkX's. Given a\n`topo_order` that is a topological order of every node once, it is NetworkX's; any\nother `topo_order`, or one that can be read only once, is left to NetworkX, as are NaN\nor infinite weights and float weights of 2**53 or more.\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.\nA graph whose class has its own `neighbors`, `successors`, `predecessors`, `in_degree`,\n`adjacency` or `__getitem__` is left to NetworkX, which reads its edges through them.",
"dag_longest_path_length": "Where several paths are longest and the weights are ints on some edges and floats on\nothers (a float `default_weight` counts), the length is that of the path this backend\nfinds, so it may be an int where NetworkX's is a float of the same value, or the\nreverse. NaN or infinite weights, and float weights of 2**53 or more, are left to\nNetworkX.\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.\nA graph whose class has its own `neighbors`, `successors`, `predecessors`, `in_degree`,\n`adjacency` or `__getitem__` is left to NetworkX, which reads its edges through them.",
"diameter": '`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.',
"disjoint_union": "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.",
"eccentricity": 'A precomputed `sp`, and the null graph, are 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
17 changes: 16 additions & 1 deletion _nx_graphblas/core.py
Original file line number Diff line number Diff line change
Expand Up @@ -132,7 +132,22 @@
"An `alpha` other than a Python int or float, unless it equals 1, is left to NetworkX."
),
"cut_size": _SUM_OVERFLOW + ".",
"dag_longest_path_length": _OWN_EDGE_READERS,
"dag_longest_path": (
"Where several paths are longest, the one given may differ from NetworkX's. Given a\n"
"`topo_order` that is a topological order of every node once, it is NetworkX's; any\n"
"other `topo_order`, or one that can be read only once, is left to NetworkX, as are NaN\n"
"or infinite weights and float weights of 2**53 or more.\n"
+ _PATH_OVERFLOW
+ "\n"
+ _OWN_EDGE_READERS
),
"dag_longest_path_length": (
"Where several paths are longest and the weights are ints on some edges and floats on\n"
"others (a float `default_weight` counts), the length is that of the path this backend\n"
"finds, so it may be an int where NetworkX's is a float of the same value, or the\n"
"reverse. NaN or infinite weights, and float weights of 2**53 or more, are left to\n"
"NetworkX.\n" + _PATH_OVERFLOW + "\n" + _OWN_EDGE_READERS
),
"diameter": _ECCENTRICITY_BOUNDS,
"eccentricity": "A precomputed `sp`, and the null graph, are left to NetworkX.\n"
+ _NEGATIVE_EDGES
Expand Down
120 changes: 118 additions & 2 deletions graphblas_algorithms/algorithms/dag.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,10 @@
"ancestors",
"dag_longest_path_length",
"descendants",
"generations",
"is_acyclic",
"longest_path",
"longest_path_lengths",
]


Expand Down Expand Up @@ -106,11 +109,12 @@ def run(self):
count += self._python_rounds()
return count

def _python_rounds(self):
def _python_rounds(self, walked=None):
"""Python rounds from `current` while the frontier stays small; the number of rounds.

One loop for every round, as `advance` would run them one call at a time: a path of n
nodes is n rounds, and a call per round costs more than the round.
nodes is n rounds, and a call per round costs more than the round. Each round's list
is appended to `walked` when it is given.
"""
indptr, indices, indegree, out = self._lists
back = max(_FEW_EDGES, self._n // 16)
Expand All @@ -119,6 +123,8 @@ def _python_rounds(self):
while this and sum(map(out.__getitem__, this)) < back:
count += 1
self.peeled += len(this)
if walked is not None:
walked.append(this)
nxt = []
for u in this:
for v in indices[indptr[u] : indptr[u + 1]]:
Expand Down Expand Up @@ -174,3 +180,113 @@ def dag_longest_path_length(G):
if peel.peeled < len(G):
return None
return max(count - 1, 0)


def generations(G):
"""Every generation's ids, first to last, or None if `G` has a cycle.

A generation is an array, or a list where it was walked in Python. The answer to
`is_acyclic` is cached on the way.
"""
peel = Generations(G)
rv = []
while len(peel.current):
rv.append(peel.advance())
if peel._python:
peel._python_rounds(rv)
G._cache["is_acyclic"] = acyclic = peel.peeled == len(G)
return rv if acyclic else None


def longest_path_lengths(G, generations, np_type, uniform=None):
"""Each node's length in NetworkX's `dag_longest_path`, and `G`'s in-edges it was found from.

NetworkX gives a node the heaviest of its predecessors' lengths plus the edge's weight, or
0 when it has no predecessor or that is negative: the path starts there. A node's
predecessors are all in earlier generations, so each generation takes the most of its
in-edges' sums at once. The weights are `G`'s values as `np_type` (int64 or float64), or
`uniform` on every edge. The value, never the order, of a sum is NetworkX's: each is one
addition of two numbers it also adds, and the most of equal numbers is that number.

A generation with few in-edges runs in Python on lists, as `Generations` walks its small
rounds, so a deep graph costs a few hundred nanoseconds a node, not a NumPy call or more.
Returns the lengths and the in-edges (`indptr`, `sources`, `weights`, by target).
"""
A = G._A
n = A.nrows
indptr, sources, weights = A.to_csc()
indptr = indptr.astype(np.int64)
sources = sources.astype(np.int64)
if uniform is None:
weights = weights.astype(np_type)
else:
weights = np.full(len(sources), uniform, np_type)
indegree = np.diff(indptr)
dist = np.zeros(n, np_type)
zero = np_type(0).item()
back = max(_FEW_EDGES, n // 16)
lists = d = None
python = False
for this in generations[1:]: # the first are the sources, of length 0
if python:
if not isinstance(this, list):
this = this.tolist()
edges = sum(map(lists[3].__getitem__, this))
if edges >= back:
dist = np.array(d, np_type)
python = False
this = np.array(this, np.int64)
else:
this = np.asarray(this, np.int64)
edges = int(indegree[this].sum())
if edges < _FEW_EDGES:
if lists is None:
lists = (indptr.tolist(), sources.tolist(), weights.tolist(), indegree.tolist())
d = dist.tolist()
python = True
this = this.tolist()
if python:
ptr, src, wts, _ = lists
for v in this:
a, b = ptr[v], ptr[v + 1]
if b - a == 1: # most nodes of a deep graph: no list to build
best = d[src[a]] + wts[a]
else:
best = max([d[u] + w for u, w in zip(src[a:b], wts[a:b], strict=True)])
d[v] = best if best >= 0 else zero
else:
# Every node after the first generation has an in-edge, so no segment is empty.
counts = indegree[this]
offsets = np.cumsum(counts) - counts
at = np.arange(edges) + np.repeat(indptr[this] - offsets, counts)
best = np.maximum.reduceat(dist[sources[at]] + weights[at], offsets)
best[best < 0] = 0
dist[this] = best
if python:
dist = np.array(d, np_type)
return dist, (indptr, sources, weights)


def longest_path(dist, in_edges):
"""The ids of a longest path, first to last, from `longest_path_lengths`'s answer.

It ends at the first node of the greatest length and steps back along an in-edge whose sum
is the node's length, until a node of length 0, where it starts. Its weights then add up,
in order, to the greatest length; where several paths do, which one is this backend's own.
"""
end = int(np.argmax(dist))
if not dist[end]:
return [end]
indptr, sources, weights = in_edges
targets = np.repeat(np.arange(len(dist)), np.diff(indptr))
length = dist[targets]
tight = (dist[sources] + weights == length) & (length != 0)
pred = np.full(len(dist), -1, np.int64)
pred[targets[tight]] = sources[tight]
path = [end]
v = end
while dist[v]:
v = int(pred[v])
path.append(v)
path.reverse()
return path
1 change: 1 addition & 0 deletions graphblas_algorithms/interface.py
Original file line number Diff line number Diff line change
Expand Up @@ -340,6 +340,7 @@ class Dispatcher:
mod = nxapi.dag
# =============
ancestors = mod.ancestors
dag_longest_path = mod.dag_longest_path
dag_longest_path_length = mod.dag_longest_path_length
descendants = mod.descendants
has_cycle = mod.has_cycle
Expand Down
Loading
Loading