5"""Combinatorial QD-GA and QD-EA on positively weighted directed graphs."""
7from collections.abc
import Hashable
8from dataclasses
import dataclass
9from math
import fsum, isfinite
10from numbers
import Integral, Real
11from operator
import index
12from types
import MappingProxyType
16__all__ = [
"GraphPath",
"GraphPathRepertoire",
"graph_path_qd"]
20@dataclass(frozen=True)
22 """Nodes appear in travel order, with the source and target included."""
24 nodes: tuple[Hashable, ...]
29@dataclass(frozen=True)
31 """Attempts include invalid or unavailable offspring. Evaluations count
32 valid offspring, including those that fail to improve the archive.
33 Direct-edge initialization is reported separately.
36 nodes: tuple[Hashable, ...]
40 _routes: dict[tuple[Hashable, Hashable], GraphPath]
44 """Mapping of discovered off-diagonal pairs to immutable routes."""
45 return MappingProxyType(self.
_routes)
48 def route(self, source, target):
49 """Return a retained path, a zero-cost self path, or None."""
50 if source == target
and source
in self.
nodes:
52 return self.
_routes.get((source, target))
55def _mutation(path, incident, rng):
56 for _
in range(1 + rng.poisson(1)):
57 start, end = path[0], path[-1]
58 edges = tuple(dict.fromkeys((*incident[start], *incident[end])))
59 edge = left, right = edges[rng.integers(len(edges))]
62 elif edge == path[-2:]:
64 elif right == start
and left
not in path:
66 elif left == end
and right
not in path:
75def _crossover(routes, occupied, nodes, feasible, rng):
79 source, middle = rng.choice(len(nodes), size=2, replace=
False)
80 first = routes.get((nodes[source], nodes[middle]))
83 target = int(rng.integers(len(nodes) - 2))
84 for excluded
in sorted((source, middle)):
85 target += target >= excluded
86 second = routes.get((nodes[middle], nodes[target]))
88 a, b = rng.integers(len(occupied), size=2)
89 first, second = routes[occupied[a]], routes[occupied[b]]
90 if second
is None or first.nodes[-1] != second.nodes[0]:
92 tail = second.nodes[1:]
93 if set(first.nodes).intersection(tail):
95 return first.nodes + tail
98def _graph(edges, nodes):
99 incident = {}
if nodes
is None else {node: []
for node
in nodes}
101 for source, target, weight
in edges:
102 if source == target
or (source, target)
in weights:
103 raise ValueError(
"Supply distinct directed edges between different nodes.")
104 if isinstance(weight, Integral):
108 valid = isinstance(weight, Real)
and isfinite(weight)
and weight > 0
110 weight = float(weight)
112 raise ValueError(
"Edge weights must be positive and finite.")
113 if nodes
is not None and (source
not in incident
or target
not in incident):
114 raise ValueError(
"Each edge endpoint must appear in nodes.")
115 key = (source, target)
116 weights[key] = weight
117 incident.setdefault(source, []).append(key)
118 incident.setdefault(target, []).append(key)
119 return weights, incident
123def graph_path_qd(edges, *, budget, nodes=None, crossover_probability=0.5,
124 crossover="feasible", seed=0):
125 """Explore routes with endpoint mutations and directed path crossover.
127 Initialize the repertoire with the direct edges. Each subsequent
128 attempt changes one path or concatenates two paths. Mutation draws
129 one plus a Poisson(1) number of incident-edge edits and ends the
130 proposal at the first invalid edit. Crossover can select occupied
131 pairs uniformly or draw the second pair from the first pair's target
132 row. Empty or incompatible pairs consume one attempt. A valid path
133 replaces an equal-cost or higher-cost incumbent.
135 :param edges: Iterable of (source, target, positive weight) triples.
136 Nodes may be any hashable labels. Weights can be integers or floats.
137 :param budget: Nonnegative number of proposals after direct-edge initialization.
138 :param nodes: Optional node labels in sampling order, including isolated
139 nodes. Omit to infer nodes in order of first occurrence in edges.
140 :param crossover_probability: Probability of a crossover attempt.
141 Zero runs mutation-only QD-EA.
142 :param crossover: "feasible" for directed-row selection or "uniform"
143 for two independent draws from occupied pairs.
144 :param seed: Local NumPy random seed.
145 :returns: A GraphPathRepertoire with routes and separate proposal counts.
147 budget = index(budget)
148 if budget < 0
or not 0 <= crossover_probability <= 1:
149 raise ValueError(
"Supply a nonnegative budget and a crossover probability in [0, 1].")
150 if crossover
not in (
"feasible",
"uniform"):
151 raise ValueError(
"Choose 'feasible' or 'uniform' crossover.")
152 weights, incident = _graph(edges, nodes)
153 labels = tuple(incident)
154 routes = {pair:
GraphPath(pair, weight)
for pair, weight
in weights.items()}
155 occupied = list(routes)
156 rng = np.random.default_rng(seed)
158 for _
in range(budget
if occupied
else 0):
159 if rng.random() < crossover_probability:
160 path = _crossover(routes, occupied, labels, crossover ==
"feasible", rng)
162 parent = routes[occupied[rng.integers(len(occupied))]]
163 path = _mutation(parent.nodes, incident, rng)
167 pair = (path[0], path[-1])
168 edge_costs = [weights[edge]
for edge
in zip(path, path[1:])]
169 cost = sum(edge_costs)
if all(isinstance(w, int)
for w
in edge_costs)
else fsum(edge_costs)
170 incumbent = routes.get(pair)
171 if incumbent
is None:
172 occupied.append(pair)
173 if incumbent
is None or cost <= incumbent.cost:
One retained route per discovered ordered pair and the proposal counts.
route(self, source, target)
Look up a path without extending the search.
An immutable directed route and its summed edge weight.