Skip to content

Survey IO

A survey file is the HDF5 output of hifuku. It holds one framework, the coordinate system that hifuku.framework builds, and the work done inside it. A file can hold a framework and no runs, and a run is appended in place.

Survey holds one file. It reads and writes the file and checks every seal when it reads. Survey.index gives one row for each run and record. A Run is one batch of work, with the provenance of the process that made it. Each SurveyRecord in a run is one gene surveyed on one chart: its parameters, its elite archive, its checkpoint history and its seal. A BrokenLink reports a record whose ancestry does not hold.

SurveyRun runs one batch of work, a Batch of SurveyTask units, inside a framework that is already built. Cloud collects the elite trees of named runs as CloudPoint values, and Ordination stores one embedding of a cloud.

Survey

One framework and the work done inside it.

Construct one directly, or with :meth:run. A survey may hold no runs at all, which is a coordinate system nobody has surveyed in yet.

save and load are a plain, predictable round trip, and :meth:append_run adds one run to a file already on disk without rewriting what is there. None of the three holds resume or caching logic; that lives in the caller.

Source code in src/hifuku/survey_io.py
 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
 906
 907
 908
 909
 910
 911
 912
 913
 914
 915
 916
 917
 918
 919
 920
 921
 922
 923
 924
 925
 926
 927
 928
 929
 930
 931
 932
 933
 934
 935
 936
 937
 938
 939
 940
 941
 942
 943
 944
 945
 946
 947
 948
 949
 950
 951
 952
 953
 954
 955
 956
 957
 958
 959
 960
 961
 962
 963
 964
 965
 966
 967
 968
 969
 970
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
class Survey:
    """One framework and the work done inside it.

    Construct one directly, or with :meth:`run`.  A survey may hold no runs at
    all, which is a coordinate system nobody has surveyed in yet.

    ``save`` and ``load`` are a plain, predictable round trip, and
    :meth:`append_run` adds one run to a file already on disk without rewriting
    what is there.  None of the three holds resume or caching logic; that lives
    in the caller.
    """

    def __init__(self, framework, runs=None, *, label="", description="",
                 clouds=None, ordinations=None, provenance=None):
        self.framework = framework
        # Runs are held in one canonical order, the order a file lists them in,
        # so that a survey and the same survey reloaded agree row for row.  A
        # caller may build a survey in any order and gets the same table.
        self.runs = sorted(runs or [], key=lambda r: r.group_name)
        #: What this project is called.  Left unset, :meth:`save` takes the
        #: output file's stem, so a file is named after itself rather than
        #: carrying nothing.  A run that is given no label of its own falls
        #: back to this.
        self.label = label
        self.description = description
        #: The named run sets embeddings are built over.  A cloud is made when
        #: one is first asked for, so a survey nobody has embedded holds none.
        self.clouds = list(clouds or [])             # list[Cloud]
        self.ordinations = list(ordinations or [])   # list[Ordination]
        #: How this file itself came to be, as distinct from how a run did.
        self.provenance = dict(provenance or {})

    # -- the framework, reached through the survey --------------------------

    @property
    def taxon_table(self):
        return self.framework.taxon_table

    @property
    def alignments(self) -> list:
        """The alignment pool, as :class:`~hifuku.framework.AlignmentInfo`."""
        return self.framework.alignments

    @property
    def charts(self) -> list:
        """The framework's charts, each an anchor triple and its triangle."""
        return self.framework.charts

    @property
    def metric_w(self) -> float:
        return self.framework.metric_w

    def alignment(self, label):
        """AlignmentInfo for a pool label."""
        return self.framework.alignment(label)

    # -- lineage ------------------------------------------------------------

    def check_lineage(self) -> list:
        """Every illumination whose ancestry no longer holds, and why.

        An illumination that continues another records the run it came from and
        the digest of what that run produced.  The digest is what the parent
        found, so a parent that has since been changed no longer matches what
        its child recorded, and the child is continuing from an archive that is
        not in the file any more.

        Four faults, told apart because they need different answers.  A link is
        ``"changed"`` when the parent is present and its seal or its end state
        is not the one the child started from, or ``"missing"`` when the parent
        is not in the file at all.  A continuation with no seal is
        ``"unsealed"``, because it names a parent and nothing binds it to one.
        Everything further down is ``"ancestor"``: its own link still matches,
        and it is untrustworthy because something above it is not.  That
        distinction is what sends a reader to where a problem started rather
        than to the whole chain at once.

        This compares the links only.  Whether each record still matches its
        own seal is :meth:`verify`.

        Returns
        -------
        list of BrokenLink
            Empty when the file's ancestry holds.  An illumination that began
            from nothing has no ancestry to check and never appears.
        """
        # Index every illumination by the run that holds it, so a parent can be
        # found without scanning.  A run holds one illumination per chart and
        # gene, which is what makes the parent link need no more than a run.
        by_run = {run.run_id: {(rec.chart, rec.gene): rec for rec in run.surveys}
                  for run in self.runs}
        label_of = {run.run_id: run.label for run in self.runs}

        def local_fault(rec):
            if not rec.sealed:
                return "unsealed"
            parent = by_run.get(rec.parent, {}).get((rec.chart, rec.gene))
            if parent is None:
                return "missing"
            if (parent.seal != rec.parent_seal
                    or parent.state_digest != rec.start_state):
                return "changed"
            return None

        continuations = [(run, rec) for run in self.runs for rec in run.surveys
                         if rec.parent != AB_INITIO]
        reasons = {}
        for run, rec in continuations:
            fault = local_fault(rec)
            if fault is not None:
                reasons[(run.run_id, rec.chart, rec.gene)] = fault
        # The runs are listed by name, which is not the order they were made
        # in, so a fault is carried down the chains until nothing changes.
        spreading = True
        while spreading:
            spreading = False
            for run, rec in continuations:
                here = (run.run_id, rec.chart, rec.gene)
                if here not in reasons and \
                        (rec.parent, rec.chart, rec.gene) in reasons:
                    reasons[here] = "ancestor"
                    spreading = True
        return [BrokenLink(run=run.label, chart=rec.chart, gene=rec.gene,
                           reason=reasons[(run.run_id, rec.chart, rec.gene)],
                           parent=label_of.get(rec.parent, rec.parent))
                for run, rec in continuations
                if (run.run_id, rec.chart, rec.gene) in reasons]

    def verify(self) -> list:
        """Every way this survey fails to match its own digests, as text.

        Each record is checked against its seal, each run against its id, and
        each link against its parent.  A record with no seal is listed, because
        nothing it claims is bound to anything.

        This shows that nothing changed after it was sealed, and which state
        each record started from.  It does not show that an end state follows
        from its inputs.  See :func:`hifuku.replay.replay_record` for that.

        Returns
        -------
        list of str
            Empty when every record is sealed and every digest holds.
        """
        problems = _digest_problems(self.runs, self.framework)
        problems += [f"run {b.run}: the record of {b.gene!r} on chart "
                     f"{b.chart} has a broken link to {b.parent}: {b.reason}"
                     for b in self.check_lineage() if b.reason != "unsealed"]
        return problems

    # -- the runs -----------------------------------------------------------

    def run_by_id(self, run_id: str):
        """The run with this id."""
        for run in self.runs:
            if run.run_id == run_id:
                return run
        raise KeyError(
            f"this survey holds no run {run_id!r}; it holds "
            f"{[r.run_id for r in self.runs]}")

    def run_by_label(self, label: str):
        """Return the run carrying this label.

        A label is set by whoever ran the batch, so two runs can carry the same
        one: two people working on two machines may pick the same word, and
        merging their files brings both into view.  A run id cannot collide,
        because it is a digest over the framework, the work and the provenance,
        so :meth:`run_by_id` is the way to name one of an ambiguous pair.

        Parameters
        ----------
        label : str
            A run label.

        Raises
        ------
        KeyError
            No run carries this label.
        ValueError
            More than one run carries it.  The message lists them by group
            name, which ends in the run id, so the call can be repeated with
            :meth:`run_by_id`.
        """
        found = [r for r in self.runs if r.label == label]
        if not found:
            raise KeyError(
                f"this survey holds no run labelled {label!r}; it holds "
                f"{[r.label for r in self.runs]}")
        if len(found) > 1:
            raise ValueError(
                f"{len(found)} runs are labelled {label!r}: "
                f"{[r.group_name for r in found]}; name one by its id")
        return found[0]

    def records(self) -> list:
        """Every ``(run, record)`` pair, in run order then survey order."""
        return [(run, rec) for run in self.runs for rec in run.surveys]

    @property
    def started(self) -> str:
        """When the earliest run began, or the empty string if none did."""
        stamps = [str(r.timing.get("started", "")) for r in self.runs]
        stamps = [s for s in stamps if s]
        return min(stamps) if stamps else ""

    @property
    def finished(self) -> str:
        """When the latest run ended, or the empty string if none did."""
        stamps = [str(r.timing.get("finished", "")) for r in self.runs]
        stamps = [s for s in stamps if s]
        return max(stamps) if stamps else ""

    @property
    def timing(self) -> dict:
        """What the runs cost together, keyed ``<step>/<clock>``.

        A file holding several runs adds their spans, because the runs happened
        one after another from the file's point of view even when they happened
        on different machines.  Read one run's own ``timing`` to compare
        machines.
        """
        total: dict = {}
        for run in self.runs:
            for key, value in run.timing.items():
                if isinstance(value, (int, float)) and not isinstance(value, bool):
                    total[key] = total.get(key, 0.0) + float(value)
        return total

    @property
    def wall_seconds(self) -> float:
        """Elapsed seconds the runs took, preparation included."""
        return float(self.timing.get("total/wall", 0.0))

    @property
    def cpu_seconds(self) -> float:
        """Processor seconds the runs held, user and system together.

        Read against :attr:`wall_seconds`.  A run holding a processor for as
        long as it ran is limited by the host.
        """
        return float(self.timing.get("total/cpu", 0.0))

    @property
    def device_seconds(self) -> float:
        """Seconds spent inside the device engine.  Zero when the engine does
        not measure device time: the host engine and the WebGPU engine."""
        return float(self.timing.get("total/device", 0.0))

    def variations_per_second(self) -> float:
        """Variations the surveys made for each elapsed second of surveying.

        This counts the surveying alone.  Building the charts is left out, so
        the rate compares one engine against another rather than one whole
        command against another.
        """
        records = [rec for _run, rec in self.records()]
        seconds = sum(rec.wall_seconds for rec in records)
        # A survey that halted made halt_iter variations.  One that ran to its
        # budget never set a halt, and made the whole budget.
        variations = sum(rec.halt_iter if rec.halt_iter > 0 else rec.n_iters
                         for rec in records)
        return (variations / seconds) if seconds > 0.0 else 0.0

    def timing_report(self) -> str:
        """The recorded steps as a table, longest first, for a person to read.

        The framework's steps are named apart from the runs', because building
        the charts is paid once and surveying is paid per batch.  Adding the two
        would hide that.
        """
        timing = {f"framework/{k}": v
                  for k, v in self.framework.timing.items()}
        timing.update(self.timing)
        steps = sorted(
            {k.rsplit("/", 1)[0] for k in timing if k.endswith("/wall")},
            key=lambda s: -float(timing.get(f"{s}/wall", 0.0)))
        if not steps:
            return "this survey carries no timing"
        width = max(len(s) for s in steps)
        lines = [f"{'step':>{width}}  {'wall s':>9} {'cpu s':>9} {'device s':>9}"]
        for step in steps:
            lines.append(
                f"{step:>{width}}  {timing.get(f'{step}/wall', 0.0):9.2f} "
                f"{timing.get(f'{step}/cpu', 0.0):9.2f} "
                f"{timing.get(f'{step}/device', 0.0):9.2f}")
        return "\n".join(lines)

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

    @classmethod
    def run(cls, batch, framework, *, device="gpu", backend=None,
            description="", monitor=False) -> "Survey":
        """Run every gene of ``batch`` in ``framework`` and return the Survey.

        This is :class:`SurveyRun` with the loop written out.  Call
        ``SurveyRun`` directly to watch a run, to skip finished work, or to send
        a task to another host.
        """
        run = SurveyRun.prepare(batch, framework, device=device,
                                backend=backend)
        for task in run.tasks:
            run.execute(task, monitor=monitor)
        return cls(framework=framework, runs=[run.finish()],
                   description=description)

    @property
    def metric(self):
        """The cloud-wide tree metric of this survey.

        Built from the NJ tree of every alignment in the pool, so analysis over
        the whole cloud uses one normalization.  A chart carries its own
        ``BranchScoreMetric``, whose weight ``w`` comes from
        that chart alone, so this is not the metric of any one chart.
        """
        from hifuku.anchor_triangle import BranchScoreMetric
        return BranchScoreMetric(w=self.metric_w)

    def archive(self, gene, chart=0, run=None):
        """EliteArchive for a surveyed gene on a chart.

        ``run`` picks between two runs that both surveyed this gene.  Without
        it, a gene surveyed twice raises rather than returning whichever came
        first: choosing between two runs is the reader's question, and the error
        names both so it can be answered.
        """
        found = [(r, rec) for r, rec in self.records()
                 if rec.gene == gene and rec.chart == chart
                 and (run is None or r.run_id == run or r.label == run)]
        if not found:
            raise KeyError(
                f"no survey of {gene!r} on chart {chart}"
                + (f" in run {run!r}" if run is not None else ""))
        if len(found) > 1:
            raise ValueError(
                f"{len(found)} runs surveyed {gene!r} on chart {chart}: "
                f"{[r.group_name for r, _ in found]}; name one with run=")
        return found[0][1].archive

    def frame(self) -> pl.DataFrame:
        """Every elite niche across every run, one row each.

        Columns: ``run``, ``label``, ``gene``, ``chart``, ``chart_label``,
        ``i``, ``j``, ``lam1``, ``lam2``, ``logL`` and ``z``.  Where
        :meth:`index` has a row per survey, this has a row per niche, so it is
        the table to reach for when the question is about where the elites sit
        rather than about which surveys are here.

        The run is a column because two runs of one gene fill the same niches
        with different trees, and a table without it would stack them silently.

        Call ``.to_pandas()`` on the result for callers who want that form.
        """
        labels = self.framework.chart_labels
        rows = []
        for run, rec in self.records():
            arch = rec.archive
            for key in arch.keys:
                lam1, lam2 = arch.niche_center(key)
                elite = arch.elites[key]
                rows.append((run.run_id, run.label, rec.gene, rec.chart,
                             labels[rec.chart], key[0], key[1],
                             lam1, lam2, elite.logL, elite.z))
        return pl.DataFrame(rows, orient="row", schema={
            "run": pl.Utf8, "label": pl.Utf8, "gene": pl.Utf8,
            "chart": pl.Int32, "chart_label": pl.Utf8,
            "i": pl.Int64, "j": pl.Int64,
            "lam1": pl.Float64, "lam2": pl.Float64,
            "logL": pl.Float64, "z": pl.Float64,
        })

    def cloud(self, run_ids=None, *, label=None) -> Cloud:
        """The stored cloud spanning these runs, made and kept if there is none.

        Called bare it means every run in this survey as it stands.  It is a
        fetcher first and a factory second: a cloud spanning exactly this run
        set is returned rather than duplicated, so a notebook cell that reruns
        does not fill the file with copies of one cloud.

        There is no reserved label and no special case for "everything".  A
        cloud given no label is named after the runs it spans, so a reader sees
        which work an embedding covers without opening anything.

        Parameters
        ----------
        run_ids : iterable of str, optional
            The runs to span.  Defaults to every run in this survey.
        label : str, optional
            A name for a cloud that has to be created.  Ignored when one is
            already stored for this run set, since a stored cloud keeps the
            name it was given.
        """
        wanted = tuple(r.run_id for r in self.runs) if run_ids is None \
            else tuple(run_ids)
        for run_id in wanted:
            self.run_by_id(run_id)
        for stored in self.clouds:
            if set(stored.run_ids) == set(wanted):
                return stored

        identity = tuple(self._identities(wanted))
        digest = cloud_digest(run_ids=wanted, identities=identity)
        if label is not None:
            check_label(label, "cloud")
        else:
            label = self._derived_cloud_label(wanted, digest)
        cloud = Cloud(
            label=label, run_ids=wanted, identity=identity,
            cloud_digest=digest,
            content_digest=self._content_digest(wanted),
            created=datetime.datetime.now(datetime.timezone.utc).isoformat())
        if any(c.label == cloud.label for c in self.clouds):
            raise ValueError(
                f"this survey already holds a cloud labelled {cloud.label!r} "
                "spanning other runs; give this one a different label")
        self.clouds.append(cloud)
        return cloud

    def _derived_cloud_label(self, run_ids, digest: str) -> str:
        """Name a cloud after the runs it spans.

        Up to three run labels joined, and a count for the rest, so that a name
        stays short over a file holding many runs.  Run labels can themselves be
        long, and three of those joined reads as one long name rather than as
        three, so past ``CLOUD_LABEL_MAX_CHARS`` the count is what a person can
        use and the name becomes one.

        A name already taken by another cloud falls back to the digest, which
        cannot collide.
        """
        labels = [self.run_by_id(r).label or "run" for r in run_ids]
        name = "+".join(labels[:3])
        if len(labels) > 3:
            name += f"+{len(labels) - 3}more"
        if not name or len(name) > CLOUD_LABEL_MAX_CHARS:
            name = f"{len(labels)}-runs-{digest[:8]}"
        if any(c.label == name for c in self.clouds):
            return f"{name}-{digest[:12]}"
        return name

    def _records_of(self, run_ids) -> list:
        """Every ``(run, record)`` of the named runs, in cloud order."""
        wanted = set(run_ids)
        return [(run, rec) for run, rec in self.records()
                if run.run_id in wanted]

    def _identities(self, run_ids) -> list:
        """The ``(run, gene, chart, i, j)`` of every point of these runs."""
        return [(run.run_id, rec.gene, rec.chart, int(key[0]), int(key[1]))
                for run, rec in self._records_of(run_ids)
                for key in rec.archive.keys]

    def _content_digest(self, run_ids) -> str:
        """A digest over what the named runs found, rather than where."""
        from hifuku.digest import canonical_digest
        return canonical_digest(b"content", *sorted(
            rec.result_digest.encode("utf-8")
            for _run, rec in self._records_of(run_ids)))

    def points(self, cloud: "Cloud | None" = None) -> list:
        """The elite trees of a cloud, in the cloud's order.

        Returns a list of :class:`CloudPoint`.  An embedding's rows line up with
        this list and with nothing else.  Without a cloud, the whole survey is
        meant, which materializes the default cloud.

        The order comes from the cloud's own stored identity rather than from
        walking the runs again.  A cloud is written once and read back many
        times, and the two walks would have to agree on the order of the runs
        forever for the rows of an embedding to keep meaning what they meant.
        Reading the order the cloud recorded makes that agreement unnecessary.
        """
        cloud = cloud if cloud is not None else self.cloud()
        archives = {(run.run_id, rec.chart, rec.gene): rec.archive
                    for run, rec in self._records_of(cloud.run_ids)}
        pts = []
        for run_id, gene, chart, i, j in cloud.identity:
            try:
                arch = archives[(run_id, chart, gene)]
                elite = arch.elites[(i, j)]
            except KeyError:
                raise ValueError(
                    f"the cloud {cloud.label!r} names a point this survey does "
                    f"not hold: {gene!r} on chart {chart} at niche ({i}, {j}) "
                    f"of run {run_id[:12]}") from None
            pts.append(CloudPoint(tree=arch.tree_at((i, j)), gene=gene,
                                  chart=chart, key=(i, j), logL=elite.logL,
                                  z=elite.z, run_id=run_id))
        return pts

    def ordination(self, label: str):
        """The stored embedding with this label."""
        for o in self.ordinations:
            if o.label == label:
                return o
        raise KeyError(
            f"no ordination labelled {label!r}; this survey holds "
            f"{[o.label for o in self.ordinations]}")

    def add_ordination(self, X, *, label: str, method: str, cloud=None,
                       params=None, faithfulness=None):
        """Keep an embedding of one cloud.

        The embedding names the cloud it was built over and records that
        cloud's digests, so a later reader can tell whether the runs it
        describes are still here and still hold what they held.

        Parameters
        ----------
        X : numpy.ndarray
            ``(n, dim)`` coordinates, one row per point in cloud order.
        label : str
            A name, unique within this survey.
        method : str
            How the embedding was produced.
        cloud : Cloud, optional
            The cloud the rows belong to.  Defaults to the whole survey, which
            materializes the default cloud.
        params : dict, optional
            What the method was given.
        faithfulness : Faithfulness, optional
            The score of this embedding.

        Returns
        -------
        Ordination
        """
        cloud = cloud if cloud is not None else self.cloud()
        X = np.asarray(X, dtype=np.float64)
        if X.ndim != 2 or X.shape[0] != cloud.n_points:
            raise ValueError(
                f"the embedding has {X.shape[0]} rows and the cloud "
                f"{cloud.label!r} holds {cloud.n_points} points; they line up "
                "by position")
        if any(o.label == label for o in self.ordinations):
            raise ValueError(f"this survey already holds an ordination "
                             f"labelled {label!r}")
        record = Ordination(
            label=label, method=method, params=dict(params or {}), X=X,
            faithfulness=faithfulness,
            created=datetime.datetime.now(datetime.timezone.utc).isoformat(),
            n_points=cloud.n_points, cloud=cloud.label,
            cloud_digest=cloud.cloud_digest,
            content_digest=cloud.content_digest)
        self.ordinations.append(record)
        return record

    def cloud_by_label(self, label: str) -> Cloud:
        """The stored cloud with this label."""
        for cloud in self.clouds:
            if cloud.label == label:
                return cloud
        raise KeyError(
            f"no cloud labelled {label!r}; this survey holds "
            f"{[c.label for c in self.clouds]}")

    def ordination_matrix(self, label: str) -> np.ndarray:
        """The coordinates of a stored embedding, checked against its cloud.

        An embedding describes the points of one cloud, and the cloud names its
        runs.  Adding a run to the file therefore leaves this valid: the points
        it describes are still here and still hold what they held.  A run that
        has gone, or one whose surveys now hold other trees, is the case this
        refuses, because the rows would then be read against points they do not
        describe.
        """
        record = self.ordination(label)
        try:
            cloud = self.cloud_by_label(record.cloud)
        except KeyError:
            raise ValueError(
                f"the ordination {label!r} was built over the cloud "
                f"{record.cloud!r}, which this survey does not hold") from None

        missing = [r for r in cloud.run_ids
                   if not any(run.run_id == r for run in self.runs)]
        if missing:
            raise ValueError(
                f"the ordination {label!r} was built over {len(cloud.run_ids)} "
                f"runs, and {len(missing)} of them are not in this survey: "
                f"{missing}; its rows describe points that are no longer here")

        now = cloud_digest(run_ids=cloud.run_ids,
                           identities=self._identities(cloud.run_ids))
        if now != cloud.cloud_digest:
            raise ValueError(
                f"the ordination {label!r} was built over a cloud digesting to "
                f"{cloud.cloud_digest[:12]}, and those runs now digest to "
                f"{now[:12]}; the points have moved under it")
        content = self._content_digest(cloud.run_ids)
        if content != cloud.content_digest:
            raise ValueError(
                f"the ordination {label!r} was built over surveys whose results "
                f"digested to {cloud.content_digest[:12]}, and they now digest "
                f"to {content[:12]}; the niches are the same and the trees in "
                "them are not")
        return record.X

    def save(self, path, *, device="cpu", author=None) -> None:
        """Write the whole survey to a new HDF5 file.

        A file that exists is refused.  A survey file holds run data, and run
        data is never overwritten.  Use :meth:`append_run` to add one run to a
        file that already holds this framework.

        Every record must be sealed and must match its seal, and every run must
        match its id.  A survey read with ``verify=False`` that does not match
        is therefore refused here.

        A survey with no label of its own takes the output file's stem, and any
        run with no label takes the survey's.  Naming happens here because this
        is the first point at which the file has a name to borrow.

        Raises
        ------
        FileExistsError
            ``path`` exists.
        ProvenanceError
            A record is not sealed, or a record or a run does not match its
            digests.
        """
        if Path(path).exists():
            raise FileExistsError(
                f"{path} exists.  A survey file is never overwritten; write to "
                f"a new path, or add a run with append_run")
        _refuse_unverified(self.runs, self.framework)
        self.label = self.label or Path(path).stem
        for run in self.runs:
            run.label = run.label or self.label
        with h5py.File(path, "w-") as f:
            f.attrs["schema_version"] = _SCHEMA_VERSION
            f.attrs["field_type"] = _FIELD_TYPE
            f.attrs["metric"] = "normalized_branch_score"
            f.attrs["self_contained"] = True
            f.attrs["label"] = self.label
            f.attrs["created"] = datetime.datetime.now(
                datetime.timezone.utc).isoformat()
            f.attrs["description"] = self.description

            prov = f.create_group("provenance")
            for key, val in (self.provenance
                             or _provenance(device, author)).items():
                prov.attrs[key] = val

            self.framework.write(f.create_group("framework"))

            runs = f.create_group("runs")
            for run in self.runs:
                _write_run(runs, run)
            _write_index(f, self.runs, self.framework)
            _write_clouds(f, self.clouds)
            _write_ordinations(f, self.ordinations)

    def append_run(self, path, run) -> None:
        """Add one run to a file that already holds this framework.

        The framework in the file is authoritative.  A run made in another
        framework is refused, with the diagnosis rather than the two digests,
        because that is the check the framework digest exists to make.

        Nothing already in the file is read or rewritten, except the index,
        which is a table computed from the runs.  A project file grown over
        months stays cheap to add a gene to.

        Every record of the run must be sealed and must match its seal, and the
        run must match its id.
        """
        with h5py.File(path, "r") as f:
            stored = _s(f["framework"].attrs["digest"])
            if run.framework_digest != stored:
                raise ValueError(
                    "this run was made in a different framework:\n"
                    + explain_mismatch(Framework.read(f["framework"]),
                                       self.framework))
        _refuse_unverified([run], self.framework)
        with h5py.File(path, "r+") as f:
            runs = f["runs"]
            if run.group_name in runs:
                raise ValueError(
                    f"{path} already holds a run named {run.group_name!r}; a "
                    "run identifies itself by its framework, its work and its "
                    "provenance, so this is the same run twice")
            run.label = run.label or self.label or Path(path).stem
            _write_run(runs, run)
            self.runs = sorted(self.runs + [run], key=lambda r: r.group_name)
            del f["index"]
            _write_index(f, self.runs, self.framework)
            # The index is rewritten whole in the current layout, and the run
            # just added records what an older one did not, so the file is
            # stamped for what it now holds rather than for how it began.
            f.attrs["schema_version"] = _SCHEMA_VERSION

    def index(self) -> pl.DataFrame:
        """One row per survey across every run.

        Columns: ``run``, ``label``, ``chart``, ``chart_label``, ``gene``, both
        digests, ``seal``, ``parent``, ``n_filled``, ``best_logL``,
        ``converged``, ``halt_iter``,
        ``n_iters``, ``seed``, ``n_walkers``, ``checkpoint_every``,
        ``capacity``, ``n_dropped``, ``cell``, ``origin``, ``device`` and
        ``wall_seconds``.

        ``n_dropped`` above zero marks a survey whose archive filled: it holds
        the region it covered and lost the rest, so it is not comparable with a
        run of the same gene that had room.  ``capacity`` is the room it had.

        ``parent`` is ``AB_INITIO`` for a survey that started from nothing, and
        otherwise the run it continues.

        This is how a reader tells two runs of one gene apart without opening a
        payload.  ``label`` and ``chart_label`` are the names a person selects
        by, and ``run`` and ``chart`` are the identities those names point at.
        ``cell`` is here so that a coarse sketch is recognizable at a glance
        beside a fine survey of the same gene.  ``n_walkers`` is the shape the
        engine ran each gene at, which on a device that sizes itself is a
        property of the gene and the machine rather than of the batch.

        >>> index = survey.index()
        >>> index.filter(pl.col("label") == "pass1").sort("best_logL")
        """
        return _index_of(self.runs, self.framework)

    @classmethod
    def load(cls, path, *, verify=True) -> "Survey":
        """Reconstruct a Survey from a file (the inverse of :meth:`save`).

        A file holding a framework and no runs loads to a survey with no runs.
        That is a coordinate system nobody has surveyed in yet, which is a
        normal state of a project file rather than an error.

        Every record is checked against its seal and every run against its
        id.

        Parameters
        ----------
        verify : bool
            False reads a file whose digests do not match, so that it can be
            examined.  A survey read so cannot be saved unless it matches.

        Raises
        ------
        ValueError
            The file, or a record in it, is of a version other than
            ``_SCHEMA_VERSION``.  The message names the last commit that
            reads it.
        ProvenanceError
            A record or a run does not match its digests.
        """
        with h5py.File(path, "r") as f:
            _refuse_version(int(f.attrs.get("schema_version", 0)), str(path))
            label = _s(f.attrs.get("label", ""))
            description = _s(f.attrs.get("description", ""))
            provenance = {k: _s(v) for k, v in f["provenance"].attrs.items()}
            framework = Framework.read(f["framework"])
            runs = [_read_run(f["runs"][name], framework)
                    for name in sorted(f["runs"])]
            clouds = _read_clouds(f)

        survey = cls(framework=framework, runs=runs, label=label,
                     description=description, clouds=clouds,
                     provenance=provenance)
        survey.ordinations = _read_ordinations(path)
        if verify:
            _refuse_unverified(survey.runs, framework, where=str(path))
        return survey

alignments property

alignments: list

The alignment pool, as :class:~hifuku.framework.AlignmentInfo.

charts property

charts: list

The framework's charts, each an anchor triple and its triangle.

started property

started: str

When the earliest run began, or the empty string if none did.

finished property

finished: str

When the latest run ended, or the empty string if none did.

timing property

timing: dict

What the runs cost together, keyed <step>/<clock>.

A file holding several runs adds their spans, because the runs happened one after another from the file's point of view even when they happened on different machines. Read one run's own timing to compare machines.

wall_seconds property

wall_seconds: float

Elapsed seconds the runs took, preparation included.

cpu_seconds property

cpu_seconds: float

Processor seconds the runs held, user and system together.

Read against :attr:wall_seconds. A run holding a processor for as long as it ran is limited by the host.

device_seconds property

device_seconds: float

Seconds spent inside the device engine. Zero when the engine does not measure device time: the host engine and the WebGPU engine.

metric property

metric

The cloud-wide tree metric of this survey.

Built from the NJ tree of every alignment in the pool, so analysis over the whole cloud uses one normalization. A chart carries its own BranchScoreMetric, whose weight w comes from that chart alone, so this is not the metric of any one chart.

alignment

alignment(label)

AlignmentInfo for a pool label.

Source code in src/hifuku/survey_io.py
def alignment(self, label):
    """AlignmentInfo for a pool label."""
    return self.framework.alignment(label)

check_lineage

check_lineage() -> list

Every illumination whose ancestry no longer holds, and why.

An illumination that continues another records the run it came from and the digest of what that run produced. The digest is what the parent found, so a parent that has since been changed no longer matches what its child recorded, and the child is continuing from an archive that is not in the file any more.

Four faults, told apart because they need different answers. A link is "changed" when the parent is present and its seal or its end state is not the one the child started from, or "missing" when the parent is not in the file at all. A continuation with no seal is "unsealed", because it names a parent and nothing binds it to one. Everything further down is "ancestor": its own link still matches, and it is untrustworthy because something above it is not. That distinction is what sends a reader to where a problem started rather than to the whole chain at once.

This compares the links only. Whether each record still matches its own seal is :meth:verify.

Returns:

Type Description
list of BrokenLink

Empty when the file's ancestry holds. An illumination that began from nothing has no ancestry to check and never appears.

Source code in src/hifuku/survey_io.py
def check_lineage(self) -> list:
    """Every illumination whose ancestry no longer holds, and why.

    An illumination that continues another records the run it came from and
    the digest of what that run produced.  The digest is what the parent
    found, so a parent that has since been changed no longer matches what
    its child recorded, and the child is continuing from an archive that is
    not in the file any more.

    Four faults, told apart because they need different answers.  A link is
    ``"changed"`` when the parent is present and its seal or its end state
    is not the one the child started from, or ``"missing"`` when the parent
    is not in the file at all.  A continuation with no seal is
    ``"unsealed"``, because it names a parent and nothing binds it to one.
    Everything further down is ``"ancestor"``: its own link still matches,
    and it is untrustworthy because something above it is not.  That
    distinction is what sends a reader to where a problem started rather
    than to the whole chain at once.

    This compares the links only.  Whether each record still matches its
    own seal is :meth:`verify`.

    Returns
    -------
    list of BrokenLink
        Empty when the file's ancestry holds.  An illumination that began
        from nothing has no ancestry to check and never appears.
    """
    # Index every illumination by the run that holds it, so a parent can be
    # found without scanning.  A run holds one illumination per chart and
    # gene, which is what makes the parent link need no more than a run.
    by_run = {run.run_id: {(rec.chart, rec.gene): rec for rec in run.surveys}
              for run in self.runs}
    label_of = {run.run_id: run.label for run in self.runs}

    def local_fault(rec):
        if not rec.sealed:
            return "unsealed"
        parent = by_run.get(rec.parent, {}).get((rec.chart, rec.gene))
        if parent is None:
            return "missing"
        if (parent.seal != rec.parent_seal
                or parent.state_digest != rec.start_state):
            return "changed"
        return None

    continuations = [(run, rec) for run in self.runs for rec in run.surveys
                     if rec.parent != AB_INITIO]
    reasons = {}
    for run, rec in continuations:
        fault = local_fault(rec)
        if fault is not None:
            reasons[(run.run_id, rec.chart, rec.gene)] = fault
    # The runs are listed by name, which is not the order they were made
    # in, so a fault is carried down the chains until nothing changes.
    spreading = True
    while spreading:
        spreading = False
        for run, rec in continuations:
            here = (run.run_id, rec.chart, rec.gene)
            if here not in reasons and \
                    (rec.parent, rec.chart, rec.gene) in reasons:
                reasons[here] = "ancestor"
                spreading = True
    return [BrokenLink(run=run.label, chart=rec.chart, gene=rec.gene,
                       reason=reasons[(run.run_id, rec.chart, rec.gene)],
                       parent=label_of.get(rec.parent, rec.parent))
            for run, rec in continuations
            if (run.run_id, rec.chart, rec.gene) in reasons]

verify

verify() -> list

Every way this survey fails to match its own digests, as text.

Each record is checked against its seal, each run against its id, and each link against its parent. A record with no seal is listed, because nothing it claims is bound to anything.

This shows that nothing changed after it was sealed, and which state each record started from. It does not show that an end state follows from its inputs. See :func:hifuku.replay.replay_record for that.

Returns:

Type Description
list of str

Empty when every record is sealed and every digest holds.

Source code in src/hifuku/survey_io.py
def verify(self) -> list:
    """Every way this survey fails to match its own digests, as text.

    Each record is checked against its seal, each run against its id, and
    each link against its parent.  A record with no seal is listed, because
    nothing it claims is bound to anything.

    This shows that nothing changed after it was sealed, and which state
    each record started from.  It does not show that an end state follows
    from its inputs.  See :func:`hifuku.replay.replay_record` for that.

    Returns
    -------
    list of str
        Empty when every record is sealed and every digest holds.
    """
    problems = _digest_problems(self.runs, self.framework)
    problems += [f"run {b.run}: the record of {b.gene!r} on chart "
                 f"{b.chart} has a broken link to {b.parent}: {b.reason}"
                 for b in self.check_lineage() if b.reason != "unsealed"]
    return problems

run_by_id

run_by_id(run_id: str)

The run with this id.

Source code in src/hifuku/survey_io.py
def run_by_id(self, run_id: str):
    """The run with this id."""
    for run in self.runs:
        if run.run_id == run_id:
            return run
    raise KeyError(
        f"this survey holds no run {run_id!r}; it holds "
        f"{[r.run_id for r in self.runs]}")

run_by_label

run_by_label(label: str)

Return the run carrying this label.

A label is set by whoever ran the batch, so two runs can carry the same one: two people working on two machines may pick the same word, and merging their files brings both into view. A run id cannot collide, because it is a digest over the framework, the work and the provenance, so :meth:run_by_id is the way to name one of an ambiguous pair.

Parameters:

Name Type Description Default
label str

A run label.

required

Raises:

Type Description
KeyError

No run carries this label.

ValueError

More than one run carries it. The message lists them by group name, which ends in the run id, so the call can be repeated with :meth:run_by_id.

Source code in src/hifuku/survey_io.py
def run_by_label(self, label: str):
    """Return the run carrying this label.

    A label is set by whoever ran the batch, so two runs can carry the same
    one: two people working on two machines may pick the same word, and
    merging their files brings both into view.  A run id cannot collide,
    because it is a digest over the framework, the work and the provenance,
    so :meth:`run_by_id` is the way to name one of an ambiguous pair.

    Parameters
    ----------
    label : str
        A run label.

    Raises
    ------
    KeyError
        No run carries this label.
    ValueError
        More than one run carries it.  The message lists them by group
        name, which ends in the run id, so the call can be repeated with
        :meth:`run_by_id`.
    """
    found = [r for r in self.runs if r.label == label]
    if not found:
        raise KeyError(
            f"this survey holds no run labelled {label!r}; it holds "
            f"{[r.label for r in self.runs]}")
    if len(found) > 1:
        raise ValueError(
            f"{len(found)} runs are labelled {label!r}: "
            f"{[r.group_name for r in found]}; name one by its id")
    return found[0]

records

records() -> list

Every (run, record) pair, in run order then survey order.

Source code in src/hifuku/survey_io.py
def records(self) -> list:
    """Every ``(run, record)`` pair, in run order then survey order."""
    return [(run, rec) for run in self.runs for rec in run.surveys]

variations_per_second

variations_per_second() -> float

Variations the surveys made for each elapsed second of surveying.

This counts the surveying alone. Building the charts is left out, so the rate compares one engine against another rather than one whole command against another.

Source code in src/hifuku/survey_io.py
def variations_per_second(self) -> float:
    """Variations the surveys made for each elapsed second of surveying.

    This counts the surveying alone.  Building the charts is left out, so
    the rate compares one engine against another rather than one whole
    command against another.
    """
    records = [rec for _run, rec in self.records()]
    seconds = sum(rec.wall_seconds for rec in records)
    # A survey that halted made halt_iter variations.  One that ran to its
    # budget never set a halt, and made the whole budget.
    variations = sum(rec.halt_iter if rec.halt_iter > 0 else rec.n_iters
                     for rec in records)
    return (variations / seconds) if seconds > 0.0 else 0.0

timing_report

timing_report() -> str

The recorded steps as a table, longest first, for a person to read.

The framework's steps are named apart from the runs', because building the charts is paid once and surveying is paid per batch. Adding the two would hide that.

Source code in src/hifuku/survey_io.py
def timing_report(self) -> str:
    """The recorded steps as a table, longest first, for a person to read.

    The framework's steps are named apart from the runs', because building
    the charts is paid once and surveying is paid per batch.  Adding the two
    would hide that.
    """
    timing = {f"framework/{k}": v
              for k, v in self.framework.timing.items()}
    timing.update(self.timing)
    steps = sorted(
        {k.rsplit("/", 1)[0] for k in timing if k.endswith("/wall")},
        key=lambda s: -float(timing.get(f"{s}/wall", 0.0)))
    if not steps:
        return "this survey carries no timing"
    width = max(len(s) for s in steps)
    lines = [f"{'step':>{width}}  {'wall s':>9} {'cpu s':>9} {'device s':>9}"]
    for step in steps:
        lines.append(
            f"{step:>{width}}  {timing.get(f'{step}/wall', 0.0):9.2f} "
            f"{timing.get(f'{step}/cpu', 0.0):9.2f} "
            f"{timing.get(f'{step}/device', 0.0):9.2f}")
    return "\n".join(lines)

run classmethod

run(batch, framework, *, device='gpu', backend=None, description='', monitor=False) -> 'Survey'

Run every gene of batch in framework and return the Survey.

This is :class:SurveyRun with the loop written out. Call SurveyRun directly to watch a run, to skip finished work, or to send a task to another host.

Source code in src/hifuku/survey_io.py
@classmethod
def run(cls, batch, framework, *, device="gpu", backend=None,
        description="", monitor=False) -> "Survey":
    """Run every gene of ``batch`` in ``framework`` and return the Survey.

    This is :class:`SurveyRun` with the loop written out.  Call
    ``SurveyRun`` directly to watch a run, to skip finished work, or to send
    a task to another host.
    """
    run = SurveyRun.prepare(batch, framework, device=device,
                            backend=backend)
    for task in run.tasks:
        run.execute(task, monitor=monitor)
    return cls(framework=framework, runs=[run.finish()],
               description=description)

archive

archive(gene, chart=0, run=None)

EliteArchive for a surveyed gene on a chart.

run picks between two runs that both surveyed this gene. Without it, a gene surveyed twice raises rather than returning whichever came first: choosing between two runs is the reader's question, and the error names both so it can be answered.

Source code in src/hifuku/survey_io.py
def archive(self, gene, chart=0, run=None):
    """EliteArchive for a surveyed gene on a chart.

    ``run`` picks between two runs that both surveyed this gene.  Without
    it, a gene surveyed twice raises rather than returning whichever came
    first: choosing between two runs is the reader's question, and the error
    names both so it can be answered.
    """
    found = [(r, rec) for r, rec in self.records()
             if rec.gene == gene and rec.chart == chart
             and (run is None or r.run_id == run or r.label == run)]
    if not found:
        raise KeyError(
            f"no survey of {gene!r} on chart {chart}"
            + (f" in run {run!r}" if run is not None else ""))
    if len(found) > 1:
        raise ValueError(
            f"{len(found)} runs surveyed {gene!r} on chart {chart}: "
            f"{[r.group_name for r, _ in found]}; name one with run=")
    return found[0][1].archive

frame

frame() -> pl.DataFrame

Every elite niche across every run, one row each.

Columns: run, label, gene, chart, chart_label, i, j, lam1, lam2, logL and z. Where :meth:index has a row per survey, this has a row per niche, so it is the table to reach for when the question is about where the elites sit rather than about which surveys are here.

The run is a column because two runs of one gene fill the same niches with different trees, and a table without it would stack them silently.

Call .to_pandas() on the result for callers who want that form.

Source code in src/hifuku/survey_io.py
def frame(self) -> pl.DataFrame:
    """Every elite niche across every run, one row each.

    Columns: ``run``, ``label``, ``gene``, ``chart``, ``chart_label``,
    ``i``, ``j``, ``lam1``, ``lam2``, ``logL`` and ``z``.  Where
    :meth:`index` has a row per survey, this has a row per niche, so it is
    the table to reach for when the question is about where the elites sit
    rather than about which surveys are here.

    The run is a column because two runs of one gene fill the same niches
    with different trees, and a table without it would stack them silently.

    Call ``.to_pandas()`` on the result for callers who want that form.
    """
    labels = self.framework.chart_labels
    rows = []
    for run, rec in self.records():
        arch = rec.archive
        for key in arch.keys:
            lam1, lam2 = arch.niche_center(key)
            elite = arch.elites[key]
            rows.append((run.run_id, run.label, rec.gene, rec.chart,
                         labels[rec.chart], key[0], key[1],
                         lam1, lam2, elite.logL, elite.z))
    return pl.DataFrame(rows, orient="row", schema={
        "run": pl.Utf8, "label": pl.Utf8, "gene": pl.Utf8,
        "chart": pl.Int32, "chart_label": pl.Utf8,
        "i": pl.Int64, "j": pl.Int64,
        "lam1": pl.Float64, "lam2": pl.Float64,
        "logL": pl.Float64, "z": pl.Float64,
    })

cloud

cloud(run_ids=None, *, label=None) -> Cloud

The stored cloud spanning these runs, made and kept if there is none.

Called bare it means every run in this survey as it stands. It is a fetcher first and a factory second: a cloud spanning exactly this run set is returned rather than duplicated, so a notebook cell that reruns does not fill the file with copies of one cloud.

There is no reserved label and no special case for "everything". A cloud given no label is named after the runs it spans, so a reader sees which work an embedding covers without opening anything.

Parameters:

Name Type Description Default
run_ids iterable of str

The runs to span. Defaults to every run in this survey.

None
label str

A name for a cloud that has to be created. Ignored when one is already stored for this run set, since a stored cloud keeps the name it was given.

None
Source code in src/hifuku/survey_io.py
def cloud(self, run_ids=None, *, label=None) -> Cloud:
    """The stored cloud spanning these runs, made and kept if there is none.

    Called bare it means every run in this survey as it stands.  It is a
    fetcher first and a factory second: a cloud spanning exactly this run
    set is returned rather than duplicated, so a notebook cell that reruns
    does not fill the file with copies of one cloud.

    There is no reserved label and no special case for "everything".  A
    cloud given no label is named after the runs it spans, so a reader sees
    which work an embedding covers without opening anything.

    Parameters
    ----------
    run_ids : iterable of str, optional
        The runs to span.  Defaults to every run in this survey.
    label : str, optional
        A name for a cloud that has to be created.  Ignored when one is
        already stored for this run set, since a stored cloud keeps the
        name it was given.
    """
    wanted = tuple(r.run_id for r in self.runs) if run_ids is None \
        else tuple(run_ids)
    for run_id in wanted:
        self.run_by_id(run_id)
    for stored in self.clouds:
        if set(stored.run_ids) == set(wanted):
            return stored

    identity = tuple(self._identities(wanted))
    digest = cloud_digest(run_ids=wanted, identities=identity)
    if label is not None:
        check_label(label, "cloud")
    else:
        label = self._derived_cloud_label(wanted, digest)
    cloud = Cloud(
        label=label, run_ids=wanted, identity=identity,
        cloud_digest=digest,
        content_digest=self._content_digest(wanted),
        created=datetime.datetime.now(datetime.timezone.utc).isoformat())
    if any(c.label == cloud.label for c in self.clouds):
        raise ValueError(
            f"this survey already holds a cloud labelled {cloud.label!r} "
            "spanning other runs; give this one a different label")
    self.clouds.append(cloud)
    return cloud

points

points(cloud: 'Cloud | None' = None) -> list

The elite trees of a cloud, in the cloud's order.

Returns a list of :class:CloudPoint. An embedding's rows line up with this list and with nothing else. Without a cloud, the whole survey is meant, which materializes the default cloud.

The order comes from the cloud's own stored identity rather than from walking the runs again. A cloud is written once and read back many times, and the two walks would have to agree on the order of the runs forever for the rows of an embedding to keep meaning what they meant. Reading the order the cloud recorded makes that agreement unnecessary.

Source code in src/hifuku/survey_io.py
def points(self, cloud: "Cloud | None" = None) -> list:
    """The elite trees of a cloud, in the cloud's order.

    Returns a list of :class:`CloudPoint`.  An embedding's rows line up with
    this list and with nothing else.  Without a cloud, the whole survey is
    meant, which materializes the default cloud.

    The order comes from the cloud's own stored identity rather than from
    walking the runs again.  A cloud is written once and read back many
    times, and the two walks would have to agree on the order of the runs
    forever for the rows of an embedding to keep meaning what they meant.
    Reading the order the cloud recorded makes that agreement unnecessary.
    """
    cloud = cloud if cloud is not None else self.cloud()
    archives = {(run.run_id, rec.chart, rec.gene): rec.archive
                for run, rec in self._records_of(cloud.run_ids)}
    pts = []
    for run_id, gene, chart, i, j in cloud.identity:
        try:
            arch = archives[(run_id, chart, gene)]
            elite = arch.elites[(i, j)]
        except KeyError:
            raise ValueError(
                f"the cloud {cloud.label!r} names a point this survey does "
                f"not hold: {gene!r} on chart {chart} at niche ({i}, {j}) "
                f"of run {run_id[:12]}") from None
        pts.append(CloudPoint(tree=arch.tree_at((i, j)), gene=gene,
                              chart=chart, key=(i, j), logL=elite.logL,
                              z=elite.z, run_id=run_id))
    return pts

ordination

ordination(label: str)

The stored embedding with this label.

Source code in src/hifuku/survey_io.py
def ordination(self, label: str):
    """The stored embedding with this label."""
    for o in self.ordinations:
        if o.label == label:
            return o
    raise KeyError(
        f"no ordination labelled {label!r}; this survey holds "
        f"{[o.label for o in self.ordinations]}")

add_ordination

add_ordination(X, *, label: str, method: str, cloud=None, params=None, faithfulness=None)

Keep an embedding of one cloud.

The embedding names the cloud it was built over and records that cloud's digests, so a later reader can tell whether the runs it describes are still here and still hold what they held.

Parameters:

Name Type Description Default
X ndarray

(n, dim) coordinates, one row per point in cloud order.

required
label str

A name, unique within this survey.

required
method str

How the embedding was produced.

required
cloud Cloud

The cloud the rows belong to. Defaults to the whole survey, which materializes the default cloud.

None
params dict

What the method was given.

None
faithfulness Faithfulness

The score of this embedding.

None

Returns:

Type Description
Ordination
Source code in src/hifuku/survey_io.py
def add_ordination(self, X, *, label: str, method: str, cloud=None,
                   params=None, faithfulness=None):
    """Keep an embedding of one cloud.

    The embedding names the cloud it was built over and records that
    cloud's digests, so a later reader can tell whether the runs it
    describes are still here and still hold what they held.

    Parameters
    ----------
    X : numpy.ndarray
        ``(n, dim)`` coordinates, one row per point in cloud order.
    label : str
        A name, unique within this survey.
    method : str
        How the embedding was produced.
    cloud : Cloud, optional
        The cloud the rows belong to.  Defaults to the whole survey, which
        materializes the default cloud.
    params : dict, optional
        What the method was given.
    faithfulness : Faithfulness, optional
        The score of this embedding.

    Returns
    -------
    Ordination
    """
    cloud = cloud if cloud is not None else self.cloud()
    X = np.asarray(X, dtype=np.float64)
    if X.ndim != 2 or X.shape[0] != cloud.n_points:
        raise ValueError(
            f"the embedding has {X.shape[0]} rows and the cloud "
            f"{cloud.label!r} holds {cloud.n_points} points; they line up "
            "by position")
    if any(o.label == label for o in self.ordinations):
        raise ValueError(f"this survey already holds an ordination "
                         f"labelled {label!r}")
    record = Ordination(
        label=label, method=method, params=dict(params or {}), X=X,
        faithfulness=faithfulness,
        created=datetime.datetime.now(datetime.timezone.utc).isoformat(),
        n_points=cloud.n_points, cloud=cloud.label,
        cloud_digest=cloud.cloud_digest,
        content_digest=cloud.content_digest)
    self.ordinations.append(record)
    return record

cloud_by_label

cloud_by_label(label: str) -> Cloud

The stored cloud with this label.

Source code in src/hifuku/survey_io.py
def cloud_by_label(self, label: str) -> Cloud:
    """The stored cloud with this label."""
    for cloud in self.clouds:
        if cloud.label == label:
            return cloud
    raise KeyError(
        f"no cloud labelled {label!r}; this survey holds "
        f"{[c.label for c in self.clouds]}")

ordination_matrix

ordination_matrix(label: str) -> np.ndarray

The coordinates of a stored embedding, checked against its cloud.

An embedding describes the points of one cloud, and the cloud names its runs. Adding a run to the file therefore leaves this valid: the points it describes are still here and still hold what they held. A run that has gone, or one whose surveys now hold other trees, is the case this refuses, because the rows would then be read against points they do not describe.

Source code in src/hifuku/survey_io.py
def ordination_matrix(self, label: str) -> np.ndarray:
    """The coordinates of a stored embedding, checked against its cloud.

    An embedding describes the points of one cloud, and the cloud names its
    runs.  Adding a run to the file therefore leaves this valid: the points
    it describes are still here and still hold what they held.  A run that
    has gone, or one whose surveys now hold other trees, is the case this
    refuses, because the rows would then be read against points they do not
    describe.
    """
    record = self.ordination(label)
    try:
        cloud = self.cloud_by_label(record.cloud)
    except KeyError:
        raise ValueError(
            f"the ordination {label!r} was built over the cloud "
            f"{record.cloud!r}, which this survey does not hold") from None

    missing = [r for r in cloud.run_ids
               if not any(run.run_id == r for run in self.runs)]
    if missing:
        raise ValueError(
            f"the ordination {label!r} was built over {len(cloud.run_ids)} "
            f"runs, and {len(missing)} of them are not in this survey: "
            f"{missing}; its rows describe points that are no longer here")

    now = cloud_digest(run_ids=cloud.run_ids,
                       identities=self._identities(cloud.run_ids))
    if now != cloud.cloud_digest:
        raise ValueError(
            f"the ordination {label!r} was built over a cloud digesting to "
            f"{cloud.cloud_digest[:12]}, and those runs now digest to "
            f"{now[:12]}; the points have moved under it")
    content = self._content_digest(cloud.run_ids)
    if content != cloud.content_digest:
        raise ValueError(
            f"the ordination {label!r} was built over surveys whose results "
            f"digested to {cloud.content_digest[:12]}, and they now digest "
            f"to {content[:12]}; the niches are the same and the trees in "
            "them are not")
    return record.X

save

save(path, *, device='cpu', author=None) -> None

Write the whole survey to a new HDF5 file.

A file that exists is refused. A survey file holds run data, and run data is never overwritten. Use :meth:append_run to add one run to a file that already holds this framework.

Every record must be sealed and must match its seal, and every run must match its id. A survey read with verify=False that does not match is therefore refused here.

A survey with no label of its own takes the output file's stem, and any run with no label takes the survey's. Naming happens here because this is the first point at which the file has a name to borrow.

Raises:

Type Description
FileExistsError

path exists.

ProvenanceError

A record is not sealed, or a record or a run does not match its digests.

Source code in src/hifuku/survey_io.py
def save(self, path, *, device="cpu", author=None) -> None:
    """Write the whole survey to a new HDF5 file.

    A file that exists is refused.  A survey file holds run data, and run
    data is never overwritten.  Use :meth:`append_run` to add one run to a
    file that already holds this framework.

    Every record must be sealed and must match its seal, and every run must
    match its id.  A survey read with ``verify=False`` that does not match
    is therefore refused here.

    A survey with no label of its own takes the output file's stem, and any
    run with no label takes the survey's.  Naming happens here because this
    is the first point at which the file has a name to borrow.

    Raises
    ------
    FileExistsError
        ``path`` exists.
    ProvenanceError
        A record is not sealed, or a record or a run does not match its
        digests.
    """
    if Path(path).exists():
        raise FileExistsError(
            f"{path} exists.  A survey file is never overwritten; write to "
            f"a new path, or add a run with append_run")
    _refuse_unverified(self.runs, self.framework)
    self.label = self.label or Path(path).stem
    for run in self.runs:
        run.label = run.label or self.label
    with h5py.File(path, "w-") as f:
        f.attrs["schema_version"] = _SCHEMA_VERSION
        f.attrs["field_type"] = _FIELD_TYPE
        f.attrs["metric"] = "normalized_branch_score"
        f.attrs["self_contained"] = True
        f.attrs["label"] = self.label
        f.attrs["created"] = datetime.datetime.now(
            datetime.timezone.utc).isoformat()
        f.attrs["description"] = self.description

        prov = f.create_group("provenance")
        for key, val in (self.provenance
                         or _provenance(device, author)).items():
            prov.attrs[key] = val

        self.framework.write(f.create_group("framework"))

        runs = f.create_group("runs")
        for run in self.runs:
            _write_run(runs, run)
        _write_index(f, self.runs, self.framework)
        _write_clouds(f, self.clouds)
        _write_ordinations(f, self.ordinations)

append_run

append_run(path, run) -> None

Add one run to a file that already holds this framework.

The framework in the file is authoritative. A run made in another framework is refused, with the diagnosis rather than the two digests, because that is the check the framework digest exists to make.

Nothing already in the file is read or rewritten, except the index, which is a table computed from the runs. A project file grown over months stays cheap to add a gene to.

Every record of the run must be sealed and must match its seal, and the run must match its id.

Source code in src/hifuku/survey_io.py
def append_run(self, path, run) -> None:
    """Add one run to a file that already holds this framework.

    The framework in the file is authoritative.  A run made in another
    framework is refused, with the diagnosis rather than the two digests,
    because that is the check the framework digest exists to make.

    Nothing already in the file is read or rewritten, except the index,
    which is a table computed from the runs.  A project file grown over
    months stays cheap to add a gene to.

    Every record of the run must be sealed and must match its seal, and the
    run must match its id.
    """
    with h5py.File(path, "r") as f:
        stored = _s(f["framework"].attrs["digest"])
        if run.framework_digest != stored:
            raise ValueError(
                "this run was made in a different framework:\n"
                + explain_mismatch(Framework.read(f["framework"]),
                                   self.framework))
    _refuse_unverified([run], self.framework)
    with h5py.File(path, "r+") as f:
        runs = f["runs"]
        if run.group_name in runs:
            raise ValueError(
                f"{path} already holds a run named {run.group_name!r}; a "
                "run identifies itself by its framework, its work and its "
                "provenance, so this is the same run twice")
        run.label = run.label or self.label or Path(path).stem
        _write_run(runs, run)
        self.runs = sorted(self.runs + [run], key=lambda r: r.group_name)
        del f["index"]
        _write_index(f, self.runs, self.framework)
        # The index is rewritten whole in the current layout, and the run
        # just added records what an older one did not, so the file is
        # stamped for what it now holds rather than for how it began.
        f.attrs["schema_version"] = _SCHEMA_VERSION

index

index() -> pl.DataFrame

One row per survey across every run.

Columns: run, label, chart, chart_label, gene, both digests, seal, parent, n_filled, best_logL, converged, halt_iter, n_iters, seed, n_walkers, checkpoint_every, capacity, n_dropped, cell, origin, device and wall_seconds.

n_dropped above zero marks a survey whose archive filled: it holds the region it covered and lost the rest, so it is not comparable with a run of the same gene that had room. capacity is the room it had.

parent is AB_INITIO for a survey that started from nothing, and otherwise the run it continues.

This is how a reader tells two runs of one gene apart without opening a payload. label and chart_label are the names a person selects by, and run and chart are the identities those names point at. cell is here so that a coarse sketch is recognizable at a glance beside a fine survey of the same gene. n_walkers is the shape the engine ran each gene at, which on a device that sizes itself is a property of the gene and the machine rather than of the batch.

index = survey.index() index.filter(pl.col("label") == "pass1").sort("best_logL")

Source code in src/hifuku/survey_io.py
def index(self) -> pl.DataFrame:
    """One row per survey across every run.

    Columns: ``run``, ``label``, ``chart``, ``chart_label``, ``gene``, both
    digests, ``seal``, ``parent``, ``n_filled``, ``best_logL``,
    ``converged``, ``halt_iter``,
    ``n_iters``, ``seed``, ``n_walkers``, ``checkpoint_every``,
    ``capacity``, ``n_dropped``, ``cell``, ``origin``, ``device`` and
    ``wall_seconds``.

    ``n_dropped`` above zero marks a survey whose archive filled: it holds
    the region it covered and lost the rest, so it is not comparable with a
    run of the same gene that had room.  ``capacity`` is the room it had.

    ``parent`` is ``AB_INITIO`` for a survey that started from nothing, and
    otherwise the run it continues.

    This is how a reader tells two runs of one gene apart without opening a
    payload.  ``label`` and ``chart_label`` are the names a person selects
    by, and ``run`` and ``chart`` are the identities those names point at.
    ``cell`` is here so that a coarse sketch is recognizable at a glance
    beside a fine survey of the same gene.  ``n_walkers`` is the shape the
    engine ran each gene at, which on a device that sizes itself is a
    property of the gene and the machine rather than of the batch.

    >>> index = survey.index()
    >>> index.filter(pl.col("label") == "pass1").sort("best_logL")
    """
    return _index_of(self.runs, self.framework)

load classmethod

load(path, *, verify=True) -> 'Survey'

Reconstruct a Survey from a file (the inverse of :meth:save).

A file holding a framework and no runs loads to a survey with no runs. That is a coordinate system nobody has surveyed in yet, which is a normal state of a project file rather than an error.

Every record is checked against its seal and every run against its id.

Parameters:

Name Type Description Default
verify bool

False reads a file whose digests do not match, so that it can be examined. A survey read so cannot be saved unless it matches.

True

Raises:

Type Description
ValueError

The file, or a record in it, is of a version other than _SCHEMA_VERSION. The message names the last commit that reads it.

ProvenanceError

A record or a run does not match its digests.

Source code in src/hifuku/survey_io.py
@classmethod
def load(cls, path, *, verify=True) -> "Survey":
    """Reconstruct a Survey from a file (the inverse of :meth:`save`).

    A file holding a framework and no runs loads to a survey with no runs.
    That is a coordinate system nobody has surveyed in yet, which is a
    normal state of a project file rather than an error.

    Every record is checked against its seal and every run against its
    id.

    Parameters
    ----------
    verify : bool
        False reads a file whose digests do not match, so that it can be
        examined.  A survey read so cannot be saved unless it matches.

    Raises
    ------
    ValueError
        The file, or a record in it, is of a version other than
        ``_SCHEMA_VERSION``.  The message names the last commit that
        reads it.
    ProvenanceError
        A record or a run does not match its digests.
    """
    with h5py.File(path, "r") as f:
        _refuse_version(int(f.attrs.get("schema_version", 0)), str(path))
        label = _s(f.attrs.get("label", ""))
        description = _s(f.attrs.get("description", ""))
        provenance = {k: _s(v) for k, v in f["provenance"].attrs.items()}
        framework = Framework.read(f["framework"])
        runs = [_read_run(f["runs"][name], framework)
                for name in sorted(f["runs"])]
        clouds = _read_clouds(f)

    survey = cls(framework=framework, runs=runs, label=label,
                 description=description, clouds=clouds,
                 provenance=provenance)
    survey.ordinations = _read_ordinations(path)
    if verify:
        _refuse_unverified(survey.runs, framework, where=str(path))
    return survey

Run dataclass

One batch of work done inside one framework.

A run carries the provenance of the process that produced it, including the digest of the framework it ran in, so that a run separated from its file still says which coordinate system it belongs to.

run_id is a digest over the framework, the work and the provenance. Two runs of one batch on one host at different times differ, because the provenance carries the time. That is deliberate: they are two runs and the file keeps both.

Source code in src/hifuku/survey_io.py
@dataclass
class Run:
    """One batch of work done inside one framework.

    A run carries the provenance of the process that produced it, including the
    digest of the framework it ran in, so that a run separated from its file
    still says which coordinate system it belongs to.

    ``run_id`` is a digest over the framework, the work and the provenance.  Two
    runs of one batch on one host at different times differ, because the
    provenance carries the time.  That is deliberate: they are two runs and the
    file keeps both.
    """

    label: str = ""
    surveys: list = field(default_factory=list)     # list[SurveyRecord]
    provenance: dict = field(default_factory=dict)
    timing: dict = field(default_factory=dict)
    run_id: str = ""

    def __post_init__(self):
        # Records are held in one canonical order, the order a file lists them
        # in, so that a run and the same run reloaded agree row for row.  The
        # order work happened to be executed in is not that order and is not
        # recorded anywhere.
        self.surveys = sorted(self.surveys, key=lambda r: (r.chart, r.gene))
        for record in self.surveys:
            if not record.result_digest:
                record.stamp_result()
        # A file stores each value as text, so the run id is computed over
        # text.  A value of another type would give an id that no reader can
        # compute again.
        self.provenance = {str(k): str(v) for k, v in self.provenance.items()}
        if not self.run_id:
            self.run_id = self.expected_id()

    def expected_id(self) -> str:
        """The run id that the framework, the seals and the provenance give."""
        return run_digest(framework_digest=self.framework_digest,
                          seals=[r.seal for r in self.surveys],
                          provenance=self.provenance)

    @property
    def framework_digest(self) -> str:
        """The framework this run happened in."""
        return str(self.provenance.get("framework_digest", ""))

    @property
    def group_name(self) -> str:
        """What this run is called in the file.

        The label makes ``h5ls`` readable and the digest makes two runs of one
        batch on one host distinct.
        """
        return f"{self.label or 'run'}-{self.run_id[:12]}"

    def record(self, gene: str, chart: int = 0) -> SurveyRecord:
        """The record for one gene on one chart of this run."""
        for r in self.surveys:
            if r.gene == gene and r.chart == chart:
                return r
        raise KeyError(
            f"this run holds no survey of {gene!r} on chart {chart}; it holds "
            f"{[(r.chart, r.gene) for r in self.surveys]}")

framework_digest property

framework_digest: str

The framework this run happened in.

group_name property

group_name: str

What this run is called in the file.

The label makes h5ls readable and the digest makes two runs of one batch on one host distinct.

expected_id

expected_id() -> str

The run id that the framework, the seals and the provenance give.

Source code in src/hifuku/survey_io.py
def expected_id(self) -> str:
    """The run id that the framework, the seals and the provenance give."""
    return run_digest(framework_digest=self.framework_digest,
                      seals=[r.seal for r in self.surveys],
                      provenance=self.provenance)

record

record(gene: str, chart: int = 0) -> SurveyRecord

The record for one gene on one chart of this run.

Source code in src/hifuku/survey_io.py
def record(self, gene: str, chart: int = 0) -> SurveyRecord:
    """The record for one gene on one chart of this run."""
    for r in self.surveys:
        if r.gene == gene and r.chart == chart:
            return r
    raise KeyError(
        f"this run holds no survey of {gene!r} on chart {chart}; it holds "
        f"{[(r.chart, r.gene) for r in self.surveys]}")

SurveyRecord dataclass

One gene surveyed on one chart: the elite archive and its metadata.

gene is the surveyed alignment's label, independent of the chart anchors: a gene may be surveyed on a chart it is not a vertex of.

The two digests are what let a reader tell duplicates apart. task_digest says what was asked and result_digest says what came back, so two records of one gene fall into one of three cases: the same question and the same answer, which is a deterministic re-run; the same question and a different answer, which is nondeterminism or a different engine; or two questions, which both belong.

cell and origin are read from the archive rather than stored beside it, so the record cannot disagree with the grid its niches are on.

n_walkers and checkpoint_every are the shape the engine ran this gene at, which is not always the shape the batch named: an engine that sizes itself to the device gives a wide alignment fewer walkers than a narrow one, so two genes of one run may differ. Neither is part of the task digest, because neither changes what the survey asked. Zero means a file written before the shape was recorded.

Source code in src/hifuku/survey_io.py
@dataclass
class SurveyRecord:
    """One gene surveyed on one chart: the elite archive and its metadata.

    ``gene`` is the surveyed alignment's label, independent of the chart anchors:
    a gene may be surveyed on a chart it is not a vertex of.

    The two digests are what let a reader tell duplicates apart.  ``task_digest``
    says what was asked and ``result_digest`` says what came back, so two records
    of one gene fall into one of three cases: the same question and the same
    answer, which is a deterministic re-run; the same question and a different
    answer, which is nondeterminism or a different engine; or two questions,
    which both belong.

    ``cell`` and ``origin`` are read from the archive rather than stored beside
    it, so the record cannot disagree with the grid its niches are on.

    ``n_walkers`` and ``checkpoint_every`` are the shape the engine ran this
    gene at, which is not always the shape the batch named: an engine that sizes
    itself to the device gives a wide alignment fewer walkers than a narrow one,
    so two genes of one run may differ.  Neither is part of the task digest,
    because neither changes what the survey asked.  Zero means a file written
    before the shape was recorded.
    """

    gene: str
    archive: object                 # EliteArchive
    chart: int = 0
    task_digest: str = ""
    result_digest: str = ""
    history: np.ndarray = field(default_factory=lambda: np.zeros((0, 5)))
    #: One landscape row per history row.  See :mod:`hifuku.landscape`.  These
    #: rows match the last ``len(landscape)`` history rows.  A stored record
    #: holds them, and a record without them is not written.
    landscape: np.ndarray = None
    #: The move tally of each checkpoint, one block per landscape row.  See
    #: :attr:`hifuku.driver.ArchiveResult.moves`.  A stored record holds it.
    moves: np.ndarray = None
    #: The QD-score rows: one ``(S, N, m)`` row per checkpoint, float64.  See
    #: :attr:`hifuku.driver.ArchiveResult.qd`.  A stored record holds them.
    qd: np.ndarray = None
    #: The seconds each checkpoint of this record took.  See
    #: :attr:`hifuku.driver.ArchiveResult.checkpoint_seconds`.  This is a
    #: sealed fact and not part of the state, so a replay does not compare it.
    #: A stored record holds them.
    checkpoint_seconds: tuple = None
    converged: bool = False
    halt_iter: int = -1
    model: str = ""
    n_iters: int = 0
    seed: int = 0
    n_walkers: int = 0
    checkpoint_every: int = 0
    device: str = "cpu"
    #: Elapsed seconds this gene took.
    wall_seconds: float = 0.0
    #: Seconds this gene held a processor, user and system together.  Read
    #: against ``wall_seconds``: a gene that holds a processor for as long as it
    #: runs is held up by the host, and a gene whose processor time falls well
    #: below its elapsed time waits on something else.
    cpu_seconds: float = 0.0
    #: Seconds between the first and last device call.  Zero when the engine
    #: does not measure device time: the host engine, and the WebGPU engine,
    #: whose device work the host waits for, so that it is in ``wall_seconds``.
    #: ``engine`` says which.
    device_seconds: float = 0.0
    #: The run holding the illumination this one continues, or ``AB_INITIO``.
    #: It has no default.  A record says where it started, because a default
    #: here would let a record that continued another one say that it started
    #: from nothing.  Both this and ``parent_seal`` enter ``task_digest``, so a
    #: continued illumination is a different question from a fresh one and
    #: says which.
    parent: str = None
    #: The ``seal`` of the record this one continues, empty for ab initio.
    parent_seal: str = ""
    #: What a further run needs to carry this illumination on: the engine's
    #: random state and the driver's bookkeeping.  The archive it walks from is
    #: the record's own, so this holds only what the archive does not.  None
    #: when the illumination was not written with it.  See
    #: :class:`~hifuku.driver.RunSnapshot`.
    snapshot: object = None
    #: The precision of each stored quantity, by name: the narrowest float type
    #: in the arithmetic that produced it, storage included.  It is copied from
    #: the engine's ``Capabilities.precision``.  It is empty for a record from a
    #: file that did not record it, and a comparison refuses such a record.
    precision: dict = field(default_factory=dict)
    #: Every archive parameter as the batch asked for it, before an engine
    #: resolved anything.  The task digest is computed from these, so a reader
    #: can compute it again.
    task_params: dict = field(default_factory=dict)
    #: Every archive parameter the engine executed with, after it settled the
    #: niche side and its shape.  ``n_iters`` here is the budget of this
    #: record, not the total of a chain of records.
    params: dict = field(default_factory=dict)
    #: The device parameters the engine executed with, empty on the host.
    gpu_params: dict = field(default_factory=dict)
    #: The name of the engine that ran the survey.
    engine: str = ""
    #: The state digest of the snapshot the engine resumed, or empty when it
    #: seeded.  It comes from the engine.  See :func:`hifuku.seal.archive_state`.
    start_state: str = ""
    #: The state digest of the state the survey ended in.
    state_digest: str = ""
    #: The seal: the parent's seal, the inputs and the end state, hashed.
    #: Empty for a record that was never sealed.  See :mod:`hifuku.seal`.
    seal: str = ""
    #: The schema the record was written in.
    schema_version: int = _SCHEMA_VERSION

    def __post_init__(self):
        if self.parent is None:
            raise TypeError(
                f"the record of {self.gene!r} does not say where it started. "
                f"Give parent=AB_INITIO for a survey that seeded, or the run it "
                f"continues")

    @property
    def sealed(self) -> bool:
        """True when the record carries a seal.  See :mod:`hifuku.seal`."""
        return bool(self.seal)

    @property
    def cell(self) -> float:
        """Niche side of the grid this survey filled."""
        return float(self.archive.cell)

    @property
    def origin(self) -> float:
        """Grid origin of the archive this survey filled."""
        return float(self.archive.origin)

    @property
    def n_dropped(self) -> int:
        """Niches the archive had no room for.

        Read from the archive rather than stored beside it, on the same grounds
        as ``cell``: the record cannot then disagree with what it holds.
        """
        return int(getattr(self.archive, "n_dropped", 0))

    @property
    def capacity(self) -> int:
        """Niches the archive had room for, or zero if nobody recorded one."""
        return int(getattr(self.archive, "capacity", 0))

    @property
    def saturated(self) -> bool:
        """True when the archive filled and dropped what it could not hold."""
        return self.n_dropped > 0

    def stamp_result(self) -> str:
        """Record what this survey produced, and return the digest.

        Called once the archive is final.  Two runs of one task that landed on
        the same elites get one digest, which is what makes a true duplicate
        recognizable as such.
        """
        arch = self.archive
        keys = sorted(arch.keys)
        self.result_digest = result_digest(
            niche_ij=keys,
            newicks=[arch.newick_at(k) for k in keys],
            logL=[arch.elites[k].logL for k in keys])
        return self.result_digest

sealed property

sealed: bool

True when the record carries a seal. See :mod:hifuku.seal.

cell property

cell: float

Niche side of the grid this survey filled.

origin property

origin: float

Grid origin of the archive this survey filled.

n_dropped property

n_dropped: int

Niches the archive had no room for.

Read from the archive rather than stored beside it, on the same grounds as cell: the record cannot then disagree with what it holds.

capacity property

capacity: int

Niches the archive had room for, or zero if nobody recorded one.

saturated property

saturated: bool

True when the archive filled and dropped what it could not hold.

stamp_result

stamp_result() -> str

Record what this survey produced, and return the digest.

Called once the archive is final. Two runs of one task that landed on the same elites get one digest, which is what makes a true duplicate recognizable as such.

Source code in src/hifuku/survey_io.py
def stamp_result(self) -> str:
    """Record what this survey produced, and return the digest.

    Called once the archive is final.  Two runs of one task that landed on
    the same elites get one digest, which is what makes a true duplicate
    recognizable as such.
    """
    arch = self.archive
    keys = sorted(arch.keys)
    self.result_digest = result_digest(
        niche_ij=keys,
        newicks=[arch.newick_at(k) for k in keys],
        logL=[arch.elites[k].logL for k in keys])
    return self.result_digest

One illumination whose ancestry no longer holds.

reason is "changed" when the parent's seal or end state is not the one this recorded, "missing" when the parent is not in the file, "unsealed" when this illumination has no seal, and "ancestor" when this illumination's own link is sound but something above it is not. See :meth:Survey.check_lineage.

Source code in src/hifuku/survey_io.py
@dataclass(frozen=True)
class BrokenLink:
    """One illumination whose ancestry no longer holds.

    ``reason`` is ``"changed"`` when the parent's seal or end state is not the
    one this recorded, ``"missing"`` when the parent is not in the file,
    ``"unsealed"`` when this illumination has no seal, and ``"ancestor"`` when
    this illumination's own link is sound but something above it is not.  See
    :meth:`Survey.check_lineage`.
    """

    run: str
    chart: int
    gene: str
    reason: str
    parent: str

SurveyRun

One batch of work, run inside a framework somebody else built.

:meth:prepare resolves the backend and the parameters and enumerates the work; it does not read alignments, build trees or embed triangles, because the framework already holds all three. That is what lets a framework be built once and surveyed by many batches, on one machine or several.

framework = Framework.build(FrameworkSpec.from_toml("markers.toml"))
batch     = Batch.from_toml("pass1.toml")
run       = SurveyRun.prepare(batch, framework, device="cuda")
for task in run.tasks:
    run.execute(task)
Survey(framework, [run.finish()]).save("markers.h5")
Source code in src/hifuku/survey_io.py
class SurveyRun:
    """One batch of work, run inside a framework somebody else built.

    :meth:`prepare` resolves the backend and the parameters and enumerates the
    work; it does not read alignments, build trees or embed triangles, because
    the framework already holds all three.  That is what lets a framework be
    built once and surveyed by many batches, on one machine or several.

        framework = Framework.build(FrameworkSpec.from_toml("markers.toml"))
        batch     = Batch.from_toml("pass1.toml")
        run       = SurveyRun.prepare(batch, framework, device="cuda")
        for task in run.tasks:
            run.execute(task)
        Survey(framework, [run.finish()]).save("markers.h5")
    """

    def __init__(self, batch, framework, device, backend, params, tasks,
                 clock=None, resume=None, data_dirs=()):
        from hifuku.timing import RunClock
        #: What each gene of this run cost.  :meth:`execute` adds one span per
        #: gene.  Building the charts is the framework's cost, not the run's.
        self.clock = clock if clock is not None else RunClock(device=device)
        self._started = datetime.datetime.now(
            datetime.timezone.utc).isoformat()
        self.batch = batch
        self.framework = framework
        self.device = device
        self.backend = backend
        self.params = params
        self.tasks = tasks
        self._records = {}                  # (chart, gene) -> SurveyRecord
        self._alignments = {}               # gene -> Alignment, read on demand
        #: Folders to search for an alignment that the framework does not hold
        #: and that is not at its recorded path.
        self.data_dirs = tuple(data_dirs)
        #: gene -> the path the batch's framework names for it, which is where
        #: the user says the alignment is now.
        self._batch_paths = _batch_paths(batch)
        #: (chart, gene) -> (RunSnapshot, the parent's state digest) for each
        #: task that continues one.
        self._resume = dict(resume or {})
        #: Every archive parameter as the batch asked for it.  The task digests
        #: were computed from these.
        from hifuku.params import ArchiveParams
        self.asked = ArchiveParams.resolve(batch.params if batch else {})
        self._framework_digest = None

    @classmethod
    def prepare(cls, batch, framework, *, device="gpu", backend=None,
                survey=None, data_dirs=()) -> "SurveyRun":
        """Resolve the engine and the parameters, and enumerate the work.

        ``backend`` defaults to the host or device backend that ``device``
        names.  Inject one to run the orchestration against another engine.

        The parameters the survey executes with are resolved against the
        backend's capability defaults, so each engine runs with the walker count
        and checkpoint cadence it wants.  The task digests come from the batch
        and never see those defaults, so one batch keeps one identity wherever
        it runs.

        ``survey`` is the project file that a work unit's ``resume`` names a run
        in.  A batch that continues nothing does not need it.  The illuminations
        to continue are read here, because what a task asks for includes where
        it starts and that is hashed before any of it runs.

        ``data_dirs`` names folders to search for an alignment that the
        framework does not hold and that is not at its recorded path; see
        :func:`~hifuku.framework.alignment_source`.
        """
        from hifuku.params import ArchiveParams, GpuParams
        from hifuku.timing import RunClock

        if backend is None:
            backend = _resolve_backend(device, batch.gpu_params)
        elif batch.gpu_params:
            GpuParams.resolve(batch.gpu_params)

        # The engine wraps its own device work in a timer, and the clock reads
        # it.  An engine without one reports no device time, which is right for
        # the host engine.
        clock = RunClock(device=device,
                         device_work=getattr(backend, "device_work", None)
                         or RunClock().device_work)
        tasks = batch.tasks(framework, survey=survey)
        params = ArchiveParams.resolve(backend.caps.defaults, batch.params)
        # The batch resolved which record each task continues, as a run and a
        # seal.  The state to continue from is in the same records, so it is
        # collected here rather than read again at execution.  It is checked
        # against the parent's state digest before any work: a snapshot that
        # was changed after the parent was sealed is not the parent's state.
        from hifuku.seal import ProvenanceError, record_state
        resume = {}
        for task in tasks:
            if not task.continues:
                continue
            run = survey.run_by_id(task.parent)
            rec = next(r for r in run.surveys
                       if r.chart == task.chart and r.gene == task.gene)
            held = record_state(rec)
            if held != rec.state_digest or rec.seal != task.parent_seal:
                raise ProvenanceError(
                    f"the record of {task.gene!r} on chart {task.chart} in run "
                    f"{run.group_name} no longer holds the state it was sealed "
                    f"with, so it cannot be continued")
            resume[(task.chart, task.gene)] = (rec.snapshot, rec.state_digest)
        return cls(batch, framework, device, backend, params, tasks,
                   clock=clock, resume=resume, data_dirs=data_dirs)

    def alignment(self, gene: str):
        """The compressed alignment for one gene, read once and kept.

        The bytes come from :func:`~hifuku.framework.alignment_source`: those
        the framework holds, or a file found by the recorded digest, first at
        the recorded path, then where the batch names it, then in the data
        folders of this run.  The digest is checked, because a different
        alignment would put a survey on coordinates that do not describe it.
        """
        if gene not in self._alignments:
            from hifuku.alignment import alignment_from_text
            from hifuku.framework import alignment_source
            info = self.framework.alignment(gene)
            named = self._batch_paths.get(gene)
            data = alignment_source(info, paths=[named] if named else [],
                                    data_dirs=self.data_dirs)
            self._alignments[gene] = alignment_from_text(
                data.decode(), self.framework.taxon_table)
        return self._alignments[gene]

    def context(self, task: SurveyTask):
        """The :class:`~hifuku.backend.RunContext` for one work unit."""
        from hifuku.backend import RunContext
        chart = self.framework.charts[task.chart]
        r = [self.framework.alignment(a).nj_tree for a in chart.anchors]
        return RunContext(anchors=(r[0], r[1], r[2]),
                          alignment=self.alignment(task.gene),
                          model=self._model(),
                          start_trees=[self.framework.alignment(
                              task.gene).nj_tree],
                          triangle=chart.triangle,
                          taxon_table=self.framework.taxon_table)

    def _model(self):
        """The substitution model object the framework's label names.

        The framework records a label, because the model object does not
        serialize.  A label reads ``"lg"`` or ``"lg (auto)"``, where the
        parenthetical records that the model was chosen from the sequence type
        rather than named, and the key is the first word either way.  The
        sequence type is not consulted here: the choice was made when the
        framework was built and is not made again.
        """
        from hifuku.cli import _resolve_model
        model, _label = _resolve_model(self.framework.model.split()[0], None)
        return model

    def execute(self, task: SurveyTask, *, monitor=False) -> SurveyRecord:
        """Survey one gene on one chart and keep the record.

        ``monitor`` reaches :func:`~hifuku.driver.run_survey`, which calls it at
        every checkpoint.  A monitor that names ``task`` receives this task.
        """
        from hifuku.driver import run_survey
        from hifuku.seal import ProvenanceError, params_dict, seal_record

        resume, parent_state = self._resume.get((task.chart, task.gene),
                                                (None, ""))
        with self.clock.span(f"survey/{task.chart}/{task.gene}") as span:
            result = run_survey(self.backend, self.context(task), self.params,
                                monitor=monitor, task=task, resume=resume)
        # The start state comes from the engine.  A task that continues a
        # record must have started from that record's end state, and a task
        # that starts from nothing must have seeded.
        if result.start_state != parent_state:
            raise ProvenanceError(
                f"the survey of {task.gene!r} on chart {task.chart} started "
                f"from state {result.start_state[:12]!r}, and its task names "
                f"parent {task.parent!r} whose end state is "
                f"{parent_state[:12]!r}")
        # The shape comes from the result rather than from ``self.params``,
        # because an engine that sizes itself to the device settles the walker
        # count and the cadence per gene.  The record says what ran.
        shape = result.params if result.params is not None else self.params
        record = SurveyRecord(
            gene=task.gene, archive=result.archive, chart=task.chart,
            task_digest=task.digest, history=result.history,
            landscape=result.landscape, moves=result.moves, qd=result.qd,
            checkpoint_seconds=tuple(result.checkpoint_seconds),
            converged=result.converged, halt_iter=result.halt_iter,
            model=self.framework.model, n_iters=int(shape.n_iters),
            seed=int(shape.seed), n_walkers=int(shape.n_walkers),
            checkpoint_every=int(shape.checkpoint_every), device=self.device,
            wall_seconds=span.wall, cpu_seconds=span.cpu,
            device_seconds=span.device,
            parent=task.parent, parent_seal=task.parent_seal,
            snapshot=result.snapshot,
            precision=dict(self.backend.caps.precision),
            task_params=params_dict(self.asked), params=params_dict(shape),
            gpu_params=params_dict(getattr(self.backend, "gpu_params", None)),
            engine=str(self.backend.caps.name),
            start_state=result.start_state)
        if self._framework_digest is None:
            self._framework_digest = self.framework.digest()
        seal_record(record, self.framework, self._framework_digest)
        self._records[(task.chart, task.gene)] = record
        return record

    def record(self, chart: int, gene: str):
        """Return the record of the task that surveyed ``gene`` on ``chart``,
        or None before that task runs."""
        return self._records.get((chart, gene))

    def finish(self, *, author=None) -> Run:
        """Assemble the executed records into a :class:`Run`.

        A task that no call executed is left out, so a run holds what was done
        rather than what was asked.
        """
        from hifuku.framework import _device_arch

        records = [self._records[(t.chart, t.gene)] for t in self.tasks
                   if (t.chart, t.gene) in self._records]
        # The architecture is the run's own, not the framework's.  A framework
        # built on a workstation and surveyed on a cluster node records both,
        # which is what a later mismatch report reads.
        provenance = dict(_provenance(self.device, author),
                          framework_digest=self.framework.digest(),
                          device=self.device, device_arch=_device_arch(self.device))
        return Run(label=self.batch.label, surveys=records,
                   provenance=provenance, timing=self.timing())

    def timing(self) -> dict:
        """What this run cost, keyed ``<step>/<clock>``.

        One span per gene, and a ``total`` that adds them.  The genes do not
        overlap, so adding them is meaningful.

        Building the charts is not here.  It is the framework's cost, paid once
        however many batches run inside it, and
        :attr:`~hifuku.framework.Framework.timing` carries it.  Adding it to
        each run would count one neighbor-joining pass once per batch.
        """
        out = {name: float(value) if not name.endswith("/count") else int(value)
               for name, value in self.clock.as_attrs(prefix="").items()}
        out = {name.lstrip("/"): value for name, value in out.items()}
        survey = self.clock.total("survey/")
        for label in ("survey", "total"):
            out[f"{label}/wall"] = float(survey.wall)
            out[f"{label}/cpu"] = float(survey.cpu)
            out[f"{label}/device"] = float(survey.device)
        out["started"] = self._started
        out["finished"] = datetime.datetime.now(
            datetime.timezone.utc).isoformat()
        return out

prepare classmethod

prepare(batch, framework, *, device='gpu', backend=None, survey=None, data_dirs=()) -> 'SurveyRun'

Resolve the engine and the parameters, and enumerate the work.

backend defaults to the host or device backend that device names. Inject one to run the orchestration against another engine.

The parameters the survey executes with are resolved against the backend's capability defaults, so each engine runs with the walker count and checkpoint cadence it wants. The task digests come from the batch and never see those defaults, so one batch keeps one identity wherever it runs.

survey is the project file that a work unit's resume names a run in. A batch that continues nothing does not need it. The illuminations to continue are read here, because what a task asks for includes where it starts and that is hashed before any of it runs.

data_dirs names folders to search for an alignment that the framework does not hold and that is not at its recorded path; see :func:~hifuku.framework.alignment_source.

Source code in src/hifuku/survey_io.py
@classmethod
def prepare(cls, batch, framework, *, device="gpu", backend=None,
            survey=None, data_dirs=()) -> "SurveyRun":
    """Resolve the engine and the parameters, and enumerate the work.

    ``backend`` defaults to the host or device backend that ``device``
    names.  Inject one to run the orchestration against another engine.

    The parameters the survey executes with are resolved against the
    backend's capability defaults, so each engine runs with the walker count
    and checkpoint cadence it wants.  The task digests come from the batch
    and never see those defaults, so one batch keeps one identity wherever
    it runs.

    ``survey`` is the project file that a work unit's ``resume`` names a run
    in.  A batch that continues nothing does not need it.  The illuminations
    to continue are read here, because what a task asks for includes where
    it starts and that is hashed before any of it runs.

    ``data_dirs`` names folders to search for an alignment that the
    framework does not hold and that is not at its recorded path; see
    :func:`~hifuku.framework.alignment_source`.
    """
    from hifuku.params import ArchiveParams, GpuParams
    from hifuku.timing import RunClock

    if backend is None:
        backend = _resolve_backend(device, batch.gpu_params)
    elif batch.gpu_params:
        GpuParams.resolve(batch.gpu_params)

    # The engine wraps its own device work in a timer, and the clock reads
    # it.  An engine without one reports no device time, which is right for
    # the host engine.
    clock = RunClock(device=device,
                     device_work=getattr(backend, "device_work", None)
                     or RunClock().device_work)
    tasks = batch.tasks(framework, survey=survey)
    params = ArchiveParams.resolve(backend.caps.defaults, batch.params)
    # The batch resolved which record each task continues, as a run and a
    # seal.  The state to continue from is in the same records, so it is
    # collected here rather than read again at execution.  It is checked
    # against the parent's state digest before any work: a snapshot that
    # was changed after the parent was sealed is not the parent's state.
    from hifuku.seal import ProvenanceError, record_state
    resume = {}
    for task in tasks:
        if not task.continues:
            continue
        run = survey.run_by_id(task.parent)
        rec = next(r for r in run.surveys
                   if r.chart == task.chart and r.gene == task.gene)
        held = record_state(rec)
        if held != rec.state_digest or rec.seal != task.parent_seal:
            raise ProvenanceError(
                f"the record of {task.gene!r} on chart {task.chart} in run "
                f"{run.group_name} no longer holds the state it was sealed "
                f"with, so it cannot be continued")
        resume[(task.chart, task.gene)] = (rec.snapshot, rec.state_digest)
    return cls(batch, framework, device, backend, params, tasks,
               clock=clock, resume=resume, data_dirs=data_dirs)

alignment

alignment(gene: str)

The compressed alignment for one gene, read once and kept.

The bytes come from :func:~hifuku.framework.alignment_source: those the framework holds, or a file found by the recorded digest, first at the recorded path, then where the batch names it, then in the data folders of this run. The digest is checked, because a different alignment would put a survey on coordinates that do not describe it.

Source code in src/hifuku/survey_io.py
def alignment(self, gene: str):
    """The compressed alignment for one gene, read once and kept.

    The bytes come from :func:`~hifuku.framework.alignment_source`: those
    the framework holds, or a file found by the recorded digest, first at
    the recorded path, then where the batch names it, then in the data
    folders of this run.  The digest is checked, because a different
    alignment would put a survey on coordinates that do not describe it.
    """
    if gene not in self._alignments:
        from hifuku.alignment import alignment_from_text
        from hifuku.framework import alignment_source
        info = self.framework.alignment(gene)
        named = self._batch_paths.get(gene)
        data = alignment_source(info, paths=[named] if named else [],
                                data_dirs=self.data_dirs)
        self._alignments[gene] = alignment_from_text(
            data.decode(), self.framework.taxon_table)
    return self._alignments[gene]

context

context(task: SurveyTask)

The :class:~hifuku.backend.RunContext for one work unit.

Source code in src/hifuku/survey_io.py
def context(self, task: SurveyTask):
    """The :class:`~hifuku.backend.RunContext` for one work unit."""
    from hifuku.backend import RunContext
    chart = self.framework.charts[task.chart]
    r = [self.framework.alignment(a).nj_tree for a in chart.anchors]
    return RunContext(anchors=(r[0], r[1], r[2]),
                      alignment=self.alignment(task.gene),
                      model=self._model(),
                      start_trees=[self.framework.alignment(
                          task.gene).nj_tree],
                      triangle=chart.triangle,
                      taxon_table=self.framework.taxon_table)

execute

execute(task: SurveyTask, *, monitor=False) -> SurveyRecord

Survey one gene on one chart and keep the record.

monitor reaches :func:~hifuku.driver.run_survey, which calls it at every checkpoint. A monitor that names task receives this task.

Source code in src/hifuku/survey_io.py
def execute(self, task: SurveyTask, *, monitor=False) -> SurveyRecord:
    """Survey one gene on one chart and keep the record.

    ``monitor`` reaches :func:`~hifuku.driver.run_survey`, which calls it at
    every checkpoint.  A monitor that names ``task`` receives this task.
    """
    from hifuku.driver import run_survey
    from hifuku.seal import ProvenanceError, params_dict, seal_record

    resume, parent_state = self._resume.get((task.chart, task.gene),
                                            (None, ""))
    with self.clock.span(f"survey/{task.chart}/{task.gene}") as span:
        result = run_survey(self.backend, self.context(task), self.params,
                            monitor=monitor, task=task, resume=resume)
    # The start state comes from the engine.  A task that continues a
    # record must have started from that record's end state, and a task
    # that starts from nothing must have seeded.
    if result.start_state != parent_state:
        raise ProvenanceError(
            f"the survey of {task.gene!r} on chart {task.chart} started "
            f"from state {result.start_state[:12]!r}, and its task names "
            f"parent {task.parent!r} whose end state is "
            f"{parent_state[:12]!r}")
    # The shape comes from the result rather than from ``self.params``,
    # because an engine that sizes itself to the device settles the walker
    # count and the cadence per gene.  The record says what ran.
    shape = result.params if result.params is not None else self.params
    record = SurveyRecord(
        gene=task.gene, archive=result.archive, chart=task.chart,
        task_digest=task.digest, history=result.history,
        landscape=result.landscape, moves=result.moves, qd=result.qd,
        checkpoint_seconds=tuple(result.checkpoint_seconds),
        converged=result.converged, halt_iter=result.halt_iter,
        model=self.framework.model, n_iters=int(shape.n_iters),
        seed=int(shape.seed), n_walkers=int(shape.n_walkers),
        checkpoint_every=int(shape.checkpoint_every), device=self.device,
        wall_seconds=span.wall, cpu_seconds=span.cpu,
        device_seconds=span.device,
        parent=task.parent, parent_seal=task.parent_seal,
        snapshot=result.snapshot,
        precision=dict(self.backend.caps.precision),
        task_params=params_dict(self.asked), params=params_dict(shape),
        gpu_params=params_dict(getattr(self.backend, "gpu_params", None)),
        engine=str(self.backend.caps.name),
        start_state=result.start_state)
    if self._framework_digest is None:
        self._framework_digest = self.framework.digest()
    seal_record(record, self.framework, self._framework_digest)
    self._records[(task.chart, task.gene)] = record
    return record

record

record(chart: int, gene: str)

Return the record of the task that surveyed gene on chart, or None before that task runs.

Source code in src/hifuku/survey_io.py
def record(self, chart: int, gene: str):
    """Return the record of the task that surveyed ``gene`` on ``chart``,
    or None before that task runs."""
    return self._records.get((chart, gene))

finish

finish(*, author=None) -> Run

Assemble the executed records into a :class:Run.

A task that no call executed is left out, so a run holds what was done rather than what was asked.

Source code in src/hifuku/survey_io.py
def finish(self, *, author=None) -> Run:
    """Assemble the executed records into a :class:`Run`.

    A task that no call executed is left out, so a run holds what was done
    rather than what was asked.
    """
    from hifuku.framework import _device_arch

    records = [self._records[(t.chart, t.gene)] for t in self.tasks
               if (t.chart, t.gene) in self._records]
    # The architecture is the run's own, not the framework's.  A framework
    # built on a workstation and surveyed on a cluster node records both,
    # which is what a later mismatch report reads.
    provenance = dict(_provenance(self.device, author),
                      framework_digest=self.framework.digest(),
                      device=self.device, device_arch=_device_arch(self.device))
    return Run(label=self.batch.label, surveys=records,
               provenance=provenance, timing=self.timing())

timing

timing() -> dict

What this run cost, keyed <step>/<clock>.

One span per gene, and a total that adds them. The genes do not overlap, so adding them is meaningful.

Building the charts is not here. It is the framework's cost, paid once however many batches run inside it, and :attr:~hifuku.framework.Framework.timing carries it. Adding it to each run would count one neighbor-joining pass once per batch.

Source code in src/hifuku/survey_io.py
def timing(self) -> dict:
    """What this run cost, keyed ``<step>/<clock>``.

    One span per gene, and a ``total`` that adds them.  The genes do not
    overlap, so adding them is meaningful.

    Building the charts is not here.  It is the framework's cost, paid once
    however many batches run inside it, and
    :attr:`~hifuku.framework.Framework.timing` carries it.  Adding it to
    each run would count one neighbor-joining pass once per batch.
    """
    out = {name: float(value) if not name.endswith("/count") else int(value)
           for name, value in self.clock.as_attrs(prefix="").items()}
    out = {name.lstrip("/"): value for name, value in out.items()}
    survey = self.clock.total("survey/")
    for label in ("survey", "total"):
        out[f"{label}/wall"] = float(survey.wall)
        out[f"{label}/cpu"] = float(survey.cpu)
        out[f"{label}/device"] = float(survey.device)
    out["started"] = self._started
    out["finished"] = datetime.datetime.now(
        datetime.timezone.utc).isoformat()
    return out

Cloud dataclass

A named set of runs, and the points they hold.

Once one file holds two runs of a gene, "the cloud" names nothing: a point is a gene, a chart and a niche, and two runs supply that identity with different trees. A cloud fixes which runs are meant, so an embedding built over it keeps describing the same points after the file grows.

Attributes:

Name Type Description
label str

A name, unique within a survey, which also names the group in the file.

run_ids tuple of str

The runs this cloud spans.

identity tuple of tuple

(run_id, gene, chart, i, j) for every point, in cloud order. The run is part of the identity because two runs of one gene fill the same niches, and without it a cloud would carry the same digest as one that dropped a duplicate.

cloud_digest str

Over the runs and the point identities: which points are here.

content_digest str

Over the result digest of every survey the cloud spans: what is in them. Kept apart from cloud_digest so that a reader of a refusal can tell a cloud that lost a run from one whose trees moved.

created str

UTC timestamp.

Source code in src/hifuku/survey_io.py
@dataclass(frozen=True)
class Cloud:
    """A named set of runs, and the points they hold.

    Once one file holds two runs of a gene, "the cloud" names nothing: a point
    is a gene, a chart and a niche, and two runs supply that identity with
    different trees.  A cloud fixes which runs are meant, so an embedding built
    over it keeps describing the same points after the file grows.

    Attributes
    ----------
    label : str
        A name, unique within a survey, which also names the group in the file.
    run_ids : tuple of str
        The runs this cloud spans.
    identity : tuple of tuple
        ``(run_id, gene, chart, i, j)`` for every point, in cloud order.  The
        run is part of the identity because two runs of one gene fill the same
        niches, and without it a cloud would carry the same digest as one that
        dropped a duplicate.
    cloud_digest : str
        Over the runs and the point identities: which points are here.
    content_digest : str
        Over the result digest of every survey the cloud spans: what is in them.
        Kept apart from ``cloud_digest`` so that a reader of a refusal can tell
        a cloud that lost a run from one whose trees moved.
    created : str
        UTC timestamp.
    """

    label: str
    run_ids: tuple
    identity: tuple
    cloud_digest: str
    content_digest: str
    created: str

    @property
    def n_points(self) -> int:
        return len(self.identity)

CloudPoint dataclass

One elite tree in the survey cloud, with its provenance.

run_id is part of the provenance because one gene may have been surveyed by more than one run, and the niche alone does not say which tree this is.

Source code in src/hifuku/survey_io.py
@dataclass
class CloudPoint:
    """One elite tree in the survey cloud, with its provenance.

    ``run_id`` is part of the provenance because one gene may have been surveyed
    by more than one run, and the niche alone does not say which tree this is.
    """

    tree: object                    # HifukuTree (materialized)
    gene: str
    chart: int
    key: tuple
    logL: float
    z: float
    run_id: str = ""

Ordination dataclass

One stored embedding of a cloud, with its provenance.

X[i] belongs to survey.points(cloud)[i]. That correspondence is by position alone, so the record names the cloud it was built over and carries that cloud's digests. :meth:Survey.ordination_matrix checks them, which turns a survey whose runs have moved into a raised error rather than a figure with the labels shuffled.

The check is at the point of use rather than at load. A file whose runs were split off elsewhere still opens and still reports what it holds, so a reader can see what an old embedding covered.

Attributes:

Name Type Description
label str

Name the caller gave this embedding, unique within a survey.

method str

How it was produced, for example "tsne" or "mds".

params dict

Whatever the method was given: a seed, a perplexity, and so on.

X ndarray

(n, dim) coordinates.

faithfulness Faithfulness or None

The score of this embedding, when one was measured.

created str

UTC timestamp.

n_points int

Rows of X, and points in the cloud it came from.

cloud str

The label of that cloud.

cloud_digest, content_digest str

The cloud's digests as they stood when the embedding was made.

Source code in src/hifuku/survey_io.py
@dataclass(frozen=True)
class Ordination:
    """One stored embedding of a cloud, with its provenance.

    ``X[i]`` belongs to ``survey.points(cloud)[i]``.  That correspondence is by
    position alone, so the record names the cloud it was built over and carries
    that cloud's digests.  :meth:`Survey.ordination_matrix` checks them, which
    turns a survey whose runs have moved into a raised error rather than a
    figure with the labels shuffled.

    The check is at the point of use rather than at load.  A file whose runs
    were split off elsewhere still opens and still reports what it holds, so a
    reader can see what an old embedding covered.

    Attributes
    ----------
    label : str
        Name the caller gave this embedding, unique within a survey.
    method : str
        How it was produced, for example ``"tsne"`` or ``"mds"``.
    params : dict
        Whatever the method was given: a seed, a perplexity, and so on.
    X : numpy.ndarray
        ``(n, dim)`` coordinates.
    faithfulness : Faithfulness or None
        The score of this embedding, when one was measured.
    created : str
        UTC timestamp.
    n_points : int
        Rows of ``X``, and points in the cloud it came from.
    cloud : str
        The label of that cloud.
    cloud_digest, content_digest : str
        The cloud's digests as they stood when the embedding was made.
    """

    label: str
    method: str
    params: dict
    X: np.ndarray
    faithfulness: object
    created: str
    n_points: int
    cloud: str
    cloud_digest: str
    content_digest: str