NeCast-simulations / README.md
Larrivhan's picture
NeCast release files
1cb35cf
|
Raw History Blame Contribute Delete
15.8 kB
---
license: cc-by-4.0
pretty_name: NeCast simulations
tags:
- population-genetics
- demographic-inference
- effective-population-size
- coalescent
- msprime
- simulation
size_categories:
- 100K<n<1M
configs:
- config_name: index
data_files: index/windows.parquet
default: true
---
# NeCast simulations
Simulated genotype windows used to train and test NeCast, a neural network that estimates the
size history of a population from 32 diploid genomes together with recombination and mutation
maps. There are 109,248 windows. Each is 30 Mb of sequence sampled from 64 diploid individuals,
with sequencing-like errors already applied, and each comes with its true size history. The
files the network was trained on are included, as are the code and configuration that made the
windows.
![What the corpus covers](https://huggingface.co/datasets/Larrivhan/NeCast-simulations/resolve/main/figures/simulations_overview.png)
**What the corpus covers.** **a**, Eight training windows drawn at random from each of the
twelve families of size history, with the number of windows in each family. Each line is a
window's 64 interval labels, drawn through the interval centres. **b**, Windows by the type of
map stored with them. Every window carries sequencing-like errors except those with constant maps
at the baseline rates. **c**, Variant sites per window, false sites included.
## Contents
| path | what it holds | size |
|---|---|---|
| `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 |
| `windows/receipts.jsonl.gz` | the receipt written when each file was generated, with its SHA-256 | small |
| `index/windows.parquet` | one row per window: where it is stored, its split, how it was simulated | 0.05 GB |
| `index/histories.parquet` | the epochs of every simulated history, by window | 0.93 GB |
| `splits/` | the train / development / reserved split, and the windows used to train, validate and test the final network | 0.2 GB |
| `features/` | what the final network reads, for the 104,996 train and development windows | 15.7 GB |
| `additional/` | the same inputs for 1, 2, 4, 8 and 16 individuals, and a variant of the PSMC+ posterior | 63.1 GB |
| `generator/` | the simulator code, the generation plan and the map scripts | small |
| `tools/necast_windows.py` | a reader that needs only numpy | small |
| `logs/` | build logs of the feature files | small |
| `figures/` | the figures on this card | small |
| `SHA256SUMS` | a checksum for every file except this card | small |
The windows are grouped by generation chunk: `windows/NNN/` holds chunks `NNN000` to `NNN999`.
Window `sim_XXXXXXXX` is member `XXXXXXXX mod 4` of file `fragment_{XXXXXXXX div 4}`. The run
planned 110,000 windows in 27,500 chunks of four; 188 chunks were not generated, so window
numbers have gaps. The index lists every window that exists.
## How the windows were simulated
- **Sequence and sample.** 30 Mb, 64 diploid individuals (128 haplotypes). msprime 1.4.2 with
the default coalescent with recombination (the full ancestral recombination graph), a binary
mutation model, the window's true recombination and mutation maps, and no gene conversion.
- **Size histories.** Twelve families, named in `generator_recipe`: constant (`constant`),
exponential (`exponential`), one size change (`size_event`), several changes (`multi_event`),
bottleneck (`bottleneck`), event on a trend (`event_on_background`), random walk
(`spectral_walk`), sawtooth (`sawtooth`), zigzag-like (`literature_sawtooth`), founder chain
(`ooa_chain`), perturbed published human histories (`empirical_human_ne_template`; 191 curves
inferred by SMC++, phlash, MSMC2 and MSMC-IM), and the 18 single-population models of the
stdpopsim catalogue (`stdpopsim_single_pop`). Sizes stay between 100 and 1,000,000. The
realised parameters of every history are in the metadata.
- **Maps** (`map_type`). A constant map at the baseline rates (`constant_clean`), constant
rates drawn at random (`constant_random_global`), synthetic heterogeneous maps
(`synthetic_heterogeneous`), or 30 Mb slices of the deCODE 2019 recombination map and the
Roulette mutation map taken from the same chromosomal interval (`empirical_slice`).
- **Errors** (`noise_profile`). `mild_noise` windows have genotype errors, missing calls, false
variant sites and phase switches within individuals, at rates drawn per window and recorded
in the metadata (`noise_*` fields). `clean` windows, which are the `constant_clean` ones,
have none.
- **Maps stored with a window** are the maps a method is given. Constant maps are stored
exactly. Synthetic and empirical maps are stored as the true map seen through noise: a
log-normal factor with mean one on short cells (`observed_cell_bp`), smaller for the mutation
map, and for synthetic maps some hotspots left out. The noise size is in the metadata
(`observed_noise_sigma`, and `rec_slice_*` and `mut_slice_*` for empirical slices). The true
maps are not stored.
- **Labels.** `target_log10_ne` gives, for each of 64 time intervals spaced evenly in log time
between 50 and 500,000 generations ago, the average of log10 Ne over the interval (averaged in
log time) of the simulated history. The file also stores the true number of pairwise
coalescences and the total branch length in each interval.
## Splits and the windows used by the final network
Windows were assigned by a hash of their identifier: 100,000 train, 5,000 development and
4,248 reserved. Four train windows have no PSMC+ output and belong to no split (`split = none`
in the index), leaving 99,996 train windows.
The final NeCast network was fitted on 89,996 train windows. Another 500 train windows picked
the training epoch (`stage = validation`), and 500 development windows were the test set
(`stage = test`); both sets of 500 sit at evenly spaced quantiles of the number of variant sites.
`splits/stages.json` lists them by sample ID and by feature row.
The 4,248 reserved windows were never used to train, select or score a network. Their PSMC+
output was computed (it is in `features/psmcplus_store/`), but they were left out of every other
feature file. Now that they are public, they no longer serve as an untouched test set.
## Reading a window
![One window](https://huggingface.co/datasets/Larrivhan/NeCast-simulations/resolve/main/figures/simulations_window.png)
**One window, `sim_00000016`**: a perturbed published human history, slices of the deCODE and
Roulette maps, and errors. **a**, Diploid genotypes of the 64 individuals at the 133 variant
sites between 15.00 and 15.10 Mb: 0 pale grey, 1 light purple, 2 purple; missing calls are empty cells.
**b**, The recombination and mutation maps stored with the window, averaged in 300-kb bins.
**c**, The simulated history (grey) and its 64 interval labels (black), which are the
network's targets.
```python
from huggingface_hub import hf_hub_download
import sys
path = hf_hub_download("Larrivhan/NeCast-simulations", "windows/000/fragment_00000000.npz", repo_type="dataset")
hf_hub_download("Larrivhan/NeCast-simulations", "windows/000/fragment_00000000.jsonl.gz", repo_type="dataset")
reader = hf_hub_download("Larrivhan/NeCast-simulations", "tools/necast_windows.py", repo_type="dataset")
sys.path.insert(0, reader.rsplit("/", 1)[0])
from necast_windows import Fragment, diploid_genotypes, TIME_EDGES
frag = Fragment(path)
w = frag.window(0)
w["genotypes"].shape # (n_sites, 128): 0/1, haplotypes 2i and 2i+1 are individual i
w["missing"].sum() # missing calls (their genotype bit is 0)
g = diploid_genotypes(w) # (n_sites, 64): 0, 1, 2, or -1 where a call is missing
w["recombination_map"] # breakpoints (bp) and rates per bp per generation
w["target_log10_ne"] # 64 labels on the intervals TIME_EDGES
w["metadata"]["generator_recipe"]
```
The index is a parquet table, so `pandas.read_parquet("index/windows.parquet")` or the
`datasets` library will load it. Filter it to pick windows, then read only the files you need.
## File format
Each `fragment_XXXXXXXX.npz` holds four windows; ragged arrays are concatenated, and an
`*_offsets` array of length 5 marks where each window starts.
| array | type and shape | meaning |
|---|---|---|
| `sample_id` | str (4) | window identifiers |
| `variant_positions_bp`, `variant_offsets` | uint32, int64 | site positions; window k is `[off[k], off[k+1])` |
| `genotype_packed` | uint8 (sites, 16) | 128 haplotypes, 8 per byte; haplotype h is bit `h % 8` of byte `h // 8` (`numpy.unpackbits(..., bitorder="little")`) |
| `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 |
| `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)` |
| `obs_mut_pos`, `obs_mut_rate`, `obs_mut_offsets` | the same | mutation map |
| `target_log10_ne` | float32 (4, 64) | labels |
| `pair_coalescences_per_bin`, `branch_length_per_bin` | float32 (4, 64) | true pairwise coalescences and branch length per interval |
| `pair_coalescences_outside` | float64 (4, 2) | pairwise coalescences before the first and after the last interval |
| `sequence_length`, `n_haplotypes`, `packed_hap_bytes` | int | 30,000,000; 128; 16 |
| `source_id`, `demography_type_id`, `generator_recipe_id` | int16 (4) | codes; the names are in the metadata |
| `generator_schema_version`, `missing_storage` | | format version (1) and the missing-call encoding |
Variant sites include the false sites added as errors. Positions are sorted; a few windows have
two sites at the same position.
The `.jsonl.gz` file has one JSON object per window with every parameter of its history, maps
and errors. The index carries the same fields, flattened: nested objects become `noise_*`,
`rec_slice_*`, `mut_slice_*` and similar columns, and short lists are stored as JSON text. The
epochs of each history (`demography_breaks` in generations ago, `demography_values` and
`demography_growth_rates`, as passed to msprime) are in `index/histories.parquet` as numeric
lists, one row per window.
**Inputs and labels.** A method under test should read only the genotypes, the site positions,
the stored maps, the sequence length and the sample size. Every other field describes how the
window was made (the history, the errors, the map type, the labels) and is there for selecting
windows and for scoring.
## Feature files (`features/`)
All feature files cover the 104,996 train and development windows in one order: feature row r
is window `splits/stages.json["feature_sample_ids"][r]`, and the index gives it as
`feature_row`. NeCast reads 32 of the 64 individuals in a window; which 32 is fixed per window by
a seeded permutation and stored in `features/level32/unphased_evidence_cache.npz` as
`ladder_columns`.
- `registry/` locates every train and development window in the fragment files
(`raw_index.jsonl`), with a byte-exact read-back check for each one.
- `level32/unphased_evidence_cache.npz` holds summary statistics of the 32 individuals:
the folded site frequency spectrum, projected to 32 haplotypes to absorb missing calls
(`folded_sfs_counts`); linkage disequilibrium between sites 1 to 64 sites apart, by genetic
distance (`ld_features`, `ld_pair_counts`, with `ld_bin_edges_morgan` and `ld_lags`);
lengths of identity-by-state tracts between pairs of individuals in 7 kinds and
powers-of-two length classes (`ibs_counts`, `ibs_bin_edges_bp`); a Watterson estimate of the
size level (`nw_log10`), which anchors the network's output; per-window context values
(`context`); and the labels (`targets`). `features` and `coordinates` hold statistics over
32-kb sub-windows that the final network does not read. The network's site encoder reads the
genotypes of the 32 individuals straight from the window files, found through `registry/`.
- `psmcplus_posterior/level32.npz` holds PSMC+ posteriors for the same 32 individuals,
decoded with the window's maps on the 64 intervals. The array is named `sidecar`
(104,996 × 256): columns 0–63 are the mean over individuals of the posterior share of the
window in each interval with a flat prior, 64–127 their standard deviation, and 128–255 the
same after one refit of the prior. `sidecar_present` marks rows with a value.
- `psmcplus_store/shards/` is the PSMC+ output these posteriors were cut from: every window
(reserved ones included), four random sets of individuals, and sample sizes of 1, 2, 4, 8, 16
and 32. Each shard has `sample_id`, `features` (rows, 4 sets, 6 sizes, 256), `flags` (the
number of individuals scored in each pass), `theta_cl` and `bin_cl` (the diversity θ and the
bin size in bp the decoder used) and `meta` (mean mutation rate, mean recombination rate,
number of sites, sequence length, seconds, and four counters). `builder/` has the scripts that made them and
`logs.tar` their logs.
## Additional files (`additional/`)
- `sample_size_levels/` has the summary statistics and PSMC+ posteriors for 1, 2, 4, 8 and 16
individuals (the first individuals of the same permutation). They were built for an earlier
design in which the network read a variable number of individuals; the final network reads 32.
- `psmcplus_converged/` has a PSMC+ posterior whose prior was refitted five times in a row
instead of once, for 13,500 windows: a 12,500-window training subset spread evenly over
variant counts, and the 500 validation and 500 test windows. The scripts and checks that made
it are included.
## Generator (`generator/`)
`generator/code/` is the simulator exactly as it ran (MIT licence), and `corpus_plan.json` the
generation plan: configuration, seeds, and checksums of the maps and templates. The simulator
shipped third-party data files: the deCODE and Roulette maps, the published human histories and
the stdpopsim trajectories. They are not copied here. `generator/EXCLUDED_THIRD_PARTY.tsv` lists
each one with its size, SHA-256 and source. The scripts that build the deCODE map and the
stdpopsim trajectories are in `generator/code/simulator/assets/`, and `generator/roulette_map/`
has the script that averaged the published Roulette rates into the 1-kb map used here.
## Checksums
`sha256sum -c SHA256SUMS` checks every file. The checksums of the window files also match the
receipts written when each file was generated (`windows/receipts.jsonl.gz`).
## Paths in provenance files
Logs, plans and other provenance files were written on the machines that ran the jobs. Absolute paths in them use
placeholders: `$WORK` and `$DATA` for the working directories, `$SW` for installed software and `~` for the home
directory. Checksums recorded inside the files match the released files.
## Licence and sources
The files here are released under CC BY 4.0. Please also cite the sources the windows build on:
- msprime: Baumdicker et al. (2022), *Genetics* 220:iyab229.
- deCODE recombination map: Halldorsson et al. (2019), *Science* 363:eaau1043.
- Roulette mutation rates: Seplyarskiy et al. (2023), *Nature Genetics*.
- Human size histories used as templates: Terhorst, Kamm and Song (2017), *Nature Genetics*
49:303 (SMC++); Terhorst (2025), *Nature Genetics* 57:2570 (phlash); Wang et al. (2020),
*PLOS Genetics* 16:e1008552 (MSMC-IM).
- stdpopsim: Adrion et al. (2020), *eLife* 9:e54967.
- PSMC+: Cousins et al. (2024), *bioRxiv*.
## Citation
The NeCast paper is in preparation; its reference will be added here.