# ===========================================================================
# 11. Therapeutic Windows — Relative IC50 (midpoint between plateaus)
# ===========================================================================
print(f'\n=== 11. Therapeutic Windows ({TEST_AB} vs {ISO_AB}) ===')
print(f' IC50 = relative IC50: conc at midpoint between untreated & max-dose plateaus')
def parse_drug(name, test_ab, iso_ab):
"""Return (antibody, linker-payload) or (None, None) if not matching."""
for ab in [test_ab, iso_ab]:
prefix = ab + '-'
if name.startswith(prefix):
return ab, name[len(prefix):]
return None, None
def relative_ic50(concs, responses):
"""
Relative IC50: concentration where response = midpoint between
the untreated plateau (lowest conc) and the max-dose plateau (highest conc).
Interpolates on log10(conc). Returns (ic50, target_pct, confident).
confident=False if the curve never monotonically crosses the midpoint.
"""
means = responses.groupby(concs).mean()
c = np.array(means.index, dtype=float)
v = np.array(means.values, dtype=float)
order = np.argsort(c)
c, v = c[order], v[order]
untreated = v[0]
max_dose = v[-1]
target = (untreated + max_dose) / 2.0
spread = abs(untreated - max_dose)
if spread < 5.0:
return np.nan, target, False
for i in range(len(v) - 1):
if (v[i] >= target >= v[i+1]) or (v[i] <= target <= v[i+1]):
log_c1, log_c2 = np.log10(max(c[i], 1e-6)), np.log10(max(c[i+1], 1e-6))
frac = (target - v[i]) / (v[i+1] - v[i])
ic50 = 10 ** (log_c1 + frac * (log_c2 - log_c1))
confident = (spread >= 20.0) and (CONC_MIN <= ic50 <= CONC_MAX)
return ic50, target, confident
return np.nan, target, False
METRICS_FOR_TI = {
'FoldD0': 'PctViable_FoldD0',
'TotalCellArea': 'PctViable_TotalCellArea',
}
all_summary_rows = []
for metric_label, pv_col in METRICS_FOR_TI.items():
if pv_col not in df.columns:
print(f'\n {metric_label}: column {pv_col} not found, skipping.')
continue
all_drugs_in_df = sorted(df.Drug.dropna().unique())
drug_ab = {d: parse_drug(d, TEST_AB, ISO_AB)[0] for d in all_drugs_in_df}
drug_lp = {d: parse_drug(d, TEST_AB, ISO_AB)[1] for d in all_drugs_in_df}
test_lps = {drug_lp[d] for d in all_drugs_in_df if drug_ab[d] == TEST_AB}
iso_lps = {drug_lp[d] for d in all_drugs_in_df if drug_ab[d] == ISO_AB}
matched_lps = sorted(test_lps & iso_lps)
if not matched_lps:
print(f'\n {metric_label}: no matched LPs between {TEST_AB} and {ISO_AB}.')
continue
days = sorted(df[df.Day.isin(fit_days)].Day.unique())
print(f'\n{"="*60}')
print(f' {metric_label} (%Viable)')
print(f' Matched LPs: {matched_lps}')
print(f'{"="*60}')
for day in days:
day_df = df[(df.Day == day)].copy()
rows = []
for lp in matched_lps:
test_drug = f'{TEST_AB}-{lp}'
iso_drug = f'{ISO_AB}-{lp}'
test_sub = day_df[(day_df.Drug == test_drug)].dropna(subset=['Conc', pv_col])
iso_sub = day_df[(day_df.Drug == iso_drug)].dropna(subset=['Conc', pv_col])
if test_sub.empty or iso_sub.empty:
continue
t_ic50, t_target, t_conf = relative_ic50(test_sub.Conc, test_sub[pv_col])
i_ic50, i_target, i_conf = relative_ic50(iso_sub.Conc, iso_sub[pv_col])
t_untx = test_sub.groupby('Conc')[pv_col].mean().sort_index().iloc[0]
t_maxd = test_sub.groupby('Conc')[pv_col].mean().sort_index().iloc[-1]
i_untx = iso_sub.groupby('Conc')[pv_col].mean().sort_index().iloc[0]
i_maxd = iso_sub.groupby('Conc')[pv_col].mean().sort_index().iloc[-1]
ti = i_ic50 / t_ic50 if (not np.isnan(t_ic50) and t_ic50 > 0
and not np.isnan(i_ic50)) else np.nan
ti_conf = t_conf and i_conf and not np.isnan(ti)
def fmt(val, conf):
if np.isnan(val):
return 'NA'
return f'{val:.2f}' if conf else f'{val:.2f}*'
rows.append({
'LP': lp,
f'{TEST_AB} untx→max': f'{t_untx:.0f}→{t_maxd:.0f}%',
f'{TEST_AB} IC50 (nM)': fmt(t_ic50, t_conf),
f'{ISO_AB} untx→max': f'{i_untx:.0f}→{i_maxd:.0f}%',
f'{ISO_AB} IC50 (nM)': fmt(i_ic50, i_conf),
f'TI ({ISO_AB}/{TEST_AB})': fmt(ti, ti_conf),
})
all_summary_rows.append({
'Method': metric_label, 'Day': day, 'LP': lp,
f'{TEST_AB}_IC50_nM': t_ic50, f'{TEST_AB}_confident': t_conf,
f'{TEST_AB}_untreated_%': t_untx, f'{TEST_AB}_maxdose_%': t_maxd,
f'{ISO_AB}_IC50_nM': i_ic50, f'{ISO_AB}_confident': i_conf,
f'{ISO_AB}_untreated_%': i_untx, f'{ISO_AB}_maxdose_%': i_maxd,
'TI': ti, 'TI_confident': ti_conf,
})
if not rows:
print(f'\n Day {day}: no matched LP pairs with data.')
continue
tbl = pd.DataFrame(rows)
print(f'\n--- {metric_label} — Day {day} ---')
print(f' IC50 = conc at midpoint of (untreated, max-dose)')
print(f' TI = IC50({ISO_AB}) / IC50({TEST_AB}) ; * = low confidence')
print(tbl.to_string(index=False))
# Grouped bar chart: IC50 by LP
plot_rows = [r for r in rows
if r[f'{TEST_AB} IC50 (nM)'] != 'NA' or r[f'{ISO_AB} IC50 (nM)'] != 'NA']
if not plot_rows:
continue
lps_plot = [r['LP'] for r in plot_rows]
fig, ax = plt.subplots(figsize=(max(6, len(lps_plot) * 2.5), 5))
x = np.arange(len(lps_plot))
width = 0.35
colors = {TEST_AB: '#2196F3', ISO_AB: '#FF9800'}
for j, ab in enumerate([TEST_AB, ISO_AB]):
col_name = f'{ab} IC50 (nM)'
vals, labels, hatches = [], [], []
for r in plot_rows:
raw = r[col_name]
if raw == 'NA':
vals.append(0); labels.append('NA'); hatches.append('//')
else:
v = float(raw.rstrip('*'))
vals.append(v)
labels.append(raw)
hatches.append('//' if raw.endswith('*') else '')
bars = ax.bar(x + (j - 0.5) * width, vals, width, label=ab,
color=colors[ab], alpha=0.85)
for bar, lbl, hatch in zip(bars, labels, hatches):
bar.set_hatch(hatch)
if lbl != 'NA' and bar.get_height() > 0:
ax.text(bar.get_x() + bar.get_width() / 2, bar.get_height(),
lbl, ha='center', va='bottom', fontsize=9)
ax.set_xticks(x)
ax.set_xticklabels(lps_plot, fontsize=11)
ax.set_ylabel('Relative IC50 (nM)')
ax.set_title(f'{metric_label} — Day {day}\nRelative IC50 by Linker-Payload (* = low confidence)',
fontsize=13)
ax.legend()
ax.set_yscale('log')
plt.tight_layout()
save_fig()
# TI bar chart
ti_rows = [r for r in plot_rows if r[f'TI ({ISO_AB}/{TEST_AB})'] != 'NA']
if ti_rows:
ti_vals = [float(r[f'TI ({ISO_AB}/{TEST_AB})'].rstrip('*')) for r in ti_rows]
ti_lps = [r['LP'] for r in ti_rows]
ti_conf = [not r[f'TI ({ISO_AB}/{TEST_AB})'].endswith('*') for r in ti_rows]
fig, ax = plt.subplots(figsize=(max(5, len(ti_vals) * 2), 4.5))
bar_colors = ['#4CAF50' if c else '#FFC107' for c in ti_conf]
bar_hatches = ['' if c else '//' for c in ti_conf]
bars = ax.bar(range(len(ti_vals)), ti_vals, color=bar_colors, alpha=0.85)
for bar, hatch, v, c in zip(bars, bar_hatches, ti_vals, ti_conf):
bar.set_hatch(hatch)
lbl = f'{v:.1f}' + ('' if c else '*')
ax.text(bar.get_x() + bar.get_width() / 2, bar.get_height(),
lbl, ha='center', va='bottom', fontsize=10, fontweight='bold')
ax.axhline(1.0, color='red', linestyle='--', linewidth=1, label='TI = 1')
ax.set_xticks(range(len(ti_vals)))
ax.set_xticklabels(ti_lps, fontsize=11)
ax.set_ylabel(f'Therapeutic Index\nIC50({ISO_AB}) / IC50({TEST_AB})')
ax.set_title(f'{metric_label} — Day {day}\nTherapeutic Index (* = low confidence)',
fontsize=13)
ax.legend()
plt.tight_layout()
save_fig()
# Export combined summary
if all_summary_rows:
df_ti_summary = pd.DataFrame(all_summary_rows)
out = os.path.join(DATA_DIR, f'{ZIP_STEM}_therapeutic_index_{TEST_AB}_vs_{ISO_AB}.csv')
df_ti_summary.to_csv(out, index=False)
print(f'\nSaved combined summary: {out}')
print('\n' + '='*60)
print(' Combined Therapeutic Index Summary')
print('='*60)
print(df_ti_summary.round(2).to_string(index=False))