#!/usr/bin/env python3
"""tensile_props.py - Young's modulus, Rp0.2, UTS and elongation from ONE tensile curve.

Free tool from Hu Lab (https://hulab.pages.dev). Needs numpy and matplotlib.

    pip install numpy matplotlib

Input: a CSV/TXT file with two numeric columns (extra header lines are skipped).

    # columns are engineering strain (mm/mm) and stress (MPa)
    python tensile_props.py curve.csv

    # strain column in percent
    python tensile_props.py curve.csv --strain-percent

    # columns are force (N) and extension (mm); give the specimen size
    python tensile_props.py raw.csv --area 20 --gauge 50

Options:
    --window LO HI   stress window for the modulus fit, in % of the maximum stress
                     (default 5 25). Check the plot: the window must lie on the straight part.
    --offset X       plastic strain offset in % (default 0.2)
    --delimiter D    column separator (default: detected from comma, semicolon, tab, space)

Output: the numbers on screen, plus <file>_props.png showing the construction.

The results depend on your strain source and the fit window. Use extensometer strain
for E and Rp0.2: crosshead displacement includes the compliance of the machine.
"""
import argparse
import os
import re

import numpy as np


def read_two_columns(path, delimiter=None):
    """First two numeric columns of every line that parses; header lines are skipped."""
    rows = []
    with open(path, encoding="utf-8", errors="replace") as f:
        for line in f:
            line = line.strip()
            if not line:
                continue
            parts = line.split(delimiter) if delimiter else re.split(r"[,;\t ]+", line)
            try:
                rows.append((float(parts[0]), float(parts[1])))
            except (ValueError, IndexError):
                continue
    if len(rows) < 10:
        raise SystemExit(f"Found only {len(rows)} numeric rows in {path}.")
    return np.array(rows)


def analyze(strain, stress, window=(5.0, 25.0), offset=0.002):
    """All inputs and outputs in mm/mm and MPa, except E (MPa)."""
    i_max = int(np.argmax(stress))
    rm = stress[i_max]

    # modulus: least-squares line through the loading data inside the stress window
    lo, hi = window[0] / 100 * rm, window[1] / 100 * rm
    i_hi = int(np.argmax(stress >= hi))
    i_lo = int(np.argmax(stress >= lo))
    if i_hi - i_lo < 5:
        raise SystemExit("Fewer than 5 points in the modulus window; widen it with --window.")
    x, y = strain[i_lo:i_hi + 1], stress[i_lo:i_hi + 1]
    e, b = np.polyfit(x, y, 1)
    r2 = 1 - np.sum((y - (e * x + b)) ** 2) / np.sum((y - y.mean()) ** 2)
    eps0 = -b / e                       # where the fitted line meets zero stress

    # offset yield: first point where the curve falls below the offset line
    diff = stress - e * (strain - eps0 - offset)
    start = i_hi
    below = np.nonzero(diff[start:] <= 0)[0]
    if below.size == 0:
        rp, eps_rp = float("nan"), float("nan")
    else:
        k = start + int(below[0])
        t = diff[k - 1] / (diff[k - 1] - diff[k])
        eps_rp = strain[k - 1] + t * (strain[k] - strain[k - 1])
        rp = stress[k - 1] + t * (stress[k] - stress[k - 1])

    eps_rm = strain[i_max] - eps0
    return {"E": e, "R2": r2, "eps0": eps0, "Rp": rp, "eps_Rp": eps_rp, "Rm": rm, "eps_Rm": eps_rm,
            "Ag": eps_rm - rm / e, "eps_end": strain[-1] - eps0, "fit_lo": x[0], "fit_hi": x[-1]}


def plot(strain, stress, r, offset, out):
    import matplotlib
    matplotlib.use("Agg")
    import matplotlib.pyplot as plt

    fig, (a, b) = plt.subplots(1, 2, figsize=(9, 3.6), layout="constrained")
    for ax in (a, b):
        ax.plot(strain * 100, stress, color="#0072B2", lw=1.4, label="data")
        ax.set_xlabel("Engineering strain (%)")
        ax.set_ylabel("Engineering stress (MPa)")
    a.plot(r["eps_Rm"] * 100 + r["eps0"] * 100, r["Rm"], "o", color="#CC79A7", label=f"Rm = {r['Rm']:.1f} MPa")
    a.legend(frameon=False)
    a.set_title("Whole curve", fontsize=10)

    top = r["Rp"] * 1.15 if np.isfinite(r["Rp"]) else r["Rm"]
    line = np.array([0, top])
    b.plot((line / r["E"] + r["eps0"]) * 100, line, color="#009E73", lw=1, label=f"E = {r['E'] / 1000:.1f} GPa")
    b.plot((line / r["E"] + r["eps0"] + offset) * 100, line, "--", color="#D55E00", lw=1, label=f"{offset * 100:g} % offset")
    b.axvspan(r["fit_lo"] * 100, r["fit_hi"] * 100, color="#56B4E9", alpha=0.25, lw=0, label="fit window")
    if np.isfinite(r["Rp"]):
        b.plot(r["eps_Rp"] * 100, r["Rp"], "o", mfc="none", color="#D55E00", label=f"Rp = {r['Rp']:.1f} MPa")
        b.set_xlim(0, max(r["eps_Rp"] * 100 * 1.6, 0.5))
    b.set_ylim(0, top * 1.05)
    b.legend(frameon=False, fontsize=8, loc="lower right")
    b.set_title("Elastic and yield region", fontsize=10)
    fig.savefig(out, dpi=300)


def main():
    ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
    ap.add_argument("file")
    ap.add_argument("--area", type=float, help="cross-section in mm2 (columns are then force N, extension mm)")
    ap.add_argument("--gauge", type=float, help="gauge length in mm (with --area)")
    ap.add_argument("--strain-percent", action="store_true", help="the strain column is in percent")
    ap.add_argument("--window", type=float, nargs=2, default=(5.0, 25.0), metavar=("LO", "HI"))
    ap.add_argument("--offset", type=float, default=0.2)
    ap.add_argument("--delimiter")
    args = ap.parse_args()

    d = read_two_columns(args.file, args.delimiter)
    if args.area or args.gauge:
        if not (args.area and args.gauge):
            raise SystemExit("--area and --gauge must be given together.")
        stress, strain = d[:, 0] / args.area, d[:, 1] / args.gauge
    else:
        strain, stress = d[:, 0] / (100 if args.strain_percent else 1), d[:, 1]

    offset = args.offset / 100
    r = analyze(strain, stress, tuple(args.window), offset)
    print(f"Young's modulus E   {r['E'] / 1000:9.2f} GPa   (R2 = {r['R2']:.5f}, "
          f"fit {r['fit_lo'] * 100:.3f}-{r['fit_hi'] * 100:.3f} % strain)")
    print(f"Rp{args.offset:g}               {r['Rp']:9.1f} MPa")
    print(f"UTS (Rm)            {r['Rm']:9.1f} MPa")
    print(f"Strain at UTS       {r['eps_Rm'] * 100:9.2f} %")
    print(f"Uniform plastic Ag  {r['Ag'] * 100:9.2f} %")
    print(f"Strain at last point{r['eps_end'] * 100:9.2f} %   (measured from the fitted zero-stress point)")
    print(f"Strain origin moved {r['eps0'] * 100:9.3f} %   (toe correction)")
    out = os.path.splitext(args.file)[0] + "_props.png"
    plot(strain, stress, r, offset, out)
    print("Plot:", out)


if __name__ == "__main__":
    main()
