# SPDX-License-Identifier: LGPL-3.0-or-later
## @file
# @brief Quality-diversity genetic search for directed endpoint-pair routes.
"""Combinatorial QD-GA and QD-EA on positively weighted directed graphs."""
from collections.abc import Hashable
from dataclasses import dataclass
from math import fsum, isfinite
from numbers import Integral, Real
from operator import index
from types import MappingProxyType
import numpy as np
__all__ = ["GraphPath", "GraphPathRepertoire", "graph_path_qd"]
## @brief An immutable directed route and its summed edge weight.
[docs]
@dataclass(frozen=True)
class GraphPath:
"""Nodes appear in travel order, with the source and target included."""
nodes: tuple[Hashable, ...]
cost: int | float
## @brief One retained route per discovered ordered pair and the proposal counts.
[docs]
@dataclass(frozen=True)
class GraphPathRepertoire:
"""Attempts include invalid or unavailable offspring. Evaluations count
valid offspring, including those that fail to improve the archive.
Direct-edge initialization is reported separately.
"""
nodes: tuple[Hashable, ...]
attempts: int
evaluations: int
initial_routes: int
_routes: dict[tuple[Hashable, Hashable], GraphPath]
@property
def routes(self):
"""Mapping of discovered off-diagonal pairs to immutable routes."""
return MappingProxyType(self._routes)
## @brief Look up a path without extending the search.
[docs]
def route(self, source, target):
"""Return a retained path, a zero-cost self path, or None."""
if source == target and source in self.nodes:
return GraphPath((source,), 0)
return self._routes.get((source, target))
def _mutation(path, incident, rng):
for _ in range(1 + rng.poisson(1)):
start, end = path[0], path[-1]
edges = tuple(dict.fromkeys((*incident[start], *incident[end])))
edge = left, right = edges[rng.integers(len(edges))]
if edge == path[:2]:
path = path[1:]
elif edge == path[-2:]:
path = path[:-1]
elif right == start and left not in path:
path = (left, *path)
elif left == end and right not in path:
path = (*path, right)
else:
return None
if len(path) < 2:
return None
return path
def _crossover(routes, occupied, nodes, feasible, rng):
if feasible:
if len(nodes) < 3:
return None
source, middle = rng.choice(len(nodes), size=2, replace=False)
first = routes.get((nodes[source], nodes[middle]))
if first is None:
return None
target = int(rng.integers(len(nodes) - 2))
for excluded in sorted((source, middle)):
target += target >= excluded
second = routes.get((nodes[middle], nodes[target]))
else:
a, b = rng.integers(len(occupied), size=2)
first, second = routes[occupied[a]], routes[occupied[b]]
if second is None or first.nodes[-1] != second.nodes[0]:
return None
tail = second.nodes[1:]
if set(first.nodes).intersection(tail):
return None
return first.nodes + tail
def _graph(edges, nodes):
incident = {} if nodes is None else {node: [] for node in nodes}
weights = {}
for source, target, weight in edges:
if source == target or (source, target) in weights:
raise ValueError("Supply distinct directed edges between different nodes.")
if isinstance(weight, Integral):
weight = int(weight)
valid = weight > 0
else:
valid = isinstance(weight, Real) and isfinite(weight) and weight > 0
if valid:
weight = float(weight)
if not valid:
raise ValueError("Edge weights must be positive and finite.")
if nodes is not None and (source not in incident or target not in incident):
raise ValueError("Each edge endpoint must appear in nodes.")
key = (source, target)
weights[key] = weight
incident.setdefault(source, []).append(key)
incident.setdefault(target, []).append(key)
return weights, incident
## @brief Search for short paths by evolving one solution per directed endpoint pair.
[docs]
def graph_path_qd(edges, *, budget, nodes=None, crossover_probability=0.5,
crossover="feasible", seed=0):
"""Explore routes with endpoint mutations and directed path crossover.
Initialize the repertoire with the direct edges. Each subsequent
attempt changes one path or concatenates two paths. Mutation draws
one plus a Poisson(1) number of incident-edge edits and ends the
proposal at the first invalid edit. Crossover can select occupied
pairs uniformly or draw the second pair from the first pair's target
row. Empty or incompatible pairs consume one attempt. A valid path
replaces an equal-cost or higher-cost incumbent.
:param edges: Iterable of (source, target, positive weight) triples.
Nodes may be any hashable labels. Weights can be integers or floats.
:param budget: Nonnegative number of proposals after direct-edge initialization.
:param nodes: Optional node labels in sampling order, including isolated
nodes. Omit to infer nodes in order of first occurrence in edges.
:param crossover_probability: Probability of a crossover attempt.
Zero runs mutation-only QD-EA.
:param crossover: "feasible" for directed-row selection or "uniform"
for two independent draws from occupied pairs.
:param seed: Local NumPy random seed.
:returns: A GraphPathRepertoire with routes and separate proposal counts.
"""
budget = index(budget)
if budget < 0 or not 0 <= crossover_probability <= 1:
raise ValueError("Supply a nonnegative budget and a crossover probability in [0, 1].")
if crossover not in ("feasible", "uniform"):
raise ValueError("Choose 'feasible' or 'uniform' crossover.")
weights, incident = _graph(edges, nodes)
labels = tuple(incident)
routes = {pair: GraphPath(pair, weight) for pair, weight in weights.items()}
occupied = list(routes)
rng = np.random.default_rng(seed)
evaluations = 0
for _ in range(budget if occupied else 0):
if rng.random() < crossover_probability:
path = _crossover(routes, occupied, labels, crossover == "feasible", rng)
else:
parent = routes[occupied[rng.integers(len(occupied))]]
path = _mutation(parent.nodes, incident, rng)
if path is None:
continue
evaluations += 1
pair = (path[0], path[-1])
edge_costs = [weights[edge] for edge in zip(path, path[1:])]
cost = sum(edge_costs) if all(isinstance(w, int) for w in edge_costs) else fsum(edge_costs)
incumbent = routes.get(pair)
if incumbent is None:
occupied.append(pair)
if incumbent is None or cost <= incumbent.cost:
routes[pair] = GraphPath(path, cost)
return GraphPathRepertoire(labels, budget, evaluations, len(weights), routes)