CFPAC — B5 vs Syn — 2026-04-16

CFPAC
B5-DM1
B5-GGFG-Dxd
B5-GGFG-Exa
B5-PDB
B5-VA-Exa
B5-VC-MMAE
Syn-DM1
Syn-GGFG-Dxd
Syn-GGFG-Exa8
Syn-PDB
Syn-VA-Exa
Syn-VC-MMAE
B5 vs Syn
Published

April 16, 2026

IC50 & Growth Kinetics — LS180 Conjugates

Analysis of PCM_LSConj data: 8 drugs across 2 plates, 6 timepoints.
Two metrics: Fold-D0 and raw Total Cell Area.
IC50 computed two ways: fitted LL.4 plateau midpoint and absolute 50% of untreated by direct interpolation.

Show code
from IPython.display import display, Image as IPImage
import os
import zipfile
import re
import pandas as pd
import numpy as np
from scipy.optimize import curve_fit
import matplotlib
import matplotlib.pyplot as plt
import seaborn as sns
import warnings
warnings.filterwarnings('ignore')

sns.set_style('whitegrid')
plt.rcParams.update({'figure.figsize': (10, 6), 'font.size': 12})

# =====================================================================
#  USER INPUT — change only this section to run a different experiment
# =====================================================================
BASE_DIR     = '/home/ericchen/gitpcm/2911_RnD/IC50_growth_kinetics'
DATA_SUBDIR  = '20260416_IC50_cfpac'  # subdir in BASE_DIR containing CSVs or zip
CELL_LINE    = 'cfpac' # cell line name shown in plot titles
TEST_AB      = 'B5'    # test article antibody prefix
ISO_AB       = 'Syn'   # isotype control antibody prefix
R2_THRESHOLD = 0.5     # minimum R² for a "reliable" LL.4 fit


SCALE_MIN_CONC = 0         # dose-response x-axis lower bound (0 = untreated pseudo-conc)
SCALE_MAX_CONC = None       # None uses all concentrations retained by the reversal filter
SCALE_EXCL_ABS = []         # all retained drugs contribute to y-axis scaling
REVERSAL_FILTER_METRIC = 'TotalCellArea'  # raw metric used to detect fragmentation artefacts
REVERSAL_INCREASE_THRESHOLD = 0.25        # exclude if >25% above the preceding concentration
# =====================================================================

DATA_DIR  = os.path.join(BASE_DIR, DATA_SUBDIR)
PLOT_DIR  = os.path.join(DATA_DIR, 'plots')
os.makedirs(PLOT_DIR, exist_ok=True)
plot_counter = [0]

def save_fig(title=''):
    plot_counter[0] += 1
    fname = os.path.join(PLOT_DIR, f'plot_{plot_counter[0]:02d}.png')
    plt.savefig(fname, dpi=120, bbox_inches='tight')
    plt.close()
    display(IPImage(filename=fname))

# Auto-discover data: prefer pre-extracted CSVs in DATA_DIR, else zip in DATA_DIR
_fname_pat    = re.compile(r'.*_P(?:late)?(\d+)_D(\d+)\.csv', re.IGNORECASE)
csv_data_files = sorted([f for f in os.listdir(DATA_DIR) if _fname_pat.match(f)])
zip_files      = sorted([f for f in os.listdir(DATA_DIR) if f.endswith('.zip')])

if len(csv_data_files) > 0:
    ZIP_PATH    = None
    ZIP_STEM    = DATA_SUBDIR
    EXTRACT_DIR = DATA_DIR
    USE_ZIP     = False
    print(f'No zip needed; using {len(csv_data_files)} pre-extracted CSV(s) in DATA_DIR')
elif len(zip_files) == 1:
    ZIP_PATH    = os.path.join(DATA_DIR, zip_files[0])
    ZIP_STEM    = os.path.splitext(zip_files[0])[0]
    EXTRACT_DIR = DATA_DIR
    USE_ZIP     = True
    print(f'Found zip: {zip_files[0]}')
else:
    raise AssertionError(
        f'No pre-extracted CSVs in {DATA_DIR} and no zip in {BASE_DIR}. '
        f'Found {len(zip_files)} zip(s).'
    )

# Plate layout CSVs live in DATA_DIR
PLATE_LAYOUTS = sorted([f for f in os.listdir(DATA_DIR)
                        if re.match(r'Plate\d+_layout\.csv', f)])
assert len(PLATE_LAYOUTS) >= 1, f'No Plate*_layout.csv found in {DATA_DIR}'

print(f'Data dir : {DATA_DIR}')
print(f'Zip      : {ZIP_PATH}')
print(f'Plates   : {len(PLATE_LAYOUTS)} layout(s) — {PLATE_LAYOUTS}')
print(f'X-axis   : {SCALE_MIN_CONC} – {SCALE_MAX_CONC if SCALE_MAX_CONC is not None else "all retained concentrations"}')
print(f'Excl ABs : {SCALE_EXCL_ABS} (excluded from y-axis range only)')
No zip needed; using 48 pre-extracted CSV(s) in DATA_DIR
Data dir : /home/ericchen/gitpcm/2911_RnD/IC50_growth_kinetics/20260416_IC50_cfpac
Zip      : None
Plates   : 6 layout(s) — ['Plate1_layout.csv', 'Plate2_layout.csv', 'Plate3_layout.csv', 'Plate4_layout.csv', 'Plate5_layout.csv', 'Plate6_layout.csv']
X-axis   : 0 – all retained concentrations
Excl ABs : [] (excluded from y-axis range only)

Load Data from Zip

Show code
# ===========================================================================
# 1. Extract zip (if needed) and load confluency data
# ===========================================================================
print('\n=== 1. Extract zip and load confluency data ===')
os.makedirs(EXTRACT_DIR, exist_ok=True)
if USE_ZIP:
    with zipfile.ZipFile(ZIP_PATH, 'r') as z:
        z.extractall(EXTRACT_DIR)

csv_files = sorted([f for f in os.listdir(EXTRACT_DIR) if f.endswith('.csv')])
print(f'{len(csv_files)} CSV files {"extracted" if USE_ZIP else "found"}')

# Flexible pattern: matches _Plate1_D0, _P1_D0, _P1_D07, etc.
fname_pattern = re.compile(r'.*_P(?:late)?(\d+)_D(\d+)\.csv', re.IGNORECASE)

frames = []
seen = set()
for fname in csv_files:
    m = fname_pattern.match(fname)
    if not m:
        continue
    plate_num = int(m.group(1))
    day       = int(m.group(2))
    key = (plate_num, day)
    if key in seen:
        continue
    seen.add(key)
    tmp = pd.read_csv(os.path.join(EXTRACT_DIR, fname), index_col=0)
    tmp.index.name = 'Well'
    tmp = tmp.reset_index()
    tmp['Plate'] = plate_num
    tmp['Day']   = day
    frames.append(tmp)

df_raw = pd.concat(frames, ignore_index=True)
df_raw.rename(columns={'Total cell area': 'TotalCellArea'}, inplace=True)

print(f'Combined raw data: {df_raw.shape[0]} rows  x  {df_raw.shape[1]} cols')
print(f'Plates: {sorted(df_raw.Plate.unique())}   Days: {sorted(df_raw.Day.unique())}')

=== 1. Extract zip and load confluency data ===
62 CSV files found
Combined raw data: 2880 rows  x  5 cols
Plates: [np.int64(1), np.int64(2), np.int64(3), np.int64(4), np.int64(5), np.int64(6)]   Days: [np.int64(0), np.int64(1), np.int64(2), np.int64(3), np.int64(4), np.int64(5), np.int64(6), np.int64(7)]

Merge Plate Layouts

Show code
# ===========================================================================
# 2. Load plate layouts and merge
# ===========================================================================
print('\n=== 2. Load plate layouts and merge ===')
layout_frames = []
for lf in PLATE_LAYOUTS:
    plate_num = int(re.search(r'Plate(\d+)', lf).group(1))
    tmp = pd.read_csv(os.path.join(DATA_DIR, lf))
    tmp.rename(columns={'Cell': 'Well'}, inplace=True)
    tmp['Plate'] = plate_num
    layout_frames.append(tmp)
    print(f'Plate {plate_num} drugs: {sorted(tmp.Drug.unique())}')

layouts = pd.concat(layout_frames, ignore_index=True)
print(f'Layout entries: {len(layouts)}  ({len(PLATE_LAYOUTS)} plates)')

df = df_raw.merge(layouts[['Well', 'Drug', 'Conc', 'Plate']],
                  on=['Well', 'Plate'], how='left')

unmatched = df.Drug.isna().sum()
if unmatched > 0:
    print(f'WARNING: {unmatched} wells did not match a layout entry')
else:
    print('All wells matched their layout.')

print(f'Drugs: {sorted(df.Drug.dropna().unique())}')
print(f'Concentrations: {sorted(df.Conc.dropna().unique())}')

# Auto-derive concentration parameters from the data
nonzero_concs = df.loc[df.Conc > 0, 'Conc']
CONC_MIN   = nonzero_concs.min()
CONC_MAX   = nonzero_concs.max()
PSEUDO_CONC = CONC_MIN / 10.0

df['Conc_orig'] = df['Conc'].copy()
df.loc[df.Conc == 0, 'Conc'] = PSEUDO_CONC
print(f'Conc range: {CONC_MIN:.4g} – {CONC_MAX:.4g} nM')
print(f'Conc==0 replaced with pseudo-conc {PSEUDO_CONC:.4g} nM')

=== 2. Load plate layouts and merge ===
Plate 1 drugs: ['B5-DM1', 'Syn-DM1']
Plate 2 drugs: ['B5-GGFG-DXd', 'Syn-GGFG-DXd']
Plate 3 drugs: ['B5-GGFG-Exa', 'Syn-GGFG-Exa']
Plate 4 drugs: ['B5-PDB', 'Syn-PDB']
Plate 5 drugs: ['B5-VA-Exa', 'Syn-VA-Exa']
Plate 6 drugs: ['B5-VC-MMAE', 'Syn-VC-MMAE']
Layout entries: 360  (6 plates)
All wells matched their layout.
Drugs: ['B5-DM1', 'B5-GGFG-DXd', 'B5-GGFG-Exa', 'B5-PDB', 'B5-VA-Exa', 'B5-VC-MMAE', 'Syn-DM1', 'Syn-GGFG-DXd', 'Syn-GGFG-Exa', 'Syn-PDB', 'Syn-VA-Exa', 'Syn-VC-MMAE']
Concentrations: [np.float64(0.0), np.float64(0.00594702672), np.float64(0.02676162024), np.float64(0.1204272911), np.float64(0.5419228099), np.float64(2.438652644), np.float64(10.9739369), np.float64(49.38271605), np.float64(222.2222222), np.float64(1000.0)]
Conc range: 0.005947 – 1000 nM
Conc==0 replaced with pseudo-conc 0.0005947 nM

Fold-D0 Normalization

Show code
# ===========================================================================
# 3. Fold-D0 normalization
# ===========================================================================
print('\n=== 3. Fold-D0 normalization ===')
d0_confl = df[df.Day == 0][['Plate', 'Well', 'Confluence']].rename(
    columns={'Confluence': 'Confluence_D0'})
d0_tca = df[df.Day == 0][['Plate', 'Well', 'TotalCellArea']].rename(
    columns={'TotalCellArea': 'TCA_D0'})

df = df.merge(d0_confl, on=['Plate', 'Well'], how='left')
df = df.merge(d0_tca, on=['Plate', 'Well'], how='left')
df['FoldD0'] = df['Confluence'] / df['Confluence_D0']
df['FoldD0_TCA'] = df['TotalCellArea'] / df['TCA_D0']

print('All wells have D0 baseline.' if df.Confluence_D0.isna().sum() == 0
      else f'WARNING: {df.Confluence_D0.isna().sum()} rows missing D0')
print(f'Fold-D0 stats by Day:')
print(df.groupby('Day')['FoldD0'].describe().round(3).to_string())

# Drug-by-drug fragmentation filter. Compare mean raw cell area at each
# concentration with the immediately preceding concentration for that drug/day.
_filter_means = (
    df.groupby(['Drug', 'Day', 'Conc'], dropna=False)[REVERSAL_FILTER_METRIC]
    .mean().rename('Reversal_Filter_Mean').reset_index()
    .sort_values(['Drug', 'Day', 'Conc'])
)
_filter_means['Reversal_Previous_Mean'] = (
    _filter_means.groupby(['Drug', 'Day'])['Reversal_Filter_Mean'].shift(1)
)
_prev = _filter_means['Reversal_Previous_Mean']
_curr = _filter_means['Reversal_Filter_Mean']
_filter_means['Reversal_Pct_Increase'] = np.where(
    _prev > 0, (_curr - _prev) / _prev,
    np.where((_prev == 0) & (_curr > 0), np.inf, np.nan)
)
_filter_means['Exclude_25pct_Reversal'] = (
    _filter_means['Reversal_Pct_Increase'] > REVERSAL_INCREASE_THRESHOLD
)
df = df.merge(
    _filter_means[['Drug', 'Day', 'Conc', 'Reversal_Filter_Mean',
                   'Reversal_Previous_Mean', 'Reversal_Pct_Increase',
                   'Exclude_25pct_Reversal']],
    on=['Drug', 'Day', 'Conc'], how='left'
)
df['Exclude_25pct_Reversal'] = df['Exclude_25pct_Reversal'].fillna(False).astype(bool)

excluded_reversals = _filter_means[_filter_means.Exclude_25pct_Reversal].copy()
print(f'\n25% reversal filter metric: {REVERSAL_FILTER_METRIC}')
print(f'Excluded drug/day/concentration groups: {len(excluded_reversals)}')
if not excluded_reversals.empty:
    display(excluded_reversals[['Drug', 'Day', 'Conc', 'Reversal_Previous_Mean',
                                'Reversal_Filter_Mean', 'Reversal_Pct_Increase']])

=== 3. Fold-D0 normalization ===
All wells have D0 baseline.
Fold-D0 stats by Day:
     count    mean     std    min    25%     50%     75%     max
Day                                                             
0    360.0   1.000   0.000  1.000  1.000   1.000   1.000   1.000
1    360.0   2.308   2.437  1.189  1.838   1.973   2.114  23.521
2    360.0   4.648   1.668  1.274  3.728   5.042   5.497  17.013
3    360.0   7.889   3.234  1.459  5.530   9.269  10.203  12.568
4    360.0  12.508   5.946  1.546  6.838  15.124  16.905  20.915
5    360.0  17.389   9.224  1.553  7.270  21.229  24.176  30.664
6    360.0  19.968  10.997  1.414  7.473  24.444  28.507  36.921
7    360.0  19.056  11.683  1.322  6.871  21.636  29.880  38.598

25% reversal filter metric: TotalCellArea
Excluded drug/day/concentration groups: 37
Drug Day Conc Reversal_Previous_Mean Reversal_Filter_Mean Reversal_Pct_Increase
19 B5-DM1 1 1000.000000 1.043374 4.746814 3.549483
29 B5-DM1 2 1000.000000 1.551995 5.353862 2.449666
39 B5-DM1 3 1000.000000 1.708196 5.808733 2.400508
49 B5-DM1 4 1000.000000 1.796861 4.609372 1.565236
59 B5-DM1 5 1000.000000 1.935504 4.372258 1.258977
69 B5-DM1 6 1000.000000 1.855016 3.767486 1.030972
79 B5-DM1 7 1000.000000 1.853400 3.538387 0.909133
157 B5-GGFG-DXd 7 49.382716 11.092589 16.239025 0.463953
247 B5-PDB 0 49.382716 0.863431 1.564800 0.812305
249 B5-PDB 0 1000.000000 1.242249 5.885008 3.737382
257 B5-PDB 1 49.382716 1.806283 3.236547 0.791827
258 B5-PDB 1 222.222222 3.236547 5.651173 0.746050
259 B5-PDB 1 1000.000000 5.651173 12.419334 1.197656
269 B5-PDB 2 1000.000000 4.041869 11.335824 1.804600
279 B5-PDB 3 1000.000000 3.128466 9.910748 2.167925
289 B5-PDB 4 1000.000000 4.781897 13.735197 1.872332
299 B5-PDB 5 1000.000000 3.482991 11.526120 2.309259
309 B5-PDB 6 1000.000000 3.345216 11.271500 2.369438
319 B5-PDB 7 1000.000000 3.265019 11.440782 2.504048
481 Syn-DM1 0 0.005947 0.969570 1.212073 0.250114
519 Syn-DM1 3 1000.000000 1.366337 1.728990 0.265419
539 Syn-DM1 5 1000.000000 1.542516 2.025114 0.312864
549 Syn-DM1 6 1000.000000 1.491629 1.985648 0.331195
559 Syn-DM1 7 1000.000000 1.462221 2.135050 0.460142
637 Syn-GGFG-DXd 7 49.382716 12.923211 17.284283 0.337460
721 Syn-PDB 0 0.005947 0.865488 1.092448 0.262233
729 Syn-PDB 0 1000.000000 0.803853 1.244651 0.548357
738 Syn-PDB 1 222.222222 1.668818 18.385714 10.017207
748 Syn-PDB 2 222.222222 1.618802 3.235699 0.998822
749 Syn-PDB 2 1000.000000 3.235699 19.459487 5.013999
758 Syn-PDB 3 222.222222 1.349897 7.354263 4.448019
759 Syn-PDB 3 1000.000000 7.354263 13.635557 0.854103
768 Syn-PDB 4 222.222222 1.375324 13.443889 8.775072
769 Syn-PDB 4 1000.000000 13.443889 21.661572 0.611258
778 Syn-PDB 5 222.222222 1.425240 20.100660 13.103355
788 Syn-PDB 6 222.222222 1.505803 20.247209 12.446119
798 Syn-PDB 7 222.222222 1.481243 20.182872 12.625633

Drug & Color Setup

Show code
# ===========================================================================
# 4. Drug/color mapping (all 8 drugs together)
# ===========================================================================
all_drugs = sorted(df.Drug.dropna().unique())
fit_days = [d for d in sorted(df.Day.unique()) if d > 0]
all_days = sorted(df.Day.unique())

def _split_ab_lp(name):
    """Split 'AB-LP' on the first dash. LP may contain further dashes."""
    idx = name.find('-')
    return (name[:idx], name[idx+1:]) if idx >= 0 else (name, None)

# Unique AB prefixes and LP suffixes
_all_abs_setup = sorted({_split_ab_lp(d)[0] for d in all_drugs})
_all_lps_setup = sorted({lp for d in all_drugs
                          for lp in [_split_ab_lp(d)[1]] if lp is not None})

# Color  → AB prefix   (same AB = same color across all LPs)
# Style  → LP suffix   (same LP = same linestyle across all ABs)
_ls_cycle = [
    '-',
    '--',
    '-.',
    ':',
    (0, (5, 1)),
    (0, (3, 1, 1, 1)),
    (0, (1, 1)),
    (0, (5, 5)),
    (0, (3, 5, 1, 5)),
    (0, (3, 1, 1, 1, 1, 1)),
]
ab_colors     = dict(zip(_all_abs_setup, sns.color_palette('tab10', len(_all_abs_setup))))
lp_linestyles = {lp: _ls_cycle[i % len(_ls_cycle)]
                 for i, lp in enumerate(_all_lps_setup)}

# Convenience dicts keyed by full drug name (used throughout plotting code)
drug_colors     = {d: ab_colors[_split_ab_lp(d)[0]] for d in all_drugs}
drug_linestyles = {d: lp_linestyles.get(_split_ab_lp(d)[1], '-') for d in all_drugs}

print(f'\n{len(all_drugs)} drugs: {all_drugs}')
print(f'  AB prefixes  ({len(_all_abs_setup)}): {_all_abs_setup}')
print(f'  Linker-payloads ({len(_all_lps_setup)}): {_all_lps_setup}')

12 drugs: ['B5-DM1', 'B5-GGFG-DXd', 'B5-GGFG-Exa', 'B5-PDB', 'B5-VA-Exa', 'B5-VC-MMAE', 'Syn-DM1', 'Syn-GGFG-DXd', 'Syn-GGFG-Exa', 'Syn-PDB', 'Syn-VA-Exa', 'Syn-VC-MMAE']
  AB prefixes  (2): ['B5', 'Syn']
  Linker-payloads (6): ['DM1', 'GGFG-DXd', 'GGFG-Exa', 'PDB', 'VA-Exa', 'VC-MMAE']
Show code
# ===========================================================================
# 4b. Heatmap: TotalCellArea — replicates (96-well grid) + mean (drug × conc)
#     Top panel   : actual plate layout, individual wells (replicates)
#     Bottom panel: mean TotalCellArea per Drug × Concentration
# ===========================================================================
print('\n=== 4b. TotalCellArea heatmaps ===')
import re as _re
from matplotlib.colors import LinearSegmentedColormap

_hm_cmap = LinearSegmentedColormap.from_list(
    'bio_heat', ['green', 'yellow', 'orange', 'red'])

def _parse_well(well):
    """Parse 'A1' → (row 0-7, col 0-11). Returns (None, None) on failure."""
    m = _re.match(r'([A-Ha-h])(\d+)', str(well).strip())
    if not m:
        return None, None
    return ord(m.group(1).upper()) - ord('A'), int(m.group(2)) - 1

_row_labels = list('ABCDEFGH')
_col_labels  = [str(i) for i in range(1, 13)]

# User setting: number of latest non-D0 scan days to show in heatmaps.
# 1 = latest scan only; 2 = latest two scans; etc.
last_n_to_show = 1

_heatmap_days = sorted(fit_days)
_total_heatmap_scans = len(_heatmap_days)
_last_n = int(last_n_to_show)
if _last_n < 1:
    print(f'WARNING: last_n_to_show={last_n_to_show} is less than 1; showing the latest scan only.')
    _last_n = 1
if _last_n > _total_heatmap_scans:
    print(
        f'WARNING: last_n_to_show={last_n_to_show} exceeds total number of scans '
        f'({_total_heatmap_scans}); showing all scans: {_heatmap_days}.'
    )
    _last_n = _total_heatmap_scans
_heatmap_days = _heatmap_days[-_last_n:]
print(f'Heatmap days selected: {_heatmap_days} (last_n_to_show={last_n_to_show})')

for _hm_plate in sorted(df.Plate.unique()):
    for _hm_day in _heatmap_days:
        _hm_sub = df[(df.Plate == _hm_plate) & (df.Day == _hm_day)].copy()
        if _hm_sub.empty:
            continue

        # ── Top: 96-well plate grid (one value per well) ──
        _grid      = np.full((8, 12), np.nan)
        _row_drug  = {}   # row_idx -> drug label
        _col_conc  = {}   # col_idx -> conc label

        for _, wr in _hm_sub.iterrows():
            r, c = _parse_well(wr['Well'])
            if r is None or not (0 <= r < 8 and 0 <= c < 12):
                continue
            _grid[r, c] = wr['TotalCellArea']
            # Collect drug per row and conc per column
            drug_val = wr['Drug'] if pd.notna(wr['Drug']) else ''
            conc_val = wr['Conc_orig'] if pd.notna(wr['Conc_orig']) else np.nan
            if drug_val:
                _row_drug.setdefault(r, set()).add(drug_val)
            if not np.isnan(conc_val):
                _col_conc.setdefault(c, set()).add(conc_val)

        _plate_df = pd.DataFrame(_grid, index=_row_labels, columns=_col_labels)

        # Build secondary axis label lists (one per row/col)
        _sec_row = []
        for ri in range(8):
            drugs = _row_drug.get(ri, set())
            _sec_row.append(', '.join(sorted(drugs)) if drugs else '')

        _sec_col = []
        for ci in range(12):
            concs = _col_conc.get(ci, set())
            if concs:
                v = sorted(concs)[0]
                _sec_col.append('Untreated' if v == 0 else f'{v:g}')
            else:
                _sec_col.append('')

        # ── Bottom: Drug × Conc mean ──
        _hm_pivot = (
            _hm_sub.groupby(['Drug', 'Conc_orig'])['TotalCellArea']
            .mean().unstack()
        )
        _hm_pivot = _hm_pivot.sort_index(axis=0)
        _hm_pivot = _hm_pivot.reindex(sorted(_hm_pivot.columns, reverse=True), axis=1)
        _hm_pivot.columns = [
            'Untreated' if c == 0 else f'{c:g}' for c in _hm_pivot.columns
        ]

        # Shared color scale
        _vmin = np.nanmin([np.nanmin(_grid), _hm_pivot.values.min()])
        _vmax = np.nanmax([np.nanmax(_grid), _hm_pivot.values.max()])

        _n_drug_rows = _hm_pivot.shape[0]
        fig, (ax_top, ax_bot) = plt.subplots(
            2, 1,
            figsize=(16, 10 + _n_drug_rows * 0.5),
            gridspec_kw={'height_ratios': [8, max(2, _n_drug_rows)]},
        )

        # Top: individual wells, formatted to match the averaged heatmap
        sns.heatmap(
            _plate_df, ax=ax_top,
            cmap=_hm_cmap, vmin=_vmin, vmax=_vmax,
            annot=True, fmt='.2f', annot_kws={'size': 7},
            linewidths=0.5, linecolor='white',
            mask=_plate_df.isna(),
            xticklabels=_sec_col,
            yticklabels=_sec_row,
            cbar_kws={'label': 'TotalCellArea (mm²)'},
        )
        ax_top.set_title('Individual wells (replicates)', fontsize=11)
        ax_top.set_xlabel('Concentration (nM)')
        ax_top.set_ylabel('Drug')
        ax_top.tick_params(axis='both', labelsize=10, length=0)
        ax_top.set_xticklabels(_sec_col, fontsize=10, rotation=0)
        ax_top.set_yticklabels(_sec_row, fontsize=10, rotation=0)
        ax_top.grid(False)

        # Bottom: mean per drug × conc
        sns.heatmap(
            _hm_pivot, ax=ax_bot,
            cmap=_hm_cmap, vmin=_vmin, vmax=_vmax,
            annot=True, fmt='.2f',
            linewidths=0.5, linecolor='white',
            cbar_kws={'label': 'TotalCellArea (mm²)'},
        )
        ax_bot.set_title('Mean per Drug × Concentration', fontsize=11)
        ax_bot.set_xlabel('Concentration (nM)')
        ax_bot.set_ylabel('Drug')
        ax_bot.tick_params(axis='both', labelsize=10, length=0)
        ax_bot.set_xticklabels([t.get_text() for t in ax_bot.get_xticklabels()], fontsize=10, rotation=0)
        ax_bot.set_yticklabels([t.get_text() for t in ax_bot.get_yticklabels()], fontsize=10, rotation=0)

        fig.suptitle(
            f'{CELL_LINE} — TotalCellArea — Day {_hm_day} (Plate {_hm_plate})',
            fontsize=13,
        )
        plt.tight_layout()
        save_fig()

=== 4b. TotalCellArea heatmaps ===
Heatmap days selected: [np.int64(7)] (last_n_to_show=1)

Growth Kinetics Plots

Show code
# ===========================================================================
# 5. Growth kinetics plots (per drug, combined plates)
# ===========================================================================
print('\n=== 4. Growth kinetics plots ===')
for drug in all_drugs:
    sub = df[df.Drug == drug].copy()
    concs = sorted(sub.Conc.unique())

    fig, axes = plt.subplots(1, 2, figsize=(16, 5), sharey=False)

    for ax, metric, ylabel in [
        (axes[0], 'FoldD0',        'Fold D0 (Confluence)'),
        (axes[1], 'TotalCellArea', 'Total Cell Area (mm²)'),
    ]:
        for conc in concs:
            csub = sub[sub.Conc == conc]
            means = csub.groupby('Day')[metric].mean()
            sds   = csub.groupby('Day')[metric].std()
            lbl = 'untreated' if conc == PSEUDO_CONC else f'{conc} nM'
            ax.errorbar(means.index, means.values, yerr=sds.values,
                        marker='o', capsize=3, label=lbl)
        ax.set_xlabel('Day')
        ax.set_ylabel(ylabel)
        ax.set_xticks(all_days)
        ax.legend(title='Conc', fontsize=8, title_fontsize=9)

    fig.suptitle(f'{drug} — Growth Kinetics', fontsize=14)
    plt.tight_layout()
    save_fig()

=== 4. Growth kinetics plots ===

LL.4 Model & Interpolation Functions

Show code
# ===========================================================================
# 6. LL.4 fitting functions
# ===========================================================================
print('\n=== 5. LL.4 model ===')

def ll4(x, slope, lower, upper, ec50):
    return lower + (upper - lower) / (1.0 + (x / ec50) ** slope)


def compute_r2(y_obs, y_pred):
    ss_res = np.sum((y_obs - y_pred) ** 2)
    ss_tot = np.sum((y_obs - np.mean(y_obs)) ** 2)
    if ss_tot == 0:
        return 0.0
    return 1.0 - ss_res / ss_tot


def fit_ll4(conc, response, p0=None):
    """Fit LL.4 using the points supplied by the shared analysis filter."""
    conc = np.asarray(conc, dtype=float)
    response = np.asarray(response, dtype=float)
    mask = (conc > 0) & np.isfinite(response)
    conc, response = conc[mask], response[mask]
    if len(conc) < 4 or len(np.unique(conc)) < 3:
        return None, None

    cmin, cmax = conc.min(), conc.max()
    if p0 is None:
        p0 = [1.0, np.min(response), np.max(response), np.median(conc)]

    bounds = (
        [0.01,   -np.inf, -np.inf, cmin * 0.01],
        [np.inf,  np.inf,  np.inf, cmax * 100 ]
    )

    try:
        popt, _ = curve_fit(ll4, conc, response, p0=p0,
                            maxfev=10000, bounds=bounds)
    except Exception:
        return None, None

    y_pred = ll4(conc, *popt)
    r2 = compute_r2(response, y_pred)
    return popt, r2


def fit_ll4_pct_viable(conc, response, upper=100.0):
    """Fit %Viable LL.4 with the untreated-normalized upper plateau fixed at 100%."""
    conc = np.asarray(conc, dtype=float)
    response = np.asarray(response, dtype=float)
    mask = (conc > 0) & np.isfinite(response)
    conc, response = conc[mask], response[mask]
    if len(conc) < 4 or len(np.unique(conc)) < 3:
        return None, None

    cmin, cmax = conc.min(), conc.max()

    def _ll4_fixed_upper(x, slope, lower, ec50):
        return ll4(x, slope, lower, upper, ec50)

    try:
        popt_fixed, _ = curve_fit(
            _ll4_fixed_upper, conc, response,
            p0=[1.0, np.min(response), np.median(conc)],
            bounds=([0.01, -np.inf, cmin * 0.01],
                    [np.inf, np.inf, cmax * 100]),
            maxfev=10000,
        )
    except Exception:
        return None, None

    slope, lower, ec50 = popt_fixed
    popt = np.array([slope, lower, upper, ec50])
    r2 = compute_r2(response, ll4(conc, *popt))
    return popt, r2


def classify_ic50(row):
    if row['R2'] < R2_THRESHOLD:
        return 'poor fit'
    if row['IC50_nM'] < CONC_MIN * 0.5:
        return f'<{CONC_MIN} nM'
    if row['IC50_nM'] > CONC_MAX * 2:
        return f'>{CONC_MAX} nM'
    return f"{row['IC50_nM']:.3g}"


def interpolate_ic50(concs, pct_viable, target=50.0):
    """
    Find concentration where mean %Viable crosses `target` (default 50%).
    Linear interpolation on log10(conc).
    Exclusions are applied before this function is called.
    Returns NaN if the curve never crosses the target.
    """
    means = pct_viable.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]

    for i in range(len(v) - 1):
        if (v[i] >= target and v[i+1] < target) or \
           (v[i] <= target and v[i+1] > target):
            log_c1, log_c2 = np.log10(c[i]), np.log10(c[i+1])
            frac = (target - v[i]) / (v[i+1] - v[i])
            return 10 ** (log_c1 + frac * (log_c2 - log_c1))

    if v[-1] < target and v[0] >= target:
        return c[-1]
    return np.nan


print(f'LL.4 defined.  R² threshold = {R2_THRESHOLD}')
print('Interpolation IC50 function defined.')
print('Drug/day-specific >25% reversal exclusions active for all IC50 calculations.')

=== 5. LL.4 model ===
LL.4 defined.  R² threshold = 0.5
Interpolation IC50 function defined.
Drug/day-specific >25% reversal exclusions active for all IC50 calculations.

Dose-Response Fitting & Plotting (Both Metrics)

Show code
# ===========================================================================
# 7. Dose-response fitting & plotting — BOTH metrics
# ===========================================================================
METRICS = {
    'FoldD0': {
        'col': 'FoldD0',
        'ylabel_dr': 'Fold D0 (Confluence)',
        'ylabel_pv': '% Viable (Fold-D0 normalized)',
    },
    'TotalCellArea': {
        'col': 'TotalCellArea',
        'ylabel_dr': 'Total Cell Area (mm²)',
        'ylabel_pv': '% Viable (TCA normalized)',
    },
}

all_ic50_tables = {}

# x-axis window derived from user-defined scale bounds
_xlo = PSEUDO_CONC if SCALE_MIN_CONC == 0 else SCALE_MIN_CONC
_xhi = CONC_MAX if SCALE_MAX_CONC is None else SCALE_MAX_CONC


def _analysis_rows(sub_df):
    """Rows allowed to affect scaling, fitted curves, and IC50 calculations."""
    return sub_df[~sub_df['Exclude_25pct_Reversal']].copy()


def _axis_limits(sub_df, col, xlo, xhi, pad=0.10):
    """Y-limits from data within [xlo, xhi], honouring SCALE_EXCL_ABS."""
    vis = _analysis_rows(sub_df[(sub_df['Conc'] >= xlo) & (sub_df['Conc'] <= xhi)])
    if SCALE_EXCL_ABS and 'Drug' in vis.columns:
        vis = vis[~vis['Drug'].str.split('-').str[0].isin(SCALE_EXCL_ABS)]
    if vis.empty:
        return None
    m = vis.groupby('Conc')[col].mean()
    s = vis.groupby('Conc')[col].std().fillna(0)
    lo, hi = (m - s).min(), (m + s).max()
    mg = (hi - lo) * pad if hi > lo else max(abs(hi), abs(lo)) * pad + 0.1
    return lo - mg, hi + mg


for metric_name, minfo in METRICS.items():
    col = minfo['col']
    print(f'\n{"="*60}')
    print(f'=== METRIC: {metric_name} ===')
    print(f'{"="*60}')

    # --- 7a. Dose-response plots (raw metric) ---
    print(f'\n--- Dose-response plots ({metric_name}) ---')
    fit_params_dr = {}
    ic50_dr_records = []

    for drug in all_drugs:
        for day in fit_days:
            sub = df[(df.Drug == drug) & (df.Day == day)].copy()
            sub = sub.dropna(subset=['Conc', col])
            sub = sub[(sub.Conc >= _xlo) & (sub.Conc <= _xhi)]
            sub = _analysis_rows(sub)
            if sub.empty:
                continue
            popt, r2 = fit_ll4(sub.Conc.values, sub[col].values)
            if popt is not None:
                fit_params_dr[(drug, day)] = popt
                ic50_dr_records.append({
                    'Drug': drug, 'Day': day,
                    'IC50_nM': popt[3], 'Slope': popt[0],
                    'Lower': popt[1], 'Upper': popt[2], 'R2': r2,
                })
            else:
                ic50_dr_records.append({
                    'Drug': drug, 'Day': day,
                    'IC50_nM': np.nan, 'Slope': np.nan,
                    'Lower': np.nan, 'Upper': np.nan, 'R2': np.nan,
                })

    for day in fit_days:
        # Pre-scan: y-range across all drugs within the visible x-window
        _all_vis = pd.concat([
            df[(df.Drug == d) & (df.Day == day)].dropna(subset=[col])
            for d in all_drugs
        ], ignore_index=True)
        _ylim_dr = _axis_limits(_all_vis, col, _xlo, _xhi)

        fig, ax = plt.subplots(figsize=(12, 7))
        for drug in all_drugs:
            sub = df[(df.Drug == drug) & (df.Day == day)].copy()
            sub = sub.dropna(subset=[col])
            if sub.empty:
                continue
            means = sub.groupby('Conc')[col].mean()
            sds   = sub.groupby('Conc')[col].std()
            ax.errorbar(means.index, means.values, yerr=sds.values,
                        marker='o', capsize=3, color=drug_colors[drug], label=drug,
                        linestyle='none', linewidth=1.0)
            key = (drug, day)
            if key in fit_params_dr:
                popt = fit_params_dr[key]
                curve_sub = _analysis_rows(sub[(sub.Conc >= _xlo) & (sub.Conc <= _xhi)])
                x_pred = np.geomspace(curve_sub.Conc.min(), curve_sub.Conc.max(), 200)
                y_pred = ll4(x_pred, *popt)
                ax.plot(x_pred, y_pred, color=drug_colors[drug], linewidth=1.5,
                        linestyle=drug_linestyles[drug])

        ax.set_xscale('log')
        if _ylim_dr:
            ax.set_ylim(*_ylim_dr)
        ax.set_xlabel('Concentration (nM, log scale)')
        ax.set_ylabel(minfo['ylabel_dr'])
        ax.set_title(f'Day {day} — Dose Response ({metric_name})')
        ax.legend(fontsize=8, loc='best')
        plt.tight_layout()
        save_fig()

    df_ic50_dr = pd.DataFrame(ic50_dr_records)
    df_ic50_dr['Reliable'] = (
        (df_ic50_dr['R2'] >= R2_THRESHOLD) &
        (df_ic50_dr['IC50_nM'] >= CONC_MIN * 0.5) &
        (df_ic50_dr['IC50_nM'] <= CONC_MAX * 2)
    )
    df_ic50_dr['Status'] = df_ic50_dr.apply(classify_ic50, axis=1)

    print(f'\n  IC50 ({metric_name} direct): {df_ic50_dr.Reliable.sum()} reliable '
          f'of {len(df_ic50_dr)}')

    # --- 7b. %Viable calculation ---
    pv_col = f'PctViable_{metric_name}'
    untx_mean = (
        df[df.Conc_orig == 0]
        .groupby(['Plate', 'Drug', 'Day'])[col]
        .mean()
        .reset_index()
        .rename(columns={col: f'UntxMean_{metric_name}'})
    )
    untx_col = f'UntxMean_{metric_name}'
    df = df.merge(untx_mean, on=['Plate', 'Drug', 'Day'], how='left')
    df[pv_col] = 100.0 * df[col] / df[untx_col]

    # --- 7c. Absolute IC50: interpolated crossing at 50% of untreated ---
    interp_records = []
    for drug in all_drugs:
        for day in fit_days:
            sub = df[(df.Drug == drug) & (df.Day == day)].copy()
            sub = sub.dropna(subset=['Conc', pv_col])
            sub = sub[(sub.Conc >= _xlo) & (sub.Conc <= _xhi)]
            sub = _analysis_rows(sub)
            if sub.empty:
                continue
            ic50_interp = interpolate_ic50(sub.Conc, sub[pv_col], target=50.0)
            interp_records.append({
                'Drug': drug, 'Day': day,
                'Absolute_IC50_nM': ic50_interp, 'IC50_interp': ic50_interp,
            })
    df_interp = pd.DataFrame(interp_records)
    all_ic50_tables[f'{metric_name}_interpolated'] = df_interp

    print(f'\n  Absolute IC50 at 50% untreated ({metric_name}): '
          f'{df_interp.IC50_interp.notna().sum()} of {len(df_interp)} crossed 50%')

    # --- 7d. Fitted IC50: LL.4 midpoint between fitted upper/lower plateaus ---
    fit_params_pv = {}
    ic50_pv_records = []

    for drug in all_drugs:
        for day in fit_days:
            sub = df[(df.Drug == drug) & (df.Day == day)].copy()
            sub = sub.dropna(subset=['Conc', pv_col])
            sub = sub[(sub.Conc >= _xlo) & (sub.Conc <= _xhi)]
            sub = _analysis_rows(sub)
            if sub.empty:
                continue
            popt, r2 = fit_ll4_pct_viable(sub.Conc.values, sub[pv_col].values)
            if popt is not None:
                fit_params_pv[(drug, day)] = popt
                ic50_pv_records.append({
                    'Drug': drug, 'Day': day,
                    'IC50_nM': popt[3], 'Fitted_IC50_nM': popt[3],
                    'Midpoint_Response': (popt[1] + popt[2]) / 2.0,
                    'Slope': popt[0], 'Lower': popt[1], 'Upper': popt[2], 'R2': r2,
                })
            else:
                ic50_pv_records.append({
                    'Drug': drug, 'Day': day,
                    'IC50_nM': np.nan, 'Fitted_IC50_nM': np.nan,
                    'Midpoint_Response': np.nan, 'Slope': np.nan,
                    'Lower': np.nan, 'Upper': np.nan, 'R2': np.nan,
                })

    # --- 7e. %Viable dose-response plots with absolute IC50 markers ---
    for day in fit_days:
        # Pre-scan: y-range across all drugs within the visible x-window
        _all_vis_pv = pd.concat([
            df[(df.Drug == d) & (df.Day == day)].dropna(subset=[pv_col])
            for d in all_drugs
        ], ignore_index=True)
        _ylim_pv = _axis_limits(_all_vis_pv, pv_col, _xlo, _xhi)
        if _ylim_pv:
            _ylim_pv = (0, _ylim_pv[1])

        fig, ax = plt.subplots(figsize=(12, 7))
        _absolute_marker_labeled = False
        for drug in all_drugs:
            sub = df[(df.Drug == drug) & (df.Day == day)].copy()
            sub = sub.dropna(subset=[pv_col])
            if sub.empty:
                continue
            means = sub.groupby('Conc')[pv_col].mean()
            sds   = sub.groupby('Conc')[pv_col].std()
            ax.errorbar(means.index, means.values, yerr=sds.values,
                        marker='o', capsize=3, color=drug_colors[drug], label=drug,
                        linestyle='none', linewidth=1.0)

            # Overlay LL.4 fitted curve if available
            key = (drug, day)
            if key in fit_params_pv:
                popt = fit_params_pv[key]
                curve_sub = _analysis_rows(sub[(sub.Conc >= _xlo) & (sub.Conc <= _xhi)])
                x_pred = np.geomspace(curve_sub.Conc.min(), curve_sub.Conc.max(), 200)
                y_pred = ll4(x_pred, *popt)
                ax.plot(x_pred, y_pred, color=drug_colors[drug], linewidth=1.5,
                        linestyle=drug_linestyles[drug])

            # Mark absolute IC50: concentration crossing 50% of untreated
            row = df_interp[(df_interp.Drug == drug) & (df_interp.Day == day)]
            if not row.empty and pd.notna(row.IC50_interp.values[0]):
                ic50_val = row.IC50_interp.values[0]
                ax.plot(ic50_val, 50, 'D', color=drug_colors[drug],
                        markersize=10, markeredgecolor='black', markeredgewidth=1,
                        label='Absolute IC50 (50% untreated)'
                        if not _absolute_marker_labeled else None,
                        zorder=5)
                _absolute_marker_labeled = True

        ax.set_xscale('log')
        if _ylim_pv:
            ax.set_ylim(*_ylim_pv)
        ax.set_xlabel('Concentration (nM, log scale)')
        ax.set_ylabel(minfo['ylabel_pv'])
        ax.set_title(f'Day {day} — %Viable ({metric_name}) — Absolute IC50 at 50% untreated')
        ax.axhline(50, color='red', ls='--', alpha=0.7, label='50% viable')
        ax.axhline(100, color='grey', ls='--', alpha=0.3)
        ax.legend(fontsize=8, loc='best')
        plt.tight_layout()
        save_fig()

    # --- 7f. %Viable dose-response plots with fitted-midpoint IC50 markers ---
    for day in fit_days:
        _all_vis_pv = pd.concat([
            df[(df.Drug == d) & (df.Day == day)].dropna(subset=[pv_col])
            for d in all_drugs
        ], ignore_index=True)
        _ylim_pv = _axis_limits(_all_vis_pv, pv_col, _xlo, _xhi, pad=0.05)

        fig, ax = plt.subplots(figsize=(12, 7))
        _fitted_marker_labeled = False
        for drug in all_drugs:
            sub = df[(df.Drug == drug) & (df.Day == day)].copy()
            sub = sub.dropna(subset=[pv_col])
            if sub.empty:
                continue
            means = sub.groupby('Conc')[pv_col].mean()
            sds   = sub.groupby('Conc')[pv_col].std()
            ax.errorbar(means.index, means.values, yerr=sds.values,
                        marker='o', capsize=3, color=drug_colors[drug], label=drug,
                        linestyle='none', linewidth=1.0)

            key = (drug, day)
            if key in fit_params_pv:
                popt = fit_params_pv[key]
                curve_sub = _analysis_rows(sub[(sub.Conc >= _xlo) & (sub.Conc <= _xhi)])
                x_pred = np.geomspace(curve_sub.Conc.min(), curve_sub.Conc.max(), 200)
                y_pred = ll4(x_pred, *popt)
                ax.plot(x_pred, y_pred, color=drug_colors[drug], linewidth=1.5,
                        linestyle=drug_linestyles[drug])

                fitted_ic50 = popt[3]
                fitted_midpoint = (popt[1] + popt[2]) / 2.0
                if _xlo <= fitted_ic50 <= _xhi:
                    ax.plot(fitted_ic50, fitted_midpoint, 'D', color=drug_colors[drug],
                            markersize=10, markeredgecolor='black', markeredgewidth=1,
                            label='Fitted IC50 (LL.4 plateau midpoint)'
                            if not _fitted_marker_labeled else None,
                            zorder=5)
                    _fitted_marker_labeled = True

        ax.set_xscale('log')
        if _ylim_pv:
            ax.set_ylim(*_ylim_pv)
        ax.set_xlabel('Concentration (nM, log scale)')
        ax.set_ylabel(minfo['ylabel_pv'])
        ax.set_title(f'Day {day} — %Viable ({metric_name}) — Fitted IC50 at LL.4 plateau midpoint')
        ax.legend(fontsize=8, loc='best')
        plt.tight_layout()
        save_fig()

    df_ic50_pv = pd.DataFrame(ic50_pv_records)
    df_ic50_pv['Reliable'] = (
        (df_ic50_pv['R2'] >= R2_THRESHOLD) &
        (df_ic50_pv['IC50_nM'] >= CONC_MIN * 0.5) &
        (df_ic50_pv['IC50_nM'] <= CONC_MAX * 2)
    )
    df_ic50_pv['Status'] = df_ic50_pv.apply(classify_ic50, axis=1)

    print(f'  Fitted-midpoint IC50 (%Viable {metric_name}): {df_ic50_pv.Reliable.sum()} reliable '
          f'of {len(df_ic50_pv)}')

    all_ic50_tables[f'{metric_name}_direct'] = df_ic50_dr
    all_ic50_tables[f'{metric_name}_pctViable'] = df_ic50_pv

============================================================
=== METRIC: FoldD0 ===
============================================================

--- Dose-response plots (FoldD0) ---


  IC50 (FoldD0 direct): 77 reliable of 84

  Absolute IC50 at 50% untreated (FoldD0): 71 of 84 crossed 50%

  Fitted-midpoint IC50 (%Viable FoldD0): 75 reliable of 84

============================================================
=== METRIC: TotalCellArea ===
============================================================

--- Dose-response plots (TotalCellArea) ---


  IC50 (TotalCellArea direct): 76 reliable of 84

  Absolute IC50 at 50% untreated (TotalCellArea): 71 of 84 crossed 50%

  Fitted-midpoint IC50 (%Viable TotalCellArea): 73 reliable of 84

Trellis: Test vs Isotype by Linker-Payload

Show code
# ===========================================================================
# 7g. Trellis: All Antibodies per Linker-Payload, one subplot per Day
# ===========================================================================
print('\n=== Trellis: dose-response by LP (all antibodies) ===')

# Build lp -> {ab: drug_name} from all drugs
_lp_ab_map = {}
for d in all_drugs:
    ab, lp = _split_ab_lp(d)
    if lp is not None:
        _lp_ab_map.setdefault(lp, {})[ab] = d

_all_lps  = sorted(_lp_ab_map.keys())
_markers  = ['o', 's', '^', 'D', 'v', 'P', '*', 'X', 'h', '<']
print(f'  Linker-payloads: {_all_lps}')
for lp, abmap in sorted(_lp_ab_map.items()):
    print(f'    {lp}: {sorted(abmap.keys())}')

# Derive TEST_AB / ISO_AB matched pairs for section 7g (TI trellis)
_test_drugs  = {lp: ab_drug[TEST_AB] for lp, ab_drug in _lp_ab_map.items() if TEST_AB in ab_drug}
_iso_drugs   = {lp: ab_drug[ISO_AB]  for lp, ab_drug in _lp_ab_map.items() if ISO_AB  in ab_drug}
_matched_lps = sorted(set(_test_drugs) & set(_iso_drugs))

for metric_name, minfo in METRICS.items():
    pv_col = f'PctViable_{metric_name}'

    for lp in _all_lps:
        ab_drug    = _lp_ab_map[lp]
        abs_sorted = sorted(ab_drug.keys())

        # Pre-scan: y-range within SCALE_MIN_CONC–SCALE_MAX_CONC, excluding SCALE_EXCL_ABS
        all_vals = []
        for day in fit_days:
            for ab, drug in ab_drug.items():
                if ab in SCALE_EXCL_ABS:
                    continue
                sub = df[(df.Drug == drug) & (df.Day == day)].dropna(subset=[pv_col])
                vis = sub[(sub.Conc >= _xlo) & (sub.Conc <= _xhi)]
                vis = _analysis_rows(vis)
                if not vis.empty:
                    means = vis.groupby('Conc')[pv_col].mean()
                    sds   = vis.groupby('Conc')[pv_col].std().fillna(0)
                    all_vals.extend((means + sds).tolist())
                    all_vals.extend((means - sds).tolist())
        if not all_vals:
            continue
        y_lo   = min(all_vals)
        y_hi   = max(all_vals)
        margin = (y_hi - y_lo) * 0.08
        ylim   = (y_lo - margin, y_hi + margin)

        ncols = len(fit_days)
        fig, axes = plt.subplots(1, ncols, figsize=(4 * ncols, 5), sharey=True)
        if ncols == 1:
            axes = [axes]

        for ax, day in zip(axes, fit_days):
            for i, ab in enumerate(abs_sorted):
                drug  = ab_drug[ab]
                sub   = df[(df.Drug == drug) & (df.Day == day)].dropna(subset=[pv_col])
                if sub.empty:
                    continue
                means = sub.groupby('Conc')[pv_col].mean()
                sds   = sub.groupby('Conc')[pv_col].std()
                mrkr  = _markers[i % len(_markers)]
                ax.errorbar(means.index, means.values, yerr=sds.values,
                            marker=mrkr, capsize=3, color=drug_colors[drug],
                            label=drug, linestyle='none', linewidth=1.0)
                key = (drug, day)
                if key in fit_params_pv:
                    popt   = fit_params_pv[key]
                    curve_sub = _analysis_rows(sub[(sub.Conc >= _xlo) & (sub.Conc <= _xhi)])
                    x_pred = np.geomspace(curve_sub.Conc.min(), curve_sub.Conc.max(), 200)
                    y_pred = ll4(x_pred, *popt)
                    ax.plot(x_pred, y_pred, color=drug_colors[drug], linewidth=1.5,
                            linestyle=drug_linestyles[drug])

            ax.set_xscale('log')
            ax.set_ylim(ylim)
            ax.set_title(f'Day {day}', fontsize=11)
            ax.set_xlabel('Conc (nM)')
            ax.axhline(50, color='red', ls=':', alpha=0.5)
            ax.axhline(100, color='grey', ls=':', alpha=0.3)
            if ax is axes[0]:
                ax.set_ylabel(minfo['ylabel_pv'])
            ax.legend(fontsize=7, loc='best')

        fig.suptitle(f'{lp} — %Viable ({metric_name})', fontsize=14, y=1.02)
        plt.tight_layout()
        save_fig()

=== Trellis: dose-response by LP (all antibodies) ===
  Linker-payloads: ['DM1', 'GGFG-DXd', 'GGFG-Exa', 'PDB', 'VA-Exa', 'VC-MMAE']
    DM1: ['B5', 'Syn']
    GGFG-DXd: ['B5', 'Syn']
    GGFG-Exa: ['B5', 'Syn']
    PDB: ['B5', 'Syn']
    VA-Exa: ['B5', 'Syn']
    VC-MMAE: ['B5', 'Syn']

Trellis: Therapeutic Index by Concentration

Show code
# ===========================================================================
# 7g. Trellis: Therapeutic Index per concentration, per LP x Day
#     TI = %Viable(ISO_AB) / %Viable(each test AB)
# ===========================================================================
print('\n=== Trellis: TI by concentration (all test ABs vs ISO_AB) ===')

for metric_name, minfo in METRICS.items():
    pv_col = f'PctViable_{metric_name}'

    _ti_data    = {}   # (lp, ab, day) -> (conc_array, ti_array)
    _lp_yranges = {}   # lp -> (ymin, ymax)

    for lp in _all_lps:
        ab_drug  = _lp_ab_map[lp]
        if ISO_AB not in ab_drug:
            continue
        iso_drug = ab_drug[ISO_AB]
        test_abs = sorted(ab_drug.keys())  # includes ISO_AB so TI=1 is shown
        if not test_abs:
            continue

        all_ti = []
        for ab in test_abs:
            drug = ab_drug[ab]
            for day in fit_days:
                sub_t = df[(df.Drug == drug)     & (df.Day == day)].dropna(subset=[pv_col])
                sub_i = df[(df.Drug == iso_drug) & (df.Day == day)].dropna(subset=[pv_col])
                sub_t = _analysis_rows(sub_t)
                sub_i = _analysis_rows(sub_i)
                if sub_t.empty or sub_i.empty:
                    continue
                mean_t = sub_t.groupby('Conc')[pv_col].mean()
                mean_i = sub_i.groupby('Conc')[pv_col].mean()
                shared = sorted(set(mean_t.index) & set(mean_i.index))
                if not shared:
                    continue
                concs = np.array(shared)
                ti    = np.array([mean_i[c] / mean_t[c] if mean_t[c] != 0 else np.nan
                                  for c in shared])
                _ti_data[(lp, ab, day)] = (concs, ti)
                all_ti.extend(ti[np.isfinite(ti)].tolist())

        if all_ti:
            _lp_yranges[lp] = (min(all_ti), max(all_ti))

    if not _lp_yranges:
        print(f'  No TI data for {metric_name}')
        continue

    lps_with_ti = [lp for lp in _all_lps if lp in _lp_yranges]
    nrows = len(lps_with_ti)
    ncols = len(fit_days)
    fig, axes = plt.subplots(nrows, ncols,
                             figsize=(3.5 * ncols, 3.5 * nrows),
                             squeeze=False)

    for row, lp in enumerate(lps_with_ti):
        ab_drug  = _lp_ab_map[lp]
        test_abs = sorted(ab_drug.keys())  # includes ISO_AB so TI=1 is shown
        y_lo, y_hi = _lp_yranges[lp]
        margin = (y_hi - y_lo) * 0.1 if y_hi > y_lo else 0.5
        ylim = (y_lo - margin, y_hi + margin)

        for col, day in enumerate(fit_days):
            ax = axes[row][col]
            for i, ab in enumerate(test_abs):
                drug = ab_drug[ab]
                key  = (lp, ab, day)
                if key not in _ti_data:
                    continue
                concs, ti = _ti_data[key]
                mrkr = _markers[i % len(_markers)]
                ax.plot(concs, ti,
                        marker=mrkr, linestyle=drug_linestyles[drug],
                        color=drug_colors[drug], markersize=5, linewidth=1.2,
                        label=drug)

            ax.axhline(1, color='red', ls='--', alpha=0.6)
            ax.set_xscale('log')
            ax.set_ylim(ylim)
            ax.legend(fontsize=6, loc='best')

            if row == 0:
                ax.set_title(f'Day {day}', fontsize=11)
            if col == 0:
                ax.set_ylabel(f'{lp}\nTI ({ISO_AB} / AB)', fontsize=9)
            else:
                ax.set_yticklabels([])
            if row == nrows - 1:
                ax.set_xlabel('Conc (nM)')
            else:
                ax.set_xticklabels([])

    fig.suptitle(f'Therapeutic Index — %Viable ({metric_name})\n'
                 f'TI = {ISO_AB} / each test AB   (red dashed = TI 1)',
                 fontsize=14, y=1.02)
    plt.tight_layout()
    save_fig()

=== Trellis: TI by concentration (all test ABs vs ISO_AB) ===

IC50 Summary Tables (Curve Fit)

Show code
# ===========================================================================
# 8. Summary tables — side-by-side comparison
# ===========================================================================
print('\n' + '='*60)
print('=== IC50 SUMMARY — COMPARISON ===')
print('='*60)

for label, df_tbl in all_ic50_tables.items():
    if 'interpolated' in label:
        continue  # handled separately below
    # Reliable IC50 pivot
    pivot = df_tbl[df_tbl.Reliable].pivot_table(
        index='Drug', columns='Day', values='IC50_nM')
    print(f'\n--- {label} — IC50 (nM), reliable only (R²≥{R2_THRESHOLD}, in range) ---')
    if pivot.empty:
        print('  (no reliable fits)')
    else:
        print(pivot.to_string(float_format=lambda x: f'{x:.3g}'))

# --- Absolute IC50 tables (direct crossing at 50% of untreated) ---
print('\n' + '='*60)
print('=== ABSOLUTE IC50 AT 50% OF UNTREATED (no curve fitting) ===')
print('='*60)

for metric_name in METRICS:
    label = f'{metric_name}_interpolated'
    df_interp_tbl = all_ic50_tables[label]
    pivot = df_interp_tbl.pivot_table(
        index='Drug', columns='Day', values='IC50_interp')
    print(f'\n--- {metric_name} — Absolute IC50 (nM) at 50% of untreated ---')
    print(pivot.to_string(float_format=lambda x: f'{x:.3g}'))

# Side-by-side: absolute 50%-untreated crossing vs fitted midpoint (FoldD0)
print('\n--- FoldD0: Absolute 50%-untreated vs fitted-midpoint IC50 ---')
interp = all_ic50_tables['FoldD0_interpolated'][['Drug', 'Day', 'IC50_interp']]
fitted = all_ic50_tables['FoldD0_pctViable']
fitted_rel = fitted[fitted.Reliable][['Drug', 'Day', 'IC50_nM']].rename(
    columns={'IC50_nM': 'IC50_LL4'})
compare = interp.merge(fitted_rel, on=['Drug', 'Day'], how='outer')
compare = compare.dropna(subset=['IC50_interp', 'IC50_LL4'], how='all')
compare['Diff_%'] = ((compare.IC50_interp - compare.IC50_LL4) /
                      compare.IC50_LL4 * 100).round(1)
print(compare.to_string(index=False, float_format=lambda x: f'{x:.3g}'))

============================================================
=== IC50 SUMMARY — COMPARISON ===
============================================================

--- FoldD0_direct — IC50 (nM), reliable only (R²≥0.5, in range) ---
Day             1    2    3    4     5     6     7
Drug                                              
B5-DM1       3.38 5.46 5.47 5.75  9.21  9.56  9.76
B5-GGFG-DXd   NaN  194  136  122   191   190   193
B5-GGFG-Exa   NaN  133 94.4 86.6  83.6  91.5   100
B5-PDB        NaN 7.36 3.42  0.9 0.586 0.504 0.408
B5-VA-Exa     223 91.1 49.3 46.9    45    44  44.6
B5-VC-MMAE    NaN   55 81.7 81.7  88.8   185   185
Syn-DM1      7.08 10.4 11.6 10.8  11.4  13.7  37.5
Syn-GGFG-DXd  NaN  167  161  124   138   192   199
Syn-GGFG-Exa  NaN  124 89.5 76.3  77.2    87  97.1
Syn-PDB      88.1 5.06 1.69 0.76 0.325 0.482 0.425
Syn-VA-Exa    NaN  109 60.7 42.7  46.1  45.3    45
Syn-VC-MMAE   143  124 95.4 91.2  92.8   185   180

--- FoldD0_pctViable — IC50 (nM), reliable only (R²≥0.5, in range) ---
Day             1    2    3     4     5     6     7
Drug                                               
B5-DM1       3.42  4.9 5.21  5.46  6.56  9.62  9.92
B5-GGFG-DXd   NaN  187  125   125   193   192   195
B5-GGFG-Exa   NaN  NaN 87.4    81  81.7  91.9  95.9
B5-PDB        NaN 8.31 3.43 0.997 0.654  0.54 0.441
B5-VA-Exa     225   94 49.4    47  45.5    45  45.2
B5-VC-MMAE    NaN 63.6 78.3  78.9  97.3   187   187
Syn-DM1      8.53 8.88 10.7  10.5  11.6  14.8  38.3
Syn-GGFG-DXd  NaN  154  148   129   198   195   205
Syn-GGFG-Exa  NaN  190 83.7  74.5    75  82.9  84.5
Syn-PDB      74.7 28.8 1.98 0.725 0.268 0.359 0.354
Syn-VA-Exa    NaN  119 58.4  40.2  45.9    45  45.3
Syn-VC-MMAE   NaN  112 88.2  85.9  88.5   182   179

--- TotalCellArea_direct — IC50 (nM), reliable only (R²≥0.5, in range) ---
Day             1      2    3     4     5     6     7
Drug                                                 
B5-DM1       3.09   4.75  4.8  5.07  5.82  9.51   9.7
B5-GGFG-DXd   NaN    176  132   120   191   190   191
B5-GGFG-Exa   NaN    140  103  93.9  90.1   100   114
B5-PDB        NaN 0.0677 0.37  0.22 0.277 0.319 0.306
B5-VA-Exa     NaN   87.6 49.8  44.8  37.5  33.7  44.3
B5-VC-MMAE    NaN   52.9 73.9  76.8  84.2   183   139
Syn-DM1      3.07    6.7 8.97   8.8  11.7  13.3  19.2
Syn-GGFG-DXd  NaN    190  169   126   144   193   199
Syn-GGFG-Exa  NaN    126 94.4  79.5  80.2  93.1   110
Syn-PDB       103   4.81 1.32 0.562 0.197 0.311 0.294
Syn-VA-Exa    NaN    106   64  41.6  36.7  33.2  45.1
Syn-VC-MMAE  59.4    123 94.5  91.6  94.5   181   181

--- TotalCellArea_pctViable — IC50 (nM), reliable only (R²≥0.5, in range) ---
Day             1      2    3     4     5     6     7
Drug                                                 
B5-DM1       3.43   4.53 4.79     5   5.7  9.53  9.88
B5-GGFG-DXd   NaN    NaN  107   107   189   190   186
B5-GGFG-Exa   NaN    131 99.5  91.6  93.6   111   121
B5-PDB        NaN 0.0587 0.47  0.23 0.277 0.291 0.285
B5-VA-Exa     NaN   81.9 47.9  37.3  45.2  40.1    45
B5-VC-MMAE    NaN    740  154  77.4  86.1   185   125
Syn-DM1      3.89   5.71 11.2  7.98  11.7  13.1  20.2
Syn-GGFG-DXd  NaN    151  150   130   198   194   204
Syn-GGFG-Exa  NaN    117 89.8  78.8  78.4  89.8  91.9
Syn-PDB       174   4.42 1.33 0.599 0.198 0.279 0.284
Syn-VA-Exa    NaN    NaN 89.6  38.5  33.5  31.4    45
Syn-VC-MMAE   NaN    111   88  86.8  90.3   181   178

============================================================
=== ABSOLUTE IC50 AT 50% OF UNTREATED (no curve fitting) ===
============================================================

--- FoldD0 — Absolute IC50 (nM) at 50% of untreated ---
Day             2    3     4     5     6     7
Drug                                          
B5-DM1       10.5 7.34  6.41   6.3  6.93  7.91
B5-GGFG-DXd   748  155   134   141   139   163
B5-GGFG-Exa   336  123   101  98.1   106   107
B5-PDB        NaN 8.46  2.42 0.897 0.579 0.475
B5-VA-Exa     175 72.6  41.9  35.6  33.2  34.3
B5-VC-MMAE    198  123   101   114   134   126
Syn-DM1      22.8 14.5  13.1  18.2  21.3  27.6
Syn-GGFG-DXd  617  169   138   145   142   194
Syn-GGFG-Exa  273  112  95.1  90.9  97.9  97.7
Syn-PDB      13.8    2 0.861 0.506 0.517 0.453
Syn-VA-Exa    192 78.2  44.4  36.7  33.3  34.7
Syn-VC-MMAE   185  120   106   106   126   120

--- TotalCellArea — Absolute IC50 (nM) at 50% of untreated ---
Day             2    3     4     5     6     7
Drug                                          
B5-DM1       9.19 6.68  5.97  5.97  6.62  7.57
B5-GGFG-DXd   834  144   127   135   132   145
B5-GGFG-Exa   654  145   116   111   117   119
B5-PDB        NaN 4.81  1.12  0.47 0.392 0.358
B5-VA-Exa     168 68.9  39.7  33.6  31.2  32.4
B5-VC-MMAE    186  113  93.2   107   128   120
Syn-DM1      14.8 9.93  9.52  14.3  17.7  24.1
Syn-GGFG-DXd  718  170   139   145   143   192
Syn-GGFG-Exa  285  120   103    98   105   105
Syn-PDB      9.43 1.81 0.742 0.455 0.472 0.422
Syn-VA-Exa    179   78  43.8  34.9  31.3  33.1
Syn-VC-MMAE   195  125   111   109   130   124

--- FoldD0: Absolute 50%-untreated vs fitted-midpoint IC50 ---
        Drug  Day  IC50_interp  IC50_LL4  Diff_%
      B5-DM1    1          NaN      3.42     NaN
      B5-DM1    2         10.5       4.9     113
      B5-DM1    3         7.34      5.21    40.7
      B5-DM1    4         6.41      5.46    17.5
      B5-DM1    5          6.3      6.56      -4
      B5-DM1    6         6.93      9.62     -28
      B5-DM1    7         7.91      9.92   -20.3
 B5-GGFG-DXd    2          748       187     301
 B5-GGFG-DXd    3          155       125    24.2
 B5-GGFG-DXd    4          134       125     6.9
 B5-GGFG-DXd    5          141       193   -26.9
 B5-GGFG-DXd    6          139       192     -28
 B5-GGFG-DXd    7          163       195   -16.3
 B5-GGFG-Exa    2          336       NaN     NaN
 B5-GGFG-Exa    3          123      87.4    40.3
 B5-GGFG-Exa    4          101        81    25.3
 B5-GGFG-Exa    5         98.1      81.7      20
 B5-GGFG-Exa    6          106      91.9    15.1
 B5-GGFG-Exa    7          107      95.9      12
      B5-PDB    2          NaN      8.31     NaN
      B5-PDB    3         8.46      3.43     146
      B5-PDB    4         2.42     0.997     143
      B5-PDB    5        0.897     0.654    37.2
      B5-PDB    6        0.579      0.54     7.3
      B5-PDB    7        0.475     0.441     7.7
   B5-VA-Exa    1          NaN       225     NaN
   B5-VA-Exa    2          175        94    86.4
   B5-VA-Exa    3         72.6      49.4      47
   B5-VA-Exa    4         41.9        47   -10.7
   B5-VA-Exa    5         35.6      45.5   -21.7
   B5-VA-Exa    6         33.2        45   -26.2
   B5-VA-Exa    7         34.3      45.2   -24.1
  B5-VC-MMAE    2          198      63.6     211
  B5-VC-MMAE    3          123      78.3    57.2
  B5-VC-MMAE    4          101      78.9    28.3
  B5-VC-MMAE    5          114      97.3    17.2
  B5-VC-MMAE    6          134       187   -28.4
  B5-VC-MMAE    7          126       187   -32.6
     Syn-DM1    1          NaN      8.53     NaN
     Syn-DM1    2         22.8      8.88     156
     Syn-DM1    3         14.5      10.7    35.5
     Syn-DM1    4         13.1      10.5    24.5
     Syn-DM1    5         18.2      11.6    56.9
     Syn-DM1    6         21.3      14.8      44
     Syn-DM1    7         27.6      38.3   -27.9
Syn-GGFG-DXd    2          617       154     301
Syn-GGFG-DXd    3          169       148      14
Syn-GGFG-DXd    4          138       129     7.2
Syn-GGFG-DXd    5          145       198   -26.8
Syn-GGFG-DXd    6          142       195   -26.9
Syn-GGFG-DXd    7          194       205    -5.7
Syn-GGFG-Exa    2          273       190    43.4
Syn-GGFG-Exa    3          112      83.7      34
Syn-GGFG-Exa    4         95.1      74.5    27.8
Syn-GGFG-Exa    5         90.9        75    21.2
Syn-GGFG-Exa    6         97.9      82.9    18.2
Syn-GGFG-Exa    7         97.7      84.5    15.6
     Syn-PDB    1          NaN      74.7     NaN
     Syn-PDB    2         13.8      28.8   -52.3
     Syn-PDB    3            2      1.98     1.1
     Syn-PDB    4        0.861     0.725    18.8
     Syn-PDB    5        0.506     0.268    88.6
     Syn-PDB    6        0.517     0.359    44.2
     Syn-PDB    7        0.453     0.354      28
  Syn-VA-Exa    2          192       119    61.8
  Syn-VA-Exa    3         78.2      58.4    33.9
  Syn-VA-Exa    4         44.4      40.2    10.5
  Syn-VA-Exa    5         36.7      45.9   -20.2
  Syn-VA-Exa    6         33.3        45   -26.1
  Syn-VA-Exa    7         34.7      45.3   -23.3
 Syn-VC-MMAE    2          185       112    65.4
 Syn-VC-MMAE    3          120      88.2    35.6
 Syn-VC-MMAE    4          106      85.9      24
 Syn-VC-MMAE    5          106      88.5    19.5
 Syn-VC-MMAE    6          126       182   -30.4
 Syn-VC-MMAE    7          120       179   -32.8

Absolute IC50 Tables

Show code
# ===========================================================================
# 9. IC50 bar plots (reliable, both metrics side by side)
# ===========================================================================
for label, df_tbl in [
    ('FoldD0 %Viable', all_ic50_tables['FoldD0_pctViable']),
    ('TotalCellArea %Viable', all_ic50_tables['TotalCellArea_pctViable']),
]:
    plot_df = df_tbl[df_tbl.Reliable].dropna(subset=['IC50_nM']).copy()
    if plot_df.empty:
        continue
    fig, ax = plt.subplots(figsize=(14, 6))
    drug_order = sorted(plot_df.Drug.unique())
    x = np.arange(len(drug_order))
    day_vals = sorted(plot_df.Day.unique())
    width = 0.8 / max(len(day_vals), 1)
    cmap = sns.color_palette('tab10', len(day_vals))

    for i, day in enumerate(day_vals):
        day_data = plot_df[plot_df.Day == day]
        vals = []
        for drug in drug_order:
            row = day_data[day_data.Drug == drug]
            vals.append(row.IC50_nM.values[0] if len(row) > 0 else np.nan)
        ax.bar(x + i * width, vals, width, label=f'Day {day}', color=cmap[i])

    ax.set_xticks(x + width * (len(day_vals) - 1) / 2)
    ax.set_xticklabels(drug_order, rotation=45, ha='right', fontsize=9)
    ax.set_ylabel('IC50 (nM)')
    ax.set_yscale('log')
    ax.set_title(f'IC50 by Drug and Day — {label}')
    ax.legend()
    plt.tight_layout()
    save_fig()

IC50 Bar Plots

Show code
# ===========================================================================
# 10. Export
# ===========================================================================
print('\n=== 10. Export ===')
out_long = os.path.join(DATA_DIR, f'{ZIP_STEM}_long_foldD0.csv')
df.to_csv(out_long, index=False)
print(f'Saved long data: {out_long}')

for label, df_tbl in all_ic50_tables.items():
    out = os.path.join(DATA_DIR, f'{ZIP_STEM}_IC50_{label}.csv')
    df_tbl.to_csv(out, index=False)
    print(f'Saved: {out}')

print(f'\nTotal plots saved: {plot_counter[0]}')
print('Done.')

=== 10. Export ===
Saved long data: /home/ericchen/gitpcm/2911_RnD/IC50_growth_kinetics/20260416_IC50_cfpac/20260416_IC50_cfpac_long_foldD0.csv
Saved: /home/ericchen/gitpcm/2911_RnD/IC50_growth_kinetics/20260416_IC50_cfpac/20260416_IC50_cfpac_IC50_FoldD0_interpolated.csv
Saved: /home/ericchen/gitpcm/2911_RnD/IC50_growth_kinetics/20260416_IC50_cfpac/20260416_IC50_cfpac_IC50_FoldD0_direct.csv
Saved: /home/ericchen/gitpcm/2911_RnD/IC50_growth_kinetics/20260416_IC50_cfpac/20260416_IC50_cfpac_IC50_FoldD0_pctViable.csv
Saved: /home/ericchen/gitpcm/2911_RnD/IC50_growth_kinetics/20260416_IC50_cfpac/20260416_IC50_cfpac_IC50_TotalCellArea_interpolated.csv
Saved: /home/ericchen/gitpcm/2911_RnD/IC50_growth_kinetics/20260416_IC50_cfpac/20260416_IC50_cfpac_IC50_TotalCellArea_direct.csv
Saved: /home/ericchen/gitpcm/2911_RnD/IC50_growth_kinetics/20260416_IC50_cfpac/20260416_IC50_cfpac_IC50_TotalCellArea_pctViable.csv

Total plots saved: 76
Done.
Show code
# ===========================================================================
# 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])
            test_sub = _analysis_rows(test_sub)
            iso_sub  = _analysis_rows(iso_sub)
            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:.3g}' if conf else f'{val:.3g}*'

            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.to_string(index=False, float_format=lambda x: f'{x:.3g}'))

=== 11. Therapeutic Windows (B5 vs Syn) ===
    IC50 = relative IC50: conc at midpoint between untreated & max-dose plateaus

============================================================
  FoldD0 (%Viable)
  Matched LPs: ['DM1', 'GGFG-DXd', 'GGFG-Exa', 'PDB', 'VA-Exa', 'VC-MMAE']
============================================================

--- FoldD0 — Day 1 ---
    IC50 = conc at midpoint of (untreated, max-dose)
    TI = IC50(Syn) / IC50(B5)  ;  * = low confidence
      LP B5 untx→max B5 IC50 (nM) Syn untx→max Syn IC50 (nM) TI (Syn/B5)
     DM1     100→70%         3.71      100→75%          5.73        1.55
GGFG-DXd     100→91%         622*      100→90%        0.251*   0.000403*
GGFG-Exa     100→88%       0.306*      100→86%        0.367*        1.2*
     PDB    100→103%           NA     100→904%           221          NA
  VA-Exa     100→79%          253      100→75%            78       0.309
 VC-MMAE     100→63%          286      100→70%          89.8       0.314


--- FoldD0 — Day 2 ---
    IC50 = conc at midpoint of (untreated, max-dose)
    TI = IC50(Syn) / IC50(B5)  ;  * = low confidence
      LP B5 untx→max B5 IC50 (nM) Syn untx→max Syn IC50 (nM) TI (Syn/B5)
     DM1     100→41%         4.71      100→41%           7.6        1.61
GGFG-DXd     100→46%          165      100→45%           135       0.818
GGFG-Exa     100→39%         94.8      100→37%           102        1.08
     PDB     100→64%            7      100→37%          2.95       0.421
  VA-Exa     100→33%         96.2      100→32%          91.9       0.955
 VC-MMAE     100→49%         73.6      100→31%           108        1.47


--- FoldD0 — Day 3 ---
    IC50 = conc at midpoint of (untreated, max-dose)
    TI = IC50(Syn) / IC50(B5)  ;  * = low confidence
      LP B5 untx→max B5 IC50 (nM) Syn untx→max Syn IC50 (nM) TI (Syn/B5)
     DM1     100→23%         5.12      100→17%          10.1        1.97
GGFG-DXd     100→21%          116      100→19%           130        1.12
GGFG-Exa     100→21%         86.9      100→17%          87.5        1.01
     PDB     100→26%         2.62      100→17%           1.2       0.457
  VA-Exa     100→18%         50.8      100→15%          57.5        1.13
 VC-MMAE     100→26%         80.9      100→19%          91.9        1.14


--- FoldD0 — Day 4 ---
    IC50 = conc at midpoint of (untreated, max-dose)
    TI = IC50(Syn) / IC50(B5)  ;  * = low confidence
      LP B5 untx→max B5 IC50 (nM) Syn untx→max Syn IC50 (nM) TI (Syn/B5)
     DM1     100→15%         5.35      100→16%          9.78        1.83
GGFG-DXd     100→15%          114      100→14%           118        1.03
GGFG-Exa     100→13%         85.2      100→11%          82.4       0.968
     PDB     100→25%        0.814      100→11%         0.618       0.759
  VA-Exa     100→11%         36.6      100→10%          37.6        1.03
 VC-MMAE     100→15%         81.8      100→13%          90.9        1.11


--- FoldD0 — Day 5 ---
    IC50 = conc at midpoint of (untreated, max-dose)
    TI = IC50(Syn) / IC50(B5)  ;  * = low confidence
      LP B5 untx→max B5 IC50 (nM) Syn untx→max Syn IC50 (nM) TI (Syn/B5)
     DM1     100→11%         5.66      100→10%          15.9        2.82
GGFG-DXd     100→12%          127      100→10%           133        1.04
GGFG-Exa      100→9%         87.9       100→8%          82.8       0.942
     PDB     100→13%         0.55      100→65%         0.114       0.207
  VA-Exa      100→8%         33.1       100→7%          33.6        1.02
 VC-MMAE     100→11%          101      100→10%          94.8       0.942


--- FoldD0 — Day 6 ---
    IC50 = conc at midpoint of (untreated, max-dose)
    TI = IC50(Syn) / IC50(B5)  ;  * = low confidence
      LP B5 untx→max B5 IC50 (nM) Syn untx→max Syn IC50 (nM) TI (Syn/B5)
     DM1     100→10%         6.39       100→8%          19.5        3.06
GGFG-DXd     100→11%          127       100→9%           132        1.04
GGFG-Exa      100→8%         97.3       100→6%          91.6       0.941
     PDB     100→11%        0.444      100→57%         0.183       0.413
  VA-Exa      100→6%         31.5       100→6%          31.4       0.997
 VC-MMAE     100→11%          122      100→11%           115       0.942


--- FoldD0 — Day 7 ---
    IC50 = conc at midpoint of (untreated, max-dose)
    TI = IC50(Syn) / IC50(B5)  ;  * = low confidence
      LP B5 untx→max B5 IC50 (nM) Syn untx→max Syn IC50 (nM) TI (Syn/B5)
     DM1     100→11%         7.28      100→10%          25.7        3.52
GGFG-DXd     100→19%          106      100→15%           144        1.36
GGFG-Exa      100→7%          100       100→6%          92.3       0.922
     PDB     100→10%        0.398      100→53%         0.196       0.494
  VA-Exa      100→5%         32.8       100→5%          33.3        1.02
 VC-MMAE      100→9%          117       100→8%           112       0.956


============================================================
  TotalCellArea (%Viable)
  Matched LPs: ['DM1', 'GGFG-DXd', 'GGFG-Exa', 'PDB', 'VA-Exa', 'VC-MMAE']
============================================================

--- TotalCellArea — Day 1 ---
    IC50 = conc at midpoint of (untreated, max-dose)
    TI = IC50(Syn) / IC50(B5)  ;  * = low confidence
      LP B5 untx→max B5 IC50 (nM) Syn untx→max Syn IC50 (nM) TI (Syn/B5)
     DM1     100→61%         3.75      100→60%          4.01        1.07
GGFG-DXd     100→95%           NA      100→94%       0.0147*          NA
GGFG-Exa    100→103%           NA      100→91%          135*          NA
     PDB     100→96%           NA    100→1290%           223          NA
  VA-Exa     100→85%         119*      100→80%        0.0655   0.000551*
 VC-MMAE     100→67%          193      100→79%         0.434     0.00224


--- TotalCellArea — Day 2 ---
    IC50 = conc at midpoint of (untreated, max-dose)
    TI = IC50(Syn) / IC50(B5)  ;  * = low confidence
      LP B5 untx→max B5 IC50 (nM) Syn untx→max Syn IC50 (nM) TI (Syn/B5)
     DM1     100→36%         4.53      100→33%          5.37        1.19
GGFG-DXd     100→48%          127      100→47%           130        1.02
GGFG-Exa     100→46%          117      100→39%           112       0.955
     PDB     100→86%      0.0115*      100→35%          2.73        238*
  VA-Exa     100→36%           86      100→34%          86.4           1
 VC-MMAE     100→52%         56.2      100→35%           108        1.93


--- TotalCellArea — Day 3 ---
    IC50 = conc at midpoint of (untreated, max-dose)
    TI = IC50(Syn) / IC50(B5)  ;  * = low confidence
      LP B5 untx→max B5 IC50 (nM) Syn untx→max Syn IC50 (nM) TI (Syn/B5)
     DM1     100→20%         4.84      100→15%          6.93        1.43
GGFG-DXd     100→22%          106      100→20%           130        1.23
GGFG-Exa     100→24%          100      100→18%          95.1       0.951
     PDB     100→35%        0.404      100→16%          1.06        2.62
  VA-Exa     100→20%         46.3      100→16%          56.9        1.23
 VC-MMAE     100→28%         68.9      100→22%          93.4        1.36


--- TotalCellArea — Day 4 ---
    IC50 = conc at midpoint of (untreated, max-dose)
    TI = IC50(Syn) / IC50(B5)  ;  * = low confidence
      LP B5 untx→max B5 IC50 (nM) Syn untx→max Syn IC50 (nM) TI (Syn/B5)
     DM1     100→13%         5.07      100→13%          7.53        1.49
GGFG-DXd     100→16%          106      100→14%           118        1.11
GGFG-Exa     100→15%         96.2      100→12%          89.5        0.93
     PDB     100→33%        0.205      100→10%          0.53        2.58
  VA-Exa     100→12%         33.6      100→11%          34.9        1.04
 VC-MMAE     100→16%         72.6      100→15%          93.3        1.28


--- TotalCellArea — Day 5 ---
    IC50 = conc at midpoint of (untreated, max-dose)
    TI = IC50(Syn) / IC50(B5)  ;  * = low confidence
      LP B5 untx→max B5 IC50 (nM) Syn untx→max Syn IC50 (nM) TI (Syn/B5)
     DM1      100→9%         5.42       100→9%          12.4        2.28
GGFG-DXd     100→13%          120      100→10%           133         1.1
GGFG-Exa     100→10%         98.3       100→8%          89.5       0.911
     PDB     100→17%        0.267      100→93%       0.0278*      0.104*
  VA-Exa      100→8%         30.8       100→8%          31.3        1.02
 VC-MMAE     100→12%         92.6      100→11%          97.1        1.05


--- TotalCellArea — Day 6 ---
    IC50 = conc at midpoint of (untreated, max-dose)
    TI = IC50(Syn) / IC50(B5)  ;  * = low confidence
      LP B5 untx→max B5 IC50 (nM) Syn untx→max Syn IC50 (nM) TI (Syn/B5)
     DM1      100→8%         6.15       100→7%          16.1        2.61
GGFG-DXd     100→11%          120       100→9%           132         1.1
GGFG-Exa      100→9%          107       100→7%            98       0.914
     PDB     100→15%        0.279      100→82%       0.0722*      0.258*
  VA-Exa      100→6%         29.3       100→6%          29.1       0.995
 VC-MMAE     100→12%          115      100→12%           118        1.02


--- TotalCellArea — Day 7 ---
    IC50 = conc at midpoint of (untreated, max-dose)
    TI = IC50(Syn) / IC50(B5)  ;  * = low confidence
      LP B5 untx→max B5 IC50 (nM) Syn untx→max Syn IC50 (nM) TI (Syn/B5)
     DM1      100→9%         7.02       100→8%          22.3        3.17
GGFG-DXd     100→20%         89.5      100→16%           141        1.58
GGFG-Exa      100→8%          110       100→6%            99       0.902
     PDB     100→14%        0.275      100→76%         0.127       0.461
  VA-Exa      100→5%         30.7       100→5%          31.5        1.02
 VC-MMAE      100→9%          110      100→10%           115        1.04


Saved combined summary: /home/ericchen/gitpcm/2911_RnD/IC50_growth_kinetics/20260416_IC50_cfpac/20260416_IC50_cfpac_therapeutic_index_B5_vs_Syn.csv

============================================================
  Combined Therapeutic Index Summary
============================================================
       Method  Day       LP  B5_IC50_nM  B5_confident  B5_untreated_%  B5_maxdose_%  Syn_IC50_nM  Syn_confident  Syn_untreated_%  Syn_maxdose_%       TI  TI_confident
       FoldD0    1      DM1        3.71          True             100          70.2         5.73           True              100           75.5     1.55          True
       FoldD0    1 GGFG-DXd         622         False             100            91        0.251          False              100           89.7 0.000403         False
       FoldD0    1 GGFG-Exa       0.306         False             100          87.6        0.367          False              100           86.1      1.2         False
       FoldD0    1      PDB         NaN         False             100           103          221           True              100            904      NaN         False
       FoldD0    1   VA-Exa         253          True             100          79.1           78           True              100           75.2    0.309          True
       FoldD0    1  VC-MMAE         286          True             100          62.6         89.8           True              100           70.4    0.314          True
       FoldD0    2      DM1        4.71          True             100          41.3          7.6           True              100             41     1.61          True
       FoldD0    2 GGFG-DXd         165          True             100          45.9          135           True              100           45.1    0.818          True
       FoldD0    2 GGFG-Exa        94.8          True             100          38.9          102           True              100           37.2     1.08          True
       FoldD0    2      PDB           7          True             100          63.7         2.95           True              100           37.4    0.421          True
       FoldD0    2   VA-Exa        96.2          True             100          33.3         91.9           True              100           32.3    0.955          True
       FoldD0    2  VC-MMAE        73.6          True             100          48.7          108           True              100           31.5     1.47          True
       FoldD0    3      DM1        5.12          True             100          23.2         10.1           True              100           16.8     1.97          True
       FoldD0    3 GGFG-DXd         116          True             100            21          130           True              100           19.2     1.12          True
       FoldD0    3 GGFG-Exa        86.9          True             100          20.6         87.5           True              100           17.4     1.01          True
       FoldD0    3      PDB        2.62          True             100          25.8          1.2           True              100           16.6    0.457          True
       FoldD0    3   VA-Exa        50.8          True             100          18.4         57.5           True              100           15.4     1.13          True
       FoldD0    3  VC-MMAE        80.9          True             100          25.9         91.9           True              100           19.3     1.14          True
       FoldD0    4      DM1        5.35          True             100          14.5         9.78           True              100           15.7     1.83          True
       FoldD0    4 GGFG-DXd         114          True             100          14.8          118           True              100           13.6     1.03          True
       FoldD0    4 GGFG-Exa        85.2          True             100          12.7         82.4           True              100           11.3    0.968          True
       FoldD0    4      PDB       0.814          True             100          24.5        0.618           True              100           10.7    0.759          True
       FoldD0    4   VA-Exa        36.6          True             100          11.1         37.6           True              100           10.5     1.03          True
       FoldD0    4  VC-MMAE        81.8          True             100          14.8         90.9           True              100           13.1     1.11          True
       FoldD0    5      DM1        5.66          True             100          10.8         15.9           True              100           9.96     2.82          True
       FoldD0    5 GGFG-DXd         127          True             100          12.2          133           True              100           9.55     1.04          True
       FoldD0    5 GGFG-Exa        87.9          True             100          8.89         82.8           True              100           7.97    0.942          True
       FoldD0    5      PDB        0.55          True             100          12.9        0.114           True              100           64.8    0.207          True
       FoldD0    5   VA-Exa        33.1          True             100          7.54         33.6           True              100           7.31     1.02          True
       FoldD0    5  VC-MMAE         101          True             100          11.4         94.8           True              100             10    0.942          True
       FoldD0    6      DM1        6.39          True             100          9.61         19.5           True              100           8.21     3.06          True
       FoldD0    6 GGFG-DXd         127          True             100          10.5          132           True              100            8.9     1.04          True
       FoldD0    6 GGFG-Exa        97.3          True             100          7.85         91.6           True              100           6.43    0.941          True
       FoldD0    6      PDB       0.444          True             100          10.8        0.183           True              100           57.5    0.413          True
       FoldD0    6   VA-Exa        31.5          True             100          5.75         31.4           True              100           5.64    0.997          True
       FoldD0    6  VC-MMAE         122          True             100            11          115           True              100           10.9    0.942          True
       FoldD0    7      DM1        7.28          True             100          10.7         25.7           True              100           9.61     3.52          True
       FoldD0    7 GGFG-DXd         106          True             100          18.8          144           True              100           15.2     1.36          True
       FoldD0    7 GGFG-Exa         100          True             100          7.03         92.3           True              100           5.54    0.922          True
       FoldD0    7      PDB       0.398          True             100            10        0.196           True              100           53.4    0.494          True
       FoldD0    7   VA-Exa        32.8          True             100          4.97         33.3           True              100           4.79     1.02          True
       FoldD0    7  VC-MMAE         117          True             100          8.53          112           True              100           8.43    0.956          True
TotalCellArea    1      DM1        3.75          True             100          60.8         4.01           True              100             60     1.07          True
TotalCellArea    1 GGFG-DXd         NaN         False             100          95.2       0.0147          False              100           93.5      NaN         False
TotalCellArea    1 GGFG-Exa         NaN         False             100           103          135          False              100           91.3      NaN         False
TotalCellArea    1      PDB         NaN         False             100          96.2          223           True              100       1.29e+03      NaN         False
TotalCellArea    1   VA-Exa         119         False             100          85.4       0.0655           True              100           79.6 0.000551         False
TotalCellArea    1  VC-MMAE         193          True             100          67.5        0.434           True              100           79.2  0.00224          True
TotalCellArea    2      DM1        4.53          True             100          35.7         5.37           True              100           32.6     1.19          True
TotalCellArea    2 GGFG-DXd         127          True             100          48.1          130           True              100           47.1     1.02          True
TotalCellArea    2 GGFG-Exa         117          True             100          45.8          112           True              100           39.4    0.955          True
TotalCellArea    2      PDB      0.0115         False             100          85.8         2.73           True              100           35.5      238         False
TotalCellArea    2   VA-Exa          86          True             100            36         86.4           True              100           34.2        1          True
TotalCellArea    2  VC-MMAE        56.2          True             100          52.3          108           True              100           35.4     1.93          True
TotalCellArea    3      DM1        4.84          True             100          20.1         6.93           True              100             15     1.43          True
TotalCellArea    3 GGFG-DXd         106          True             100            22          130           True              100           20.1     1.23          True
TotalCellArea    3 GGFG-Exa         100          True             100          24.2         95.1           True              100           18.5    0.951          True
TotalCellArea    3      PDB       0.404          True             100          34.8         1.06           True              100           15.7     2.62          True
TotalCellArea    3   VA-Exa        46.3          True             100          19.9         56.9           True              100           16.3     1.23          True
TotalCellArea    3  VC-MMAE        68.9          True             100          27.9         93.4           True              100           21.8     1.36          True
TotalCellArea    4      DM1        5.07          True             100          12.6         7.53           True              100           12.5     1.49          True
TotalCellArea    4 GGFG-DXd         106          True             100          15.5          118           True              100           14.2     1.11          True
TotalCellArea    4 GGFG-Exa        96.2          True             100            15         89.5           True              100             12     0.93          True
TotalCellArea    4      PDB       0.205          True             100          33.1         0.53           True              100           10.1     2.58          True
TotalCellArea    4   VA-Exa        33.6          True             100          11.9         34.9           True              100           11.1     1.04          True
TotalCellArea    4  VC-MMAE        72.6          True             100            16         93.3           True              100           14.7     1.28          True
TotalCellArea    5      DM1        5.42          True             100          9.37         12.4           True              100           8.82     2.28          True
TotalCellArea    5 GGFG-DXd         120          True             100          12.7          133           True              100           9.97      1.1          True
TotalCellArea    5 GGFG-Exa        98.3          True             100          10.5         89.5           True              100           8.46    0.911          True
TotalCellArea    5      PDB       0.267          True             100          17.3       0.0278          False              100           92.6    0.104         False
TotalCellArea    5   VA-Exa        30.8          True             100          8.13         31.3           True              100           7.75     1.02          True
TotalCellArea    5  VC-MMAE        92.6          True             100          12.2         97.1           True              100           11.2     1.05          True
TotalCellArea    6      DM1        6.15          True             100          8.35         16.1           True              100           7.29     2.61          True
TotalCellArea    6 GGFG-DXd         120          True             100            11          132           True              100           9.29      1.1          True
TotalCellArea    6 GGFG-Exa         107          True             100          9.24           98           True              100            6.8    0.914          True
TotalCellArea    6      PDB       0.279          True             100          14.6       0.0722          False              100           81.9    0.258         False
TotalCellArea    6   VA-Exa        29.3          True             100           6.2         29.1           True              100           5.98    0.995          True
TotalCellArea    6  VC-MMAE         115          True             100          11.8          118           True              100           12.3     1.02          True
TotalCellArea    7      DM1        7.02          True             100          9.32         22.3           True              100            8.5     3.17          True
TotalCellArea    7 GGFG-DXd        89.5          True             100          19.7          141           True              100           15.8     1.58          True
TotalCellArea    7 GGFG-Exa         110          True             100          8.28           99           True              100           5.88    0.902          True
TotalCellArea    7      PDB       0.275          True             100          13.5        0.127           True              100           76.2    0.461          True
TotalCellArea    7   VA-Exa        30.7          True             100          5.37         31.5           True              100           5.08     1.02          True
TotalCellArea    7  VC-MMAE         110          True             100          9.15          115           True              100           9.55     1.04          True