lorapop / code /src /analysis /population.py
bryan7264's picture
Add files using upload-large-folder tool
aaba844 verified
Raw History Blame Contribute Delete
5.72 kB
# MIT License, Bryan Cheng, 2026.
"""Assemble a population: phenotypes, reliabilities, covariates, genotype matrix, relatedness, families, splits
(RESEARCH_PLAN 4.3-4.4, 5, 7.2, 7.7)."""
import glob
import hashlib
import json
import os
from collections import Counter
import numpy as np
import torch
from scipy.cluster.hierarchy import fcluster, linkage
from scipy.sparse.csgraph import connected_components
from scipy.spatial.distance import squareform
from .scan import int_transform
MODTYPES = ["q_proj", "k_proj", "v_proj", "o_proj", "gate_proj", "up_proj", "down_proj"]
def law(r1, r2, d):
return np.sqrt(r1 * r2) / np.sqrt((r1 + 1 + d) * (r2 + 1 + d))
def load_phenotypes(pheno_dir, names):
recs = {}
for n in names:
fn = os.path.join(pheno_dir, n + ".json")
if os.path.exists(fn):
r = json.load(open(fn))
if r.get("status") == "ok":
recs[n] = r
return recs
def reliability(h0, h1):
ok = np.isfinite(h0) & np.isfinite(h1)
if ok.sum() < 10 or np.std(h0[ok]) == 0 or np.std(h1[ok]) == 0:
return np.nan
r = np.corrcoef(h0[ok], h1[ok])[0, 1]
return float(2 * r / (1 + r)) if r > -1 else np.nan
def build(geno_dir, pheno_dir, recipe_threshold=None, q_law=896, loci_file="loci.pt", fam_mult=3.0):
A = json.load(open(os.path.join(geno_dir, "adapters.json")))
names_all, info = A["names"], A["info"]
recs = load_phenotypes(pheno_dir, names_all)
keep = np.array([(n in recs) and not info[n]["flags"].get("dora") for n in names_all])
names = [x for x, k in zip(names_all, keep) if k]
n = len(names)
traits = sorted(set().union(*[set(recs[x]["traits"]) for x in names]))
Y = np.full((3, n, len(traits)), np.nan)
for i, x in enumerate(names):
for j, t in enumerate(traits):
v = recs[x]["traits"].get(t)
if v is not None:
Y[:, i, j] = v
rel = {t: reliability(Y[1, :, j], Y[2, :, j]) for j, t in enumerate(traits)}
Yt = np.stack([int_transform(Y[0, :, j]) for j in range(len(traits))], 1)
# covariates
rmax = np.array([max(info[x]["ranks"]) for x in names], float)
lnorm = np.array([0.5 * np.log(info[x]["sqnorm"]) for x in names])
pats = [tuple(sorted(info[x]["modules"])) for x in names]
top = [p for p, _ in Counter(pats).most_common(9)][1:] # most common pattern is the reference level
Xp = np.array([[float(p == t) for t in top] for p in pats]).reshape(n, len(top))
mts = np.array([float(bool(info[x]["flags"].get("modules_to_save"))) for x in names])
quant = np.array([float(any(s in str(info[x].get("cfg_base") or "").lower() for s in ("bnb", "4bit", "8bit", "awq",
"gptq"))) for x in names])
gpus = sorted({recs[x].get("gpu", "?") for x in names}) # measurement hardware (D-019/D-027): one-hot if mixed
Xg = np.column_stack([[float(recs[x].get("gpu", "?") == g) for x in names] for g in gpus[1:]]) if len(gpus) > 1 \
else np.zeros((n, 0))
X = np.column_stack([np.ones(n), np.log(rmax), lnorm, Xp, mts, quant, Xg])
X = X[:, np.r_[0, 1 + np.where(X[:, 1:].std(0) > 0)[0]]]
# genotypes
loci = torch.load(os.path.join(geno_dir, loci_file))
cols, gl = [], []
for k, v in loci.items():
for l in range(v["n_loci"]):
g = v["g"][keep, l].double().numpy()
cols.append(g - g.mean())
gl.append({"module": k, "l": l, "layer": int(k.split(".")[0]), "type": k.split(".")[1],
"lam": float(v["lam"][l]), "sigma": float(v["g"][:, l].std())})
pres = np.array([[float(any(m == t for m in info[x]["modules"])) for t in MODTYPES] for x in names])
for j, t in enumerate(MODTYPES):
if 0 < pres[:, j].mean() < 1:
cols.append(pres[:, j] - pres[:, j].mean())
gl.append({"module": f"presence.{t}", "l": -1, "layer": -1, "type": t, "lam": np.nan, "sigma": 1.0})
Gm = np.column_stack(cols)
Kz = np.load(os.path.join(geno_dir, "K.npz"))
Kd, Kf = Kz["K_desc"][np.ix_(keep, keep)], Kz["K_func"][np.ix_(keep, keep)]
# descent families: K_desc above fam_mult (3 = plan 5.2; 2 and 5 = sensitivity 14.6) x the same-task law value
thr = fam_mult * law(rmax[:, None], rmax[None, :], q_law)
adj = (Kd > thr) & ~np.eye(n, dtype=bool)
nf, fam_d = connected_components(adj, directed=False)
# recipe families: average linkage on 1 - K_func, cut at recipe_threshold (distance)
if recipe_threshold is None:
recipe_threshold = 1 - np.quantile(Kf[np.triu_indices(n, 1)], 0.99)
Z = linkage(squareform(np.clip(1 - Kf, 0, None), checks=False), method="average")
fam_r = fcluster(Z, t=recipe_threshold, criterion="distance") - 1
authors = [x.split("__")[0] for x in names]
# discovery / estimation split by descent family (RESEARCH_PLAN 7.7)
fams = {}
for i, f in enumerate(fam_d):
fams.setdefault(f, []).append(i)
order = sorted(fams, key=lambda f: hashlib.sha1(min(names[i] for i in fams[f]).encode()).hexdigest())
split = np.zeros(n, int)
cnt = [0, 0]
for f in order:
s = 0 if cnt[0] <= cnt[1] else 1
split[fams[f]] = s
cnt[s] += len(fams[f])
return {"names": names, "gpu": [recs[x].get("gpu", "?") for x in names], "traits": traits, "Y": Y, "Yt": Yt, "rel": rel, "X": X, "G": Gm, "loci": gl,
"K_desc": Kd, "K_func": Kf, "fam_d": fam_d, "fam_r": fam_r, "authors": authors, "split": split,
"rmax": rmax, "recipe_threshold": float(recipe_threshold), "info": {x: info[x] for x in names}}
def neff(K):
return float(np.trace(K) ** 2 / np.sum(K * K))