File size: 7,094 Bytes
b7a4ca1 c0764bc b7a4ca1 c0764bc | 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 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 | """Loaders for the package's core data layers.
All loaders accept an optional ``root`` (package root directory). When
omitted, the root is located by walking upward from the current working
directory looking for ``core/basis/basis_registry.json``.
Contracts (docs/DATA_DICTIONARY.md): every matrix is row-aligned to its
sibling ``*_compounds.parquet`` (positional alignment is the join key);
usage column j is program P{j+1} of the pinned basis; gene symbols come
only from the harmonized panel file.
"""
from __future__ import annotations
from pathlib import Path
import numpy as np
import pandas as pd
CONTEXTS = (
"zel024_hek293",
"zel024_h1650",
"zel028_hek293",
"zel028_a549",
"zel028_h1650",
"zel031_a549",
"zel031_thp1",
"zel039_aec7",
)
CONTROL_CONTEXTS = (
"zic008_a549",
"zic008_aec7",
"zic008_h1650",
"zic008_hek293",
"zic008_hek293clone",
)
_ROOT_MARKERS = ("core/basis/basis_registry.json", "core/recipes.parquet")
def find_root(start: str | Path | None = None) -> Path:
"""Locate the package root by walking upward from ``start`` (default:
the current working directory)."""
here = Path(start or Path.cwd()).resolve()
for candidate in (here, *here.parents):
if all((candidate / marker).exists() for marker in _ROOT_MARKERS):
return candidate
raise FileNotFoundError(
"could not locate the package root (no core/basis/basis_registry.json "
"found upward from "
f"{here}); pass root= explicitly")
def _resolve(root: str | Path | None) -> Path:
return Path(root).resolve() if root is not None else find_root()
def _check_context(context: str) -> str:
if context not in CONTEXTS:
raise ValueError(
f"unknown context {context!r}; expected one of {', '.join(CONTEXTS)}")
return context
def load_usages(context: str, root: str | Path | None = None):
"""Return (usages, compounds) for a context: usages is float32
(n_compounds, 32), compounds is the aligned single-column
public_compound_id frame. Row i of the matrix is row i of the frame."""
root = _resolve(root)
_check_context(context)
usages = np.load(root / "core" / "usages" / f"usages_{context}.npy")
compounds = pd.read_parquet(
root / "core" / "usages" / f"usages_{context}_compounds.parquet")
if usages.shape[0] != len(compounds):
raise ValueError(
f"row-alignment broken for {context}: {usages.shape[0]} usage rows "
f"vs {len(compounds)} compound rows")
return usages, compounds
def load_surface(context: str, root: str | Path | None = None):
"""Return (surface, compounds) for a context: surface is float32
(n_compounds, 6000) on the harmonized panel, compounds is the aligned
single-column public_compound_id frame."""
root = _resolve(root)
_check_context(context)
surface = np.load(root / "core" / "surfaces" / f"surfaces_{context}.npy")
compounds = pd.read_parquet(
root / "core" / "surfaces" / f"{context}_compounds.parquet")
if surface.shape[0] != len(compounds):
raise ValueError(
f"row-alignment broken for {context}: {surface.shape[0]} surface rows "
f"vs {len(compounds)} compound rows")
return surface, compounds
def load_basis(k: int = 32, root: str | Path | None = None) -> np.ndarray:
"""Return the pinned shared basis as float32 (k, 6000). k is 32
(shared_program_basis_v1) or 12 (shared_program_basis_k12_v1)."""
root = _resolve(root)
if k not in (12, 32):
raise ValueError("k must be 32 or 12")
return np.load(root / "core" / "basis" / f"shared_basis_k{k}.npy")
def load_recipes(root: str | Path | None = None) -> pd.DataFrame:
"""Return the building-block grammar table: one row per
public_compound_id, columns bb0..bb4 (null = absent position) and
n_positions_occupied."""
root = _resolve(root)
return pd.read_parquet(root / "core" / "recipes.parquet")
def load_folds(root: str | Path | None = None) -> pd.DataFrame:
"""Return fold assignments: context, public_compound_id, fold
(fold = SHA256(public_compound_id) mod 5). Basis and reference model
were fit with fold 0 held out."""
root = _resolve(root)
return pd.read_parquet(root / "core" / "splits" / "fold_assignments.parquet")
def panel_genes(root: str | Path | None = None) -> pd.DataFrame:
"""Return the harmonized 6,000-gene panel definition
(panel_position, gene_index, gene). The only authoritative mapping of
panel columns to gene symbols."""
root = _resolve(root)
return pd.read_parquet(root / "core" / "surfaces" / "harmonized_6000_genes.parquet")
def _check_control_context(context: str) -> str:
if context not in CONTROL_CONTEXTS:
raise ValueError(
f"unknown control context {context!r}; expected one of "
f"{', '.join(CONTROL_CONTEXTS)}")
return context
def load_control_surface(context: str, root: str | Path | None = None):
"""Return (surface, controls) for a control context: surface is
float32 (35, 6000) on the harmonized panel, controls is the aligned
frame (public_compound_id, control_name, n_wells, n_devices,
total_umis). Row i of the matrix is row i of the frame."""
root = _resolve(root)
_check_control_context(context)
surface = np.load(root / "annex_controls" / f"control_surfaces_{context}.npy")
controls = pd.read_parquet(
root / "annex_controls" / f"control_surfaces_{context}_compounds.parquet")
if surface.shape[0] != len(controls):
raise ValueError(
f"row-alignment broken for {context}: {surface.shape[0]} surface rows "
f"vs {len(controls)} control rows")
return surface, controls
def load_control_pseudobulks(context: str, root: str | Path | None = None):
"""Return (counts, pseudobulks) for a control context: counts is
float32 (n_pseudobulks, 6000) summed UMI counts (raw, not
normalized) on the harmonized panel, pseudobulks is the aligned
frame (public_compound_id, control_name, batch_id, n_wells,
total_umis). Normalize as log1p(counts / total_umis * 1e4)."""
root = _resolve(root)
_check_control_context(context)
counts = np.load(
root / "annex_controls" / f"control_pseudobulk_counts_{context}.npy")
pseudobulks = pd.read_parquet(
root / "annex_controls" / f"control_pseudobulks_{context}.parquet")
if counts.shape[0] != len(pseudobulks):
raise ValueError(
f"row-alignment broken for {context}: {counts.shape[0]} count rows "
f"vs {len(pseudobulks)} pseudobulk rows")
return counts, pseudobulks
def load_control_usages(root: str | Path | None = None) -> pd.DataFrame:
"""Return the per-control 32-program usage table (175 rows:
control_context, public_compound_id, control_name, n_wells,
u_P01..u_P32). Column u_P0j is program Pj of the pinned basis."""
root = _resolve(root)
return pd.read_parquet(root / "annex_controls" / "control_usages_k32.parquet")
|