File size: 4,962 Bytes
ee5b44c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
"""Loader for the frozen stdpopsim single-population trajectories.

These eighteen models, across eight species, are the held-out evaluation set.
They exist so that generalisation can be measured against histories that were
published by other people for other reasons, rather than against our own prior
re-drawn -- which measures nothing.  phlash validates the same way, on twelve
stdpopsim models across eight species.

The trajectories are frozen into ``data/templates/stdpopsim_single_pop`` by
``scripts/build_stdpopsim_single_pop.py`` rather than imported at runtime; the
reasons are in that script's docstring.
"""

from __future__ import annotations

import csv
from dataclasses import dataclass
from functools import lru_cache
from pathlib import Path

import numpy as np

from .assets import asset_path
from .config import NE_LOG10_BOUNDS, Config


DEFAULT_STDPOPSIM_TEMPLATE_PATH = "data/templates/stdpopsim_single_pop/trajectories.csv"

# Models held out of the draw because another recipe produces them.  Empty at
# present: Zigzag_1S14 had a recipe of its own for a while and was excluded here
# so that exactly one code path produced it; that recipe is gone and the model
# is back in the catalogue.  The hand-written published event table stays in
# ``demography.py`` as the independent source this freeze is checked against.
CATALOGUE_EXCLUSIONS: frozenset[str] = frozenset()


@dataclass(frozen=True)
class StdpopsimTemplate:
    species: str
    model_id: str
    population: str
    generation_time_years: float
    breaks: tuple[float, ...]
    values: tuple[float, ...]
    growth_rates: tuple[float, ...]
    ne_rescale: float

    @property
    def key(self) -> str:
        return "%s/%s" % (self.species, self.model_id)


def _fit_to_bounds(values: tuple[float, ...]) -> float:
    """Return the single factor that slides a trajectory into the Ne band.

    Two of the eighteen models -- *Anopheles gambiae* and the Indian
    *M. m. castaneus* -- carry effective sizes above a million, and one Holstein
    model dips below a hundred.  Clipping them would flatten exactly the
    features they are held out to test, so the whole trajectory is multiplied by
    one constant instead: Ne is only identifiable jointly with the mutation
    rate, and a uniform factor leaves the shape -- which is what generalisation
    is being measured on -- bit-for-bit intact.  The factor is recorded so the
    published model can always be recovered.
    """

    low, high = 10.0 ** NE_LOG10_BOUNDS[0], 10.0 ** NE_LOG10_BOUNDS[1]
    smallest, largest = min(values), max(values)
    if largest / smallest > high / low:
        raise ValueError("trajectory spans more than the declared Ne band")
    if largest > high:
        return high / largest
    if smallest < low:
        return low / smallest
    return 1.0


@lru_cache(maxsize=4)
def _load(path: str) -> tuple[StdpopsimTemplate, ...]:
    source = asset_path(path)
    if not source.exists():
        return ()
    grouped: dict[tuple[str, str], list[dict[str, str]]] = {}
    with source.open(newline="") as stream:
        for row in csv.DictReader(stream):
            grouped.setdefault((row["species"], row["model_id"]), []).append(row)

    out: list[StdpopsimTemplate] = []
    for (species, model_id), rows in sorted(grouped.items()):
        rows.sort(key=lambda item: int(item["epoch_index"]))
        starts = [float(item["start_generations_ago"]) for item in rows]
        sizes = tuple(float(item["size"]) for item in rows)
        rates = tuple(float(item["growth_rate_per_generation"]) for item in rows)
        rescale = _fit_to_bounds(sizes)
        out.append(
            StdpopsimTemplate(
                species=species,
                model_id=model_id,
                population=rows[0]["population"],
                generation_time_years=float(rows[0]["generation_time_years"]),
                breaks=tuple(starts[1:]),
                values=tuple(size * rescale for size in sizes),
                growth_rates=rates,
                ne_rescale=float(rescale),
            )
        )
    return tuple(out)


def load_stdpopsim_templates(cfg: Config) -> tuple[StdpopsimTemplate, ...]:
    return _load(str(getattr(cfg, "stdpopsim_template_path", DEFAULT_STDPOPSIM_TEMPLATE_PATH)))


def stdpopsim_templates_available(cfg: Config) -> bool:
    return len(drawable_stdpopsim_templates(cfg)) > 0


def drawable_stdpopsim_templates(cfg: Config) -> tuple[StdpopsimTemplate, ...]:
    """The catalogue minus the models that have a recipe of their own."""

    return tuple(
        template
        for template in load_stdpopsim_templates(cfg)
        if template.model_id not in CATALOGUE_EXCLUSIONS
    )


def choose_stdpopsim_template(
    rng: np.random.Generator, cfg: Config
) -> StdpopsimTemplate | None:
    templates = drawable_stdpopsim_templates(cfg)
    if not templates:
        return None
    return templates[int(rng.integers(0, len(templates)))]