Skip to content

Survey Analysis

Functions that read survey files and analyze them. They make no assumption about how a study is organized.

  • load reads any mix of files, directories and glob patterns, and returns a dict from each file's path to its Survey. It assumes no naming scheme.
  • run_chain gives the runs of one survey in order, by the sealed parent links and not by the text of the labels.
  • qd_history gives the variations, the QD-score and the growth exponent of one survey. It reads the (S, N, m) rows where the record holds them, and otherwise the archive stored at the end of each run. A run that holds the records of more than one gene needs the gene argument.
  • hypsometric_curve gives the elite log-likelihoods of an archive, best first.
  • explored_edge gives the edge of the filled niches as Cartesian lines on the chart.
  • kh_scale gives each elite of an archive its height below the archive's best tree, its own Kishino-Hasegawa standard error against that tree, and their ratio z. It computes one log-likelihood pass per elite on the host, so it needs the alignment and the model of the survey.
  • shoreline gives, from that scale, the edge z of an archive (every shoreline closes at a datum at or below it), the niche that sets it, and the z at the survey's gate.
  • datum_range gives, from one shoreline per gene, the cap of a study's datum, the genes that set it, and a default datum. DatumRange.to_frame gives one row per gene as a polars DataFrame.
  • halt_status gives whether and where a survey record halted and, for a survey that did not, the projected variations to the halt.

Datums and shorelines gives the reasons for the scale and the shoreline test.

The module also exports the QD-score functions of hifuku.halt, the coordinate functions of hifuku.utils, and elite_frame, so one import serves an analysis. The functions read files and write nothing. The driver does not import this module.

analysis

Helpers for analyzing hifuku survey files.

The functions here take no position on how a study is organized. load reads any mix of files, directories and glob patterns. run_chain follows the sealed parent links of a survey, so it works for any labeling. The other functions work on one survey or one archive at a time. Pieces that live in other modules and serve an analysis are aliased here, so one import serves. The functions read files and write nothing.

KhScale dataclass

Each elite's height below its archive's best tree, and its z.

The arrays align with keys, in the archive's key order. height is L_best - L. se is the tree's own standard error against the best tree, by Kishino and Hasegawa's eq. 12 over site patterns weighted by their site counts. z is height / se, and the best tree has z = 0. The best tree is selected from the same data, so z is biased toward overconfidence.

Source code in src/hifuku/analysis.py
@dataclass(frozen=True)
class KhScale:
    """Each elite's height below its archive's best tree, and its z.

    The arrays align with ``keys``, in the archive's key order.  ``height``
    is ``L_best - L``.  ``se`` is the tree's own standard error against the
    best tree, by Kishino and Hasegawa's eq. 12 over site patterns weighted
    by their site counts.  ``z`` is ``height / se``, and the best tree has
    ``z = 0``.  The best tree is selected from the same data, so ``z`` is
    biased toward overconfidence.
    """

    keys: np.ndarray
    height: np.ndarray
    se: np.ndarray
    z: np.ndarray
    n_sites: int
    best_key: tuple

Shoreline dataclass

Where the shorelines of one archive stop closing, on the KH scale.

A datum d on the scale selects the filled niches with z < d. Every empty niche is outside that region. The boundary of the region consists only of closed loops between filled niches when no edge elite has z < d, that is when d is at most edge_z. An edge elite has at least one empty niche among its eight neighbors. An empty niche inside the filled region counts. edge_key is the niche that sets edge_z, and n_edge counts the edge elites. gate_z is the median z of the trees whose height lies within SHORELINE_GATE_BAND of the gate height, or None.

Source code in src/hifuku/analysis.py
@dataclass(frozen=True)
class Shoreline:
    """Where the shorelines of one archive stop closing, on the KH scale.

    A datum ``d`` on the scale selects the filled niches with ``z < d``.
    Every empty niche is outside that region.  The boundary of the region
    consists only of closed loops between filled niches when no edge elite
    has ``z < d``, that is when ``d`` is at most ``edge_z``.  An edge elite
    has at least one empty niche among its eight neighbors.  An empty niche
    inside the filled region counts.  ``edge_key`` is the niche that sets
    ``edge_z``, and ``n_edge`` counts the edge elites.
    ``gate_z`` is the median z of the trees whose height lies within
    ``SHORELINE_GATE_BAND`` of the gate height, or None.
    """

    edge_z: float
    edge_key: tuple
    gate_z: float | None
    n_edge: int

DatumRange dataclass

The datums a study's archives allow, one archive per gene.

cap is the lowest edge z over the genes: every shoreline of every archive closes at a datum at or below it. constraining names the gene or genes whose edge z equals the cap. default is the largest of levels strictly below the cap, or None. per_gene and gate_z map each gene to its edge z and to the z at which its gate falls.

Source code in src/hifuku/analysis.py
@dataclass(frozen=True)
class DatumRange:
    """The datums a study's archives allow, one archive per gene.

    ``cap`` is the lowest edge z over the genes: every shoreline of every
    archive closes at a datum at or below it.  ``constraining`` names the
    gene or genes whose edge z equals the cap.  ``default`` is the largest of
    ``levels`` strictly below the cap, or None.  ``per_gene`` and ``gate_z`` map each
    gene to its edge z and to the z at which its gate falls.
    """

    cap: float
    default: float | None
    constraining: tuple
    per_gene: dict
    gate_z: dict
    levels: tuple

    def to_frame(self):
        """One row per gene, lowest edge z first, as a polars DataFrame."""
        import polars as pl
        genes = sorted(self.per_gene, key=lambda g: (self.per_gene[g], g))
        return pl.DataFrame({
            "gene": genes,
            "edge_z": [self.per_gene[g] for g in genes],
            "gate_z": [self.gate_z[g] for g in genes],
            "constraining": [g in self.constraining for g in genes],
        })

to_frame

to_frame()

One row per gene, lowest edge z first, as a polars DataFrame.

Source code in src/hifuku/analysis.py
def to_frame(self):
    """One row per gene, lowest edge z first, as a polars DataFrame."""
    import polars as pl
    genes = sorted(self.per_gene, key=lambda g: (self.per_gene[g], g))
    return pl.DataFrame({
        "gene": genes,
        "edge_z": [self.per_gene[g] for g in genes],
        "gate_z": [self.gate_z[g] for g in genes],
        "constraining": [g in self.constraining for g in genes],
    })

HaltStatus dataclass

Whether and where one survey halted, and what it would still cost.

rule is "qd_score" or "rate". halted_at is the variation count at the halt, or None. variations is the count spent. Under the QD-score rule, beta is the last decided growth exponent and tau the threshold. Both are None under the rate rule. beta is also None before the guard, without QD-score rows, and while the last row counts no elites. projections maps each fitted model that describes the survey to its projected total variations to the halt. It is empty when the survey halted.

Source code in src/hifuku/analysis.py
@dataclass(frozen=True)
class HaltStatus:
    """Whether and where one survey halted, and what it would still cost.

    ``rule`` is ``"qd_score"`` or ``"rate"``.  ``halted_at`` is the variation
    count at the halt, or None.  ``variations`` is the count spent.  Under
    the QD-score rule, ``beta`` is the last decided growth exponent and
    ``tau`` the threshold.  Both are None under the rate rule.  ``beta`` is
    also None before the guard, without QD-score rows, and while the last
    row counts no elites.  ``projections`` maps each fitted model that
    describes the survey to its projected total variations to the halt.  It
    is empty when the survey halted.
    """

    rule: str
    halted: bool
    halted_at: int | None
    variations: int
    beta: float | None
    tau: float | None
    projections: dict

fit_models

fit_models(variations, qd) -> dict

Fit each accumulation function by least squares on log Q.

Only checkpoints with positive variations and positive QD-score are used. Of these, the fit uses the checkpoints at or past the guard of :func:past_guard. When fewer than three such checkpoints are past the guard, the fit uses all of them. A model whose fit fails, or that has fewer than three points to fit, is left out of the result.

Source code in src/hifuku/halt.py
def fit_models(variations, qd) -> dict:
    """Fit each accumulation function by least squares on ``log Q``.

    Only checkpoints with positive variations and positive QD-score are
    used.  Of these, the fit uses the checkpoints at or past the guard of
    :func:`past_guard`.  When fewer than three such checkpoints are past
    the guard, the fit uses all of them.  A model whose fit fails, or that
    has fewer than three points to fit, is left out of the result.
    """
    v = np.asarray(variations, float)
    q = np.asarray(qd, float)
    keep = (v > 0.0) & (q > 0.0)
    guarded = keep & np.array([past_guard(v, i) for i in range(v.size)],
                              dtype=bool)
    if np.count_nonzero(guarded) >= 3:
        keep = guarded
    v, q = v[keep], q[keep]
    out = {}
    if v.size < 3:
        return out
    for name, f in MODELS.items():
        try:
            with np.errstate(invalid="ignore", divide="ignore",
                             over="ignore"), warnings.catch_warnings():
                warnings.simplefilter("ignore", OptimizeWarning)
                p, _ = curve_fit(lambda x, a, b: np.log(f(x, a, b)), v,
                                 np.log(q), p0=_start(name, v, q),
                                 maxfev=20000)
            if np.all(np.isfinite(p)) and np.all(p > 0.0):
                out[name] = (float(p[0]), float(p[1]))
        except (RuntimeError, ValueError, FloatingPointError):
            continue
    return out

growth_exponent

growth_exponent(variations, qd, i: int) -> float | None

The growth exponent at checkpoint i, or None when undecided.

Undecided when there is no earlier checkpoint, when the half checkpoint has no variations, or when either QD-score is not positive.

Source code in src/hifuku/halt.py
def growth_exponent(variations, qd, i: int) -> float | None:
    """The growth exponent at checkpoint ``i``, or None when undecided.

    Undecided when there is no earlier checkpoint, when the half checkpoint
    has no variations, or when either QD-score is not positive.
    """
    variations = np.asarray(variations, float)
    qd = np.asarray(qd, float)
    h = _half(variations, i)
    if h is None or variations[h] <= 0.0 or qd[h] <= 0.0 or qd[i] <= 0.0:
        return None
    return math.log2(qd[i] / qd[h]) / math.log2(variations[i] / variations[h])

qd_scores

qd_scores(sums, counts, offset: float) -> np.ndarray

The QD-score of each checkpoint, read with one offset.

Source code in src/hifuku/halt.py
def qd_scores(sums, counts, offset: float) -> np.ndarray:
    """The QD-score of each checkpoint, read with one offset."""
    return np.asarray(sums, float) - np.asarray(counts, float) * float(offset)

variations_to_tau

variations_to_tau(model: str, params, tau: float) -> float | None

Variations at which a fitted model's growth exponent reaches tau.

Source code in src/hifuku/halt.py
def variations_to_tau(model: str, params, tau: float) -> float | None:
    """Variations at which a fitted model's growth exponent reaches ``tau``."""
    a, b = params
    if model == "Clench (Michaelis-Menten)":
        return (1.0 / tau - 1.0) / b
    if model == "negative exponential":
        # math.expm1 overflows above about 709; s/expm1(s) is far below any
        # tau by 700, so the bracket holds the root.
        x = brentq(lambda s: s / math.expm1(s) - tau, 1e-12, 700.0)
        return x / b
    if model == "logarithmic":
        # Solve in w = ln(u): the root spans many orders of magnitude.  At
        # w = 690 the growth exponent is far below any tau in (0, 1).
        w = brentq(lambda w: math.exp(w) / ((1.0 + math.exp(w))
                                            * math.log1p(math.exp(w))) - tau,
                   -27.0, 690.0)
        return math.exp(w) / (b * a)
    return None

barycentric_to_cartesian

barycentric_to_cartesian(lam1, lam2, anchors)

Map barycentric (lambda1, lambda2) to Cartesian (x, y).

lambda3 = 1 - lambda1 - lambda2 is applied internally. lam1 and lam2 broadcast against each other.

Returns:

Type Description
(x, y) : tuple of numpy arrays

Cartesian coordinates in the Euclidean chart plane, so ax.scatter(*barycentric_to_cartesian(lam1, lam2, tri)) plots the true anchor geometry.

Source code in src/hifuku/utils.py
def barycentric_to_cartesian(lam1, lam2, anchors):
    """Map barycentric ``(lambda1, lambda2)`` to Cartesian ``(x, y)``.

    ``lambda3 = 1 - lambda1 - lambda2`` is applied internally.  ``lam1`` and
    ``lam2`` broadcast against each other.

    Returns
    -------
    (x, y) : tuple of numpy arrays
        Cartesian coordinates in the Euclidean chart plane, so
        ``ax.scatter(*barycentric_to_cartesian(lam1, lam2, tri))`` plots the true
        anchor geometry.
    """
    lam1 = np.asarray(lam1, dtype=float)
    lam2 = np.asarray(lam2, dtype=float)
    lam3 = 1.0 - lam1 - lam2
    (p1, p2, p3) = _anchor_points(anchors)
    x = lam1 * p1[0] + lam2 * p2[0] + lam3 * p3[0]
    y = lam1 * p1[1] + lam2 * p2[1] + lam3 * p3[1]
    return x, y

cartesian_to_barycentric

cartesian_to_barycentric(x, y, anchors)

Map Cartesian (x, y) to barycentric (lambda1, lambda2).

The exact inverse of :func:barycentric_to_cartesian. x and y broadcast against each other. lambda3 is 1 - lambda1 - lambda2.

Returns:

Type Description
(lam1, lam2) : tuple of numpy arrays
Source code in src/hifuku/utils.py
def cartesian_to_barycentric(x, y, anchors):
    """Map Cartesian ``(x, y)`` to barycentric ``(lambda1, lambda2)``.

    The exact inverse of :func:`barycentric_to_cartesian`.  ``x`` and ``y``
    broadcast against each other.  ``lambda3`` is ``1 - lambda1 - lambda2``.

    Returns
    -------
    (lam1, lam2) : tuple of numpy arrays
    """
    x = np.asarray(x, dtype=float)
    y = np.asarray(y, dtype=float)
    (p1, p2, p3) = _anchor_points(anchors)
    m_inv = np.linalg.inv(np.column_stack([p1 - p3, p2 - p3]))
    dx = x - p3[0]
    dy = y - p3[1]
    lam1 = m_inv[0, 0] * dx + m_inv[0, 1] * dy
    lam2 = m_inv[1, 0] * dx + m_inv[1, 1] * dy
    return lam1, lam2

elite_frame

elite_frame(archive, anchors=None, backend: str = 'pandas')

Extract an elite archive into a dataframe of one row per elite.

Columns are those of :func:elite_arrays. backend is "pandas" or "polars". Pass anchors to add the Cartesian x, y columns.

Source code in src/hifuku/utils.py
def elite_frame(archive, anchors=None, backend: str = "pandas"):
    """Extract an elite archive into a dataframe of one row per elite.

    Columns are those of :func:`elite_arrays`.  ``backend`` is ``"pandas"`` or
    ``"polars"``.  Pass ``anchors`` to add the Cartesian ``x``, ``y`` columns.
    """
    cols = elite_arrays(archive, anchors=anchors)
    if backend == "pandas":
        import pandas as pd
        return pd.DataFrame(cols)
    if backend == "polars":
        import polars as pl
        return pl.DataFrame(cols)
    raise ValueError(f"backend must be 'pandas' or 'polars', got {backend!r}")

load

load(*paths) -> dict

Read survey files, by path, directory or glob pattern.

Each argument is a str or pathlib.Path. A directory gives every *.h5 file in it; a pattern gives every *.h5 file it matches. Returns a dict from each file's path to its Survey, in path order. Two spellings of one file, such as a relative and an absolute path, give one entry, under the first spelling. Every file is read with its seals checked. An argument that matches no survey file raises FileNotFoundError.

Source code in src/hifuku/analysis.py
def load(*paths) -> dict:
    """Read survey files, by path, directory or glob pattern.

    Each argument is a ``str`` or ``pathlib.Path``.  A directory gives every
    ``*.h5`` file in it; a pattern gives every ``*.h5`` file it matches.
    Returns a dict from each file's path to its ``Survey``, in path order.
    Two spellings of one file, such as a relative and an absolute path, give
    one entry, under the first spelling.  Every file is read with its seals
    checked.  An argument that matches no survey file raises
    ``FileNotFoundError``.
    """
    found: dict[Path, Path] = {}
    for item in paths:
        path = Path(item)
        if path.is_dir():
            matches = sorted(path.glob("*.h5"))
        elif path.exists():
            matches = [path]
        else:
            matches = sorted(Path(p) for p in glob.glob(str(item))
                             if Path(p).suffix == ".h5" and Path(p).is_file())
        if not matches:
            raise FileNotFoundError(f"no survey file matches {item}")
        for match in matches:
            found.setdefault(match.resolve(), match)
    return {p: Survey.load(p) for _key, p in sorted(found.items())}

run_chain

run_chain(survey, label=None, *, gene=None, chart=None) -> list

The runs of one survey, oldest first, by their parent links.

label names the last run of the chain. By default the chain ends at the run that no other run continues. A file that holds several chains needs label. When the parent of a run is not in the file, the chain starts at the earliest run that is present.

The records of one run can name different parents. gene and chart select the record whose parent links are followed, by the rule of :func:qd_history. Only the runs that hold such a record are part of the chain. Without them, all records of a run must name one parent, else this raises ValueError.

Source code in src/hifuku/analysis.py
def run_chain(survey, label=None, *, gene=None, chart=None) -> list:
    """The runs of one survey, oldest first, by their parent links.

    ``label`` names the last run of the chain.  By default the chain ends at
    the run that no other run continues.  A file that holds several chains
    needs ``label``.  When the parent of a run is not in the file, the chain
    starts at the earliest run that is present.

    The records of one run can name different parents.  ``gene`` and
    ``chart`` select the record whose parent links are followed, by the rule
    of :func:`qd_history`.  Only the runs that hold such a record are part
    of the chain.  Without them, all records of a run must name one parent,
    else this raises ``ValueError``.
    """
    if gene is None and chart is None:
        runs = list(survey.runs)
        parent = {}
        for run in runs:
            named = {rec.parent for rec in run.surveys}
            if len(named) != 1:
                raise ValueError(
                    f"the records of run {run.label} name {len(named)} "
                    f"parents; name the gene with gene")
            parent[run.run_id] = named.pop()
    else:
        runs = [run for run in survey.runs if _matches(run, gene, chart)]
        parent = {run.run_id: _record(run, gene, chart).parent
                  for run in runs}
    by_id = {run.run_id: run for run in runs}
    children = set(parent.values())
    if label is None:
        ends = [run for run in runs if run.run_id not in children]
        if len(ends) != 1:
            raise ValueError(
                f"the file holds {len(ends)} chains; name the last run with "
                f"label")
        end = ends[0]
    else:
        end = survey.run_by_label(label)
        if end.run_id not in by_id:
            raise ValueError(
                f"run {label} holds no record of {gene!r} on chart {chart}")
    chain = [end]
    seen = {end.run_id}
    while (parent[chain[-1].run_id] in by_id
           and parent[chain[-1].run_id] not in seen):
        chain.append(by_id[parent[chain[-1].run_id]])
        seen.add(chain[-1].run_id)
    return chain[::-1]

qd_history

qd_history(survey, label=None, *, gene=None, chart=None)

Variations, QD-score and growth exponent of one survey.

gene and chart select one record of each run. A run with one record needs neither. A run with more than one record needs gene, else this raises ValueError and names the genes.

The values come from the per-checkpoint (S, N, m) rows where the selected record of the last run holds them. Otherwise they come from the archive stored at the end of each run. A qd array with no rows counts as absent. The rows of the last record cover the whole chain, back to the first run that recorded rows. The variations are the matching last rows of its history. The offset is the lowest elite at the last row. The growth exponent is NaN where it is undecided and at every checkpoint before the guard of :func:hifuku.halt.past_guard.

Source code in src/hifuku/analysis.py
def qd_history(survey, label=None, *, gene=None, chart=None):
    """Variations, QD-score and growth exponent of one survey.

    ``gene`` and ``chart`` select one record of each run.  A run with one
    record needs neither.  A run with more than one record needs ``gene``,
    else this raises ``ValueError`` and names the genes.

    The values come from the per-checkpoint ``(S, N, m)`` rows where the
    selected record of the last run holds them.  Otherwise they come from
    the archive stored at the end of each run.  A ``qd`` array with no rows
    counts as absent.  The rows of the last record cover the whole chain,
    back to the first run that recorded rows.  The variations are the
    matching last rows of its history.  The offset is the lowest elite at
    the last row.  The growth exponent is NaN where it is undecided and at
    every checkpoint before the guard of :func:`hifuku.halt.past_guard`.
    """
    chain = run_chain(survey, label, gene=gene, chart=chart)
    records = [_record(run, gene, chart) for run in chain]
    last = records[-1]
    if getattr(last, "qd", None) is not None and len(last.qd) > 0:
        rows = np.asarray(last.qd, float)
        v = np.asarray(last.history, float)[-len(rows):, 0]
        q = qd_scores(rows[:, 0], rows[:, 1], rows[-1, 2])
    else:
        ends = [(float(np.asarray(rec.history, float)[-1, 0]),
                 np.array([e.logL for e in rec.archive.elites.values()]))
                for rec in records]
        offset = min(float(l.min()) for _v, l in ends)
        v = np.array([x for x, _l in ends])
        q = np.array([float(np.sum(l - offset)) for _x, l in ends])
    beta = [growth_exponent(v, q, i) if past_guard(v, i) else None
            for i in range(len(v))]
    return v, q, np.array([np.nan if b is None else b for b in beta], float)

hypsometric_curve

hypsometric_curve(archive) -> np.ndarray

The elite log-likelihoods of an archive, best first.

Source code in src/hifuku/analysis.py
def hypsometric_curve(archive) -> np.ndarray:
    """The elite log-likelihoods of an archive, best first."""
    return np.sort([e.logL for e in archive.elites.values()])[::-1]

explored_edge

explored_edge(archive, anchors) -> list

The edge of the filled niches, as Cartesian lines on the chart.

The niches form a grid in barycentric coordinates. Holes inside the filled region are filled first, so the lines trace its outer edge. A separate island of filled niches gets a line of its own. The contour of the occupancy grid at one half runs along the cell edges between filled and empty niches. anchors fixes the Cartesian coordinates.

Returns a list of (x, y) array pairs, one per line. An archive with no elites gives an empty list.

Source code in src/hifuku/analysis.py
def explored_edge(archive, anchors) -> list:
    """The edge of the filled niches, as Cartesian lines on the chart.

    The niches form a grid in barycentric coordinates.  Holes inside the
    filled region are filled first, so the lines trace its outer edge.  A
    separate island of filled niches gets a line of its own.  The contour of
    the occupancy grid at one half runs along the cell edges between filled
    and empty niches.  ``anchors`` fixes the Cartesian coordinates.

    Returns a list of ``(x, y)`` array pairs, one per line.  An archive with
    no elites gives an empty list.
    """
    if not archive.elites:
        return []
    keys = np.array(list(archive.elites))
    lo, hi = keys.min(axis=0) - 1, keys.max(axis=0) + 1
    occupied = np.zeros((hi[1] - lo[1] + 1, hi[0] - lo[0] + 1))
    occupied[keys[:, 1] - lo[1], keys[:, 0] - lo[0]] = 1.0
    occupied = binary_fill_holes(occupied).astype(float)
    i, j = np.meshgrid(np.arange(lo[0], hi[0] + 1),
                       np.arange(lo[1], hi[1] + 1))
    lines = []
    for line in contour_generator(i, j, occupied).lines(0.5):
        lam1 = archive.origin + (line[:, 0] + 0.5) * archive.cell
        lam2 = archive.origin + (line[:, 1] + 0.5) * archive.cell
        lines.append(barycentric_to_cartesian(lam1, lam2, anchors))
    return lines

kh_scale

kh_scale(archive, alignment, model) -> KhScale

The per-tree Kishino-Hasegawa scale of one archive.

The best tree is the elite with the highest log-likelihood computed on the host. On a tie, it is the first in archive.keys. Each tree costs one pass of :func:hifuku.pruning.pattern_log_likelihoods. An archive with no elites raises ValueError. A tree with a positive height and a zero standard error has z = inf.

Source code in src/hifuku/analysis.py
def kh_scale(archive, alignment, model) -> KhScale:
    """The per-tree Kishino-Hasegawa scale of one archive.

    The best tree is the elite with the highest log-likelihood computed on
    the host.  On a tie, it is the first in ``archive.keys``.  Each tree costs
    one pass of :func:`hifuku.pruning.pattern_log_likelihoods`.  An archive
    with no elites raises ``ValueError``.  A tree with a positive height and
    a zero standard error has ``z = inf``.
    """
    from hifuku.pruning import pattern_log_likelihoods

    keys = [tuple(int(x) for x in k) for k in archive.keys]
    if not keys:
        raise ValueError("an archive with no elites has no scale")
    w = np.asarray(alignment.weights, dtype=np.float64)
    n = float(w.sum())
    sites = np.array([pattern_log_likelihoods(archive.tree_at(k), alignment,
                                              model) for k in keys])
    b = int(np.argmax(sites @ w))
    d = sites[b][None, :] - sites
    height = d @ w
    if n > 1.0:
        centered = d - (height / n)[:, None]
        se = np.sqrt((n / (n - 1.0)) * ((centered ** 2) @ w))
    else:
        se = np.zeros(len(keys))
    with np.errstate(divide="ignore", invalid="ignore"):
        z = np.where(se > 0.0, height / se,
                     np.where(height > 0.0, np.inf, 0.0))
    return KhScale(keys=np.array(keys, dtype=np.int64).reshape(-1, 2),
                   height=height, se=se, z=z, n_sites=int(n),
                   best_key=keys[b])

shoreline

shoreline(scale, gate_height=None)

The shoreline of an archive from its KH scale, or None.

gate_height is the height of the survey's gate below its best tree, in nats. It is None when the survey ran under an absolute floor, and then gate_z is None. An archive of fewer than two elites has no shoreline.

Source code in src/hifuku/analysis.py
def shoreline(scale, gate_height=None):
    """The shoreline of an archive from its KH scale, or None.

    ``gate_height`` is the height of the survey's gate below its best tree,
    in nats.  It is None when the survey ran under an absolute floor, and
    then ``gate_z`` is None.  An archive of fewer than two elites has no
    shoreline.
    """
    keys = [tuple(int(x) for x in k) for k in scale.keys]
    if len(keys) < 2:
        return None
    filled = set(keys)
    edge = [i for i, (a, b) in enumerate(keys)
            if any((a + da, b + db) not in filled for da, db in _NEIGHBORS)]
    i = min(edge, key=lambda j: scale.z[j])
    gate_z = None
    if gate_height is not None and gate_height > 0.0:
        band = (np.abs(np.asarray(scale.height) - gate_height)
                <= SHORELINE_GATE_BAND * gate_height)
        if int(band.sum()) >= SHORELINE_GATE_MIN_ELITES:
            gate_z = float(np.median(np.asarray(scale.z)[band]))
    return Shoreline(edge_z=float(scale.z[i]), edge_key=keys[i],
                     gate_z=gate_z, n_edge=len(edge))

datum_range

datum_range(shorelines, levels=DATUM_LEVELS) -> DatumRange

The datum range of a study from one shoreline per gene.

shorelines maps each gene's label to its :class:Shoreline. An empty mapping, or a gene whose shoreline is None, raises ValueError.

Source code in src/hifuku/analysis.py
def datum_range(shorelines, levels=DATUM_LEVELS) -> DatumRange:
    """The datum range of a study from one shoreline per gene.

    ``shorelines`` maps each gene's label to its :class:`Shoreline`.  An
    empty mapping, or a gene whose shoreline is None, raises
    ``ValueError``.
    """
    if not shorelines:
        raise ValueError("a datum range needs the shoreline of at least one "
                         "gene")
    missing = sorted(g for g, s in shorelines.items() if s is None)
    if missing:
        raise ValueError(f"no shoreline for {', '.join(missing)}; an archive "
                         f"of fewer than two elites has none")
    per_gene = {g: float(s.edge_z) for g, s in shorelines.items()}
    cap = min(per_gene.values())
    below = [float(x) for x in levels if x < cap]
    return DatumRange(
        cap=cap, default=max(below) if below else None,
        constraining=tuple(sorted(g for g, z in per_gene.items()
                                  if z == cap)),
        per_gene=per_gene,
        gate_z={g: s.gate_z for g, s in shorelines.items()},
        levels=tuple(float(x) for x in levels))

halt_status

halt_status(record) -> HaltStatus

The halt status of one survey record.

Source code in src/hifuku/analysis.py
def halt_status(record) -> HaltStatus:
    """The halt status of one survey record."""
    from hifuku.halt import projected_totals
    from hifuku.params import ArchiveParams

    params = ArchiveParams.from_record(record.params)
    history = np.asarray(record.history, float)
    variations = int(history[-1, 0]) if len(history) else 0
    halted = bool(record.converged)
    halted_at = int(record.halt_iter) if halted else None
    if params.halt_rule != "qd_score":
        return HaltStatus(params.halt_rule, halted, halted_at, variations,
                          None, None, {})
    tau = float(params.qd_tau)
    rows = getattr(record, "qd", None)
    if rows is None or len(rows) == 0:
        return HaltStatus("qd_score", halted, halted_at, variations, None,
                          tau, {})
    rows = np.asarray(rows, float)
    v = history[-len(rows):, 0]
    i = len(rows) - 1
    if rows[i, 1] == 0.0:
        return HaltStatus("qd_score", halted, halted_at, variations, None,
                          tau, {})
    qd = qd_scores(rows[:, 0], rows[:, 1], rows[i, 2])
    beta = growth_exponent(v, qd, i) if past_guard(v, i) else None
    projections = {}
    if not halted:
        projections, _ = projected_totals(v, qd, beta, tau)
    return HaltStatus("qd_score", halted, halted_at, variations, beta, tau,
                      projections)