OpenIslet

scripts/rank_islet1_stacks.py

Step 5 & 6: Project Islet-1 Sign-Sensitive, Endpoint-Oriented & Locus-Penalized Evaluator (v0.6.9).

script Release v0.8.0 gen-eb955f8266035aba 638 KB · 42 sections

Use this file in any AI chat (paste-only or attachment-capable):

Download as text (.txt) Download section (.txt)

Pinned raw file: https://openislet.org/files/gen-eb955f8266035aba/scripts/rank_islet1_stacks.py · SHA-256: c05d5fe606219e88…

        "clinical_modality_separation_note": (
            "BPR-12 / Finding 025 strict separation of three distinct clinical records — this scored IS-free grid row "
            "(rank #460/2,160, composite 0.0023) represents ONLY the unedited macrodevice proxy (1): "
            "(1) Vertex VX-264 (NCT05791201): unedited SC-islets inside a channel-array macro-encapsulation device without systemic immunosuppression "
            "(modeled directly by this search-grid combination; sponsor reported missing the Day-90 stimulated C-peptide endpoint and stopped clinical advancement in March 2025, proposing explant analysis without establishing a single mechanism; registry lists active follow-up with no posted results); "
            "(2) Vertex zimislecel / VX-880 (NCT04786262; Reichman et al. 2025 NEJM, PMID:40544428 — UNSCORED in this IS-free grid): naked intraportal infusion of unedited SC-islets "
            "achieving Day-365 insulin independence in 10/12 adult T1D full-dose completers (12/12 HbA1c < 7% and 0 SHEs Days 90-365), but requiring lifelong systemic calcineurin/mTOR/anti-thymocyte immunosuppression outside the IS-free Target Product Profile; "
            "(3) NCT06832410 (UNSCORED registration only): recruiting trial in kidney-transplant recipients already taking systemic IS (estimated n=10, no posted results — registration establishes a planned endpoint only, not clinical efficacy)."
        ),
        "edit_stack_specification": [],
        "counter_evidence_and_residual_risks": [
            "0 genetic edits (K=0); scored strictly as the IS-free unedited macro-encapsulation device proxy (VX-264, NCT05791201, clinical advancement stopped March 2025 after missing Day-90 stimulated C-peptide; active follow-up with no posted results and no single established failure mechanism). Naked intraportal zimislecel / VX-880 under chronic systemic IS (NCT04786262, PMID:40544428) and recruiting kidney-recipient trial NCT06832410 (no posted results) are separate unscored comparators.",
        ],
    },
    {
        "architecture_id": "FLAWED_STACK_CLONAL_STAT1_OR_TYK2_KO_WITH_INDUCIBLE_CHECKPOINTS",
        "name": "Flawed Epistatic Stack: Clonal STAT1-/- Combined with GAS/ISRE-Inducible Checkpoints + G6PC2::iCasp9 (K=4)",
        "matched_combinatorial_search_id": (
            "ALLO_B2M_HLAE_CD47_SWAP_CIITA_KO__AUTO_NONE__"
            "CYTO_STAT1_OR_TYK2_CLONAL_KO_WITH_GAS_IND_PDL1__ER_NONE__"
            "NICHE_NAKED_AVASCULAR_TRANSPLANT__SAF_G6PC2_ENDOGENOUS_ICASP9"
        ),
        "genomic_locus_edit_count_K": 4,
        "base_edit_count_B": 0,
        "edit_stack_specification": [],
        "counter_evidence_and_residual_risks": [
            "Triggers Graveyard 001 (BLOCK): Clonal STAT1 knockout abolishes IFN-gamma/STAT1-mediated induction of GAS/ISRE promoters.",
            "Triggers Graveyard 002 (BLOCK): Lineage-restricted G6PC2::iCasp9 fails to ablate dedifferentiated, teratoma, or SLC18A1+ off-target cells.",
        ],
    },
]


# ---------------------------------------------------------------------------------------------------------------------------------
# Exact-rational algebra for the HIP-Core wet-lab design.  Every multiplier / leverage / VIF reported in the protocol JSON is computed
# here from the run table with `fractions.Fraction` (no floating-point arithmetic and no hand-typed numbers), and is re-derived
# independently by tests/test_design_algebra_exact.py.
# ---------------------------------------------------------------------------------------------------------------------------------
HIP_FACTOR_KEYS = ("X1", "X2", "X3", "X4", "X5", "X6")
HIP_2FI_PAIRS = [(i, j) for i in range(6) for j in range(i + 1, 6)]
HIP_TERM_NAMES = (
    ["I"]
    + list(HIP_FACTOR_KEYS)
    + [f"{HIP_FACTOR_KEYS[i]}:{HIP_FACTOR_KEYS[j]}" for i, j in HIP_2FI_PAIRS]
    + ["stage_block_B"]
)
# Current Scenario A lead genotype: X1 = +1 HLA-E single-chain-trimer knock-in, X2 = +1 constitutive hEF1a-core CD47 package (3' of GSG-P2A in Arm 1A or antisense 2A-free in Arm 1B), X3 = +1 CXCL10 Locus-3 swap;
# TYK2 / TXNIP / RNLS wild type (X4..X6 = -1).
HIP_LEAD_CHASSIS_A_CODED = (1, 1, 1, -1, -1, -1)
HIP_LEAD_CHASSIS_BLOCK = "Tier2_Lead_Chassis_A_Confirmatory_Replicate"


def _hip_frac_text(x: "Fraction") -> str:
    return f"{x.numerator}/{x.denominator} ({float(x):.6f})" if x.denominator != 1 else f"{x.numerator} ({float(x):.6f})"


def _hip_frac_plain(x: "Fraction") -> str:
    return f"{x.numerator}/{x.denominator}" if x.denominator != 1 else str(x.numerator)


def _hip_model_rows(runs: list[dict], include_block: bool = True) -> list[list[int]]:
    if not isinstance(runs, list) or not runs:
        raise ValueError("HIP design requires nonempty run rows")
    rows = []
    for run in runs:
        if not isinstance(run, dict) or not isinstance(run.get("coded_levels"), dict):
            raise ValueError("Each HIP run requires an explicit coded-level mapping")
        levels = [run["coded_levels"].get(k) for k in HIP_FACTOR_KEYS]
        if any(type(level) is not int or level not in (-1, 1) for level in levels):
            raise ValueError("HIP coded factors must be exact integer -1/+1 values")
        if include_block and (type(run.get("stage_block")) is not int or run["stage_block"] not in (0, 1)):
            raise ValueError("HIP stage block must be exact integer 0/1")
        row = [1] + levels + [levels[i] * levels[j] for i, j in HIP_2FI_PAIRS]
        if include_block:
            row.append(int(run["stage_block"]))
        rows.append(row)
    return rows


def _hip_gram(rows: list[list[int]]) -> list[list["Fraction"]]:
    p = len(rows[0])
    gram = [[0] * p for _ in range(p)]
    for row in rows:
        for a in range(p):
            if row[a]:
                for b in range(p):
                    gram[a][b] += row[a] * row[b]
    return [[Fraction(v) for v in r] for r in gram]


def _hip_inverse(matrix: list[list["Fraction"]]) -> list[list["Fraction"]]:
    n = len(matrix)
    aug = [list(row) + [Fraction(int(i == j)) for j in range(n)] for i, row in enumerate(matrix)]
    for col in range(n):
        pivot = next(i for i in range(col, n) if aug[i][col] != 0)  # StopIteration => singular; callers check rank first
        aug[col], aug[pivot] = aug[pivot], aug[col]
        inv_p = 1 / aug[col][col]
        aug[col] = [v * inv_p for v in aug[col]]
        for i in range(n):
            if i != col and aug[i][col] != 0:
                f = aug[i][col]
                aug[i] = [u - f * v for u, v in zip(aug[i], aug[col])]
    return [row[n:] for row in aug]


def _hip_pivot_columns(rows: list[list[int]]) -> list[int]:
    a = [[Fraction(v) for v in r] for r in rows]
    pivots: list[int] = []
    r = 0
    for c in range(len(a[0])):
        p = next((i for i in range(r, len(a)) if a[i][c] != 0), None)
        if p is None:
            continue
        a[r], a[p] = a[p], a[r]
        inv_p = 1 / a[r][c]
        a[r] = [v * inv_p for v in a[r]]
        for i in range(len(a)):
            if i != r and a[i][c] != 0:
                f = a[i][c]
                a[i] = [u - f * v for u, v in zip(a[i], a[r])]
        pivots.append(c)
        r += 1
        if r == len(a):
            break
    return pivots


def _hip_hat_diag(rows: list[list[int]]) -> list["Fraction"]:
    """Diagonal of the column-space projector (valid for rank-deficient matrices through their pivot columns)."""
    pivots = _hip_pivot_columns(rows)
    sub = [[r[c] for c in pivots] for r in rows]
    inv = _hip_inverse(_hip_gram(sub))
    out = []
    for r in sub:
        left = [sum(r[a] * inv[a][b] for a in range(len(r)) if r[a]) for b in range(len(r))]
        out.append(sum(left[b] * r[b] for b in range(len(r))))
    return out


def _hip_design_summary(runs: list[dict]) -> dict:
    """Exact-rational summary of the 22-column genetic model [I, X1..X6, 15 2FIs] and the 23-column model with additive stage block B."""
    n = len(runs)
    x23 = _hip_model_rows(runs, True)
    x22 = [row[:22] for row in x23]
    piv22, piv23 = _hip_pivot_columns(x22), _hip_pivot_columns(x23)
    if len(piv22) != 22 or len(piv23) != 23:
        raise ValueError("Design is not full rank; algebra below would be undefined")
    inv22, inv23 = _hip_inverse(_hip_gram(x22)), _hip_inverse(_hip_gram(x23))

    def centered_vif(rows: list[list[int]], inv: list[list["Fraction"]]) -> list["Fraction"]:
        out = []
        for j in range(len(rows[0])):
            col = [Fraction(r[j]) for r in rows]
            mean = sum(col) / n
            out.append(inv[j][j] * sum((v - mean) ** 2 for v in col))
        return out

    b = [r[22] for r in x23]
    xtb = [sum(x22[i][j] * b[i] for i in range(n)) for j in range(22)]
    ssr = Fraction(sum(v * v for v in b)) - sum(xtb[a] * inv22[a][c] * xtb[c] for a in range(22) for c in range(22))
    mean_b = Fraction(sum(b), n)
    cross = [sum(Fraction(x23[i][j]) * (b[i] - mean_b) for i in range(n)) for j in range(1, 22)]
    tier1_rows = [row[:22] for row, run in zip(x23, runs) if run["block"].startswith("Tier1")]
    hat22 = _hip_hat_diag(x22)
    hat23 = _hip_hat_diag(x23)
    loo_max_main_23 = Fraction(0, 1)
    loo_max_2fi_23 = Fraction(0, 1)
    loo_max_b_23 = Fraction(0, 1)
    for i_row, r_i in enumerate(x23):
        h_i = hat23[i_row]
        if h_i < 1:
            denom = Fraction(1, 1) - h_i
            v_i = [sum(inv23[a][c] * r_i[c] for c in range(23) if r_i[c]) for a in range(23)]
            diag_loo = [inv23[a][a] + (v_i[a] * v_i[a]) / denom for a in range(23)]
            loo_max_main_23 = max(loo_max_main_23, max(diag_loo[1:7]))
            loo_max_2fi_23 = max(loo_max_2fi_23, max(diag_loo[7:22]))
            loo_max_b_23 = max(loo_max_b_23, diag_loo[22])
    loo_min_ssr_b_23 = Fraction(1, 1) / loo_max_b_23 if loo_max_b_23 > 0 else Fraction(0, 1)
    return {
        "n": n,
        "rank22": len(piv22),
        "rank23": len(piv23),
        "rank_tier1_22": len(_hip_pivot_columns(tier1_rows)),
        "rank29_with_stage_by_main": len(_hip_pivot_columns([row + [row[22] * row[k] for k in range(1, 7)] for row in x23])),
        "inv22": inv22,
        "inv23": inv23,
        "diag22": [inv22[i][i] for i in range(22)],
        "diag23": [inv23[i][i] for i in range(23)],
        "vif23": centered_vif(x23, inv23),
        "hat22": hat22,
        "hat23": hat23,
        "ssr": ssr,
        "mean_b": mean_b,
        "cross": cross,
        "loo_max_main_23": loo_max_main_23,
        "loo_max_2fi_23": loo_max_2fi_23,
        "loo_max_b_23": loo_max_b_23,
        "loo_min_ssr_b_23": loo_min_ssr_b_23,
        # c = (X'X)^-1 X'B: least-squares coefficients of B on the 22 genetic columns; Var_23(b_k) = Var_22(b_k) + c_k^2 / SSR
        "proj_coef": [sum(inv22[a][d] * xtb[d] for d in range(22)) for a in range(22)],
    }


def _hip_prediction_variance(inv23: list[list["Fraction"]], levels: tuple, stage: int) -> "Fraction":
    row = [1] + list(levels) + [levels[i] * levels[j] for i, j in HIP_2FI_PAIRS] + [stage]
    return sum(row[a] * inv23[a][c] * row[c] for a in range(23) for c in range(23))


def _hip_leverage_groups(run_numbers: list[int], hat: list["Fraction"]) -> list[dict]:
    groups: dict = {}
    for rn, h in zip(run_numbers, hat):
        groups.setdefault(h, []).append(rn)
    return [
        {"h_ii": _hip_frac_text(h), "h_ii_rational": _hip_frac_plain(h), "h_ii_float": round(float(h), 6), "n_runs": len(rns), "runs": rns}
        for h, rns in sorted(groups.items(), key=lambda kv: -kv[0])
    ]


def _hip_main_effect_block(summary: dict) -> dict:
    out = {}
    for k, key in enumerate(HIP_FACTOR_KEYS, start=1):
        v22, v23 = summary["diag22"][k], summary["diag23"][k]
        out[key] = {
            "var_22col": _hip_frac_text(v22),
            "var_23col": _hip_frac_text(v23),
            "block_inflation_pct": round(float((v23 / v22 - 1) * 100), 4),
            "centered_vif_23col": round(float(summary["vif23"][k]), 6),
        }
    return out


def _hip_protocol_algebra_fields(runs: list[dict]) -> dict:
    """Return every design-algebra field of the HIP-Core protocol dict, computed from `runs` (exact rationals)."""
    n = len(runs)
    run_numbers = [r["run_number"] for r in runs]
    s = _hip_design_summary(runs)
    base_runs = [r for r in runs if r["block"] != HIP_LEAD_CHASSIS_BLOCK]
    s_base = _hip_design_summary(base_runs)
    extra = []
    for rn in (3, 14):
        src = next(r for r in runs if r["run_number"] == rn)
        extra.append({"coded_levels": src["coded_levels"], "stage_block": 1, "block": "Tier2_InterStage_Bridge_Control_Optional", "run_number": 1000 + rn})
    s_up = _hip_design_summary(runs + extra)
    extra_3_13 = [
        {"coded_levels": next(r for r in runs if r["run_number"] == rn)["coded_levels"], "stage_block": 1, "block": "Tier2_InterStage_Bridge_Control_Optional", "run_number": 1100 + rn}
        for rn in (3, 13)
    ]
    s_up_3_13 = _hip_design_summary(runs + extra_3_13)
    extra_5_11 = [
        {"coded_levels": next(r for r in runs if r["run_number"] == rn)["coded_levels"], "stage_block": 1, "block": "Tier2_InterStage_Bridge_Control_Optional", "run_number": 1200 + rn}