scripts/wetlab_contract.py
Use this file in any AI chat (paste-only or attachment-capable):
Pinned raw file: https://openislet.org/files/gen-eb955f8266035aba/scripts/wetlab_contract.py · SHA-256: 6bb3955530f8f05d…
'sample_ids': [canon_tok],
'records': [rec],
'obs_identities': [(rec, list(aliquot_tokens))],
'cal_by_key': {cal_key_obs: cal_tuple_obs},
'untr_by_id': {untr_sid: (untr_k, untr_n)},
'obs_list': [(n_raw, plated_n, untr_k, untr_n)],
'fraction_roles': ({_explicit_frole} if _explicit_frole is not None else set()),
'rec': rec,
}
else:
prev_r = agg_by_frac[fid]['rec']
if _explicit_frole is not None:
agg_by_frac[fid]['fraction_roles'].add(_explicit_frole)
if len(agg_by_frac[fid]['fraction_roles']) > 1:
return _hold_unqual(f'CONFLICTING_TIER6B_FRACTION_ROLE:{fid}')
if (
_tier6b_signature(prev_r.get('w_i')) != _tier6b_signature(rec.get('w_i'))
or agg_by_frac[fid]['presort_fraction_cells'] != ps_frac
):
return _hold_unqual(f'CONFLICTING_WEIGHTS_OR_PRESORT_CELLS_WITHIN_FRACTION:{fid}')
if cal_key_obs in agg_by_frac[fid]['cal_by_key']:
if agg_by_frac[fid]['cal_by_key'][cal_key_obs] != cal_tuple_obs:
return _hold_unqual(f'CONFLICTING_CALIBRATION_COUNTS_FOR_SAME_CAL_BATCH_ID:{fid}')
else:
agg_by_frac[fid]['cal_by_key'][cal_key_obs] = cal_tuple_obs
if untr_sid in agg_by_frac[fid]['untr_by_id']:
if agg_by_frac[fid]['untr_by_id'][untr_sid] != (untr_k, untr_n):
return _hold_unqual(f'CONFLICTING_UNTREATED_CFU_CONTROL_COUNTS:{untr_sid}')
else:
agg_by_frac[fid]['untr_by_id'][untr_sid] = (untr_k, untr_n)
agg_by_frac[fid]['N'] += n_raw
agg_by_frac[fid]['plated_treated_cells_sum'] += plated_n
agg_by_frac[fid]['sample_ids'].append(canon_tok)
agg_by_frac[fid]['records'].append(rec)
agg_by_frac[fid]['obs_identities'].append((rec, list(aliquot_tokens)))
agg_by_frac[fid]['obs_list'].append((n_raw, plated_n, untr_k, untr_n))
if rec.get('presort_clonogenic_opportunities') is not None:
agg_by_frac[fid]['declared_clonogenic_opportunities'].append(rec['presort_clonogenic_opportunities'])
if lot_conflicts:
return _hold_unqual(lot_conflicts[0])
if not all_untreated_sample_ids.isdisjoint(all_treated_sample_ids):
return _hold_unqual('NON_DISJOINT_UNTREATED_CFU_SAMPLE_ID_ACROSS_LOT')
if not all_calibrant_specimen_ids.isdisjoint(all_treated_sample_ids) or not all_calibrant_specimen_ids.isdisjoint(all_untreated_sample_ids):
return _hold_unqual('NON_DISJOINT_CALIBRANT_SPECIMEN_ID_ACROSS_LOT')
if lot_roster is None or lot_presort_total_cells is None or lot_reconciled_loss_cells is None:
return _hold_unqual('MISSING_SORTED_LOT_TIER6B_EVIDENCE')
m_fracs = len(lot_roster)
def _norm_frac_label(lbl: str) -> tuple[str, list[str], set[str]]:
words = re.findall(r'[a-z0-9]+', lbl.lower())
norm = '_'.join(words)
return norm, words, set(words)
_negation_words = frozenset({
'not', 'non', 'no', 'un', 'without', 'anti', 'never', 'neither', 'except', 'minus', 'negative',
'mixed', 'hybrid', 'pooled', 'pool', 'unsorted', 'unfractionated', 'bulk', 'crude', 'raw',
'whole', 'total', 'impure', 'contaminated', 'contaminant', 'unknown', 'unclassified',
'ambiguous', 'uncertain', 'partial', 'other', 'bypass', 'skipped', 'mock', 'blank',
'reverse', 'inverted', 'failed', 'unpurified', 'unselected', 'pseudo', 'quasi',
})
_negated_substrings = (
'unenriched', 'nonenriched', 'notenriched',
'unflowthrough', 'nonflowthrough', 'notflowthrough',
'neg_enriched', 'enriched_neg',
'neg_flow_through', 'flow_through_neg',
'neg_flowthrough', 'flowthrough_neg',
'neg_ft', 'ft_neg',
'unsortedenriched', 'mixedenriched', 'bulkenriched',
)
_ft_or_excl_words = frozenset({
'flowthrough', 'ft', 'excluded', 'exclude', 'depleted', 'deplete', 'depletion',
'discard', 'discarded', 'waste', 'rejected', 'reject', 'residual', 'remainder',
'remaining', 'leftover', 'removed', 'stripped', 'unbound', 'unretained',
'wash', 'eluate', 'eluted', 'sidestream', 'nontarget', 'offtarget',
})
_hybrid_concat_substrings = (
'depletedenriched', 'enricheddepleted',
'excludedenriched', 'enrichedexcluded',
'discardenriched', 'enricheddiscard',
'wasteenriched', 'enrichedwaste',
'flowthroughenriched', 'enrichedflowthrough',
'rejectedenriched', 'enrichedrejected',
)
def _is_negated_lbl(lbl: str) -> bool:
norm, words, word_set = _norm_frac_label(lbl)
if word_set.intersection(_negation_words):
return True
if any(sub in norm for sub in _negated_substrings):
return True
for i in range(len(words) - 1):
if words[i] == 'neg' and words[i + 1] in ('enriched', 'flow', 'flowthrough', 'ft'):
return True
if words[i] in ('enriched', 'through', 'flowthrough', 'ft') and words[i + 1] == 'neg':
return True
return any(
w.startswith(('non', 'not', 'un')) and any(w[len(p):].startswith(('enriched', 'flow', 'ft')) for p in ('non', 'not', 'un') if w.startswith(p))
for w in words
)
if any(_is_negated_lbl(f) for f in lot_roster):
return _hold_unqual('AMBIGUOUS_OR_NEGATED_FRACTION_ID')
def _has_enr_token(lbl: str) -> bool:
norm, _words, word_set = _norm_frac_label(lbl)
return ('enriched' in word_set) or ('enriched' in norm)
def _is_ft_lbl(lbl: str) -> bool:
_norm, words, word_set = _norm_frac_label(lbl)
return (
('flowthrough' in word_set)
or ('ft' in word_set)
or any(words[i] == 'flow' and words[i + 1] == 'through' for i in range(len(words) - 1))
)
def _has_ft_or_excl_token(lbl: str) -> bool:
norm, words, word_set = _norm_frac_label(lbl)
return (
_is_ft_lbl(lbl)
or bool(word_set.intersection(_ft_or_excl_words))
or any(sub in norm for sub in _hybrid_concat_substrings)
or any(
(words[i], words[i + 1]) in (('neg', 'sort'), ('side', 'stream'), ('non', 'target'), ('off', 'target'))
for i in range(len(words) - 1)
)
)
# Strict closed positive token grammar for unambiguous sorted-lot ENRICHED vs FLOW_THROUGH_OR_EXCLUDED roles:
_enr_neg_markers = frozenset({'cd31', 'cd144', 'cd34', 'pecam1', 'cdh5', 'kdr', 'vegfr2', 'cd276', 'b7h3', 'cd45'})
_enr_allowed_qualifiers = frozenset({
'fraction', 'subfraction', 'arm', 'part', 'sort', 'sorted', 'stage7',
'endocrine', 'islet', 'beta', 'pure', 'target',
})
_ft_excl_allowed_tokens = frozenset({
'flow', 'through', 'flowthrough', 'ft', 'and', 'or',
'excluded', 'exclude', 'discard', 'discarded', 'waste', 'depleted', 'deplete',
'fraction', 'subfraction', 'arm', 'part', 'sort', 'sorted',
'neg', 'pos', 'cd31', 'cd144', 'cd34', 'pecam1', 'cdh5', 'kdr', 'vegfr2', 'cd45',
'vascular', 'endothelial', 'stage7', 'pre', 'assembly',
})
def _is_strict_enr_lbl(lbl: str) -> bool:
if not re.fullmatch(r'[A-Za-z0-9_-]+', lbl):
return False
_norm, words, _word_set = _norm_frac_label(lbl)
if not words or words[0] != 'enriched' or _has_ft_or_excl_token(lbl):
return False
idx_w = 1
while idx_w < len(words):
w = words[idx_w]
if w in _enr_neg_markers and idx_w + 1 < len(words) and words[idx_w + 1] == 'neg':
idx_w += 2
continue
if w == 'pre' and idx_w + 1 < len(words) and words[idx_w + 1] == 'assembly':
idx_w += 2
continue
if w in _enr_allowed_qualifiers or re.fullmatch(r'[0-9]+', w):
idx_w += 1
continue
return False
return True
def _is_strict_ft_or_excl_lbl(lbl: str) -> bool:
if not re.fullmatch(r'[A-Za-z0-9_-]+', lbl):
return False
_norm, words, _word_set = _norm_frac_label(lbl)
if not words or _has_enr_token(lbl):
return False
starts_ft_excl = (
words[0] in ('flowthrough', 'ft', 'excluded', 'exclude', 'discard', 'discarded', 'waste', 'depleted', 'deplete')
or (len(words) >= 2 and (words[0], words[1]) in (('flow', 'through'), ('neg', 'sort')))
)
if not starts_ft_excl:
return False
return all((w in _ft_excl_allowed_tokens or re.fullmatch(r'[0-9]+', w)) for w in words)
hybrid_fracs = [f for f in lot_roster if _has_enr_token(f) and _has_ft_or_excl_token(f)]
if hybrid_fracs:
return _hold_unqual('AMBIGUOUS_HYBRID_ENRICHED_FLOW_THROUGH_FRACTION_ID')
# Every declared fraction in the roster must classify into an unambiguous strict sorted-lot role (#26, T6; Patch v11):
unclassified_fracs = [f for f in lot_roster if not _is_strict_enr_lbl(f) and not _is_strict_ft_or_excl_lbl(f)]
if unclassified_fracs:
return _hold_unqual(f'UNCLASSIFIED_OR_AMBIGUOUS_FRACTION_ROLE:{",".join(unclassified_fracs)}')
pure_enriched = [f for f in lot_roster if _is_strict_enr_lbl(f)]
pure_ft = [f for f in lot_roster if _is_strict_ft_or_excl_lbl(f) and _is_ft_lbl(f)]
if m_fracs < 2 or not pure_enriched or not pure_ft or set(pure_enriched).intersection(pure_ft):
return _hold_unqual('OMITTED_ENRICHED_OR_FLOW_THROUGH_FRACTION_IN_SORTED_LOT')
missing_fracs = [f for f in lot_roster if f not in agg_by_frac]
if missing_fracs:
return _hold_unqual(f'MISSING_DECLARED_FRACTION_EVIDENCE:{",".join(missing_fracs)}')
# Cross-check optional explicit typed `fraction_role` against the unambiguous label classification:
for f in lot_roster:
declared_roles = agg_by_frac[f]['fraction_roles']
if declared_roles:
expected_role = 'ENRICHED' if _is_strict_enr_lbl(f) else 'FLOW_THROUGH_OR_EXCLUDED'
if declared_roles != {expected_role}:
return _hold_unqual(f'CONFLICTING_TIER6B_FRACTION_ROLE_AND_LABEL:{f}')
# Enforce exact integer pre-sort mass balance & disjoint treated + untreated cell budget <= fraction physical cells:
total_sorted_cells = sum(int(agg_by_frac[f]['presort_fraction_cells']) for f in lot_roster)
if total_sorted_cells + lot_reconciled_loss_cells != lot_presort_total_cells:
return _hold_unqual('PRESORT_INTEGER_MASS_BALANCE_MISMATCH')
for f in lot_roster:
untr_n_f_sum = sum(n_u for _k_u, n_u in agg_by_frac[f]['untr_by_id'].values())
if int(agg_by_frac[f]['plated_treated_cells_sum']) > int(agg_by_frac[f]['presort_fraction_cells']):
return _hold_unqual(f'PLATED_CELLS_EXCEED_FRACTION_PHYSICAL_CELLS:{f}')
if int(agg_by_frac[f]['plated_treated_cells_sum']) + untr_n_f_sum > int(agg_by_frac[f]['presort_fraction_cells']):
return _hold_unqual(f'PLATED_AND_UNTREATED_CELLS_EXCEED_FRACTION_PHYSICAL_CELLS:{f}')
# Verify point-estimate pre-sort clonogenic-risk-unit shares w_i = E_clono_i / sum(E_clono_j) if w_i is declared:
e_clono_by_frac: dict[str, Fraction] = {}
for f in lot_roster:
uk_sum = sum(k_u for k_u, _n_u in agg_by_frac[f]['untr_by_id'].values())
un_sum = sum(n_u for _k_u, n_u in agg_by_frac[f]['untr_by_id'].values())
e_clono_f = Fraction(int(agg_by_frac[f]['presort_fraction_cells']), 1) * Fraction(uk_sum, un_sum)
for sup_e in agg_by_frac[f]['declared_clonogenic_opportunities']:
if not _is_strict_finite_number_iip0024(sup_e) or float(sup_e) <= 0.0:
return _hold_unqual(f'INVALID_PRESORT_CLONOGENIC_OPPORTUNITIES:{f}')
if abs(float(sup_e) - float(e_clono_f)) > max(1.0, 1e-6 * float(e_clono_f)):
return _hold_unqual(f'PRESORT_CLONOGENIC_OPPORTUNITIES_MISMATCH_WITH_UNTREATED_CFU:{f}')
e_clono_by_frac[f] = e_clono_f
total_e_clono = sum(e_clono_by_frac.values(), Fraction(0, 1))
if total_e_clono <= 0:
return _hold_unqual('ZERO_TOTAL_PRE_SORT_CLONOGENIC_RISK_UNITS')
w_point: dict[str, float] = {}
for f in lot_roster:
w_verified_f = float(e_clono_by_frac[f] / total_e_clono)
r_f = agg_by_frac[f]['rec']
if 'w_i' in r_f:
w_raw = r_f.get('w_i')
if not _is_strict_finite_number_iip0024(w_raw):
return _hold_unqual(f'INVALID_OR_MISSING_FRACTION_WEIGHT:{f}')
w_v = float(w_raw)
if not (0.0 < w_v <= 1.0):
return _hold_unqual(f'OUT_OF_RANGE_FRACTION_WEIGHT:{f}')
if abs(w_v - w_verified_f) > 1e-9:
return _hold_unqual(f'FRACTION_WEIGHT_MISMATCH_WITH_VERIFIED_CLONOGENIC_RISK_UNIT_SHARE:{f}')
w_point[f] = w_verified_f
if abs(sum(w_point.values()) - 1.0) > 1e-9:
return _hold_unqual('INVALID_FRACTION_WEIGHT_SUM_NOT_EQUAL_TO_1')
# UNCONDITIONAL 3-way simultaneous Clopper-Pearson finite-sample 95% coverage across ALL m fractions:
alpha_obs = 0.05 / (3.0 * float(m_fracs))
alpha_cal = 0.05 / (3.0 * float(m_fracs))
alpha_cfu = 0.05 / (3.0 * float(m_fracs))
alpha_each = alpha_cal / 2.0