QDpy
Loading...
Searching...
No Matches
genealogy.py
Go to the documentation of this file.
1# SPDX-License-Identifier: LGPL-3.0-or-later
2
4
5"""Ancestry archives, goal switching, and stepping stones in QD searches."""
6
7from collections import Counter
8from collections.abc import Mapping
9from dataclasses import dataclass, field
10from fractions import Fraction
11from operator import index
12
13import numpy as np
14
15from .lineage import read_lineage
16
17__all__ = ["GoalSwitch", "SearchTrajectoryNetwork", "SteppingStoneAnalysis", "ancestry", "ancestor_archive", "goal_switches",
18 "lineage_trajectory_network", "plot_ancestry_archive", "plot_stepping_stones", "search_trajectory_network"]
19
20
21def _lineage_nodes(source):
22 return source if isinstance(source, Mapping) else read_lineage(source)
23
24
25def _ancestor_ids(nodes, targets):
26 selected = set()
27 stack = list(targets)
28 while stack:
29 node = stack.pop()
30 if node not in nodes:
31 raise ValueError(f"Unknown lineage node {node}.")
32 if node not in selected:
33 selected.add(node)
34 stack.extend(nodes[node].parents)
35 return selected
36
37
38
39def ancestry(source, elite, *, include_elite=False):
40 """Return a dictionary of the selected elite's unique ancestors ordered by proposal ID.
41
42 Supply a lineage JSONL path or a mapping of IDs to ``LineageNode`` records.
43 ``include_elite`` adds the focal individual to the returned graph.
44 """
45 nodes = _lineage_nodes(source)
46 selected = _ancestor_ids(nodes, (elite,))
47 if not include_elite:
48 selected.remove(elite)
49 return {node: nodes[node] for node in sorted(selected)}
50
51
52def _project_ancestors(nodes, grid):
53 from .containers import CVTGrid, Grid
54 from .phenotype import Features, Fitness, Individual
55
56 if type(grid) not in (Grid, CVTGrid):
57 raise TypeError("Use a fixed Grid or CVTGrid as the reporting geometry.")
58 if any(item.fitness is None or item.descriptors is None or item.fitness_weights is None
59 for item in nodes.values()):
60 raise ValueError("Ancestor projection requires a log recorded with record_measurements=True.")
61 weights = grid.fitness_weights
62 if weights is None and nodes:
63 weights = next(iter(nodes.values())).fitness_weights
64 settings = dict(shape=grid.shape, fitness_domain=grid.fitness_domain, features_domain=grid.features_domain,
65 fitness_weights=weights)
66 projected = Grid(**settings) if type(grid) is Grid else CVTGrid(centroids=grid.cluster_centers, **settings)
67 for node in nodes.values():
68 if len(node.fitness) != len(projected.fitness_domain) or len(node.descriptors) != len(projected.features_domain):
69 raise ValueError("Recorded measurement dimensions differ from the reporting grid.")
70 if tuple(node.fitness_weights) != tuple(projected.fitness_weights):
71 raise ValueError("Recorded objective weights differ from the reporting grid.")
72 if not projected.in_bounds(node.fitness, projected.fitness_domain):
73 continue
74 try:
75 projected.index_grid(node.descriptors)
76 except IndexError:
77 continue
78 projected.add(Individual([node.id], fitness=Fitness(node.fitness, weights=weights),
79 features=Features(node.descriptors)))
80 return projected
81
82
83
85def ancestor_archive(source, elite, *, grid, include_elite=False):
86 """Build a new Grid or CVTGrid containing measurements from one elite's ancestry.
87
88 Use a measured lineage and a fixed reporting grid with matching objectives
89 and descriptors. Ignore measurements outside the reporting domain. Each
90 candidate stores its lineage ID as its sole genome coordinate. The grid
91 can be plotted and scored with ordinary QDpy archive methods.
92 """
93 return _project_ancestors(ancestry(source, elite, include_elite=include_elite), grid)
94
95
96
97@dataclass(frozen=True)
99 """Identify the two nodes and their distinct cells or categorical goals."""
100
101 parent: int
102 child: int
103 source: object
104 target: object
105
106
107def _edges(nodes, selected):
108 for child in selected:
109 for parent in dict.fromkeys(nodes[child].parents):
110 yield parent, child
111
112
113
115def goal_switches(source, *, elite=None, goals=None):
116 """Return all observed switches, or just switches in one elite's ancestry.
117
118 By default use the cells recorded at admission. Provide ``goals`` as a
119 mapping from proposal IDs to explicit categorical goals to override them.
120 Edges with an unknown endpoint are omitted. A repeated parent on one
121 proposal contributes at most one edge.
122 """
123 nodes = _lineage_nodes(source)
124 selected = nodes if elite is None else ancestry(nodes, elite, include_elite=True)
125 labels = {node: item.cell for node, item in selected.items()} if goals is None else goals
126 switches = []
127 for parent, child in _edges(nodes, selected):
128 origin, target = labels.get(parent), labels.get(child)
129 if origin is not None and target is not None and origin != target:
130 switches.append(GoalSwitch(parent, child, origin, target))
131 return tuple(switches)
132
133
134
135@dataclass(frozen=True)
137 """Store ordered states and counts of observed directed transitions between them."""
138
139 states: tuple
140 transitions: dict
141 measured_transitions: dict = field(default_factory=dict)
142 worsening_transitions: dict = field(default_factory=dict)
143
144 @property
146 """Return the fraction of scored transitions that worsened, or None without scores."""
147 measured = sum(self.measured_transitions.values())
148 return sum(self.worsening_transitions.values()) / measured if measured else None
149
150 def _adjacency(self):
151 adjacency = {state: [] for state in self.states}
152 for origin, target in self.transitions:
153 if origin != target:
154 adjacency[origin].append(target)
155 return adjacency
156
157
158 def betweenness(self, *, normalized=True):
159 """Return exact Brandes betweenness excluding path endpoints and self-loops.
160
161 Normalize by the number of ordered endpoint pairs excluding the
162 focal state. Transition frequencies remain available in ``transitions``.
163 """
164 adjacency = self._adjacency()
165 scores = dict.fromkeys(self.states, 0.)
166 for origin in self.states:
167 order, paths, predecessors = _shortest_paths(adjacency, origin)
168 dependency = dict.fromkeys(order, 0.)
169 for target in reversed(order):
170 for state in predecessors[target]:
171 dependency[state] += (paths[state] / paths[target]) * (1. + dependency[target])
172 if target != origin:
173 scores[target] += dependency[target]
174 size = len(self.states)
175 divisor = (size - 1) * (size - 2) if normalized and size > 2 else 1
176 return {state: value / divisor for state, value in scores.items()}
177
178
180 def stepping_stones(self, endpoints, *, percentile=75):
181 """Flag states strictly above the chosen percentile of shortest-path counts.
182
183 Supply an iterable of ordered ``(start, final)`` pairs. Counts sum
184 over all equally short directed paths for each pair, excluding the
185 pair's endpoints. Repeated pairs contribute repeatedly. Unreachable
186 pairs contribute zero paths. The percentile includes zero-count states.
187 """
188 quantile = Fraction(str(percentile)) / 100
189 if not 0 <= quantile <= 1:
190 raise ValueError("percentile must be between 0 and 100.")
191 adjacency = self._adjacency()
192 by_start = {}
193 for start, final in endpoints:
194 if start not in adjacency or final not in adjacency:
195 raise ValueError("Each start and final state must appear in the network.")
196 by_start.setdefault(start, Counter())[final] += 1
197 counts = dict.fromkeys(self.states, 0)
198 total = 0
199 for start, finals in by_start.items():
200 order, paths, predecessors = _shortest_paths(adjacency, start)
201 endings = dict.fromkeys(order, 0)
202 for final, count in finals.items():
203 if final in paths:
204 total += paths[final] * count
205 endings[final] = count
206 for state in reversed(order):
207 if state != start:
208 counts[state] += paths[state] * (endings[state] - finals.get(state, 0))
209 for previous in predecessors[state]:
210 endings[previous] += endings[state]
211 ordered = sorted(counts.values())
212 cutoff = Fraction(0)
213 if ordered:
214 rank = (len(ordered) - 1) * quantile
215 lower, remainder = divmod(rank.numerator, rank.denominator)
216 cutoff = Fraction(ordered[lower])
217 if remainder:
218 cutoff += Fraction(remainder, rank.denominator) * (ordered[lower + 1] - ordered[lower])
219 return SteppingStoneAnalysis(counts, tuple(node for node, count in counts.items() if count > cutoff), total)
220
221
222def _shortest_paths(adjacency, origin):
223 """Build a breadth-first DAG and count the shortest paths to each state."""
224 distance = {origin: 0}
225 paths = {origin: 1}
226 predecessors = {origin: []}
227 order = [origin]
228 for state in order:
229 depth = distance[state] + 1
230 for target in adjacency[state]:
231 if target not in distance:
232 distance[target] = depth
233 paths[target] = 0
234 predecessors[target] = []
235 order.append(target)
236 if distance[target] == depth:
237 paths[target] += paths[state]
238 predecessors[target].append(state)
239 return order, paths, predecessors
240
241
242
243@dataclass(frozen=True)
245 """Store intermediate path counts by state, qualifying states, and total shortest paths."""
246
247 counts: dict
248 stones: tuple
249 shortest_paths: int
250
251
252
254def search_trajectory_network(trajectories):
255 """Build a directed network from an iterable of ordered sequences of hashable states."""
256 states, transitions = {}, Counter()
257 for trajectory in trajectories:
258 locations = iter(trajectory)
259 try:
260 previous = next(locations)
261 except StopIteration:
262 continue
263 states[previous] = None
264 for state in locations:
265 states[state] = None
266 transitions[previous, state] += 1
267 previous = state
268 return SearchTrajectoryNetwork(tuple(states), dict(transitions))
269
270
271
273def lineage_trajectory_network(runs, *, state=None, targets=None, objective=0):
274 """Aggregate parent-to-child transitions across a mapping of run labels to lineage logs.
275
276 Use recorded admission cells or supply ``state(node)`` returning a
277 hashable location. ``None`` marks an unknown location. To restrict the
278 graph to stepping stones of selected elites, pass ``targets`` as a
279 mapping from run label to an iterable of node IDs. Supply the same state
280 definition and geometry for all runs. Counts preserve repeated transitions.
281 Record worsening on ``objective`` when both endpoints have comparable
282 measurements. Pass ``objective=None`` for a topology-only analysis.
283 """
284 if not isinstance(runs, Mapping) or (targets is not None and set(targets) != set(runs)):
285 raise ValueError("Provide a mapping of runs and, when used, target IDs for each run.")
286 if objective is not None and (objective := index(objective)) < 0:
287 raise ValueError("objective must be nonnegative.")
288 states, transitions = {}, Counter()
289 scored, worsening = Counter(), Counter()
290 for label, source in runs.items():
291 nodes = _lineage_nodes(source)
292 selected = nodes if targets is None else sorted(_ancestor_ids(nodes, targets[label]))
293 labels = {node: nodes[node].cell if state is None else state(nodes[node]) for node in selected}
294 states.update(dict.fromkeys(value for value in labels.values() if value is not None))
295 for parent, child in _edges(nodes, selected):
296 origin, target = labels.get(parent), labels[child]
297 if origin is not None and target is not None:
298 transitions[origin, target] += 1
299 delta = _fitness_change(nodes[parent], nodes[child], objective)
300 if delta is not None:
301 scored[origin, target] += 1
302 if delta < 0:
303 worsening[origin, target] += 1
304 return SearchTrajectoryNetwork(tuple(states), dict(transitions), dict(scored), dict(worsening))
305
306
307def _fitness_change(before, after, objective):
308 if objective is None:
309 return None
310 vectors = before.fitness, before.fitness_weights, after.fitness, after.fitness_weights
311 if any(values is None or objective >= len(values) for values in vectors):
312 return None
313 prior, prior_weight, current, weight = [values[objective] for values in vectors]
314 if not np.isfinite((prior, prior_weight, current, weight)).all() or not weight or not prior_weight:
315 return None
316 direction = 1 if weight > 0 else -1
317 if (prior_weight > 0) != (weight > 0):
318 return None
319 return direction * (current - prior)
320
321
322
323def plot_ancestry_archive(source, elite, *, grid, ax=None):
324 """Plot directed ancestry paths on a two-descriptor Grid or CVTGrid.
325
326 The background contains the ancestors' cell elites. The outlined focal
327 elite is included in the paths and excluded from the background colors.
328 """
329 from .plots import plot_archive
330
331 nodes = ancestry(source, elite, include_elite=True)
332 focal = nodes.pop(elite)
333 if len(grid.features_domain) != 2:
334 raise ValueError("The ancestry overlay needs two descriptor axes.")
335 if focal.descriptors is None or len(focal.descriptors) != 2:
336 raise ValueError("The selected elite needs two recorded descriptors.")
337 archive = _project_ancestors(nodes, grid)
338 ax = plot_archive(archive, ax=ax)
339 nodes[elite] = focal
340 segments = [(nodes[parent].descriptors, nodes[child].descriptors) for parent, child in _edges(nodes, nodes)
341 if parent in nodes and nodes[parent].descriptors != nodes[child].descriptors]
342 if segments:
343 starts, ends = (np.asarray(points) for points in zip(*segments))
344 ax.quiver(*starts.T, *(ends - starts).T, angles="xy", scale_units="xy", scale=1.,
345 width=.005, color="#172638", alpha=.75, zorder=3)
346 ax.scatter(*focal.descriptors, s=100, facecolors="none", edgecolors="#ec6b28", linewidth=2, zorder=4)
347 ax.set_title(f"Archive paths to elite {elite}")
348 return ax
349
350
351
352def plot_stepping_stones(network, *, analysis=None, positions=None, ax=None):
353 """Plot a directed trajectory network, using supplied two-dimensional positions or a circle.
354
355 Node color shows normalized betweenness, or shortest-path counts if
356 ``analysis`` is supplied. A ring marks states classified as stepping
357 stones. Thicker arrows correspond to more observations. Self-loops
358 count in the data and are omitted from the plot.
359 """
360 import matplotlib.pyplot as plt
361 from matplotlib.patches import FancyArrowPatch
362
363 if not network.states:
364 raise ValueError("No recorded states to plot.")
365 if ax is None:
366 ax = plt.figure(figsize=(6, 5), layout="constrained").add_subplot()
367 if positions is None:
368 angle = np.linspace(0., 2 * np.pi, len(network.states), endpoint=False)
369 positions = dict(zip(network.states, zip(np.cos(angle), np.sin(angle))))
370 coords = np.asarray([positions[state] for state in network.states], dtype=float)
371 if coords.shape != (len(network.states), 2) or not np.isfinite(coords).all():
372 raise ValueError("Provide two finite coordinates per state.")
373 max_count = max((n for (a, b), n in network.transitions.items() if a != b), default=1)
374 for (origin, target), count in network.transitions.items():
375 if origin == target:
376 continue
377 arrow = FancyArrowPatch(positions[origin], positions[target], arrowstyle="-|>", mutation_scale=10,
378 shrinkA=6, shrinkB=7, connectionstyle="arc3,rad=.13",
379 color="#576578", linewidth=.5 + 2. * count / max_count, alpha=.65)
380 ax.add_patch(arrow)
381 scores = network.betweenness() if analysis is None else analysis.counts
382 scatter = ax.scatter(*coords.T, c=[scores[state] for state in network.states], cmap="plasma",
383 s=62, linewidth=.5, edgecolors="#172638", zorder=3)
384 label = "Betweenness centrality" if analysis is None else "Paths through state"
385 ax.figure.colorbar(scatter, ax=ax, label=label)
386 if analysis is not None and analysis.stones:
387 stones = [positions[state] for state in analysis.stones]
388 ax.scatter(*zip(*stones), s=125, facecolors="none", edgecolors="#ef6c37", linewidths=1.6, zorder=4)
389 ax.set_aspect("equal")
390 ax.margins(.12)
391 ax.set_title("Search trajectory network")
392 return ax
An observed parent-to-child transition between distinct goals.
Definition genealogy.py:98
A directed graph of transitions aggregated by search state.
Definition genealogy.py:136
stepping_stones(self, endpoints, *, percentile=75)
Count intermediate states on shortest paths between specified start and final states.
Definition genealogy.py:180
betweenness(self, *, normalized=True)
Compute directed unweighted betweenness, independent of edge frequency.
Definition genealogy.py:158
Endpoint-restricted path counts and the states passing the percentile cutoff.
Definition genealogy.py:244