{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 5,
   "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 os\n",
    "import sys\n",
    "os.path.expanduser('~')\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 labkeyDatabaseBrowser\n",
    "import labkeyFileBrowser\n",
    "#local files\n",
    "import downloadPatient\n",
    "\n",
    "def connect(server,f):\n",
    "    net=labkeyInterface.labkeyInterface()\n",
    "    fconfig=os.path.join(os.path.expanduser('~'),'.labkey','{}.json'.format(server))\n",
    "    net.init(fconfig)\n",
    "    net.getCSRF()\n",
    "    return f(net)\n",
    "\n",
    "def connectDB(server):\n",
    "    return connect(server,labkeyDatabaseBrowser.labkeyDB)\n",
    "\n",
    "def connectFB(server):\n",
    "    return connect(server,labkeyFileBrowser.labkeyFileBrowser)\n",
    "\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "User: andrej studen CSRF: 46851818c35cf1d4b585917ae2c6f635\n",
      "User: andrej studen CSRF: b7db61cfb531e7ccc9b334d169e7de4c\n",
      "['10KFMIR', '10KFOBR', '11ZMMIR', '11ZMOBR', '2SBMIR', '2SMobr', '3ZFMIR', '3ZFOBR', '5MIMIR', '5MIOBR', '7TMMIR', '7TMOBR', '8JSMIR', '8JSOBR']\n"
     ]
    }
   ],
   "source": [
    "fb=connectFB('merlin')\n",
    "db=connectDB('merlin')\n",
    "project='dinamic_spect/Patients'\n",
    "ds=db.selectRows(project,'study','Imaging',[])\n",
    "patients=[row['aliasID'] for row in ds['rows']]\n",
    "print(patients)\n",
    "\n",
    "\n",
    "locDir=os.path.join(os.path.expanduser('~'),'temp','dynamicSPECT')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {},
   "outputs": [],
   "source": [
    "#download files\n",
    "import labkeyDatabaseBrowser\n",
    "db=labkeyDatabaseBrowser.labkeyDB(net)\n",
    "ds=db.selectRows(project,'study','Imaging',[])\n",
    "patients=[row['aliasID'] for row in ds['rows']]\n",
    "patients1=['7TMOBR']\n",
    "for p in patients1:\n",
    "    pass\n",
    "\n",
    "    #patientId='7TMMIR'\n",
    "    #files=downloadPatient.readPatient(fb,locDir,project,p)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {},
   "outputs": [],
   "source": [
    "import SimpleITK\n",
    "import matplotlib.pyplot\n",
    "import numpy"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "metadata": {},
   "outputs": [],
   "source": [
    "def getPatientNIM(id):\n",
    "    f=os.path.join(locDir,id,id+'Volume19.nrrd')\n",
    "    im=SimpleITK.ReadImage(f)\n",
    "    nim=SimpleITK.GetArrayFromImage(im)\n",
    "    return nim\n",
    "    "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 888,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "2SBMIR: [28]:160521.0 0.3870876729488373\n"
     ]
    },
    {
     "data": {
      "image/png": "[encoded data, 10936 characters]\n",
      "text/plain": [
       "<Figure size 432x288 with 1 Axes>"
      ]
     },
     "metadata": {
      "needs_background": "light"
     },
     "output_type": "display_data"
    }
   ],
   "source": [
    "patients1=[patients[4]]\n",
    "for p in patients1:\n",
    "    if p.find('8')==0:\n",
    "        continue\n",
    "    f=os.path.join(locDir,p,p+'Volume19.nrrd')\n",
    "    im=SimpleITK.ReadImage(f)\n",
    "    nim=SimpleITK.GetArrayFromImage(im)\n",
    "    pz=list(numpy.sum(numpy.sum(nim,0),1))\n",
    "    pz1=[pz[i-1]+pz[i+1]-2*pz[i] for i in numpy.arange(1,len(pz)-1)]\n",
    "    imin=pz1.index(min(pz1))\n",
    "    imax=pz.index(max(pz))\n",
    "    imin-=9\n",
    "    print('{}: [{}]:{} {}'.format(p,imin,pz[imin],pz[imin]/pz[imax]))\n",
    "    matplotlib.pyplot.plot(pz)\n",
    "    matplotlib.pyplot.scatter(imin,pz[imin])\n",
    "    \n",
    "matplotlib.pyplot.show()\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 257,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "image/png": "[encoded data, 9224 characters]\n",
      "text/plain": [
       "<Figure size 432x288 with 1 Axes>"
      ]
     },
     "metadata": {
      "needs_background": "light"
     },
     "output_type": "display_data"
    }
   ],
   "source": [
    "matplotlib.pyplot.imshow(nim[:,31,:])\n",
    "matplotlib.pyplot.show()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "metadata": {},
   "outputs": [],
   "source": [
    "def getSegment(nim,tip,base,w1,w2):\n",
    "    ctr=base+1/3.*(tip-base)\n",
    "    kap=base+2/3.*(tip-base)\n",
    "    n=(tip-base)/numpy.sqrt(numpy.dot(tip-base,tip-base))\n",
    "    sphCtr=tip-w2*n;\n",
    "    print(n)\n",
    "    x,y,z=numpy.meshgrid(numpy.arange(nim.shape[0])+0.5,numpy.arange(nim.shape[1])+0.5,numpy.arange(nim.shape[2])+0.5,indexing='xy')\n",
    "    #because of xy ordering, columns 2 and 1 are swapped, but that seems to fit well with reshape\n",
    "    #location coded as (r)\n",
    "    fr=numpy.array([x,y,z])\n",
    "    fr1=fr.transpose()\n",
    "    fr2=fr1.reshape(nim.size,-1)\n",
    "    print(fr2.shape)\n",
    "    #require r to lie above the r*n plane\n",
    "    fw=numpy.dot(fr2,n)\n",
    "    fw=fw.reshape(x.shape)\n",
    "    print(fw.shape)\n",
    "    fwkap=numpy.dot(kap,n)\n",
    "    fwctr=numpy.dot(ctr,n)\n",
    "    fwbase=numpy.dot(base,n)\n",
    "    \n",
    "    fcSph=numpy.array([sphCtr[0]*numpy.ones(x.shape),sphCtr[1]*numpy.ones(x.shape),sphCtr[2]*numpy.ones(x.shape)])\n",
    "    fcSph1=fcSph.transpose()\n",
    "    fcSph2=fcSph1.reshape((nim.size,-1))\n",
    "    vcSph=numpy.array([numpy.dot(v1-v2,v1-v2) for (v1,v2) in zip(fcSph2,fr2)])\n",
    "    vcSph2=vcSph.reshape(x.shape)\n",
    "    \n",
    "    fc=numpy.array([ctr[0]*numpy.ones(x.shape),ctr[1]*numpy.ones(x.shape),ctr[2]*numpy.ones(x.shape)])\n",
    "    fc1=fc.transpose()\n",
    "    fc2=fc1.reshape((nim.size,-1))\n",
    "    vc=numpy.array([numpy.dot(v1-v2,v1-v2) for (v1,v2) in zip(fc2,fr2)])\n",
    "    print('vc shape {}'.format(vc.shape))\n",
    "    vc2=vc.reshape(x.shape)\n",
    "    vcrho2=numpy.array([numpy.dot(v1-v2,n)*numpy.dot(v1-v2,n) for (v1,v2) in zip(fc2,fr2)])\n",
    "    vcrho2Flat=vc-vcrho2\n",
    "    print(len(vcrho2Flat[vcrho2Flat<0]))\n",
    "    vcrho2=vcrho2.reshape(x.shape)\n",
    "    vcrho2=vc2-vcrho2\n",
    "\n",
    "    vcsqrt=numpy.sqrt(vcrho2Flat)\n",
    "    print(len(vcsqrt[vcsqrt==0]))\n",
    "    tgphi2=numpy.array([(v1[2]-v2[2]) for (v1,v2) in zip(fr2,fc2)])\n",
    "    tgphi2[vcsqrt>0]/=vcsqrt[vcsqrt>0]\n",
    "    tgphi2=tgphi2.reshape(x.shape)\n",
    "    tgphi1=numpy.array([(v1[1]-v2[1]) for (v1,v2) in zip(fr2,fc2)])\n",
    "    tgphi1[vcsqrt>0]/=vcsqrt[vcsqrt>0]\n",
    "    tgphi1=tgphi1.reshape(x.shape)\n",
    "    print('Shape (tgphi):{}'.format(tgphi1.shape))\n",
    "    \n",
    "    cap=9*numpy.ones(x.shape)\n",
    "    cap[vcSph2<w1*w1]=0\n",
    "    cap[vcSph2>w2*w2]=0\n",
    "    cap[fw<fwkap]=0\n",
    "    \n",
    "    bar1=numpy.ones(x.shape)\n",
    "    bar1[vcrho2>w2*w2]=0\n",
    "    bar1[vcrho2<w1*w1]=0\n",
    "    bar1[fw<fwctr]=0\n",
    "    bar1[fw>fwkap]=0\n",
    "    bar1[tgphi2>numpy.sqrt(2)/2]*=4\n",
    "    bar1[tgphi2<-numpy.sqrt(2)/2]*=2\n",
    "    bar1[tgphi1>numpy.sqrt(2)/2]*=3\n",
    "    bar1[tgphi1<-numpy.sqrt(2)/2]*=1\n",
    "    bar1[bar1>0]+=4\n",
    "\n",
    "    bar2=numpy.ones(x.shape)\n",
    "    bar2[vcrho2>w2*w2]=0\n",
    "    bar2[vcrho2<w1*w1]=0\n",
    "    bar2[fw>fwctr]=0\n",
    "    bar2[fw<fwbase]=0\n",
    "    bar2[tgphi2>numpy.sqrt(2)/2]*=4\n",
    "    bar2[tgphi2<-numpy.sqrt(2)/2]*=2\n",
    "    bar2[tgphi1>numpy.sqrt(2)/2]*=3\n",
    "    bar2[tgphi1<-numpy.sqrt(2)/2]*=1\n",
    "\n",
    "    segm=bar1\\\n",
    "        +cap\\\n",
    "        +bar2\\\n",
    "    #transpose back to nim space (equivalent to ij indexing order)\n",
    "    vc2=numpy.transpose(vc2,axes=[1,0,2])\n",
    "    segm=numpy.transpose(segm,axes=[1,0,2])\n",
    "    return segm\n",
    "\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 987,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[-1.  0.  0.]\n",
      "(114688, 3)\n",
      "(64, 28, 64)\n",
      "vc shape (114688,)\n",
      "0\n",
      "0\n",
      "Shape (tgphi):(64, 28, 64)\n"
     ]
    },
    {
     "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: 7cefbfa156cf7df98b848d539c3da76e\n",
      "User: andrej studen CSRF: 5d36f73137830665383bdf7cfd5f49b1\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "b'{\\n  \"rowsAffected\" : 1,\\n  \"queryName\" : \"Imaging\",\\n  \"schemaName\" : \"study\",\\n  \"containerPath\" : \"/dinamic_spect/Patients\",\\n  \"rows\" : [ {\\n    \"date\" : null,\\n    \"dsrowid\" : 112,\\n    \"CreatedBy\" : 1090,\\n    \"sliceView\" : \"5MIMIR_sliceView.png\",\\n    \"tipY\" : 32.0,\\n    \"tipZ\" : 32.5,\\n    \"ctData\" : \"2\",\\n    \"QCState\" : null,\\n    \"tipX\" : 6.0,\\n    \"SequenceNum\" : 1.0000,\\n    \"Created\" : \"2019/07/11 12:02:39\",\\n    \"lsid\" : \"urn:lsid:ijs.si:Study.Data-113:5001.5MI.1.0000\",\\n    \"CT\" : \"5MIMIRCT.nrrd\",\\n    \"baseX\" : 18.0,\\n    \"aliasID\" : \"5MIMIR\",\\n    \"sourcelsid\" : null,\\n    \"nmCorrData\" : \"9\",\\n    \"PatientId\" : \"5MI\",\\n    \"segmentation\" : \"5MIMIR_Segm.nrrd\",\\n    \"baseY\" : 32.0,\\n    \"w1\" : 2.0,\\n    \"nmMaster\" : \"4\",\\n    \"w2\" : 6.0,\\n    \"baseZ\" : 32.5\\n  } ],\\n  \"command\" : \"update\"\\n}'"
      ]
     },
     "execution_count": 987,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "pId='5MIMIR'\n",
    "idFilter={'variable':'aliasID','value':pId,'oper':'eq'}\n",
    "ds=db.selectRows(project,'study','Imaging',[idFilter])\n",
    "rows=ds['rows']\n",
    "outrows=[]\n",
    "for r in rows:\n",
    "    p=r['aliasID']\n",
    "    if p.find('8')==0:\n",
    "        continue\n",
    "    f=os.path.join(locDir,p,p+'Volume19.nrrd')\n",
    "    im=SimpleITK.ReadImage(f)\n",
    "    nim=SimpleITK.GetArrayFromImage(im)\n",
    "    tip=numpy.array([float(r[x]) for x in ['tipX','tipY','tipZ']])\n",
    "    base=numpy.array([float(r[x]) for x in ['baseX','baseY','baseZ']])\n",
    "    segm=getSegment(nim,tip,base,float(r['w1']),float(r['w2']))\n",
    "    #adjust file name\n",
    "    outDir=os.path.join(locDir,p)\n",
    "    if not os.path.isdir(outDir):\n",
    "        os.makedirs(outDir)\n",
    "    segmImage=SimpleITK.GetImageFromArray(segm)\n",
    "    segmImage.SetOrigin(im.GetOrigin())\n",
    "    segmImage.SetDirection(im.GetDirection())\n",
    "    segmImage.SetSpacing(im.GetSpacing())\n",
    "    fname=p+'_Segm.nrrd'\n",
    "    SimpleITK.WriteImage(segmImage,os.path.join(locDir,p,fname))\n",
    "    r['segmentation']=fname\n",
    "    r['CT']=p+'CT.nrrd'\n",
    "    outrows.append(r)\n",
    "    remoteSegmentation=fb.buildPathURL(project,[p])\n",
    "    remoteSegmentation+='/'+fname\n",
    "    fb.writeFileToFile(os.path.join(locDir,p,fname),remoteSegmentation)\n",
    "db.modifyRows('update',project,'study','Imaging',outrows)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "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"
     ]
    },
    {
     "ename": "NameError",
     "evalue": "name 'getSegment' is not defined",
     "output_type": "error",
     "traceback": [
      "\u001b[0;31m---------------------------------------------------------------------------\u001b[0m",
      "\u001b[0;31mNameError\u001b[0m                                 Traceback (most recent call last)",
      "\u001b[0;32m<ipython-input-7-a3a104143944>\u001b[0m in \u001b[0;36m<module>\u001b[0;34m\u001b[0m\n\u001b[1;32m      7\u001b[0m \u001b[0mtip\u001b[0m\u001b[0;34m=\u001b[0m\u001b[0mnumpy\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0marray\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m[\u001b[0m\u001b[0mfloat\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mr\u001b[0m\u001b[0;34m[\u001b[0m\u001b[0mx\u001b[0m\u001b[0;34m]\u001b[0m\u001b[0;34m)\u001b[0m \u001b[0;32mfor\u001b[0m \u001b[0mx\u001b[0m \u001b[0;32min\u001b[0m \u001b[0;34m[\u001b[0m\u001b[0;34m'tipX'\u001b[0m\u001b[0;34m,\u001b[0m\u001b[0;34m'tipY'\u001b[0m\u001b[0;34m,\u001b[0m\u001b[0;34m'tipZ'\u001b[0m\u001b[0;34m]\u001b[0m\u001b[0;34m]\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m      8\u001b[0m \u001b[0mbase\u001b[0m\u001b[0;34m=\u001b[0m\u001b[0mnumpy\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0marray\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m[\u001b[0m\u001b[0mfloat\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mr\u001b[0m\u001b[0;34m[\u001b[0m\u001b[0mx\u001b[0m\u001b[0;34m]\u001b[0m\u001b[0;34m)\u001b[0m \u001b[0;32mfor\u001b[0m \u001b[0mx\u001b[0m \u001b[0;32min\u001b[0m \u001b[0;34m[\u001b[0m\u001b[0;34m'baseX'\u001b[0m\u001b[0;34m,\u001b[0m\u001b[0;34m'baseY'\u001b[0m\u001b[0;34m,\u001b[0m\u001b[0;34m'baseZ'\u001b[0m\u001b[0;34m]\u001b[0m\u001b[0;34m]\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m----> 9\u001b[0;31m \u001b[0msegm\u001b[0m\u001b[0;34m=\u001b[0m\u001b[0mgetSegment\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mnim\u001b[0m\u001b[0;34m,\u001b[0m\u001b[0mtip\u001b[0m\u001b[0;34m,\u001b[0m\u001b[0mbase\u001b[0m\u001b[0;34m,\u001b[0m\u001b[0mfloat\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mr\u001b[0m\u001b[0;34m[\u001b[0m\u001b[0;34m'w1'\u001b[0m\u001b[0;34m]\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m,\u001b[0m\u001b[0mfloat\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mr\u001b[0m\u001b[0;34m[\u001b[0m\u001b[0;34m'w2'\u001b[0m\u001b[0;34m]\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m\u001b[1;32m     10\u001b[0m \u001b[0mslc\u001b[0m\u001b[0;34m=\u001b[0m\u001b[0;36m32\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m     11\u001b[0m \u001b[0mmatplotlib\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mpyplot\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mimshow\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0msegm\u001b[0m\u001b[0;34m[\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;34m,\u001b[0m\u001b[0mslc\u001b[0m\u001b[0;34m,\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;34m]\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n",
      "\u001b[0;31mNameError\u001b[0m: name 'getSegment' is not defined"
     ]
    }
   ],
   "source": [
    "#test a segmentation\n",
    "pId='5MIMIR'\n",
    "nim=getPatientNIM(pId)\n",
    "idFilter={'variable':'aliasID','value':pId,'oper':'eq'}\n",
    "ds=db.selectRows(project,'study','Imaging',[idFilter])\n",
    "r=[row for row in ds['rows'] if row['aliasID']==pId][0]\n",
    "tip=numpy.array([float(r[x]) for x in ['tipX','tipY','tipZ']])\n",
    "base=numpy.array([float(r[x]) for x in ['baseX','baseY','baseZ']])\n",
    "segm=getSegment(nim,tip,base,float(r['w1']),float(r['w2']))\n",
    "slc=32\n",
    "matplotlib.pyplot.imshow(segm[:,slc,:])\n",
    "matplotlib.pyplot.show()\n",
    "matplotlib.pyplot.imshow(segm[:,slc,:])\n",
    "matplotlib.pyplot.show()\n",
    "matplotlib.pyplot.imshow(nim[:,slc,:])\n",
    "matplotlib.pyplot.show()\n",
    "matplotlib.pyplot.imshow(nim[:,slc,:])\n",
    "matplotlib.pyplot.imshow(segm[:,slc,:],alpha=0.2)\n",
    "matplotlib.pyplot.show()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 151,
   "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": [
      "16\n",
      "User: andrej studen CSRF: b2c5deaab50bbf312e803a4cb3ef654e\n",
      "User: andrej studen CSRF: 257a1acd17787f893ba19e2cf7e4dece\n",
      "User: andrej studen CSRF: cfa94419791e6d319f39db3b13dce0e8\n",
      "User: andrej studen CSRF: 9d1d2f1e76553c26eebf4a9a7e899894\n",
      "User: andrej studen CSRF: e7120ad92526021212ce0b35a7d8cc5d\n",
      "User: andrej studen CSRF: ba551108b45a9b4265a90ea84293ddb8\n",
      "User: andrej studen CSRF: ad3ce0403b63f901b140bf6b0e0170bd\n",
      "User: andrej studen CSRF: 1aaa66797a94a9d2e367ecb246c380db\n",
      "User: andrej studen CSRF: 8f9253891755ab14c876b8410f359da7\n",
      "User: andrej studen CSRF: 5507dd1a79c30bb4d0c658cffdac8b4a\n",
      "User: andrej studen CSRF: d9a4fa48be3393f3e6af67b74c0cfe1a\n",
      "User: andrej studen CSRF: 94c79b240b55d4d4241de6c63af139e5\n",
      "User: andrej studen CSRF: 631565d37ef0465a614d56c1566fa652\n",
      "User: andrej studen CSRF: 364c4c95011879d23cba730802820615\n",
      "User: andrej studen CSRF: be4a3a5941458ae25a28213cb92cdf53\n",
      "User: andrej studen CSRF: c564a5e90bb291a3f4559426b636eaa0\n"
     ]
    },
    {
     "data": {
      "image/png": "[encoded data, 52464 characters]\n",
      "text/plain": [
       "<Figure size 1440x864 with 27 Axes>"
      ]
     },
     "metadata": {
      "needs_background": "light"
     },
     "output_type": "display_data"
    }
   ],
   "source": [
    "#manipulate segmentations\n",
    "pId='7TMOBR'\n",
    "save=True\n",
    "nim=getPatientNIM(pId)\n",
    "idFilter={'variable':'aliasID','value':pId,'oper':'eq'}\n",
    "ds=db.selectRows(project,'study','Imaging',[idFilter])\n",
    "r=[row for row in ds['rows'] if row['aliasID']==pId][0]\n",
    "tip=numpy.array([float(r[x]) for x in ['tipX','tipY','tipZ']])\n",
    "base=numpy.array([float(r[x]) for x in ['baseX','baseY','baseZ']])\n",
    "#segm=getSegment(nim,tip,base,float(r['w1']),float(r['w2']))\n",
    "\n",
    "fp=[]\n",
    "for i in numpy.arange(16):\n",
    "    sNum=r['SequenceNum']+0.0100*i\n",
    "    seqFilter={'variable':'SequenceNum','value':'{:.2f}'.format(sNum),'oper':'eq'}\n",
    "    ds=db.selectRows(project,'study','Segmentation',[idFilter,seqFilter])\n",
    "    \n",
    "    if len(ds['rows'])==0:\n",
    "        print('Not found for s={}'.format(sNum))\n",
    "        sx=12\n",
    "        sy=28\n",
    "        sz=32\n",
    "        rz=4\n",
    "        oz=0\n",
    "\n",
    "        slc=[sx,sy,sz]\n",
    "        p1=[sx,sy,sz]\n",
    "\n",
    "        #tip\n",
    "        p2=[7,sy,32]\n",
    "        p3=[10,sy,sz-rz]\n",
    "        p5=[15,sy,sz-rz]\n",
    "        p4=[10,sy,sz+rz-1]\n",
    "        p6=[15,sy,sz+rz]\n",
    "        \n",
    "        p7=[11,sy-rz,sz]\n",
    "        p8=[11,sy+rz-1,sz]\n",
    "        p9=[15,sy-rz,sz]\n",
    "        p10=[15,sy+rz,sz]\n",
    "\n",
    "        p11=[sx,sy+rz+oz,sz]\n",
    "        p12=[sx,sy+0.3*rz+oz,sz-rz]\n",
    "        p13=[sx,sy-0.3*rz+oz,sz-rz]\n",
    "        p14=[sx,sy-rz+oz,sz]\n",
    "        p15=[sx,sy-0.3*rz+oz,sz+rz]\n",
    "        p16=[sx,sy+0.3*rz+oz,sz+rz]\n",
    "        break\n",
    "    else:\n",
    "        frow=ds['rows'][0]\n",
    "        fp.append([float(x) for x in [frow['x'],frow['y'],frow['z']]])\n",
    "        fpp=fp[-1]\n",
    "        if i==0:\n",
    "            sx=int(fpp[0])\n",
    "            sy=int(fpp[1])\n",
    "            sz=int(fpp[2])\n",
    "\n",
    "if len(fp)>0:\n",
    "    print(len(fp))\n",
    "    p1=fp[0]\n",
    "    p2=fp[1]\n",
    "    p3=fp[2]\n",
    "    p4=fp[3]\n",
    "    p5=fp[4]\n",
    "    p6=fp[5]\n",
    "    p7=fp[6]\n",
    "    p8=fp[7]\n",
    "    p9=fp[8]\n",
    "    p10=fp[9]\n",
    "    p11=fp[10]\n",
    "    p12=fp[11]\n",
    "    p13=fp[12]\n",
    "    p14=fp[13]\n",
    "    p15=fp[14]\n",
    "    p16=fp[15]\n",
    "\n",
    "oz=0\n",
    "\n",
    "#sy+=2\n",
    "#sx+=1\n",
    "#sz+=2\n",
    "#rz=4\n",
    "\n",
    "slc=[sx,sy,sz]\n",
    "p1=[sx,sy,sz]\n",
    "\n",
    "p11=[sx,sy+rz+oz,sz]\n",
    "p12=[sx,sy+0.3*rz+oz,sz-rz]\n",
    "p13=[sx,sy-0.3*rz+oz,sz-rz]\n",
    "p14=[sx,sy-rz+oz,sz]\n",
    "p15=[sx,sy-0.3*rz+oz,sz+rz]\n",
    "p16=[sx,sy+0.3*rz+oz,sz+rz]  \n",
    "    \n",
    "#p8[1]-=1\n",
    "#p10[1]-=2\n",
    "#p8[0]+=1\n",
    "    \n",
    "cut0=20\n",
    "w0=20\n",
    "cut1=20\n",
    "w1=20\n",
    "cut2=5\n",
    "w2=20\n",
    "vmax=1000\n",
    "vmin=100\n",
    "fig,ax=matplotlib.pyplot.subplots(3,9,figsize=(20,12))\n",
    "for i in numpy.arange(0,9):\n",
    "    ax[0,i].imshow(nim[:,slc[1]-4+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]-4+i].T,cmap='gray_r',vmax=vmax,vmin=vmin)\n",
    "    ax[2,i].imshow(nim[slc[0]-4+i,cut1:cut1+w1,cut1:cut1+w1],cmap='gray_r',vmax=vmax,vmin=vmin)\n",
    "    if i==4:\n",
    "        pt=[p1,p2,p3,p4,p5,p6]\n",
    "        ax[0,i].scatter([x[2]-cut0 for x in pt],[x[0] for x in pt])\n",
    "        pt=[p1,p2,p7,p8,p9,p10]\n",
    "        ax[1,i].scatter([x[0]-cut2 for x in pt],[x[1]-cut0 for x in pt])\n",
    "        pt=[p1,p11,p12,p13,p14,p15,p16]\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",
    "if save:\n",
    "    of=os.path.join(locDir,pId,'{}_segments.png'.format(pId))\n",
    "    matplotlib.pyplot.savefig(of)\n",
    "    \n",
    "    ds=db.selectRows(project,'study','Segmentation',[idFilter])\n",
    "    pts=[p1,p2,p3,p4,p5,p6,p7,p8,p9,p10,p11,p12,p13,p14,p15,p16]\n",
    "    for i in numpy.arange(len(pts)):\n",
    "        seqFilter={'variable':'SequenceNum','value':str(r['SequenceNum']+0.01*i),'oper':'eq'}\n",
    "        ds=db.selectRows(project,'study','Segmentation',[idFilter,seqFilter])\n",
    "        if len(ds['rows'])>0:\n",
    "            qrow=ds['rows'][0]\n",
    "            mode='update'\n",
    "        else:\n",
    "            qrow={}\n",
    "            qrow['PatientId']=r['PatientId']\n",
    "            qrow['SequenceNum']=0.01*i+r['SequenceNum']\n",
    "            qrow['aliasID']=pId\n",
    "            mode='insert'\n",
    "        qrow['regionId']=int(i)\n",
    "        qrow['x']=pts[i][0]\n",
    "        qrow['y']=pts[i][1]\n",
    "        qrow['z']=pts[i][2]\n",
    "        db.modifyRows(mode,project,'study','Segmentation',[qrow])\n",
    "    \n",
    "            \n",
    "matplotlib.pyplot.show()\n",
    "\n",
    "    \n",
    "    "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 307,
   "metadata": {},
   "outputs": [],
   "source": [
    "n=numpy.zeros((3,3))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 309,
   "metadata": {},
   "outputs": [],
   "source": [
    "n[1,1]=1"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 314,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "<matplotlib.collections.PathCollection at 0x7f6198cabdf0>"
      ]
     },
     "execution_count": 314,
     "metadata": {},
     "output_type": "execute_result"
    },
    {
     "data": {
      "image/png": "[encoded data, 5128 characters]\n",
      "text/plain": [
       "<Figure size 432x288 with 1 Axes>"
      ]
     },
     "metadata": {
      "needs_background": "light"
     },
     "output_type": "display_data"
    }
   ],
   "source": [
    "matplotlib.pyplot.imshow(n)\n",
    "matplotlib.pyplot.scatter([1],[1])"
   ]
  },
  {
   "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
}
