"""
dotplot_ci.py — show every measurement plus mean ± 95 % CI, and print the numbers for your paper.

Hu Lab · https://hulab.pages.dev/en/guides/error-bars-bar-charts/
Requires: pip install numpy pandas scipy matplotlib

Input: a CSV with one column per group (condition), one row per independent sample, e.g.

    200 °C,250 °C,300 °C
    11.9,15.6,24.4
    12.6,18.1,24.0
    ...

    python dotplot_ci.py shear.csv "Shear strength (MPa)"
    -> shear_dotplot.png / .svg  and a summary table printed to the console
"""
import sys
import os
import numpy as np
import pandas as pd
import matplotlib
matplotlib.use("Agg")
import matplotlib.pyplot as plt
from scipy import stats

path = sys.argv[1]
ylabel = sys.argv[2] if len(sys.argv) > 2 else "Value"
df = pd.read_csv(path)

plt.rcParams.update({"font.family": ["Arial", "DejaVu Sans"], "font.size": 8,
                     "xtick.direction": "in", "ytick.direction": "in", "svg.fonttype": "none"})
fig, ax = plt.subplots(figsize=(3.5, 2.8), layout="constrained")       # 90 mm single column

print(f"{'group':<12}{'n':>3}{'mean':>9}{'SD':>8}{'SEM':>8}{'95% CI':>18}")
for i, col in enumerate(df.columns):
    x = df[col].dropna().to_numpy(float)
    n = len(x)
    m, sd = x.mean(), x.std(ddof=1)
    sem = sd / np.sqrt(n)
    half = stats.t.ppf(0.975, n - 1) * sem
    jitter = np.linspace(-0.12, 0.12, n) if n > 1 else [0]
    ax.scatter(i + np.asarray(jitter), x, s=14, color="#0072B2", zorder=3, linewidths=0)
    ax.errorbar(i + 0.3, m, yerr=half, fmt="o", ms=4, color="#1F3A5F", capsize=3, lw=1)
    print(f"{col:<12}{n:>3}{m:>9.2f}{sd:>8.2f}{sem:>8.2f}   [{m - half:.2f}, {m + half:.2f}]")

ax.set_xticks(range(len(df.columns)))
ax.set_xticklabels(df.columns)
ax.set_xlim(-0.5, len(df.columns) - 0.3)
ax.set_ylabel(ylabel)
base = os.path.splitext(path)[0] + "_dotplot"
fig.savefig(base + ".png", dpi=600, facecolor="white")
fig.savefig(base + ".svg", facecolor="white")
print("\nCaption sentence: Points show individual samples; markers and bars show the mean ± 95% confidence interval (n = ...).")
print("saved", base + ".png /.svg")
