{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "/usr/lib/python3/dist-packages/urllib3/connection.py:391: SubjectAltNameWarning: Certificate for merlin.fmf.uni-lj.si has no `subjectAltName`, falling back to check for a `commonName` for now. This feature is being removed by major browsers and deprecated by RFC 2818. (See https://github.com/urllib3/urllib3/issues/497 for details.)\n",
      "  warnings.warn(\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "User: andrej studen CSRF: 1a03f123c4c0ef7fdc5740ce155aaf0e\n"
     ]
    }
   ],
   "source": [
    "import sys\n",
    "import os\n",
    "import SimpleITK\n",
    "import numpy\n",
    "import matplotlib.pyplot\n",
    "sys.path.append(os.path.join(os.path.expanduser('~'),'software','src','nixSuite','wrapper'))\n",
    "import nixWrapper\n",
    "nixWrapper.loadLibrary('labkeyInterface')\n",
    "import labkeyInterface\n",
    "net=labkeyInterface.labkeyInterface()\n",
    "fconfig=os.path.join(os.path.expanduser('~'),'.labkey','network.json')\n",
    "net.init(fconfig)\n",
    "net.getCSRF()\n",
    "import labkeyFileBrowser\n",
    "sys.path.append(os.getcwd())\n",
    "import downloadPatient\n",
    "fb=labkeyFileBrowser.labkeyFileBrowser(net)\n",
    "project='dinamic_spect/Patients'\n",
    "locDir=os.path.join(os.path.expanduser('~'),'temp','dynamicSPECT')\n",
    "import labkeyDatabaseBrowser\n",
    "db=labkeyDatabaseBrowser.labkeyDB(net)\n",
    "ds=db.selectRows(project,'study','ImagingData',[])\n",
    "patients=list(set([row['PatientId'] for row in ds['rows']]))\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [],
   "source": [
    "#make polar plot\n",
    "def drawPolar(regionContent,scale):\n",
    "    cmap=matplotlib.pyplot.cm.viridis\n",
    "    #cmap=matplotlib.pyplot.cm.inferno\n",
    "    #cmap=matplotlib.pyplot.cm.magma\n",
    "    #cmap=matplotlib.pyplot.cm.plasma\n",
    "    #cmap=matplotlib.pyplot.cm.Reds\n",
    "    \n",
    "    N=4\n",
    "    r0=8\n",
    "    theta = numpy.linspace(0.0, 2 * numpy.pi, N, endpoint=False)\n",
    "    width = (2*numpy.pi) / N\n",
    "    radii = r0*numpy.ones(theta.size)\n",
    "    theta1 = numpy.linspace(0.0, 2 * numpy.pi, 1, endpoint=False)\n",
    "    width1 = (2*numpy.pi) / 1\n",
    "    radii1 = r0*numpy.ones(theta1.size)\n",
    "    ax = matplotlib.pyplot.subplot(111, polar=True)\n",
    "    barsOuter = ax.bar(theta, radii, width=width, bottom=2*r0)\n",
    "    barsInner = ax.bar(theta, radii, width=width, bottom=1*r0)\n",
    "    barsCenter = ax.bar(theta1, radii1, width=width1, bottom=0*r0)\n",
    "    for (r,b) in zip(regionContent[0:4],barsOuter):\n",
    "        b.set_facecolor(cmap(r*scale))\n",
    "    for (r,b) in zip(regionContent[4:8],barsInner):\n",
    "        b.set_facecolor(cmap(r*scale))\n",
    "    for (r,b) in zip(regionContent[8:9],barsCenter):\n",
    "        b.set_facecolor(cmap(r*scale))\n",
    "    ax.get_yaxis().set_visible(False)\n",
    "    return ax"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 46,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "User: andrej studen CSRF: 71974729a92d902434d7ddea345c421b\n"
     ]
    },
    {
     "data": {
      "image/png": "[encoded data, 30040 characters]\n",
      "text/plain": [
       "<Figure size 432x288 with 1 Axes>"
      ]
     },
     "metadata": {
      "needs_background": "light"
     },
     "output_type": "display_data"
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "User: andrej studen CSRF: c0d2c8d37846c63d731e8350b7b4a022\n"
     ]
    },
    {
     "data": {
      "image/png": "[encoded data, 29424 characters]\n",
      "text/plain": [
       "<Figure size 432x288 with 1 Axes>"
      ]
     },
     "metadata": {
      "needs_background": "light"
     },
     "output_type": "display_data"
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "User: andrej studen CSRF: 29e37e3b41751fc987b41df08b0e771b\n"
     ]
    },
    {
     "data": {
      "image/png": "[encoded data, 29276 characters]\n",
      "text/plain": [
       "<Figure size 432x288 with 1 Axes>"
      ]
     },
     "metadata": {
      "needs_background": "light"
     },
     "output_type": "display_data"
    }
   ],
   "source": [
    "patients1=[patients[5]]\n",
    "statVar='Mean'\n",
    "var='k1'\n",
    "vscale=2*60\n",
    "nclass=30\n",
    "classId={'variable':'nclass','value':str(nclass),'oper':'eq'}\n",
    "ds=db.selectRows(project,'study','ImagingData',[classId])\n",
    "rows=ds['rows']\n",
    "for p in patients1:\n",
    "    oDir=os.path.join(locDir,p)\n",
    "    oDirRemote=fb.buildPathURL(project,[p]);\n",
    "    if not os.path.isdir(oDir):\n",
    "        os.makedirs(oDir)\n",
    "        \n",
    "    rows=[row for row in ds['rows'] if row['PatientId']==p]\n",
    "    \n",
    "    scale=vscale\n",
    "        \n",
    "    regionContent=[row[var+'MIR'+statVar] for row in rows]\n",
    "    if var=='v19':\n",
    "        scale=1/numpy.max(regionContent)\n",
    "    ax=drawPolar(regionContent,scale)\n",
    "    ax.set_title('[{}] {} MIR {} ({})'.format(p,var,statVar,nclass),pad=20)\n",
    "    fname='{}MIR_{}_{}{}.png'.format(p,nclass,var,statVar)\n",
    "    matplotlib.pyplot.savefig(os.path.join(oDir,fname))\n",
    "    fb.writeFileToFile(os.path.join(oDir,fname),oDirRemote+'/'+fname)\n",
    "    matplotlib.pyplot.show()\n",
    "    \n",
    "    regionContent=[row[var+'OBR'+statVar] for row in rows]\n",
    "    if var=='v19':\n",
    "        scale=1/numpy.max(regionContent)\n",
    "    ax1=drawPolar(regionContent,scale)\n",
    "    ax1.set_title('[{}] {} OBR {} ({})'.format(p,var,statVar,nclass),pad=20)\n",
    "    fname='{}OBR_{}_{}{}.png'.format(p,nclass,var,statVar)\n",
    "    matplotlib.pyplot.savefig(os.path.join(oDir,fname))\n",
    "    fb.writeFileToFile(os.path.join(oDir,fname),oDirRemote+'/'+fname)\n",
    "    matplotlib.pyplot.show()\n",
    "    \n",
    "    if var!='k1':\n",
    "        continue\n",
    "    regionContent=[row[var+'OBR'+statVar]/row[var+'MIR'+statVar] for row in rows]\n",
    "    #regionContent=[row['k1Ratio'+statVar] for row in rows]\n",
    "    \n",
    "    ax1=drawPolar(regionContent,0.25)\n",
    "    ax1.set_title('[{}] k1 {} Ratio ({})'.format(p, statVar,nclass),pad=20)\n",
    "    fname='{}_{}_k1Ratio{}.png'.format(p,nclass,statVar)\n",
    "    matplotlib.pyplot.savefig(os.path.join(oDir,fname))\n",
    "    fb.writeFileToFile(os.path.join(oDir,fname),oDirRemote+'/'+fname)\n",
    "    matplotlib.pyplot.show()\n",
    "    \n",
    "    "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 28,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "{'7TM': ['7TMMIR', '7TMOBR'], '10KF': ['10KFMIR', '10KFOBR'], '5MI': ['5MIMIR', '5MIOBR'], '3ZF': ['3ZFMIR', '3ZFOBR'], '11ZM': ['11ZMMIR', '11ZMOBR'], '2SB': ['2SBMIR', '2SMobr']}\n"
     ]
    }
   ],
   "source": [
    "pairs={}\n",
    "for p in patients:\n",
    "    idFilter={'variable':'PatientId','value':p,'oper':'eq'}\n",
    "    ds=db.selectRows(project,'study','Imaging',[idFilter])\n",
    "    pairs[p]=[r['aliasID'] for r in ds['rows']]\n",
    "print(pairs)\n",
    "    "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 44,
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "/usr/lib/python3/dist-packages/urllib3/connection.py:391: SubjectAltNameWarning: Certificate for merlin.fmf.uni-lj.si has no `subjectAltName`, falling back to check for a `commonName` for now. This feature is being removed by major browsers and deprecated by RFC 2818. (See https://github.com/urllib3/urllib3/issues/497 for details.)\n",
      "  warnings.warn(\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "{'7TM': ['7TMMIR', '7TMOBR'], '10KF': ['10KFMIR', '10KFOBR'], '5MI': ['5MIMIR', '5MIOBR'], '3ZF': ['3ZFMIR', '3ZFOBR'], '11ZM': ['11ZMMIR', '11ZMOBR'], '2SB': ['2SBMIR', '2SMobr']}\n"
     ]
    },
    {
     "data": {
      "image/png": "[encoded data, 132196 characters]\n",
      "text/plain": [
       "<Figure size 1440x720 with 6 Axes>"
      ]
     },
     "metadata": {
      "needs_background": "light"
     },
     "output_type": "display_data"
    }
   ],
   "source": [
    "pairs={}\n",
    "for p in patients:\n",
    "    idFilter={'variable':'PatientId','value':p,'oper':'eq'}\n",
    "    ds=db.selectRows(project,'study','Imaging',[idFilter])\n",
    "    pairs[p]=[r['aliasID'] for r in ds['rows']]\n",
    "print(pairs)\n",
    "    \n",
    "s2=1.0\n",
    "fig, ax = matplotlib.pyplot.subplots(1,6,figsize=(20,10),subplot_kw={'projection': 'polar'})\n",
    "i=0    \n",
    "for pt in pairs:\n",
    "    for p in pairs[pt]:\n",
    "        idFilter={'variable':'aliasID','value':p,'oper':'eq'}\n",
    "        sigmaFilter={'variable':'sigma2','value':str(s2),'oper':'eq'}\n",
    "        typeFilter={'variable':'option','value':'D','oper':'eq'}\n",
    "        ds=db.selectRows(project,'study','Summary',[idFilter,sigmaFilter,typeFilter])\n",
    "        nr=len(ds['rows'])\n",
    "        k1=numpy.zeros(nr)\n",
    "        for r in ds['rows']:\n",
    "            k1[int(r['regionId'])]=60*r['mean']\n",
    "        if k1[0]>0.8:\n",
    "            k1[0]=0\n",
    "        theta1 = numpy.linspace(0.0, 2 * numpy.pi, nr, endpoint=False)\n",
    "        ax[i].plot(theta1,k1)\n",
    "        ax[i].set_rmax(0.8)\n",
    "        ax[i].text(0.5*numpy.pi,0.65,pt,fontsize='large')\n",
    "        #print(k1)\n",
    "    i+=1\n",
    "matplotlib.pyplot.show()\n",
    "\n",
    "    "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "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.8.5"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 4
}
