OpenIslet

scripts/verify_iip0058_armz_ensc_isletsort_v2_and_2p24_portfolio.py

Provisional IIP-0058 / DEC-139 / GATE-37 / GY-036 (Round-14 Blueprint Alignment; staged in iip0058/):

script Release v0.8.0 gen-eb955f8266035aba 837 KB · 62 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/verify_iip0058_armz_ensc_isletsort_v2_and_2p24_portfolio.py · SHA-256: 33439d619c00fcc3…

        "SB-431542",
        "SB-505124",
        "RepSox",
        "LY364947",
        "GW788388",
        "Galunisertib",
        "LY2157299",
        "Vactosertib",
        "TEW-7197",
        "PF-06952229",
        "ALK5i-II",
        "SD-208",
        "EW-7197",
        "IN-1130",
    ],
    "prohibited_alk5_tgfbr1_aliases": [
        "A77-01",
        "SB-525334",
        "E-616452",
        "LY2109761",
        "LY580276",
        "R-268712",
        "SM16",
        "D4476",
        "ALK5i",
        "ALK5i-2",
        "ALK5-inhibitor",
        "ALK5-inhibitor-II",
        "TGFBR1i",
        "TGFBRi",
        "TGFBR1-inhibitor",
        "TGFbetaRI-inhibitor",
    ],
    "allowed_concrete_reagents": {
        "Betacellulin": {"aliases": ["Betacellulin", "BTC"], "target_class": "EGFR_ERBB4_ISLET_GROWTH_FACTOR"},
        "Nicotinamide": {"aliases": ["Nicotinamide", "NAM"], "target_class": "NAD_PRECURSOR_MATURATION_COFACTOR"},
        "DEC1-entrainer": {"aliases": ["DEC1-entrainer", "DEC1_entrainer", "Dexamethasone"], "target_class": "DEC1_CIRCADIAN_ENTRAINMENT_PMID41385368"},
        "T3": {"aliases": ["T3", "Triiodothyronine"], "target_class": "THYROID_HORMONE_RECEPTOR_AGONIST"},
        "WY14643": {"aliases": ["WY14643", "WY-14643", "Pirinixic-acid"], "target_class": "PPARA_AGONIST_PMID41372150"},
        "N-acetylcysteine": {"aliases": ["N-acetylcysteine", "NAC"], "target_class": "ANTIOXIDANT_GLUTATHIONE_PRECURSOR"},
        "Trolox": {"aliases": ["Trolox"], "target_class": "VITAMIN_E_ANTIOXIDANT"},
        "R428": {"aliases": ["R428", "Bemcentinib"], "target_class": "AXL_INHIBITOR"},
        "LDN-193189": {"aliases": ["LDN-193189", "LDN193189"], "target_class": "BMP_TYPE_I_ALK2_ALK3_INHIBITOR"},
        "Sant-1": {"aliases": ["Sant-1", "SANT1"], "target_class": "SMO_HEDGEHOG_ANTAGONIST"},
        "XXi": {"aliases": ["XXi", "GSI-XX", "DBZ"], "target_class": "GAMMA_SECRETASE_NOTCH_INHIBITOR"},
        "ISX9": {"aliases": ["ISX9", "ISX-9"], "target_class": "STAGE4_NKX61_INDUCER_PMID42962661"},
        "TEPP-46": {"aliases": ["TEPP-46", "TEPP46", "ML265"], "target_class": "PKM2_ALLOSTERIC_AGONIST_NON_ALK5I_NOT_LIN2025_PKM1_OVEREXPRESSION"},
        "SU6656": {"aliases": ["SU6656", "SU-6656"], "target_class": "GEO_GSM8880337_ZINC_TRANSPORT_AMPK_MODULATOR_PMID41932324"},
        "TPEN": {"aliases": ["TPEN"], "target_class": "ZINC_CHELATOR_NON_ALK5I_COMPARATOR"},
        "ZnSO4": {"aliases": ["ZnSO4", "Zinc-sulfate"], "target_class": "TRACE_MINERAL_COFACTOR"},
        "Heparin": {"aliases": ["Heparin"], "target_class": "GLYCOSAMINOGLYCAN_STABILIZER"},
        "ZM447439": {"aliases": ["ZM447439"], "target_class": "AURORA_KINASE_ANTIPROLIFERATIVE"},
        "CMRL-1066": {"aliases": ["CMRL-1066", "CMRL1066"], "target_class": "BASAL_MEDIA_COMPONENT"},
        "MCDB-131": {"aliases": ["MCDB-131", "MCDB131"], "target_class": "BASAL_MEDIA_COMPONENT"},
        "BSA": {"aliases": ["BSA"], "target_class": "BASAL_MEDIA_COMPONENT"},
        "HSA": {"aliases": ["HSA"], "target_class": "BASAL_MEDIA_COMPONENT"},
        "GlutaMAX": {"aliases": ["GlutaMAX"], "target_class": "BASAL_MEDIA_COMPONENT"},
        "B27": {"aliases": ["B27", "B-27"], "target_class": "BASAL_MEDIA_COMPONENT"},
    },
    "rejected_generic_class_labels": [
        "PKM1 activator",
        "PKM1-activator",
        "PKM2 activator",
        "ZnT-inhibitor",
        "ZnT_inhibitor",
        "ZnT8-inhibitor",
        "zinc-transport-inhibitor",
        "circadian-entrainment-pulse",
        "small molecule",
        "maturation factor",
        "growth factor",
        "kinase inhibitor",
        "ALK inhibitor",
    ],
}


def _norm_token(s: str) -> str:
    return re.sub(r"[^a-z0-9]", "", s.lower())


_PROHIBITED_ALK5_TGFBR1_INHIBITOR_REGISTRY: dict[str, str] = {
    _norm_token(name): "ALK5_TGFBR1_INHIBITOR"
    for name in (
        list(ENSC_TERMINAL_REAGENT_REGISTRY_V2["prohibited_alk5_tgfbr1_inhibitors_15"])
        + list(ENSC_TERMINAL_REAGENT_REGISTRY_V2["prohibited_alk5_tgfbr1_aliases"])
    )
}
_GOVERNED_NON_ALK5I_TERMINAL_REAGENT_ALLOWLIST: dict[str, tuple[str, str]] = {}
for _canon_id, _meta in ENSC_TERMINAL_REAGENT_REGISTRY_V2["allowed_concrete_reagents"].items():
    for _alias in [_canon_id] + list(_meta["aliases"]):
        _GOVERNED_NON_ALK5I_TERMINAL_REAGENT_ALLOWLIST[_norm_token(_alias)] = (_canon_id, str(_meta["target_class"]))
_REJECTED_GENERIC_REAGENT_CLASS_LABELS: FrozenSet[str] = frozenset(
    _norm_token(lbl) for lbl in ENSC_TERMINAL_REAGENT_REGISTRY_V2["rejected_generic_class_labels"]
)
_GY030_FIVE_LINEAGES = frozenset({"beta", "alpha", "delta", "plvap_iec", "pericyte"})
_GATE0V_BANK_ONLY_DECISIONS = frozenset({"PASS_WHOLEGRAFT_BANK_QUALIFICATION", "PASS_COMPOSITE_BANK_QUALIFICATION"})
_GATE0V_CLINICAL_DECISIONS = frozenset({"PASS_WHOLEGRAFT_LOT_RELEASE_SURROGATE", "PASS_COMPOSITE_CLINICAL_RELEASE"})
_GATE34_CLINICAL_DECISIONS = frozenset({"PASS", "PASS_GATE34_CLINICAL_LOT_RELEASE", "PASS_GATE34_CLINICAL_PROMOTION"})
_GATE34_BANK_ONLY_DECISIONS = frozenset({"PASS_GATE34_BANK_QUALIFICATION", "STAGE_LIMITED_BANK_QUALIFIED"})
_GATE5_PASS_DECISIONS = frozenset({"PASS_GATE5_OQ012_CLONOGENIC_ERADICATION", "PASS_GATE5_OQ012", "PASS"})
_MAX_SAFE_INT_COUNT = 10**18


def _to_exact_decimal(v: Any) -> Optional[Decimal]:
    """Convert strict finite int/float/Decimal (never bool) to exact Decimal."""
    if isinstance(v, bool):
        return None
    if isinstance(v, Decimal):
        return v if v.is_finite() else None
    if isinstance(v, int):
        if abs(v) > _MAX_SAFE_INT_COUNT:
            return None
        return Decimal(v)
    if isinstance(v, float):
        if not math.isfinite(v):
            return None
        return Decimal(str(v))
    return None


def _is_num(v: Any) -> bool:
    if isinstance(v, bool) or not isinstance(v, (int, float)):
        return False
    try:
        fv = float(v)
    except (OverflowError, ValueError):
        return False
    return math.isfinite(fv)


def _is_strict_int(v: Any) -> bool:
    return isinstance(v, int) and not isinstance(v, bool) and abs(v) <= _MAX_SAFE_INT_COUNT


def _is_strict_bool(v: Any) -> bool:
    return isinstance(v, bool)


def _is_nonempty_str(v: Any) -> bool:
    return isinstance(v, str) and bool(v.strip())


CANONICAL_ID_RE = re.compile(r"^[A-Za-z0-9][A-Za-z0-9._:-]{0,63}$")
CANONICAL_COMPOSITE_RECORD_ID_RE = re.compile(r"^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$")
_UNICODE_DASH_TRANSLATION = str.maketrans({
    "\u2010": "-",
    "\u2011": "-",
    "\u2012": "-",
    "\u2013": "-",
    "\u2014": "-",
    "\u2015": "-",
    "\u2212": "-",
    "\ufe58": "-",
    "\ufe63": "-",
    "\uff0d": "-",
})


def _is_canonical_id(v: Any, *, allow_composite_record_id: bool = False) -> bool:
    """Enforce ONE strict ASCII canonical identifier grammar across all Gate 35 evaluators (Audit R7-04).

    Valid iff:
      - isinstance(v, str) and v.isascii()
      - unicodedata.normalize("NFKC", v) == v
      - all(unicodedata.category(ch)[0] not in ("C", "Z", "M") for ch in v)
      - CANONICAL_ID_RE.fullmatch(v) is not None  (^[A-Za-z0-9][A-Za-z0-9._:-]{0,63}$), or
        CANONICAL_COMPOSITE_RECORD_ID_RE (max 128 chars) strictly for composite `record_id` keys
        joining gate:product_id:lot_id:bank_id (e.g., W6-C1 default Gate 32 Arm Z receipt).
    Rejects EVERY Unicode formatting char (Cf: soft hyphen U+00AD, word joiner U+2060,
    ZWSP/ZWNJ/ZWJ/LRM/RLM U+200B-U+200F, BOM U+FEFF, bidi overrides U+202A-U+202E,
    variation selectors U+FE00-U+FE0F, tags U+E0000-U+E007F), ALL Unicode spaces (Z*),
    ALL control chars (C*), ALL combining marks (M*), ALL fullwidth/NFKC lookalikes,
    and ALL non-ASCII hyphens/punctuation.
    """
    if not isinstance(v, str) or not v:
        return False
    if not v.isascii():
        return False
    if unicodedata.normalize("NFKC", v) != v:
        return False
    for ch in v:
        if unicodedata.category(ch)[0] in ("C", "Z", "M"):
            return False
    pat = CANONICAL_COMPOSITE_RECORD_ID_RE if allow_composite_record_id else CANONICAL_ID_RE
    return pat.fullmatch(v) is not None


def _canonical_id_key(v: str) -> str:
    """Compute separator-first, digit-padding-second canonical equivalence key (Audit R7-04 / R8-07).

    Equivalence normalization applied after strict ASCII ingress validation:
      1. NFKD + Unicode dash translation -> strip ALL C*/Z*/M* -> NFKC -> casefold().
      2. Strip ALL ASCII separators (._:-) FIRST (so e.g. 'M-0-1' -> 'm01').
      3. Normalize every contiguous ASCII digit run by stripping leading zeros
         ('m01' -> 'm1', '000' -> '0') without int() to prevent digit-limit ValueError.
    """
    norm = unicodedata.normalize("NFKD", v).translate(_UNICODE_DASH_TRANSLATION)
    stripped = "".join(ch for ch in norm if unicodedata.category(ch)[0] not in ("C", "Z", "M"))
    scrubbed = unicodedata.normalize("NFKC", stripped).casefold()
    alnum = re.sub(r"[._:-]+", "", scrubbed)
    return re.sub(r"[0-9]+", lambda m: m.group(0).lstrip("0") or "0", alnum)


def _canonical_id_keys(v: str) -> tuple[str, str]:
    """Return canonical deduplication keys for subject/animal/donor IDs (Audit R7-04 / R8-07)."""
    k = _canonical_id_key(v)
    return k, k


_GOVERNED_CANONICAL_NON_ID_FIELDS: FrozenSet[str] = frozenset({
    "gate_source",
    "process_class",
    "seedline_source",
    "tumor_host_strain",
    "host_strain",
    "binder_valency",
    "perifusion_mode",
    "macs_recovery_denominator_type",
    "starting_cell_origin",
    "bank_origin",
    "evidence_tier",
    "decision",
    "authority_scope",
    "study_record_ref",
})


def _audit_canonical_identifier_fields(
    rec: Any,
    *,
    label: str,
    failures: list[str],
    skip_keys: FrozenSet[str] = frozenset(),
) -> None:
    """Apply strict canonical ASCII identity validation (_is_canonical_id) to EVERY assay, record,
    lot, bank, binder, study, issuer & governed token ID field in a mapping (Audit R8-07)."""
    if not isinstance(rec, Mapping):
        return
    for k, v in rec.items():
        if not isinstance(k, str) or k in skip_keys or v is None:
            continue
        if k.endswith("_id") or k.endswith("_ref") or k in _GOVERNED_CANONICAL_NON_ID_FIELDS:
            if not _is_canonical_id(v, allow_composite_record_id=(k == "record_id")):
                if "FAIL_NONCANONICAL_ASSAY_OR_RECORD_IDENTIFIER" not in failures:
                    failures.append("FAIL_NONCANONICAL_ASSAY_OR_RECORD_IDENTIFIER")
                spec_code = f"FAIL_{label}_NONCANONICAL_{k.upper()}"
                if spec_code not in failures:
                    failures.append(spec_code)
        elif k.endswith("_ids") and isinstance(v, list):