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

CASES = [('tension_10.txt','10 K/ps'),('tension_100.txt','100 K/ps')]
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]
    ax.plot(strain, stress, label=label); mask = (strain >= 0) & (strain <= 0.02); print(f"{label}: modulus = {np.polyfit(strain[mask], stress[mask], 1)[0]:.4g} GPa" if mask.sum() >= 2 and np.ptp(strain[mask]) > 0 else f"{label}: insufficient points for modulus")
    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.")
