5"""Ancestry archives, goal switching, and stepping stones in QD searches."""
7from collections
import Counter
8from collections.abc
import Mapping
9from dataclasses
import dataclass, field
10from fractions
import Fraction
11from operator
import index
15from .lineage
import read_lineage
17__all__ = [
"GoalSwitch",
"SearchTrajectoryNetwork",
"SteppingStoneAnalysis",
"ancestry",
"ancestor_archive",
"goal_switches",
18 "lineage_trajectory_network",
"plot_ancestry_archive",
"plot_stepping_stones",
"search_trajectory_network"]
21def _lineage_nodes(source):
22 return source
if isinstance(source, Mapping)
else read_lineage(source)
25def _ancestor_ids(nodes, targets):
31 raise ValueError(f
"Unknown lineage node {node}.")
32 if node
not in selected:
34 stack.extend(nodes[node].parents)
39def ancestry(source, elite, *, include_elite=False):
40 """Return a dictionary of the selected elite's unique ancestors ordered by proposal ID.
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.
45 nodes = _lineage_nodes(source)
46 selected = _ancestor_ids(nodes, (elite,))
48 selected.remove(elite)
49 return {node: nodes[node]
for node
in sorted(selected)}
52def _project_ancestors(nodes, grid):
53 from .containers
import CVTGrid, Grid
54 from .phenotype
import Features, Fitness, Individual
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):
75 projected.index_grid(node.descriptors)
78 projected.add(Individual([node.id], fitness=Fitness(node.fitness, weights=weights),
79 features=Features(node.descriptors)))
85def ancestor_archive(source, elite, *, grid, include_elite=False):
86 """Build a new Grid or CVTGrid containing measurements from one elite's ancestry.
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.
93 return _project_ancestors(ancestry(source, elite, include_elite=include_elite), grid)
97@dataclass(frozen=True)
99 """Identify the two nodes and their distinct cells or categorical goals."""
107def _edges(nodes, selected):
108 for child
in selected:
109 for parent
in dict.fromkeys(nodes[child].parents):
115def goal_switches(source, *, elite=None, goals=None):
116 """Return all observed switches, or just switches in one elite's ancestry.
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.
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
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)
135@dataclass(frozen=True)
137 """Store ordered states and counts of observed directed transitions between them."""
141 measured_transitions: dict = field(default_factory=dict)
142 worsening_transitions: dict = field(default_factory=dict)
146 """Return the fraction of scored transitions that worsened, or None without scores."""
150 def _adjacency(self):
151 adjacency = {state: []
for state
in self.
states}
154 adjacency[origin].append(target)
159 """Return exact Brandes betweenness excluding path endpoints and self-loops.
161 Normalize by the number of ordered endpoint pairs excluding the
162 focal state. Transition frequencies remain available in ``transitions``.
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])
173 scores[target] += dependency[target]
175 divisor = (size - 1) * (size - 2)
if normalized
and size > 2
else 1
176 return {state: value / divisor
for state, value
in scores.items()}
181 """Flag states strictly above the chosen percentile of shortest-path counts.
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.
188 quantile = Fraction(str(percentile)) / 100
189 if not 0 <= quantile <= 1:
190 raise ValueError(
"percentile must be between 0 and 100.")
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)
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():
204 total += paths[final] * count
205 endings[final] = count
206 for state
in reversed(order):
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())
214 rank = (len(ordered) - 1) * quantile
215 lower, remainder = divmod(rank.numerator, rank.denominator)
216 cutoff = Fraction(ordered[lower])
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)
222def _shortest_paths(adjacency, origin):
223 """Build a breadth-first DAG and count the shortest paths to each state."""
224 distance = {origin: 0}
226 predecessors = {origin: []}
229 depth = distance[state] + 1
230 for target
in adjacency[state]:
231 if target
not in distance:
232 distance[target] = depth
234 predecessors[target] = []
236 if distance[target] == depth:
237 paths[target] += paths[state]
238 predecessors[target].append(state)
239 return order, paths, predecessors
243@dataclass(frozen=True)
245 """Store intermediate path counts by state, qualifying states, and total shortest paths."""
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)
260 previous = next(locations)
261 except StopIteration:
263 states[previous] =
None
264 for state
in locations:
266 transitions[previous, state] += 1
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.
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.
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
303 worsening[origin, target] += 1
307def _fitness_change(before, after, objective):
308 if objective
is 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):
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:
316 direction = 1
if weight > 0
else -1
317 if (prior_weight > 0) != (weight > 0):
319 return direction * (current - prior)
323def plot_ancestry_archive(source, elite, *, grid, ax=None):
324 """Plot directed ancestry paths on a two-descriptor Grid or CVTGrid.
326 The background contains the ancestors' cell elites. The outlined focal
327 elite is included in the paths and excluded from the background colors.
329 from .plots
import plot_archive
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)
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]
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}")
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.
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.
360 import matplotlib.pyplot
as plt
361 from matplotlib.patches
import FancyArrowPatch
363 if not network.states:
364 raise ValueError(
"No recorded states to plot.")
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():
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)
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")
391 ax.set_title(
"Search trajectory network")
An observed parent-to-child transition between distinct goals.
A directed graph of transitions aggregated by search state.
stepping_stones(self, endpoints, *, percentile=75)
Count intermediate states on shortest paths between specified start and final states.
dict measured_transitions
dict worsening_transitions
betweenness(self, *, normalized=True)
Compute directed unweighted betweenness, independent of edge frequency.
Endpoint-restricted path counts and the states passing the percentile cutoff.