File size: 4,356 Bytes
4c0a8e4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
#!/usr/bin/env python3
"""Flatten every fitted scMPRA model into tidy Parquet for release.

The saved fits are pickles of scMPRAforge.core.parameters objects: they only
load with the package importable, and a pickle is a poor thing to hand a
stranger. Each holds, per stratum, a frame of fitted means, an optional
zero-inflation frame, and a scalar dispersion. Those are tables, so this
writes them as tables.

Two of them, not one. The fitted mean is indexed by the axis the model was
NOT stratified on (a CRE, for a by-cell-type fit), while zero inflation is fit
per replicate. They are indexed by different things and share no levels, so
they cannot sit on the same row.
"""
import json
import pathlib
import pickle
import sys

import pandas as pd

ROOT = pathlib.Path("/nfs/roberts/project/pi_skr2/shared/tabula_data_new")
OUT = pathlib.Path(sys.argv[1] if len(sys.argv) > 1 else "/tmp/hf_stage")
DATASETS = ("shendure", "cohen", "seelig")
AXES = (("cell_type", "by_cell_type_parameters.pkl"),
        ("cre", "by_cre_parameters.pkl"))


def tag(frame, stratum, fit, axis, index_name):
    frame = frame.copy()
    frame["level"] = frame.index.astype(str)
    frame["level_axis"] = index_name or "level"
    frame["stratum"], frame["fit"], frame["stratified_by"] = str(stratum), fit, axis
    return frame.reset_index(drop=True)


def tidy(par, fit, axis):
    """One parameters object -> (mean rows, zero-inflation rows)."""
    means, zis = [], []
    for stratum in par.keys:
        nb, zi, th = par.nb.get(stratum), par.zi.get(stratum), par.theta.get(stratum)
        if nb is not None and len(nb):
            f = tag(nb.rename(columns={nb.columns[0]: "mu"}), stratum, fit,
                    axis, nb.index.name)
            # dispersion is fit once per stratum, so it repeats down one
            f["theta"] = float(th) if th is not None else pd.NA
            means.append(f)
        if isinstance(zi, pd.DataFrame) and len(zi):
            zis.append(tag(zi.rename(columns={zi.columns[0]: "zi"}), stratum,
                           fit, axis, zi.index.name))
    return means, zis


def main():
    OUT.mkdir(parents=True, exist_ok=True)
    means, zeros, manifest = [], [], []
    for ds in DATASETS:
        for d in sorted((ROOT / ds).iterdir()):
            # A symlink here is a fit living on the older data root, not a
            # thing to skip. What marks a directory as raw data rather than a
            # fit is having no ortho_meta.json -- and anything holding
            # parameters without metadata is a problem, not something to pass
            # over quietly, which is how four cohen fits went missing.
            meta_p = d / "ortho_meta.json"
            has_params = any((d / f).is_file() for _, f in AXES)
            if not meta_p.is_file():
                assert not has_params, f"{d} has parameters but no ortho_meta.json"
                continue
            meta = json.loads(meta_p.read_text())
            meta["fit"] = d.name
            for axis, fname in AXES:
                if not (d / fname).is_file():
                    continue
                with open(d / fname, "rb") as fh:
                    m_rows, z_rows = tidy(pickle.load(fh), d.name, axis)
                means.extend(m_rows)
                zeros.extend(z_rows)
            manifest.append(meta)
            print(f"  {d.name:34} ok")

    mean_cols = ["fit", "stratified_by", "stratum", "level_axis", "level", "mu", "theta"]
    zero_cols = ["fit", "stratified_by", "stratum", "level_axis", "level", "zi"]
    tbl = pd.concat(means, ignore_index=True)[mean_cols]
    zt = pd.concat(zeros, ignore_index=True)[zero_cols]
    man = pd.DataFrame(manifest)

    zinb = set(man.loc[man.model_family == "zinb", "fit"])
    missing = zinb - set(zt.fit)
    assert not missing, f"zinb fits with no zero inflation: {sorted(missing)}"
    assert not tbl.mu.isna().any(), "null fitted means"
    assert not tbl.theta.isna().any(), "null dispersions"

    tbl.to_parquet(OUT / "fitted_means.parquet", index=False, compression="zstd")
    zt.to_parquet(OUT / "zero_inflation.parquet", index=False, compression="zstd")
    man.to_csv(OUT / "fits.csv", index=False)
    print(f"\n{len(tbl):,} mean rows, {len(zt):,} zero-inflation rows, "
          f"{len(man)} fits ({int(man.canonical.sum())} canonical)")


if __name__ == "__main__":
    main()