{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Quench liquid tin at two rates, then stretch it\n",
    "\n",
    "Melt Sn, cool it at 10 and 100 K/ps with a MEAM potential, and compare strength and stiffness of the two solids.\n",
    "\n",
    "Paper: Effects of Ultra-High Cooling Rates on the Tensile and Cyclic Stress–Strain Behavior of Nanoscale Solder Materials\n",
    "\n",
    "Website tutorial: reproduce/solder-cooling/ · Status: Inputs not yet validated · Runtime: ~15 min (4 cores, estimate)."
   ],
   "id": "cell-1"
  },
  {
   "cell_type": "code",
   "metadata": {},
   "execution_count": null,
   "outputs": [],
   "source": [
    "!pip install -q lammps numpy matplotlib"
   ],
   "id": "cell-2"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Download the potential files below and upload them to the notebook's working directory before running the simulation. Keep these exact filenames.\n",
    "\n",
    "- [library.meam](https://www.ctcms.nist.gov/potentials/Download/2018--Ko-W-S-Kim-D-H-Kwon-Y-J-Lee-M--Sn/1/library.meam)\n",
    "- [Sn.meam](https://www.ctcms.nist.gov/potentials/Download/2018--Ko-W-S-Kim-D-H-Kwon-Y-J-Lee-M--Sn/1/Sn.meam)"
   ],
   "id": "cell-3"
  },
  {
   "cell_type": "code",
   "metadata": {},
   "execution_count": null,
   "outputs": [],
   "source": [
    "%%writefile in.solder.lmp\n",
    "units metal\n",
    "atom_style atomic\n",
    "boundary p p p\n",
    "variable T index 300\n",
    "variable rate index 0.01\n",
    "variable seed index 87287\n",
    "variable cool index 10\n",
    "variable out index tension_10.txt\n",
    "timestep 0.001\n",
    "# A compact FCC starting structure is melted before quenching.\n",
    "lattice fcc 5.8\n",
    "region box block 0 8 0 8 0 8\n",
    "create_box 1 box\n",
    "create_atoms 1 box\n",
    "mass 1 118.710\n",
    "pair_style meam\n",
    "pair_coeff * * library.meam Sn Sn.meam Sn\n",
    "neighbor 2 bin\n",
    "minimize 1e-7 1e-7 200 2000\n",
    "velocity all create 1200 ${seed} mom yes rot yes dist gaussian\n",
    "fix heat all nvt temp 1200 1200 0.1\n",
    "thermo 500\n",
    "run 5000\n",
    "unfix heat\n",
    "# cool is K/ps; the timestep is 0.001 ps.\n",
    "variable nquench equal ceil((1200-v_T)/(v_cool*0.001))\n",
    "fix quench all nvt temp 1200 ${T} 0.1\n",
    "run ${nquench}\n",
    "unfix quench\n",
    "fix relax all npt temp ${T} ${T} 0.1 iso 0 0 1\n",
    "run 5000\n",
    "unfix relax\n",
    "variable L0 equal $(lz)\n",
    "variable V0 equal $(vol)\n",
    "variable strain equal (lz-v_L0)/v_L0\n",
    "variable stress equal -pzz*vol/(v_V0)*0.0001\n",
    "fix heat all nvt temp ${T} ${T} 0.1\n",
    "fix deform all deform 1 z erate ${rate} units box remap x\n",
    "fix output all print 100 \"${strain} ${stress}\" file ${out} screen no title \"# strain stress_GPa\"\n",
    "run 15000\n"
   ],
   "id": "cell-4"
  },
  {
   "cell_type": "code",
   "metadata": {},
   "execution_count": null,
   "outputs": [],
   "source": [
    "%%writefile analyze.py\n",
    "from pathlib import Path\n",
    "import numpy as np\n",
    "import matplotlib.pyplot as plt\n",
    "\n",
    "CASES = [('tension_10.txt','10 K/ps'),('tension_100.txt','100 K/ps')]\n",
    "fig, ax = plt.subplots()\n",
    "found = 0\n",
    "for filename, label in CASES:\n",
    "    path = Path(filename)\n",
    "    if not path.exists():\n",
    "        print(f\"Missing output: {path}. Run the matching LAMMPS command first.\")\n",
    "        continue\n",
    "    try:\n",
    "        data = np.loadtxt(path, comments=\"#\", ndmin=2)\n",
    "        if data.shape[1] < 2 or data.shape[0] == 0:\n",
    "            print(f\"{path}: expected strain and stress_GPa columns; skipping.\")\n",
    "            continue\n",
    "        data = data[np.isfinite(data[:, :2]).all(axis=1)]\n",
    "        if not len(data):\n",
    "            print(f\"{path}: no finite data rows; skipping.\")\n",
    "            continue\n",
    "    except (ValueError, OSError) as exc:\n",
    "        print(f\"Cannot read {path}: {exc}\")\n",
    "        continue\n",
    "    strain, stress = data[:, 0], data[:, 1]\n",
    "    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\")\n",
    "    found += 1\n",
    "if found:\n",
    "    ax.set(xlabel=\"Engineering strain\", ylabel=\"Engineering stress (GPa)\")\n",
    "    ax.legend()\n",
    "    fig.tight_layout()\n",
    "    fig.savefig(\"stress_strain.png\", dpi=200)\n",
    "    print(\"Saved stress_strain.png\")\n",
    "else:\n",
    "    print(\"No usable data; no figure written.\")\n"
   ],
   "id": "cell-5"
  },
  {
   "cell_type": "code",
   "metadata": {},
   "execution_count": null,
   "outputs": [],
   "source": [
    "from lammps import lammps\n",
    "simulation = lammps(cmdargs=[\"-var\",\"cool\",\"10\",\"-var\",\"out\",\"tension_10.txt\"])\n",
    "try:\n",
    "    simulation.file(\"in.solder.lmp\")\n",
    "finally:\n",
    "    simulation.close()"
   ],
   "id": "cell-6"
  },
  {
   "cell_type": "code",
   "metadata": {},
   "execution_count": null,
   "outputs": [],
   "source": [
    "from lammps import lammps\n",
    "simulation = lammps(cmdargs=[\"-var\",\"cool\",\"100\",\"-var\",\"out\",\"tension_100.txt\"])\n",
    "try:\n",
    "    simulation.file(\"in.solder.lmp\")\n",
    "finally:\n",
    "    simulation.close()"
   ],
   "id": "cell-7"
  },
  {
   "cell_type": "code",
   "metadata": {},
   "execution_count": null,
   "outputs": [],
   "source": [
    "!python analyze.py"
   ],
   "id": "cell-8"
  },
  {
   "cell_type": "code",
   "metadata": {},
   "execution_count": null,
   "outputs": [],
   "source": [
    "from IPython.display import Image, display\n",
    "import glob\n",
    "for f in sorted(glob.glob('out/*.png') + glob.glob('*.png')):\n",
    "    print(f); display(Image(f))"
   ],
   "id": "cell-9"
  }
 ],
 "metadata": {
  "kernelspec": {
   "name": "python3",
   "display_name": "Python 3"
  },
  "language_info": {
   "name": "python"
  },
  "colab": {
   "provenance": []
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}