PineForge HPO 1.11.0
Native hyperparameter optimization for PineForge strategies
Loading...
Searching...
No Matches
pbo.py
Go to the documentation of this file.
1"""Probability of Backtest Overfitting (CSCV) over per-block moments: the exact stdlib reference.
2
3Post hoc and pure. The input is an N x S table of block moments, one record per trial
4(``{trial_id, status, block_returns: {status, count[S], sum[S], m2[S]}}``), never the T x N
5return matrix. ``count`` is the number of intervals in a block, ``sum`` the sum of the
6per-interval returns and ``m2`` the sum of squared deviations from the block mean. A row with
7status ``ok`` or ``constraint_violation`` is computed (default D5); a failed, pruned or partial
8row, or a payload that reports a non-positive equity, refuses with a code of its own. The rows
9come in parts, each part with the result-level ``return_blocks`` object its rows were reduced
10under plus a ``dataset_identity`` that the caller states (a call with one part passes a list of
11one pair), and the caller declares the roster (the declared trial set). The module refuses
12unless the parts declare one and the same object, every row's counts equal the ``n_b`` of its
13own part's object, and the rows of all the parts together are exactly the roster. It checks what
14it is handed: the grouping of the rows into parts and the object declared for each part are the
15caller's. The module enumerates all C(S, S/2) ordered train/test splits of the S blocks, ranks
16every trial on the training blocks, and reports how the training winner ranks on the
17complementary blocks.
18
19Every number is plain binary64 arithmetic in a fixed operation order, with no fused
20operations and no tolerance. Counts and the sign of the logit are exact integer arithmetic; only
21the logarithm of a logit value depends on the platform math library. Contract text and defaults:
22``docs/pbo.md``.
23Status: the native-proof PBO run uses synthetic data only; PBO on real data is not yet proven.
24"""
25
26from __future__ import annotations
27
28from collections import Counter
29from dataclasses import dataclass, field
30from fractions import Fraction
31import hashlib
32from itertools import combinations
33import json
34import math
35from typing import Any, Iterable, Iterator, Sequence
36
37CONTRACT = "pineforge-hpo-pbo/v1"
38ALGORITHM = "cscv-all-ordered-splits/v1"
39STATISTIC = "pooled-mean-over-sample-sigma/v1"
40
41CONSTRAINT_VIOLATION = "constraint_violation"
42NON_POSITIVE_EQUITY = "non_positive_equity"
43
44# Row statuses (default D5). A constraint-violating trial was tried, so it belongs to the roster
45# and is computed like an ok trial. A failed, pruned or partial trial refuses, each with its own
46# code; so does a payload whose status says an equity at or below zero skipped an interval.
47ROSTER_ROW_STATUSES = (OK, CONSTRAINT_VIOLATION)
48ERROR_ROW_STATUSES = (
49 "error",
50 "objective_error",
51 "constraint_error",
52 "engine_error",
53 "trial_error",
54 "trial_timeout",
55)
56PRUNED_ROW_STATUS = "pruned"
57PARTIAL_ROW_STATUS = "partial"
58
59# The result-level ``return_blocks`` object of the pinned wire (dossier clause 3.3) declares the
60# layout the rows of a part were reduced under. These are its keys.
61RETURN_BLOCKS_CONTRACT = "pineforge-hpo-return-blocks/v1"
62RETURN_BLOCKS_SERIES = "bar"
63RETURN_BLOCKS_KEYS = (
64 "contract",
65 "series",
66 "S",
67 "K",
68 "n_b",
69 "boundary_time_ms",
70 "numeric_build_identity",
71)
72# The declared object of a part is that object plus one key of this API, not of the wire: the
73# caller states a text that names the dataset the rows of the part were reduced over. Contract
74# clause 3.5 refuses a dataset that differs between parts, and the interval count and the time
75# axis alone cannot tell two datasets of the same length apart. Exactly the keys of
76# ``DECLARED_OBJECT_KEYS`` are read; any other key refuses.
77DATASET_IDENTITY_KEY = "dataset_identity"
78DECLARED_OBJECT_KEYS = RETURN_BLOCKS_KEYS + (DATASET_IDENTITY_KEY,)
79
80TIE_RULES = {
81 "equality": "exact_binary64",
82 "train_best": "mixture_weight_1_over_k",
83 "oos_rank": "mid_rank",
84}
85
86INTERPRETATION = (
87 "A deterministic frequency over the re-labellings of one dataset into training and testing "
88 "halves. The composition of the trial roster moves it. For adaptive or correlated trials it "
89 "is a diagnostic, not a probability under independent strategy draws."
90)
91
92PAPER_CONFORMANT_SAMPLERS = ("grid", "random", "sobol")
93DIAGNOSTIC_SAMPLERS = ("tpe", "dlib_global", "candidates")
94
95# A required keyword of ``pbo`` that was not passed (None is a value: no early stop).
96
97
98CODES = (
99 "pbo_input_invalid",
100 "pbo_parameter_missing",
101 "pbo_roster_mismatch",
102 "pbo_return_blocks_mismatch",
103 "pbo_block_sizes_uneven",
104 "pbo_dataset_mismatch",
105 "pbo_window_mismatch",
106 "pbo_identity_mismatch",
107 "pbo_rows_incomplete",
108 "pbo_status_error",
109 "pbo_status_pruned",
110 "pbo_status_partial",
111 "pbo_non_positive_equity",
112 "pbo_odd_s",
113 "pbo_too_few_trials",
114 "pbo_zero_variance",
115 "pbo_block_mismatch",
116 "pbo_resource_exceeded",
117 "pbo_sampler_unknown",
118)
119
120# When several kinds of row problems occur at once, the first kind in this order is reported
121# (with every offending id of that kind), so the refusal does not depend on the row order.
122# Every code that a row, or the comparison of the rows with the roster, can raise is listed.
123
124
125
126
127
128
129
130
131
132
133
134# The fields in which the declared objects of two parts can differ (contract clause 3.5), with the
135# code of each difference. K comes first: a different interval count is a different dataset (and
136# changes n_b with it), and so is a different dataset identity; the same K with other counts is a
137# different block layout. The contract, the series and S are not listed: every declared object
138# must carry the fixed contract and series and the S of the call, so they cannot differ between
139# parts that were accepted one by one.
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156class PboError(Exception):
157 """A refusal: a module-local ``pbo_`` code, one plain sentence, the offending trial ids and,
158 when a call parameter is the offender, its name.
159
160 ``code`` and ``ids`` are those of the first kind of problem in the fixed priority order.
161 ``refusals`` names every kind that was found, in that order, each with its ``count`` and its
162 offending ``ids`` (contract clause 3.5: counts per reason and offending ids), and
163 ``coverage`` says how much of the declared roster the rows cover (``declared`` trials,
164 ``supplied`` rows, ``usable`` declared trials whose row had no problem) when the rows were
165 examined, else None; a refusal raised after the rows were accepted, such as a zero variance
166 or a work figure above ``max_work``, carries it too. A refusal that was not found among rows
167 has the one entry of its own code, counting its ids (or 1 when it has none).
168 """
169
171 self,
172 code: str,
173 detail: str,
174 ids: Iterable[Any] = (),
175 names: Iterable[str] = (),
176 *,
177 coverage: dict[str, int] | None = None,
178 refusals: Iterable[dict[str, Any]] | None = None,
179 ) -> None:
180 super().__init__(f"{code}: {detail}")
181 self.code = code
182 self.detail = detail
183 self.ids = tuple(sorted(ids, key=_id_key))
184 self.names = tuple(names)
185 self.coverage = None if coverage is None else dict(coverage)
186 if refusals is None:
187 refusals = [{"code": code, "count": len(self.ids) or 1, "ids": self.ids}]
188 self.refusals = tuple(
189 {"code": item["code"], "count": item["count"], "ids": tuple(item["ids"])}
190 for item in refusals
191 )
192
193 def document(self) -> dict[str, Any]:
194 """The refusal as a JSON-ready document; it carries no number of the analysis."""
195 return {
196 "contract": CONTRACT,
197 "status": "refused",
198 "code": self.code,
199 "detail": self.detail,
200 "ids": list(self.ids),
201 "names": list(self.names),
202 "coverage": None if self.coverage is None else dict(self.coverage),
203 "refusals": [
204 {"code": item["code"], "count": item["count"], "ids": list(item["ids"])}
205 for item in self.refusals
206 ],
207 }
208
209
210
211
212
213
214
215
216
217@dataclass(frozen=True)
219 """A validated N x S table of block moments; rows ascend by trial id.
220
221 ``counts`` is common to every row and equals ``n_b`` of the declared object. ``sums[i][b]``
222 and ``m2[i][b]`` belong to trial ``trial_ids[i]`` and block ``b``. ``return_blocks_json`` is
223 the text of the declared object that every part declared.
224
225 The table checks itself whenever it is built, whoever builds it: at least 2 trials, unique
226 ascending ids of one type, arrays of the right lengths, counts equal to ``n_b``, finite
227 moments, and the declared object itself (including the half-size rule). ``input_sha256`` is
228 not an argument: it is computed from the content, so it cannot disagree with it. A refusal is
229 a ``PboError``.
230 """
231
232 S: int
233 trial_ids: tuple[Any, ...]
234 counts: tuple[int, ...]
235 sums: tuple[tuple[float, ...], ...]
236 m2: tuple[tuple[float, ...], ...]
237 return_blocks_json: str
238 input_sha256: str = field(init=False)
239
240 def __post_init__(self) -> None:
241 size = _check_s(self.S)
242 context = _table_context(self.return_blocks_json, size)
243 ids = _table_ids(self.trial_ids)
244 counts = self.counts
245 if not isinstance(counts, (list, tuple)):
246 raise PboError("pbo_input_invalid", "counts must be an array")
247 if len(counts) != size:
248 raise PboError(
249 "pbo_block_mismatch",
250 f"counts has {len(counts)} entries, expected S={size}",
251 )
252 if any(type(count) is not int for count in counts):
253 raise PboError("pbo_input_invalid", "every count must be an integer")
254 if list(counts) != context["n_b"]:
255 raise PboError(
256 "pbo_block_mismatch", "the counts differ from return_blocks.n_b"
257 )
258 raw_sums = _table_matrix("sums", self.sums, len(ids), size)
259 raw_m2 = _table_matrix("m2", self.m2, len(ids), size)
260 sums: list[tuple[float, ...]] = []
261 m2s: list[tuple[float, ...]] = []
262 for position, trial_id in enumerate(ids):
263 try:
264 blocks = [
265 _check_block(
266 index,
267 counts[index],
268 raw_sums[position][index],
269 raw_m2[position][index],
270 )
271 for index in range(size)
272 ]
273 except _RowProblem as problem:
274 raise PboError(
275 problem.code, f"trial {trial_id!r}: {problem.detail}", [trial_id]
276 ) from None
277 sums.append(tuple(total for total, _ in blocks))
278 m2s.append(tuple(centred for _, centred in blocks))
279 object.__setattr__(self, "S", size)
280 object.__setattr__(self, "trial_ids", ids)
281 object.__setattr__(self, "counts", tuple(counts))
282 object.__setattr__(self, "sums", tuple(sums))
283 object.__setattr__(self, "m2", tuple(m2s))
284 object.__setattr__(
285 self, "return_blocks_json", _canonical(context).decode("ascii")
286 )
287 object.__setattr__(self, "input_sha256", _input_digest(ids, counts, sums, m2s))
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813def load_moment_table(parts: Any, *, S: int, roster: Any = None) -> MomentTable:
814 """Validate the parts (contract clause 3.5) and return the merged table sorted by trial id.
815
816 ``parts`` is a list of ``(declared object, rows)`` pairs, one for each part of the lineage (a
817 call with one part passes a list of one pair): the declared object is the result-level
818 ``return_blocks`` object the rows of that part were reduced under, plus the
819 ``dataset_identity`` that the caller states. ``roster`` is the declared trial set of the
820 lineage. Both are required. The declared objects of all the parts must be
821 one and the same, every row's counts must equal the ``n_b`` of its own part's object, and the
822 rows of all the parts together must be exactly the roster. Refuses with ``PboError`` and
823 never subsets: one bad row refuses the whole roster.
824 """
825 S = _check_s(S)
826 declared_ids = _declared_ids(roster)
827 return _load_parts(parts, S, declared_ids)
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
941def merge_moments(a: Triple, b: Triple) -> Triple:
942 """Merge two ``(count, sum, m2)`` triples, ``a`` before ``b``, by the Chan/Pebay rule.
943
944 ``M2 = M2a + M2b + d*d*na*nb/n`` with ``d = sum_b/nb - sum_a/na``. The operation order is
945 pinned: ``(((d*d)*na)*nb)/n`` is formed first and added to ``(M2a + M2b)``; each operation
946 is a separate binary64 step, so nothing is fused. The term added is never negative, hence
947 neither is the result.
948 """
949 na, sa, ma = a
950 nb, sb, mb = b
951 n = na + nb
952 d = sb / nb - sa / na
953 t = d * d
954 t = t * na
955 t = t * nb
956 t = t / n
957 return n, sa + sb, (ma + mb) + t
958
959
960def pooled_moments(blocks: Iterable[Triple]) -> Triple:
961 """Merge the triples left to right in the order given (block order); the fold is pinned."""
962 iterator = iter(blocks)
963 try:
964 n, s, m2 = next(iterator)
965 except StopIteration:
966 raise PboError("pbo_input_invalid", "there are no blocks to pool") from None
967 pooled = (n, s, m2)
968 for block in iterator:
969 pooled = merge_moments(pooled, block)
970 return pooled
971
972
973def ranking_statistic(n: int, s: float, m2: float) -> float | None:
974 """Pooled mean over sample sigma: ``(s/n) / sqrt(m2/(n-1))``; risk-free 0, unannualised.
975
976 Returns None when the variance is exactly zero in binary64 (the caller refuses; a flat
977 trial is never imputed). Refuses a count below 2 or a non-finite value.
978 """
979 if n < 2:
980 raise PboError(
981 "pbo_input_invalid", "the sample deviation needs at least 2 intervals"
982 )
983 if not (math.isfinite(s) and math.isfinite(m2)):
984 raise PboError("pbo_input_invalid", "the pooled moments are not finite")
985 if not m2 > 0.0:
986 return None
987 sigma = math.sqrt(m2 / (n - 1))
988 if not sigma > 0.0:
989 return None
990 statistic = (s / n) / sigma
991 if not math.isfinite(statistic):
992 raise PboError("pbo_input_invalid", "the ranking statistic is not finite")
993 return statistic
994
995
996def estimate_work(S: int, N: int) -> dict[str, int]:
997 """The admission figure of contract clause 3.7, exact integers, before any split is run.
998
999 ``n_splits = C(S, S/2)``. Each complementary pair is evaluated once, so the merges are
1000 ``(n_splits/2) * N * (S - 2)``; the comparisons are ``2 * n_splits * N`` (a count of the
1001 selected trial's rank, not a sort). ``work`` is their sum.
1002 """
1003 S = _check_s(S)
1004 if type(N) is not int or N < 0:
1005 raise PboError("pbo_input_invalid", "N must be an integer that is not negative")
1006 n_splits = math.comb(S, S // 2)
1007 merges = (n_splits // 2) * N * (S - 2)
1008 comparisons = 2 * n_splits * N
1009 return {
1010 "n_splits": n_splits,
1011 "merges": merges,
1012 "comparisons": comparisons,
1013 "work": merges + comparisons,
1014 }
1015
1016
1017def roster_label(sampler: Any, *, early_stop: Any = _UNSET) -> str:
1018 """The roster label of default D6; an unknown or missing sampler refuses.
1019
1020 ``diagnostic_adaptive_roster`` for an adaptive sampler and for any sampler whose study had a
1021 no-improvement early stop; ``paper_conformant`` for ``grid``, ``random`` and ``sobol`` without
1022 one. The early stop is not a sampler: it is a separate object of the result, so it is its own
1023 argument and ``"early_stop"`` is not a sampler name. As for ``pbo``, the caller must say
1024 whether the study had one (the result's ``early_stop`` object or ``True``; ``None`` or
1025 ``False`` when it had none): leaving it out refuses with ``pbo_parameter_missing``, so a study
1026 with an early stop cannot get ``paper_conformant`` by a default.
1027 """
1028 stopped = _check_early_stop(early_stop)
1029 if isinstance(sampler, str):
1030 if sampler in DIAGNOSTIC_SAMPLERS:
1031 return "diagnostic_adaptive_roster"
1032 if sampler in PAPER_CONFORMANT_SAMPLERS:
1033 return "diagnostic_adaptive_roster" if stopped else "paper_conformant"
1034 raise PboError(
1035 "pbo_sampler_unknown",
1036 f"sampler {sampler!r} is not one of "
1037 f"{', '.join(PAPER_CONFORMANT_SAMPLERS + DIAGNOSTIC_SAMPLERS)}",
1038 )
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055def iter_ordered_splits(S: int) -> Iterator[tuple[tuple[int, ...], tuple[int, ...]]]:
1056 """Yield every ordered ``(train, test)`` split: C(S, S/2) of them.
1057
1058 Train is a size-S/2 subset of the blocks in original order and test is its complement.
1059 Order: the half that holds block 0, in lexicographic order, as train first and then as test.
1060 """
1061 return _ordered_splits(_check_s(S))
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
1112def pbo(
1113 parts: Any,
1114 *,
1115 S: int,
1116 roster: Any = None,
1117 max_work: int | float | None = None,
1118 sampler: str | None = None,
1119 early_stop: Any = _UNSET,
1120 with_lambdas: bool = False,
1121) -> dict[str, Any]:
1122 """Run CSCV over every ordered split and return the result object (contract clause 3.6).
1123
1124 ``parts`` is a list of ``(declared object, rows)`` pairs, one for each part of the lineage (a
1125 call with one part passes a list of one pair): the declared object is the result-level
1126 ``return_blocks`` object the rows of that part were reduced under, plus the
1127 ``dataset_identity`` that the caller states, and the rows are those that
1128 ``load_moment_table`` takes. A table is not accepted: it has lost its parts.
1129 ``roster`` (the declared trial set of the lineage) is required: the call refuses unless the
1130 declared objects of all the parts are one and the same, every row's counts equal the ``n_b``
1131 of its own part's object, and the rows of all the parts together are exactly the roster
1132 (contract clause 3.5). Block sizes may differ by at most one interval (default D2); the
1133 result then says ``equal_blocks: false`` and names ``block_counts``, and a larger spread
1134 refuses.
1135 ``sampler`` and ``early_stop`` (the result's ``early_stop`` object, or None when it has none)
1136 are both required and decide the roster label of default D6.
1137 Per split, the training winner is the trial with the largest ranking statistic; k tied
1138 winners (exact binary64 equality) each carry weight 1/k. Its out-of-sample rank is the
1139 mid-rank among the N trials, ``omega = rank / (N + 1)`` and
1140 ``lambda = ln(omega / (1 - omega))``. The primary rate ``pbo`` is the share of splits with
1141 lambda <= 0 (default D3); the share with lambda < 0 is reported next to it. A refusal raises
1142 ``PboError``; nothing partial is returned.
1143 """
1144 S = _check_s(S)
1145 _check_budget(max_work)
1146 stopped = _check_early_stop(early_stop)
1147 label = roster_label(sampler, early_stop=stopped)
1148 declared_ids = _declared_ids(roster)
1149 table = _load_parts(parts, S, declared_ids)
1150 n_trials = len(table.trial_ids)
1151 # Every row was accepted and the rows are the roster, so the three numbers are N. A refusal
1152 # from here on carries them: its rows were examined.
1153 coverage = {"declared": n_trials, "supplied": n_trials, "usable": n_trials}
1154 work = estimate_work(S, n_trials)
1155 if max_work is not None and work["work"] > max_work:
1156 raise PboError(
1157 "pbo_resource_exceeded",
1158 f"the estimated work {work['work']} (n_splits {work['n_splits']}, N {n_trials}, "
1159 f"S {S}) exceeds max_work {max_work}",
1160 coverage=coverage,
1161 )
1162 n_splits = work["n_splits"]
1163
1164 below: dict[int, int] = {}
1165 atom: dict[int, int] = {}
1166 above: dict[int, int] = {}
1167 lambdas: list[float] = []
1168 tie_sizes: list[int] = []
1169 total = n_trials + 1
1170 for first, second in _partitions(S):
1171 stats_first = _half_statistics(table, first, coverage)
1172 stats_second = _half_statistics(table, second, coverage)
1173 for train, test in ((stats_first, stats_second), (stats_second, stats_first)):
1174 best = max(train)
1175 winners = [index for index, value in enumerate(train) if value == best]
1176 k = len(winners)
1177 for index in winners:
1178 reference = test[index]
1179 less = 0
1180 equal = 0
1181 for value in test:
1182 if value < reference:
1183 less += 1
1184 elif value == reference:
1185 equal += 1
1186 # twice the mid-rank: omega = rank / (N + 1), odds = omega / (1 - omega).
1187 twice_rank = 2 * less + equal + 1
1188 if twice_rank < total:
1189 bucket = below
1190 elif twice_rank == total:
1191 bucket = atom
1192 else:
1193 bucket = above
1194 bucket[k] = bucket.get(k, 0) + 1
1195 if with_lambdas:
1196 lambdas.append(math.log(twice_rank / (2 * total - twice_rank)))
1197 tie_sizes.append(k)
1198
1199 n_lt0 = _exact_count(below)
1200 n_eq0 = _exact_count(atom)
1201 n_gt0 = _exact_count(above)
1202 if n_lt0 + n_eq0 + n_gt0 != n_splits:
1203 raise RuntimeError(
1204 "internal accounting error: the split counts do not add up to n_splits"
1205 )
1206 rate_le0 = float((n_lt0 + n_eq0) / n_splits)
1207 result: dict[str, Any] = {
1208 "contract": CONTRACT,
1209 "algorithm": ALGORITHM,
1210 "status": OK,
1211 "S": S,
1212 "N": n_trials,
1213 "n_splits": n_splits,
1214 "equal_blocks": len(set(table.counts)) == 1,
1215 "block_counts": list(table.counts),
1216 "statistic": STATISTIC,
1217 "tie_rules": dict(TIE_RULES),
1218 "n_lt0": _count_value(n_lt0),
1219 "n_eq0": _count_value(n_eq0),
1220 "n_gt0": _count_value(n_gt0),
1221 "pbo": rate_le0,
1222 "rate_le0": rate_le0,
1223 "rate_lt0": float(n_lt0 / n_splits),
1224 "calibrated": False,
1225 "interpretation": INTERPRETATION,
1226 "sampler": sampler,
1227 "early_stop": stopped,
1228 "roster_label": label,
1229 "work_estimate": work["work"],
1230 "input_sha256": table.input_sha256,
1231 "return_blocks_sha256": hashlib.sha256(
1232 table.return_blocks_json.encode("ascii")
1233 ).hexdigest(),
1234 "coverage": dict(coverage),
1235 "refusals": [],
1236 }
1237 if with_lambdas:
1238 result["lambdas"] = lambdas
1239 result["lambda_tie_sizes"] = tie_sizes
1240 return result
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
dict[str, Any] document(self)
Definition pbo.py:193
None __init__(self, str code, str detail, Iterable[Any] ids=(), Iterable[str] names=(), *dict[str, int]|None coverage=None, Iterable[dict[str, Any]]|None refusals=None)
Definition pbo.py:179
MomentTable load_moment_table(Any parts, *int S, Any roster=None)
Definition pbo.py:813
Triple merge_moments(Triple a, Triple b)
Definition pbo.py:941
float|None ranking_statistic(int n, float s, float m2)
Definition pbo.py:973
Iterator[tuple[tuple[int,...], tuple[int,...]]] iter_ordered_splits(int S)
Definition pbo.py:1055
Triple pooled_moments(Iterable[Triple] blocks)
Definition pbo.py:960
dict[str, int] estimate_work(int S, int N)
Definition pbo.py:996
str roster_label(Any sampler, *Any early_stop=_UNSET)
Definition pbo.py:1017