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…

            name, start, end, length = (part.get(k) for k in ("part_name", "start_1based", "end_1based", "length_bp"))
            if (not isinstance(name, str) or not name or name in names
                    or any(type(value) is not int for value in (start, end, length))
                    or length <= 0 or start != cursor or end != start + length - 1
                    or part.get("orientation") not in {"+", "-"}):
                raise ValueError(f"Invalid, duplicate, or noncontiguous construct part: {cid}/{name}")
            names.add(name)
            cursor = end + 1
            if part.get("part_type") == "CDS":
                aa = part.get("translated_aa_sequence")
                if (length % 3 or not isinstance(aa, str) or len(aa) != length // 3
                        or any(x not in CODON_TABLE for x in aa) or "*" in aa[:-1]):
                    raise ValueError(f"Invalid CDS translation metadata: {cid}/{name}")
                if "P2A" in name:
                    if aa != "GSGATNFSLLKQAGDVEENPGP":
                        raise ValueError(f"Reference P2A translation differs: {cid}/{name}")
                else:
                    followed_by_p2a = index + 1 < len(parts) and "P2A" in str(parts[index + 1].get("part_name", ""))
                    if not aa.startswith("M") or aa.endswith("*") == followed_by_p2a:
                        raise ValueError(f"Start/stop codon violates CDS translation order: {cid}/{name}")
        if cursor != total + 1:
            raise ValueError(f"Part ledger does not tile declared total donor length: {cid}")
        for name, orientation, target_prefix in kozak_requirements[cid]:
            selected = [p for p in parts if p["part_name"] == name]
            targets = [p for p in parts if p["part_name"].startswith(target_prefix) and p.get("part_type") == "CDS"]
            if len(selected) != 1 or len(targets) != 1:
                raise ValueError(f"Required Kozak and CDS modules missing/ambiguous: {cid}/{name}")
            kozak, target = selected[0], targets[0]
            dna = "GCCGCCACC" if orientation == "+" else revcomp("GCCGCCACC")
            adjacent = (kozak["end_1based"] + 1 == target["start_1based"] if orientation == "+"
                        else target["end_1based"] + 1 == kozak["start_1based"])
            if (kozak["orientation"] != orientation or kozak["length_bp"] != 9
                    or kozak.get("sha256") != sha256_str(dna) or not adjacent):
                raise ValueError(f"Kozak identity/orientation/CDS adjacency mismatch: {cid}/{name}")
        if tuple(part["part_name"] for part in parts) != required_part_order[cid]:
            return invalid_reference_grammar()
        for part in parts:
            name = part["part_name"]
            expected_type = ("CDS" if "_CDS_" in name else "PROMOTER" if "promoter" in name.lower() or "minp" in name.lower()
                             else "REGULATORY_OR_FLANK")
            expected_orientation = "-" if name.endswith("_antisense") else "+"
            if part.get("part_type") != expected_type or part["orientation"] != expected_orientation:
                return invalid_reference_grammar()
            if name in REFERENCE_REGULATORY_PART_SHA256 and part.get("sha256") != REFERENCE_REGULATORY_PART_SHA256[name]:
                return invalid_reference_grammar()
    source_registry = construct_verification.get("validated_homology_arm_source_registry", {})
    expected_arm_keys = {
        "LOCUS1_ARM1A_TPT2A_BICISTRONIC": ("B2M_HA_L_800bp", "B2M_HA_R_800bp"),
        "LOCUS1_ARM1B_2AFREE_BIDIRECTIONAL_R01": ("B2M_HA_L_600bp", "B2M_HA_R_600bp"),
        "LOCUS3_CXCL10_SERPINB9_TPT2A_PDL1_R01": ("CXCL10_HA_L_600bp_minus", "CXCL10_HA_R_600bp_minus"),
        "LOCUS4_AAVS1_CHS4_455BP_CBX3_A2UCOE_ICASP9_R17": ("AAVS1_HA_L_600bp_minus", "AAVS1_HA_R_600bp_minus"),
    }
    if (not isinstance(source_registry, dict)
            or set(source_registry) != {key for pair in expected_arm_keys.values() for key in pair}):
        raise ValueError("Missing validated homology source registry")
    if sha256_str(json.dumps(source_registry, sort_keys=True, separators=(",", ":"), allow_nan=False)) != REFERENCE_HOMOLOGY_REGISTRY_SHA256:
        return invalid_reference_grammar()

    def _is_contiguous(parts_list: List[Dict[str, Any]]) -> bool:
        if not parts_list:
            return False
        cur = 1
        for p in parts_list:
            s1 = p.get("start_1based")
            e1 = p.get("end_1based")
            ln = p.get("length_bp")
            if type(s1) is not int or type(e1) is not int or type(ln) is not int:
                return False
            if s1 != cur or (e1 - s1 + 1) != ln:
                return False
            cur = e1 + 1
        return True

    def _check_construct_homology_arms(c_obj: Dict[str, Any]) -> Tuple[bool, int]:
        p_list = c_obj.get("part_ledger", [])
        ha_items = [p for p in p_list if "_HA_" in str(p.get("part_name", ""))]
        if len(ha_items) != 2:
            return False, 0
        p_l, p_r = ha_items[0], ha_items[1]
        required_keys = expected_arm_keys[c_obj["construct_id"]]
        if (p_l is not p_list[0] or p_r is not p_list[-1]
                or tuple(p.get("raw_reference_key") for p in (p_l, p_r)) != required_keys
                or tuple(p.get("part_name") for p in (p_l, p_r)) != required_keys
                or any(p.get("orientation") != "+" for p in (p_l, p_r))):
            return False, 0
        seq_ov = 0
        if p_l.get("sha256") and p_l.get("sha256") == p_r.get("sha256"):
            seq_ov = min(int(p_l.get("length_bp", 0)), int(p_r.get("length_bp", 0)))
        for part in (p_l, p_r):
            key = part.get("raw_reference_key")
            pin = source_registry.get(key, {})
            coord = _parse_grch38_coord(str(part.get("source_accession_or_coordinate", "")))
            if (not pin or pin.get("assembly") != "GRCh38" or coord is None
                or coord[1] < 1 or coord[1] > coord[2]
                or (coord[0], coord[1], coord[2], int(coord[3])) != (pin["chrom"], pin["start_1based"], pin["end_1based"], pin["strand"])
                or part.get("sha256") != pin["sequence_sha256"] or part.get("length_bp") != pin["length_bp"]):
                return False, 0
        c_l = _parse_grch38_coord(str(p_l.get("source_accession_or_coordinate", "")))
        c_r = _parse_grch38_coord(str(p_r.get("source_accession_or_coordinate", "")))
        if c_l is None or c_r is None or c_l[0] != c_r[0]:
            return False, max(seq_ov, int(c_obj.get("homology_arm_overlap_bp", 0)))
        coord_ov = max(0, min(c_l[2], c_r[2]) - max(c_l[1], c_r[1]) + 1)
        tot_ov = max(seq_ov, coord_ov, int(c_obj.get("homology_arm_overlap_bp", 0)))
        c_obj["homology_arm_overlap_bp"] = tot_ov
        return (tot_ov == 0), tot_ov

    all_ha_non_overlapping_verified = True
    per_construct_ha_ok: Dict[str, bool] = {}
    for cid_k, c_obj in constructs_by_id.items():
        ha_ok, _ = _check_construct_homology_arms(c_obj)
        per_construct_ha_ok[cid_k] = ha_ok
        if not ha_ok:
            all_ha_non_overlapping_verified = False

    # 1. Validate LOCUS1_ARM1B_2AFREE_BIDIRECTIONAL_R01
    arm1b_constitutive_cd47_verified = False
    arm1b_sense_hlae_verified = False
    if "LOCUS1_ARM1B_2AFREE_BIDIRECTIONAL_R01" in constructs_by_id and per_construct_ha_ok.get("LOCUS1_ARM1B_2AFREE_BIDIRECTIONAL_R01", False):
        parts_1b = constructs_by_id["LOCUS1_ARM1B_2AFREE_BIDIRECTIONAL_R01"].get("part_ledger", [])
        if _is_contiguous(parts_1b) and len(parts_1b) >= 8 and all(p.get("orientation") in ("+", "-") for p in parts_1b):
            cd47_hits = [(idx, p) for idx, p in enumerate(parts_1b) if "CD47" in p.get("part_name", "") and p.get("part_type") == "CDS"]
            eef_hits = [(idx, p) for idx, p in enumerate(parts_1b) if "EEF1A1" in p.get("part_name", "") and p.get("part_type") == "PROMOTER"]
            sv40_hits = [(idx, p) for idx, p in enumerate(parts_1b) if "SV40_late_polyA" in p.get("part_name", "")]
            if cd47_hits and eef_hits and sv40_hits:
                (c_idx, c0), (e_idx, e0), (s_idx, s0) = cd47_hits[0], eef_hits[0], sv40_hits[0]
                # Antisense '-' unit: in + strand donor order, SV40_polyA (s_idx) < CD47_CDS (c_idx) < EEF1A1_promoter (e_idx)
                if (
                    c0.get("orientation") == "-"
                    and e0.get("orientation") == "-"
                    and s0.get("orientation") == "-"
                    and s_idx < c_idx < e_idx
                    and e0["start_1based"] > c0["end_1based"]
                    and s0["end_1based"] < c0["start_1based"]
                ):
                    arm1b_constitutive_cd47_verified = True

            isre_hits = [(idx, p) for idx, p in enumerate(parts_1b) if "5xISRE" in p.get("part_name", "") and p.get("part_type") == "PROMOTER"]
            hlae_hits = [(idx, p) for idx, p in enumerate(parts_1b) if "HLAE" in p.get("part_name", "") and p.get("part_type") == "CDS"]
            bgh_hits = [(idx, p) for idx, p in enumerate(parts_1b) if "bGH_polyA" in p.get("part_name", "")]
            if isre_hits and hlae_hits and bgh_hits:
                (i_idx, i0), (h_idx, h0), (b_idx, b0) = isre_hits[0], hlae_hits[0], bgh_hits[0]
                # Sense '+' unit: in + strand donor order, 5xISRE_promoter (i_idx) < HLAE_CDS (h_idx) < bGH_polyA (b_idx)
                if (
                    i0.get("orientation") == "+"
                    and h0.get("orientation") == "+"
                    and b0.get("orientation") == "+"
                    and i_idx < h_idx < b_idx
                    and i0["end_1based"] < h0["start_1based"]
                    and h0["end_1based"] < b0["start_1based"]
                ):
                    arm1b_sense_hlae_verified = True

    # 2. Validate LOCUS1_ARM1A_TPT2A_BICISTRONIC
    arm1a_bicistronic_verified = False
    if "LOCUS1_ARM1A_TPT2A_BICISTRONIC" in constructs_by_id and per_construct_ha_ok.get("LOCUS1_ARM1A_TPT2A_BICISTRONIC", False):
        parts_1a = constructs_by_id["LOCUS1_ARM1A_TPT2A_BICISTRONIC"].get("part_ledger", [])
        if _is_contiguous(parts_1a):
            eef_1a = [p for p in parts_1a if "EEF1A1" in p.get("part_name", "") and p.get("part_type") == "PROMOTER"]
            hlae_1a = [p for p in parts_1a if "HLAE" in p.get("part_name", "") and p.get("part_type") == "CDS"]
            p2a_1a = [p for p in parts_1a if "P2A" in p.get("part_name", "") and p.get("part_type") == "CDS"]
            cd47_1a = [p for p in parts_1a if "CD47" in p.get("part_name", "") and p.get("part_type") == "CDS"]
            bgh_1a = [p for p in parts_1a if "bGH_polyA" in p.get("part_name", "")]
            if eef_1a and hlae_1a and p2a_1a and cd47_1a and bgh_1a:
                e1, h1, p1, c1, b1 = eef_1a[0], hlae_1a[0], p2a_1a[0], cd47_1a[0], bgh_1a[0]
                p2a_aa = str(p1.get("translated_aa_sequence") or "")
                if (
                    all(x.get("orientation") == "+" for x in (e1, h1, p1, c1, b1))
                    and e1["end_1based"] < h1["start_1based"]
                    and h1["end_1based"] + 1 == p1["start_1based"]
                    and p1["end_1based"] + 1 == c1["start_1based"]
                    and c1["end_1based"] < b1["start_1based"]
                    and p2a_aa.endswith("GDVEENPGP")
                ):
                    arm1a_bicistronic_verified = True

    # 3. Validate LOCUS3_CXCL10_SERPINB9_TPT2A_PDL1_R01
    locus3_bicistronic_verified = False
    if "LOCUS3_CXCL10_SERPINB9_TPT2A_PDL1_R01" in constructs_by_id and per_construct_ha_ok.get("LOCUS3_CXCL10_SERPINB9_TPT2A_PDL1_R01", False):
        parts_l3 = constructs_by_id["LOCUS3_CXCL10_SERPINB9_TPT2A_PDL1_R01"].get("part_ledger", [])
        if _is_contiguous(parts_l3):
            sb9_l3 = [p for p in parts_l3 if "SERPINB9" in p.get("part_name", "") and p.get("part_type") == "CDS"]
            p2a_l3 = [p for p in parts_l3 if "P2A" in p.get("part_name", "") and p.get("part_type") == "CDS"]
            pdl1_l3 = [p for p in parts_l3 if "PDL1" in p.get("part_name", "") and p.get("part_type") == "CDS"]
            bgh_l3 = [p for p in parts_l3 if "bGH_polyA" in p.get("part_name", "")]
            if sb9_l3 and p2a_l3 and pdl1_l3 and bgh_l3:
                s3, p3, d3, b3 = sb9_l3[0], p2a_l3[0], pdl1_l3[0], bgh_l3[0]
                p2a_aa3 = str(p3.get("translated_aa_sequence") or "")
                if (
                    all(x.get("orientation") == "+" for x in (s3, p3, d3, b3))
                    and s3["end_1based"] + 1 == p3["start_1based"]
                    and p3["end_1based"] + 1 == d3["start_1based"]
                    and d3["end_1based"] < b3["start_1based"]
                    and p2a_aa3.endswith("GDVEENPGP")
                ):
                    locus3_bicistronic_verified = True

    # 4. Validate LOCUS4_AAVS1_CHS4_455BP_CBX3_A2UCOE_ICASP9_R17 (including UCOE sequence SHA-256 & AVI alignment)
    locus4_ucoe_icasp9_verified = False
    if "LOCUS4_AAVS1_CHS4_455BP_CBX3_A2UCOE_ICASP9_R17" in constructs_by_id:
        if not per_construct_ha_ok.get("LOCUS4_AAVS1_CHS4_455BP_CBX3_A2UCOE_ICASP9_R17", False):
            locus4_ucoe_icasp9_verified = False
        else:
            parts_l4 = constructs_by_id["LOCUS4_AAVS1_CHS4_455BP_CBX3_A2UCOE_ICASP9_R17"].get("part_ledger", [])
            ucoe_parts = [p for p in parts_l4 if "CBX3_A2UCOE" in str(p.get("part_name", ""))]
            ucoe_audit_obj = construct_verification.get("regulatory_element_audits", {}).get("CBX3_A2UCOE_core_455bp_R17", {})
            expected_ucoe_sha = "6a4a4ad89dc417532b4066c02f8ff660a30706d7e56691e1d376cfb72e79b0d9"
            required_l4 = {
                "iCasp9": [p for p in parts_l4 if "iCasp9" in p.get("part_name", "") and p.get("part_type") == "CDS"],
                "promoter": [p for p in parts_l4 if "EEF1A1" in p.get("part_name", "") and p.get("part_type") == "PROMOTER"],
                "polyA": [p for p in parts_l4 if "SV40_late_polyA" in p.get("part_name", "")],
            }
            if not _is_contiguous(parts_l4) or len(ucoe_parts) != 1 or not ucoe_audit_obj or not all(required_l4.values()):
                locus4_ucoe_icasp9_verified = False
            else:
                u_part = ucoe_parts[0]
                promoter, cds, polya = required_l4["promoter"][0], required_l4["iCasp9"][0], required_l4["polyA"][0]
                locus4_ucoe_icasp9_verified = bool(
                    all(p.get("orientation") == "+" for p in (u_part, promoter, cds, polya))
                    and u_part["end_1based"] < promoter["start_1based"]
                    and promoter["end_1based"] < cds["start_1based"] < polya["start_1based"]
                    and ucoe_audit_obj.get("sequence_sha256") == expected_ucoe_sha
                    and ucoe_audit_obj.get("genomic_coordinates_grch38") == "chr7:26200580-26201034")
                if u_part.get("sha256") != expected_ucoe_sha:
                    locus4_ucoe_icasp9_verified = False
                if ucoe_audit_obj and (
                    ucoe_audit_obj.get("sequence_sha256") != expected_ucoe_sha
                    or ucoe_audit_obj.get("anti_silencing_functional_status") != "PREREGISTERED_PENDING"
                ):
                    locus4_ucoe_icasp9_verified = False

    all_ok = bool(
        all_ha_non_overlapping_verified
        and arm1b_constitutive_cd47_verified
        and arm1b_sense_hlae_verified
        and arm1a_bicistronic_verified
        and locus3_bicistronic_verified
        and locus4_ucoe_icasp9_verified
    )
    return {
        "all_construct_grammars_verified": all_ok,
        "all_construct_grammars_valid": all_ok,
        "all_homology_arms_non_overlapping_verified": all_ha_non_overlapping_verified,
        "construct_grammar_validation_status": "PASS_ALL_CASSETTES_VERIFIED" if all_ok else "INVALID_CONSTRUCT_GRAMMAR_DETECTED",
        "arm1b_constitutive_cd47_verified": arm1b_constitutive_cd47_verified,
        "arm1b_sense_hlae_verified": arm1b_sense_hlae_verified,
        "arm1a_bicistronic_verified": arm1a_bicistronic_verified,
        "locus3_bicistronic_verified": locus3_bicistronic_verified,
        "locus4_ucoe_icasp9_verified": locus4_ucoe_icasp9_verified,
    }