Skip to content

Framework

A framework is the coordinate system a survey runs inside: the taxon namespace, each alignment with its neighbor-joining tree, the charts with their anchors and geometry, and the settings that fix the coordinates. The substitution model, the metric weight and the occupancy floor decide where the charts are, so they belong to the framework. The niche size and the origin decide how one run bins a chart, so they belong to the run.

FrameworkSpec is the recipe. It is small enough to write by hand, and it reads from and writes to TOML. Framework.build turns the recipe into a Framework, at the cost of one neighbor-joining pass per alignment, so a batch of work is given the built form. Each chart of a framework is a FrameworkChart: three anchor labels and the triangle they embed.

Framework.digest identifies a framework. Two surveys with the same digest project into one coordinate system. explain_mismatch says how two frameworks differ when their digests do not match. A Batch names the work done inside a framework, and a survey file holds the framework together with that work.

FrameworkSpec dataclass

The recipe for a framework: which alignments, which charts, what settings.

The spec validates its own labels at construction, so a typo raises where the user wrote it rather than after several minutes of neighbor joining.

Attributes:

Name Type Description
alignments dict

Label to alignment path. A label names an HDF5 group in the survey file, so it may not contain a slash.

charts list of tuple

Each chart as three distinct anchor labels, in the order that fixes which corner is which.

chart_labels list of str

A name per chart, in the same order. Shorter than charts, or holding an empty string, means the rest are derived from the anchors, so a caller who wants to name one chart need not name them all. After construction this is always as long as charts and every entry is filled.

model str

Substitution model name, or "auto".

w float

Topology weight of the tree metric, in [0, 1].

min_occupancy float

The fraction of a gene's alignment a taxon must carry to enter that gene's tree. A taxon carrying nothing is left out whatever this says.

Source code in src/hifuku/framework.py
@dataclass(frozen=True)
class FrameworkSpec:
    """The recipe for a framework: which alignments, which charts, what settings.

    The spec validates its own labels at construction, so a typo raises where
    the user wrote it rather than after several minutes of neighbor joining.

    Attributes
    ----------
    alignments : dict
        Label to alignment path.  A label names an HDF5 group in the survey
        file, so it may not contain a slash.
    charts : list of tuple
        Each chart as three distinct anchor labels, in the order that fixes
        which corner is which.
    chart_labels : list of str
        A name per chart, in the same order.  Shorter than ``charts``, or
        holding an empty string, means the rest are derived from the anchors,
        so a caller who wants to name one chart need not name them all.  After
        construction this is always as long as ``charts`` and every entry is
        filled.
    model : str
        Substitution model name, or ``"auto"``.
    w : float
        Topology weight of the tree metric, in [0, 1].
    min_occupancy : float
        The fraction of a gene's alignment a taxon must carry to enter that
        gene's tree.  A taxon carrying nothing is left out whatever this says.
    """

    alignments: dict
    charts: list
    model: str = "LG"
    w: float = 0.5
    min_occupancy: float = MIN_TAXON_OCCUPANCY
    chart_labels: list = field(default_factory=list)

    def __post_init__(self):
        object.__setattr__(self, "alignments", dict(self.alignments))
        object.__setattr__(self, "charts",
                           [tuple(c) for c in self.charts])
        given = list(self.chart_labels)
        given += [""] * (len(self.charts) - len(given))
        resolved = [check_label(given[i] or chart_label(anchors), "chart")
                    for i, anchors in enumerate(self.charts)]
        if len(set(resolved)) != len(resolved):
            raise ValueError(
                f"two charts share the label {sorted(resolved)}; a label picks "
                "one chart out of a framework, so it has to name one")
        object.__setattr__(self, "chart_labels", resolved)
        for label in self.alignments:
            if "/" in label:
                raise ValueError(
                    f"the alignment label {label!r} contains a slash, and a "
                    "label names a group in the survey file; rename it or pass "
                    "an explicit label")
        known = set(self.alignments)
        for i, anchors in enumerate(self.charts):
            if len(anchors) != 3:
                raise ValueError(
                    f"chart {i} needs three anchors, got {len(anchors)}: "
                    f"{list(anchors)}")
            if len(set(anchors)) != 3:
                raise ValueError(
                    f"chart {i} needs three distinct anchors, got "
                    f"{list(anchors)}")
            for label in anchors:
                if label not in known:
                    raise ValueError(
                        f"chart {i} names anchor {label!r}, which is not in "
                        f"alignments; known labels are {sorted(known)}")

    @classmethod
    def from_toml(cls, path) -> "FrameworkSpec":
        """Read a framework file.

        The file holds a ``[framework]`` table of settings, an ``[alignments]``
        table of label to path, and one ``[[charts]]`` table per chart holding
        ``anchors`` and an optional ``label``.
        """
        import tomllib
        with open(path, "rb") as fh:
            raw = tomllib.load(fh)
        return cls.from_mapping(raw)

    @classmethod
    def from_mapping(cls, raw: dict) -> "FrameworkSpec":
        """Build a spec from an already-parsed mapping.

        A batch file may carry a framework inline, so the mapping and the file
        are read by one function and the two forms cannot drift apart.
        """
        settings = dict(raw.get("framework", {}))
        charts = list(raw.get("charts", []))
        return cls(
            alignments=dict(raw.get("alignments", {})),
            charts=[tuple(c["anchors"]) for c in charts],
            chart_labels=[c.get("label", "") for c in charts],
            model=settings.get("model", "LG"),
            w=float(settings.get("w", 0.5)),
            min_occupancy=float(settings.get("min_occupancy",
                                             MIN_TAXON_OCCUPANCY)),
        )

    def to_toml(self, path) -> None:
        """Write the framework file that :meth:`from_toml` reads."""
        Path(path).write_text("\n".join(self.as_toml_lines()) + "\n")

    def as_toml_lines(self) -> list:
        """The framework file as lines, for writing alone or inside a batch."""
        lines = ["[framework]",
                 f"model = {toml_value(self.model)}",
                 f"w = {toml_value(self.w)}",
                 f"min_occupancy = {toml_value(self.min_occupancy)}",
                 "",
                 "[alignments]"]
        lines += [f"{label} = {toml_value(str(path))}"
                  for label, path in self.alignments.items()]
        for anchors, label in zip(self.charts, self.chart_labels):
            lines += ["", "[[charts]]",
                      f"anchors = {json.dumps(list(anchors))}"]
            # A derived label is not written back.  Writing it would freeze a
            # name that follows the anchors, so a chart whose anchors changed
            # would keep a label describing the ones it no longer has.
            if label != chart_label(anchors):
                lines.append(f"label = {toml_value(label)}")
        return lines

from_toml classmethod

from_toml(path) -> 'FrameworkSpec'

Read a framework file.

The file holds a [framework] table of settings, an [alignments] table of label to path, and one [[charts]] table per chart holding anchors and an optional label.

Source code in src/hifuku/framework.py
@classmethod
def from_toml(cls, path) -> "FrameworkSpec":
    """Read a framework file.

    The file holds a ``[framework]`` table of settings, an ``[alignments]``
    table of label to path, and one ``[[charts]]`` table per chart holding
    ``anchors`` and an optional ``label``.
    """
    import tomllib
    with open(path, "rb") as fh:
        raw = tomllib.load(fh)
    return cls.from_mapping(raw)

from_mapping classmethod

from_mapping(raw: dict) -> 'FrameworkSpec'

Build a spec from an already-parsed mapping.

A batch file may carry a framework inline, so the mapping and the file are read by one function and the two forms cannot drift apart.

Source code in src/hifuku/framework.py
@classmethod
def from_mapping(cls, raw: dict) -> "FrameworkSpec":
    """Build a spec from an already-parsed mapping.

    A batch file may carry a framework inline, so the mapping and the file
    are read by one function and the two forms cannot drift apart.
    """
    settings = dict(raw.get("framework", {}))
    charts = list(raw.get("charts", []))
    return cls(
        alignments=dict(raw.get("alignments", {})),
        charts=[tuple(c["anchors"]) for c in charts],
        chart_labels=[c.get("label", "") for c in charts],
        model=settings.get("model", "LG"),
        w=float(settings.get("w", 0.5)),
        min_occupancy=float(settings.get("min_occupancy",
                                         MIN_TAXON_OCCUPANCY)),
    )

to_toml

to_toml(path) -> None

Write the framework file that :meth:from_toml reads.

Source code in src/hifuku/framework.py
def to_toml(self, path) -> None:
    """Write the framework file that :meth:`from_toml` reads."""
    Path(path).write_text("\n".join(self.as_toml_lines()) + "\n")

as_toml_lines

as_toml_lines() -> list

The framework file as lines, for writing alone or inside a batch.

Source code in src/hifuku/framework.py
def as_toml_lines(self) -> list:
    """The framework file as lines, for writing alone or inside a batch."""
    lines = ["[framework]",
             f"model = {toml_value(self.model)}",
             f"w = {toml_value(self.w)}",
             f"min_occupancy = {toml_value(self.min_occupancy)}",
             "",
             "[alignments]"]
    lines += [f"{label} = {toml_value(str(path))}"
              for label, path in self.alignments.items()]
    for anchors, label in zip(self.charts, self.chart_labels):
        lines += ["", "[[charts]]",
                  f"anchors = {json.dumps(list(anchors))}"]
        # A derived label is not written back.  Writing it would freeze a
        # name that follows the anchors, so a chart whose anchors changed
        # would keep a label describing the ones it no longer has.
        if label != chart_label(anchors):
            lines.append(f"label = {toml_value(label)}")
    return lines

Framework dataclass

The built coordinate system: the trees, the charts, and their provenance.

Construct one with :meth:build from a :class:FrameworkSpec. Everything a coordinate depends on is decided once, when the framework is built, so that a batch run against it later cannot move the frame under its own results.

Source code in src/hifuku/framework.py
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
@dataclass
class Framework:
    """The built coordinate system: the trees, the charts, and their provenance.

    Construct one with :meth:`build` from a :class:`FrameworkSpec`.  Everything
    a coordinate depends on is decided once, when the framework is built, so
    that a batch run against it later cannot move the frame under its own
    results.
    """

    taxon_table: object                     # TaxonTable
    alignments: list                        # list[AlignmentInfo]
    charts: list                            # list[FrameworkChart]
    model: str = ""
    metric_w: float = 0.5
    min_occupancy: float = MIN_TAXON_OCCUPANCY
    provenance: dict = field(default_factory=dict)
    #: What building this framework cost, keyed ``<step>/<clock>``.  Neighbor
    #: joining is the expensive step and it is paid once however many batches
    #: run inside the framework, so its cost belongs here rather than in any one
    #: run.  A framework read from a file written without it holds an empty
    #: mapping, so a reader gets zero rather than an error.
    timing: dict = field(default_factory=dict)

    def __post_init__(self):
        self._by_label = {a.label: a for a in self.alignments}

    @classmethod
    def build(cls, spec: "FrameworkSpec", *, clock=None) -> "Framework":
        """Read the alignments, build the trees, and embed the charts.

        The three steps scale differently, so each takes its own span on the
        clock.  Neighbor joining costs the cube of the taxon count and takes
        over on a large namespace, where reading the alignments and embedding
        the triangles do not.

        Every triangle is embedded before the framework returns, so a chart that
        will not embed reports in seconds rather than after a survey has run.
        """
        from hifuku.alignment import load_alignment, peek_seq_type
        from hifuku.anchor_triangle import AnchorTriangle
        from hifuku.cli import _resolve_model
        from hifuku.nj import nj_tree, tree_distances
        from hifuku.taxa import TaxonTable
        from hifuku.timing import RunClock

        clock = clock if clock is not None else RunClock()
        tt = TaxonTable()
        labels = sorted(spec.alignments)
        paths = {label: str(spec.alignments[label]) for label in labels}

        with clock.span("prepare/alignments"):
            alns = {label: load_alignment(paths[label], tt) for label in labels}
            _model, model_label = _resolve_model(
                spec.model, peek_seq_type(paths[labels[0]]))

        with clock.span("prepare/trees"):
            # The correction reports what it capped, and the framework records
            # it.  ``tree_distances`` is the one place the matrix is built, so
            # these statistics describe the matrix the tree came from.
            occ = spec.min_occupancy
            corrections = {label: tree_distances(alns[label],
                                                 min_occupancy=occ)[2]
                           for label in labels}
            trees = {label: nj_tree(alns[label], tt, label=label,
                                    min_occupancy=occ)
                     for label in labels}

        with clock.span("prepare/digests"):
            # The bytes are read once, and the digest is of the bytes the
            # framework holds, so the two cannot disagree.
            sources = {label: Path(paths[label]).read_bytes() for label in labels}
            infos = [AlignmentInfo(label, trees[label], paths[label],
                                   hashlib.sha256(sources[label]).hexdigest(),
                                   corrections[label], source=sources[label])
                     for label in labels]

        with clock.span("prepare/charts"):
            charts = []
            for i, anchors in enumerate(spec.charts):
                r = [trees[a] for a in anchors]
                try:
                    triangle = AnchorTriangle.from_anchors(
                        r[0], r[1], r[2], w=spec.w)
                except ValueError as exc:
                    raise ValueError(
                        f"chart {i} with anchors {list(anchors)} is not a "
                        f"usable chart:\n  {exc}") from exc
                charts.append(FrameworkChart(anchors=anchors,
                                             triangle=triangle,
                                             label=spec.chart_labels[i]))

        return cls(taxon_table=tt, alignments=infos, charts=charts,
                   model=model_label, metric_w=spec.w,
                   min_occupancy=spec.min_occupancy,
                   provenance=_framework_provenance(),
                   timing=_timing_attrs(clock))

    def digest(self) -> str:
        """The key two frameworks are compared on.

        Covers what the framework produced rather than what went into it: the
        taxon set, the trees, the chart geometry, the model and the metric
        weight.  The niche size and origin are not here, because they belong to
        a run and two runs at different resolutions share these coordinates.
        """
        return framework_digest(
            taxa=list(self.taxon_table.labels),
            alignments=[(a.label, a.alignment_sha256, a.nj_tree.as_newick())
                        for a in self.alignments],
            charts=[(c.anchors,
                     np.stack([c.triangle.P1, c.triangle.P2, c.triangle.P3]),
                     c.triangle.dist, c.triangle.qual)
                    for c in self.charts],
            model=self.model, metric_w=self.metric_w)

    def write(self, group) -> None:
        """Write this framework into one HDF5 group.

        The digest is stored beside the parts it covers, so a reader can check
        what it was handed against what it was told.  Each alignment gets a
        group named for it, because ``framework/alignments/PF00410`` is what a
        reader wants to type.
        """
        from hifuku.anchor_triangle import triangle_quality

        group.attrs["digest"] = self.digest()
        group.attrs["digest_scheme"] = DIGEST_SCHEME
        group.attrs["model"] = self.model
        group.attrs["metric_w"] = float(self.metric_w)
        group.attrs["min_occupancy"] = float(self.min_occupancy)
        for key, value in self.provenance.items():
            group.attrs[key] = value
        # What the build cost.  This is not digested: two frameworks that define
        # the same coordinates are the same framework however long each took.
        for key, value in self.timing.items():
            group.attrs[f"timing/{key}"] = value

        # In the table's own order, not sorted.  A taxon's position here is its
        # global index, the index fixes the leaf order every tree is numbered
        # in, and a walk picks a node by drawing an index.  Sorting on the way
        # out renumbered every taxon, so a framework read back from a file
        # numbered its trees differently from the one that wrote it and sent an
        # otherwise identical survey somewhere else.
        group.create_dataset(
            "namespace/taxa",
            data=np.array(self.taxon_table.labels, dtype=object),
            dtype=_STR_DTYPE)

        for info in self.alignments:
            g = group.create_group(f"alignments/{info.label}")
            g.attrs["label"] = info.label
            g.attrs["path"] = str(info.alignment_path or "")
            g.attrs["sha256"] = info.alignment_sha256 or ""
            g.create_dataset("nj_newick", data=info.nj_tree.as_newick(),
                             dtype=_STR_DTYPE)
            # The bytes of the alignment file, so that the survey needs no file
            # outside this one.  They digest to the sha256 attribute.
            if info.source is not None:
                g.create_dataset("source",
                                 data=np.frombuffer(info.source, dtype=np.uint8),
                                 compression="gzip", compression_opts=6)
            # What the distance correction did before neighbor joining ran.  A
            # capped pair is neither its own distance nor an additive estimate
            # of it, so the count, the pairs, and the distances the cap sits
            # among are recorded for a reader to judge.
            stats = info.correction
            if stats is not None:
                k = g.create_group("distance_correction")
                k.attrs["model"] = stats.model
                k.attrs["p_saturating"] = float(stats.p_saturating)
                k.attrs["n_taxa"] = int(stats.n_taxa)
                k.attrs["n_taxa_dropped"] = int(stats.n_taxa_dropped)
                k.attrs["n_pairs"] = int(stats.n_pairs)
                k.attrs["n_saturated"] = int(stats.n_saturated)
                k.attrs["cap"] = float(stats.cap)
                k.attrs["d_median"] = float(stats.d_median)
                k.attrs["d_p95"] = float(stats.d_p95)
                k.attrs["d_max"] = float(stats.d_max)
                k.create_dataset(
                    "saturated_pairs",
                    data=np.asarray(stats.saturated_pairs,
                                    dtype=np.int32).reshape(-1, 2))

        for i, chart in enumerate(self.charts):
            tri = chart.triangle
            c = group.create_group(f"charts/{i}")
            c.attrs["anchors"] = np.array(list(chart.anchors), dtype=object)
            # A name, not an identity.  The group stays numbered because a
            # chart is referred to by position from a batch and from every
            # stored niche, and a name a reader may change cannot be that.
            c.attrs["label"] = chart.label
            Q, _lam_min, _lam_max = triangle_quality(tri.P1, tri.P2, tri.P3)
            c.attrs["Q"] = float(Q)
            c.create_dataset("P", data=np.stack(
                [tri.P1, tri.P2, tri.P3]).astype(np.float64))
            c.create_dataset("dist", data=tri.dist.astype(np.float64))
            c.create_dataset("qual", data=tri.qual.astype(np.float64))

    @classmethod
    def read(cls, group) -> "Framework":
        """Rebuild a framework from one HDF5 group.

        The digest is recomputed from what was read and checked against the
        stored one.  A file truncated in transit, or edited by hand, is refused
        here rather than becoming a framework that later runs are checked
        against.

        A file written under an older digest scheme is read and not refused.
        Its digest covers what a digest covered then, so it cannot match one
        computed now, and refusing it would make a change to the scheme destroy
        the files written before it.  Such a framework carries no identity a
        later run can be checked against, so the reader is warned and told what
        that costs.  See ``DIGEST_SCHEME``.
        """
        from hifuku.anchor_triangle import AnchorTriangle
        from hifuku.archive import _set_global_leaf_indices
        from hifuku.metric import BranchScoreMetric
        from hifuku.nj import DistanceCorrectionStats
        from hifuku.taxa import TaxonTable
        from hifuku.tree_io import read_tree

        metric_w = float(group.attrs["metric_w"])
        provenance = {k: _s(v) for k, v in group.attrs.items()
                      if k not in ("digest", "digest_scheme", "model",
                                   "metric_w", "min_occupancy")
                      and not k.startswith("timing/")}
        timing = {k[len("timing/"):]: (v.item() if hasattr(v, "item") else v)
                  for k, v in group.attrs.items() if k.startswith("timing/")}

        tt = TaxonTable()
        for label in group["namespace/taxa"][:]:
            tt.require(_s(label))

        alignments = []
        for label in sorted(group["alignments"]):
            g = group[f"alignments/{label}"]
            tree = read_tree(_s(g["nj_newick"][()]), tt, from_string=True)
            _set_global_leaf_indices(tree, tt)
            correction = None
            if "distance_correction" in g:
                k = g["distance_correction"]
                correction = DistanceCorrectionStats(
                    model=_s(k.attrs["model"]),
                    p_saturating=float(k.attrs["p_saturating"]),
                    n_taxa=int(k.attrs["n_taxa"]),
                    n_taxa_dropped=int(k.attrs["n_taxa_dropped"]),
                    n_pairs=int(k.attrs["n_pairs"]),
                    n_saturated=int(k.attrs["n_saturated"]),
                    saturated_pairs=np.asarray(k["saturated_pairs"][()],
                                               dtype=np.int32).reshape(-1, 2),
                    cap=float(k.attrs["cap"]),
                    d_median=float(k.attrs["d_median"]),
                    d_p95=float(k.attrs["d_p95"]),
                    d_max=float(k.attrs["d_max"]))
            alignments.append(AlignmentInfo(
                _s(g.attrs["label"]), tree, _s(g.attrs["path"]),
                _s(g.attrs["sha256"]), correction,
                source=bytes(g["source"][()]) if "source" in g else None))

        by_label = {a.label: a.nj_tree for a in alignments}
        charts = []
        for key in sorted(group["charts"], key=int):
            c = group[f"charts/{key}"]
            anchors = tuple(_s(a) for a in c.attrs["anchors"])
            P = c["P"][:]
            charts.append(FrameworkChart(
                anchors=anchors,
                label=_s(c.attrs["label"]) if "label" in c.attrs else "",
                triangle=AnchorTriangle(
                    P1=P[0], P2=P[1], P3=P[2],
                    r1=by_label[anchors[0]], r2=by_label[anchors[1]],
                    r3=by_label[anchors[2]],
                    dist=c["dist"][:], qual=c["qual"][:],
                    metric=BranchScoreMetric(w=metric_w))))

        framework = cls(taxon_table=tt, alignments=alignments, charts=charts,
                        model=_s(group.attrs["model"]), metric_w=metric_w,
                        min_occupancy=float(group.attrs["min_occupancy"]),
                        provenance=provenance, timing=timing)
        scheme = _s(group.attrs.get("digest_scheme", ""))
        stored = _s(group.attrs["digest"])
        if scheme != DIGEST_SCHEME:
            # Written under different digest rules, so its digest reads what a
            # digest read then and cannot match what one reads now.  The
            # coordinates themselves are whatever the file says they are, so the
            # framework is returned and the reader is told what it cannot do
            # with it.
            warnings.warn(
                f"this framework was written under digest scheme "
                f"{scheme or 'none'} and this is {DIGEST_SCHEME}, so its "
                f"recorded digest {stored[:12]} cannot be checked.  What the "
                f"file holds is readable and its coordinates are unchanged.  "
                f"What it cannot do is identify itself to a framework built "
                f"now, so a new run will not append to it and an illumination "
                f"in it cannot be continued.  Build the framework again to do "
                f"either.",
                RuntimeWarning, stacklevel=2)
        elif framework.digest() != stored:
            raise ValueError(
                f"this framework does not match its own digest: it records "
                f"{stored[:12]} and what was read digests to "
                f"{framework.digest()[:12]}; the file has been edited or "
                "damaged, and nothing can be checked against it")
        return framework

    def check_spec(self, spec: "FrameworkSpec") -> None:
        """Raise unless this framework is what ``spec`` asks for.

        Appending to a project file uses the framework the file already holds,
        which saves rebuilding every tree.  That saving is only safe if the
        batch was asking for those coordinates, so this compares the inputs a
        framework is built from: the alignment files and their contents, the
        chart anchors and their order, the substitution model, the metric
        weight and the occupancy floor.

        Every one of those is recorded, so the check costs a file digest per
        alignment rather than a neighbor-joining pass.

        A spec names each alignment by the path it had when the spec was
        written.  A file at that path must be the recorded alignment.  A path
        with no file there is not checked: the alignment has moved, and the
        framework holds it or finds it by its digest.

        Raises
        ------
        ValueError
            The spec asks for different coordinates.  The message names the
            first thing that differs.
        """
        from hifuku.cli import _resolve_model
        from hifuku.alignment import _read_character_matrix

        labels = sorted(spec.alignments)
        if labels != sorted(self.labels):
            raise ValueError(
                f"this framework pools {sorted(self.labels)} and the batch "
                f"asks for {labels}")
        for label in labels:
            path = str(spec.alignments[label])
            if not Path(path).is_file():
                continue
            found = _sha256(path)
            recorded = self.alignment(label).alignment_sha256
            if recorded and found != recorded:
                raise ValueError(
                    f"the alignment for {label!r} at {path} is not the one "
                    f"this framework was built from: it records "
                    f"{recorded[:12]} and the file digests to {found[:12]}")

        anchors = [tuple(c.anchors) for c in self.charts]
        if [tuple(c) for c in spec.charts] != anchors:
            raise ValueError(
                f"this framework holds the charts {anchors} and the batch "
                f"asks for {[tuple(c) for c in spec.charts]}; a chart is "
                "referred to by position, so the order has to agree too")

        # DNA or protein, read from the alignment this framework holds or
        # finds, which the loop above has checked against any file the spec
        # names.
        first = self.alignment(labels[0])
        text = alignment_source(first, paths=[str(spec.alignments[labels[0]])])
        seq_type = _read_character_matrix(None, "fasta", data=text.decode())[1]
        _model, model_label = _resolve_model(spec.model, seq_type)
        for name, mine, theirs in (("model", self.model, model_label),
                                   ("metric weight", self.metric_w, spec.w),
                                   ("occupancy floor", self.min_occupancy,
                                    spec.min_occupancy)):
            if mine != theirs:
                raise ValueError(
                    f"this framework was built with {name} {mine!r} and the "
                    f"batch asks for {theirs!r}")

    def alignment(self, label: str) -> "AlignmentInfo":
        """The pool entry with this label."""
        try:
            return self._by_label[label]
        except KeyError:
            raise KeyError(
                f"this framework holds no alignment labelled {label!r}; it "
                f"holds {sorted(self._by_label)}") from None

    @property
    def labels(self) -> list:
        """The alignment labels, in the order the framework stores them."""
        return [a.label for a in self.alignments]

    @property
    def chart_labels(self) -> list:
        """The chart labels, in chart order."""
        return [c.label for c in self.charts]

    def chart(self, key) -> "FrameworkChart":
        """Return one chart, given either its label or its position.

        A chart can be named two ways.  Its position is the integer a batch
        file writes as ``chart = 0``, and it is stored with every surveyed
        niche.  Its label is the text a person reads, ``capsid+tf2s+vltf3`` by
        default, and a caller may set it to anything.

        Both are accepted here so that analysis code can select by the name a
        reader knows, while stored data keeps referring to the position.  The
        position is used for storage because a label may be changed and a
        stored reference must not move when it is.

        Parameters
        ----------
        key : int or str
            A position in ``charts``, or a chart label.

        Raises
        ------
        KeyError
            No chart carries this label.
        IndexError
            This position is past the end of ``charts``.
        """
        return self.charts[self.chart_index(key)]

    def chart_index(self, key) -> int:
        """Return the position of a chart, given its label or its position.

        A batch and a survey record refer to a chart by position, so code that
        takes a label from a user converts it here before storing anything.
        """
        if isinstance(key, (int, np.integer)):
            return int(key)
        for i, chart in enumerate(self.charts):
            if chart.label == key:
                return i
        raise KeyError(
            f"this framework holds no chart labelled {key!r}; it holds "
            f"{self.chart_labels}")

    @property
    def n_taxa(self) -> int:
        return len(self.taxon_table)

    @property
    def wall_seconds(self) -> float:
        """Elapsed seconds this framework took to build.

        Paid once, however many batches then run inside it.  A framework read
        from a file that recorded no timing reports zero.
        """
        return float(self.timing.get("total/wall", 0.0))

    @property
    def cpu_seconds(self) -> float:
        """Processor seconds the build held, user and system together."""
        return float(self.timing.get("total/cpu", 0.0))

    def timing_report(self) -> str:
        """What the build cost, step by step, longest first."""
        steps = sorted(
            {k.rsplit("/", 1)[0] for k in self.timing if k.endswith("/wall")},
            key=lambda s: -float(self.timing.get(f"{s}/wall", 0.0)))
        if not steps:
            return "this framework carries no timing"
        width = max(len(s) for s in steps)
        lines = [f"{'step':>{width}}  {'wall s':>9} {'cpu s':>9}"]
        for step in steps:
            lines.append(
                f"{step:>{width}}  {self.timing.get(f'{step}/wall', 0.0):9.2f} "
                f"{self.timing.get(f'{step}/cpu', 0.0):9.2f}")
        return "\n".join(lines)

labels property

labels: list

The alignment labels, in the order the framework stores them.

chart_labels property

chart_labels: list

The chart labels, in chart order.

wall_seconds property

wall_seconds: float

Elapsed seconds this framework took to build.

Paid once, however many batches then run inside it. A framework read from a file that recorded no timing reports zero.

cpu_seconds property

cpu_seconds: float

Processor seconds the build held, user and system together.

build classmethod

build(spec: 'FrameworkSpec', *, clock=None) -> 'Framework'

Read the alignments, build the trees, and embed the charts.

The three steps scale differently, so each takes its own span on the clock. Neighbor joining costs the cube of the taxon count and takes over on a large namespace, where reading the alignments and embedding the triangles do not.

Every triangle is embedded before the framework returns, so a chart that will not embed reports in seconds rather than after a survey has run.

Source code in src/hifuku/framework.py
@classmethod
def build(cls, spec: "FrameworkSpec", *, clock=None) -> "Framework":
    """Read the alignments, build the trees, and embed the charts.

    The three steps scale differently, so each takes its own span on the
    clock.  Neighbor joining costs the cube of the taxon count and takes
    over on a large namespace, where reading the alignments and embedding
    the triangles do not.

    Every triangle is embedded before the framework returns, so a chart that
    will not embed reports in seconds rather than after a survey has run.
    """
    from hifuku.alignment import load_alignment, peek_seq_type
    from hifuku.anchor_triangle import AnchorTriangle
    from hifuku.cli import _resolve_model
    from hifuku.nj import nj_tree, tree_distances
    from hifuku.taxa import TaxonTable
    from hifuku.timing import RunClock

    clock = clock if clock is not None else RunClock()
    tt = TaxonTable()
    labels = sorted(spec.alignments)
    paths = {label: str(spec.alignments[label]) for label in labels}

    with clock.span("prepare/alignments"):
        alns = {label: load_alignment(paths[label], tt) for label in labels}
        _model, model_label = _resolve_model(
            spec.model, peek_seq_type(paths[labels[0]]))

    with clock.span("prepare/trees"):
        # The correction reports what it capped, and the framework records
        # it.  ``tree_distances`` is the one place the matrix is built, so
        # these statistics describe the matrix the tree came from.
        occ = spec.min_occupancy
        corrections = {label: tree_distances(alns[label],
                                             min_occupancy=occ)[2]
                       for label in labels}
        trees = {label: nj_tree(alns[label], tt, label=label,
                                min_occupancy=occ)
                 for label in labels}

    with clock.span("prepare/digests"):
        # The bytes are read once, and the digest is of the bytes the
        # framework holds, so the two cannot disagree.
        sources = {label: Path(paths[label]).read_bytes() for label in labels}
        infos = [AlignmentInfo(label, trees[label], paths[label],
                               hashlib.sha256(sources[label]).hexdigest(),
                               corrections[label], source=sources[label])
                 for label in labels]

    with clock.span("prepare/charts"):
        charts = []
        for i, anchors in enumerate(spec.charts):
            r = [trees[a] for a in anchors]
            try:
                triangle = AnchorTriangle.from_anchors(
                    r[0], r[1], r[2], w=spec.w)
            except ValueError as exc:
                raise ValueError(
                    f"chart {i} with anchors {list(anchors)} is not a "
                    f"usable chart:\n  {exc}") from exc
            charts.append(FrameworkChart(anchors=anchors,
                                         triangle=triangle,
                                         label=spec.chart_labels[i]))

    return cls(taxon_table=tt, alignments=infos, charts=charts,
               model=model_label, metric_w=spec.w,
               min_occupancy=spec.min_occupancy,
               provenance=_framework_provenance(),
               timing=_timing_attrs(clock))

digest

digest() -> str

The key two frameworks are compared on.

Covers what the framework produced rather than what went into it: the taxon set, the trees, the chart geometry, the model and the metric weight. The niche size and origin are not here, because they belong to a run and two runs at different resolutions share these coordinates.

Source code in src/hifuku/framework.py
def digest(self) -> str:
    """The key two frameworks are compared on.

    Covers what the framework produced rather than what went into it: the
    taxon set, the trees, the chart geometry, the model and the metric
    weight.  The niche size and origin are not here, because they belong to
    a run and two runs at different resolutions share these coordinates.
    """
    return framework_digest(
        taxa=list(self.taxon_table.labels),
        alignments=[(a.label, a.alignment_sha256, a.nj_tree.as_newick())
                    for a in self.alignments],
        charts=[(c.anchors,
                 np.stack([c.triangle.P1, c.triangle.P2, c.triangle.P3]),
                 c.triangle.dist, c.triangle.qual)
                for c in self.charts],
        model=self.model, metric_w=self.metric_w)

write

write(group) -> None

Write this framework into one HDF5 group.

The digest is stored beside the parts it covers, so a reader can check what it was handed against what it was told. Each alignment gets a group named for it, because framework/alignments/PF00410 is what a reader wants to type.

Source code in src/hifuku/framework.py
def write(self, group) -> None:
    """Write this framework into one HDF5 group.

    The digest is stored beside the parts it covers, so a reader can check
    what it was handed against what it was told.  Each alignment gets a
    group named for it, because ``framework/alignments/PF00410`` is what a
    reader wants to type.
    """
    from hifuku.anchor_triangle import triangle_quality

    group.attrs["digest"] = self.digest()
    group.attrs["digest_scheme"] = DIGEST_SCHEME
    group.attrs["model"] = self.model
    group.attrs["metric_w"] = float(self.metric_w)
    group.attrs["min_occupancy"] = float(self.min_occupancy)
    for key, value in self.provenance.items():
        group.attrs[key] = value
    # What the build cost.  This is not digested: two frameworks that define
    # the same coordinates are the same framework however long each took.
    for key, value in self.timing.items():
        group.attrs[f"timing/{key}"] = value

    # In the table's own order, not sorted.  A taxon's position here is its
    # global index, the index fixes the leaf order every tree is numbered
    # in, and a walk picks a node by drawing an index.  Sorting on the way
    # out renumbered every taxon, so a framework read back from a file
    # numbered its trees differently from the one that wrote it and sent an
    # otherwise identical survey somewhere else.
    group.create_dataset(
        "namespace/taxa",
        data=np.array(self.taxon_table.labels, dtype=object),
        dtype=_STR_DTYPE)

    for info in self.alignments:
        g = group.create_group(f"alignments/{info.label}")
        g.attrs["label"] = info.label
        g.attrs["path"] = str(info.alignment_path or "")
        g.attrs["sha256"] = info.alignment_sha256 or ""
        g.create_dataset("nj_newick", data=info.nj_tree.as_newick(),
                         dtype=_STR_DTYPE)
        # The bytes of the alignment file, so that the survey needs no file
        # outside this one.  They digest to the sha256 attribute.
        if info.source is not None:
            g.create_dataset("source",
                             data=np.frombuffer(info.source, dtype=np.uint8),
                             compression="gzip", compression_opts=6)
        # What the distance correction did before neighbor joining ran.  A
        # capped pair is neither its own distance nor an additive estimate
        # of it, so the count, the pairs, and the distances the cap sits
        # among are recorded for a reader to judge.
        stats = info.correction
        if stats is not None:
            k = g.create_group("distance_correction")
            k.attrs["model"] = stats.model
            k.attrs["p_saturating"] = float(stats.p_saturating)
            k.attrs["n_taxa"] = int(stats.n_taxa)
            k.attrs["n_taxa_dropped"] = int(stats.n_taxa_dropped)
            k.attrs["n_pairs"] = int(stats.n_pairs)
            k.attrs["n_saturated"] = int(stats.n_saturated)
            k.attrs["cap"] = float(stats.cap)
            k.attrs["d_median"] = float(stats.d_median)
            k.attrs["d_p95"] = float(stats.d_p95)
            k.attrs["d_max"] = float(stats.d_max)
            k.create_dataset(
                "saturated_pairs",
                data=np.asarray(stats.saturated_pairs,
                                dtype=np.int32).reshape(-1, 2))

    for i, chart in enumerate(self.charts):
        tri = chart.triangle
        c = group.create_group(f"charts/{i}")
        c.attrs["anchors"] = np.array(list(chart.anchors), dtype=object)
        # A name, not an identity.  The group stays numbered because a
        # chart is referred to by position from a batch and from every
        # stored niche, and a name a reader may change cannot be that.
        c.attrs["label"] = chart.label
        Q, _lam_min, _lam_max = triangle_quality(tri.P1, tri.P2, tri.P3)
        c.attrs["Q"] = float(Q)
        c.create_dataset("P", data=np.stack(
            [tri.P1, tri.P2, tri.P3]).astype(np.float64))
        c.create_dataset("dist", data=tri.dist.astype(np.float64))
        c.create_dataset("qual", data=tri.qual.astype(np.float64))

read classmethod

read(group) -> 'Framework'

Rebuild a framework from one HDF5 group.

The digest is recomputed from what was read and checked against the stored one. A file truncated in transit, or edited by hand, is refused here rather than becoming a framework that later runs are checked against.

A file written under an older digest scheme is read and not refused. Its digest covers what a digest covered then, so it cannot match one computed now, and refusing it would make a change to the scheme destroy the files written before it. Such a framework carries no identity a later run can be checked against, so the reader is warned and told what that costs. See DIGEST_SCHEME.

Source code in src/hifuku/framework.py
@classmethod
def read(cls, group) -> "Framework":
    """Rebuild a framework from one HDF5 group.

    The digest is recomputed from what was read and checked against the
    stored one.  A file truncated in transit, or edited by hand, is refused
    here rather than becoming a framework that later runs are checked
    against.

    A file written under an older digest scheme is read and not refused.
    Its digest covers what a digest covered then, so it cannot match one
    computed now, and refusing it would make a change to the scheme destroy
    the files written before it.  Such a framework carries no identity a
    later run can be checked against, so the reader is warned and told what
    that costs.  See ``DIGEST_SCHEME``.
    """
    from hifuku.anchor_triangle import AnchorTriangle
    from hifuku.archive import _set_global_leaf_indices
    from hifuku.metric import BranchScoreMetric
    from hifuku.nj import DistanceCorrectionStats
    from hifuku.taxa import TaxonTable
    from hifuku.tree_io import read_tree

    metric_w = float(group.attrs["metric_w"])
    provenance = {k: _s(v) for k, v in group.attrs.items()
                  if k not in ("digest", "digest_scheme", "model",
                               "metric_w", "min_occupancy")
                  and not k.startswith("timing/")}
    timing = {k[len("timing/"):]: (v.item() if hasattr(v, "item") else v)
              for k, v in group.attrs.items() if k.startswith("timing/")}

    tt = TaxonTable()
    for label in group["namespace/taxa"][:]:
        tt.require(_s(label))

    alignments = []
    for label in sorted(group["alignments"]):
        g = group[f"alignments/{label}"]
        tree = read_tree(_s(g["nj_newick"][()]), tt, from_string=True)
        _set_global_leaf_indices(tree, tt)
        correction = None
        if "distance_correction" in g:
            k = g["distance_correction"]
            correction = DistanceCorrectionStats(
                model=_s(k.attrs["model"]),
                p_saturating=float(k.attrs["p_saturating"]),
                n_taxa=int(k.attrs["n_taxa"]),
                n_taxa_dropped=int(k.attrs["n_taxa_dropped"]),
                n_pairs=int(k.attrs["n_pairs"]),
                n_saturated=int(k.attrs["n_saturated"]),
                saturated_pairs=np.asarray(k["saturated_pairs"][()],
                                           dtype=np.int32).reshape(-1, 2),
                cap=float(k.attrs["cap"]),
                d_median=float(k.attrs["d_median"]),
                d_p95=float(k.attrs["d_p95"]),
                d_max=float(k.attrs["d_max"]))
        alignments.append(AlignmentInfo(
            _s(g.attrs["label"]), tree, _s(g.attrs["path"]),
            _s(g.attrs["sha256"]), correction,
            source=bytes(g["source"][()]) if "source" in g else None))

    by_label = {a.label: a.nj_tree for a in alignments}
    charts = []
    for key in sorted(group["charts"], key=int):
        c = group[f"charts/{key}"]
        anchors = tuple(_s(a) for a in c.attrs["anchors"])
        P = c["P"][:]
        charts.append(FrameworkChart(
            anchors=anchors,
            label=_s(c.attrs["label"]) if "label" in c.attrs else "",
            triangle=AnchorTriangle(
                P1=P[0], P2=P[1], P3=P[2],
                r1=by_label[anchors[0]], r2=by_label[anchors[1]],
                r3=by_label[anchors[2]],
                dist=c["dist"][:], qual=c["qual"][:],
                metric=BranchScoreMetric(w=metric_w))))

    framework = cls(taxon_table=tt, alignments=alignments, charts=charts,
                    model=_s(group.attrs["model"]), metric_w=metric_w,
                    min_occupancy=float(group.attrs["min_occupancy"]),
                    provenance=provenance, timing=timing)
    scheme = _s(group.attrs.get("digest_scheme", ""))
    stored = _s(group.attrs["digest"])
    if scheme != DIGEST_SCHEME:
        # Written under different digest rules, so its digest reads what a
        # digest read then and cannot match what one reads now.  The
        # coordinates themselves are whatever the file says they are, so the
        # framework is returned and the reader is told what it cannot do
        # with it.
        warnings.warn(
            f"this framework was written under digest scheme "
            f"{scheme or 'none'} and this is {DIGEST_SCHEME}, so its "
            f"recorded digest {stored[:12]} cannot be checked.  What the "
            f"file holds is readable and its coordinates are unchanged.  "
            f"What it cannot do is identify itself to a framework built "
            f"now, so a new run will not append to it and an illumination "
            f"in it cannot be continued.  Build the framework again to do "
            f"either.",
            RuntimeWarning, stacklevel=2)
    elif framework.digest() != stored:
        raise ValueError(
            f"this framework does not match its own digest: it records "
            f"{stored[:12]} and what was read digests to "
            f"{framework.digest()[:12]}; the file has been edited or "
            "damaged, and nothing can be checked against it")
    return framework

check_spec

check_spec(spec: 'FrameworkSpec') -> None

Raise unless this framework is what spec asks for.

Appending to a project file uses the framework the file already holds, which saves rebuilding every tree. That saving is only safe if the batch was asking for those coordinates, so this compares the inputs a framework is built from: the alignment files and their contents, the chart anchors and their order, the substitution model, the metric weight and the occupancy floor.

Every one of those is recorded, so the check costs a file digest per alignment rather than a neighbor-joining pass.

A spec names each alignment by the path it had when the spec was written. A file at that path must be the recorded alignment. A path with no file there is not checked: the alignment has moved, and the framework holds it or finds it by its digest.

Raises:

Type Description
ValueError

The spec asks for different coordinates. The message names the first thing that differs.

Source code in src/hifuku/framework.py
def check_spec(self, spec: "FrameworkSpec") -> None:
    """Raise unless this framework is what ``spec`` asks for.

    Appending to a project file uses the framework the file already holds,
    which saves rebuilding every tree.  That saving is only safe if the
    batch was asking for those coordinates, so this compares the inputs a
    framework is built from: the alignment files and their contents, the
    chart anchors and their order, the substitution model, the metric
    weight and the occupancy floor.

    Every one of those is recorded, so the check costs a file digest per
    alignment rather than a neighbor-joining pass.

    A spec names each alignment by the path it had when the spec was
    written.  A file at that path must be the recorded alignment.  A path
    with no file there is not checked: the alignment has moved, and the
    framework holds it or finds it by its digest.

    Raises
    ------
    ValueError
        The spec asks for different coordinates.  The message names the
        first thing that differs.
    """
    from hifuku.cli import _resolve_model
    from hifuku.alignment import _read_character_matrix

    labels = sorted(spec.alignments)
    if labels != sorted(self.labels):
        raise ValueError(
            f"this framework pools {sorted(self.labels)} and the batch "
            f"asks for {labels}")
    for label in labels:
        path = str(spec.alignments[label])
        if not Path(path).is_file():
            continue
        found = _sha256(path)
        recorded = self.alignment(label).alignment_sha256
        if recorded and found != recorded:
            raise ValueError(
                f"the alignment for {label!r} at {path} is not the one "
                f"this framework was built from: it records "
                f"{recorded[:12]} and the file digests to {found[:12]}")

    anchors = [tuple(c.anchors) for c in self.charts]
    if [tuple(c) for c in spec.charts] != anchors:
        raise ValueError(
            f"this framework holds the charts {anchors} and the batch "
            f"asks for {[tuple(c) for c in spec.charts]}; a chart is "
            "referred to by position, so the order has to agree too")

    # DNA or protein, read from the alignment this framework holds or
    # finds, which the loop above has checked against any file the spec
    # names.
    first = self.alignment(labels[0])
    text = alignment_source(first, paths=[str(spec.alignments[labels[0]])])
    seq_type = _read_character_matrix(None, "fasta", data=text.decode())[1]
    _model, model_label = _resolve_model(spec.model, seq_type)
    for name, mine, theirs in (("model", self.model, model_label),
                               ("metric weight", self.metric_w, spec.w),
                               ("occupancy floor", self.min_occupancy,
                                spec.min_occupancy)):
        if mine != theirs:
            raise ValueError(
                f"this framework was built with {name} {mine!r} and the "
                f"batch asks for {theirs!r}")

alignment

alignment(label: str) -> 'AlignmentInfo'

The pool entry with this label.

Source code in src/hifuku/framework.py
def alignment(self, label: str) -> "AlignmentInfo":
    """The pool entry with this label."""
    try:
        return self._by_label[label]
    except KeyError:
        raise KeyError(
            f"this framework holds no alignment labelled {label!r}; it "
            f"holds {sorted(self._by_label)}") from None

chart

chart(key) -> 'FrameworkChart'

Return one chart, given either its label or its position.

A chart can be named two ways. Its position is the integer a batch file writes as chart = 0, and it is stored with every surveyed niche. Its label is the text a person reads, capsid+tf2s+vltf3 by default, and a caller may set it to anything.

Both are accepted here so that analysis code can select by the name a reader knows, while stored data keeps referring to the position. The position is used for storage because a label may be changed and a stored reference must not move when it is.

Parameters:

Name Type Description Default
key int or str

A position in charts, or a chart label.

required

Raises:

Type Description
KeyError

No chart carries this label.

IndexError

This position is past the end of charts.

Source code in src/hifuku/framework.py
def chart(self, key) -> "FrameworkChart":
    """Return one chart, given either its label or its position.

    A chart can be named two ways.  Its position is the integer a batch
    file writes as ``chart = 0``, and it is stored with every surveyed
    niche.  Its label is the text a person reads, ``capsid+tf2s+vltf3`` by
    default, and a caller may set it to anything.

    Both are accepted here so that analysis code can select by the name a
    reader knows, while stored data keeps referring to the position.  The
    position is used for storage because a label may be changed and a
    stored reference must not move when it is.

    Parameters
    ----------
    key : int or str
        A position in ``charts``, or a chart label.

    Raises
    ------
    KeyError
        No chart carries this label.
    IndexError
        This position is past the end of ``charts``.
    """
    return self.charts[self.chart_index(key)]

chart_index

chart_index(key) -> int

Return the position of a chart, given its label or its position.

A batch and a survey record refer to a chart by position, so code that takes a label from a user converts it here before storing anything.

Source code in src/hifuku/framework.py
def chart_index(self, key) -> int:
    """Return the position of a chart, given its label or its position.

    A batch and a survey record refer to a chart by position, so code that
    takes a label from a user converts it here before storing anything.
    """
    if isinstance(key, (int, np.integer)):
        return int(key)
    for i, chart in enumerate(self.charts):
        if chart.label == key:
            return i
    raise KeyError(
        f"this framework holds no chart labelled {key!r}; it holds "
        f"{self.chart_labels}")

timing_report

timing_report() -> str

What the build cost, step by step, longest first.

Source code in src/hifuku/framework.py
def timing_report(self) -> str:
    """What the build cost, step by step, longest first."""
    steps = sorted(
        {k.rsplit("/", 1)[0] for k in self.timing if k.endswith("/wall")},
        key=lambda s: -float(self.timing.get(f"{s}/wall", 0.0)))
    if not steps:
        return "this framework carries no timing"
    width = max(len(s) for s in steps)
    lines = [f"{'step':>{width}}  {'wall s':>9} {'cpu s':>9}"]
    for step in steps:
        lines.append(
            f"{step:>{width}}  {self.timing.get(f'{step}/wall', 0.0):9.2f} "
            f"{self.timing.get(f'{step}/cpu', 0.0):9.2f}")
    return "\n".join(lines)

FrameworkChart dataclass

One chart: three anchor labels and the triangle they embed.

The anchor order is kept as the chart was built with, because that order fixes which corner of the triangle is which.

label is what a reader selects the chart by. Unset, it is the three anchors joined. It names the chart and nothing else: a chart is identified within a framework by its position, which is what a batch and every stored niche refer to, so renaming one moves nothing.

Source code in src/hifuku/framework.py
@dataclass
class FrameworkChart:
    """One chart: three anchor labels and the triangle they embed.

    The anchor order is kept as the chart was built with, because that order
    fixes which corner of the triangle is which.

    ``label`` is what a reader selects the chart by.  Unset, it is the three
    anchors joined.  It names the chart and nothing else: a chart is identified
    within a framework by its position, which is what a batch and every stored
    niche refer to, so renaming one moves nothing.
    """

    anchors: tuple
    triangle: object                # AnchorTriangle
    label: str = ""

    def __post_init__(self):
        self.anchors = tuple(self.anchors)
        self.label = check_label(self.label or chart_label(self.anchors),
                                 "chart")

explain_mismatch

explain_mismatch(a: 'Framework', b: 'Framework') -> str

Why two frameworks that should agree do not.

A digest says that two frameworks differ and nothing about why. The provenance of each says where it was built, and a difference there is usually the cause: a package version that moved the numerics, a different host, a different device architecture. This names those before it reports the digests, because the digests are the part a reader can do nothing with.

Two frameworks built in one environment differ because their inputs differ, and the report says so rather than listing nothing.

Source code in src/hifuku/framework.py
def explain_mismatch(a: "Framework", b: "Framework") -> str:
    """Why two frameworks that should agree do not.

    A digest says that two frameworks differ and nothing about why.  The
    provenance of each says where it was built, and a difference there is
    usually the cause: a package version that moved the numerics, a different
    host, a different device architecture.  This names those before it reports
    the digests, because the digests are the part a reader can do nothing with.

    Two frameworks built in one environment differ because their inputs differ,
    and the report says so rather than listing nothing.
    """
    lines = []
    for key in _MISMATCH_KEYS:
        first, second = a.provenance.get(key), b.provenance.get(key)
        if first != second:
            lines.append(f"  {key}: {first} against {second}")
    head = (f"these frameworks define different coordinates: "
            f"{a.digest()[:12]} against {b.digest()[:12]}")
    if not lines:
        return (head + "\nThe two were built in the same environment, so the "
                "difference is in the inputs: an alignment, a chart, or a "
                "setting that fixes the coordinates.")
    return (head + "\nThey were built in different environments, which is the "
            "likely cause:\n" + "\n".join(lines))

chart_label

chart_label(anchors) -> str

The name a chart carries when its caller gives it none.

Three anchors joined, which is what a reader recognizes a chart by and what they would have written themselves. It is a name and nothing more: the framework digest does not cover it, so renaming a chart leaves the coordinates it defines unchanged.

Source code in src/hifuku/framework.py
def chart_label(anchors) -> str:
    """The name a chart carries when its caller gives it none.

    Three anchors joined, which is what a reader recognizes a chart by and what
    they would have written themselves.  It is a name and nothing more: the
    framework digest does not cover it, so renaming a chart leaves the
    coordinates it defines unchanged.
    """
    return "+".join(anchors)