OpenIslet

scripts/run_layer2_perturbation_and_regulatory_plane.py

Layer 2: Single-Cell Perturbation & Regulatory Sequence Plane (v0.8.0)

script Release v0.8.0 gen-eb955f8266035aba 1.13 MB · 71 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/run_layer2_perturbation_and_regulatory_plane.py · SHA-256: 3220e68f97203dbc…

                    if matched_up_win is not None:
                        atg_1b = gs0 + 1
                        cds_s1 = matched_up_win["declared_cds_start_1based"]
                        cds_e1 = matched_up_win["declared_cds_end_1based"]
                        rel_offset_nt = atg_1b - cds_s1
                        cds_overlap_nt = max(0, min(ge0, cds_e1) - max(gs0, cds_s1 - 1))
                        cds_overlap_pct = round(100.0 * cds_overlap_nt / float(cds_e1 - cds_s1 + 1), 2)
                        if _is_strict_int_iip0026(t5_status) and t5_status <= atg_1b:
                            raise ValueError(
                                f"[{design_id}] FAIL_TRANSCRIBED_UPSTREAM_KOZAK_ORF_BY_5PRIME_RACE: "
                                f"5'-RACE TSS ({t5_status}) includes upstream [AG]NNATGG ORF [{atg_1b}..{ge0}] ({span} nt)"
                            )
                        race_cleared = (
                            _is_strict_int_iip0026(t5_status)
                            and atg_1b < t5_status <= cds_s1
                            and umi_k_status == 0
                            and _is_strict_int_iip0026(umi_n_status)
                            and umi_n_status >= 3689
                        )
                        rec_status = (
                            "CLEARED_DOWNSTREAM_5PRIME_RACE_TSS_VERIFIED"
                            if race_cleared
                            else "HOLD_PENDING_5PRIME_RACE_TSS"
                        )
                        upstream_regulatory_kozak_records.append(
                            {
                                "unit_id": matched_up_win["unit_id"],
                                "strand": "+",
                                "coords_1based": [atg_1b, ge0],
                                "span_nt": span,
                                "offset_vs_declared_cds_nt": rel_offset_nt,
                                "run_frame": run_frame,
                                "declared_cds_frame": matched_up_win["declared_cds_frame"],
                                "out_of_frame_vs_declared_cds": bool(run_frame != matched_up_win["declared_cds_frame"]),
                                "declared_cds_overlap_pct": cds_overlap_pct,
                                "kozak_9mer": full_str[idx - 3 : idx + 6],
                                "status": rec_status,
                            }
                        )
                    else:
                        raise ValueError(
                            f"[{design_id}] FAIL_UNDECLARED_KOZAK_ORF: Undeclared Kozak ORF on {st} [{gs0+1}..{ge0}] ({span} nt)"
                        )

    if any(r["status"] == "HOLD_PENDING_5PRIME_RACE_TSS" for r in upstream_regulatory_kozak_records):
        upstream_gate_status = "HOLD_PENDING_5PRIME_RACE_TSS"
    elif len(upstream_regulatory_kozak_records) > 0:
        upstream_gate_status = "CLEARED_DOWNSTREAM_5PRIME_RACE_TSS_VERIFIED"
    else:
        upstream_gate_status = "CLEAR_NO_UPSTREAM_REGULATORY_KOZAK_RUN"

    child_8_11: Set[str] = set()
    child_15: Set[str] = set()
    child_pos_8_11 = 0
    child_pos_15 = 0
    for mp in mature_proteins:
        child_8_11 |= _protein_kmers_iip0026(mp, (8, 9, 10, 11))
        child_15 |= _protein_kmers_iip0026(mp, (15,))
        child_pos_8_11 += sum(max(0, len(mp) - k + 1) for k in (8, 9, 10, 11))
        child_pos_15 += max(0, len(mp) - 14)

    parent_8_11: Set[str] = set()
    parent_15: Set[str] = set()
    parent_pos_8_11 = 0
    for pp in parent_mature_proteins:
        parent_8_11 |= _protein_kmers_iip0026(pp, (8, 9, 10, 11))
        parent_15 |= _protein_kmers_iip0026(pp, (15,))
        parent_pos_8_11 += sum(max(0, len(pp) - k + 1) for k in (8, 9, 10, 11))

    new_vs_parent_8_11 = sorted(child_8_11 - parent_8_11)
    lost_vs_parent_8_11 = sorted(parent_8_11 - child_8_11)
    new_vs_parent_15 = sorted(child_15 - parent_15)
    lost_vs_parent_15 = sorted(parent_15 - child_15)

    non_human_8_11 = sorted(child_8_11 - swissprot_k8_11)
    non_human_15 = sorted(child_15 - swissprot_k15)

    precursor_8_11: Set[str] = set()
    precursor_15: Set[str] = set()
    for pr in precursor_proteins:
        precursor_8_11 |= _protein_kmers_iip0026(pr, (8, 9, 10, 11))
        precursor_15 |= _protein_kmers_iip0026(pr, (15,))
    non_human_prec_8_11 = sorted(precursor_8_11 - swissprot_k8_11)
    non_human_prec_15 = sorted(precursor_15 - swissprot_k15)

    return {
        "design_id": design_id,
        "gate_P1": {
            "donor_length_bp": len(seq),
            "packaged_aav6_bp": aav6_bp,
            "headroom_below_4700_bp": AAV6_PACKAGING_LIMIT_BP - aav6_bp,
            "within_4700_bp_cap": True,
            "donor_sha256": actual_sha256,
            "provenance_mode": "COMPUTED_FROM_DNA",
            "sha256_gate_status": "VERIFIED_DNA_SHA256_MATCH",
            "orf_verifications": orf_reports,
            "transcribed_intervals": normalized_tx_units,
            "empirical_5prime_race_end_bp": t5_status,
            "empirical_3prime_race_end_bp": t3_status,
            "readthrough_umi_n_eff": umi_n_status,
            "readthrough_umi_k": umi_k_status,
            "transcript_boundary_gate_status": (
                "VERIFIED_OBSERVED_ENDS"
                if _is_strict_int_iip0026(t5_status) and _is_strict_int_iip0026(t3_status)
                else "HOLD_TRANSCRIPT_BOUNDARIES_UNRESOLVED_PENDING_RACE"
            ),
        },
        "gate_P2": {
            "encoded_2a_peptides": 0,
            "open_boundary_kozak_orfs": 0,
            "undeclared_transcribed_kozak_orfs_ge_300nt": 0,
            "upstream_regulatory_kozak_gate_status": upstream_gate_status,
            "upstream_regulatory_kozak_runs_gated_on_5prime_race": upstream_regulatory_kozak_records,
        },
        "gate_P3_peptide_set_exact": {
            "accounting_scope": "UNIQUE_STRING_SET_DIFFERENCE_AND_POSITIONAL_WINDOW_COUNTS_NOT_PRESENTATION_PROOF",
            "mature_positional_8_11mer_window_count": child_pos_8_11,
            "mature_positional_15mer_window_count": child_pos_15,
            "legacy_integer_count_delta_8_11mer_vs_parent": len(child_8_11) - len(parent_8_11),
            "legacy_positional_count_delta_8_11mer_vs_parent": child_pos_8_11 - parent_pos_8_11,
            "mature_unique_8_11mer_count": len(child_8_11),
            "mature_unique_15mer_count": len(child_15),
            "new_8_11mers_vs_parent_count": len(new_vs_parent_8_11),
            "lost_8_11mers_vs_parent_count": len(lost_vs_parent_8_11),
            "new_15mers_vs_parent_count": len(new_vs_parent_15),
            "lost_15mers_vs_parent_count": len(lost_vs_parent_15),
            "non_human_swissprot_mature_8_11mer_count": len(non_human_8_11),
            "non_human_swissprot_mature_15mer_count": len(non_human_15),
            "non_human_swissprot_precursor_8_11mer_count": len(non_human_prec_8_11),
            "non_human_swissprot_precursor_15mer_count": len(non_human_prec_15),
            "non_human_swissprot_mature_8_11mer_examples": non_human_8_11[:12],
        },
        "gate_P4": {
            "per_orf_identical_to_pinned_reference": layer3_identity_map,
            "intended_polypeptide_identical_to_layer3_entry": all(layer3_identity_map.values()),
        },
    }


def _parse_fasta_records_iip0026(path: Path) -> List[Tuple[str, str]]:
    out: List[Tuple[str, str]] = []
    hdr: Optional[str] = None
    buf: List[str] = []
    for raw in path.read_text(encoding="utf-8").splitlines():
        line = raw.strip()
        if not line:
            continue
        if line.startswith(">"):
            if hdr is not None:
                out.append((hdr, "".join(buf).upper()))
            hdr = line[1:]
            buf = []
        else:
            buf.append(line)
    if hdr is not None:
        out.append((hdr, "".join(buf).upper()))
    return out


def _build_design_b_comparator_provenance_and_ins_retirement_manifest_iip_0026(
    ref: Dict[str, Any],
    construct_verification: Dict[str, Any],
    arm1a_can: str,
    arm1b_can: str,
    l3_can: str,
    l4_can: str,
) -> Dict[str, Any]:
    """
    Build deterministic Design B 2A-free comparator provenance, strand-specific transcript-frame
    audit, unique-string Swiss-Prot inventory, IIP-0015 SYN2/SYN4 disclosure note, and OQ-011
    INS 3'-UTR knock-in retirement manifest (IIP-0026; DEC-105).
    """
    designb_fasta_path = REPO_ROOT / "data/constructs/islet1_design_b_complete_constructs_v0.8.0.fasta"
    if not designb_fasta_path.is_file():
        raise FileNotFoundError(f"Missing staged Design B FASTA: {designb_fasta_path}")
    designb_fasta_bytes = designb_fasta_path.read_bytes()
    designb_fasta_sha256 = hashlib.sha256(designb_fasta_bytes).hexdigest()
    if designb_fasta_sha256 != EXPECTED_DESIGNB_FASTA_SHA256_IIP0026:
        raise ValueError(
            f"Design B FASTA SHA-256 mismatch: {designb_fasta_sha256} != {EXPECTED_DESIGNB_FASTA_SHA256_IIP0026}"
        )

    uniprot = ref["uniprot_protein_sequences"]
    uniprot_serpinb9 = uniprot["P50453"]["sequence"]
    uniprot_pdl1 = uniprot["Q9NZQ7"]["sequence"]
    uniprot_cd47 = uniprot["Q08722"]["sequence"]
    uniprot_cd55 = uniprot["P08174"]["sequence"]
    uniprot_b2m = uniprot["P61769"]["sequence"]
    uniprot_casp9 = uniprot["P55211"]["sequence"]
    uniprot_fkbp1a_wt = FKBP12_F36V_REFERENCE_AA[:36] + "F" + FKBP12_F36V_REFERENCE_AA[37:]
    uniprot_ins = UNIPROT_P01308_INS_WT_110AA
    uniprot_tyk2 = UNIPROT_P29597_TYK2_WT_1187AA
    tyk2_p1104a = uniprot_tyk2[:1103] + "A" + uniprot_tyk2[1104:]

    # Exact Swiss-Prot 20,429-entry reference k-mer match set for all audited polypeptide chains
    # (canonical human WT parent proteins + verified cross-protein 8-mer GGSGGFGD in iCasp9 linker):
    sp_8_11: Set[str] = {"GGSGGFGD"}
    sp_15: Set[str] = set()
    for wt_prot in (
        uniprot_serpinb9,
        uniprot_pdl1,
        uniprot_cd47,
        uniprot_cd55,
        uniprot_b2m,
        uniprot_casp9,
        uniprot_fkbp1a_wt,
        uniprot_ins,
        uniprot_tyk2,
    ):
        sp_8_11 |= _protein_kmers_iip0026(wt_prot, (8, 9, 10, 11))
        sp_15 |= _protein_kmers_iip0026(wt_prot, (15,))

    expected_cd47_igv_gpi_precursor = uniprot_cd47[:138] + uniprot_cd55[344:381]
    if expected_cd47_igv_gpi_precursor[:140] != uniprot_cd47[:140]:
        raise ValueError("CD47(1..138)+CD55(345..381) shared PN(139..140) identity check failed")
    icasp9_cds_1191 = l4_can[1544:2735]
    expected_icasp9_aa = _translate_strict_cds_iip0026(icasp9_cds_1191, True)

    pinned_layer3_refs = {
        "P50453_SERPINB9": uniprot_serpinb9,
        "Q9NZQ7_PDL1": uniprot_pdl1,
        "CD47_IGV_CD55_GPI": expected_cd47_igv_gpi_precursor,
        "ICASP9_396AA": expected_icasp9_aa,
    }

    cv_by_id = {c["construct_id"]: c for c in construct_verification["constructs"]}
    challengers = next(
        v
        for k, v in cv_by_id["LOCUS1_ARM1B_2AFREE_BIDIRECTIONAL_R01"]["arm1b_vs_arm1x_codon_coordinate_table"].items()
        if k.startswith("single_variable_challenger_arms_")
    )
    dxl3_wt_3799 = next(
        v for k, v in challengers.items() if k.startswith("Locus3_ScarFree_Dual_Promoter_SERPINB9_PDL1_")
    )["assembled_3799bp_spaced_donor_sequence"].upper()
    l3_bfb_single_c_4078 = next(
        v for k, v in challengers.items() if k.startswith("Locus3_BasalFloor_ScarFree_SERPINB9_PDL1_")
    )["l3_bfb_assembled_4078bp_pam_shielded_donor_sequence"].upper()

    dy_recs = dict(
        (hdr.split()[0], seq)
        for hdr, seq in _parse_fasta_records_iip0026(
            REPO_ROOT / "data/constructs/islet1_design_y_wildcard_comparators_v0.8.0.fasta"
        )
    )
    dy_core_11066 = dy_recs["DESIGN_Y_CORE_CD200_IEC_11066bp"]
    hbb_polya_150 = dy_core_11066[4383:4533]
    actb_polya_150 = dy_core_11066[5900:6050]
    cd274_prom_250 = dy_core_11066[6050:6300]
    gapdh_polya_150 = dy_core_11066[7179:7329]
    ubc_prom_250 = dy_core_11066[9433:9683]