Skip to content

Elite Archive (CPU)

The MAP-Elites survey over tree space. run_archive fills the archive niche by niche and halts by the halt rule of the driver. EliteArchive holds the elites and renders coordinates, surfaces, and dataframes.

run_archive

run_archive(r1: HifukuTree, r2: HifukuTree, r3: HifukuTree, alignment, model, start_trees, triangle: AnchorTriangle, taxon_table: TaxonTable, *, monitor=False, **overrides) -> ArchiveResult

Run a CPU elite-archive survey for one alignment.

The three anchor trees fix the chart. The archive is seeded with the anchors and the start trees. The survey then repeats a pass: select a random occupied niche, vary its elite, evaluate the offspring fitness and niche, and place it. Fitness is the alignment log-likelihood.

This function builds a :class:~hifuku.cpu_backend.CpuBackend and gives it to :func:~hifuku.driver.run_survey. The loop and the halt rule are in the driver, which the GPU survey also uses. One rule then has one implementation.

The survey runs batch variations between two checkpoints, up to n_iters. When converge is set, it halts by halt_rule. The QD-score rule, the default, halts when a doubling of effort multiplies the QD-score of the archive by 2**qd_tau or less. The rate rule halts when the trailing-window coverage rate and precision rate both fall to or below their thresholds. force_full_run turns the halt off.

Parameters:

Name Type Description Default
r1 HifukuTree

Anchor trees that fix the chart. Used only for CV distances.

required
r2 HifukuTree

Anchor trees that fix the chart. Used only for CV distances.

required
r3 HifukuTree

Anchor trees that fix the chart. Used only for CV distances.

required
alignment

The alignment surveyed and its substitution model.

required
model

The alignment surveyed and its substitution model.

required
start_trees list[HifukuTree]

Extra seed trees, normally the anchor tree for the surveyed gene.

required
triangle AnchorTriangle

Anchor geometry. It carries the chart metric.

required
taxon_table TaxonTable

Shared namespace.

required
monitor (callable, None or False)

A checkpoint callback. False, the default, reports nothing. None selects the default reporter. See :mod:hifuku.monitor.

False
**overrides

Any field of :class:~hifuku.params.ArchiveParams, which documents them. They are stated here rather than redeclared, so this entry point carries no second copy of a default that could disagree with the first. A name no parameter class declares raises, naming what is accepted. See :func:~hifuku.params.split_overrides.

{}

Returns:

Type Description
ArchiveResult

The archive, its per-checkpoint history, and the halt state.

Source code in src/hifuku/archive.py
def run_archive(
    r1: HifukuTree,
    r2: HifukuTree,
    r3: HifukuTree,
    alignment,
    model,
    start_trees,
    triangle: AnchorTriangle,
    taxon_table: TaxonTable,
    *,
    monitor=False,
    **overrides,
) -> ArchiveResult:
    """Run a CPU elite-archive survey for one alignment.

    The three anchor trees fix the chart.  The archive is seeded with the anchors
    and the start trees.  The survey then repeats a pass: select a random
    occupied niche, vary its elite, evaluate the offspring fitness and niche, and
    place it.  Fitness is the alignment log-likelihood.

    This function builds a :class:`~hifuku.cpu_backend.CpuBackend` and gives it
    to :func:`~hifuku.driver.run_survey`.  The loop and the halt rule are in the
    driver, which the GPU survey also uses.  One rule then has one
    implementation.

    The survey runs ``batch`` variations between two checkpoints, up to
    ``n_iters``.  When ``converge`` is set, it halts by ``halt_rule``.  The
    QD-score rule, the default, halts when a doubling of effort multiplies
    the QD-score of the archive by ``2**qd_tau`` or less.  The rate rule halts
    when the trailing-window coverage rate and precision rate both fall to or
    below their thresholds.  ``force_full_run`` turns the halt off.

    Parameters
    ----------
    r1, r2, r3 : HifukuTree
        Anchor trees that fix the chart.  Used only for CV distances.
    alignment, model
        The alignment surveyed and its substitution model.
    start_trees : list[HifukuTree]
        Extra seed trees, normally the anchor tree for the surveyed gene.
    triangle : AnchorTriangle
        Anchor geometry.  It carries the chart metric.
    taxon_table : TaxonTable
        Shared namespace.
    monitor : callable, None or False
        A checkpoint callback.  False, the default, reports nothing.  None
        selects the default reporter.  See :mod:`hifuku.monitor`.
    **overrides
        Any field of :class:`~hifuku.params.ArchiveParams`, which documents
        them.  They are stated here rather than redeclared, so this entry point
        carries no second copy of a default that could disagree with the first.
        A name no parameter class declares raises, naming what is accepted.
        See :func:`~hifuku.params.split_overrides`.

    Returns
    -------
    ArchiveResult
        The archive, its per-checkpoint history, and the halt state.
    """
    from hifuku.cpu_backend import CpuBackend
    from hifuku.driver import run_survey
    from hifuku.params import ArchiveParams, split_overrides

    backend = CpuBackend()
    survey_overrides, device_overrides = split_overrides(overrides)
    if device_overrides:
        named = ", ".join(sorted(device_overrides))
        raise ValueError(
            f"{named} sizes a device allocation, and this is the host survey. "
            f"Use run_archive_gpu to run on a device.")
    params = ArchiveParams.resolve(backend.caps.defaults, survey_overrides)
    ctx = RunContext(anchors=(r1, r2, r3), alignment=alignment, model=model,
                     start_trees=list(start_trees), triangle=triangle,
                     taxon_table=taxon_table)
    return run_survey(backend, ctx, params, monitor=monitor)

EliteArchive dataclass

A map from niche to elite over an unbounded 2D chart grid.

A niche is a square cell of side cell, indexed by integer coordinates (i, j) from origin. The grid has no window: any chart point has a niche. Exploration is bounded by the log-likelihood gate in the survey, not by the grid, and the filled niches form the map's footprint.

A niche holds one tree. Its coordinates hold a fiber. A distance reads only the splits two trees share and the lengths on them, so two trees land on one chart point when those agree against all three anchors, however the trees differ elsewhere. Sharing a taxon set is necessary for the comparison to be defined and is not sufficient: two trees over the same taxa separate as soon as a shared split or one of its lengths differs.

The map from a tree to its coordinates is therefore many-to-one. One family that sits over a single point is the placements of the taxa an anchor does not carry, when the placement leaves the paths between shared taxa alone: 2 ** k times a rising factorial in the shared count, for k unshared taxa. That direction is one the metric does not measure, so no cell width separates a fiber and narrowing the grid does not help.

The one tree a niche keeps is the best member of its fiber the survey has found, because the log-likelihood reads every taxon and does separate them. Two consequences for reading a survey. A coverage count counts occupied coordinates, not distinct trees. And a variation that moves a tree along its fiber can improve the elite without filling a niche, so it shows in the precision rate and not in the coverage rate.

Derived in docs/theory/algebra/kuhner1994-robinson1981-cell-resonance.py, step 9.

anchors (an AnchorTriangle), taxon_table, and metric hold the context the archive was built against. The accessors fall back to anchors when their argument is omitted. :meth:locate uses all three to place a new tree in the same frame as the map. A later re-anchoring step can use the anchors to stitch archives on different anchor planes into one frame.

Source code in src/hifuku/archive.py
@dataclass
class EliteArchive:
    """A map from niche to elite over an unbounded 2D chart grid.

    A niche is a square cell of side ``cell``, indexed by integer coordinates
    ``(i, j)`` from ``origin``.  The grid has no window: any chart point has a
    niche.  Exploration is bounded by the log-likelihood gate in the survey, not
    by the grid, and the filled niches form the map's footprint.

    A niche holds one tree.  Its coordinates hold a fiber.  A distance reads only
    the splits two trees share and the lengths on them, so two trees land on one
    chart point when those agree against all three anchors, however the trees
    differ elsewhere.  Sharing a taxon set is necessary for the comparison to be
    defined and is not sufficient: two trees over the same taxa separate as soon
    as a shared split or one of its lengths differs.

    The map from a tree to its coordinates is therefore many-to-one.  One family
    that sits over a single point is the placements of the taxa an anchor does
    not carry, when the placement leaves the paths between shared taxa alone:
    ``2 ** k`` times a rising factorial in the shared count, for ``k`` unshared
    taxa.  That direction is one the metric does not measure, so no cell width
    separates a fiber and narrowing the grid does not help.

    The one tree a niche keeps is the best member of its fiber the survey has
    found, because the log-likelihood reads every taxon and does separate them.
    Two consequences for reading a survey.  A coverage count counts occupied
    coordinates, not distinct trees.  And a variation that moves a tree along its
    fiber can improve the elite without filling a niche, so it shows in the
    precision rate and not in the coverage rate.

    Derived in docs/theory/algebra/kuhner1994-robinson1981-cell-resonance.py,
    step 9.

    ``anchors`` (an ``AnchorTriangle``), ``taxon_table``, and ``metric`` hold the
    context the archive was built against.  The accessors fall back to ``anchors``
    when their argument is omitted.  :meth:`locate` uses all three to place a new
    tree in the same frame as the map.  A later re-anchoring step can use the
    anchors to stitch archives on different anchor planes into one frame.
    """

    cell: float = ARCHIVE_CELL
    origin: float = 0.0
    anchors: object = field(default=None, repr=False)      # the AnchorTriangle used
    taxon_table: object = field(default=None, repr=False)  # namespace for locate()
    metric: object = field(default=None, repr=False)       # tree metric used
    tree_source: object = field(default=None, repr=False)   # dict (i,j) -> newick, for loaded archives
    elites: dict = field(default_factory=dict)   # (i, j) -> Elite
    keys: list = field(default_factory=list)     # occupied niches, insertion order
    #: Niches the archive had no room for, and the room it had.  A device
    #: archive holds its elites in a pool of fixed capacity, and a survey that
    #: reaches more niches than that drops the rest rather than failing: what it
    #: found is still a survey of the region it covered, and losing hours of run
    #: to an exception is worse than finishing with the limit recorded.  The
    #: host archive is a dictionary and never fills, so both stay zero there.
    #: A capacity of zero means nobody recorded one.
    n_dropped: int = 0
    capacity: int = 0
    #: The leaf order every tree this archive holds is numbered in, which is the
    #: survey's shared order: the seed tree's own.  ``None`` leaves trees as
    #: they arrive, which is what an archive assembled by hand in a test wants.
    #: See :func:`~hifuku.tree_io.canonical`.
    leaf_order: object = None
    #: The newick text of each elite that has been written, by niche.  The
    #: result digest and the survey file both read every elite as text, and
    #: writing a tree of a few thousand taxa costs a few milliseconds.
    _newick: dict = field(default_factory=dict, init=False, repr=False,
                          compare=False)

    @property
    def n_filled(self) -> int:
        return len(self.elites)

    @property
    def saturated(self) -> bool:
        """True when the archive ran out of room and dropped niches."""
        return self.n_dropped > 0

    def tree_at(self, key):
        """Return the elite tree at niche ``key``, parsing its stored newick on
        first access.  For a live archive the tree is already present; for a
        loaded archive it is materialized from ``tree_source`` and cached."""
        elite = self.elites[key]
        if elite.tree is not None:
            return elite.tree
        if self.tree_source is None or key not in self.tree_source:
            raise KeyError(f"no tree available for niche {key}")
        from hifuku.tree_io import canonical, read_tree
        t = read_tree(self.tree_source[key], self.taxon_table, from_string=True)
        # Newick records names and not indices, so the reader numbers the tree
        # as it parses.  Canonical form is what the archive holds, so a tree
        # materialized from storage is put back into it rather than arriving in
        # whatever order the text implied.
        if self.leaf_order is not None:
            t = canonical(t, self.leaf_order)
        _set_global_leaf_indices(t, self.taxon_table)
        elite.tree = t
        return t

    def newick_at(self, key) -> str:
        """Return the newick text of the elite at niche ``key``.

        An archive read from a file holds the text of each elite, so this
        returns that text and does not parse the tree.  For a live elite, this
        writes the tree once and keeps the text.  Placing a new elite in the
        niche removes both, so the text always describes the elite that the
        niche holds.

        The text of a tree does not depend on its node numbering, because the
        writer follows the child links from the root.  So the stored text and
        the text of the tree parsed from it are the same.
        """
        text = self._newick.get(key)
        if text is not None:
            return text
        if self.tree_source is not None and key in self.tree_source:
            return self.tree_source[key]
        text = self.tree_at(key).as_newick()
        self._newick[key] = text
        return text

    def trees(self):
        """Iterate ``((i, j), HifukuTree)`` over all elites, parsing lazily."""
        for key in self.keys:
            yield key, self.tree_at(key)

    def niche_of(self, lam1: float, lam2: float):
        """Return the ``(i, j)`` niche of a chart point.  Unbounded: never None."""
        i = int(np.floor((lam1 - self.origin) / self.cell))
        j = int(np.floor((lam2 - self.origin) / self.cell))
        return (i, j)

    def niche_center(self, key):
        """Chart coordinates ``(lam1, lam2)`` of a niche's center."""
        i, j = key
        return (self.origin + (i + 0.5) * self.cell,
                self.origin + (j + 0.5) * self.cell)

    def place(self, key, elite: Elite) -> bool:
        """Store the elite when its niche is empty or the elite is better.

        A stored tree is put into canonical form first, when the archive knows
        the leaf order to use.  That is the archive's invariant: what it holds
        is numbered as a function of the tree, so it can be written to a file,
        read back and continued.  A walk numbers nodes however its moves leave
        them, which is a property of the path taken rather than of the tree.
        """
        cur = self.elites.get(key)
        if cur is None:
            self._store(key, elite)
            self.keys.append(key)
            return True
        if elite.logL > cur.logL:
            self._store(key, elite)
            return True
        return False

    def place_batch(self, items, outcomes: bool = False):
        """Merge a batch of candidates and return ``(n_new, gain)``.

        ``items`` is a sequence of ``(key, Elite)``.  The method reduces the
        batch to one winner per niche, then compares each winner against the
        incumbent.  ``n_new`` counts the niches that were empty.  ``gain`` sums
        the improvement of each winner over its incumbent.  A new niche adds no
        gain.

        The tie rules follow the device place in ``gpu_archive``, which packs a
        fitness in the high bits and a slot index in the low bits, then takes an
        atomic maximum.  The incumbent holds the largest slot, so it wins a tie
        against a candidate.  Among candidates of equal fitness, the last one
        wins.

        One call with one candidate gives the same result as :meth:`place`, so
        a one-walker run reproduces a sequential run.

        When ``outcomes`` is true, the method returns ``(n_new, gain,
        outcomes)`` instead.  ``outcomes`` is a list of ``(code, gain)``
        pairs, one per item of ``items``, in input order.

        - Code 0: the item placed nothing.  Another candidate won its niche
          in this batch, or the batch winner did not beat the incumbent.
        - Code 1: the item filled an empty niche.
        - Code 2: the item improved an incumbent.  ``gain`` holds the
          improvement.
        """
        winners: dict = {}
        winner_pos: dict = {}
        for pos, (key, elite) in enumerate(items):
            best = winners.get(key)
            if best is None or elite.logL >= best.logL:
                winners[key] = elite
                winner_pos[key] = pos

        n_new, gain = 0, 0.0
        codes = [0] * len(items) if outcomes else None
        item_gains = [0.0] * len(items) if outcomes else None
        for key, elite in winners.items():
            cur = self.elites.get(key)
            if cur is None:
                self._store(key, elite)
                self.keys.append(key)
                n_new += 1
                if outcomes:
                    codes[winner_pos[key]] = 1
            elif elite.logL > cur.logL:
                item_gain = elite.logL - cur.logL
                gain += item_gain
                self._store(key, elite)
                if outcomes:
                    codes[winner_pos[key]] = 2
                    item_gains[winner_pos[key]] = item_gain
        if outcomes:
            return n_new, gain, list(zip(codes, item_gains))
        return n_new, gain

    def _store(self, key, elite: Elite) -> None:
        """Put one elite in a niche, in canonical form.

        Every route into the archive goes through here, so that what the archive
        holds is numbered as a function of the tree and not of the path the walk
        took to reach it.  A survey draws its next parent from what this stored,
        so the canonical form is what the walk continues from, and a survey
        carried on from a saved archive walks from the same trees as one that
        was never stopped.
        """
        if self.leaf_order is not None and elite.tree is not None:
            from hifuku.tree_io import canonical
            elite = Elite(logL=elite.logL,
                          tree=canonical(elite.tree, self.leaf_order),
                          z=elite.z)
        # The text of the elite this one displaces no longer describes the
        # niche, whether it was written here or read from a file.
        self._newick.pop(key, None)
        if self.tree_source is not None:
            self.tree_source.pop(key, None)
        self.elites[key] = elite

    def best_logL(self) -> float:
        """The largest finite log-likelihood held, or -inf if none is.

        Non-finite values are skipped rather than compared.  ``max`` keeps the
        first item a comparison cannot beat, so a NaN in the sequence returns
        either itself or its neighbor depending on where it sits, which would
        make the answer a function of insertion order.
        """
        return max((elite.logL for elite in self.elites.values()
                    if math.isfinite(elite.logL)),
                   default=float("-inf"))

    def index_bounds(self):
        """``(i_min, i_max, j_min, j_max)`` over filled niches, or None if empty."""
        if not self.elites:
            return None
        iis = [k[0] for k in self.elites]
        jjs = [k[1] for k in self.elites]
        return (min(iis), max(iis), min(jjs), max(jjs))

    def filled_bounds(self):
        """Chart bounding box ``(lam1_lo, lam1_hi, lam2_lo, lam2_hi)`` of the
        filled niches, or None if empty."""
        b = self.index_bounds()
        if b is None:
            return None
        i0, i1, j0, j1 = b
        return (self.origin + i0 * self.cell, self.origin + (i1 + 1) * self.cell,
                self.origin + j0 * self.cell, self.origin + (j1 + 1) * self.cell)

    def elevation_grid(self) -> np.ma.MaskedArray:
        """Elite log-likelihood over the filled bounding box, a masked array."""
        b = self.index_bounds()
        if b is None:
            return np.ma.masked_all((1, 1))
        i0, i1, j0, j1 = b
        g = np.full((i1 - i0 + 1, j1 - j0 + 1), np.nan)
        for (i, j), elite in self.elites.items():
            g[i - i0, j - j0] = elite.logL
        return np.ma.masked_invalid(g)

    # -- accessors for downstream analysis and plotting -------------------
    # hifuku computes; the caller plots.  These return plain arrays and
    # dataframes in barycentric or Cartesian coordinates.

    def points(self, coords: str = "barycentric", anchors=None):
        """Scattered elite points as ``(x, y, logL, z)`` arrays.

        ``coords="barycentric"`` returns the niche centers ``(lam1, lam2)``;
        ``coords="cartesian"`` maps them through the anchor triangle into the
        Euclidean chart plane.  ``anchors`` defaults to the archive's stored
        ``anchors``; a cartesian request with neither is an error.
        """
        from hifuku.utils import barycentric_to_cartesian
        if anchors is None:
            anchors = self.anchors
        keys = list(self.elites)
        lam1 = np.array([self.origin + (k[0] + 0.5) * self.cell for k in keys])
        lam2 = np.array([self.origin + (k[1] + 0.5) * self.cell for k in keys])
        logL = np.array([self.elites[k].logL for k in keys])
        z = np.array([self.elites[k].z for k in keys])
        if coords == "barycentric":
            return lam1, lam2, logL, z
        if coords == "cartesian":
            if anchors is None:
                raise ValueError("cartesian coords require anchors")
            x, y = barycentric_to_cartesian(lam1, lam2, anchors)
            return x, y, logL, z
        raise ValueError(f"coords must be 'barycentric' or 'cartesian', got {coords!r}")

    def records(self, coords: str = "barycentric", anchors=None) -> np.ndarray:
        """Scattered elevation records as an ``(N, 3)`` array.

        Each row is one elite ``(coord1, coord2, logL)``, in barycentric
        ``(lam1, lam2, logL)`` or Cartesian ``(x, y, logL)`` coordinates per
        ``coords``.  Unlike :meth:`surface`, this does no interpolation; it hands
        the raw scattered records to a plotting utility that triangulates them,
        for example ``ax.tricontourf(*archive.records(coords="cartesian",
        anchors=tri).T)``.
        """
        c1, c2, logL, _z = self.points(coords=coords, anchors=anchors)
        return np.column_stack([c1, c2, logL])

    def locate(self, tree, coords: str = "barycentric"):
        """Return the chart coordinates of a tree as ``(x, y, z)``.

        This method places ``tree`` in the same frame as the map.  It uses the
        archive's own anchors, taxon table, and metric.  A feature tree, such as
        the maximum-likelihood tree or a ufboot replicate, lands where it belongs
        on the map.  ``coords`` is "barycentric" or "cartesian".  ``z`` is the
        out-of-plane residual.
        """
        if self.anchors is None or self.taxon_table is None:
            raise ValueError(
                "archive lacks anchors or taxon_table; build it with "
                "run_archive or run_archive_gpu"
            )
        return locate_tree(tree, self.taxon_table, self.anchors, coords)

    def frame(self, anchors=None, backend: str = "pandas"):
        """Tidy dataframe of the elites (niche indices, coordinates, logL, z).

        Includes Cartesian ``x``, ``y`` columns when ``anchors`` is given or the
        archive has stored ``anchors``.
        """
        from hifuku.utils import elite_frame
        if anchors is None:
            anchors = self.anchors
        return elite_frame(self, anchors=anchors, backend=backend)

    def surface(self, n: int = 200, coords: str = "barycentric",
                anchors=None, radius=None, z_scale=None):
        """Interpolated elevation surface as ``(X, Y, Z)`` meshgrids.

        Shepard-interpolates the elite log-likelihoods over a regular ``n`` by
        ``n`` grid spanning the filled region, in barycentric or Cartesian
        coordinates.  ``Z`` is masked beyond the support radius.  The result is a
        plain gridded field: it drops into ``ax.contourf(X, Y, Z)``,
        ``ax.pcolormesh(X, Y, Z)``, ``ax.plot_surface(X, Y, Z)``, and the like.
        """
        from hifuku.utils import shepard_grid
        if self.n_filled == 0:
            raise ValueError("empty archive")
        px, py, logL, z = self.points(coords=coords, anchors=anchors)
        xs = np.linspace(px.min(), px.max(), n)
        ys = np.linspace(py.min(), py.max(), n)
        X, Y = np.meshgrid(xs, ys)
        Z = shepard_grid(np.column_stack([px, py]), logL, X, Y,
                         radius=radius, z=(z if z_scale else None), z_scale=z_scale)
        return X, Y, Z

saturated property

saturated: bool

True when the archive ran out of room and dropped niches.

tree_at

tree_at(key)

Return the elite tree at niche key, parsing its stored newick on first access. For a live archive the tree is already present; for a loaded archive it is materialized from tree_source and cached.

Source code in src/hifuku/archive.py
def tree_at(self, key):
    """Return the elite tree at niche ``key``, parsing its stored newick on
    first access.  For a live archive the tree is already present; for a
    loaded archive it is materialized from ``tree_source`` and cached."""
    elite = self.elites[key]
    if elite.tree is not None:
        return elite.tree
    if self.tree_source is None or key not in self.tree_source:
        raise KeyError(f"no tree available for niche {key}")
    from hifuku.tree_io import canonical, read_tree
    t = read_tree(self.tree_source[key], self.taxon_table, from_string=True)
    # Newick records names and not indices, so the reader numbers the tree
    # as it parses.  Canonical form is what the archive holds, so a tree
    # materialized from storage is put back into it rather than arriving in
    # whatever order the text implied.
    if self.leaf_order is not None:
        t = canonical(t, self.leaf_order)
    _set_global_leaf_indices(t, self.taxon_table)
    elite.tree = t
    return t

newick_at

newick_at(key) -> str

Return the newick text of the elite at niche key.

An archive read from a file holds the text of each elite, so this returns that text and does not parse the tree. For a live elite, this writes the tree once and keeps the text. Placing a new elite in the niche removes both, so the text always describes the elite that the niche holds.

The text of a tree does not depend on its node numbering, because the writer follows the child links from the root. So the stored text and the text of the tree parsed from it are the same.

Source code in src/hifuku/archive.py
def newick_at(self, key) -> str:
    """Return the newick text of the elite at niche ``key``.

    An archive read from a file holds the text of each elite, so this
    returns that text and does not parse the tree.  For a live elite, this
    writes the tree once and keeps the text.  Placing a new elite in the
    niche removes both, so the text always describes the elite that the
    niche holds.

    The text of a tree does not depend on its node numbering, because the
    writer follows the child links from the root.  So the stored text and
    the text of the tree parsed from it are the same.
    """
    text = self._newick.get(key)
    if text is not None:
        return text
    if self.tree_source is not None and key in self.tree_source:
        return self.tree_source[key]
    text = self.tree_at(key).as_newick()
    self._newick[key] = text
    return text

trees

trees()

Iterate ((i, j), HifukuTree) over all elites, parsing lazily.

Source code in src/hifuku/archive.py
def trees(self):
    """Iterate ``((i, j), HifukuTree)`` over all elites, parsing lazily."""
    for key in self.keys:
        yield key, self.tree_at(key)

niche_of

niche_of(lam1: float, lam2: float)

Return the (i, j) niche of a chart point. Unbounded: never None.

Source code in src/hifuku/archive.py
def niche_of(self, lam1: float, lam2: float):
    """Return the ``(i, j)`` niche of a chart point.  Unbounded: never None."""
    i = int(np.floor((lam1 - self.origin) / self.cell))
    j = int(np.floor((lam2 - self.origin) / self.cell))
    return (i, j)

niche_center

niche_center(key)

Chart coordinates (lam1, lam2) of a niche's center.

Source code in src/hifuku/archive.py
def niche_center(self, key):
    """Chart coordinates ``(lam1, lam2)`` of a niche's center."""
    i, j = key
    return (self.origin + (i + 0.5) * self.cell,
            self.origin + (j + 0.5) * self.cell)

place

place(key, elite: Elite) -> bool

Store the elite when its niche is empty or the elite is better.

A stored tree is put into canonical form first, when the archive knows the leaf order to use. That is the archive's invariant: what it holds is numbered as a function of the tree, so it can be written to a file, read back and continued. A walk numbers nodes however its moves leave them, which is a property of the path taken rather than of the tree.

Source code in src/hifuku/archive.py
def place(self, key, elite: Elite) -> bool:
    """Store the elite when its niche is empty or the elite is better.

    A stored tree is put into canonical form first, when the archive knows
    the leaf order to use.  That is the archive's invariant: what it holds
    is numbered as a function of the tree, so it can be written to a file,
    read back and continued.  A walk numbers nodes however its moves leave
    them, which is a property of the path taken rather than of the tree.
    """
    cur = self.elites.get(key)
    if cur is None:
        self._store(key, elite)
        self.keys.append(key)
        return True
    if elite.logL > cur.logL:
        self._store(key, elite)
        return True
    return False

place_batch

place_batch(items, outcomes: bool = False)

Merge a batch of candidates and return (n_new, gain).

items is a sequence of (key, Elite). The method reduces the batch to one winner per niche, then compares each winner against the incumbent. n_new counts the niches that were empty. gain sums the improvement of each winner over its incumbent. A new niche adds no gain.

The tie rules follow the device place in gpu_archive, which packs a fitness in the high bits and a slot index in the low bits, then takes an atomic maximum. The incumbent holds the largest slot, so it wins a tie against a candidate. Among candidates of equal fitness, the last one wins.

One call with one candidate gives the same result as :meth:place, so a one-walker run reproduces a sequential run.

When outcomes is true, the method returns (n_new, gain, outcomes) instead. outcomes is a list of (code, gain) pairs, one per item of items, in input order.

  • Code 0: the item placed nothing. Another candidate won its niche in this batch, or the batch winner did not beat the incumbent.
  • Code 1: the item filled an empty niche.
  • Code 2: the item improved an incumbent. gain holds the improvement.
Source code in src/hifuku/archive.py
def place_batch(self, items, outcomes: bool = False):
    """Merge a batch of candidates and return ``(n_new, gain)``.

    ``items`` is a sequence of ``(key, Elite)``.  The method reduces the
    batch to one winner per niche, then compares each winner against the
    incumbent.  ``n_new`` counts the niches that were empty.  ``gain`` sums
    the improvement of each winner over its incumbent.  A new niche adds no
    gain.

    The tie rules follow the device place in ``gpu_archive``, which packs a
    fitness in the high bits and a slot index in the low bits, then takes an
    atomic maximum.  The incumbent holds the largest slot, so it wins a tie
    against a candidate.  Among candidates of equal fitness, the last one
    wins.

    One call with one candidate gives the same result as :meth:`place`, so
    a one-walker run reproduces a sequential run.

    When ``outcomes`` is true, the method returns ``(n_new, gain,
    outcomes)`` instead.  ``outcomes`` is a list of ``(code, gain)``
    pairs, one per item of ``items``, in input order.

    - Code 0: the item placed nothing.  Another candidate won its niche
      in this batch, or the batch winner did not beat the incumbent.
    - Code 1: the item filled an empty niche.
    - Code 2: the item improved an incumbent.  ``gain`` holds the
      improvement.
    """
    winners: dict = {}
    winner_pos: dict = {}
    for pos, (key, elite) in enumerate(items):
        best = winners.get(key)
        if best is None or elite.logL >= best.logL:
            winners[key] = elite
            winner_pos[key] = pos

    n_new, gain = 0, 0.0
    codes = [0] * len(items) if outcomes else None
    item_gains = [0.0] * len(items) if outcomes else None
    for key, elite in winners.items():
        cur = self.elites.get(key)
        if cur is None:
            self._store(key, elite)
            self.keys.append(key)
            n_new += 1
            if outcomes:
                codes[winner_pos[key]] = 1
        elif elite.logL > cur.logL:
            item_gain = elite.logL - cur.logL
            gain += item_gain
            self._store(key, elite)
            if outcomes:
                codes[winner_pos[key]] = 2
                item_gains[winner_pos[key]] = item_gain
    if outcomes:
        return n_new, gain, list(zip(codes, item_gains))
    return n_new, gain

best_logL

best_logL() -> float

The largest finite log-likelihood held, or -inf if none is.

Non-finite values are skipped rather than compared. max keeps the first item a comparison cannot beat, so a NaN in the sequence returns either itself or its neighbor depending on where it sits, which would make the answer a function of insertion order.

Source code in src/hifuku/archive.py
def best_logL(self) -> float:
    """The largest finite log-likelihood held, or -inf if none is.

    Non-finite values are skipped rather than compared.  ``max`` keeps the
    first item a comparison cannot beat, so a NaN in the sequence returns
    either itself or its neighbor depending on where it sits, which would
    make the answer a function of insertion order.
    """
    return max((elite.logL for elite in self.elites.values()
                if math.isfinite(elite.logL)),
               default=float("-inf"))

index_bounds

index_bounds()

(i_min, i_max, j_min, j_max) over filled niches, or None if empty.

Source code in src/hifuku/archive.py
def index_bounds(self):
    """``(i_min, i_max, j_min, j_max)`` over filled niches, or None if empty."""
    if not self.elites:
        return None
    iis = [k[0] for k in self.elites]
    jjs = [k[1] for k in self.elites]
    return (min(iis), max(iis), min(jjs), max(jjs))

filled_bounds

filled_bounds()

Chart bounding box (lam1_lo, lam1_hi, lam2_lo, lam2_hi) of the filled niches, or None if empty.

Source code in src/hifuku/archive.py
def filled_bounds(self):
    """Chart bounding box ``(lam1_lo, lam1_hi, lam2_lo, lam2_hi)`` of the
    filled niches, or None if empty."""
    b = self.index_bounds()
    if b is None:
        return None
    i0, i1, j0, j1 = b
    return (self.origin + i0 * self.cell, self.origin + (i1 + 1) * self.cell,
            self.origin + j0 * self.cell, self.origin + (j1 + 1) * self.cell)

elevation_grid

elevation_grid() -> np.ma.MaskedArray

Elite log-likelihood over the filled bounding box, a masked array.

Source code in src/hifuku/archive.py
def elevation_grid(self) -> np.ma.MaskedArray:
    """Elite log-likelihood over the filled bounding box, a masked array."""
    b = self.index_bounds()
    if b is None:
        return np.ma.masked_all((1, 1))
    i0, i1, j0, j1 = b
    g = np.full((i1 - i0 + 1, j1 - j0 + 1), np.nan)
    for (i, j), elite in self.elites.items():
        g[i - i0, j - j0] = elite.logL
    return np.ma.masked_invalid(g)

points

points(coords: str = 'barycentric', anchors=None)

Scattered elite points as (x, y, logL, z) arrays.

coords="barycentric" returns the niche centers (lam1, lam2); coords="cartesian" maps them through the anchor triangle into the Euclidean chart plane. anchors defaults to the archive's stored anchors; a cartesian request with neither is an error.

Source code in src/hifuku/archive.py
def points(self, coords: str = "barycentric", anchors=None):
    """Scattered elite points as ``(x, y, logL, z)`` arrays.

    ``coords="barycentric"`` returns the niche centers ``(lam1, lam2)``;
    ``coords="cartesian"`` maps them through the anchor triangle into the
    Euclidean chart plane.  ``anchors`` defaults to the archive's stored
    ``anchors``; a cartesian request with neither is an error.
    """
    from hifuku.utils import barycentric_to_cartesian
    if anchors is None:
        anchors = self.anchors
    keys = list(self.elites)
    lam1 = np.array([self.origin + (k[0] + 0.5) * self.cell for k in keys])
    lam2 = np.array([self.origin + (k[1] + 0.5) * self.cell for k in keys])
    logL = np.array([self.elites[k].logL for k in keys])
    z = np.array([self.elites[k].z for k in keys])
    if coords == "barycentric":
        return lam1, lam2, logL, z
    if coords == "cartesian":
        if anchors is None:
            raise ValueError("cartesian coords require anchors")
        x, y = barycentric_to_cartesian(lam1, lam2, anchors)
        return x, y, logL, z
    raise ValueError(f"coords must be 'barycentric' or 'cartesian', got {coords!r}")

records

records(coords: str = 'barycentric', anchors=None) -> np.ndarray

Scattered elevation records as an (N, 3) array.

Each row is one elite (coord1, coord2, logL), in barycentric (lam1, lam2, logL) or Cartesian (x, y, logL) coordinates per coords. Unlike :meth:surface, this does no interpolation; it hands the raw scattered records to a plotting utility that triangulates them, for example ax.tricontourf(*archive.records(coords="cartesian", anchors=tri).T).

Source code in src/hifuku/archive.py
def records(self, coords: str = "barycentric", anchors=None) -> np.ndarray:
    """Scattered elevation records as an ``(N, 3)`` array.

    Each row is one elite ``(coord1, coord2, logL)``, in barycentric
    ``(lam1, lam2, logL)`` or Cartesian ``(x, y, logL)`` coordinates per
    ``coords``.  Unlike :meth:`surface`, this does no interpolation; it hands
    the raw scattered records to a plotting utility that triangulates them,
    for example ``ax.tricontourf(*archive.records(coords="cartesian",
    anchors=tri).T)``.
    """
    c1, c2, logL, _z = self.points(coords=coords, anchors=anchors)
    return np.column_stack([c1, c2, logL])

locate

locate(tree, coords: str = 'barycentric')

Return the chart coordinates of a tree as (x, y, z).

This method places tree in the same frame as the map. It uses the archive's own anchors, taxon table, and metric. A feature tree, such as the maximum-likelihood tree or a ufboot replicate, lands where it belongs on the map. coords is "barycentric" or "cartesian". z is the out-of-plane residual.

Source code in src/hifuku/archive.py
def locate(self, tree, coords: str = "barycentric"):
    """Return the chart coordinates of a tree as ``(x, y, z)``.

    This method places ``tree`` in the same frame as the map.  It uses the
    archive's own anchors, taxon table, and metric.  A feature tree, such as
    the maximum-likelihood tree or a ufboot replicate, lands where it belongs
    on the map.  ``coords`` is "barycentric" or "cartesian".  ``z`` is the
    out-of-plane residual.
    """
    if self.anchors is None or self.taxon_table is None:
        raise ValueError(
            "archive lacks anchors or taxon_table; build it with "
            "run_archive or run_archive_gpu"
        )
    return locate_tree(tree, self.taxon_table, self.anchors, coords)

frame

frame(anchors=None, backend: str = 'pandas')

Tidy dataframe of the elites (niche indices, coordinates, logL, z).

Includes Cartesian x, y columns when anchors is given or the archive has stored anchors.

Source code in src/hifuku/archive.py
def frame(self, anchors=None, backend: str = "pandas"):
    """Tidy dataframe of the elites (niche indices, coordinates, logL, z).

    Includes Cartesian ``x``, ``y`` columns when ``anchors`` is given or the
    archive has stored ``anchors``.
    """
    from hifuku.utils import elite_frame
    if anchors is None:
        anchors = self.anchors
    return elite_frame(self, anchors=anchors, backend=backend)

surface

surface(n: int = 200, coords: str = 'barycentric', anchors=None, radius=None, z_scale=None)

Interpolated elevation surface as (X, Y, Z) meshgrids.

Shepard-interpolates the elite log-likelihoods over a regular n by n grid spanning the filled region, in barycentric or Cartesian coordinates. Z is masked beyond the support radius. The result is a plain gridded field: it drops into ax.contourf(X, Y, Z), ax.pcolormesh(X, Y, Z), ax.plot_surface(X, Y, Z), and the like.

Source code in src/hifuku/archive.py
def surface(self, n: int = 200, coords: str = "barycentric",
            anchors=None, radius=None, z_scale=None):
    """Interpolated elevation surface as ``(X, Y, Z)`` meshgrids.

    Shepard-interpolates the elite log-likelihoods over a regular ``n`` by
    ``n`` grid spanning the filled region, in barycentric or Cartesian
    coordinates.  ``Z`` is masked beyond the support radius.  The result is a
    plain gridded field: it drops into ``ax.contourf(X, Y, Z)``,
    ``ax.pcolormesh(X, Y, Z)``, ``ax.plot_surface(X, Y, Z)``, and the like.
    """
    from hifuku.utils import shepard_grid
    if self.n_filled == 0:
        raise ValueError("empty archive")
    px, py, logL, z = self.points(coords=coords, anchors=anchors)
    xs = np.linspace(px.min(), px.max(), n)
    ys = np.linspace(py.min(), py.max(), n)
    X, Y = np.meshgrid(xs, ys)
    Z = shepard_grid(np.column_stack([px, py]), logL, X, Y,
                     radius=radius, z=(z if z_scale else None), z_scale=z_scale)
    return X, Y, Z

locate_tree

locate_tree(tree, taxon_table, triangle, coords='barycentric')

Return the chart coordinates of a tree as (x, y, z).

This function aligns the leaves of the tree to taxon_table. It measures the distance from the tree to each anchor of triangle with the chart's own metric, then solves for the chart position.

coords="barycentric" returns (lambda1, lambda2, z). coords="cartesian" returns the point in the Euclidean metric plane. z is the out-of-plane residual. It measures how far the tree sits off the anchor plane.

triangle provides the anchor trees, their embedded geometry, and the metric. The chart owns its metric so a tree cannot be placed under a metric inconsistent with the chart it lands on.

Source code in src/hifuku/archive.py
def locate_tree(tree, taxon_table, triangle, coords="barycentric"):
    """Return the chart coordinates of a tree as ``(x, y, z)``.

    This function aligns the leaves of the tree to ``taxon_table``.  It measures
    the distance from the tree to each anchor of ``triangle`` with the chart's
    own metric, then solves for the chart position.

    ``coords="barycentric"`` returns ``(lambda1, lambda2, z)``.
    ``coords="cartesian"`` returns the point in the Euclidean metric plane.
    ``z`` is the out-of-plane residual.  It measures how far the tree sits off
    the anchor plane.

    ``triangle`` provides the anchor trees, their embedded geometry, and the
    metric.  The chart owns its metric so a tree cannot be placed under a metric
    inconsistent with the chart it lands on.
    """
    from hifuku.utils import barycentric_to_cartesian
    metric = triangle.tree_metric
    anchors = (triangle.r1, triangle.r2, triangle.r3)
    _set_global_leaf_indices(tree, taxon_table)
    for a in anchors:
        _set_global_leaf_indices(a, taxon_table)
    s = [float(metric(tree, a)[0]) for a in anchors]
    lam, z = barycentric(s[0], s[1], s[2], triangle)
    lam1, lam2 = float(lam[0]), float(lam[1])
    if coords == "barycentric":
        return lam1, lam2, float(z)
    if coords == "cartesian":
        x, y = barycentric_to_cartesian(lam1, lam2, triangle)
        return float(x), float(y), float(z)
    raise ValueError(f"coords must be 'barycentric' or 'cartesian', got {coords!r}")