from pathlib import Path
import numpy as np
import matplotlib.pyplot as plt

CASES = [('loops_aucore.txt','Au core'),('loops_agcore.txt','Ag core')]
fig, ax = plt.subplots()
found = 0
for filename, label in CASES:
    path = Path(filename)
    if not path.exists():
        print(f"Missing output: {path}. Run the matching LAMMPS command first.")
        continue
    try:
        data = np.loadtxt(path, comments="#", ndmin=2)
        if data.shape[1] < 2 or data.shape[0] == 0:
            print(f"{path}: expected strain and stress_GPa columns; skipping.")
            continue
        data = data[np.isfinite(data[:, :2]).all(axis=1)]
        if not len(data):
            print(f"{path}: no finite data rows; skipping.")
            continue
    except (ValueError, OSError) as exc:
        print(f"Cannot read {path}: {exc}")
        continue
    strain, stress = data[:, 0], data[:, 1]
    # Each complete loop starts at the +10% turning point.
    peaks = np.flatnonzero((strain[1:-1] >= strain[:-2]) & (strain[1:-1] > strain[2:])) + 1
    if len(strain) > 1 and strain[-1] > strain[-2]:
        peaks = np.append(peaks, len(strain) - 1)
    if len(peaks) < 2:
        ax.plot(strain, stress, label=label + " (incomplete)")
        print(f"{label}: fewer than two tensile turning points")
    for i, (a, b) in enumerate(zip(peaks[:-1], peaks[1:]), 1):
        ax.plot(strain[a:b+1], stress[a:b+1], label=f"{label}, cycle {i}")
    found += 1
if found:
    ax.set(xlabel="Engineering strain", ylabel="Engineering stress (GPa)")
    ax.legend()
    fig.tight_layout()
    fig.savefig("stress_strain.png", dpi=200)
    print("Saved stress_strain.png")
else:
    print("No usable data; no figure written.")
