QDpy
Loading...
Searching...
No Matches
graph_paths.py
Go to the documentation of this file.
1# SPDX-License-Identifier: LGPL-3.0-or-later
2
4
5"""Combinatorial QD-GA and QD-EA on positively weighted directed graphs."""
6
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
13
14import numpy as np
15
16__all__ = ["GraphPath", "GraphPathRepertoire", "graph_path_qd"]
17
18
19
20@dataclass(frozen=True)
22 """Nodes appear in travel order, with the source and target included."""
23
24 nodes: tuple[Hashable, ...]
25 cost: int | float
26
27
28
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.
34 """
35
36 nodes: tuple[Hashable, ...]
37 attempts: int
38 evaluations: int
39 initial_routes: int
40 _routes: dict[tuple[Hashable, Hashable], GraphPath]
41
42 @property
43 def routes(self):
44 """Mapping of discovered off-diagonal pairs to immutable routes."""
45 return MappingProxyType(self._routes)
46
47
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:
51 return GraphPath((source,), 0)
52 return self._routes.get((source, target))
53
54
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))]
60 if edge == path[:2]:
61 path = path[1:]
62 elif edge == path[-2:]:
63 path = path[:-1]
64 elif right == start and left not in path:
65 path = (left, *path)
66 elif left == end and right not in path:
67 path = (*path, right)
68 else:
69 return None
70 if len(path) < 2:
71 return None
72 return path
73
74
75def _crossover(routes, occupied, nodes, feasible, rng):
76 if feasible:
77 if len(nodes) < 3:
78 return None
79 source, middle = rng.choice(len(nodes), size=2, replace=False)
80 first = routes.get((nodes[source], nodes[middle]))
81 if first is None:
82 return None
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]))
87 else:
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]:
91 return None
92 tail = second.nodes[1:]
93 if set(first.nodes).intersection(tail):
94 return None
95 return first.nodes + tail
96
97
98def _graph(edges, nodes):
99 incident = {} if nodes is None else {node: [] for node in nodes}
100 weights = {}
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):
105 weight = int(weight)
106 valid = weight > 0
107 else:
108 valid = isinstance(weight, Real) and isfinite(weight) and weight > 0
109 if valid:
110 weight = float(weight)
111 if not valid:
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
120
121
122
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.
126
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.
134
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.
146 """
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)
157 evaluations = 0
158 for _ in range(budget if occupied else 0):
159 if rng.random() < crossover_probability:
160 path = _crossover(routes, occupied, labels, crossover == "feasible", rng)
161 else:
162 parent = routes[occupied[rng.integers(len(occupied))]]
163 path = _mutation(parent.nodes, incident, rng)
164 if path is None:
165 continue
166 evaluations += 1
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:
174 routes[pair] = GraphPath(path, cost)
175 return GraphPathRepertoire(labels, budget, evaluations, len(weights), routes)
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.