{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 28,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "loadLibrary\n",
      "remoteSourcesURL https://git0.fmf.uni-lj.si/studen/nixSuite/raw/master/remoteResources/resources.json\n",
      "{'labkeyInterface': {'url': 'https://git0.fmf.uni-lj.si/studen/labkeyInterface/archive/master.zip', 'branch': 'master', 'modules': []}, 'irAEMM': {'url': 'https://git0.fmf.uni-lj.si/studen/iraemm/archive/master.zip', 'branch': 'master', 'modules': ['iraemmBrowser']}, 'SlicerLabkeyExtension': {'url': 'https://git0.fmf.uni-lj.si/studen/SlicerLabkeyExtension/archive/SlicerExtensionIndex.zip', 'branch': 'SlicerExtensionIndex', 'modules': ['labkeyBrowser']}, 'limfomiPET': {'url': 'https://git0.fmf.uni-lj.si/studen/limfomiPET/archive/master.zip', 'branch': 'master', 'modules': ['imageBrowser', 'segmentationBrowser']}, 'parseConfig': {'url': 'https://git0.fmf.uni-lj.si/studen/parseConfig/archive/master.zip', 'branch': 'master', 'modules': []}, 'orthancInterface': {'url': 'https://git0.fmf.uni-lj.si/studen/orthancInterface/archive/master.zip', 'branch': 'master', 'modules': []}}\n",
      "{'url': 'https://git0.fmf.uni-lj.si/studen/labkeyInterface/archive/master.zip', 'branch': 'master', 'modules': []}\n",
      "File  /home/studen/temp/labkeyInterface.zip: True\n"
     ]
    }
   ],
   "source": [
    "import sys\n",
    "import os\n",
    "import SimpleITK\n",
    "import numpy\n",
    "import matplotlib.pyplot\n",
    "import subprocess\n",
    "import json\n",
    "import config\n",
    "import getData\n",
    "import segmentation\n",
    "import importlib\n",
    "importlib.reload(segmentation)\n",
    "\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",
    "import labkeyFileBrowser\n",
    "import labkeyDatabaseBrowser\n",
    "\n",
    "#manipulate segmentations\n",
    "#rewrite this\n",
    "#nim=getPatientNIM(pId)\n",
    "\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "User: andrej studen CSRF: e94f23e7501ad232073d2f15b2b9fa99\n"
     ]
    }
   ],
   "source": [
    "#\n",
    "\n",
    "fsetup='../template/cardiacSPECT.json'\n",
    "with open(fsetup,'r') as f:\n",
    "    setup=json.load(f)\n",
    "    \n",
    "net=labkeyInterface.labkeyInterface()\n",
    "fconfig=os.path.join(os.path.expanduser('~'),'.labkey',setup['network'])\n",
    "net.init(fconfig)\n",
    "net.getCSRF()\n",
    "db=labkeyDatabaseBrowser.labkeyDB(net)\n",
    "fb=labkeyFileBrowser.labkeyFileBrowser(net)\n",
    "#rewrite this\n",
    "#nim=getPatientNIM(pId)\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 29,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "['0', '1', '2']\n",
      "{'0': [[32, 31, 31], [32, 31, 27], [32, 31, 35]], '1': [[32, 31, 31], [32, 27, 31], [32, 35, 31]], '2': [[32, 31, 31], [32, 31, 27], [32, 31, 35], [32, 27, 31], [32, 35, 31]]}\n",
      "{'0': '0;1;2', '1': '0;2', '2': '0;2', '3': '1;2', '4': '1;2'}\n",
      "User: andrej studen CSRF: 0a2d1813fd7ad785feb121c516a8c908\n",
      "User: andrej studen CSRF: 539c6a69b64efcbabcf84c1d74393d22\n",
      "User: andrej studen CSRF: dee212c676c920c6ad16eec86f918b3d\n",
      "User: andrej studen CSRF: ece858aaad9e8bef81ef8ebed6ee1971\n",
      "User: andrej studen CSRF: 329441e5b96393f3df9b31ddf76ee043\n",
      "Done\n"
     ]
    }
   ],
   "source": [
    "def plotPoints(db,setup,pId='MM',visitName='MIR'):    \n",
    "    cx={}\n",
    "    cx[pId]=[32,31,31]\n",
    "    #pId='pred15052022'\n",
    "    #cx[pId]=[30,32,31]\n",
    "    #order\n",
    "    #[green,blue,red]\n",
    "\n",
    "    fp={'0':[],'1':[],'2':[]}\n",
    "\n",
    "    idFilter={'variable':'PatientId','value':pId,'oper':'eq'}\n",
    "    visitFilter={'variable':'visitName','value':visitName,'oper':'eq'}\n",
    "\n",
    "    rows=getData.getPatients(db,setup,[idFilter,visitFilter])\n",
    "\n",
    "    r=rows[0]\n",
    "    #nim=segmentation.getPatientNIM(r,setup)\n",
    "    #i labels segments\n",
    "    #ns=16\n",
    "    #for i in numpy.arange(ns):\n",
    "    #    sNum=r['SequenceNum']+0.0100*i\n",
    "    #seqFilter={'variable':'SequenceNum','value':'{:.2f}'.format(sNum),'oper':'eq'}\n",
    "    rows=getData.getSegmentation(db,setup,[idFilter,visitFilter])\n",
    "\n",
    "    #if len(rows)==0:\n",
    "    if True:\n",
    "        print('Not found for id={}/{}'.format(pId,visitName))\n",
    "        fp=segmentation.guessPixelPosition15(*cx[pId])\n",
    "    else:\n",
    "        for q in rows:\n",
    "            #print(q)\n",
    "            slices=q['sliceId'].split(';')\n",
    "            for s in slices:\n",
    "                fp[s].append([float(x) for x in [q['x'],q['y'],q['z']]])\n",
    "            #first point is (sx,sy,sz)\n",
    "    return \n",
    "    oz=0\n",
    "    rz=4\n",
    "    #update last 6 points \n",
    "    sx=fp['0'][0][0]\n",
    "    sy=fp['0'][0][1]\n",
    "    sz=fp['0'][0][2]\n",
    "    slc=[int(x) for x in fp['0'][0]]\n",
    "    #print('Center ({})'.format(slc))\n",
    "\n",
    "    cut0=20\n",
    "    w0=20\n",
    "    cut1=20\n",
    "    w1=20\n",
    "    cut2=20\n",
    "    w2=20\n",
    "    vmax=1000\n",
    "    vmin=0\n",
    "    nd=3\n",
    "    fig,ax=matplotlib.pyplot.subplots(3,2*nd+1,figsize=(20,12))\n",
    "    for i in numpy.arange(0,2*nd+1):\n",
    "        ax[0,i].imshow(nim[cut2:cut2+w2,slc[1]-nd+i,cut0:cut0+w0],cmap='gray_r',vmax=vmax,vmin=vmin)\n",
    "        ax[1,i].imshow(nim[cut2:cut2+w2,cut0:cut0+w0,slc[2]-nd+i].T,cmap='gray_r',vmax=vmax,vmin=vmin)\n",
    "        ax[2,i].imshow(nim[slc[0]-nd+i,cut1:cut1+w1,cut1:cut1+w1],cmap='gray_r',vmax=vmax,vmin=vmin)\n",
    "        if i==nd:\n",
    "            pt=fp['0']\n",
    "            ax[0,i].scatter([x[2]-cut0 for x in pt],[x[0]-cut2 for x in pt])\n",
    "            pt=fp['1']\n",
    "            ax[1,i].scatter([x[0]-cut2 for x in pt],[x[1]-cut0 for x in pt])\n",
    "            pt=fp['2']\n",
    "            ax[2,i].scatter([x[2]-cut1 for x in pt],[x[1]-cut1 for x in pt])\n",
    "\n",
    "        if i==0:\n",
    "            ax[0,i].text(2,2,pId,fontsize='large')\n",
    "          \n",
    "def guessSegmentation(db,setup,pId='MM',visitName='MIR'):    \n",
    "   idFilter={'variable':'PatientId','value':pId,'oper':'eq'}\n",
    "   visitFilter={'variable':'visitName','value':visitName,'oper':'eq'}  \n",
    "   rows=getData.getPatients(db,setup,[idFilter,visitFilter])\n",
    "   r=rows[0] \n",
    "   pixels=segmentation.guessPixelPosition4() \n",
    "   segmentation.updateSegmentation(db,setup,r,pixels)\n",
    "\n",
    "guessSegmentation(db,setup)     "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "#rarely used. Mostly, segmentation points are edited in LabKey\n",
    "rows=getData.getPatients(db,setup)\n",
    "for r in rows:\n",
    "    print('******{}******'.format(config.getCode(r,setup)))\n",
    "    segmentation.writeSegmentation(db,r,setup)"
   ]
  }
 ],
 "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
}
