# Scratch assay, drug vs control: migration speed per field (from the slope of width over time) and percent closure at
# 24 h, compared with wells as n and with experiments as n. Python 3.13, NumPy, pandas, SciPy.
import numpy as np, pandas as pd
from scipy import stats

d = pd.read_csv("wound.csv")                         # one row per field and time: experiment, condition, well, field, hours, width_um
def per_field(x):
    open_ = x[x.width_um > 20]                         # linear phase only: drop time points after the wound has closed
    slope = np.polyfit(open_.hours, open_.width_um, 1)[0]
    w0, w24 = x.width_um[x.hours == 0].iloc[0], x.width_um[x.hours == 24].iloc[0]
    return pd.Series({"speed": -slope / 2, "closure": 100 * (w0 - w24) / w0, "w0": w0})
f = d.groupby(["experiment", "condition", "well", "field"]).apply(per_field, include_groups=False).reset_index()
print(f"Starting width across fields: mean {f.w0.mean():.0f} µm, range {f.w0.min():.0f} to {f.w0.max():.0f}; "
      f"correlation of 24-h percent closure with starting width r = {np.corrcoef(f.w0, f.closure)[0, 1]:.2f}, with migration speed r = {np.corrcoef(f.w0, f.speed)[0, 1]:.2f}")
w = f.groupby(["experiment", "condition", "well"])[["speed", "closure"]].mean().reset_index(); dw = w.condition == "drug"
t1 = stats.ttest_ind(np.log(w.speed[dw]), np.log(w.speed[~dw]), equal_var=False)
print(f"Migration speed, wells as n ({dw.sum()} vs {(~dw).sum()}): drug / control {np.exp(np.log(w.speed[dw]).mean() - np.log(w.speed[~dw]).mean()):.2f}, p = {t1.pvalue:.2g}")
e = w.groupby(["experiment", "condition"])[["speed", "closure"]].mean().unstack()
r = np.log(e["speed"]["drug"] / e["speed"]["control"]).to_numpy(); t2 = stats.ttest_1samp(r, 0); c2 = t2.confidence_interval()
print(f"Migration speed, experiments as n ({len(r)}): drug / control {np.exp(r.mean()):.2f} (95% CI {np.exp(c2.low):.2f} to {np.exp(c2.high):.2f}), p = {t2.pvalue:.2g}; "
      f"control speed {e['speed']['control'].mean():.1f} µm/h per edge")
dc = (e["closure"]["drug"] - e["closure"]["control"]).to_numpy(); t3 = stats.ttest_1samp(dc, 0); c3 = t3.confidence_interval()
print(f"24-h percent closure, experiments as n: drug - control {dc.mean():.1f} percentage points (95% CI {c3.low:.1f} to {c3.high:.1f}), p = {t3.pvalue:.2g}; "
      f"control closure {e['closure']['control'].mean():.1f}%")
