# SPDX-License-Identifier: LGPL-3.0-or-later
## @file
# @brief Analyze genealogies and search trajectory networks in quality-diversity runs.
"""Ancestry archives, goal switching, and stepping stones in QD searches."""
from collections import Counter
from collections.abc import Mapping
from dataclasses import dataclass, field
from fractions import Fraction
from operator import index
import numpy as np
from .lineage import read_lineage
__all__ = ["GoalSwitch", "SearchTrajectoryNetwork", "SteppingStoneAnalysis", "ancestry", "ancestor_archive", "goal_switches",
"lineage_trajectory_network", "plot_ancestry_archive", "plot_stepping_stones", "search_trajectory_network"]
def _lineage_nodes(source):
return source if isinstance(source, Mapping) else read_lineage(source)
def _ancestor_ids(nodes, targets):
selected = set()
stack = list(targets)
while stack:
node = stack.pop()
if node not in nodes:
raise ValueError(f"Unknown lineage node {node}.")
if node not in selected:
selected.add(node)
stack.extend(nodes[node].parents)
return selected
## @brief Extract the ancestor graph of a selected proposal without duplicating shared ancestors.
[docs]
def ancestry(source, elite, *, include_elite=False):
"""Return a dictionary of the selected elite's unique ancestors ordered by proposal ID.
Supply a lineage JSONL path or a mapping of IDs to ``LineageNode`` records.
``include_elite`` adds the focal individual to the returned graph.
"""
nodes = _lineage_nodes(source)
selected = _ancestor_ids(nodes, (elite,))
if not include_elite:
selected.remove(elite)
return {node: nodes[node] for node in sorted(selected)}
def _project_ancestors(nodes, grid):
from .containers import CVTGrid, Grid
from .phenotype import Features, Fitness, Individual
if type(grid) not in (Grid, CVTGrid):
raise TypeError("Use a fixed Grid or CVTGrid as the reporting geometry.")
if any(item.fitness is None or item.descriptors is None or item.fitness_weights is None
for item in nodes.values()):
raise ValueError("Ancestor projection requires a log recorded with record_measurements=True.")
weights = grid.fitness_weights
if weights is None and nodes:
weights = next(iter(nodes.values())).fitness_weights
settings = dict(shape=grid.shape, fitness_domain=grid.fitness_domain, features_domain=grid.features_domain,
fitness_weights=weights)
projected = Grid(**settings) if type(grid) is Grid else CVTGrid(centroids=grid.cluster_centers, **settings)
for node in nodes.values():
if len(node.fitness) != len(projected.fitness_domain) or len(node.descriptors) != len(projected.features_domain):
raise ValueError("Recorded measurement dimensions differ from the reporting grid.")
if tuple(node.fitness_weights) != tuple(projected.fitness_weights):
raise ValueError("Recorded objective weights differ from the reporting grid.")
if not projected.in_bounds(node.fitness, projected.fitness_domain):
continue
try:
projected.index_grid(node.descriptors)
except IndexError:
continue
projected.add(Individual([node.id], fitness=Fitness(node.fitness, weights=weights),
features=Features(node.descriptors)))
return projected
## @brief Rebin an elite's ancestors and keep one representative per reporting cell.
# @see https://doi.org/10.3389/frobt.2021.639173
[docs]
def ancestor_archive(source, elite, *, grid, include_elite=False):
"""Build a new Grid or CVTGrid containing measurements from one elite's ancestry.
Use a measured lineage and a fixed reporting grid with matching objectives
and descriptors. Ignore measurements outside the reporting domain. Each
candidate stores its lineage ID as its sole genome coordinate. The grid
can be plotted and scored with ordinary QDpy archive methods.
"""
return _project_ancestors(ancestry(source, elite, include_elite=include_elite), grid)
## @brief An observed parent-to-child transition between distinct goals.
[docs]
@dataclass(frozen=True)
class GoalSwitch:
"""Identify the two nodes and their distinct cells or categorical goals."""
parent: int
child: int
source: object
target: object
def _edges(nodes, selected):
for child in selected:
for parent in dict.fromkeys(nodes[child].parents):
yield parent, child
## @brief Count observed ancestry edges that move between distinct goals.
# @see https://doi.org/10.1162/EVCO_a_00189
[docs]
def goal_switches(source, *, elite=None, goals=None):
"""Return all observed switches, or just switches in one elite's ancestry.
By default use the cells recorded at admission. Provide ``goals`` as a
mapping from proposal IDs to explicit categorical goals to override them.
Edges with an unknown endpoint are omitted. A repeated parent on one
proposal contributes at most one edge.
"""
nodes = _lineage_nodes(source)
selected = nodes if elite is None else ancestry(nodes, elite, include_elite=True)
labels = {node: item.cell for node, item in selected.items()} if goals is None else goals
switches = []
for parent, child in _edges(nodes, selected):
origin, target = labels.get(parent), labels.get(child)
if origin is not None and target is not None and origin != target:
switches.append(GoalSwitch(parent, child, origin, target))
return tuple(switches)
## @brief A directed graph of transitions aggregated by search state.
[docs]
@dataclass(frozen=True)
class SearchTrajectoryNetwork:
"""Store ordered states and counts of observed directed transitions between them."""
states: tuple
transitions: dict
measured_transitions: dict = field(default_factory=dict)
worsening_transitions: dict = field(default_factory=dict)
@property
def worsening_fraction(self):
"""Return the fraction of scored transitions that worsened, or None without scores."""
measured = sum(self.measured_transitions.values())
return sum(self.worsening_transitions.values()) / measured if measured else None
def _adjacency(self):
adjacency = {state: [] for state in self.states}
for origin, target in self.transitions:
if origin != target:
adjacency[origin].append(target)
return adjacency
## @brief Compute directed unweighted betweenness, independent of edge frequency.
[docs]
def betweenness(self, *, normalized=True):
"""Return exact Brandes betweenness excluding path endpoints and self-loops.
Normalize by the number of ordered endpoint pairs excluding the
focal state. Transition frequencies remain available in ``transitions``.
"""
adjacency = self._adjacency()
scores = dict.fromkeys(self.states, 0.)
for origin in self.states:
order, paths, predecessors = _shortest_paths(adjacency, origin)
dependency = dict.fromkeys(order, 0.)
for target in reversed(order):
for state in predecessors[target]:
dependency[state] += (paths[state] / paths[target]) * (1. + dependency[target])
if target != origin:
scores[target] += dependency[target]
size = len(self.states)
divisor = (size - 1) * (size - 2) if normalized and size > 2 else 1
return {state: value / divisor for state, value in scores.items()}
## @brief Count intermediate states on shortest paths between specified start and final states.
# @see https://doi.org/10.1007/978-3-031-89991-1_14
[docs]
def stepping_stones(self, endpoints, *, percentile=75):
"""Flag states strictly above the chosen percentile of shortest-path counts.
Supply an iterable of ordered ``(start, final)`` pairs. Counts sum
over all equally short directed paths for each pair, excluding the
pair's endpoints. Repeated pairs contribute repeatedly. Unreachable
pairs contribute zero paths. The percentile includes zero-count states.
"""
quantile = Fraction(str(percentile)) / 100
if not 0 <= quantile <= 1:
raise ValueError("percentile must be between 0 and 100.")
adjacency = self._adjacency()
by_start = {}
for start, final in endpoints:
if start not in adjacency or final not in adjacency:
raise ValueError("Each start and final state must appear in the network.")
by_start.setdefault(start, Counter())[final] += 1
counts = dict.fromkeys(self.states, 0)
total = 0
for start, finals in by_start.items():
order, paths, predecessors = _shortest_paths(adjacency, start)
endings = dict.fromkeys(order, 0)
for final, count in finals.items():
if final in paths:
total += paths[final] * count
endings[final] = count
for state in reversed(order):
if state != start:
counts[state] += paths[state] * (endings[state] - finals.get(state, 0))
for previous in predecessors[state]:
endings[previous] += endings[state]
ordered = sorted(counts.values())
cutoff = Fraction(0)
if ordered:
rank = (len(ordered) - 1) * quantile
lower, remainder = divmod(rank.numerator, rank.denominator)
cutoff = Fraction(ordered[lower])
if remainder:
cutoff += Fraction(remainder, rank.denominator) * (ordered[lower + 1] - ordered[lower])
return SteppingStoneAnalysis(counts, tuple(node for node, count in counts.items() if count > cutoff), total)
def _shortest_paths(adjacency, origin):
"""Build a breadth-first DAG and count the shortest paths to each state."""
distance = {origin: 0}
paths = {origin: 1}
predecessors = {origin: []}
order = [origin]
for state in order:
depth = distance[state] + 1
for target in adjacency[state]:
if target not in distance:
distance[target] = depth
paths[target] = 0
predecessors[target] = []
order.append(target)
if distance[target] == depth:
paths[target] += paths[state]
predecessors[target].append(state)
return order, paths, predecessors
## @brief Endpoint-restricted path counts and the states passing the percentile cutoff.
[docs]
@dataclass(frozen=True)
class SteppingStoneAnalysis:
"""Store intermediate path counts by state, qualifying states, and total shortest paths."""
counts: dict
stones: tuple
shortest_paths: int
## @brief Aggregate successive states from explicit search trajectories.
# @see https://doi.org/10.1016/j.asoc.2021.107492
[docs]
def search_trajectory_network(trajectories):
"""Build a directed network from an iterable of ordered sequences of hashable states."""
states, transitions = {}, Counter()
for trajectory in trajectories:
locations = iter(trajectory)
try:
previous = next(locations)
except StopIteration:
continue
states[previous] = None
for state in locations:
states[state] = None
transitions[previous, state] += 1
previous = state
return SearchTrajectoryNetwork(tuple(states), dict(transitions))
## @brief Build a trajectory network from recorded genealogy rather than consecutive evaluations.
# @see https://doi.org/10.1007/978-3-031-89991-1_14
[docs]
def lineage_trajectory_network(runs, *, state=None, targets=None, objective=0):
"""Aggregate parent-to-child transitions across a mapping of run labels to lineage logs.
Use recorded admission cells or supply ``state(node)`` returning a
hashable location. ``None`` marks an unknown location. To restrict the
graph to stepping stones of selected elites, pass ``targets`` as a
mapping from run label to an iterable of node IDs. Supply the same state
definition and geometry for all runs. Counts preserve repeated transitions.
Record worsening on ``objective`` when both endpoints have comparable
measurements. Pass ``objective=None`` for a topology-only analysis.
"""
if not isinstance(runs, Mapping) or (targets is not None and set(targets) != set(runs)):
raise ValueError("Provide a mapping of runs and, when used, target IDs for each run.")
if objective is not None and (objective := index(objective)) < 0:
raise ValueError("objective must be nonnegative.")
states, transitions = {}, Counter()
scored, worsening = Counter(), Counter()
for label, source in runs.items():
nodes = _lineage_nodes(source)
selected = nodes if targets is None else sorted(_ancestor_ids(nodes, targets[label]))
labels = {node: nodes[node].cell if state is None else state(nodes[node]) for node in selected}
states.update(dict.fromkeys(value for value in labels.values() if value is not None))
for parent, child in _edges(nodes, selected):
origin, target = labels.get(parent), labels[child]
if origin is not None and target is not None:
transitions[origin, target] += 1
delta = _fitness_change(nodes[parent], nodes[child], objective)
if delta is not None:
scored[origin, target] += 1
if delta < 0:
worsening[origin, target] += 1
return SearchTrajectoryNetwork(tuple(states), dict(transitions), dict(scored), dict(worsening))
def _fitness_change(before, after, objective):
if objective is None:
return None
vectors = before.fitness, before.fitness_weights, after.fitness, after.fitness_weights
if any(values is None or objective >= len(values) for values in vectors):
return None
prior, prior_weight, current, weight = [values[objective] for values in vectors]
if not np.isfinite((prior, prior_weight, current, weight)).all() or not weight or not prior_weight:
return None
direction = 1 if weight > 0 else -1
if (prior_weight > 0) != (weight > 0):
return None
return direction * (current - prior)
## @brief Overlay the measured parent edges of one elite on its ancestor archive.
[docs]
def plot_ancestry_archive(source, elite, *, grid, ax=None):
"""Plot directed ancestry paths on a two-descriptor Grid or CVTGrid.
The background contains the ancestors' cell elites. The outlined focal
elite is included in the paths and excluded from the background colors.
"""
from .plots import plot_archive
nodes = ancestry(source, elite, include_elite=True)
focal = nodes.pop(elite)
if len(grid.features_domain) != 2:
raise ValueError("The ancestry overlay needs two descriptor axes.")
if focal.descriptors is None or len(focal.descriptors) != 2:
raise ValueError("The selected elite needs two recorded descriptors.")
archive = _project_ancestors(nodes, grid)
ax = plot_archive(archive, ax=ax)
nodes[elite] = focal
segments = [(nodes[parent].descriptors, nodes[child].descriptors) for parent, child in _edges(nodes, nodes)
if parent in nodes and nodes[parent].descriptors != nodes[child].descriptors]
if segments:
starts, ends = (np.asarray(points) for points in zip(*segments))
ax.quiver(*starts.T, *(ends - starts).T, angles="xy", scale_units="xy", scale=1.,
width=.005, color="#172638", alpha=.75, zorder=3)
ax.scatter(*focal.descriptors, s=100, facecolors="none", edgecolors="#ec6b28", linewidth=2, zorder=4)
ax.set_title(f"Archive paths to elite {elite}")
return ax
## @brief Draw a search trajectory network with betweenness and transition frequencies.
[docs]
def plot_stepping_stones(network, *, analysis=None, positions=None, ax=None):
"""Plot a directed trajectory network, using supplied two-dimensional positions or a circle.
Node color shows normalized betweenness, or shortest-path counts if
``analysis`` is supplied. A ring marks states classified as stepping
stones. Thicker arrows correspond to more observations. Self-loops
count in the data and are omitted from the plot.
"""
import matplotlib.pyplot as plt
from matplotlib.patches import FancyArrowPatch
if not network.states:
raise ValueError("No recorded states to plot.")
if ax is None:
ax = plt.figure(figsize=(6, 5), layout="constrained").add_subplot()
if positions is None:
angle = np.linspace(0., 2 * np.pi, len(network.states), endpoint=False)
positions = dict(zip(network.states, zip(np.cos(angle), np.sin(angle))))
coords = np.asarray([positions[state] for state in network.states], dtype=float)
if coords.shape != (len(network.states), 2) or not np.isfinite(coords).all():
raise ValueError("Provide two finite coordinates per state.")
max_count = max((n for (a, b), n in network.transitions.items() if a != b), default=1)
for (origin, target), count in network.transitions.items():
if origin == target:
continue
arrow = FancyArrowPatch(positions[origin], positions[target], arrowstyle="-|>", mutation_scale=10,
shrinkA=6, shrinkB=7, connectionstyle="arc3,rad=.13",
color="#576578", linewidth=.5 + 2. * count / max_count, alpha=.65)
ax.add_patch(arrow)
scores = network.betweenness() if analysis is None else analysis.counts
scatter = ax.scatter(*coords.T, c=[scores[state] for state in network.states], cmap="plasma",
s=62, linewidth=.5, edgecolors="#172638", zorder=3)
label = "Betweenness centrality" if analysis is None else "Paths through state"
ax.figure.colorbar(scatter, ax=ax, label=label)
if analysis is not None and analysis.stones:
stones = [positions[state] for state in analysis.stones]
ax.scatter(*zip(*stones), s=125, facecolors="none", edgecolors="#ef6c37", linewidths=1.6, zorder=4)
ax.set_aspect("equal")
ax.margins(.12)
ax.set_title("Search trajectory network")
return ax