{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 43,
   "metadata": {},
   "outputs": [],
   "source": [
    "import scipy.integrate\n",
    "import numpy\n",
    "import matplotlib.pyplot\n",
    "import os\n",
    "import json\n",
    "import scipy.interpolate\n",
    "#for partial specialization\n",
    "import cModel\n",
    "import importlib\n",
    "importlib.reload(cModel)\n",
    "import time\n",
    "import ivp\n",
    "importlib.reload(ivp)\n",
    "import runSolver\n",
    "importlib.reload(runSolver)\n",
    "\n",
    "def getModel(solution,modelName):\n",
    "    Q=solution[modelName]\n",
    "    model=cModel.model()\n",
    "    setupFile=Q['setup']\n",
    "    modelFile=Q['model']\n",
    "    parameterFile=Q['parameters']\n",
    "    print('modelFile: {} {}'.format(modelFile,os.path.isfile(modelFile)))\n",
    "    print('parameterFile: {} {}'.format(parameterFile,os.path.isfile(parameterFile)))\n",
    "    model.parse(modelFile,parameterFile)\n",
    "    return model\n",
    "\n",
    "def getSum(data,modelName):\n",
    "    \n",
    "    model=getModel(data,modelName)\n",
    "    Q=data[modelName]['solution']\n",
    "    lut=Q['lut']\n",
    "    total=Q['sol'][-1,lut['total']]\n",
    "    #print(total)\n",
    "    fQ={}\n",
    "    for x in lut:\n",
    "        if x=='total':\n",
    "            continue\n",
    "        j=lut[x]\n",
    "        try:\n",
    "            v=model.get(model.mod['volumes'][x])['value']\n",
    "            fQ[x]=Q['sol'][-1,j]*v/total\n",
    "        except KeyError:\n",
    "            #print('{} {}'.format(x,x in model.mod['scaled']))\n",
    "            fQ[x]=Q['sol'][-1,j]\n",
    "    print(sum(list(fQ.values())))\n",
    "    print(sorted(fQ.items(), key=lambda item:item[1]))\n",
    "\n",
    "def mergeSolutions(seq):\n",
    "    out={}\n",
    "    #each element in sequence should have this components\n",
    "    for v in ['t','sol','se','qt','sOut']:\n",
    "        out[v]=numpy.concatenate([x[v] for x in seq])\n",
    "    #copy last for settings\n",
    "    for v in ['lut','lutSE','setup','model','parameters','qt','sOut']:\n",
    "        out[v]=seq[-1][v]\n",
    "    return out    "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "a={}\n",
    "fh=os.path.expanduser('~')\n",
    "a['jobDir']=os.path.join(fh,'temp','cDiazepam')\n",
    "a['modelFile']=os.path.join(fh,'software','src','PBPK','models','cDiazepam.json')\n",
    "a['parameterFile']=os.path.join(fh,'software','src','PBPK','models','cDiazepam_parameters.json')\n",
    "a['setupFile']=os.path.join(fh,'software','src','PBPK','setup','setupMinute.json')\n",
    "model=cModel.model()\n",
    "model.parse(a['modelFile'],a['parameterFile'])\n",
    "model.inspect()\n",
    "model.get('venousInput')\n",
    "#runSolver.main([a['setupFile'],a['modelFile'],a['parameterFile']],jobDir=a['jobDir'],startDir='NONE')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 50,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Using /home/studen/temp/cDiazepam\n",
      "Using solution from None\n",
      "t0=0\n",
      "t0 0 tmax 1.0\n",
      "Done simultaneous LSODA SE\n",
      "Time: 0.027 s\n",
      "Completed step _step000\n",
      "Completed run\n",
      "Written /home/studen/temp/cDiazepam/setup.json\n",
      "Written /home/studen/temp/cDiazepam/model.json\n",
      "Written /home/studen/temp/cDiazepam/parameters.json\n",
      "Using /home/studen/temp/cDiazepam1\n",
      "Using solution from /home/studen/temp/cDiazepam\n",
      "t0 0 tmax 1.0\n",
      "Parsing [1/1]\n",
      "t0=1.0\n",
      "t0 1.0 tmax 720.0\n",
      "At t=24.79\n",
      "At t=49.58\n",
      "At t=72.33\n",
      "At t=96.51\n",
      "At t=123.87\n",
      "At t=151.34\n",
      "At t=178.93\n",
      "At t=206.49\n",
      "At t=234.00\n",
      "Done simultaneous LSODA SE\n",
      "Time: 0.658 s\n",
      "Completed step _step000\n",
      "At t=263.39\n",
      "At t=291.02\n",
      "At t=318.58\n",
      "At t=346.08\n",
      "At t=373.71\n",
      "At t=401.37\n",
      "At t=429.04\n",
      "At t=456.51\n",
      "Done simultaneous LSODA SE\n",
      "Time: 0.637 s\n",
      "Completed step _step001\n",
      "At t=484.70\n",
      "At t=512.21\n",
      "At t=539.84\n",
      "At t=567.51\n",
      "At t=595.17\n",
      "At t=622.63\n",
      "At t=650.24\n",
      "At t=677.90\n",
      "At t=705.62\n",
      "Done simultaneous LSODA SE\n",
      "Time: 0.663 s\n",
      "Completed step _step002\n",
      "Completed run\n",
      "Written /home/studen/temp/cDiazepam1/setup.json\n",
      "Written /home/studen/temp/cDiazepam1/model.json\n",
      "Written /home/studen/temp/cDiazepam1/parameters.json\n"
     ]
    }
   ],
   "source": [
    "#run solver\n",
    "fh=os.path.expanduser('~')\n",
    "i=0\n",
    "data={}\n",
    "a={}\n",
    "#based on\n",
    "#MD Thompson, DA Beard, F Wu. Use of partition coefficient in flow-limited physiologically based pharmacokinetic modelling. \n",
    "#J Pharmacokinet Pharmacodyn 39 (4) 2012.\n",
    "a['jobDir']=os.path.join(fh,'temp','cDiazepam')\n",
    "a['modelFile']=os.path.join(fh,'software','src','PBPK','models','cDiazepam.json')\n",
    "#set input to 1 for one minute\n",
    "a['parameterFile']=os.path.join(fh,'software','src','PBPK','models','cDiazepam_parameters1.json')\n",
    "a['setupFile']=os.path.join(fh,'software','src','PBPK','setup','setupMinute.json')\n",
    "a['srcDir']='NONE'\n",
    "a['doCalculate']=True\n",
    "data['cDiazepam']=[a]\n",
    "\n",
    "c={}\n",
    "c['jobDir']=os.path.join(fh,'temp','cDiazepam1')\n",
    "c['modelFile']=os.path.join(fh,'software','src','PBPK','models','cDiazepam.json')\n",
    "#set input to 0\n",
    "c['parameterFile']=os.path.join(fh,'software','src','PBPK','models','cDiazepam_parameters2.json')\n",
    "c['setupFile']=os.path.join(fh,'software','src','PBPK','setup','setupHours.json')\n",
    "c['srcDir']=os.path.join(fh,'temp','cDiazepam')\n",
    "c['doCalculate']=True\n",
    "data['cDiazepam'].append(c)\n",
    "\n",
    "b={}\n",
    "#MD Thompson, DA Beard, F Wu. Use of partition coefficient in flow-limited physiologically based pharmacokinetic modelling. \n",
    "#J Pharmacokinet Pharmacodyn 39 (4) 2012.\n",
    "b['jobDir']=os.path.join(fh,'temp','cDiazepamF')\n",
    "b['modelFile']=os.path.join(fh,'software','src','PBPK','models','cDiazepam.json')\n",
    "b['parameterFile']=os.path.join(fh,'software','src','PBPK','models','cDiazepam_parameters.json')\n",
    "b['setupFile']=os.path.join(fh,'software','src','PBPK','setup','setupHours.json')\n",
    "b['srcDir']='NONE'\n",
    "b['doCalculate']=False\n",
    "data['cDiazepamF']=[b]\n",
    "\n",
    "#make sure we do it in proper order\n",
    "for x in data:\n",
    "    seq=data[x]\n",
    "    for job in seq:\n",
    "        if not job['doCalculate']:\n",
    "            continue\n",
    "    \n",
    "        if not os.path.isdir(job['jobDir']):\n",
    "            os.mkdir(job['jobDir'])\n",
    "        runSolver.main([job['setupFile'],job['modelFile'],job['parameterFile']],job['jobDir'],job['srcDir'])\n",
    "    \n",
    "\n",
    "#t0,y0,S1,lut,lutSE=runSolver.getStartPoint(setup)\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 51,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "t0 0 tmax 1.0\n",
      "Parsing [1/1]\n",
      "t0 1.0 tmax 720.0\n",
      "Parsing [1/3]\n",
      "Parsing [2/3]\n",
      "Parsing [3/3]\n",
      "t0 0 tmax 720.0\n",
      "Parsing [1/3]\n",
      "Parsing [2/3]\n",
      "Parsing [3/3]\n"
     ]
    }
   ],
   "source": [
    "#make solutions transparent\n",
    "solution={}\n",
    "for x in data:\n",
    "    seq=[runSolver.loadSolutionFromDir(job['jobDir'],True) for job in data[x]]\n",
    "    solution[x]=mergeSolutions(seq)\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "model=getModel(data,'cDiazepamF')\n",
    "tscale=runSolver.getScale(solution['cDiazepamF']['setup'])\n",
    "print(f'tscale={tscale}')\n",
    "model.inspect()    \n",
    "\n",
    "print(\"***********done************\")\n",
    "print(model.M(1).shape)\n",
    "#print(sys.fSS(2))\n",
    "print(model.m)\n",
    "\n",
    "nt=setup['nt']\n",
    "qtmax=1 #minute\n",
    "qt=numpy.linspace(0,qtmax,nt)\n",
    "#ft=[fw['derivatives']['fetusGrowthDuration'](x) for x in qt]\n",
    "par='venousInput'\n",
    "#plot parameters\n",
    "try:\n",
    "    hw=model.get(par)\n",
    "    print(hw)\n",
    "    ht=[10*hw['value'](x) for x in qt]\n",
    "    matplotlib.pyplot.plot(qt/tscale,ht)\n",
    "except (KeyError,TypeError):\n",
    "    print(f'Troubles getting {par}')\n",
    "    pass\n",
    "start_time=time.time()\n",
    "for i in range(100000):\n",
    "    model.M(1e7)\n",
    "end_time=time.time()\n",
    "print('Time: {:.3f} s'.format(end_time-start_time))\n",
    "print(model.M(0)[8,:])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 52,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "modelFile: /home/studen/temp/cDiazepamF/model.json True\n",
      "parameterFile: /home/studen/temp/cDiazepamF/parameters.json True\n"
     ]
    },
    {
     "data": {
      "image/png": "[encoded data, 342884 characters]\n",
      "text/plain": [
       "<Figure size 1500x2000 with 12 Axes>"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "i=0\n",
    "modelName='cDiazepamF'\n",
    "model=getModel(solution,modelName)\n",
    "tscale=runSolver.getScale(solution[modelName]['setup'])\n",
    "\n",
    "name=['venous','adipose','brain',\n",
    "      'heart','kidney','liver',\n",
    "      'lung','muscle','skin',\n",
    "      #'brainBlood','inorganicMercury','total'\n",
    "     'stomach','splanchnic','excrement'\n",
    "      ]\n",
    "tmax=solution[modelName]['t'][-1]\n",
    "max=[-1]*len(name)\n",
    "#max[2]=2000\n",
    "models={}\n",
    "models['cDiazepam']={'color':'orange','shadeColor':'red'}\n",
    "models['cDiazepamF']={'color':'black','shadeColor':'green'}\n",
    "\n",
    "fig, axs = matplotlib.pyplot.subplots(4, 3,figsize=(15,20))\n",
    "for i in range(len(name)):\n",
    "    row=i//3\n",
    "    col=i%3\n",
    "    ax=axs[row,col]\n",
    "    for m in models:\n",
    "        fM=models[m]\n",
    "        Q=solution[m]\n",
    "        v=name[i]\n",
    "        try:\n",
    "            j=Q['lut'][v]\n",
    "        except KeyError:\n",
    "            try:\n",
    "                v1=alias[v]\n",
    "            except KeyError:\n",
    "                print('No data for {}'.format(v))\n",
    "                continue    \n",
    "            try:\n",
    "                j=Q['lut'][v1]\n",
    "            except KeyError:\n",
    "                print('No data for {}/{}'.format(v,v1))\n",
    "                continue    \n",
    "                \n",
    "        fy=Q['sol'][:,j]\n",
    "        fe=Q['se'][:,j]\n",
    "        t=Q['t']\n",
    "        ax.plot(t/tscale,fy,color=fM['color'])\n",
    "        ax.fill_between(t/tscale, fy-fe, fy + fe, color=fM['shadeColor'],alpha=0.1)\n",
    "        ax.plot(t/tscale,fy-fe,color=fM['shadeColor'],linewidth=1,alpha=0.2)\n",
    "        ax.plot(t/tscale,fy+fe,color=fM['shadeColor'],linewidth=1,alpha=0.2)\n",
    "        \n",
    "        \n",
    "    if max[i]>0:\n",
    "        axs[row,col].set_ylim([0,max[i]])\n",
    "    axs[row,col].set_xlim([0,1.1*tmax/tscale])\n",
    "    axs[row,col].set_xlabel(setup['tUnit'])\n",
    "    axs[row,col].set_title(name[i])\n",
    "    \n",
    "\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 59,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "[<matplotlib.lines.Line2D at 0x7f659fa8d780>]"
      ]
     },
     "execution_count": 59,
     "metadata": {},
     "output_type": "execute_result"
    },
    {
     "data": {
      "image/png": "[encoded data, 18432 characters]\n",
      "text/plain": [
       "<Figure size 640x480 with 1 Axes>"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "Q=data['humanHG_RBC']['solution']\n",
    "lut=Q['lut']\n",
    "fy1=Q['sol'][:,lut['redBloodCells']]\n",
    "fy=Q['sol'][:,lut['plasma']]\n",
    "qy=fy1[1:]/fy[1:]\n",
    "t=Q['t']\n",
    "matplotlib.pyplot.plot(t[1:],qy)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "\n",
    "pmodel=cModel.model()\n",
    "\n",
    "model.parse(modelFile,parameterFile)\n",
    "print('w(oI) {}'.format(model.getWeight('oralIngestion')))\n",
    "t,sol,se,sOut,qt,lut,lutSE,setup1=runSolver.loadSolutionFromDir(humanHG)\n",
    "compartment='kidney'\n",
    "#compartment='liverI'\n",
    "d=model.getDerivatives(sOut,lut[compartment])\n",
    "w=model.getWeights(lutSE)\n",
    "w=numpy.ones((len(lutSE)))\n",
    "print('Sum ({}, der, sigma_p)'.format(compartment))\n",
    "s={x:d[lutSE[x]]*w[lutSE[x]] for x in lutSE}\n",
    "s=dict(sorted(s.items(), key=lambda item:item[1],reverse=True))\n",
    "for p in list(s)[:10]:\n",
    "    j=lutSE[p]\n",
    "    print('\\t{:.2g} [{:.2g} {:.2g}] {} '.format(d[j]*w[j],d[j],w[j],p))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 23,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "modelFile: /home/studen/temp/humanHGplusI_RBC/model.json True\n",
      "parameterFile: /home/studen/temp/humanHGplusI_RBC/parameters.json True\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "{'value': 4.33728,\n",
       " 'derivatives': {'plasmaTotalVolumeFraction': 67.77,\n",
       "  'redBloodCellsVolumeFraction': 67.77,\n",
       "  'bodyWeight': 0.064}}"
      ]
     },
     "execution_count": 23,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "model=getModel(data,'humanHGplusI_RBC')\n",
    "tscale=runSolver.getScale(data['humanHGplusI_RBC']['solution']['setup'])\n",
    "#calculate total mass of xeno-substance\n",
    "model.get(\"bloodToPlasmaPCscale\")\n",
    "model.get(\"bloodVolume\")\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 40,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "modelFile: /home/studen/temp/humanHGplusI_RBC/model.json True\n",
      "parameterFile: /home/studen/temp/humanHGplusI_RBC/parameters.json True\n",
      "0\n",
      "1\n",
      "2\n",
      "3\n",
      "5\n",
      "6\n",
      "7\n",
      "9\n",
      "10\n",
      "11\n",
      "12\n",
      "13\n",
      "15\n",
      "16\n",
      "17\n",
      "19\n",
      "0.999999998652029\n",
      "[('brainI', 5.591268564730524e-08), ('urine', 6.920503851883565e-07), ('hairI', 2.829112820729282e-06), ('hair', 2.5908112965118847e-05), ('bloodI', 6.48014370354082e-05), ('kidneyI', 0.00034539782696188444), ('brainBlood', 0.0008838108138251085), ('fecesI', 0.0009365878956040508), ('liverI', 0.0016857155746677485), ('plasma', 0.002537491433132075), ('venous', 0.0025444401202051573), ('brain', 0.004082574560654416), ('kidney', 0.010365728769627663), ('gut', 0.013662463918991298), ('fat', 0.0257916393847429), ('feces', 0.02667203433643526), ('redBloodCells', 0.03545009717387017), ('richlyPerfused', 0.0636064259191453), ('liver', 0.09840624607901789), ('intestine', 0.30824288460368277), ('slowlyPerfused', 0.40469217361557336)]\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "{'value': 4.33728,\n",
       " 'derivatives': {'plasmaTotalVolumeFraction': 67.77,\n",
       "  'redBloodCellsVolumeFraction': 67.77,\n",
       "  'bodyWeight': 0.064}}"
      ]
     },
     "execution_count": 40,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "getSum(data,'humanHGplusI_RBC')\n",
    "tscale=runSolver.getScale(Q['setup'])\n",
    "#calculate total mass of xeno-substance\n",
    "model.get(\"bloodToPlasmaPCscale\")\n",
    "model.get(\"bloodVolume\")"
   ]
  },
  {
   "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.12"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 4
}
