{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Interactive fitting of critical point data for ammonia + water with GERG and invariant reducing functions\n",
    "\n",
    "No departure term..."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from ipywidgets import interact, interactive, fixed, interact_manual\n",
    "import ipywidgets as widgets\n",
    "%matplotlib inline\n",
    "import timeit\n",
    "import pandas\n",
    "import matplotlib.pyplot as plt, numpy as np\n",
    "import matplotlib as mpl\n",
    "mpl.rcParams['figure.dpi']= 100\n",
    "import teqp"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "names = ['Water','Ammonia']\n",
    "model = teqp.build_multifluid_model(names, '../mycp', '../mycp/dev/mixtures/mixture_binary_pairs.json',{'estimate':'Lorentz-Berthelot'})\n",
    "puremodels = [teqp.build_multifluid_model([name], '../mycp', '../mycp/dev/mixtures/mixture_binary_pairs.json') for name in names]\n",
    "        \n",
    "def get_mutant(params):\n",
    "    \"\"\" Build a teqp-based mutant from the model parameters \"\"\"\n",
    "    if 'type' not in params:\n",
    "        raise KeyError('type must be provided')\n",
    "\n",
    "    if params['type'] == 'invariant':\n",
    "        s = {\n",
    "            \"0\":{\n",
    "                \"1\": {\n",
    "                    \"BIP\":{\n",
    "                        \"type\": \"invariant\",\n",
    "                        \"lambdaT\": params['lambdaT'],\n",
    "                        \"phiT\": params['phiT'],\n",
    "                        \"lambdaV\": params['lambdaV'],\n",
    "                        \"phiV\": params['phiV'],\n",
    "                        \"Fij\": 0.0\n",
    "                    },\n",
    "                    \"departure\":{\n",
    "                        \"type\" : \"none\"\n",
    "                    }\n",
    "                }\n",
    "            }\n",
    "        }\n",
    "        return teqp.build_multifluid_mutant(model, s)\n",
    "    elif params['type'] == 'GERG':\n",
    "        s = {\n",
    "            \"0\":{\n",
    "                \"1\": {\n",
    "                    \"BIP\":{\n",
    "                        \"type\": \"GERG2004\",\n",
    "                        \"betaT\": params['betaT'],\n",
    "                        \"gammaT\": params['gammaT'],\n",
    "                        \"betaV\": params['betaV'],\n",
    "                        \"gammaV\": params['gammaV'],\n",
    "                        \"Fij\": 0.0\n",
    "                    },\n",
    "                    \"departure\":{\n",
    "                        \"type\" : \"none\"\n",
    "                    }\n",
    "                }\n",
    "            }\n",
    "        }\n",
    "        return teqp.build_multifluid_mutant(model, s)\n",
    "    else:\n",
    "        raise KeyError(\"Bad type for get_mutant\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "def get_critical_curve(params):\n",
    "    \"\"\" Trace the critical curve and return values \"\"\"    \n",
    "\n",
    "    tweaked = get_mutant(params)\n",
    "    # print(tweaked.get_meta())\n",
    "\n",
    "    basemodel = None\n",
    "    tic = timeit.default_timer()\n",
    "    Tcvec = basemodel.get_Tcvec() if basemodel else model.get_Tcvec()\n",
    "    rhocvec = 1/basemodel.get_vcvec() if basemodel else 1/model.get_vcvec()\n",
    "    k = 1 # Have to start at pure second component for now... In theory either are possible.\n",
    "    T0 = Tcvec[k]\n",
    "    rho0 = rhocvec\n",
    "    rho0[1-k] = 0\n",
    "    curveJSON = tweaked.trace_critical_arclength_binary(T0, rho0, \"\")\n",
    "    toc = timeit.default_timer()\n",
    "#     print(toc-tic, 'sec. to trace critical locus')\n",
    "    df = pandas.DataFrame(curveJSON)\n",
    "    df['z0 / mole frac.'] = df['rho0 / mol/m^3']/(df['rho0 / mol/m^3']+df['rho1 / mol/m^3'])\n",
    "    def add_splus(row):\n",
    "        rhovec = np.array([row['rho0 / mol/m^3'], row['rho1 / mol/m^3']])\n",
    "        return tweaked.get_splus(T=row['T / K'], rhovec=rhovec)\n",
    "    df['s^+'] = df.apply(add_splus,axis=1)\n",
    "    df['rho / mol/m^3'] = df['rho0 / mol/m^3']+df['rho1 / mol/m^3']\n",
    "    # df.info()\n",
    "    return df\n",
    "\n",
    "def crit_curve_plotter(**kwargs):\n",
    "    df = get_critical_curve(kwargs)\n",
    "    plt.plot(df['T / K'], df['p / Pa'])\n",
    "    \n",
    "    d = pandas.read_csv('NH3H2Odata.csv', sep=';')\n",
    "    d = d[d.type == 'PTcrit']\n",
    "    plt.plot(d['T (K)'], d['p (Pa)'], 'o')\n",
    "    \n",
    "    plt.gca().set(xlabel='$T$ / K', ylabel='$p$ / Pa')\n",
    "    "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "crit_curve_plotter(**{'lambdaT': 0.07999999999999999, 'phiT': 1.05, 'lambdaV': -0.1, 'phiV': 0.9800000000000001, 'type': 'invariant'})\n",
    "\n",
    "interactive_plot = interactive(crit_curve_plotter, lambdaT=(-0.1,0.1,0.02),phiT=(0.9,1.5,0.02),lambdaV=(-0.1,0.1,0.02),phiV=(0.9,1.5,0.02), type=['invariant'])\n",
    "output = interactive_plot.children[-1]\n",
    "output.layout.height = '400px'\n",
    "interactive_plot"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# crit_curve_plotter(**{'betaT': 1.0, 'gammaT': 1.0, 'betaV': 1.0, 'gammaV': 1, 'type': 'GERG'})\n",
    "\n",
    "interactive_plot = interactive(crit_curve_plotter, betaT=(0.9,1.1,0.01),gammaT=(0.5,2,0.02),betaV=(0.9,1.1,0.02),gammaV=(0.2,2,0.02), type=['GERG'])\n",
    "output = interactive_plot.children[-1]\n",
    "output.layout.height = '400px'\n",
    "interactive_plot"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.10.6"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 4
}