import itertools import numpy as np import pandas as pd from common import RES, SEED, hom, axes, centre TARGET = "YPL270W" MC_REPLICATES = 10 MC_SMALL = 10_000 MC_LARGE = 10_000_000 CHUNK = 500_000 Z = hom() ag, ox, os_, ref = axes(Z.columns) Zc = centre(Z) s = np.concatenate([np.where(ox)[0], np.where(os_)[0]]) v = Zc.loc[TARGET].values[s] lab = ox[s].astype(int) n1, n = int(lab.sum()), len(lab) obs = abs(v[lab == 1].mean() - v[lab == 0].mean()) tot = v.sum() def stat_from_idx(idx): a = v[idx].sum(axis=-1) return np.abs(a / n1 - (tot - a) / (n - n1)) combos = np.array(list(itertools.combinations(range(n), n1))) exact_stats = stat_from_idx(combos) k_exact = int((exact_stats >= obs - 1e-12).sum()) p_exact = k_exact / len(combos) rng = np.random.default_rng(SEED) def mc(B): hits, done = 0, 0 while done < B: b = min(CHUNK, B - done) idx = np.argsort(rng.random((b, n)), axis=1)[:, :n1] hits += int((stat_from_idx(idx) >= obs - 1e-12).sum()) done += b return (hits + 1) / (B + 1) small = [mc(MC_SMALL) for _ in range(MC_REPLICATES)] large = [mc(MC_LARGE) for _ in range(MC_REPLICATES)] agents = list(dict.fromkeys(ag[s])) blocks = [np.where(ag[s] == a)[0] for a in agents] n_ox_agents = len({a for a in agents if ox[s][ag[s] == a][0]}) balanced = [] for chosen in itertools.combinations(range(len(agents)), n_ox_agents): m = np.zeros(n, bool) for c in chosen: m[blocks[c]] = True balanced.append(abs(v[m].mean() - v[~m].mean())) balanced = np.array(balanced) k_bal = int((balanced >= obs - 1e-12).sum()) anyp = [] for assign in itertools.product((0, 1), repeat=len(agents)): if len(set(assign)) < 2: continue m = np.concatenate([[assign[i]] * len(blocks[i]) for i in range(len(agents))]) order = np.concatenate(blocks) vv = v[order] anyp.append(abs(vv[m == 1].mean() - vv[m == 0].mean())) anyp = np.array(anyp) k_any = int((anyp >= obs - 1e-12).sum()) out = pd.DataFrame([ ("condition-level, exact enumeration", len(combos), k_exact, p_exact, np.nan, np.nan), (f"condition-level, Monte Carlo {MC_SMALL:,} x {MC_REPLICATES}", MC_SMALL, np.nan, np.mean(small), min(small), max(small)), (f"condition-level, Monte Carlo {MC_LARGE:,} x {MC_REPLICATES}", MC_LARGE, np.nan, np.mean(large), min(large), max(large)), ("agent-level, exact, design-preserving (3 vs 2 agents)", len(balanced), k_bal, k_bal / len(balanced), np.nan, np.nan), ("agent-level, exact, all bipartitions of 5 agents", len(anyp), k_any, k_any / len(anyp), np.nan, np.nan)], columns=["procedure", "assignments_or_B", "k_extreme", "p", "p_min_replicate", "p_max_replicate"]) out.to_csv(RES / "permutation_mdl2.csv", index=False) pd.DataFrame({"permutations": [MC_SMALL] * MC_REPLICATES + [MC_LARGE] * MC_REPLICATES, "replicate": list(range(1, MC_REPLICATES + 1)) * 2, "p": small + large}).to_csv( RES / "permutation_mdl2_replicates.csv", index=False)