{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 12,
   "metadata": {},
   "outputs": [],
   "source": [
    "import numpy\n",
    "import matplotlib.pyplot\n",
    "import os\n",
    "import json\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",
    "import numpy.linalg\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 \n",
    "\n",
    "def updateSetup(job):\n",
    "    setupFileSrc=job['setupFile']\n",
    "    setupFile=os.path.join(job['jobDir'],'setupInput.json')\n",
    "\n",
    "    with open(setupFileSrc,'r') as f:\n",
    "        setup=json.load(f)\n",
    "    try:\n",
    "        setup.update(job['setupUpdates'])\n",
    "    except KeyError:\n",
    "        pass\n",
    "    \n",
    "    with open(setupFile,'w+') as f:\n",
    "        f.write(json.dumps(setup))\n",
    "    return setupFile\n",
    "        "
   ]
  },
  {
   "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": 32,
   "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",
      "At t=21.86\n",
      "At t=33.23\n",
      "At t=44.66\n",
      "At t=59.22\n",
      "At t=75.71\n",
      "At t=93.42\n",
      "Done simultaneous LSODA SE\n",
      "Time: 0.479 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/cDiazepamF\n",
      "Using solution from None\n",
      "t0=0\n",
      "t0 0 tmax 1.0\n",
      "At t=24.99\n",
      "At t=33.75\n",
      "At t=38.07\n",
      "At t=42.68\n",
      "At t=45.68\n",
      "At t=48.08\n",
      "At t=50.55\n",
      "At t=53.08\n",
      "At t=55.98\n",
      "At t=59.13\n",
      "At t=62.36\n",
      "At t=65.66\n",
      "At t=69.04\n",
      "At t=72.48\n",
      "At t=75.95\n",
      "At t=79.27\n",
      "At t=82.21\n",
      "At t=85.19\n",
      "At t=88.22\n",
      "At t=91.32\n",
      "At t=94.46\n",
      "At t=97.66\n",
      "Done simultaneous LSODA SE\n",
      "Time: 7.988 s\n",
      "Completed step _step000\n",
      "Completed run\n",
      "Written /home/studen/temp/cDiazepamF/setup.json\n",
      "Written /home/studen/temp/cDiazepamF/model.json\n",
      "Written /home/studen/temp/cDiazepamF/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','setupMinute.json')\n",
    "b['srcDir']='NONE'\n",
    "b['doCalculate']=True\n",
    "data['cDiazepamF']=[b]\n",
    "\n",
    "d={}\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",
    "d['jobDir']=os.path.join(fh,'temp','cDiazepamB')\n",
    "d['modelFile']=os.path.join(fh,'software','src','PBPK','models','cDiazepam.json')\n",
    "d['parameterFile']=os.path.join(fh,'software','src','PBPK','models','cDiazepam_parameters3.json')\n",
    "d['setupFile']=os.path.join(fh,'software','src','PBPK','setup','setupHours.json')\n",
    "#d['setupUpdates']={'mode':'solveMatrix','method':'separately'}\n",
    "d['srcDir']='NONE'\n",
    "d['doCalculate']=True\n",
    "#data['cDiazepamB']=[d]\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",
    "            \n",
    "        #adjust local setup file with ad-hoc modifications\n",
    "        setupFile=updateSetup(job)\n",
    "        \n",
    "        runSolver.main([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": 33,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "t0 0 tmax 1.0\n",
      "Parsing [1/1]\n",
      "t0 0 tmax 1.0\n",
      "Parsing [1/1]\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": 27,
   "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",
      "tscale=1\n",
      "Time unit: min\n",
      "Compartments\n",
      "adipose/0:\n",
      "\ttargets\n",
      "\t\tadipose[0,0]: [-0.01103896103896104]\n",
      "\t\tarterial[0,13]: [0.255]\n",
      "brain/1:\n",
      "\ttargets\n",
      "\t\tbrain[1,1]: [-0.2954545454545454]\n",
      "\t\tarterial[1,13]: [0.65]\n",
      "heart/2:\n",
      "\ttargets\n",
      "\t\theart[2,2]: [-0.9767441860465117]\n",
      "\t\tarterial[2,13]: [4.2]\n",
      "kidney/3:\n",
      "\ttargets\n",
      "\t\tkidney[3,3]: [-1.5971153846153845]\n",
      "\t\tarterial[3,13]: [8.305]\n",
      "liver/4:\n",
      "\ttargets\n",
      "\t\tliver[4,4]: [-0.057272727272727274, -0.25674325674325676]\n",
      "\t\tsplanchnic[4,5]: [0.4281183932346723]\n",
      "\t\tstomach[4,6]: [0.03838383838383838]\n",
      "\t\tarterial[4,13]: [0.3227272727272727]\n",
      "splanchnic/5:\n",
      "\ttargets\n",
      "\t\tsplanchnic[5,5]: [-0.3139534883720931]\n",
      "\t\tarterial[5,13]: [1.35]\n",
      "stomach/6:\n",
      "\ttargets\n",
      "\t\tstomach[6,6]: [-0.3838383838383838]\n",
      "\t\tarterial[6,13]: [1.727272727272727]\n",
      "muscle/7:\n",
      "\ttargets\n",
      "\t\tmuscle[7,7]: [-0.05416666666666667]\n",
      "\t\tarterial[7,13]: [0.13]\n",
      "skin/8:\n",
      "\ttargets\n",
      "\t\tskin[8,8]: [-0.05065639269406392]\n",
      "\t\tarterial[8,13]: [0.16210045662100456]\n",
      "testes/9:\n",
      "\ttargets\n",
      "\t\ttestes[9,9]: [-0.16170212765957445]\n",
      "\t\tarterial[9,13]: [0.76]\n",
      "remainder/10:\n",
      "\ttargets\n",
      "\t\tremainder[10,10]: [-0.01883390870732643]\n",
      "\t\tarterial[10,13]: [0.31075949367088607]\n",
      "lung/11:\n",
      "\ttargets\n",
      "\t\tvenous[11,14]: [66.66666666666667]\n",
      "\t\tlung[11,11]: [-12.578616352201259]\n",
      "excrement/12:\n",
      "\ttargets\n",
      "\t\tliver[12,4]: [0.63]\n",
      "arterial/13:\n",
      "\ttargets\n",
      "\t\tarterial[13,13]: [-0.375, -0.11470588235294119, -0.6176470588235294, -2.442647058823529, -0.5220588235294118, -2.389705882352941, -1.0441176470588236, -0.27941176470588236, -0.7220588235294118, -2.9779411764705883, -0.27941176470588236]\n",
      "\t\tlung[13,11]: [2.219755826859046]\n",
      "venous/14:\n",
      "\tinput\n",
      "\t\tvenousInput\n",
      "\ttargets\n",
      "\t\tadipose[14,0]: [0.008116883116883116]\n",
      "\t\tbrain[14,1]: [0.02606951871657754]\n",
      "\t\theart[14,2]: [0.07181942544459645]\n",
      "\t\tkidney[14,3]: [0.23486990950226241]\n",
      "\t\tliver[14,4]: [0.2076599870717518]\n",
      "\t\tmuscle[14,7]: [0.49785539215686275]\n",
      "\t\tskin[14,8]: [0.16314338235294118]\n",
      "\t\ttestes[14,9]: [0.02972465581977472]\n",
      "\t\tremainder[14,10]: [0.021880570409982175]\n",
      "\t\tvenous[14,14]: [-5.882352941176471]\n",
      "total/15:\n",
      "\ttargets\n",
      "Flows\n",
      "\tarterial:adipose[(arterial,venous):adipose]:adiposeFlow [{'value': 2.55, 'derivatives': {'adiposeFlow': 1}}]\n",
      "\tvenous:adipose[(arterial,venous):adipose]:adiposeFlow [{'value': 2.55, 'derivatives': {'adiposeFlow': 1}}]\n",
      "\tarterial:brain[(arterial,venous):brain]:brainFlow [{'value': 0.78, 'derivatives': {'brainFlow': 1}}]\n",
      "\tvenous:brain[(arterial,venous):brain]:brainFlow [{'value': 0.78, 'derivatives': {'brainFlow': 1}}]\n",
      "\tarterial:heart[(arterial,venous):heart]:heartFlow [{'value': 4.2, 'derivatives': {'heartFlow': 1}}]\n",
      "\tvenous:heart[(arterial,venous):heart]:heartFlow [{'value': 4.2, 'derivatives': {'heartFlow': 1}}]\n",
      "\tarterial:kidney[(arterial,venous):kidney]:kidneyFlow [{'value': 16.61, 'derivatives': {'kidneyFlow': 1}}]\n",
      "\tvenous:kidney[(arterial,venous):kidney]:kidneyFlow [{'value': 16.61, 'derivatives': {'kidneyFlow': 1}}]\n",
      "\tarterial:liver[arterial:liver]:liverInFlow [{'value': 3.55, 'derivatives': {'liverInFlow': 1}}]\n",
      "\tliver:venous[liver:venous]:liverOutFlow [{'value': 25.7, 'derivatives': {'liverInFlow': 1, 'stomachFlow': 1, 'splanchnicFlow': 1}}]\n",
      "\tarterial:lung[(arterial,venous):lung]:totalFlow [{'value': 80, 'derivatives': {'totalFlow': 1}}]\n",
      "\tvenous:lung[(arterial,venous):lung]:totalFlow [{'value': 80, 'derivatives': {'totalFlow': 1}}]\n",
      "\tarterial:muscle[(arterial,venous):muscle]:muscleFlow [{'value': 16.25, 'derivatives': {'muscleFlow': 1}}]\n",
      "\tvenous:muscle[(arterial,venous):muscle]:muscleFlow [{'value': 16.25, 'derivatives': {'muscleFlow': 1}}]\n",
      "\tarterial:skin[(arterial,venous):skin]:skinFlow [{'value': 7.1, 'derivatives': {'skinFlow': 1}}]\n",
      "\tvenous:skin[(arterial,venous):skin]:skinFlow [{'value': 7.1, 'derivatives': {'skinFlow': 1}}]\n",
      "\tarterial:splanchnic[(arterial,liver):splanchnic]:splanchnicFlow [{'value': 20.25, 'derivatives': {'splanchnicFlow': 1}}]\n",
      "\tliver:splanchnic[(arterial,liver):splanchnic]:splanchnicFlow [{'value': 20.25, 'derivatives': {'splanchnicFlow': 1}}]\n",
      "\tarterial:stomach[(arterial,liver):stomach]:stomachFlow [{'value': 1.9, 'derivatives': {'stomachFlow': 1}}]\n",
      "\tliver:stomach[(arterial,liver):stomach]:stomachFlow [{'value': 1.9, 'derivatives': {'stomachFlow': 1}}]\n",
      "\tarterial:testes[(arterial,venous):testes]:testesFlow [{'value': 1.9, 'derivatives': {'testesFlow': 1}}]\n",
      "\tvenous:testes[(arterial,venous):testes]:testesFlow [{'value': 1.9, 'derivatives': {'testesFlow': 1}}]\n",
      "\tarterial:remainder[(arterial,venous):remainder]:remainderFlow [{'value': 4.91, 'derivatives': {'remainderFlow': 1}}]\n",
      "\tvenous:remainder[(arterial,venous):remainder]:remainderFlow [{'value': 4.91, 'derivatives': {'remainderFlow': 1}}]\n",
      "Volumes\n",
      "\tadipose:adiposeVolume [{'value': 10, 'derivatives': {'adiposeVolume': 1}}]\n",
      "\tbrain:brainVolume [{'value': 1.2, 'derivatives': {'brainVolume': 1}}]\n",
      "\theart:heartVolume [{'value': 1, 'derivatives': {'heartVolume': 1}}]\n",
      "\tkidney:kidneyVolume [{'value': 2, 'derivatives': {'kidneyVolume': 1}}]\n",
      "\tliver:liverVolume [{'value': 11, 'derivatives': {'liverVolume': 1}}]\n",
      "\tlung:lungVolume [{'value': 1.2, 'derivatives': {'lungVolume': 1}}]\n",
      "\tmuscle:muscleVolume [{'value': 125, 'derivatives': {'muscleVolume': 1}}]\n",
      "\tskin:skinVolume [{'value': 43.8, 'derivatives': {'skinVolume': 1}}]\n",
      "\tsplanchnic:splanchnicVolume [{'value': 15, 'derivatives': {'splanchnicVolume': 1}}]\n",
      "\tstomach:stomachVolume [{'value': 1.1, 'derivatives': {'stomachVolume': 1}}]\n",
      "\ttestes:testesVolume [{'value': 2.5, 'derivatives': {'testesVolume': 1}}]\n",
      "\tremainder:remainderVolume [{'value': 15.8, 'derivatives': {'remainderVolume': 1}}]\n",
      "\tvenous:venousVolume [{'value': 13.6, 'derivatives': {'venousVolume': 1}}]\n",
      "\tarterial:arterialVolume [{'value': 6.8, 'derivatives': {'arterialVolume': 1}}]\n",
      "Partition coefficients\n",
      "\tadipose:adiposePC [{'value': 23.1, 'derivatives': {'adiposePC': 1}}]\n",
      "\tbrain:brainPC [{'value': 2.2, 'derivatives': {'brainPC': 1}}]\n",
      "\theart:heartPC [{'value': 4.3, 'derivatives': {'heartPC': 1}}]\n",
      "\tkidney:kidneyPC [{'value': 5.2, 'derivatives': {'kidneyPC': 1}}]\n",
      "\tliver:liverPC [{'value': 9.1, 'derivatives': {'liverPC': 1}}]\n",
      "\tlung:lungPC [{'value': 5.3, 'derivatives': {'lungPC': 1}}]\n",
      "\tmuscle:musclePC [{'value': 2.4, 'derivatives': {'musclePC': 1}}]\n",
      "\tremainder:remainderPC [{'value': 16.5, 'derivatives': {'remainderPC': 1}}]\n",
      "\tskin:skinPC [{'value': 3.2, 'derivatives': {'skinPC': 1}}]\n",
      "\tsplanchnic:splanchnicPC [{'value': 4.3, 'derivatives': {'splanchnicPC': 1}}]\n",
      "\tstomach:stomachPC [{'value': 4.5, 'derivatives': {'stomachPC': 1}}]\n",
      "\ttestes:testesPC [{'value': 4.7, 'derivatives': {'testesPC': 1}}]\n",
      "***********done************\n",
      "(16, 16)\n",
      "6\n",
      "{'value': functools.partial(<function feps at 0x7ffb4ce91990>, A=250000.0, tau=10), 'function': True, 'derivatives': {'inputTau': <function sumArray.<locals>.<lambda> at 0x7ffb472afd00>, 'inputA': <function sumArray.<locals>.<lambda> at 0x7ffb472af2e0>}}\n",
      "Time: 0.038 s\n",
      "Rank: 14/(16, 16)\n",
      "[[ -0.01   0.     0.     0.     0.     0.     0.     0.     0.     0.     0.     0.     0.     0.26   0.     0.  ]\n",
      " [  0.    -0.3    0.     0.     0.     0.     0.     0.     0.     0.     0.     0.     0.     0.65   0.     0.  ]\n",
      " [  0.     0.    -0.98   0.     0.     0.     0.     0.     0.     0.     0.     0.     0.     4.2    0.     0.  ]\n",
      " [  0.     0.     0.    -1.6    0.     0.     0.     0.     0.     0.     0.     0.     0.     8.3    0.     0.  ]\n",
      " [  0.     0.     0.     0.    -0.31   0.43   0.04   0.     0.     0.     0.     0.     0.     0.32   0.     0.  ]\n",
      " [  0.     0.     0.     0.     0.    -0.31   0.     0.     0.     0.     0.     0.     0.     1.35   0.     0.  ]\n",
      " [  0.     0.     0.     0.     0.     0.    -0.38   0.     0.     0.     0.     0.     0.     1.73   0.     0.  ]\n",
      " [  0.     0.     0.     0.     0.     0.     0.    -0.05   0.     0.     0.     0.     0.     0.13   0.     0.  ]\n",
      " [  0.     0.     0.     0.     0.     0.     0.     0.    -0.05   0.     0.     0.     0.     0.16   0.     0.  ]\n",
      " [  0.     0.     0.     0.     0.     0.     0.     0.     0.    -0.16   0.     0.     0.     0.76   0.     0.  ]\n",
      " [  0.     0.     0.     0.     0.     0.     0.     0.     0.     0.    -0.02   0.     0.     0.31   0.     0.  ]\n",
      " [  0.     0.     0.     0.     0.     0.     0.     0.     0.     0.     0.   -12.58   0.     0.    66.67   0.  ]\n",
      " [  0.     0.     0.     0.     0.63   0.     0.     0.     0.     0.     0.     0.     0.     0.     0.     0.  ]\n",
      " [  0.     0.     0.     0.     0.     0.     0.     0.     0.     0.     0.     2.22   0.   -11.76   0.     0.  ]\n",
      " [  0.01   0.03   0.07   0.23   0.21   0.     0.     0.5    0.16   0.03   0.02   0.     0.     0.    -5.88   0.  ]\n",
      " [  0.     0.     0.     0.     0.     0.     0.     0.     0.     0.     0.     0.     0.     0.     0.     0.  ]]\n",
      "[[-0.01+3.14e-03j -0.01-3.14e-03j]\n",
      " [-0.03+8.06e-03j -0.03-8.06e-03j]\n",
      " [-0.23+5.26e-02j -0.23-5.26e-02j]\n",
      " [-0.49+1.04e-01j -0.49-1.04e-01j]\n",
      " [-0.01+3.82e-03j -0.01-3.82e-03j]\n",
      " [-0.07+1.67e-02j -0.07-1.67e-02j]\n",
      " [-0.09+2.15e-02j -0.09-2.15e-02j]\n",
      " [-0.01+1.60e-03j -0.01-1.60e-03j]\n",
      " [-0.01+2.00e-03j -0.01-2.00e-03j]\n",
      " [-0.04+9.39e-03j -0.04-9.39e-03j]\n",
      " [-0.01+3.82e-03j -0.01-3.82e-03j]\n",
      " [ 0.71+0.00e+00j  0.71-0.00e+00j]\n",
      " [ 0.  -1.08e-04j  0.  +1.08e-04j]\n",
      " [ 0.38-1.80e-01j  0.38+1.80e-01j]\n",
      " [ 0.05+1.75e-02j  0.05-1.75e-02j]\n",
      " [ 0.  +0.00e+00j  0.  -0.00e+00j]]\n",
      "101 101\n",
      "[ 2.50e+05+4.44e-12j -1.20e+05-5.11e-11j  4.70e+04-3.07e+05j  4.70e+04+3.07e+05j  2.63e+04+2.27e-11j -3.88e+04-9.01e-12j  2.33e+04+4.02e-12j\n",
      "  1.03e+03-6.35e-12j  3.45e+01+5.13e-13j -7.98e+03-2.39e-12j -2.15e+04+9.46e-12j  2.11e+05+5.67e-12j -9.67e+03+5.28e-13j  1.39e+04+6.74e-12j\n",
      " -1.11e+02-3.68e-13j  2.50e+05+0.00e+00j]\n"
     ]
    },
    {
     "data": {
      "image/png": "[encoded data, 24420 characters]\n",
      "text/plain": [
       "<Figure size 640x480 with 1 Axes>"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    },
    {
     "data": {
      "image/png": "[encoded data, 23600 characters]\n",
      "text/plain": [
       "<Figure size 640x480 with 1 Axes>"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "modelName='cDiazepamF'\n",
    "model=getModel(solution,modelName)\n",
    "setup=solution[modelName]['setup']\n",
    "tscale=runSolver.getScale(solution[modelName]['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",
    "fM=model.M(0)\n",
    "print('Rank: {}/{}'.format(numpy.linalg.matrix_rank(fM),fM.shape))\n",
    "numpy.set_printoptions(suppress=True,precision=2,linewidth=150)\n",
    "print(f'{fM}')\n",
    "v,Q=numpy.linalg.eig(fM)\n",
    "#matplotlib.pyplot.imshow(Q.real)\n",
    "numpy.set_printoptions(suppress=False)\n",
    "print(Q[:,2:4])\n",
    "Q1=numpy.linalg.inv(Q)\n",
    "D=numpy.diag(v)\n",
    "#nearly 0\n",
    "#print(Q @ D @ Q1 - fM)\n",
    "t=numpy.linspace(0,100,101)\n",
    "fy=[model.u(x)[14] for x in t]\n",
    "print('{} {}'.format(len(fy),len(t)))\n",
    "matplotlib.pyplot.figure()\n",
    "matplotlib.pyplot.plot(fy)\n",
    "fu=model.u(0)\n",
    "print(Q1 @ fu)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 34,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "modelFile: /home/studen/temp/cDiazepam/model.json True\n",
      "parameterFile: /home/studen/temp/cDiazepam/parameters.json True\n"
     ]
    },
    {
     "data": {
      "image/png": "[encoded data, 430844 characters]\n",
      "text/plain": [
       "<Figure size 1500x2000 with 12 Axes>"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "i=0\n",
    "modelName='cDiazepam'\n",
    "model=getModel(solution,modelName)\n",
    "tscale=runSolver.getScale(solution[modelName]['setup'])\n",
    "setup=solution[modelName]['setup']\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",
    "#models['cDiazepamB']={'color':'blue','shadeColor':'orange'}\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
}
