scripts/ingest_wetlab_results.py
Use this file in any AI chat (paste-only or attachment-capable):
Pinned raw file: https://openislet.org/files/gen-eb955f8266035aba/scripts/ingest_wetlab_results.py · SHA-256: e050593675170515…
)
and (
"HAZARD_PROLIF_SURVIVOR" not in stop_required_s9_categories
or (
hist_meas_for_s0.get("obs_hazard_state_prolif_survivor_count_k") not in ("UNAVAILABLE", None)
and float(hist_meas_for_s0.get("obs_hazard_state_prolif_effective_trials") or 0.0) >= 299573228.0
)
)
and (
"PULSED_PK_KILL" not in stop_required_s9_categories
or (
hist_meas_for_s0.get("obs_ap1903_pulsed_pk_log10_kill") not in ("UNAVAILABLE", None)
and entry.get("obs_ap1903_pulsed_pk_washout_regimen_verified") is not False
)
)
and (
"MONOTHERAPY_PULSED_PK_KILL" not in stop_required_s9_categories
or (
hist_meas_for_s0.get("obs_ap1903_monotherapy_pulsed_pk_log10_kill") not in ("UNAVAILABLE", None)
and entry.get("obs_ap1903_pulsed_pk_washout_regimen_verified") is not False
)
)
and (
"STEP1_SUBLETHAL_SURVIVOR" not in stop_required_s9_categories
or (
hist_meas_for_s0.get("obs_ap1903_step1_sublethal_survivor_count_k") not in ("UNAVAILABLE", None)
and float(hist_meas_for_s0.get("obs_ap1903_step1_effective_trials") or 0.0) >= 29957322.8
)
)
and (
"EXPLANT_RECOVERY" not in stop_required_s9_categories
or (
entry.get("obs_vascularized_explant_en_bloc_recovery_verified") is True
and _explant_recovery_clears_student_t_0p99(hist_meas_for_s0)
)
)
and _extra_iip0024_stop_categories_cleared(stop_required_s9_categories, hist_meas_for_s0)
and isinstance(entry.get("batch_id"), str)
and entry["batch_id"].strip()
):
post_stop_passing_s9_batch_ids.append(entry["batch_id"].strip())
step_s0_input = dict(pooled_hist_for_s0)
if isinstance(entry.get("batch_id"), str) and entry["batch_id"].strip():
step_s0_input["batch_id"] = entry["batch_id"].strip()
_req_tcat_h = _clean_optional_id_str(entry.get("reset_prior_safety_stop_target_category"))
if _req_tcat_h is not None and stop_required_s9_categories and stop_required_s9_categories != {_req_tcat_h}:
step_s0_input["verified_ledger_passing_s9_batch_ids"] = []
else:
step_s0_input["verified_ledger_passing_s9_batch_ids"] = list(post_stop_passing_s9_batch_ids)
for qp_k in (
"prior_batch_sticky_s9_safety_stop",
"prior_variant_safety_status",
"reset_prior_safety_stop_after_investigation",
"reset_prior_safety_stop_reason",
"reset_prior_safety_stop_reason_code",
"reset_prior_safety_stop_repeat_batch_ids",
"reset_prior_safety_stop_independent_qp_approver_id",
"reset_prior_safety_stop_target_category",
"submitter_id",
):
if entry.get(qp_k) is not None:
step_s0_input[qp_k] = entry[qp_k]
hist_s0 = evaluate_stage0_decision_tree(
step_s0_input,
defaulted_se_keys=sorted(pooled_hist_def_se),
prior_batch_sticky_s9_safety_stop=running_sticky_s9,
)
running_sticky_s9 = bool(hist_s0.get("safety_kill_s9_triggered") is True) or bool(single_batch_s0.get("safety_kill_s9_triggered") is True)
if not running_sticky_s9:
stop_required_mcb_clonogenic_clearance = False
stop_required_5endpoint_er_clearance = False
stop_required_s9_categories.clear()
if running_sticky_s9 and prior_stage0_eval.get("safety_kill_s9_triggered") is not True:
raise ValueError(
"Prior report stage0_decision_tree_evaluation.safety_kill_s9_triggered=False contradicts S9 hard safety stop in ordered_batch_observation_ledger (AUDIT-REF)"
)
return norm_batches, prev_payload_hashes, validated_priors
def current_model_reference_metadata() -> Dict[str, Dict[str, Any]]:
"""Derived comparisons are separate from independent target priors and assays."""
metadata = {key: dict(value) for key, value in ENDPOINT_PROVENANCE_AND_MODEL_RECONCILIATION.items()}
if not LAYER2_ATLAS_PATH.exists():
return metadata
atlas = loads_strict_json(LAYER2_ATLAS_PATH.read_text(encoding="utf-8"))
try:
rows = atlas["stage0_to_stage7_perturbation_plane"]["perturbation_profiles"]
if not isinstance(rows, list) or any(not isinstance(row, dict) for row in rows):
raise ValueError("Layer2 model profiles must be a list of objects")
profiles = {}
for row in rows:
identifier = row.get("genotype_id")
if not isinstance(identifier, str) or not identifier or identifier in profiles:
raise ValueError("Layer2 model profiles require unique genotype identifiers")
profiles[identifier] = row
wt = profiles["WT_UNEDITED_CONTROL"]
arm = profiles["SCENARIO_A_ARM_1B_UNIVERSAL_LEAN_4LOCUS"]
except (KeyError, TypeError) as exc:
raise ValueError("Missing or malformed Layer2 model comparison profiles") from exc
def model_number(profile: Dict[str, Any], key: str, label: str, maximum: float | None = None) -> float:
try:
value = _require_finite_float(profile[key], label)
except (KeyError, OverflowError) as exc:
raise ValueError(f"Invalid Layer2 model comparison value: {label}") from exc
if value < 0.0 or (maximum is not None and value > maximum):
raise ValueError(f"Layer2 model comparison value outside physical domain: {label}")
return value
wt_density = model_number(wt, "hour0_basal_cd47_molecules_per_cell", "WT CD47 density")
arm_density = model_number(arm, "hour0_basal_cd47_molecules_per_cell", "Arm1B CD47 density")
fold = arm_density / wt_density if wt_density > 0.0 else None
cd = metadata["cd47_igv_hour0_fold_over_baseline_arm1b"]
cd.update(layer2_or_layer3_model_reference_value=fold,
layer2_arm1b_molecules_per_cell=arm_density,
layer2_wt_molecules_per_cell=wt_density,
model_reference_status=("CONDITIONAL_LAYER2_PRIOR_COMPARISON_NOT_MEASURED" if fold is not None
else "UNDEFINED_ZERO_REFERENCE_CD47_DENSITY"))
wt_yield = model_number(wt, "stage7_sc_beta_yield_fraction", "WT Stage7 yield", 1.0)
arm_yield = model_number(arm, "stage7_sc_beta_yield_fraction", "Arm1B Stage7 yield", 1.0)
yield_ratio = arm_yield / wt_yield if wt_yield > 0.0 else None
metadata["stage7_sc_beta_yield_fraction_arm1b"].update(
layer2_or_layer3_model_reference_value=yield_ratio,
model_reference_status=("CONDITIONAL_LAYER2_PRIOR_COMPARISON_NOT_MEASURED" if yield_ratio is not None
else "UNDEFINED_ZERO_REFERENCE_STAGE7_YIELD"))
return metadata
def evaluate_stage0_decision_tree(
observations: Dict[str, Any],
*,
require_full_5endpoint_s9_panel: bool = False,
defaulted_se_keys: Any = None,
prior_batch_sticky_s9_safety_stop: bool = False,
product_def: Dict[str, Any] | None = None,
) -> Dict[str, Any]:
"""Evaluate the machine-readable Stage-0 decision tree (`data/protocols/stage0_decision_tree_v1.json`, `S1-S9`) in strict precedence order (`DEC-036`, `DEC-039`, `DEC-040`, & `DEC-041`)."""
global _MEASUREMENT_CONTRACT_MODULE
if _MEASUREMENT_CONTRACT_MODULE is None:
spec = importlib.util.spec_from_file_location("openislet_measurement_contract", REPO_ROOT / "scripts/wetlab_contract.py")
helper = importlib.util.module_from_spec(spec)
spec.loader.exec_module(helper)
_MEASUREMENT_CONTRACT_MODULE = helper
return _MEASUREMENT_CONTRACT_MODULE.evaluate_stage0_decision_tree(
observations,
root=REPO_ROOT,
require_full_5endpoint_s9_panel=require_full_5endpoint_s9_panel,
defaulted_se_keys=defaulted_se_keys,
prior_batch_sticky_s9_safety_stop=prior_batch_sticky_s9_safety_stop,
product_def=product_def,
)
def run_calibration(
input_payload: Dict[str, Any],
is_dry_run: bool,
prior_posterior_report: Dict[str, Any] | None = None,
fail_on_conflict_gt_3sigma: bool = False,
*,
require_full_5endpoint_s9_panel: bool = False,
) -> Dict[str, Any]:
"""
Execute conjugate Bayesian calibration (closes AUDIT-REF, AUDIT-REF, AUDIT-REF,
AUDIT-REF, AUDIT-REF, AUDIT-REF, AUDIT-REF,
AUDIT-REF & 07, and AUDIT-REF / EXT-A).
"""
if not isinstance(input_payload, dict) or not input_payload:
raise ValueError("input_payload must be a non-empty dictionary")
if not isinstance(is_dry_run, bool) or not isinstance(fail_on_conflict_gt_3sigma, bool) or not isinstance(require_full_5endpoint_s9_panel, bool):
raise ValueError("Calibration mode, conflict policy, and S9 panel policy must be booleans")
global _MEASUREMENT_CONTRACT_MODULE
if _MEASUREMENT_CONTRACT_MODULE is None:
spec = importlib.util.spec_from_file_location("openislet_measurement_contract", REPO_ROOT / "scripts/wetlab_contract.py")
helper = importlib.util.module_from_spec(spec)
spec.loader.exec_module(helper)
_MEASUREMENT_CONTRACT_MODULE = helper
normalize_measurements = _MEASUREMENT_CONTRACT_MODULE.normalize_measurements
received_payload_sha256 = hashlib.sha256(json.dumps(input_payload, sort_keys=True, allow_nan=False).encode("utf-8")).hexdigest()
input_payload, measurement_validation = normalize_measurements(input_payload, require_observation=not is_dry_run)
if input_payload.get("require_full_5endpoint_s9_panel") is True:
require_full_5endpoint_s9_panel = True
batch_id = input_payload.get("batch_id", input_payload.get("assay_id"))
if not is_dry_run:
if not isinstance(batch_id, str) or not batch_id.strip():
raise ValueError("Empirical wet-lab payload must include a non-empty string 'batch_id' or 'assay_id'.")
batch_id = batch_id.strip()
if batch_id.upper().startswith("DRY-RUN"):
raise ValueError(f"Empirical wet-lab payload cannot use a DRY-RUN batch_id ({batch_id!r}).")
else:
if batch_id is not None and (not isinstance(batch_id, str) or not batch_id.strip()):
raise ValueError("batch_id must be a non-empty string when provided")
batch_id = str(batch_id or "DRY-RUN-CALIBRATION-001").strip()
batch_payload_sha256 = compute_measurement_payload_sha256(input_payload)
prev_batches: list[str] = []
prev_payload_hashes: list[str] = []
validated_priors: Dict[str, tuple[float, float]] = {}
parent_report_sha256: str | None = None
if prior_posterior_report is not None:
prev_batches, prev_payload_hashes, validated_priors = _validate_prior_posterior_report(
prior_posterior_report,
is_dry_run=is_dry_run,
new_batch_id=batch_id,
new_batch_payload_sha256=batch_payload_sha256,
)
parent_report_sha256 = hashlib.sha256(
json.dumps(prior_posterior_report, sort_keys=True, allow_nan=False).encode("utf-8")
).hexdigest()
has_any_extended_stage0_stage1_obs = any(
(mean_key in input_payload and input_payload.get(mean_key) not in ("UNAVAILABLE", None))
for _ep, _dm, _dsd, mean_key, _sk, _dse, _minv, _maxv, _u in EXTENDED_STAGE0_STAGE1_SPECS
) or any(
(mean_key in input_payload and input_payload.get(mean_key) not in ("UNAVAILABLE", None))
for _eid, mean_key, _sk, _lo, _hi, _u in _get_stage0_decision_tree_specs()
)
model_reference_metadata = current_model_reference_metadata()
updates: Dict[str, Any] = {}
observed_count = 0
for ep_name, default_prior_m, default_prior_sd, mean_key, se_key, min_valid, max_valid, unit_desc in ENDPOINT_SPECS:
if ep_name in validated_priors:
prior_m, prior_sd = validated_priors[ep_name]
else:
prior_m, prior_sd = float(default_prior_m), float(default_prior_sd)
prov_meta = model_reference_metadata.get(ep_name, {})
# Allow pouch-only or Stage-0/Stage-1 partial batches to omit core keys when at least one extended endpoint is present
if input_payload.get(mean_key) == "UNAVAILABLE" or (mean_key not in input_payload and has_any_extended_stage0_stage1_obs):
updates[ep_name] = {
"status": "UNAVAILABLE_PRIOR_RETAINED",
"unit_and_support": unit_desc,
"minimum_biological_se_floor_enforced": MIN_BIOLOGICAL_SE_FLOOR,
"prior_provenance": prov_meta.get("prior_source", ""),
"layer2_or_layer3_model_reference_value": prov_meta.get("layer2_or_layer3_model_reference_value"),
"mapped_ranker_prior_key": prov_meta.get("mapped_ranker_prior_key"),
"prior_mean": round(prior_m, 4),
"prior_sd": _safe_round_positive_sd(prior_sd),
"prior_mean_exact": float(prior_m),
"prior_sd_exact": float(prior_sd),
"observed_mean": None,
"observed_se": None,
"observed_mean_exact": None,
"observed_se_exact": None,
"posterior_mean": round(prior_m, 4),
"posterior_sd": _safe_round_positive_sd(prior_sd),