{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Deposit an alloy layer by layer, then test it\n",
    "\n",
    "Mimic additive manufacturing: deposit Ni–Cr–Fe atoms in batches, cool at two rates, and run a tensile test.\n",
    "\n",
    "Paper: Atomistic Study on the Cooling Rate Induced Mechanical Properties Variations in Additively Manufactured Inconel-718\n",
    "\n",
    "Website tutorial: reproduce/imece-inconel-am/ · Status: Inputs not yet validated · Runtime: ~20 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",
    "- [FeNiCr.eam.alloy](https://www.ctcms.nist.gov/potentials/Download/2011--Bonny-G-Terentyev-D-Pasianot-R-C-et-al--Fe-Ni-Cr/3/FeNiCr.eam.alloy)"
   ],
   "id": "cell-3"
  },
  {
   "cell_type": "code",
   "metadata": {},
   "execution_count": null,
   "outputs": [],
   "source": [
    "%%writefile in.deposition.lmp\n",
    "units metal\n",
    "atom_style atomic\n",
    "boundary p p f\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",
    "lattice fcc 3.52\n",
    "region box block 0 28.16 0 28.16 0 65 units box\n",
    "create_box 3 box\n",
    "region substrate block 0 28.16 0 28.16 0 21.12 units box\n",
    "create_atoms 1 region substrate\n",
    "mass 1 58.6934\n",
    "mass 2 51.9961\n",
    "mass 3 55.845\n",
    "pair_style eam/alloy\n",
    "pair_coeff * * FeNiCr.eam.alloy Ni Cr Fe\n",
    "neighbor 2 bin\n",
    "minimize 1e-7 1e-7 200 2000\n",
    "velocity all create 1000 ${seed} mom yes rot yes dist gaussian\n",
    "# Add three sequential batches at increasing heights; each batch is a thin source layer.\n",
    "fix integration all nve\n",
    "fix bath all langevin 1000 1000 0.1 ${seed}\n",
    "thermo 1000\n",
    "thermo_modify lost error\n",
    "region layer1 block 0 28.16 0 28.16 29 35 units box\n",
    "region layer2 block 0 28.16 0 28.16 34 40 units box\n",
    "region layer3 block 0 28.16 0 28.16 39 45 units box\n",
    "fix dep all deposit 300 1 10 ${seed} region layer1 near 2.2 attempt 50 vz -1.0 -0.5 units box\n",
    "run 3000\n",
    "unfix dep\n",
    "fix dep all deposit 300 1 10 ${seed} region layer2 near 2.2 attempt 50 vz -1.0 -0.5 units box\n",
    "run 3000\n",
    "unfix dep\n",
    "fix dep all deposit 300 1 10 ${seed} region layer3 near 2.2 attempt 50 vz -1.0 -0.5 units box\n",
    "run 3000\n",
    "unfix dep\n",
    "unfix bath\n",
    "# Randomize the final deposit and substrate to the intended alloy fractions.\n",
    "set type 1 type/fraction 2 0.21 ${seed}\n",
    "variable seed2 equal v_seed+17\n",
    "set type 1 type/fraction 3 0.2405063291 ${seed2}\n",
    "fix bath all langevin 1000 ${T} 0.1 ${seed}\n",
    "variable nquench equal ceil((1000-v_T)/(v_cool*0.001))\n",
    "run ${nquench}\n",
    "unfix bath\n",
    "fix bath all langevin ${T} ${T} 0.1 ${seed}\n",
    "run 2000\n",
    "# Periodic x loading; pxx includes the vacuum, so normalize by a defined initial slab height.\n",
    "variable L0 equal $(lx)\n",
    "variable V0 equal $(lx*ly*30.0)\n",
    "variable strain equal (lx-v_L0)/v_L0\n",
    "variable stress equal -pxx*vol/v_V0*0.0001\n",
    "fix deform all deform 1 x erate ${rate} remap x units box\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)\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.deposition.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.deposition.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
}