OpenIslet

scripts/wetlab_contract.py

One measurement contract for Python ingestion and generated MCP metadata.

script Release v0.8.0 gen-eb955f8266035aba 913 KB · 68 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/wetlab_contract.py · SHA-256: 6bb3955530f8f05d…

            batch.get('iip0026_molecular_observations') if isinstance(batch.get('iip0026_molecular_observations'), dict) else {},
            batch.get('measurements') if isinstance(batch.get('measurements'), dict) else {},
        )
        _b_t6_null_seen = False
        for _b_src in _b_t6_ctrs:
            if 'tier6b_sorted_lot_observations' in _b_src:
                if _b_src['tier6b_sorted_lot_observations'] is None:
                    _b_t6_null_seen = True
                else:
                    has_t6b_container = True
                    _b_t6 = _b_src['tier6b_sorted_lot_observations']
                    if isinstance(_b_t6, (list, tuple)):
                        tier6b_atoms_collected.extend(_b_t6)
                    else:
                        tier6b_atoms_collected.append(None)
        if _b_t6_null_seen and has_t6b_container:
            tier6b_atoms_collected.append(None)
        atoms = batch.get('atoms', [] if (has_t6b_container or 'tier6b_sorted_lot_observations' in batch) else None)
        if not isinstance(atoms, list):
            malformed_batch_holds.append('HOLD_MALFORMED_BATCH_ATOM_LIST')
            continue
        for atom in atoms:
            if not isinstance(atom, AtomicObservation):
                malformed_batch_holds.append('HOLD_NON_ATOMIC_OBSERVATION_OBJECT')
                if isinstance(atom, dict) and (
                    atom.get('endpoint_id') == 'lot_tier6b_sorted_prolif_clonogenic_escape'
                    or (isinstance(atom.get('controls'), dict) and atom['controls'].get('endpoint_id') == 'lot_tier6b_sorted_prolif_clonogenic_escape')
                ):
                    tier6b_atoms_collected.append(atom)
                else:
                    tier6b_atoms_collected.append(None)
                continue
            sk_tup = _canon_scope_tuple_iip0031(atom.scope_key)
            # Route sorted-lot Tier 6B observations exclusively through the IIP-0031 per-fraction thinning evaluator:
            nested_tier6b = atom.controls.get('endpoint_id') == 'lot_tier6b_sorted_prolif_clonogenic_escape'
            if nested_tier6b or atom.endpoint_id == 'lot_tier6b_sorted_prolif_clonogenic_escape':
                tier6b_atoms_collected.append(atom)
            if atom.endpoint_id == 'lot_tier6b_sorted_prolif_clonogenic_escape':
                if atom.scope_type == 'LOT_SCOPE' and sk_tup == lot_k_c.as_tuple():
                    if atom.campaign_id != target_campaign_id:
                        structural_holds.append(f'HOLD_UNLINKED_CAMPAIGN:{atom.endpoint_id}')
                    else:
                        lot_store[atom.endpoint_id] = atom
                elif atom.scope_type == 'LOT_SCOPE' and sk_tup[:4] == mcb_k_c.as_tuple():
                    invalidated_stale_keys.add(atom.endpoint_id)
                continue
            # Evaluate atom validity and latch any adverse failure on its exact scope:
            expected_kind = _ATOMIC_ENDPOINT_KINDS.get(atom.endpoint_id)
            if expected_kind is None:
                atom_status = 'HOLD_UNKNOWN_ATOMIC_ENDPOINT'
            elif atom.kind != expected_kind:
                atom_status = 'HOLD_INVALID_ATOM_KIND_OR_NON_NUMERIC_VALUE'
            elif atom.scope_type != _ATOMIC_REQUIRED_SCOPES.get(atom.endpoint_id, atom.scope_type):
                atom_status = 'HOLD_INVALID_ATOMIC_ENDPOINT_SCOPE'
            elif atom.endpoint_id in S9_CORE_LOT_ENDPOINT_IDS and not (
                _S9_ASSAY_RANGES[atom.endpoint_id][0] <= atom.value_or_k <= _S9_ASSAY_RANGES[atom.endpoint_id][1]
                and STAGE0_CUSTOM_MINIMUM_SE.get(atom.endpoint_id, 0.001) <= atom.se_or_n <= 1e12
            ):
                atom_status = 'HOLD_S9_OUT_OF_RANGE_MEASUREMENT_OR_REPLICATE_COUNT'
            elif atom.kind == 'CONTINUOUS_STUDENT_T' and atom.endpoint_id not in S9_CORE_LOT_ENDPOINT_IDS and atom.sample_n > 10000:
                atom_status = 'HOLD_S9_OUT_OF_RANGE_MEASUREMENT_OR_REPLICATE_COUNT'
            elif atom.kind == 'METADATA_CONTROL':
                atom_status = 'PASS' if atom.value_or_k is True else 'HOLD_UNVERIFIED_METADATA_CONTROL'
            elif atom.kind == 'EXACT_INTEGER_COUNT':
                spec_c = count_caps[atom.endpoint_id]
                ctrl = dict(atom.controls)
                c_res = evaluate_rare_event_count_iip0024(
                    gate_id=('GATE0S_SHEDDING_' + atom.endpoint_id.upper() if atom.endpoint_id.startswith('gate0s_shedding_') else atom.endpoint_id.upper()),
                    k=atom.value_or_k,
                    n=atom.se_or_n,
                    max_u95_fraction=float(spec_c['cap']),
                    require_observed_zero=bool(spec_c['require_observed_zero']),
                    sampling_independence_model=str(ctrl.get('sampling_independence_model', 'INDEPENDENT_BIOLOGICAL_OPPORTUNITIES')),
                    clustered_sampling=bool(ctrl.get('clustered_sampling', False)),
                    validated_clustered_estimator_id=ctrl.get('validated_clustered_estimator_id'),
                    eta_spike_recovery_l95=ctrl.get('eta_spike_recovery_l95'),
                    f_clonogenic=ctrl.get('f_clonogenic'),
                    use_poisson_protocol_floor=bool(spec_c.get('use_poisson_protocol_floor', False)),
                )
                atom_status = c_res['status']
            elif atom.kind == 'CONTINUOUS_STUDENT_T':
                # The immutable constructor validated the numeric mean, SE and sample_n >= 6.
                atom_status = 'HOLD_UNEVALUATED_CONTINUOUS_ENDPOINT'
                _eff_cont_n = min(atom.sample_n, 10000)
                t_95_a = student_t_ppf_one_sided_95(float(_eff_cont_n - 1))
                u95_a = float(atom.value_or_k) + t_95_a * float(atom.se_or_n)
                l95_a = float(atom.value_or_k) - t_95_a * float(atom.se_or_n)
                if atom.endpoint_id in ('mcb_1q32_mdm4_diploid_cn', 'mcb_20q11_bcl2l1_diploid_cn'):
                    atom_status = 'PASS' if 1.85 <= l95_a <= u95_a <= 2.15 else 'FAIL_HARD_STOP'
                elif atom.endpoint_id == 'mcb_donor_pairwise_ibd_pi_hat':
                    atom_status = 'PASS' if 0 <= atom.value_or_k and u95_a < 0.05 else 'HOLD_DONOR_PAIRWISE_IBD'
                elif atom.endpoint_id == 'obs_iapp_d84_immunocapture_oligomer_elisa_fold':
                    atom_status = 'PASS' if 0 <= atom.value_or_k and u95_a <= 1.5 else 'HOLD_INCONCLUSIVE_IAPP_EVIDENCE'
                elif atom.endpoint_id == 'obs_iapp_d84_colocalized_fibril_area_pct':
                    atom_status = 'PASS' if 0 <= atom.value_or_k and u95_a <= 1.0 else 'HOLD_INCONCLUSIVE_IAPP_EVIDENCE'
                elif atom.endpoint_id == 'stage7_stored_mature_insulin_iu':
                    ctrl_a = dict(atom.controls)
                    max_lot_iu_a = ctrl_a.get('max_lot_iu', float(atom.value_or_k))
                    if not _is_strict_finite_number_iip0024(max_lot_iu_a) or float(max_lot_iu_a) < 0.0:
                        atom_status = 'HOLD_INVALID_STORED_MATURE_INSULIN_MAX_LOT_IU'
                    else:
                        crossed_138p3 = (
                            u95_a > float(STAGE0_IIP0029_CONSTANTS['GATE0S_ABSOLUTE_STORED_INSULIN_CEILING_IU'])
                            or float(max_lot_iu_a) > float(STAGE0_IIP0029_CONSTANTS['GATE0S_ABSOLUTE_STORED_INSULIN_CEILING_IU'])
                        )
                        if atom.scope_type == 'LOT_SCOPE' and sk_tup == lot_k_c.as_tuple():
                            if elevated_store_gate0s_escalated_on_lot and not crossed_138p3:
                                atom_status = 'FAIL_HARD_STOP'
                                structural_holds.append('FAIL_IIP0029_IMMUTABLE_SOURCE_OR_THRESHOLD_REPLACEMENT_DETECTED')
                            elif iip0029_lot_store_sample_unit_id is not None and atom.sample_unit_id != iip0029_lot_store_sample_unit_id and not crossed_138p3 and elevated_store_gate0s_escalated_on_lot:
                                atom_status = 'FAIL_HARD_STOP'
                                structural_holds.append('FAIL_IIP0029_IMMUTABLE_SOURCE_OR_THRESHOLD_REPLACEMENT_DETECTED')
                            else:
                                iip0029_lot_store_sample_unit_id = atom.sample_unit_id
                                if crossed_138p3:
                                    elevated_store_gate0s_escalated_on_lot = True
                                atom_status = 'PASS'
                elif atom.endpoint_id == 'gate0s_ap1903_1h_insulin_burst_iu':
                    atom_status = 'PASS' if u95_a <= 2.8 else 'FAIL_HARD_STOP'
                elif atom.endpoint_id == 'gate0s_ap1903_24h_insulin_dump_fraction':
                    atom_status = 'PASS' if u95_a <= 0.15 else 'FAIL_HARD_STOP'
                elif atom.endpoint_id == 'obs_explant_en_bloc_recovery_fraction':
                    atom_status = 'PASS' if l95_a >= 0.99 else 'FAIL_HARD_STOP'
                elif atom.endpoint_id == 'obs_icasp9_log10_kill':
                    ctrl_ic9 = dict(atom.controls)
                    _b_n_ctrs = (
                        ctrl_ic9,
                        batch,
                        batch.get('scope') if isinstance(batch.get('scope'), dict) else {},
                        batch.get('measurements') if isinstance(batch.get('measurements'), dict) else {},
                        batch.get('iip0026_molecular_observations') if isinstance(batch.get('iip0026_molecular_observations'), dict) else {},
                        target_provenance,
                    )
                    _ic9_n_vals = [atom.sample_n] + [
                        _c_n[k]
                        for _c_n in _b_n_ctrs
                        for k in (*S9_REPLICATE_KEYS['default'], *S9_REPLICATE_KEYS['obs_icasp9_log10_kill'])
                        if k in _c_n
                    ]
                    _ic9_n_bad = any(
                        not _is_integral_count_iip0026(v) or not (6 <= int(v) <= 10000) or int(v) != atom.sample_n
                        for v in _ic9_n_vals
                    )
                    _ic9_valid_ge2 = [
                        (v if type(v) is int else int(round(v)))
                        for v in _ic9_n_vals
                        if (
                            (type(v) is int and 2 <= v <= 10000)
                            or (isinstance(v, float) and math.isfinite(v) and 2.0 <= v <= 10000.0 and v.is_integer())
                        )
                    ]
                    _ic9_eff_n = min(_ic9_valid_ge2 + ([6] if _ic9_n_bad else [])) if _ic9_valid_ge2 else 6
                    _ic9_t95 = student_t_ppf_one_sided_95(float(_ic9_eff_n - 1))
                    _ic9_l95 = float(atom.value_or_k) - _ic9_t95 * float(atom.se_or_n)
                    if _ic9_l95 < 4.0:
                        atom_status = 'FAIL_HARD_STOP'
                    elif _ic9_n_bad:
                        atom_status = 'HOLD_S9_INVALID_OR_CONFLICTING_REPLICATE_COUNT'
                    else:
                        atom_status = 'PASS'
                elif atom.endpoint_id in ('obs_tp53_ppm1d_bcor_vaf', 'obs_castseq_translocation_freq'):
                    ctrl_s9 = dict(atom.controls)
                    _b_n_ctrs = (
                        ctrl_s9,
                        batch,
                        batch.get('scope') if isinstance(batch.get('scope'), dict) else {},
                        batch.get('measurements') if isinstance(batch.get('measurements'), dict) else {},
                        batch.get('iip0026_molecular_observations') if isinstance(batch.get('iip0026_molecular_observations'), dict) else {},
                        target_provenance,
                    )
                    _s9_n_vals = [atom.sample_n] + [
                        _c_n[k]
                        for _c_n in _b_n_ctrs
                        for k in (*S9_REPLICATE_KEYS['default'], *S9_REPLICATE_KEYS[atom.endpoint_id])
                        if k in _c_n
                    ]
                    _s9_n_bad = any(
                        not _is_integral_count_iip0026(v) or not (6 <= int(v) <= 10000) or int(v) != atom.sample_n
                        for v in _s9_n_vals
                    )
                    _s9_valid_ge2 = [
                        (v if type(v) is int else int(round(v)))
                        for v in _s9_n_vals
                        if (
                            (type(v) is int and 2 <= v <= 10000)
                            or (isinstance(v, float) and math.isfinite(v) and 2.0 <= v <= 10000.0 and v.is_integer())
                        )
                    ]
                    _s9_eff_n = min(_s9_valid_ge2 + ([6] if _s9_n_bad else [])) if _s9_valid_ge2 else 6
                    depth_key, count_key = S9_FREQUENCY_ASSAY_KEYS[atom.endpoint_id]
                    depth_raw = ctrl_s9.get(depth_key, ctrl_s9.get('duplex_depth'))
                    s9_res = _evaluate_s9_tp53_vaf_guard(
                        atom.value_or_k,
                        atom.se_or_n,
                        depth_raw,
                        sample_n=_s9_eff_n,
                        mutant_molecules_k=ctrl_s9.get(count_key),
                        require_explicit_depth=True,
                        endpoint_label=atom.endpoint_id,
                    )
                    atom_status = str(s9_res['status'])
                    if not s9_res['hard_stop'] and _s9_n_bad:
                        atom_status = 'HOLD_S9_INVALID_OR_CONFLICTING_REPLICATE_COUNT'
                    elif not s9_res['hard_stop'] and 'duplex_depth' in ctrl_s9 and depth_key in ctrl_s9 and (
                        not _is_integral_count_iip0026(ctrl_s9['duplex_depth'])
                        or ctrl_s9['duplex_depth'] != ctrl_s9[depth_key]
                    ):
                        atom_status = 'HOLD_S9_CONFLICTING_DUPLEX_DEPTH'
            elif atom.kind == 'STRUCTURED_PANEL':
                p_dict = _deep_to_jsonable_iip0024(atom.value_or_k)
                if 'imprinting_' in atom.endpoint_id or 'meg3_dmr' in atom.endpoint_id:
                    atom_status = _atomic_mcb_panel_status(evaluate_conjunctive_imprinting_dmr_iip0024, atom.scope_type, p_dict)
                elif 'xci_46xx' in atom.endpoint_id:
                    atom_status = _atomic_mcb_panel_status(evaluate_conjunctive_xci_46xx_iip0024, atom.scope_type, p_dict)
                elif 'mtdna_1000x' in atom.endpoint_id:
                    atom_status = _atomic_mcb_panel_status(evaluate_scoped_mtdna_gate_iip0024, atom.scope_type, p_dict)
                elif atom.endpoint_id == 'stage0_locus2_modeb_v3_panel':
                    if atom.scope_type != 'LOT_SCOPE':
                        atom_status = 'HOLD_S11_PANEL_REQUIRES_LOT_SCOPE'
                        if sk_tup in target_scope_tuples:
                            structural_holds.append('HOLD_S11_PANEL_REQUIRES_LOT_SCOPE')
                    elif not isinstance(p_dict, dict):
                        atom_status = 'HOLD_S11_MALFORMED_RECORD'
                        if sk_tup == lot_k_c.as_tuple():
                            structural_holds.append('HOLD_S11_MALFORMED_RECORD')
                    else:
                        outer_ctx_31 = {
                            'product_variant_id': pvid_canon,
                            'construct_sha256': atom.scope_key.construct_sha256,
                            'donor_seedline_id': atom.scope_key.donor_seedline_id,
                            'mcb_id': atom.scope_key.mcb_id,
                            'lot_id': atom.scope_key.lot_id,
                            'campaign_id': atom.campaign_id,
                            'sample_id': atom.sample_unit_id,
                            'scope_type': atom.scope_type,
                            **({'background_id': target_provenance['background_id']} if 'background_id' in target_provenance else {}),
                            **({'l2_v3_donor_id': target_provenance['l2_v3_donor_id']} if 'l2_v3_donor_id' in target_provenance else {}),
                            **({'donor_id': target_provenance['donor_id']} if 'donor_id' in target_provenance else {}),
                        }
                        res_31 = evaluate_locus2_ciita_modeb_challenger_v3_gate(
                            {**outer_ctx_31, 'iip0031_locus2_record': dict(p_dict)},
                            root=root_path,
                            product_def=pdef,
                            _trusted_p_mod=p_mod,
                        )
                        st_31 = str(res_31.get('status'))
                        if sk_tup == lot_k_c.as_tuple() and atom.campaign_id == target_campaign_id:
                            if st_31.startswith('FAIL_'):
                                for _rf31 in res_31.get('reasons', [st_31]):
                                    if str(_rf31).startswith('FAIL_') and str(_rf31) not in latched_s11_all_fail_reasons: