Larrivhan commited on
Commit
1cb35cf
·
0 Parent(s):

NeCast release files

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. .gitattributes +91 -0
  2. README.md +253 -0
  3. SHA256SUMS +0 -0
  4. additional/psmcplus_converged/RECEIPT.json +166 -0
  5. additional/psmcplus_converged/apply_patch.py +82 -0
  6. additional/psmcplus_converged/assemble_converged.py +394 -0
  7. additional/psmcplus_converged/build.slurm +39 -0
  8. additional/psmcplus_converged/dropin/chain0_level32.npz +3 -0
  9. additional/psmcplus_converged/meanfill/chain0_level32.npz +3 -0
  10. additional/psmcplus_converged/meanfill_baseline/chain0_level32.npz +3 -0
  11. additional/psmcplus_converged/patch.npz +3 -0
  12. additional/psmcplus_converged/per_row_checks.csv +0 -0
  13. additional/psmcplus_converged/pilot_rows_12500.json +25 -0
  14. additional/psmcplus_converged/pilot_rows_12500.npz +3 -0
  15. additional/psmcplus_converged/psmcplus_converged.py +459 -0
  16. additional/psmcplus_converged/select_pilot_rows.py +193 -0
  17. additional/psmcplus_converged/shards/shard_00000.npz +3 -0
  18. additional/psmcplus_converged/shards/shard_00001.npz +3 -0
  19. additional/psmcplus_converged/shards/shard_00002.npz +3 -0
  20. additional/psmcplus_converged/shards/shard_00003.npz +3 -0
  21. additional/psmcplus_converged/shards/shard_00004.npz +3 -0
  22. additional/psmcplus_converged/shards/shard_00005.npz +3 -0
  23. additional/psmcplus_converged/shards/shard_00006.npz +3 -0
  24. additional/psmcplus_converged/shards/shard_00007.npz +3 -0
  25. additional/psmcplus_converged/shards/shard_00008.npz +3 -0
  26. additional/psmcplus_converged/shards/shard_00009.npz +3 -0
  27. additional/psmcplus_converged/shards/shard_00010.npz +3 -0
  28. additional/psmcplus_converged/shards/shard_00011.npz +3 -0
  29. additional/psmcplus_converged/shards/shard_00012.npz +3 -0
  30. additional/psmcplus_converged/shards/shard_00013.npz +3 -0
  31. additional/psmcplus_converged/shards/shard_00014.npz +3 -0
  32. additional/psmcplus_converged/shards/shard_00015.npz +3 -0
  33. additional/psmcplus_converged/shards/shard_00016.npz +3 -0
  34. additional/psmcplus_converged/shards/shard_00017.npz +3 -0
  35. additional/psmcplus_converged/shards/shard_00018.npz +3 -0
  36. additional/psmcplus_converged/shards/shard_00019.npz +3 -0
  37. additional/psmcplus_converged/shards/shard_00020.npz +3 -0
  38. additional/psmcplus_converged/shards/shard_00021.npz +3 -0
  39. additional/psmcplus_converged/shards/shard_00022.npz +3 -0
  40. additional/psmcplus_converged/shards/shard_00023.npz +3 -0
  41. additional/psmcplus_converged/shards/shard_00024.npz +3 -0
  42. additional/psmcplus_converged/shards/shard_00025.npz +3 -0
  43. additional/psmcplus_converged/shards/shard_00026.npz +3 -0
  44. additional/psmcplus_converged/shards/shard_00027.npz +3 -0
  45. additional/psmcplus_converged/shards/shard_00028.npz +3 -0
  46. additional/psmcplus_converged/shards/shard_00029.npz +3 -0
  47. additional/psmcplus_converged/shards/shard_00030.npz +3 -0
  48. additional/psmcplus_converged/shards/shard_00031.npz +3 -0
  49. additional/psmcplus_converged/shards/shard_00032.npz +3 -0
  50. additional/psmcplus_converged/shards/shard_00033.npz +3 -0
.gitattributes ADDED
@@ -0,0 +1,91 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ *.7z filter=lfs diff=lfs merge=lfs -text
2
+ *.arrow filter=lfs diff=lfs merge=lfs -text
3
+ *.avro filter=lfs diff=lfs merge=lfs -text
4
+ *.bin filter=lfs diff=lfs merge=lfs -text
5
+ *.bz2 filter=lfs diff=lfs merge=lfs -text
6
+ *.ckpt filter=lfs diff=lfs merge=lfs -text
7
+ *.ftz filter=lfs diff=lfs merge=lfs -text
8
+ *.gz filter=lfs diff=lfs merge=lfs -text
9
+ *.h5 filter=lfs diff=lfs merge=lfs -text
10
+ *.joblib filter=lfs diff=lfs merge=lfs -text
11
+ *.lfs.* filter=lfs diff=lfs merge=lfs -text
12
+ *.lz4 filter=lfs diff=lfs merge=lfs -text
13
+ *.mds filter=lfs diff=lfs merge=lfs -text
14
+ *.mlmodel filter=lfs diff=lfs merge=lfs -text
15
+ *.model filter=lfs diff=lfs merge=lfs -text
16
+ *.msgpack filter=lfs diff=lfs merge=lfs -text
17
+ *.npy filter=lfs diff=lfs merge=lfs -text
18
+ *.npz filter=lfs diff=lfs merge=lfs -text
19
+ *.onnx filter=lfs diff=lfs merge=lfs -text
20
+ *.ot filter=lfs diff=lfs merge=lfs -text
21
+ *.parquet filter=lfs diff=lfs merge=lfs -text
22
+ *.pb filter=lfs diff=lfs merge=lfs -text
23
+ *.pickle filter=lfs diff=lfs merge=lfs -text
24
+ *.pkl filter=lfs diff=lfs merge=lfs -text
25
+ *.pt filter=lfs diff=lfs merge=lfs -text
26
+ *.pth filter=lfs diff=lfs merge=lfs -text
27
+ *.rar filter=lfs diff=lfs merge=lfs -text
28
+ *.safetensors filter=lfs diff=lfs merge=lfs -text
29
+ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
30
+ *.tar.* filter=lfs diff=lfs merge=lfs -text
31
+ *.tar filter=lfs diff=lfs merge=lfs -text
32
+ *.tflite filter=lfs diff=lfs merge=lfs -text
33
+ *.tgz filter=lfs diff=lfs merge=lfs -text
34
+ *.wasm filter=lfs diff=lfs merge=lfs -text
35
+ *.xz filter=lfs diff=lfs merge=lfs -text
36
+ *.zip filter=lfs diff=lfs merge=lfs -text
37
+ *.zst filter=lfs diff=lfs merge=lfs -text
38
+ *tfevents* filter=lfs diff=lfs merge=lfs -text
39
+ # Audio files - uncompressed
40
+ *.pcm filter=lfs diff=lfs merge=lfs -text
41
+ *.sam filter=lfs diff=lfs merge=lfs -text
42
+ *.raw filter=lfs diff=lfs merge=lfs -text
43
+ # Audio files - compressed
44
+ *.aac filter=lfs diff=lfs merge=lfs -text
45
+ *.flac filter=lfs diff=lfs merge=lfs -text
46
+ *.mp3 filter=lfs diff=lfs merge=lfs -text
47
+ *.ogg filter=lfs diff=lfs merge=lfs -text
48
+ *.wav filter=lfs diff=lfs merge=lfs -text
49
+ # Image files - uncompressed
50
+ *.bmp filter=lfs diff=lfs merge=lfs -text
51
+ *.gif filter=lfs diff=lfs merge=lfs -text
52
+ *.png filter=lfs diff=lfs merge=lfs -text
53
+ *.tiff filter=lfs diff=lfs merge=lfs -text
54
+ # Image files - compressed
55
+ *.jpg filter=lfs diff=lfs merge=lfs -text
56
+ *.jpeg filter=lfs diff=lfs merge=lfs -text
57
+ *.webp filter=lfs diff=lfs merge=lfs -text
58
+ # Video files - compressed
59
+ *.mp4 filter=lfs diff=lfs merge=lfs -text
60
+ *.webm filter=lfs diff=lfs merge=lfs -text
61
+ splits/cohort/snapshot.json filter=lfs diff=lfs merge=lfs -text
62
+ splits/cohort/architecture_split.jsonl filter=lfs diff=lfs merge=lfs -text
63
+ splits/cohort/sample_identities.jsonl filter=lfs diff=lfs merge=lfs -text
64
+ additional/sample_size_levels/level04/snapshot.json filter=lfs diff=lfs merge=lfs -text
65
+ additional/sample_size_levels/level04/sample_metadata.jsonl filter=lfs diff=lfs merge=lfs -text
66
+ additional/sample_size_levels/level04/architecture_split.jsonl filter=lfs diff=lfs merge=lfs -text
67
+ additional/sample_size_levels/level04/sample_identities.jsonl filter=lfs diff=lfs merge=lfs -text
68
+ additional/sample_size_levels/level08/sample_identities.jsonl filter=lfs diff=lfs merge=lfs -text
69
+ additional/sample_size_levels/level08/architecture_split.jsonl filter=lfs diff=lfs merge=lfs -text
70
+ additional/sample_size_levels/level08/sample_metadata.jsonl filter=lfs diff=lfs merge=lfs -text
71
+ additional/sample_size_levels/level08/snapshot.json filter=lfs diff=lfs merge=lfs -text
72
+ additional/sample_size_levels/level16/sample_identities.jsonl filter=lfs diff=lfs merge=lfs -text
73
+ additional/sample_size_levels/level16/snapshot.json filter=lfs diff=lfs merge=lfs -text
74
+ additional/sample_size_levels/level16/architecture_split.jsonl filter=lfs diff=lfs merge=lfs -text
75
+ additional/sample_size_levels/level16/sample_metadata.jsonl filter=lfs diff=lfs merge=lfs -text
76
+ additional/sample_size_levels/level01/sample_metadata.jsonl filter=lfs diff=lfs merge=lfs -text
77
+ additional/sample_size_levels/level01/sample_identities.jsonl filter=lfs diff=lfs merge=lfs -text
78
+ additional/sample_size_levels/level01/snapshot.json filter=lfs diff=lfs merge=lfs -text
79
+ additional/sample_size_levels/level01/architecture_split.jsonl filter=lfs diff=lfs merge=lfs -text
80
+ additional/sample_size_levels/level02/sample_identities.jsonl filter=lfs diff=lfs merge=lfs -text
81
+ additional/sample_size_levels/level02/architecture_split.jsonl filter=lfs diff=lfs merge=lfs -text
82
+ additional/sample_size_levels/level02/sample_metadata.jsonl filter=lfs diff=lfs merge=lfs -text
83
+ additional/sample_size_levels/level02/snapshot.json filter=lfs diff=lfs merge=lfs -text
84
+ features/level32/architecture_split.jsonl filter=lfs diff=lfs merge=lfs -text
85
+ features/level32/snapshot.json filter=lfs diff=lfs merge=lfs -text
86
+ features/level32/sample_identities.jsonl filter=lfs diff=lfs merge=lfs -text
87
+ features/level32/sample_metadata.jsonl filter=lfs diff=lfs merge=lfs -text
88
+ features/registry/sample_identities.jsonl filter=lfs diff=lfs merge=lfs -text
89
+ features/registry/architecture_split.jsonl filter=lfs diff=lfs merge=lfs -text
90
+ features/registry/snapshot.json filter=lfs diff=lfs merge=lfs -text
91
+ features/registry/raw_index.jsonl filter=lfs diff=lfs merge=lfs -text
README.md ADDED
@@ -0,0 +1,253 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ license: cc-by-4.0
3
+ pretty_name: NeCast simulations
4
+ tags:
5
+ - population-genetics
6
+ - demographic-inference
7
+ - effective-population-size
8
+ - coalescent
9
+ - msprime
10
+ - simulation
11
+ size_categories:
12
+ - 100K<n<1M
13
+ configs:
14
+ - config_name: index
15
+ data_files: index/windows.parquet
16
+ default: true
17
+ ---
18
+
19
+ # NeCast simulations
20
+
21
+ Simulated genotype windows used to train and test NeCast, a neural network that estimates the
22
+ size history of a population from 32 diploid genomes together with recombination and mutation
23
+ maps. There are 109,248 windows. Each is 30 Mb of sequence sampled from 64 diploid individuals,
24
+ with sequencing-like errors already applied, and each comes with its true size history. The
25
+ files the network was trained on are included, as are the code and configuration that made the
26
+ windows.
27
+
28
+ ![What the corpus covers](https://huggingface.co/datasets/Larrivhan/NeCast-simulations/resolve/main/figures/simulations_overview.png)
29
+
30
+ **What the corpus covers.** **a**, Eight training windows drawn at random from each of the
31
+ twelve families of size history, with the number of windows in each family. Each line is a
32
+ window's 64 interval labels, drawn through the interval centres. **b**, Windows by the type of
33
+ map stored with them. Every window carries sequencing-like errors except those with constant maps
34
+ at the baseline rates. **c**, Variant sites per window, false sites included.
35
+
36
+ ## Contents
37
+
38
+ | path | what it holds | size |
39
+ |---|---|---|
40
+ | `windows/000/` to `windows/027/` | the 109,248 windows, four per `.npz` file, with per-window metadata in the `.jsonl.gz` file of the same name | 567 GB |
41
+ | `windows/receipts.jsonl.gz` | the receipt written when each file was generated, with its SHA-256 | small |
42
+ | `index/windows.parquet` | one row per window: where it is stored, its split, how it was simulated | 0.05 GB |
43
+ | `index/histories.parquet` | the epochs of every simulated history, by window | 0.93 GB |
44
+ | `splits/` | the train / development / reserved split, and the windows used to train, validate and test the final network | 0.2 GB |
45
+ | `features/` | what the final network reads, for the 104,996 train and development windows | 15.7 GB |
46
+ | `additional/` | the same inputs for 1, 2, 4, 8 and 16 individuals, and a variant of the PSMC+ posterior | 63.1 GB |
47
+ | `generator/` | the simulator code, the generation plan and the map scripts | small |
48
+ | `tools/necast_windows.py` | a reader that needs only numpy | small |
49
+ | `logs/` | build logs of the feature files | small |
50
+ | `figures/` | the figures on this card | small |
51
+ | `SHA256SUMS` | a checksum for every file except this card | small |
52
+
53
+ The windows are grouped by generation chunk: `windows/NNN/` holds chunks `NNN000` to `NNN999`.
54
+ Window `sim_XXXXXXXX` is member `XXXXXXXX mod 4` of file `fragment_{XXXXXXXX div 4}`. The run
55
+ planned 110,000 windows in 27,500 chunks of four; 188 chunks were not generated, so window
56
+ numbers have gaps. The index lists every window that exists.
57
+
58
+ ## How the windows were simulated
59
+
60
+ - **Sequence and sample.** 30 Mb, 64 diploid individuals (128 haplotypes). msprime 1.4.2 with
61
+ the default coalescent with recombination (the full ancestral recombination graph), a binary
62
+ mutation model, the window's true recombination and mutation maps, and no gene conversion.
63
+ - **Size histories.** Twelve families, named in `generator_recipe`: constant (`constant`),
64
+ exponential (`exponential`), one size change (`size_event`), several changes (`multi_event`),
65
+ bottleneck (`bottleneck`), event on a trend (`event_on_background`), random walk
66
+ (`spectral_walk`), sawtooth (`sawtooth`), zigzag-like (`literature_sawtooth`), founder chain
67
+ (`ooa_chain`), perturbed published human histories (`empirical_human_ne_template`; 191 curves
68
+ inferred by SMC++, phlash, MSMC2 and MSMC-IM), and the 18 single-population models of the
69
+ stdpopsim catalogue (`stdpopsim_single_pop`). Sizes stay between 100 and 1,000,000. The
70
+ realised parameters of every history are in the metadata.
71
+ - **Maps** (`map_type`). A constant map at the baseline rates (`constant_clean`), constant
72
+ rates drawn at random (`constant_random_global`), synthetic heterogeneous maps
73
+ (`synthetic_heterogeneous`), or 30 Mb slices of the deCODE 2019 recombination map and the
74
+ Roulette mutation map taken from the same chromosomal interval (`empirical_slice`).
75
+ - **Errors** (`noise_profile`). `mild_noise` windows have genotype errors, missing calls, false
76
+ variant sites and phase switches within individuals, at rates drawn per window and recorded
77
+ in the metadata (`noise_*` fields). `clean` windows, which are the `constant_clean` ones,
78
+ have none.
79
+ - **Maps stored with a window** are the maps a method is given. Constant maps are stored
80
+ exactly. Synthetic and empirical maps are stored as the true map seen through noise: a
81
+ log-normal factor with mean one on short cells (`observed_cell_bp`), smaller for the mutation
82
+ map, and for synthetic maps some hotspots left out. The noise size is in the metadata
83
+ (`observed_noise_sigma`, and `rec_slice_*` and `mut_slice_*` for empirical slices). The true
84
+ maps are not stored.
85
+ - **Labels.** `target_log10_ne` gives, for each of 64 time intervals spaced evenly in log time
86
+ between 50 and 500,000 generations ago, the average of log10 Ne over the interval (averaged in
87
+ log time) of the simulated history. The file also stores the true number of pairwise
88
+ coalescences and the total branch length in each interval.
89
+
90
+ ## Splits and the windows used by the final network
91
+
92
+ Windows were assigned by a hash of their identifier: 100,000 train, 5,000 development and
93
+ 4,248 reserved. Four train windows have no PSMC+ output and belong to no split (`split = none`
94
+ in the index), leaving 99,996 train windows.
95
+
96
+ The final NeCast network was fitted on 89,996 train windows. Another 500 train windows picked
97
+ the training epoch (`stage = validation`), and 500 development windows were the test set
98
+ (`stage = test`); both sets of 500 sit at evenly spaced quantiles of the number of variant sites.
99
+ `splits/stages.json` lists them by sample ID and by feature row.
100
+
101
+ The 4,248 reserved windows were never used to train, select or score a network. Their PSMC+
102
+ output was computed (it is in `features/psmcplus_store/`), but they were left out of every other
103
+ feature file. Now that they are public, they no longer serve as an untouched test set.
104
+
105
+ ## Reading a window
106
+
107
+ ![One window](https://huggingface.co/datasets/Larrivhan/NeCast-simulations/resolve/main/figures/simulations_window.png)
108
+
109
+ **One window, `sim_00000016`**: a perturbed published human history, slices of the deCODE and
110
+ Roulette maps, and errors. **a**, Diploid genotypes of the 64 individuals at the 133 variant
111
+ sites between 15.00 and 15.10 Mb: 0 pale grey, 1 light purple, 2 purple; missing calls are empty cells.
112
+ **b**, The recombination and mutation maps stored with the window, averaged in 300-kb bins.
113
+ **c**, The simulated history (grey) and its 64 interval labels (black), which are the
114
+ network's targets.
115
+
116
+ ```python
117
+ from huggingface_hub import hf_hub_download
118
+ import sys
119
+
120
+ path = hf_hub_download("Larrivhan/NeCast-simulations", "windows/000/fragment_00000000.npz", repo_type="dataset")
121
+ hf_hub_download("Larrivhan/NeCast-simulations", "windows/000/fragment_00000000.jsonl.gz", repo_type="dataset")
122
+ reader = hf_hub_download("Larrivhan/NeCast-simulations", "tools/necast_windows.py", repo_type="dataset")
123
+ sys.path.insert(0, reader.rsplit("/", 1)[0])
124
+ from necast_windows import Fragment, diploid_genotypes, TIME_EDGES
125
+
126
+ frag = Fragment(path)
127
+ w = frag.window(0)
128
+ w["genotypes"].shape # (n_sites, 128): 0/1, haplotypes 2i and 2i+1 are individual i
129
+ w["missing"].sum() # missing calls (their genotype bit is 0)
130
+ g = diploid_genotypes(w) # (n_sites, 64): 0, 1, 2, or -1 where a call is missing
131
+ w["recombination_map"] # breakpoints (bp) and rates per bp per generation
132
+ w["target_log10_ne"] # 64 labels on the intervals TIME_EDGES
133
+ w["metadata"]["generator_recipe"]
134
+ ```
135
+
136
+ The index is a parquet table, so `pandas.read_parquet("index/windows.parquet")` or the
137
+ `datasets` library will load it. Filter it to pick windows, then read only the files you need.
138
+
139
+ ## File format
140
+
141
+ Each `fragment_XXXXXXXX.npz` holds four windows; ragged arrays are concatenated, and an
142
+ `*_offsets` array of length 5 marks where each window starts.
143
+
144
+ | array | type and shape | meaning |
145
+ |---|---|---|
146
+ | `sample_id` | str (4) | window identifiers |
147
+ | `variant_positions_bp`, `variant_offsets` | uint32, int64 | site positions; window k is `[off[k], off[k+1])` |
148
+ | `genotype_packed` | uint8 (sites, 16) | 128 haplotypes, 8 per byte; haplotype h is bit `h % 8` of byte `h // 8` (`numpy.unpackbits(..., bitorder="little")`) |
149
+ | `missing_flat_idx`, `missing_offsets` | uint32, int64 | missing calls as row-major indices into the window's (sites, 128) matrix; the genotype bit of a missing call is 0 |
150
+ | `obs_rec_pos`, `obs_rec_rate`, `obs_rec_offsets` | float64, float32, int64 | recombination map: breakpoints in bp and the rate (per bp per generation) between them; window k has one rate fewer than breakpoints, so rates for window k start at `sum(len_j - 1 for j < k)` |
151
+ | `obs_mut_pos`, `obs_mut_rate`, `obs_mut_offsets` | the same | mutation map |
152
+ | `target_log10_ne` | float32 (4, 64) | labels |
153
+ | `pair_coalescences_per_bin`, `branch_length_per_bin` | float32 (4, 64) | true pairwise coalescences and branch length per interval |
154
+ | `pair_coalescences_outside` | float64 (4, 2) | pairwise coalescences before the first and after the last interval |
155
+ | `sequence_length`, `n_haplotypes`, `packed_hap_bytes` | int | 30,000,000; 128; 16 |
156
+ | `source_id`, `demography_type_id`, `generator_recipe_id` | int16 (4) | codes; the names are in the metadata |
157
+ | `generator_schema_version`, `missing_storage` | | format version (1) and the missing-call encoding |
158
+
159
+ Variant sites include the false sites added as errors. Positions are sorted; a few windows have
160
+ two sites at the same position.
161
+
162
+ The `.jsonl.gz` file has one JSON object per window with every parameter of its history, maps
163
+ and errors. The index carries the same fields, flattened: nested objects become `noise_*`,
164
+ `rec_slice_*`, `mut_slice_*` and similar columns, and short lists are stored as JSON text. The
165
+ epochs of each history (`demography_breaks` in generations ago, `demography_values` and
166
+ `demography_growth_rates`, as passed to msprime) are in `index/histories.parquet` as numeric
167
+ lists, one row per window.
168
+
169
+ **Inputs and labels.** A method under test should read only the genotypes, the site positions,
170
+ the stored maps, the sequence length and the sample size. Every other field describes how the
171
+ window was made (the history, the errors, the map type, the labels) and is there for selecting
172
+ windows and for scoring.
173
+
174
+ ## Feature files (`features/`)
175
+
176
+ All feature files cover the 104,996 train and development windows in one order: feature row r
177
+ is window `splits/stages.json["feature_sample_ids"][r]`, and the index gives it as
178
+ `feature_row`. NeCast reads 32 of the 64 individuals in a window; which 32 is fixed per window by
179
+ a seeded permutation and stored in `features/level32/unphased_evidence_cache.npz` as
180
+ `ladder_columns`.
181
+
182
+ - `registry/` locates every train and development window in the fragment files
183
+ (`raw_index.jsonl`), with a byte-exact read-back check for each one.
184
+ - `level32/unphased_evidence_cache.npz` holds summary statistics of the 32 individuals:
185
+ the folded site frequency spectrum, projected to 32 haplotypes to absorb missing calls
186
+ (`folded_sfs_counts`); linkage disequilibrium between sites 1 to 64 sites apart, by genetic
187
+ distance (`ld_features`, `ld_pair_counts`, with `ld_bin_edges_morgan` and `ld_lags`);
188
+ lengths of identity-by-state tracts between pairs of individuals in 7 kinds and
189
+ powers-of-two length classes (`ibs_counts`, `ibs_bin_edges_bp`); a Watterson estimate of the
190
+ size level (`nw_log10`), which anchors the network's output; per-window context values
191
+ (`context`); and the labels (`targets`). `features` and `coordinates` hold statistics over
192
+ 32-kb sub-windows that the final network does not read. The network's site encoder reads the
193
+ genotypes of the 32 individuals straight from the window files, found through `registry/`.
194
+ - `psmcplus_posterior/level32.npz` holds PSMC+ posteriors for the same 32 individuals,
195
+ decoded with the window's maps on the 64 intervals. The array is named `sidecar`
196
+ (104,996 × 256): columns 0–63 are the mean over individuals of the posterior share of the
197
+ window in each interval with a flat prior, 64–127 their standard deviation, and 128–255 the
198
+ same after one refit of the prior. `sidecar_present` marks rows with a value.
199
+ - `psmcplus_store/shards/` is the PSMC+ output these posteriors were cut from: every window
200
+ (reserved ones included), four random sets of individuals, and sample sizes of 1, 2, 4, 8, 16
201
+ and 32. Each shard has `sample_id`, `features` (rows, 4 sets, 6 sizes, 256), `flags` (the
202
+ number of individuals scored in each pass), `theta_cl` and `bin_cl` (the diversity θ and the
203
+ bin size in bp the decoder used) and `meta` (mean mutation rate, mean recombination rate,
204
+ number of sites, sequence length, seconds, and four counters). `builder/` has the scripts that made them and
205
+ `logs.tar` their logs.
206
+
207
+ ## Additional files (`additional/`)
208
+
209
+ - `sample_size_levels/` has the summary statistics and PSMC+ posteriors for 1, 2, 4, 8 and 16
210
+ individuals (the first individuals of the same permutation). They were built for an earlier
211
+ design in which the network read a variable number of individuals; the final network reads 32.
212
+ - `psmcplus_converged/` has a PSMC+ posterior whose prior was refitted five times in a row
213
+ instead of once, for 13,500 windows: a 12,500-window training subset spread evenly over
214
+ variant counts, and the 500 validation and 500 test windows. The scripts and checks that made
215
+ it are included.
216
+
217
+ ## Generator (`generator/`)
218
+
219
+ `generator/code/` is the simulator exactly as it ran (MIT licence), and `corpus_plan.json` the
220
+ generation plan: configuration, seeds, and checksums of the maps and templates. The simulator
221
+ shipped third-party data files: the deCODE and Roulette maps, the published human histories and
222
+ the stdpopsim trajectories. They are not copied here. `generator/EXCLUDED_THIRD_PARTY.tsv` lists
223
+ each one with its size, SHA-256 and source. The scripts that build the deCODE map and the
224
+ stdpopsim trajectories are in `generator/code/simulator/assets/`, and `generator/roulette_map/`
225
+ has the script that averaged the published Roulette rates into the 1-kb map used here.
226
+
227
+ ## Checksums
228
+
229
+ `sha256sum -c SHA256SUMS` checks every file. The checksums of the window files also match the
230
+ receipts written when each file was generated (`windows/receipts.jsonl.gz`).
231
+
232
+ ## Paths in provenance files
233
+
234
+ Logs, plans and other provenance files were written on the machines that ran the jobs. Absolute paths in them use
235
+ placeholders: `$WORK` and `$DATA` for the working directories, `$SW` for installed software and `~` for the home
236
+ directory. Checksums recorded inside the files match the released files.
237
+
238
+ ## Licence and sources
239
+
240
+ The files here are released under CC BY 4.0. Please also cite the sources the windows build on:
241
+
242
+ - msprime: Baumdicker et al. (2022), *Genetics* 220:iyab229.
243
+ - deCODE recombination map: Halldorsson et al. (2019), *Science* 363:eaau1043.
244
+ - Roulette mutation rates: Seplyarskiy et al. (2023), *Nature Genetics*.
245
+ - Human size histories used as templates: Terhorst, Kamm and Song (2017), *Nature Genetics*
246
+ 49:303 (SMC++); Terhorst (2025), *Nature Genetics* 57:2570 (phlash); Wang et al. (2020),
247
+ *PLOS Genetics* 16:e1008552 (MSMC-IM).
248
+ - stdpopsim: Adrion et al. (2020), *eLife* 9:e54967.
249
+ - PSMC+: Cousins et al. (2024), *bioRxiv*.
250
+
251
+ ## Citation
252
+
253
+ The NeCast paper is in preparation; its reference will be added here.
SHA256SUMS ADDED
The diff for this file is too large to render. See raw diff
 
additional/psmcplus_converged/RECEIPT.json ADDED
@@ -0,0 +1,166 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "builder_is_bitwise_the_production_builder": {
3
+ "both_vs_the_stored_2026_09_06_artifact": "the same 4.9267e-07 on the refit mean, 2.468e-07 on the plain mean, 1.54413e-06 max over all 128 columns of a block",
4
+ "conclusion": "this builder reproduces the production builder exactly; the residual is a property of the stored artifact against today's environment, not of the reimplementation. The stored sidecar is therefore not bit-reproducible today by its own code either. Cause not identified: PSMCplus/, ladder_spec.py, psmc_exact.py, psmcplus_sidecar.py and the ctdd conda environment all predate 2026-09-06 unchanged, the decode gives the same bits on Intel Gold 6148, Cascadelake, AMD EPYC 7702 and AMD EPYC 9655, and the residual does not cluster by node nor correlate with variant count.",
5
+ "my_iterate_1_mean_vs_its_plain_mean": "BITWISE IDENTICAL",
6
+ "my_iterate_2_mean_vs_its_refit_mean": "BITWISE IDENTICAL",
7
+ "test": "the UNMODIFIED production builder $DATA/DLCoalSim/psmcplus_ladder.py was rerun today on one row (inventory index 2370, sim_00002386, registry row 2271) into a scratch output dir, all 24 (chain, level) pairs, 1,261 s"
8
+ },
9
+ "checks": {
10
+ "amplitude_500_5k_log10ne_sd": {
11
+ "band_bins": [
12
+ 17,
13
+ 32
14
+ ],
15
+ "converged_iterate6_mean_sd": 0.31738618313207767,
16
+ "median_ratio": 1.3284331298074532,
17
+ "stored_refit_iterate2_mean_sd": 0.2628786060618472
18
+ },
19
+ "converged_vs_stored_refit_max_abs_occupancy_diff": {
20
+ "max": 0.08005288243293762,
21
+ "median": 0.01004735566675663
22
+ },
23
+ "diploids_scored": {
24
+ "plain_all_32": false,
25
+ "plain_min": 30,
26
+ "refit_all_32": false,
27
+ "refit_min": 30
28
+ },
29
+ "finite": true,
30
+ "iterates_reached": {
31
+ "all_rows_reached_6": false,
32
+ "histogram": {
33
+ "4": 1,
34
+ "5": 1,
35
+ "6": 13498
36
+ },
37
+ "rows_with_stored_refit_carried_through_flag_minus_1": 0
38
+ },
39
+ "mean_block_sums_to_one_max_abs_error": 3.696311523526674e-08,
40
+ "means_nonnegative": true,
41
+ "plain_block_vs_stored": {
42
+ "bitwise_identical_rows": 5523,
43
+ "max_abs_diff": 1.691281795501709e-06,
44
+ "note": "recorded, then the STORED plain block is copied into the output so the variant differs from production in exactly the 128 refit columns"
45
+ },
46
+ "reproduction_of_stored_iterates_1_and_2": {
47
+ "bitwise_identical_rows": 4928,
48
+ "max": 2.9653310775756836e-06,
49
+ "median": 7.450580596923828e-09,
50
+ "metric": "max |mine - stored| over all 128 columns of the plain block and of the refit block, float32",
51
+ "p99": 4.954636096954346e-07,
52
+ "relative_to_the_change_being_made": "compare with converged_vs_stored_refit_max_abs_occupancy_diff below",
53
+ "rows_over_1e-4": 0,
54
+ "rows_over_1e-5": 0,
55
+ "rows_over_1e-8": 6248
56
+ },
57
+ "rows": 13500,
58
+ "sd_nonnegative": true,
59
+ "tolerance_violations": []
60
+ },
61
+ "files": {
62
+ "dropin/chain0_level32.npz": {
63
+ "bytes": 107621430,
64
+ "note": "production values on every row the build did not cover; converged refit on the built rows; production present flags, so the runner's normalisation moments mix stored and converged rows",
65
+ "present_rows": 104996,
66
+ "present_sha256_bool_as_the_runner_reads_it": "c4e31d9b42a839fef1f9f158fd70ef3079e33fcb6dfc5bb38c43c54ec97e14cf",
67
+ "sha256": "3b44482f739e0da4fc46c702eb22b0c97fccb80325d555f50748222ccbddb63a",
68
+ "sidecar_sha256_float64_as_the_runner_reads_it": "a4c09638f3bac6e84a7ad6b2800606ed29106cd325dead2397ca519b4cafb397"
69
+ },
70
+ "meanfill/chain0_level32.npz": {
71
+ "bytes": 107621430,
72
+ "note": "converged refit on the built rows; every other row set to the built-fit mean of the converged vectors, so the runner's normalisation mean is exactly the built rows' mean and every column's SD is scaled by the same sqrt(n_built_fit/89996)",
73
+ "present_rows": 104996,
74
+ "present_sha256_bool_as_the_runner_reads_it": "c4e31d9b42a839fef1f9f158fd70ef3079e33fcb6dfc5bb38c43c54ec97e14cf",
75
+ "sha256": "ef67fb185db3cc72133d9a88503c14b29ad4ce942bdda7c792c57297db6f64aa",
76
+ "sidecar_sha256_float64_as_the_runner_reads_it": "5ca4354af182bacd44bf81a43a91d6f9ad7af46322e37bc6c3d17ce4a140df42"
77
+ },
78
+ "meanfill_baseline/chain0_level32.npz": {
79
+ "bytes": 107621430,
80
+ "note": "the matched control for meanfill: STORED values on the built rows, every other row set to the stored built-fit mean; identical fill construction, so the two arms differ only in the refit",
81
+ "present_rows": 104996,
82
+ "present_sha256_bool_as_the_runner_reads_it": "c4e31d9b42a839fef1f9f158fd70ef3079e33fcb6dfc5bb38c43c54ec97e14cf",
83
+ "sha256": "1aa9f6b66ce60f682509d0ebed70c82112b8a5f0d1d6d9cc979dbdce5faa36e9",
84
+ "sidecar_sha256_float64_as_the_runner_reads_it": "68afd4fff329c3799ec02be3a510cb6648526375488cb780b4d864dbcc6b07e4"
85
+ }
86
+ },
87
+ "inputs": {
88
+ "fragments": "$DATA/DLCoalSim/prod_30mb_110k_128hap_20260824/samples/.fragments",
89
+ "plan": "$WORK/compshare_archive_20260916/files/runs/fixed32_fit89996_inner500_eval500_d128_e12_seed20260728/PLAN.json",
90
+ "production_builder_copied_verbatim": "$DATA/DLCoalSim/psmcplus_ladder.py",
91
+ "production_run_sidecar_sha256": "a40187ce360e422d3b059b8aa58d8ecf0f3c1ca9f18f95eb69830e0f610f6dec",
92
+ "psmcplus": "$DATA/DLCoalSim/PSMCplus",
93
+ "registry": "$WORK/registry109k",
94
+ "sidecar_module": "$WORK/src_20260903/training/psmcplus_sidecar.py",
95
+ "stored_sidecar": "$WORK/sidecar109k/chain0_level32.npz",
96
+ "stored_sidecar_sha256": "a40187ce360e422d3b059b8aa58d8ecf0f3c1ca9f18f95eb69830e0f610f6dec"
97
+ },
98
+ "iteration": {
99
+ "definition": "lambda_1 = 1 (plain decode); lambda_{k+1,b} = N0 / 10^occ_to_ne(pooled occupancy of iterate k)_b, clipped to [0.05, 50] by the decoder; pooled = mean over the level's scored diploids",
100
+ "iterates_total": 6,
101
+ "layout": {
102
+ "0:64": "iterate 1 pooled mean (unchanged from production)",
103
+ "128:192": "iterate 6 pooled mean",
104
+ "192:256": "iterate 6 population SD",
105
+ "64:128": "iterate 1 population SD (unchanged from production)"
106
+ },
107
+ "stored_production_file_is": "iterates 1 and 2 of the same recursion"
108
+ },
109
+ "patch_npz": {
110
+ "bytes": 36898552,
111
+ "path": "$WORK/sidecar109k_converged_20260916/patch.npz",
112
+ "sha256": "8a469373454b7102b71d5bc9fa221d3be3ad8189036c4aa9687db6a21b7d409f"
113
+ },
114
+ "per_row_checks_csv": {
115
+ "bytes": 1048594,
116
+ "path": "$WORK/sidecar109k_converged_20260916/per_row_checks.csv",
117
+ "sha256": "d37f0c4bb279f2cf309d84031414f43b18402d7ba07fdef39967f75c4a921fe2"
118
+ },
119
+ "rebuild": {
120
+ "assemble": "cd $WORK/bench_h2h_20260915/analysis/final_round/sidecar_variant && ~/micromamba/envs/ctdd/bin/python -u assemble_converged.py",
121
+ "build": "cd $WORK/bench_h2h_20260915/analysis/final_round/sidecar_variant && sbatch build.slurm # array 0-199%184, 1 cpu / 16G / 4 h each, requeues itself; env PSMC_ITERATES=6 PSMC_WARM_START=0 PSMC_ROWS_NPZ=$PWD/pilot_rows_12500.npz PSMC_OUT=$WORK/sidecar109k_converged_20260916/shards",
122
+ "one_row_by_hand": "cd $WORK/bench_h2h_20260915/analysis/final_round/sidecar_variant && PSMC_ROWS_NPZ=$PWD/probe_rows.npz PSMC_ITERATES=6 PSMC_TIME_ONLY=1 PSMC_OUT=/tmp/x ~/micromamba/envs/ctdd/bin/python -u psmcplus_converged.py 0 8",
123
+ "select_rows": "cd $WORK/bench_h2h_20260915/analysis/final_round/sidecar_variant && ~/micromamba/envs/ctdd/bin/python -u select_pilot_rows.py . 12500"
124
+ },
125
+ "row_order": "identical to sidecar109k/chain0_level32.npz: cohort109k sample_id order, split_code != 2, ascending, 104,996 rows; sidecar row i describes cache row i and registry row i",
126
+ "row_set": {
127
+ "candidate_pool_sha256": "d571bd350f9fc0c7ddf91a02a29b9705c99b2ce7272c7c3545c40485e54843d7",
128
+ "one_logical_root": "the registry has a single logical_dataset_root, so the rule reduces to: sort the 89,996 fit rows by (variant_count, canonical_id) and take np.linspace(0, 89995, 12500) positions",
129
+ "pilot_evaluation_rows": 500,
130
+ "pilot_evaluation_sha256": "89b266b21d80790ee1cd0e65315a9e567949e4df3c42eb94aa038e2b311b7c2f",
131
+ "pilot_fit_rows": 12500,
132
+ "pilot_fit_sha256": "c22183c23581f840ebcd0f5f5098c6f707e1a46419a14776183cf7700e4c7e13",
133
+ "pilot_inner_rows": 500,
134
+ "pilot_inner_sha256": "efb80b6c6bb63a378f1645e9c8cd2a296b65f3a97bd9e753744fb3df749a9699",
135
+ "rule": "carrier_raw_runner._select_stage_rows(stage='pilot') -> _balanced_quantiles(reverse[fit], rows, --pilot-fit-rows) on the registry109k rows, candidates = PLAN stage_rows['fit'] of the production run (its --pilot-fit-rows 89996 == len(fit) took the census branch, so that list IS reverse[fit])",
136
+ "rule_copy_verified": "select_pilot_rows.balanced_quantiles / root_key are AST-identical to deploy_20260913_fixed32 carrier_raw_runner._balanced_quantiles / _root_key apart from type annotations and the leading underscore; and the census branch (count == len(candidates)) reproduces the production run's stage_rows_identity.fit sha256 exactly",
137
+ "sealed_rows_in_selection": 0,
138
+ "sealed_rows_read": 0,
139
+ "union_sha256": "05eea0a41793a0bc92d7a181ceb793272276d1b7c099b9dafa338f0b74a790c8"
140
+ },
141
+ "rows_built": 13500,
142
+ "rows_missing": [],
143
+ "rows_missing_count": 0,
144
+ "rows_requested": 13500,
145
+ "runner_notes": {
146
+ "basename_is_load_bearing": "fixed_view.SIDECAR_BASENAME == 'chain0_level32.npz'; the runner refuses any other filename, so each variant lives in its own directory",
147
+ "coverage_floor": "MINIMUM_SIDECAR_COVERAGE = 0.90 of the fit rows; flagging the 77,496 un-rebuilt fit rows absent would be 0.139 and the frozen runner would refuse, which is why meanfill exists",
148
+ "how_the_run_reads_it": "--sidecar-npz /path/to/<variant>/chain0_level32.npz, with --arms raw_plus_all_sidecar",
149
+ "normalisation": "carrier_raw_summary_fusion_runner._load_sidecar centres and scales on fit & present rows, where fit is the FULL 89,996-row architecture-fit split, not the pilot subset",
150
+ "verify_cohort_artifacts_will_flag_this_on_purpose": "check [5] wants chain0_level{1,2,4,8,16,32}.npz and a RECEIPT_chain0.json in one directory, and these variant directories hold only the level-32 file the run reads; check [6] compares every value against the psmcplus_ladder store, and the refit half of the rebuilt rows is meant to differ. Run that script against sidecar109k/, not against these."
151
+ },
152
+ "status": "complete",
153
+ "stored_sidecar_is_the_one_the_production_run_read": true,
154
+ "transfer_to_compshare": {
155
+ "alternative": "ship a whole variant file (108 MB, ~83 s)",
156
+ "destination": "/cloud/cloud-ssd1/dlcoal/ablation_20260916/sidecars/<variant>/chain0_level32.npz -- the path the ablation harness on that box already expects (its README: 'alternative sidecars live here', beside the existing ctrl_same_bytes symlink). Suggested variant directory names: converged_refit6 (from dropin/), and converged_refit6_meanfill / stored_refit2_meanfill for the strict pair. sidecar109k/ is never written.",
157
+ "recommended": "ship patch.npz (36.9 MB, ~28 s) and rebuild the full file on Compshare with apply_patch.py against /cloud/cloud-ssd1/dlcoal/sidecar109k/chain0_level32.npz",
158
+ "relay": "~1.3 MB/s via the local machine (no direct cluster<->Compshare route)",
159
+ "stored_file_on_compshare_is_the_same_bytes": "sha256 a40187ce360e422d3b059b8aa58d8ecf0f3c1ca9f18f95eb69830e0f610f6dec on Compshare, on the cluster, and in the production run's PLAN -- so apply_patch.py's plain-block check passes there (verified by reading, 2026-09-16)"
160
+ },
161
+ "what": "converged-PSMC+ sidecar variant, chain 0 / level 32, for the (a) training ablation",
162
+ "which_variant_to_use": {
163
+ "default": "dropin -- the runner's normalisation moments stay within a percent of the production file's (measured: normalised built rows rms 1.024 against 0.998, per-column SD ratio median 0.995), so the arm differs from the production run essentially only in the refit values of the rows it trains on. Compare it against sidecar109k/chain0_level32.npz.",
164
+ "strict": "meanfill against meanfill_baseline -- an exact A/B: identical fill construction, so the runner's mean is exactly the built-fit mean and every column's SD is scaled by the same sqrt(n_built_fit/89996). Both arms carry that one scalar input gain (2.68x at 12,500 built fit rows), so it cancels between them but they are NOT comparable to the production run."
165
+ }
166
+ }
additional/psmcplus_converged/apply_patch.py ADDED
@@ -0,0 +1,82 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Rebuild a converged-sidecar variant on any host from patch.npz + the production sidecar.
2
+
3
+ The production file is read only. The output is written into a NEW directory and is always
4
+ named chain0_level32.npz, because the frozen runner refuses any other basename
5
+ (training/fixed_view.py: SIDECAR_BASENAME = f"chain{VIEW_CHAIN}_level{VIEW_DIPLOIDS}.npz").
6
+
7
+ Variants (see RECEIPT.json for why meanfill exists):
8
+ dropin production values on every un-rebuilt row, converged refit on the rebuilt ones
9
+ meanfill converged refit on the rebuilt rows; every other row = the rebuilt-fit mean of
10
+ the converged vectors
11
+ meanfill_baseline the matched control: stored values on the rebuilt rows; every other row = the
12
+ rebuilt-fit mean of the stored vectors
13
+
14
+ Usage:
15
+ python apply_patch.py --stored /cloud/cloud-ssd1/dlcoal/sidecar109k/chain0_level32.npz \
16
+ --patch patch.npz \
17
+ --out /cloud/cloud-ssd1/dlcoal/sidecar109k_converged_20260916 \
18
+ --variant dropin --variant meanfill --variant meanfill_baseline
19
+ """
20
+ import argparse, hashlib, json, os
21
+ import numpy as np
22
+
23
+ FEAT = 256
24
+ BASENAME = "chain0_level32.npz"
25
+
26
+
27
+ def sha256_file(path, chunk=1 << 22):
28
+ h = hashlib.sha256()
29
+ with open(path, "rb") as f:
30
+ for block in iter(lambda: f.read(chunk), b""):
31
+ h.update(block)
32
+ return h.hexdigest()
33
+
34
+
35
+ ap = argparse.ArgumentParser()
36
+ ap.add_argument("--stored", required=True)
37
+ ap.add_argument("--patch", required=True)
38
+ ap.add_argument("--out", required=True)
39
+ ap.add_argument("--variant", action="append", default=None,
40
+ choices=["dropin", "meanfill", "meanfill_baseline"])
41
+ A = ap.parse_args()
42
+ variants = A.variant or ["dropin"]
43
+
44
+ store = np.load(A.stored, allow_pickle=False)
45
+ stored = store["sidecar"].astype(np.float32)
46
+ present = store["sidecar_present"]
47
+ patch = np.load(A.patch, allow_pickle=False)
48
+ reg = patch["registry_index"].astype(np.int64)
49
+ feats = patch["features"].astype(np.float32)
50
+ pilot_fit = patch["pilot_fit"].astype(np.int64)
51
+ assert stored.ndim == 2 and stored.shape[1] == FEAT, stored.shape
52
+ assert feats.shape == (len(reg), FEAT)
53
+ assert reg.min() >= 0 and reg.max() < len(stored), "the patch does not fit this cohort"
54
+ assert len(np.unique(reg)) == len(reg)
55
+ # the patch leaves the plain half of every rebuilt row exactly as production had it
56
+ assert np.array_equal(feats[:, 0:128], stored[reg][:, 0:128]), \
57
+ "patch plain block differs from the stored file: wrong production sidecar"
58
+ built_fit = np.asarray(sorted(set(pilot_fit.tolist()) & set(reg.tolist())), dtype=np.int64)
59
+ os.makedirs(A.out, exist_ok=True)
60
+ report = {"stored": A.stored, "stored_sha256": sha256_file(A.stored), "patch": A.patch,
61
+ "patch_sha256": sha256_file(A.patch), "rows": int(len(stored)),
62
+ "rows_patched": int(len(reg)), "built_fit_rows": int(len(built_fit)), "written": {}}
63
+
64
+ for name in variants:
65
+ if name == "dropin":
66
+ values = stored.copy(); values[reg] = feats
67
+ elif name == "meanfill":
68
+ fill = feats[np.isin(reg, built_fit)].mean(axis=0)
69
+ values = np.repeat(fill[None, :], len(stored), axis=0).astype(np.float32); values[reg] = feats
70
+ else:
71
+ fill = stored[built_fit].mean(axis=0)
72
+ values = np.repeat(fill[None, :], len(stored), axis=0).astype(np.float32)
73
+ values[reg] = stored[reg]
74
+ assert np.isfinite(values).all()
75
+ d = os.path.join(A.out, name); os.makedirs(d, exist_ok=True)
76
+ p = os.path.join(d, BASENAME)
77
+ np.savez(p, sidecar=values, sidecar_present=np.asarray(present).astype(np.uint8))
78
+ report["written"][name] = {"path": p, "sha256": sha256_file(p), "bytes": os.path.getsize(p)}
79
+ print("wrote", p)
80
+
81
+ json.dump(report, open(os.path.join(A.out, "APPLY_PATCH.json"), "w"), indent=1, sort_keys=True)
82
+ print(json.dumps(report, indent=1, sort_keys=True))
additional/psmcplus_converged/assemble_converged.py ADDED
@@ -0,0 +1,394 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Assemble the converged-PSMC+ sidecar variant from the per-task shards, with a receipt.
2
+
3
+ Writes, under $WORK/sidecar109k_converged_20260916/ :
4
+
5
+ patch.npz the built rows only: registry_index, sample_id, features(256),
6
+ flags, meta, iterate_means(K,64). ~14 MB, the thing to relay.
7
+ dropin/chain0_level32.npz 104,996 x 256, production values everywhere, converged refit on
8
+ the built rows; sidecar_present copied from production.
9
+ meanfill/chain0_level32.npz converged refit on the built rows; EVERY OTHER ROW set to the
10
+ built-fit mean of the converged vectors.
11
+ meanfill_baseline/chain0_level32.npz
12
+ the matched control for meanfill: the STORED values on the built
13
+ rows, every other row set to the stored built-fit mean.
14
+ RECEIPT.json
15
+
16
+ Why meanfill exists. The frozen runner normalises the sidecar over ALL 89,996 architecture-fit
17
+ rows (carrier_raw_summary_fusion_runner._load_sidecar, fit= the full split), and refuses a file
18
+ whose sidecar_present covers under 90% of them (MINIMUM_SIDECAR_COVERAGE = 0.90), so the honest
19
+ "flag the un-rebuilt rows absent" route is not available without a new deploy. Filling the
20
+ un-rebuilt rows with the built rows' own fit mean is the same imputation the runner itself applies
21
+ to absent rows, expressed in raw values: it makes the normalisation mean EXACTLY the built rows'
22
+ mean, and multiplies every column's SD by the same constant sqrt(n_built_fit / 89,996), i.e. one
23
+ scalar gain on the whole stream -- identical in the variant and in its matched baseline, so the
24
+ A/B stays clean. dropin/ is the simpler file for anyone who prefers production values elsewhere
25
+ and accepts mixed normalisation moments.
26
+
27
+ Usage: python assemble_converged.py [--out DIR]
28
+ """
29
+ import glob, hashlib, json, os, sys
30
+ import numpy as np
31
+
32
+ A = "$WORK"
33
+ OUTROOT = A + "/sidecar109k_converged_20260916"
34
+ SHARDS = OUTROOT + "/shards"
35
+ STORED = A + "/sidecar109k/chain0_level32.npz"
36
+ WORK = A + "/bench_h2h_20260915/analysis/final_round/sidecar_variant"
37
+ ROWS_NPZ = WORK + "/pilot_rows_12500.npz"
38
+ RUN = A + "/compshare_archive_20260916/files/runs/fixed32_fit89996_inner500_eval500_d128_e12_seed20260728"
39
+ FEAT, NB = 256, 64
40
+ BASENAME = "chain0_level32.npz"
41
+
42
+
43
+ def sha256_file(path, chunk=1 << 22):
44
+ h = hashlib.sha256()
45
+ with open(path, "rb") as f:
46
+ for block in iter(lambda: f.read(chunk), b""):
47
+ h.update(block)
48
+ return h.hexdigest()
49
+
50
+
51
+ def array_sha256(value): # training/data.py::_array_sha256
52
+ array = np.ascontiguousarray(value)
53
+ digest = hashlib.sha256()
54
+ digest.update(array.dtype.str.encode("ascii"))
55
+ digest.update(json.dumps(array.shape).encode("ascii"))
56
+ digest.update(memoryview(array).cast("B"))
57
+ return digest.hexdigest()
58
+
59
+
60
+ sys.path.insert(0, "$DATA/DLCoalSim/train-deploy-20260826-carrier-raw-v76-tap-label")
61
+ from simulator.utils import time_grid
62
+ from simulator.config import Config
63
+ edges_gen, _ = time_grid(Config())
64
+ edges_gen = np.asarray(edges_gen, float)
65
+ dt = np.diff(edges_gen)
66
+ assert len(dt) == NB
67
+
68
+
69
+ def occ_to_ne(occ): # psmc_exact.py, verbatim
70
+ f = np.maximum(occ, 1e-12); f = f / f.sum()
71
+ surv = 1.0 - np.concatenate([[0.0], np.cumsum(f)[:-1]])
72
+ eta = f / (dt * np.maximum(surv, 1e-6))
73
+ return np.log10(1.0 / (2.0 * np.maximum(eta, 1e-12)))
74
+
75
+
76
+ RL = np.load(ROWS_NPZ, allow_pickle=False)
77
+ want_reg = RL["registry_index"].astype(np.int64)
78
+ want_sid = np.asarray(RL["sample_id"]).astype(str)
79
+ kind = RL["kind"].astype(np.int8)
80
+ pilot_fit = RL["pilot_fit"].astype(np.int64)
81
+ sid_of_reg = {int(r): s for r, s in zip(want_reg.tolist(), want_sid.tolist())}
82
+
83
+ store = np.load(STORED, allow_pickle=False)
84
+ stored_sidecar = store["sidecar"].astype(np.float32)
85
+ stored_present = store["sidecar_present"]
86
+ NROWS = stored_sidecar.shape[0]
87
+ assert stored_sidecar.shape == (NROWS, FEAT)
88
+
89
+ reg_seen, feats, flags, metas, iters = [], [], [], [], []
90
+ K = None
91
+ for path in sorted(glob.glob(SHARDS + "/shard_*.npz")):
92
+ try:
93
+ z = np.load(path, allow_pickle=False)
94
+ except BaseException as error:
95
+ print(f"skip unreadable shard {path}: {error!r}")
96
+ continue
97
+ if "registry_index" not in z.files or len(z["registry_index"]) == 0:
98
+ continue
99
+ K = int(z["iterates"]) if K is None else K
100
+ assert int(z["iterates"]) == K, (path, "shard built with a different iterate count")
101
+ assert int(z["warm_start"]) == 0, (path, "shard is warm-started; the receipt claims cold")
102
+ reg_seen.extend(z["registry_index"].tolist())
103
+ feats.append(z["features"]); flags.append(z["flags"])
104
+ metas.append(z["meta"]); iters.append(z["iterate_means"])
105
+
106
+ reg_seen = np.asarray(reg_seen, dtype=np.int64)
107
+ order = np.argsort(reg_seen, kind="stable") # cache identity order == ascending registry index
108
+ reg_seen = reg_seen[order]
109
+ feats = np.concatenate(feats, axis=0)[order]
110
+ flags = np.concatenate(flags, axis=0)[order]
111
+ metas = np.concatenate(metas, axis=0)[order]
112
+ iters = np.concatenate(iters, axis=0)[order]
113
+ assert len(np.unique(reg_seen)) == len(reg_seen), "a row was built twice"
114
+ assert set(reg_seen.tolist()).issubset(set(want_reg.tolist())), "a shard holds a row outside the list"
115
+
116
+ built = set(reg_seen.tolist())
117
+ missing = [int(r) for r in want_reg.tolist() if r not in built]
118
+ built_fit = np.asarray(sorted(set(pilot_fit.tolist()) & built), dtype=np.int64)
119
+ print(f"built {len(reg_seen)} of {len(want_reg)} rows ({len(missing)} missing); "
120
+ f"pilot-fit built {len(built_fit)} of {len(pilot_fit)}")
121
+
122
+ # ---------------------------------------------------------------- per-row checks
123
+ max_repro = metas[:, 10]
124
+ plain_scored, refit_scored = flags[:, 0].astype(int), flags[:, 1].astype(int)
125
+ mean_blocks = np.stack([feats[:, 0:64], feats[:, 128:192]], axis=1).astype(np.float64)
126
+ sd_blocks = np.stack([feats[:, 64:128], feats[:, 192:256]], axis=1).astype(np.float64)
127
+ checks = {
128
+ "rows": int(len(reg_seen)),
129
+ "reproduction_of_stored_iterates_1_and_2": {
130
+ "metric": "max |mine - stored| over all 128 columns of the plain block and of the refit block, float32",
131
+ "bitwise_identical_rows": int((max_repro == 0.0).sum()),
132
+ "max": float(max_repro.max()), "median": float(np.median(max_repro)),
133
+ "p99": float(np.percentile(max_repro, 99)),
134
+ "rows_over_1e-8": int((max_repro > 1e-8).sum()),
135
+ "rows_over_1e-5": int((max_repro > 1e-5).sum()),
136
+ "rows_over_1e-4": int((max_repro > 1e-4).sum()),
137
+ "relative_to_the_change_being_made": "compare with converged_vs_stored_refit_max_abs_occupancy_diff below",
138
+ },
139
+ "diploids_scored": {
140
+ "plain_all_32": bool((plain_scored == 32).all()), "refit_all_32": bool((refit_scored == 32).all()),
141
+ "plain_min": int(plain_scored.min()), "refit_min": int(refit_scored.min()),
142
+ },
143
+ "finite": bool(np.isfinite(feats).all()),
144
+ "means_nonnegative": bool((mean_blocks >= 0).all()),
145
+ "sd_nonnegative": bool((sd_blocks >= 0).all()),
146
+ "mean_block_sums_to_one_max_abs_error": float(np.abs(mean_blocks.sum(axis=2) - 1.0).max()),
147
+ "plain_block_vs_stored": {
148
+ "bitwise_identical_rows": int(
149
+ (np.abs(feats[:, 0:128].astype(np.float64)
150
+ - stored_sidecar[reg_seen][:, 0:128].astype(np.float64)).max(axis=1) == 0.0).sum()
151
+ ),
152
+ "max_abs_diff": float(np.abs(feats[:, 0:128].astype(np.float64)
153
+ - stored_sidecar[reg_seen][:, 0:128].astype(np.float64)).max()),
154
+ "note": "recorded, then the STORED plain block is copied into the output so the variant "
155
+ "differs from production in exactly the 128 refit columns",
156
+ },
157
+ }
158
+ # what the extra iterates bought, as log10 Ne amplitude in 500-5,000 generations
159
+ band = np.flatnonzero((edges_gen[:-1] >= 500.0) & (edges_gen[:-1] < 5000.0))
160
+ ne_stored = np.apply_along_axis(occ_to_ne, 1, stored_sidecar[reg_seen][:, 128:192].astype(np.float64))
161
+ ne_conv = np.apply_along_axis(occ_to_ne, 1, feats[:, 128:192].astype(np.float64))
162
+ checks["amplitude_500_5k_log10ne_sd"] = {
163
+ "band_bins": [int(band.min()), int(band.max())],
164
+ "stored_refit_iterate2_mean_sd": float(ne_stored[:, band].std(axis=1).mean()),
165
+ "converged_iterate%d_mean_sd" % K: float(ne_conv[:, band].std(axis=1).mean()),
166
+ "median_ratio": float(np.median(ne_conv[:, band].std(axis=1) / np.maximum(ne_stored[:, band].std(axis=1), 1e-12))),
167
+ }
168
+ # how far each row actually iterated: a row that stopped early leaves trailing zero rows
169
+ reached = np.array([int(np.max(np.flatnonzero(iters[i].any(axis=1))) + 1) for i in range(len(iters))])
170
+ checks["iterates_reached"] = {
171
+ "all_rows_reached_%d" % K: bool((reached == K).all()),
172
+ "histogram": {str(int(v)): int(c) for v, c in zip(*np.unique(reached, return_counts=True))},
173
+ "rows_with_stored_refit_carried_through_flag_minus_1": int((flags[:, 1] == -1).sum()),
174
+ }
175
+ checks["converged_vs_stored_refit_max_abs_occupancy_diff"] = {
176
+ "median": float(np.median(np.abs(feats[:, 128:192] - stored_sidecar[reg_seen][:, 128:192]).max(axis=1))),
177
+ "max": float(np.abs(feats[:, 128:192] - stored_sidecar[reg_seen][:, 128:192]).max()),
178
+ }
179
+ print(json.dumps(checks, indent=1))
180
+ # Tolerance, not bitwise, and RECORDED rather than asserted: this script runs unattended after the
181
+ # array, and a file plus a receipt that says a tolerance was exceeded beats no file at all. The
182
+ # decode is a 10^5-10^6 step forward-backward recursion in compiled kernels, so a rerun can differ
183
+ # in the last places and the drift accumulates along the sequence; what matters is that it stays
184
+ # orders of magnitude below the change being made, which the two numbers here let a reader check.
185
+ violations = []
186
+ if not checks["finite"]:
187
+ violations.append("nonfinite values in the built rows")
188
+ if checks["plain_block_vs_stored"]["max_abs_diff"] >= 1e-4:
189
+ violations.append("plain block differs from production by >= 1e-4")
190
+ if checks["reproduction_of_stored_iterates_1_and_2"]["rows_over_1e-4"]:
191
+ violations.append("%d rows reproduce the stored columns only to worse than 1e-4"
192
+ % checks["reproduction_of_stored_iterates_1_and_2"]["rows_over_1e-4"])
193
+ checks["tolerance_violations"] = violations
194
+ if violations:
195
+ print("WARNING: " + "; ".join(violations))
196
+ assert checks["finite"], "refusing to write nonfinite values"
197
+ # the variant differs from production in exactly the refit half: carry the stored plain half through
198
+ feats[:, 0:128] = stored_sidecar[reg_seen][:, 0:128]
199
+
200
+ os.makedirs(OUTROOT, exist_ok=True)
201
+ np.savez(OUTROOT + "/patch.npz",
202
+ registry_index=reg_seen,
203
+ sample_id=np.asarray([sid_of_reg[int(r)] for r in reg_seen.tolist()]),
204
+ features=feats.astype(np.float32), flags=flags.astype(np.int16), meta=metas,
205
+ # every iterate's POOLED MEAN is kept (so any K <= this one can be re-derived); the
206
+ # population SD is kept only for iterate 1 and for the last iterate each row reached,
207
+ # in features[64:128] and features[192:256]
208
+ iterate_means=iters.astype(np.float32), iterates=np.int32(K),
209
+ pilot_fit=pilot_fit, pilot_inner=RL["pilot_inner"], pilot_evaluation=RL["pilot_evaluation"],
210
+ kind=kind, union_registry_index=want_reg)
211
+
212
+ # A per-row receipt, readable without numpy. meta columns are, in order:
213
+ # mu, r, variant_count, sequence_length, seconds, theta, BIN, N0, j_max, cold_recomb_segments,
214
+ # max_repro, iterate_seconds_total
215
+ with open(OUTROOT + "/per_row_checks.csv", "w") as handle:
216
+ handle.write("registry_index,sample_id,variant_count,theta,bin_bp,j_max,plain_scored,refit_scored,"
217
+ "iterates_reached,max_abs_diff_vs_stored_iterates_1_2,max_abs_diff_converged_vs_stored_refit,"
218
+ "seconds\n")
219
+ conv_delta = np.abs(feats[:, 128:192].astype(np.float64)
220
+ - stored_sidecar[reg_seen][:, 128:192].astype(np.float64)).max(axis=1)
221
+ for i, r in enumerate(reg_seen.tolist()):
222
+ handle.write("%d,%s,%d,%.8g,%d,%d,%d,%d,%d,%.6g,%.6g,%.1f\n" % (
223
+ r, sid_of_reg[int(r)], int(metas[i, 2]), metas[i, 5], int(metas[i, 6]), int(metas[i, 8]),
224
+ int(flags[i, 0]), int(flags[i, 1]), int(reached[i]), max_repro[i], conv_delta[i], metas[i, 4]))
225
+ print("per-row receipt ->", OUTROOT + "/per_row_checks.csv")
226
+
227
+ files = {}
228
+
229
+
230
+ def write_variant(subdir, values, present, note):
231
+ os.makedirs(OUTROOT + "/" + subdir, exist_ok=True)
232
+ path = f"{OUTROOT}/{subdir}/{BASENAME}"
233
+ np.savez(path, sidecar=values.astype(np.float32), sidecar_present=np.asarray(present).astype(np.uint8))
234
+ files[subdir + "/" + BASENAME] = {
235
+ "sha256": sha256_file(path), "bytes": os.path.getsize(path),
236
+ "sidecar_sha256_float64_as_the_runner_reads_it": array_sha256(values.astype(np.float32).astype(np.float64)),
237
+ "present_sha256_bool_as_the_runner_reads_it": array_sha256(np.asarray(present).astype(bool)),
238
+ "present_rows": int(np.count_nonzero(np.asarray(present))), "note": note,
239
+ }
240
+ print(f"wrote {path}")
241
+
242
+
243
+ dropin = stored_sidecar.copy()
244
+ dropin[reg_seen] = feats
245
+ write_variant("dropin", dropin, stored_present,
246
+ "production values on every row the build did not cover; converged refit on the built rows; "
247
+ "production present flags, so the runner's normalisation moments mix stored and converged rows")
248
+
249
+ conv_fit_mean = feats[np.isin(reg_seen, built_fit)].mean(axis=0)
250
+ meanfill = np.repeat(conv_fit_mean[None, :], NROWS, axis=0).astype(np.float32)
251
+ meanfill[reg_seen] = feats
252
+ write_variant("meanfill", meanfill, stored_present,
253
+ "converged refit on the built rows; every other row set to the built-fit mean of the converged "
254
+ "vectors, so the runner's normalisation mean is exactly the built rows' mean and every column's "
255
+ "SD is scaled by the same sqrt(n_built_fit/89996)")
256
+
257
+ stored_fit_mean = stored_sidecar[built_fit].mean(axis=0)
258
+ base = np.repeat(stored_fit_mean[None, :], NROWS, axis=0).astype(np.float32)
259
+ base[reg_seen] = stored_sidecar[reg_seen]
260
+ write_variant("meanfill_baseline", base, stored_present,
261
+ "the matched control for meanfill: STORED values on the built rows, every other row set to the "
262
+ "stored built-fit mean; identical fill construction, so the two arms differ only in the refit")
263
+
264
+ plan = json.load(open(RUN + "/PLAN.json"))
265
+ stored_sha = sha256_file(STORED)
266
+ plan_sidecar_sha = plan["evidence_identity"]["sidecar"]["file_sha256"]
267
+ receipt = {
268
+ "stored_sidecar_is_the_one_the_production_run_read": bool(stored_sha == plan_sidecar_sha),
269
+ "what": "converged-PSMC+ sidecar variant, chain 0 / level 32, for the (a) training ablation",
270
+ "iteration": {
271
+ "definition": "lambda_1 = 1 (plain decode); lambda_{k+1,b} = N0 / 10^occ_to_ne(pooled occupancy of iterate k)_b, "
272
+ "clipped to [0.05, 50] by the decoder; pooled = mean over the level's scored diploids",
273
+ "iterates_total": int(K),
274
+ "stored_production_file_is": "iterates 1 and 2 of the same recursion",
275
+ "layout": {"0:64": "iterate 1 pooled mean (unchanged from production)",
276
+ "64:128": "iterate 1 population SD (unchanged from production)",
277
+ "128:192": "iterate %d pooled mean" % K,
278
+ "192:256": "iterate %d population SD" % K},
279
+ },
280
+ "row_order": "identical to sidecar109k/chain0_level32.npz: cohort109k sample_id order, split_code != 2, "
281
+ "ascending, 104,996 rows; sidecar row i describes cache row i and registry row i",
282
+ "rows_built": int(len(reg_seen)),
283
+ "rows_requested": int(len(want_reg)),
284
+ "rows_missing": missing[:200],
285
+ "rows_missing_count": len(missing),
286
+ "row_set": {
287
+ "rule": "carrier_raw_runner._select_stage_rows(stage='pilot') -> _balanced_quantiles(reverse[fit], rows, "
288
+ "--pilot-fit-rows) on the registry109k rows, candidates = PLAN stage_rows['fit'] of the production "
289
+ "run (its --pilot-fit-rows 89996 == len(fit) took the census branch, so that list IS reverse[fit])",
290
+ "pilot_fit_rows": int(len(pilot_fit)),
291
+ "pilot_fit_sha256": array_sha256(pilot_fit),
292
+ "pilot_inner_rows": int(len(RL["pilot_inner"])), "pilot_inner_sha256": array_sha256(RL["pilot_inner"]),
293
+ "pilot_evaluation_rows": int(len(RL["pilot_evaluation"])),
294
+ "pilot_evaluation_sha256": array_sha256(RL["pilot_evaluation"]),
295
+ "union_sha256": array_sha256(want_reg),
296
+ "candidate_pool_sha256": plan["stage_rows_identity"]["fit"]["sha256"],
297
+ "sealed_rows_read": 0,
298
+ "sealed_rows_in_selection": 0,
299
+ "rule_copy_verified": "select_pilot_rows.balanced_quantiles / root_key are AST-identical to "
300
+ "deploy_20260913_fixed32 carrier_raw_runner._balanced_quantiles / _root_key apart from type "
301
+ "annotations and the leading underscore; and the census branch (count == len(candidates)) "
302
+ "reproduces the production run's stage_rows_identity.fit sha256 exactly",
303
+ "one_logical_root": "the registry has a single logical_dataset_root, so the rule reduces to: sort the "
304
+ "89,996 fit rows by (variant_count, canonical_id) and take np.linspace(0, 89995, 12500) positions",
305
+ },
306
+ "status": "complete" if (not missing and not violations) else "partial_or_flagged",
307
+ "builder_is_bitwise_the_production_builder": {
308
+ "test": "the UNMODIFIED production builder $DATA/DLCoalSim/psmcplus_ladder.py was rerun "
309
+ "today on one row (inventory index 2370, sim_00002386, registry row 2271) into a scratch "
310
+ "output dir, all 24 (chain, level) pairs, 1,261 s",
311
+ "my_iterate_1_mean_vs_its_plain_mean": "BITWISE IDENTICAL",
312
+ "my_iterate_2_mean_vs_its_refit_mean": "BITWISE IDENTICAL",
313
+ "both_vs_the_stored_2026_09_06_artifact": "the same 4.9267e-07 on the refit mean, 2.468e-07 on the "
314
+ "plain mean, 1.54413e-06 max over all 128 columns of a block",
315
+ "conclusion": "this builder reproduces the production builder exactly; the residual is a property of "
316
+ "the stored artifact against today's environment, not of the reimplementation. The stored "
317
+ "sidecar is therefore not bit-reproducible today by its own code either. Cause not "
318
+ "identified: PSMCplus/, ladder_spec.py, psmc_exact.py, psmcplus_sidecar.py and the ctdd conda "
319
+ "environment all predate 2026-09-06 unchanged, the decode gives the same bits on Intel Gold "
320
+ "6148, Cascadelake, AMD EPYC 7702 and AMD EPYC 9655, and the residual does not cluster by "
321
+ "node nor correlate with variant count.",
322
+ },
323
+ "checks": checks,
324
+ "inputs": {
325
+ "stored_sidecar": STORED, "stored_sidecar_sha256": stored_sha,
326
+ "production_run_sidecar_sha256": plan_sidecar_sha,
327
+ "fragments": "$DATA/DLCoalSim/prod_30mb_110k_128hap_20260824/samples/.fragments",
328
+ "psmcplus": "$DATA/DLCoalSim/PSMCplus",
329
+ "sidecar_module": "$WORK/src_20260903/training/psmcplus_sidecar.py",
330
+ "production_builder_copied_verbatim": "$DATA/DLCoalSim/psmcplus_ladder.py",
331
+ "registry": A + "/registry109k",
332
+ "plan": RUN + "/PLAN.json",
333
+ },
334
+ "files": files,
335
+ "patch_npz": {"path": OUTROOT + "/patch.npz", "sha256": sha256_file(OUTROOT + "/patch.npz"),
336
+ "bytes": os.path.getsize(OUTROOT + "/patch.npz")},
337
+ "per_row_checks_csv": {"path": OUTROOT + "/per_row_checks.csv",
338
+ "sha256": sha256_file(OUTROOT + "/per_row_checks.csv"),
339
+ "bytes": os.path.getsize(OUTROOT + "/per_row_checks.csv")},
340
+ "rebuild": {
341
+ "select_rows": "cd %s && ~/micromamba/envs/ctdd/bin/python -u select_pilot_rows.py . 12500" % WORK,
342
+ "build": "cd %s && sbatch build.slurm # array 0-199%%184, 1 cpu / 16G / 4 h each, requeues itself; "
343
+ "env PSMC_ITERATES=6 PSMC_WARM_START=0 PSMC_ROWS_NPZ=$PWD/pilot_rows_12500.npz "
344
+ "PSMC_OUT=%s" % (WORK, SHARDS),
345
+ "assemble": "cd %s && ~/micromamba/envs/ctdd/bin/python -u assemble_converged.py" % WORK,
346
+ "one_row_by_hand": "cd %s && PSMC_ROWS_NPZ=$PWD/probe_rows.npz PSMC_ITERATES=6 PSMC_TIME_ONLY=1 "
347
+ "PSMC_OUT=/tmp/x ~/micromamba/envs/ctdd/bin/python -u "
348
+ "psmcplus_converged.py 0 8" % WORK,
349
+ },
350
+ "transfer_to_compshare": {
351
+ "relay": "~1.3 MB/s via the local machine (no direct cluster<->Compshare route)",
352
+ "recommended": "ship patch.npz (%.1f MB, ~%.0f s) and rebuild the full file on Compshare with "
353
+ "apply_patch.py against /cloud/cloud-ssd1/dlcoal/sidecar109k/chain0_level32.npz"
354
+ % (os.path.getsize(OUTROOT + "/patch.npz") / 1e6,
355
+ os.path.getsize(OUTROOT + "/patch.npz") / 1.3e6),
356
+ "alternative": "ship a whole variant file (%.0f MB, ~%.0f s)"
357
+ % (os.path.getsize(f"{OUTROOT}/dropin/{BASENAME}") / 1e6,
358
+ os.path.getsize(f"{OUTROOT}/dropin/{BASENAME}") / 1.3e6),
359
+ "destination": "/cloud/cloud-ssd1/dlcoal/ablation_20260916/sidecars/<variant>/chain0_level32.npz -- the "
360
+ "path the ablation harness on that box already expects (its README: 'alternative sidecars "
361
+ "live here', beside the existing ctrl_same_bytes symlink). Suggested variant directory "
362
+ "names: converged_refit6 (from dropin/), and converged_refit6_meanfill / "
363
+ "stored_refit2_meanfill for the strict pair. sidecar109k/ is never written.",
364
+ "stored_file_on_compshare_is_the_same_bytes": "sha256 a40187ce360e422d3b059b8aa58d8ecf0f3c1ca9f18f95eb69830e"
365
+ "0f610f6dec on Compshare, on the cluster, and in the production run's PLAN -- so apply_patch.py's "
366
+ "plain-block check passes there (verified by reading, 2026-09-16)",
367
+ },
368
+ "which_variant_to_use": {
369
+ "default": "dropin -- the runner's normalisation moments stay within a percent of the production "
370
+ "file's (measured: normalised built rows rms 1.024 against 0.998, per-column SD ratio "
371
+ "median 0.995), so the arm differs from the production run essentially only in the refit "
372
+ "values of the rows it trains on. Compare it against sidecar109k/chain0_level32.npz.",
373
+ "strict": "meanfill against meanfill_baseline -- an exact A/B: identical fill construction, so the "
374
+ "runner's mean is exactly the built-fit mean and every column's SD is scaled by the same "
375
+ "sqrt(n_built_fit/89996). Both arms carry that one scalar input gain (2.68x at 12,500 "
376
+ "built fit rows), so it cancels between them but they are NOT comparable to the "
377
+ "production run.",
378
+ },
379
+ "runner_notes": {
380
+ "basename_is_load_bearing": "fixed_view.SIDECAR_BASENAME == 'chain0_level32.npz'; the runner refuses any "
381
+ "other filename, so each variant lives in its own directory",
382
+ "normalisation": "carrier_raw_summary_fusion_runner._load_sidecar centres and scales on fit & present rows, "
383
+ "where fit is the FULL 89,996-row architecture-fit split, not the pilot subset",
384
+ "coverage_floor": "MINIMUM_SIDECAR_COVERAGE = 0.90 of the fit rows; flagging the 77,496 un-rebuilt fit rows "
385
+ "absent would be 0.139 and the frozen runner would refuse, which is why meanfill exists",
386
+ "verify_cohort_artifacts_will_flag_this_on_purpose": "check [5] wants chain0_level{1,2,4,8,16,32}.npz and a "
387
+ "RECEIPT_chain0.json in one directory, and these variant directories hold only the level-32 file the "
388
+ "run reads; check [6] compares every value against the psmcplus_ladder store, and the refit half of the "
389
+ "rebuilt rows is meant to differ. Run that script against sidecar109k/, not against these.",
390
+ "how_the_run_reads_it": "--sidecar-npz /path/to/<variant>/chain0_level32.npz, with --arms raw_plus_all_sidecar",
391
+ },
392
+ }
393
+ json.dump(receipt, open(OUTROOT + "/RECEIPT.json", "w"), indent=1, sort_keys=True)
394
+ print("receipt ->", OUTROOT + "/RECEIPT.json")
additional/psmcplus_converged/build.slurm ADDED
@@ -0,0 +1,39 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/bin/bash
2
+ # Converged-PSMC+ sidecar (chain 0, level 32) over the 13,500 pilot rows.
3
+ # The row -> task deal lives in psmcplus_converged.py:my_rows and is a SNAKE over descending
4
+ # variant_count, so it is a pure function of (task, NTASK). NTASK is FIXED at 200.
5
+ # Each task rewrites its shard after EVERY row, skips rows it already holds on restart, stops
6
+ # starting new rows before the wall (PSMC_BUDGET_S) and then requeues itself. The requeue is
7
+ # guarded three ways: python exit 0, the remaining-row count must have strictly decreased, and
8
+ # SLURM_RESTART_COUNT under 8.
9
+ #SBATCH --job-name=sc_conv
10
+ #SBATCH --array=0-199%184
11
+ #SBATCH --time=04:00:00
12
+ #SBATCH --cpus-per-task=1
13
+ #SBATCH --mem=16G
14
+ #SBATCH --requeue
15
+ #SBATCH --open-mode=append
16
+ #SBATCH --output=$WORK/bench_h2h_20260915/analysis/final_round/sidecar_variant/logs/conv-%A_%a.out
17
+ #SBATCH --error=$WORK/bench_h2h_20260915/analysis/final_round/sidecar_variant/logs/conv-%A_%a.err
18
+ export OMP_NUM_THREADS=1 MKL_NUM_THREADS=1 NUMBA_NUM_THREADS=1 OPENBLAS_NUM_THREADS=1
19
+ D=$WORK/bench_h2h_20260915/analysis/final_round/sidecar_variant
20
+ export PSMC_ROWS_NPZ=$D/pilot_rows_12500.npz
21
+ export PSMC_OUT=$WORK/sidecar109k_converged_20260916/shards
22
+ export PSMC_ITERATES=6
23
+ export PSMC_WARM_START=0
24
+ export PSMC_BUDGET_S=13200 # stop starting rows ~20 min before the 4 h wall
25
+ NTASK=200
26
+ PY=~/micromamba/envs/ctdd/bin/python
27
+ mkdir -p "$PSMC_OUT" "$D/logs"
28
+ cd $D
29
+
30
+ int_or_zero() { case "$1" in ''|*[!0-9]*) echo 0 ;; *) echo "$1" ;; esac; }
31
+ BEFORE=$(int_or_zero "$($PY psmcplus_converged.py $SLURM_ARRAY_TASK_ID $NTASK --remaining 2>/dev/null | tail -1)")
32
+ $PY -u psmcplus_converged.py $SLURM_ARRAY_TASK_ID $NTASK
33
+ RC=$?
34
+ AFTER=$(int_or_zero "$($PY psmcplus_converged.py $SLURM_ARRAY_TASK_ID $NTASK --remaining 2>/dev/null | tail -1)")
35
+ echo "task $SLURM_ARRAY_TASK_ID: rc=$RC remaining $BEFORE -> $AFTER restart=${SLURM_RESTART_COUNT:-0}"
36
+ if [ "$RC" -eq 0 ] && [ "$AFTER" -gt 0 ] && [ "$AFTER" -lt "$BEFORE" ] && [ "${SLURM_RESTART_COUNT:-0}" -lt 8 ]; then
37
+ scontrol requeue "$SLURM_JOB_ID"
38
+ fi
39
+ exit $RC
additional/psmcplus_converged/dropin/chain0_level32.npz ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:3b44482f739e0da4fc46c702eb22b0c97fccb80325d555f50748222ccbddb63a
3
+ size 107621430
additional/psmcplus_converged/meanfill/chain0_level32.npz ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:ef67fb185db3cc72133d9a88503c14b29ad4ce942bdda7c792c57297db6f64aa
3
+ size 107621430
additional/psmcplus_converged/meanfill_baseline/chain0_level32.npz ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:1aa9f6b66ce60f682509d0ebed70c82112b8a5f0d1d6d9cc979dbdce5faa36e9
3
+ size 107621430
additional/psmcplus_converged/patch.npz ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:8a469373454b7102b71d5bc9fa221d3be3ad8189036c4aa9687db6a21b7d409f
3
+ size 36898552
additional/psmcplus_converged/per_row_checks.csv ADDED
The diff for this file is too large to render. See raw diff
 
additional/psmcplus_converged/pilot_rows_12500.json ADDED
@@ -0,0 +1,25 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "candidate_pool_rows": 89996,
3
+ "candidate_pool_sha256": "d571bd350f9fc0c7ddf91a02a29b9705c99b2ce7272c7c3545c40485e54843d7",
4
+ "pilot_evaluation_rows": 500,
5
+ "pilot_evaluation_sha256": "89b266b21d80790ee1cd0e65315a9e567949e4df3c42eb94aa038e2b311b7c2f",
6
+ "pilot_fit_rows": 12500,
7
+ "pilot_fit_sha256": "c22183c23581f840ebcd0f5f5098c6f707e1a46419a14776183cf7700e4c7e13",
8
+ "pilot_inner_rows": 500,
9
+ "pilot_inner_sha256": "efb80b6c6bb63a378f1645e9c8cd2a296b65f3a97bd9e753744fb3df749a9699",
10
+ "plan": "$WORK/compshare_archive_20260916/files/runs/fixed32_fit89996_inner500_eval500_d128_e12_seed20260728/PLAN.json",
11
+ "registry_dir": "$WORK/registry109k",
12
+ "registry_rows": 104996,
13
+ "roots": [
14
+ "$DATA/DLCoalSim/prod_30mb_110k_128hap_20260824"
15
+ ],
16
+ "union_rows": 13500,
17
+ "union_sha256": "05eea0a41793a0bc92d7a181ceb793272276d1b7c099b9dafa338f0b74a790c8",
18
+ "variant_count": {
19
+ "max": 12309022,
20
+ "mean": 458194.39762962965,
21
+ "median": 84318.0,
22
+ "min": 667,
23
+ "sum": 6185624368
24
+ }
25
+ }
additional/psmcplus_converged/pilot_rows_12500.npz ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:936c345a349f5696e836e8bc9e5fce08159207d9eedf5c1dc96e34cc2d8d0e57
3
+ size 1312046
additional/psmcplus_converged/psmcplus_converged.py ADDED
@@ -0,0 +1,459 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Converged-PSMC+ sidecar variant: the stored refit, iterated, for chain 0 / level 32 only.
2
+
3
+ The stored production sidecar (sidecar109k/chain0_level32.npz) is
4
+
5
+ [ 0: 64] pooled mean over the level's scored diploids of the PLAIN decode (lambda = 1)
6
+ [ 64:128] population SD of that decode
7
+ [128:192] pooled mean after ONE prior refit (lambda_b = N0 / Ne_b of the plain pooled curve)
8
+ [192:256] population SD of that refit
9
+
10
+ i.e. iterates 1 and 2 of a fixed-point iteration that has not converged. This driver runs the
11
+ SAME iteration for K iterates and writes iterate K into the second half, leaving the first half
12
+ (the plain decode) untouched, so a training ablation against the stored file changes exactly one
13
+ thing: how far the refit was iterated.
14
+
15
+ Everything that touches PSMC+ is copied VERBATIM from the production builder
16
+ $DATA/DLCoalSim/psmcplus_ladder.py (install_grid, map_slices, segments, write_bed,
17
+ binned_map, seq_parts, make_seq_info, make_shared, decode, the mhs construction, the level-local
18
+ theta / N / rho / BIN, the (1.0, 9.5) units guard) and occ_to_ne comes from psmc_exact.py's head
19
+ through the same exec-the-head trick, so iterate 1 and iterate 2 reproduce the stored columns.
20
+
21
+ Two modes:
22
+ cold (PSMC_WARM_START=0, default) all K iterates decoded here; iterates 1 and 2 are compared
23
+ against the stored file per row and the max abs difference is recorded.
24
+ warm (PSMC_WARM_START=1) iterates 1 and 2 are READ from the stored file (float32) and
25
+ only iterates 3..K are decoded. Saves 2 of K decode passes. The only difference from cold
26
+ is that lambda for iterate 3 is built from the float32 stored pooled mean instead of the
27
+ float64 one; the induced relative change in lambda is ~1e-7.
28
+
29
+ Never opens a sealed selection row: the row list is built by select_pilot_rows.py from the
30
+ registry, which excludes all 4,248 sealed rows, and every sample_id is re-checked against the
31
+ cohort split here before any fragment is touched.
32
+
33
+ Usage: python psmcplus_converged.py TASK NTASK
34
+ Env: PSMC_ROWS_NPZ (row list), PSMC_OUT, PSMC_ITERATES (default 6), PSMC_WARM_START,
35
+ PSMC_BUDGET_S, PSMC_MAX_ROWS, PSMC_STORED (stored sidecar npz), PSMC_TIME_ONLY
36
+ """
37
+ import sys, os, glob, time, tempfile, io, contextlib, json
38
+ import numpy as np
39
+ import pandas as pd
40
+
41
+ sys.path.insert(0, '$DATA/DLCoalSim/PSMCplus')
42
+ sys.path.insert(0, '$DATA/DLCoalSim/train-deploy-20260826-carrier-raw-v76-tap-label')
43
+ sys.path.insert(0, '$DATA/DLCoalSim/ladder')
44
+ sys.path.insert(0, '$WORK/src_20260903')
45
+
46
+ task, ntask = int(sys.argv[1]), int(sys.argv[2])
47
+ # occ_to_ne (and the dt it closes over) come from psmc_exact.py's head, verbatim, as in psmcplus_ladder.py
48
+ _src = open('$DATA/DLCoalSim/psmc_exact.py').read(); _head = _src.split('rows_done = 0')[0]
49
+ _argv = sys.argv; sys.argv = ['x', '0', '1', '1', '/tmp']; exec(compile(_head, 'psmc_exact_head', 'exec')); sys.argv = _argv
50
+ task, ntask = int(_argv[1]), int(_argv[2])
51
+ from simulator.utils import time_grid
52
+ from simulator.config import Config
53
+ edges_gen, _ = time_grid(Config()); edges_gen = np.asarray(edges_gen, float); NB = len(edges_gen) - 1
54
+ assert NB == 64, ('expected 64 bins, got', NB)
55
+ assert edges_gen[0] > 0 and np.all(np.diff(edges_gen) > 0), 'edges must be positive and increasing'
56
+ DP = NB + 1
57
+
58
+ from ladder_spec import chain_columns
59
+ os.environ.setdefault('PSMCPLUS_ROOT', '$DATA/DLCoalSim/PSMCplus')
60
+ import importlib.util as _ilu
61
+ _spec = _ilu.spec_from_file_location(
62
+ 'dlcoal_psmcplus_sidecar',
63
+ '$WORK/src_20260903/training/psmcplus_sidecar.py')
64
+ _side = _ilu.module_from_spec(_spec)
65
+ sys.modules[_spec.name] = _side
66
+ _spec.loader.exec_module(_side)
67
+ Emissions, _FORWARD, _BACKWARD = _side.Emissions, _side._FORWARD, _side._BACKWARD
68
+
69
+ import transition_matrix as TM, utils as U, BaumWelch as BWmod
70
+ from utils import (get_het_mask_indices, get_binned_data, get_B_sequence, write_emission_probs,
71
+ write_emission_masked_probs, write_Q_array_withR)
72
+ from BaumWelch import BaumWelch
73
+
74
+ CHAIN, LEVEL, FEAT = 0, 32, 256
75
+ GUARD_LO, GUARD_HI = 1.0, 9.5
76
+ N_HAP, N_DIP = 128, 64
77
+ FRAG_DIR = '$DATA/DLCoalSim/prod_30mb_110k_128hap_20260824/samples/.fragments'
78
+ ROWS_NPZ = os.environ['PSMC_ROWS_NPZ']
79
+ STORED = os.environ.get('PSMC_STORED', '$WORK/sidecar109k/chain0_level32.npz')
80
+ ITERATES = int(os.environ.get('PSMC_ITERATES', '6'))
81
+ WARM = os.environ.get('PSMC_WARM_START', '0') == '1'
82
+ TIME_ONLY = os.environ.get('PSMC_TIME_ONLY', '0') == '1'
83
+ OUT = os.environ.get('PSMC_OUT', '$WORK/sidecar109k_converged_20260916/shards')
84
+ os.makedirs(OUT, exist_ok=True)
85
+ SHARD = '%s/shard_%05d.npz' % (OUT, task)
86
+ assert ITERATES >= 2
87
+
88
+
89
+ def install_grid(edges_coal):
90
+ e = np.concatenate([[0.0], np.asarray(edges_coal, float)])
91
+ def ti(D, spread_1, spread_2, final_T_factor=None): return e.copy()
92
+ TM.time_intervals = ti; U.time_intervals = ti; BWmod.time_intervals = ti
93
+ return e
94
+
95
+
96
+ def map_slices(z, k):
97
+ if 'obs_mut_pos_offsets' in z.files:
98
+ mpo, mro = z['obs_mut_pos_offsets'], z['obs_mut_rate_offsets']; rpo, rro = z['obs_rec_pos_offsets'], z['obs_rec_rate_offsets']
99
+ mp = z['obs_mut_pos'][int(mpo[k]):int(mpo[k+1])]; mrt = z['obs_mut_rate'][int(mro[k]):int(mro[k+1])]
100
+ rp = z['obs_rec_pos'][int(rpo[k]):int(rpo[k+1])]; rrt = z['obs_rec_rate'][int(rro[k]):int(rro[k+1])]
101
+ else:
102
+ mo, ro = z['obs_mut_offsets'], z['obs_rec_offsets']
103
+ mp = z['obs_mut_pos'][int(mo[k]):int(mo[k+1])]; mrt = z['obs_mut_rate'][int(mo[k])-k:int(mo[k+1])-(k+1)]
104
+ rp = z['obs_rec_pos'][int(ro[k]):int(ro[k+1])]; rrt = z['obs_rec_rate'][int(ro[k])-k:int(ro[k+1])-(k+1)]
105
+ return mp, mrt, rp, rrt
106
+
107
+
108
+ def segments(pos, rate, L):
109
+ pos = np.asarray(pos, float); rate = np.asarray(rate, float); assert len(pos) == len(rate) + 1
110
+ starts = pos[:-1].copy(); ends = pos[1:].copy(); r = rate.copy()
111
+ if starts[0] > 0: starts = np.concatenate([[0.0], starts]); ends = np.concatenate([[starts[1]], ends]); r = np.concatenate([[r[0]], r])
112
+ keep = starts < L; starts, ends, r = starts[keep], np.minimum(ends[keep], L), r[keep]
113
+ if ends[-1] < L: starts = np.concatenate([starts, [ends[-1]]]); ends = np.concatenate([ends, [L]]); r = np.concatenate([r, [r[-1]]])
114
+ e = np.rint(ends).astype(np.int64); e[-1] = int(L); s = np.concatenate([[0], e[:-1]])
115
+ ok = e > s; s, e, r = s[ok], e[ok], r[ok]
116
+ mean = float((r * (e - s)).sum() / (e - s).sum())
117
+ return s, e, r, mean
118
+
119
+
120
+ def write_bed(path, s, e, rel, fmt, chrom='1'):
121
+ with open(path, 'w') as f:
122
+ for a, b, v in zip(s, e, rel): f.write(('%s\t%d\t%d\t' + fmt + '\n') % (chrom, a, b, v))
123
+
124
+
125
+ def binned_map(bed, L, is_rec, BIN):
126
+ B = get_B_sequence(bed, int(L), BIN, ztype='R' if is_rec else 'B')
127
+ Bb = B[:len(B) - len(B) % BIN].reshape(-1, BIN).mean(1)
128
+ if is_rec: Bb = np.floor(Bb * 100) / 100.0; Bb[Bb == 0] = 1e-5
129
+ vals = np.unique(Bb); idx = np.searchsorted(vals, Bb).astype(int)
130
+ return idx, vals
131
+
132
+
133
+ def seq_parts(mhs, BIN):
134
+ hets_sequence, masks_sequence, seq_length, hets, masks = get_het_mask_indices(mhs, BIN)
135
+ het_data = get_binned_data(hets, BIN); mask_data = get_binned_data(masks, BIN)
136
+ j_max = int(np.max(het_data[1, :]))
137
+ return (het_data, mask_data, j_max, int(seq_length), len(hets), len(masks))
138
+
139
+
140
+ def make_seq_info(parts, Bidx, Bvals, Ridx, Rvals, BIN):
141
+ het_data, mask_data, j_max, seq_length, n_hets, n_masks = parts
142
+ nb = int(seq_length / BIN)
143
+ bi = Bidx[:nb]; ri = Ridx[:nb]
144
+ if len(bi) < nb: bi = np.concatenate([bi, np.full(nb - len(bi), bi[-1] if len(bi) else 0)])
145
+ if len(ri) < nb: ri = np.concatenate([ri, np.full(nb - len(ri), ri[-1] if len(ri) else 0)])
146
+ return [het_data, mask_data, j_max, seq_length, n_hets, n_masks, bi, Bvals.copy(), ri, Rvals.copy()]
147
+
148
+
149
+ def make_shared(theta, rho, edges_full, lam, Rvals, BIN, j_max):
150
+ E = write_emission_probs(DP, BIN, theta, j_max, edges_full, midpoint_end=True)
151
+ Em = write_emission_masked_probs(DP, BIN, theta, j_max, edges_full, midpoint_end=True)
152
+ lam_vals = np.ones(DP) if lam is None else np.clip(np.asarray(lam, float), 0.05, 50.0)
153
+ assert lam_vals.shape == (DP,)
154
+ buf = io.StringIO()
155
+ try:
156
+ with contextlib.redirect_stdout(buf):
157
+ bw = BaumWelch(sequences_info=[None], D=DP, E=E, E_masked=Em, lambda_A_values=lam_vals,
158
+ lambda_B_values=None, gamma_fg=None, lambda_A_segs=[[DP, 1]], lambda_B_segs=None,
159
+ rho=rho * BIN, theta=theta, T_S=None, T_E=None, T_array=edges_full,
160
+ bin_size=BIN, j_max=j_max, cores=1, estimate_rho=False,
161
+ midpoint_end=True, output_path=None)
162
+ tm = TM.Transition_Matrix(D=DP, midpoint_transitions=False)
163
+ tm.write_tm(lambda_A=bw.lambda_A_current, lambda_B=None, T_S_index=None, T_E_index=None,
164
+ gamma=None, check=False, rho=bw.rho, exponential=True)
165
+ Qarr = np.ascontiguousarray(
166
+ write_Q_array_withR(tm.Q, np.asarray(Rvals, float), bw.rho, DP, 0.1, 50,
167
+ bw.lambda_A_current, False))
168
+ except BaseException as e:
169
+ raise RuntimeError('PSMC+ setup failed: %r | %s' % (e, buf.getvalue().strip()[-300:]))
170
+ return bw, Qarr
171
+
172
+
173
+ def decode(parts, shared, theta, Bidx, Bvals, Ridx, Rvals, BIN):
174
+ bw, Qarr = shared
175
+ bw.sequences_info = [make_seq_info(parts, Bidx, Bvals, Ridx, Rvals, BIN)]
176
+ buf = io.StringIO()
177
+ with contextlib.redirect_stdout(buf):
178
+ sequence, Bs, Bv, Rs, Rv = bw.sequence_fcn(0)
179
+ emissions = Emissions.tabulate(n_states=DP, bin_bp=BIN, theta=theta,
180
+ midpoints=bw.midpoints, map_values=Bv, sequence=sequence)
181
+ rank = emissions.rank(sequence)
182
+ Bs = np.asarray(Bs, dtype=np.int64); Rs = np.asarray(Rs, dtype=np.int64)
183
+ fwd, scales = _FORWARD(emissions.table, Qarr, Bs, Rs, rank, np.ascontiguousarray(bw.init_dist))
184
+ bwd = _BACKWARD(emissions.table, Qarr, Bs, Rs, rank, np.ascontiguousarray(scales))
185
+ post = np.maximum(fwd * bwd, 0.0); post = post / np.maximum(post.sum(0, keepdims=True), 1e-300)
186
+ occ = post.mean(1)[1:]; occ = occ / max(occ.sum(), 1e-300)
187
+ with np.errstate(divide='ignore', invalid='ignore'):
188
+ ll = float(np.sum(np.log(scales)))
189
+ return occ, ll
190
+
191
+
192
+ # ------------------------------------------------------------------ rows
193
+ RL = np.load(ROWS_NPZ, allow_pickle=False)
194
+ R_SID = np.asarray(RL['sample_id']).astype(str)
195
+ R_FRAG, R_ROW, R_VC = RL['fragment'].astype(np.int64), RL['row'].astype(np.int64), RL['variant_count'].astype(np.int64)
196
+ R_REG = RL['registry_index'].astype(np.int64)
197
+ NSEL = len(R_SID)
198
+
199
+ # hard gate: no sealed row may be in this list, checked here and not only upstream
200
+ _split = np.load('$WORK/cohort109k/cohort109k_split.npz', allow_pickle=False)
201
+ _sealed = set(np.asarray(_split['sample_id'])[np.asarray(_split['split_code']) == 2].astype(str).tolist())
202
+ assert not (set(R_SID.tolist()) & _sealed), 'a sealed selection row is in the row list'
203
+ del _split, _sealed
204
+
205
+ STORE = np.load(STORED, allow_pickle=False)
206
+ STORE_SIDECAR = STORE['sidecar']
207
+ assert STORE_SIDECAR.shape[1] == FEAT
208
+
209
+
210
+ def my_rows(task, ntask):
211
+ """Snake deal over descending variant_count -- the production builder's cost balance."""
212
+ order = np.argsort(-R_VC, kind='stable')
213
+ p = np.arange(NSEL)
214
+ slot = np.where((p // ntask) % 2 == 0, p % ntask, ntask - 1 - (p % ntask))
215
+ return np.sort(order[slot == task])
216
+
217
+
218
+ if len(sys.argv) > 3 and sys.argv[3] == '--remaining':
219
+ done = set()
220
+ if os.path.exists(SHARD):
221
+ try:
222
+ zz = np.load(SHARD, allow_pickle=False); done = set(zz['registry_index'].tolist())
223
+ except BaseException:
224
+ done = set()
225
+ print(sum(1 for i in my_rows(task, ntask) if int(R_REG[i]) not in done)); sys.exit(0)
226
+
227
+
228
+ # ------------------------------------------------------------------ resume
229
+ O_reg, O_sid, O_frag, O_row = [], [], [], []
230
+ O_feat, O_flag, O_meta, O_iter = [], [], [], []
231
+ have = set()
232
+ if os.path.exists(SHARD):
233
+ try:
234
+ z0 = np.load(SHARD, allow_pickle=False)
235
+ O_reg = z0['registry_index'].tolist(); O_sid = z0['sample_id'].astype(str).tolist()
236
+ O_frag = z0['fragment'].tolist(); O_row = z0['row'].tolist()
237
+ O_feat = list(z0['features']); O_flag = list(z0['flags'])
238
+ O_meta = list(z0['meta']); O_iter = list(z0['iterate_means'])
239
+ have = set(O_reg)
240
+ print('task %d: resuming with %d rows' % (task, len(O_reg)), flush=True)
241
+ except BaseException as e:
242
+ print('task %d: could not resume (%r); starting fresh' % (task, e), flush=True)
243
+ O_reg, O_sid, O_frag, O_row, O_feat, O_flag, O_meta, O_iter, have = [], [], [], [], [], [], [], [], set()
244
+
245
+ META_COLS = 12
246
+
247
+
248
+ def save():
249
+ np.savez(SHARD + '.tmp.npz',
250
+ registry_index=np.array(O_reg, dtype=np.int64),
251
+ sample_id=np.array(O_sid), fragment=np.array(O_frag, dtype=np.int32),
252
+ row=np.array(O_row, dtype=np.int8),
253
+ features=np.array(O_feat, dtype=np.float32).reshape(-1, FEAT),
254
+ flags=np.array(O_flag, dtype=np.int16).reshape(-1, 2),
255
+ meta=np.array(O_meta, dtype=np.float64).reshape(-1, META_COLS),
256
+ iterate_means=np.array(O_iter, dtype=np.float32).reshape(-1, ITERATES, NB),
257
+ iterates=np.int32(ITERATES), warm_start=np.int32(1 if WARM else 0))
258
+ os.replace(SHARD + '.tmp.npz', SHARD)
259
+
260
+
261
+ _cache = {}
262
+ def frag(p):
263
+ if p not in _cache: _cache.clear(); _cache[p] = np.load(p, allow_pickle=False)
264
+ return _cache[p]
265
+
266
+
267
+ FR = sorted(glob.glob(FRAG_DIR + '/fragment_*.npz'))
268
+ t0 = time.time()
269
+ tmpdir = tempfile.mkdtemp(prefix='psmcconv_')
270
+ BUDGET = float(os.environ.get('PSMC_BUDGET_S', '1e18'))
271
+ todo = np.array([i for i in my_rows(task, ntask) if int(R_REG[i]) not in have], dtype=np.int64)
272
+ if os.environ.get('PSMC_MAX_ROWS'): todo = todo[:int(os.environ['PSMC_MAX_ROWS'])]
273
+ print('task %d/%d: %d rows to do (%d already done), iterates=%d warm=%d'
274
+ % (task, ntask, len(todo), len(have), ITERATES, int(WARM)), flush=True)
275
+
276
+ n_new, row_times = 0, []
277
+ mut_bed = os.path.join(tmpdir, 'mut.bed'); rec_bed = os.path.join(tmpdir, 'rec.bed')
278
+
279
+ for sel in todo:
280
+ sel = int(sel)
281
+ if row_times and time.time() - t0 + 1.25 * max(row_times[-3:]) > BUDGET:
282
+ print('task %d: stopping before selection row %d, budget %.0fs nearly spent' % (task, sel, BUDGET), flush=True)
283
+ break
284
+ row_t0 = time.time()
285
+ j, k, reg = int(R_FRAG[sel]), int(R_ROW[sel]), int(R_REG[sel])
286
+ z = frag(FR[j]); sid = str(z['sample_id'][k])
287
+ assert sid == str(R_SID[sel]), ('row list / fragment sample_id mismatch', sel, j, k, sid, str(R_SID[sel]))
288
+
289
+ feats = np.zeros(FEAT, np.float32); flags = np.zeros(2, np.int16)
290
+ it_means = np.zeros((ITERATES, NB), np.float32)
291
+
292
+ vo = z['variant_offsets']; a, b = int(vo[k]), int(vo[k + 1])
293
+ L = float(z['sequence_length'][k])
294
+ mp, mrt, rp, rrt = map_slices(z, k)
295
+ assert len(mp) == len(mrt) + 1 and len(rp) == len(rrt) + 1, (sel, j, k, 'map slice')
296
+ ms, me, mrate, mu = segments(mp, mrt, L); rs, re_, rrate, r = segments(rp, rrt, L)
297
+ assert np.isfinite(mu) and mu > 0 and np.isfinite(r) and r > 0, (sel, j, k, 'bad map rates')
298
+
299
+ pos = z['variant_positions_bp'][a:b].astype(np.int64)
300
+ bits = np.unpackbits(np.ascontiguousarray(z['genotype_packed'][a:b]), axis=1, bitorder='little')
301
+ V = b - a
302
+ anymiss = np.zeros((V, N_DIP), dtype=bool)
303
+ mf, mo_ = z['missing_flat_idx'], z['missing_offsets']; mi = mf[int(mo_[k]):int(mo_[k + 1])].astype(np.int64)
304
+ if len(mi):
305
+ mvar, mhap = np.divmod(mi, N_HAP); anymiss[mvar, mhap >> 1] = True
306
+ het = bits[:, 0::2] != bits[:, 1::2]
307
+ het &= ~anymiss
308
+ del bits
309
+ callable_ = L - anymiss.sum(0)
310
+ het_frac = het.sum(0) / np.maximum(callable_, 1)
311
+
312
+ rel_m = mrate / mu; rel_r = rrate / r; n_cold = int((rel_r < 0.02).sum()); rel_r = np.maximum(rel_r, 0.02)
313
+ write_bed(mut_bed, ms, me, rel_m, '%.3f'); write_bed(rec_bed, rs, re_, rel_r, '%.2f')
314
+
315
+ cols = np.asarray(chain_columns(sid, CHAIN)[:LEVEL], dtype=np.int64)
316
+ th = float(np.mean(het_frac[cols]))
317
+ assert np.isfinite(th) and th > 0.0, (sel, sid, 'level-32 theta is not positive')
318
+ BIN = 100 if th * 100.0 <= 1.0 else max(10, int(1.0 / th))
319
+ N = th / (4.0 * mu); rho = 4.0 * N * r
320
+ edges_full = install_grid(edges_gen / (2.0 * N))
321
+
322
+ mhs_paths = {}
323
+ for d in cols.tolist():
324
+ hp = pos[het[:, d]]
325
+ if len(hp) < 8: continue
326
+ mpos = pos[anymiss[:, d]]; prev = np.concatenate([[-1], hp[:-1]])
327
+ nmb = np.searchsorted(mpos, hp, side='right') - np.searchsorted(mpos, prev, side='right')
328
+ nmb = np.minimum(nmb, np.maximum(hp - prev - 2, 0))
329
+ called = (hp - prev) - nmb
330
+ p_ = os.path.join(tmpdir, 'd%02d.mhs' % d)
331
+ pd.DataFrame({'c': '1', 'p': hp + 1, 'n': called, 'a': 'AT'}).to_csv(p_, sep='\t', header=False, index=False)
332
+ mhs_paths[d] = p_
333
+ del het, anymiss, pos
334
+
335
+ Bidx, Bvals = binned_map(mut_bed, L, False, BIN); Ridx, Rvals = binned_map(rec_bed, L, True, BIN)
336
+ parts = {}
337
+ for d in cols.tolist():
338
+ if d not in mhs_paths: continue
339
+ try:
340
+ parts[d] = seq_parts(mhs_paths[d], BIN)
341
+ except BaseException as e:
342
+ parts[d] = None
343
+ print('row %d d%02d seq_parts failed: %s' % (reg, d, str(e)[:160]), flush=True)
344
+ usable = [int(d) for d in cols.tolist() if parts.get(d) is not None]
345
+ assert usable, (sel, sid, 'no usable diploid at chain 0 level 32')
346
+ j_max_all = max(parts[d][2] for d in usable)
347
+
348
+ it_sec = np.zeros(ITERATES); it_scored = np.zeros(ITERATES, dtype=int)
349
+ lam = None
350
+ start_it = 0
351
+ last_good = -1; last_mean = None; last_std = None; last_n = 0
352
+ if WARM:
353
+ stored = STORE_SIDECAR[reg]
354
+ it_means[0] = stored[0:64]; it_means[1] = stored[128:192]
355
+ feats[0:64] = stored[0:64]; feats[64:128] = stored[64:128]
356
+ flags[0] = len(usable)
357
+ log_ne = np.asarray(occ_to_ne(np.asarray(stored[128:192], dtype=np.float64)), float)
358
+ med = float(np.median(log_ne))
359
+ assert GUARD_LO < med < GUARD_HI, ('occ_to_ne not log10 diploid Ne', med, sid)
360
+ lam64 = N / np.power(10.0, log_ne); lam = np.concatenate([[lam64[0]], lam64])
361
+ start_it = 2
362
+ last_good, last_mean, last_std, last_n = 1, stored[128:192].astype(np.float64), \
363
+ stored[192:256].astype(np.float64), len(usable)
364
+
365
+ max_repro = -1.0
366
+ row_failed = False
367
+ for it in range(start_it, ITERATES):
368
+ t_it = time.time()
369
+ try:
370
+ shared = make_shared(th, rho, edges_full, lam, Rvals, BIN, j_max_all)
371
+ except BaseException as e:
372
+ # An extreme lambda can make PSMC+'s transition matrix degenerate. Iterating stops
373
+ # here: the row keeps the last iterate that decoded, and the zero rows left in
374
+ # iterate_means are how the receipt counts what it reached.
375
+ print('row %d it %d shared setup failed, stopping at iterate %d: %s'
376
+ % (reg, it, last_good, str(e)[:400]), flush=True)
377
+ break
378
+ per = np.full((len(cols), NB), np.nan)
379
+ for s, d in enumerate(cols.tolist()):
380
+ if parts.get(d) is None: continue
381
+ try:
382
+ occ, _ = decode(parts[d], shared, th, Bidx, Bvals, Ridx, Rvals, BIN)
383
+ if np.isfinite(occ).all(): per[s] = occ
384
+ except BaseException as e:
385
+ print('row %d it %d d%02d decode failed (Q %s, E %s): %s'
386
+ % (reg, it, d, getattr(shared[1], 'dtype', '?'),
387
+ getattr(getattr(shared[0], 'E', None), 'dtype', '?'), str(e)[:400]), flush=True)
388
+ keep = np.isfinite(per).all(1)
389
+ if not keep.any():
390
+ # Never fatal to the task: one unscorable row must not cost the other ~70 it holds.
391
+ print('row %d it %d scored no diploid, stopping at iterate %d' % (reg, it, last_good), flush=True)
392
+ if it == 0:
393
+ print('row %d: PLAIN PASS FAILED, row skipped entirely' % reg, flush=True)
394
+ row_failed = True
395
+ break
396
+ pooled = per[keep].mean(0)
397
+ it_means[it] = pooled
398
+ it_sec[it] = time.time() - t_it
399
+ it_scored[it] = int(keep.sum())
400
+ last_good, last_mean, last_std, last_n = it, pooled, per[keep].std(0), int(keep.sum())
401
+ if it == 0:
402
+ feats[0:64] = pooled; feats[64:128] = per[keep].std(0); flags[0] = int(keep.sum())
403
+ if not WARM and it in (0, 1):
404
+ # the stored file's own layout: iterate 1 is [0:128], iterate 2 is [128:256]
405
+ off = 0 if it == 0 else 128
406
+ mine = np.concatenate([pooled, per[keep].std(0)]).astype(np.float32)
407
+ d0 = float(np.max(np.abs(mine.astype(np.float64)
408
+ - np.asarray(STORE_SIDECAR[reg][off:off + 128], dtype=np.float64))))
409
+ max_repro = max(max_repro, d0)
410
+ log_ne = np.asarray(occ_to_ne(pooled), float)
411
+ assert log_ne.shape == (NB,)
412
+ med = float(np.median(log_ne))
413
+ if it == 0:
414
+ # the production builder's units guard, in the same place and as strict
415
+ assert GUARD_LO < med < GUARD_HI, ('occ_to_ne not log10 diploid Ne', med, sid, it)
416
+ elif not (GUARD_LO < med < GUARD_HI):
417
+ # later iterates over-disperse by design; lambda is clipped to [0.05, 50] downstream
418
+ print('row %d it %d: median log10 Ne %.3f outside (%.1f, %.1f)' % (reg, it, med, GUARD_LO, GUARD_HI), flush=True)
419
+ lam64 = N / np.power(10.0, log_ne); lam = np.concatenate([[lam64[0]], lam64])
420
+
421
+ parts.clear()
422
+ if row_failed:
423
+ print('row %d: not written; the assembler will report it missing' % reg, flush=True)
424
+ continue
425
+ # The refit half is the LAST iterate that decoded. It is ITERATES-1 on every row that ran to
426
+ # the end; a row that stopped early carries fewer, and iterate_means' trailing zero rows say so.
427
+ if last_good >= 1:
428
+ feats[128:192] = last_mean; feats[192:256] = last_std; flags[1] = last_n
429
+ if last_good != ITERATES - 1:
430
+ print('row %d: converged refit is iterate %d of %d' % (reg, last_good + 1, ITERATES), flush=True)
431
+ else:
432
+ # Not one refit iterate decoded. Carry the production refit through and flag it with -1,
433
+ # so the row is present and complete but never counted as converged.
434
+ feats[128:256] = STORE_SIDECAR[reg][128:256]; flags[1] = -1
435
+ print('row %d: NO refit iterate decoded; stored production refit carried through (flag -1)'
436
+ % reg, flush=True)
437
+ dt_row = time.time() - row_t0; row_times.append(dt_row)
438
+ if TIME_ONLY:
439
+ print(json.dumps({'registry_index': reg, 'sample_id': sid, 'variant_count': int(b - a),
440
+ 'theta': th, 'BIN': BIN, 'N0': N, 'j_max': j_max_all,
441
+ 'seconds_total': dt_row, 'seconds_per_iterate': it_sec.tolist(),
442
+ 'scored': it_scored.tolist(), 'max_repro_diff': max_repro}), flush=True)
443
+ continue
444
+ O_reg.append(reg); O_sid.append(sid); O_frag.append(j); O_row.append(k)
445
+ O_feat.append(feats); O_flag.append(flags); O_iter.append(it_means)
446
+ O_meta.append([mu, r, float(b - a), L, dt_row, th, float(BIN), N, float(j_max_all),
447
+ float(n_cold), max_repro, float(it_sec.sum())])
448
+ n_new += 1
449
+ save()
450
+ if n_new <= 3 or n_new % 5 == 0:
451
+ print('task %d: reg %d (%s f%d r%d) V=%d theta=%.5f BIN=%d scored=%d/%d repro=%.3g %.0fs | %d rows, %.0fs'
452
+ % (task, reg, sid, j, k, b - a, th, BIN, int(flags[1]), LEVEL, max_repro, dt_row,
453
+ len(O_reg), time.time() - t0), flush=True)
454
+
455
+ if not TIME_ONLY:
456
+ save()
457
+ el = time.time() - t0
458
+ print('task %d: %d rows in shard (+%d new), %.0fs, %.1f s/row new'
459
+ % (task, len(O_reg), n_new, el, el / max(n_new, 1)), flush=True)
additional/psmcplus_converged/select_pilot_rows.py ADDED
@@ -0,0 +1,193 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Reproduce the runner's --pilot-fit-rows selection for a 12,500-row ablation.
2
+
3
+ Rule, read from the FROZEN deploy (deploy_20260913_fixed32/training/carrier_raw_runner.py):
4
+
5
+ _select_stage_rows(stage="pilot", ...) ->
6
+ _balanced_quantiles(reverse[fit], rows, args.pilot_fit_rows)
7
+
8
+ reverse[fit] are the REGISTRY indices of the architecture-training fit split.
9
+ _balanced_quantiles groups those candidates by _root_key(row) =
10
+ row["logical_dataset_root"] or row["physical_dataset_root"],
11
+ allocates count//n_roots to every sorted root (+1 to the first count%n_roots),
12
+ orders each root's candidates by (variant_count, canonical_id), takes
13
+ np.linspace(0, len-1, n_take, dtype=int64) positions, and returns the union
14
+ SORTED ascending.
15
+
16
+ When count == len(candidates) it is a full census: sorted(candidates).
17
+
18
+ The production run 'fixed32_fit89996_inner500_eval500' was stage=pilot with
19
+ --pilot-fit-rows 89996 == len(fit), i.e. the census branch, so its PLAN.json
20
+ stage_rows["fit"] IS reverse[fit]. That list is the candidate pool here; the
21
+ identity sha in PLAN is re-checked before it is used.
22
+
23
+ Nothing in this script opens a fragment, and the registry itself already
24
+ excludes the 4,248 sealed selection rows (104,996 = 109,244 - 4,248); the
25
+ sealed sample_ids are loaded only to assert that none of them was selected.
26
+ """
27
+ import hashlib
28
+ import json
29
+ import sys
30
+
31
+ import numpy as np
32
+
33
+ A = "$WORK"
34
+ RUN = f"{A}/compshare_archive_20260916/files/runs/fixed32_fit89996_inner500_eval500_d128_e12_seed20260728"
35
+ REG = f"{A}/registry109k"
36
+ OUT = sys.argv[1] if len(sys.argv) > 1 else f"{A}/bench_h2h_20260915/analysis/final_round/sidecar_variant"
37
+ N_FIT = int(sys.argv[2]) if len(sys.argv) > 2 else 12500
38
+
39
+
40
+ def array_sha256(value): # training/data.py::_array_sha256
41
+ array = np.ascontiguousarray(value)
42
+ digest = hashlib.sha256()
43
+ digest.update(array.dtype.str.encode("ascii"))
44
+ digest.update(json.dumps(array.shape).encode("ascii"))
45
+ digest.update(memoryview(array).cast("B"))
46
+ return digest.hexdigest()
47
+
48
+
49
+ def root_key(row): # carrier_raw_runner._root_key
50
+ value = str(row.get("logical_dataset_root") or row.get("physical_dataset_root") or "")
51
+ if not value:
52
+ raise ValueError("registry row lacks dataset root")
53
+ return value
54
+
55
+
56
+ def balanced_quantiles(candidates, rows, count): # carrier_raw_runner._balanced_quantiles
57
+ values = [int(index) for index in candidates]
58
+ if count <= 0 or len(values) < count:
59
+ raise ValueError("not enough candidates for balanced selection")
60
+ if count == len(values):
61
+ if len(set(values)) != count:
62
+ raise ValueError("full split census contains duplicate candidates")
63
+ return np.asarray(sorted(values), dtype=np.int64)
64
+ groups = {}
65
+ for index in values:
66
+ groups.setdefault(root_key(rows[index]), []).append(index)
67
+ roots = sorted(groups)
68
+ allocation = {root: count // len(roots) for root in roots}
69
+ for root in roots[: count % len(roots)]:
70
+ allocation[root] += 1
71
+ selected = []
72
+ for root in roots:
73
+ ordered = sorted(
74
+ groups[root],
75
+ key=lambda index: (int(rows[index]["variant_count"]), str(rows[index]["canonical_id"])),
76
+ )
77
+ n_take = allocation[root]
78
+ if len(ordered) < n_take:
79
+ raise ValueError("one logical root cannot satisfy balanced allocation")
80
+ positions = np.linspace(0, len(ordered) - 1, n_take, dtype=np.int64)
81
+ selected.extend(ordered[int(position)] for position in positions)
82
+ if len(selected) != count or len(set(selected)) != count:
83
+ raise RuntimeError("balanced quantile selection is not exact/unique")
84
+ return np.asarray(sorted(selected), dtype=np.int64)
85
+
86
+
87
+ plan = json.load(open(f"{RUN}/PLAN.json"))
88
+ fit = np.asarray(plan["stage_rows"]["fit"], dtype=np.int64)
89
+ inner = np.asarray(plan["stage_rows"]["inner"], dtype=np.int64)
90
+ evaluation = np.asarray(plan["stage_rows"]["evaluation"], dtype=np.int64)
91
+ ident = plan["stage_rows_identity"]
92
+ for name, arr in (("fit", fit), ("inner", inner), ("evaluation", evaluation)):
93
+ assert array_sha256(arr) == ident[name]["sha256"], (name, "PLAN stage-row digest mismatch")
94
+ assert len(arr) == ident[name]["rows"]
95
+ print(f"PLAN stage rows verified: fit {len(fit)}, inner {len(inner)}, eval {len(evaluation)}")
96
+ assert plan["stage"] == "pilot"
97
+ assert len(fit) == len(set(fit.tolist()))
98
+
99
+ rows = []
100
+ with open(f"{REG}/raw_index.jsonl") as handle:
101
+ for line in handle:
102
+ row = json.loads(line)
103
+ rows.append(
104
+ {
105
+ "logical_dataset_root": row.get("logical_dataset_root"),
106
+ "physical_dataset_root": row.get("physical_dataset_root"),
107
+ "variant_count": int(row["variant_count"]),
108
+ "canonical_id": str(row["canonical_id"]),
109
+ "sample_id": str(row["sample_id"]),
110
+ "output_index": int(row["output_index"]),
111
+ }
112
+ )
113
+ n_rows = len(rows)
114
+ print(f"registry rows {n_rows}")
115
+ assert all(r["output_index"] == i for i, r in enumerate(rows)), "registry order is not output_index order"
116
+
117
+ # Registry order == level-cache order == sidecar row order:
118
+ # registry sample_identities.jsonl and the cache's are the SAME file digest
119
+ # (PLAN registry_sha256 / cache_sha256 both b91dbfe2...), and the sidecar was
120
+ # assembled in that same cohort order minus the sealed rows.
121
+ assert plan["registry_sha256"]["sample_identities.jsonl"] == plan["cache_sha256"]["identities"], (
122
+ "registry and cache identity manifests differ; the identity map is not the identity"
123
+ )
124
+
125
+ # fit census branch reproduces PLAN exactly
126
+ census = balanced_quantiles(fit, rows, len(fit))
127
+ assert array_sha256(census) == ident["fit"]["sha256"], "census branch does not reproduce PLAN fit rows"
128
+
129
+ pilot_fit = balanced_quantiles(fit, rows, N_FIT)
130
+ print(f"pilot fit rows ({N_FIT}) sha256 {array_sha256(pilot_fit)}")
131
+
132
+ # rows the ablation also needs values for: the pilot inner/eval sets, already
133
+ # balanced-quantile subsampled at 500 each in the production run.
134
+ union = np.unique(np.concatenate([pilot_fit, inner, evaluation]))
135
+ print(f"union fit+inner+eval = {len(union)} rows (overlap {len(pilot_fit) + len(inner) + len(evaluation) - len(union)})")
136
+
137
+ split = np.load(f"{A}/cohort109k/cohort109k_split.npz", allow_pickle=False)
138
+ sealed = set(np.asarray(split["sample_id"])[np.asarray(split["split_code"]) == 2].tolist())
139
+ print(f"sealed sample_ids: {len(sealed)}")
140
+ sel_sid = [rows[int(i)]["sample_id"] for i in union]
141
+ assert not (set(sel_sid) & sealed), "a sealed row entered the selection"
142
+ assert not (set(r["sample_id"] for r in rows) & sealed), "the registry itself contains sealed rows"
143
+ print("no sealed row in the registry or in the selection")
144
+
145
+ inv = np.load("$DATA/DLCoalSim/prod_inventory_all.npz", allow_pickle=False)
146
+ inv_pos = {str(s): i for i, s in enumerate(inv["sample_id"].tolist())}
147
+ inv_idx = np.asarray([inv_pos[s] for s in sel_sid], dtype=np.int64)
148
+ frag = inv["fragment"][inv_idx].astype(np.int64)
149
+ row_in_frag = inv["row"][inv_idx].astype(np.int64)
150
+ vc = inv["variant_count"][inv_idx].astype(np.int64)
151
+ assert all(str(inv["sample_id"][i]) == s for i, s in zip(inv_idx.tolist(), sel_sid))
152
+
153
+ kind = np.zeros(len(union), dtype=np.int8) # bit0 fit, bit1 inner, bit2 eval
154
+ pos = {int(v): i for i, v in enumerate(union.tolist())}
155
+ for arr, bit in ((pilot_fit, 1), (inner, 2), (evaluation, 4)):
156
+ for v in arr.tolist():
157
+ kind[pos[int(v)]] |= bit
158
+
159
+ np.savez(
160
+ f"{OUT}/pilot_rows_{N_FIT}.npz",
161
+ registry_index=union,
162
+ sample_id=np.asarray(sel_sid),
163
+ inventory_index=inv_idx,
164
+ fragment=frag,
165
+ row=row_in_frag,
166
+ variant_count=vc,
167
+ kind=kind,
168
+ pilot_fit=pilot_fit,
169
+ pilot_inner=inner,
170
+ pilot_evaluation=evaluation,
171
+ )
172
+ receipt = {
173
+ "pilot_fit_rows": int(N_FIT),
174
+ "pilot_fit_sha256": array_sha256(pilot_fit),
175
+ "pilot_inner_rows": int(len(inner)),
176
+ "pilot_inner_sha256": array_sha256(inner),
177
+ "pilot_evaluation_rows": int(len(evaluation)),
178
+ "pilot_evaluation_sha256": array_sha256(evaluation),
179
+ "union_rows": int(len(union)),
180
+ "union_sha256": array_sha256(union),
181
+ "candidate_pool_rows": int(len(fit)),
182
+ "candidate_pool_sha256": ident["fit"]["sha256"],
183
+ "registry_rows": int(n_rows),
184
+ "registry_dir": REG,
185
+ "plan": f"{RUN}/PLAN.json",
186
+ "variant_count": {
187
+ "min": int(vc.min()), "max": int(vc.max()),
188
+ "mean": float(vc.mean()), "median": float(np.median(vc)), "sum": int(vc.sum()),
189
+ },
190
+ "roots": sorted({root_key(rows[int(i)]) for i in union}),
191
+ }
192
+ json.dump(receipt, open(f"{OUT}/pilot_rows_{N_FIT}.json", "w"), indent=1, sort_keys=True)
193
+ print(json.dumps(receipt, indent=1, sort_keys=True))
additional/psmcplus_converged/shards/shard_00000.npz ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:175783a8efd90931367f45309f776da3f2b273ae0ec4d64e462393a830856651
3
+ size 184821
additional/psmcplus_converged/shards/shard_00001.npz ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:678a8c6e0cd1dac22818647f421a7907fb25facdd741d167cca2e0e305a3de19
3
+ size 184821
additional/psmcplus_converged/shards/shard_00002.npz ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:07415e026ac145fa9848bea01becb0003fbd362c389e50c4b2334b41625d0d54
3
+ size 184821
additional/psmcplus_converged/shards/shard_00003.npz ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:52dff0d85cf58d549f1654a246af421ebfe1aae14c4ab6c427f761561045069a
3
+ size 184821
additional/psmcplus_converged/shards/shard_00004.npz ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:0ad6ebd873f75ef271b734978bf9d6cbf147160c65937e9f3360e1b4dd2b0066
3
+ size 184821
additional/psmcplus_converged/shards/shard_00005.npz ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:2793118f8c0ae31dc690d94afb8e4ef2e94a2950a1678d179d375d19360e731f
3
+ size 184821
additional/psmcplus_converged/shards/shard_00006.npz ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:73263856ab89af57aed1c1e2cb307274b255aca5903b2799b7d39a2ea9517828
3
+ size 184821
additional/psmcplus_converged/shards/shard_00007.npz ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:786b1c07556e36299137cf231a9cd25d331afdd9eb5db6f415f58f8aad284fa3
3
+ size 184821
additional/psmcplus_converged/shards/shard_00008.npz ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:fa4eab05bdd6a96e7fec6abe65dd6d9d7dd614c0cb54559fb2a55a105f0941fd
3
+ size 184821
additional/psmcplus_converged/shards/shard_00009.npz ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:d32bf2ab69c79099f4df480141de2b68756880883500d4f996ac54bd5d7b1250
3
+ size 184821
additional/psmcplus_converged/shards/shard_00010.npz ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:cb05ca7d7ba691ed33fd2ed5e676e693f2e1822389b17f8650b899c4e8d69b9f
3
+ size 184821
additional/psmcplus_converged/shards/shard_00011.npz ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:4a900bafeb58b2521748e127e9428f01bd5b298d815d97c3ff84fed92e529e34
3
+ size 184821
additional/psmcplus_converged/shards/shard_00012.npz ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:f97fc3694c052cd32c52654f8dab09e30b406199f8fe520a5edd73673dd95dd4
3
+ size 184821
additional/psmcplus_converged/shards/shard_00013.npz ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:2ff68248d333594f28db2b7868cf65d8239d483971107b3e71a7694c05cc93cb
3
+ size 184821
additional/psmcplus_converged/shards/shard_00014.npz ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:2daf719bf1286a33067ef350b10caded42a5e12afbadda00984c01375aeddbcb
3
+ size 184821
additional/psmcplus_converged/shards/shard_00015.npz ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:db9ec5136280354918bad1928fba286a4b4a306f1b5c94c0380e3959859c188a
3
+ size 184821
additional/psmcplus_converged/shards/shard_00016.npz ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:bb4a7b3defd7ee55d7cb04268325955af787628f141779ded3906603ab4b4940
3
+ size 184821
additional/psmcplus_converged/shards/shard_00017.npz ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:3458694ad498b4d126dd79866968176986cee680ba51151fe5ec74ef2dd016dd
3
+ size 184821
additional/psmcplus_converged/shards/shard_00018.npz ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:672abdbafdb39c3fc8f499d7cefc9052ede8f297c057d1c51cf6a65ce1ec2982
3
+ size 184821
additional/psmcplus_converged/shards/shard_00019.npz ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:685a9cf4f8c5e8675838cebde74b67470877bfce3ecc1fb3877e115f54e59edf
3
+ size 184821
additional/psmcplus_converged/shards/shard_00020.npz ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:6a3bce717bd0d54ca23786cc03eb5c6b6ec56901525cc368032fb871da3a5a7b
3
+ size 184821
additional/psmcplus_converged/shards/shard_00021.npz ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:404cd7b5e5e6b72ba54fbaa9c037ea2c081c67cc8241666ef83de5b5e2ced770
3
+ size 184821
additional/psmcplus_converged/shards/shard_00022.npz ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:febd7dc6b540753b456ad2c910396f28d5f2cc394e3698ec10f201d09f6fb9d5
3
+ size 184821
additional/psmcplus_converged/shards/shard_00023.npz ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:5c7be5a49b708b5d27a71334b4b7f18c7981a336b0005314c85446615f9c1263
3
+ size 184821
additional/psmcplus_converged/shards/shard_00024.npz ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:16d9df2af97aa56e963d9a50c95c1dd00596e9219db1b5a349d58cda960d7c8e
3
+ size 184821
additional/psmcplus_converged/shards/shard_00025.npz ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:5d45b36f57abab27a5a96b0f113e2b9d44edb4111a9ed5af0721262d4ee876f8
3
+ size 184821
additional/psmcplus_converged/shards/shard_00026.npz ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:02f84aa1553533bbba280fd7d3f4be5f2b496de7c159cf3fba731e151090f392
3
+ size 184821
additional/psmcplus_converged/shards/shard_00027.npz ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:247626952195e61d1f5371ea76097a4713f0b3a1dbccd4e99e56d943b0ad826f
3
+ size 184821
additional/psmcplus_converged/shards/shard_00028.npz ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:3c12a928c830199be65caa1e0c48657ea148a341915f492e2dd31780b7e6417a
3
+ size 184821
additional/psmcplus_converged/shards/shard_00029.npz ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:e65ac17f3c361d309b2b6665a7ef76778c9141fabf0bc9d5ecb27f0c0ad6f53a
3
+ size 184821
additional/psmcplus_converged/shards/shard_00030.npz ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:7bdf1723f8ce0b039e236ed5908077159a30efbd41c50cd0acf6a858069f82ab
3
+ size 184821
additional/psmcplus_converged/shards/shard_00031.npz ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:1f0019112740515346de29c8f1638ad5eaff2fcf73b24f81dc7d68899bfdc533
3
+ size 184821
additional/psmcplus_converged/shards/shard_00032.npz ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:38cee36da5d99a80a99a6589ca1ea1b6c2d1510aa4bc60417aa93cc635794d27
3
+ size 184821
additional/psmcplus_converged/shards/shard_00033.npz ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:c48c3be002de381da87a63c2d9a9fe34afd9ca30f1dd81e5116984319555ff0b
3
+ size 184821