segmentation.py 6.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241
  1. import numpy
  2. import config
  3. import SimpleITK
  4. import os
  5. import getData
  6. def guessPixelPosition15(sx=-1,sy=-1,sz=-1):
  7. #guess position of segments
  8. if sx<0:
  9. sx=12
  10. if sy<0:
  11. sy=28
  12. if sz<0:
  13. sz=32
  14. rz=4
  15. oz=0
  16. slc=[sx,sy,sz]
  17. p1=[sx,sy,sz]
  18. pts={
  19. '0':[sx-5,sy,sz],\
  20. '1':[sx-2,sy,sz-rz],\
  21. '2':[sx-2,sy,sz+rz-1],\
  22. '3':[sx-1,sy-rz,sz],\
  23. '4':[sx-1,sy+rz-1,sz],\
  24. '5':[sx,sy-rz+oz,sz],\
  25. '6':[sx,sy-0.3*rz+oz,sz-rz],\
  26. '7':[sx,sy-0.3*rz+oz,sz+rz],\
  27. '8':[sx,sy,sz],\
  28. '9':[sx,sy+0.3*rz+oz,sz-rz],\
  29. '10':[sx,sy+0.3*rz+oz,sz+rz],\
  30. '11':[sx,sy+rz+oz,sz],\
  31. '12':[sx+3,sy-rz,sz],\
  32. '13':[sx+3,sy,sz-rz],\
  33. '14':[sx+3,sy,sz+rz],\
  34. '15':[sx+3,sy+rz,sz]}
  35. slices={'0':['8','0','1','13','2','14'],\
  36. '1':['8','0','3','4','12','15'],\
  37. '2':['8','11','9','6','5','7','10']}
  38. print(slices['0'])
  39. fp={x:[pts[q] for q in slices[x]] for x in slices}
  40. sliceIds={x:[] for x in pts}
  41. for p in pts:
  42. for s in slices:
  43. if p in slices[s]:
  44. sliceIds[p].append(s)
  45. sliceCode={x:';'.join(sliceIds[x]) for x in sliceIds}
  46. print(fp)
  47. print(sliceCode)
  48. return fp
  49. #tip
  50. fp={'0':[\
  51. [sx,sy,sz],
  52. [sx-5,sy,sz],\
  53. [sx-2,sy,sz-rz],\
  54. [sx+3,sy,sz-rz],\
  55. [sx-2,sy,sz+rz-1],\
  56. [sx+3,sy,sz+rz]],\
  57. '1':[\
  58. [sx,sy,sz],
  59. [sx-5,sy,sz],\
  60. [sx-1,sy-rz,sz],\
  61. [sx-1,sy+rz-1,sz],\
  62. [sx+3,sy-rz,sz],\
  63. [sx+3,sy+rz,sz]],\
  64. '2':[\
  65. [sx,sy,sz],
  66. [sx,sy+rz+oz,sz],\
  67. [sx,sy+0.3*rz+oz,sz-rz],\
  68. [sx,sy-0.3*rz+oz,sz-rz],\
  69. [sx,sy-rz+oz,sz],\
  70. [sx,sy-0.3*rz+oz,sz+rz],\
  71. [sx,sy+0.3*rz+oz,sz+rz]]}
  72. return fp
  73. def guessPixelPosition4(sx=-1,sy=-1,sz=-1):
  74. #guess position of segments
  75. if sx<0:
  76. sx=32
  77. if sy<0:
  78. sy=31
  79. if sz<0:
  80. sz=31
  81. rz=4
  82. pts={
  83. '0':[sx,sy,sz],\
  84. '1':[sx,sy,sz-rz],\
  85. '2':[sx,sy,sz+rz],\
  86. '3':[sx,sy-rz,sz],\
  87. '4':[sx,sy+rz,sz]}
  88. slices={
  89. '0':['0','1','2'],\
  90. '1':['0','3','4'],\
  91. '2':['0','1','2','3','4']}
  92. print(slices['0'])
  93. fp={x:[pts[q] for q in slices[x]] for x in slices}
  94. sliceIds={x:[] for x in pts}
  95. for p in pts:
  96. for s in slices:
  97. if p in slices[s]:
  98. sliceIds[p].append(s)
  99. sliceCode={x:';'.join(sliceIds[x]) for x in sliceIds}
  100. print(fp)
  101. print(sliceCode)
  102. return [{'regionId':x,'x':pts[x][0],'y':pts[x][1],'z':pts[x][2],'sliceId':sliceCode[x]} for x in pts]
  103. def updateSegmentation(db,setup,r,pixels):
  104. copyFields=['PatientId','visitCode']
  105. for x in pixels:
  106. for c in copyFields:
  107. x[c]=r[c]
  108. x['SequenceNum']=r['SequenceNum']+0.01*int(x['regionId'])
  109. filterVar=['PatientId','SequenceNum']
  110. qFilter=[{'variable':y,'value':'{}'.format(x[y]),'oper':'eq'} for y in filterVar]
  111. ds=db.selectRows(setup['project'],'study','Segmentation',qFilter)
  112. entry={}
  113. mode='insert'
  114. if len(ds['rows'])>0:
  115. entry=ds['rows'][0]
  116. mode='update'
  117. for q in x:
  118. entry[q]=x[q]
  119. db.modifyRows(mode,setup['project'],'study','Segmentation',[entry])
  120. print('Done')
  121. def getSegmentationFileName(r,setup,db=None):
  122. if not db:
  123. db,fb=getData.connectDB(setup['network'])
  124. if setup['segmentationMode']=='TXT':
  125. return '{}_Segmentation.txt'.format(config.getCode(r,setup))
  126. if setup['segmentationMode']=='NRRD':
  127. copyFields=['PatientId','visitCode']
  128. qFilter=[{'variable':x,'value':r[x],'oper':'eq'} for x in copyFields]
  129. qFilter.append({'variable':'User','value':setup['targetUser'],'oper':'eq'})
  130. rows=getData.getSegmentation(db,setup,qFilter)
  131. r=rows[0]
  132. return r['latestFile']
  133. def getURL(fb,r,setup,name):
  134. remoteDir=fb.buildPathURL(setup['project'],config.getPathList(r,setup))
  135. return '/'.join([remoteDir,'Segmentations',name])
  136. def copyFromServer(fb,r,setup,names):
  137. try:
  138. forceReload=setup['forceReload']
  139. except KeyError:
  140. forceReload=False
  141. getData.getLocalDir(r,setup,createIfMissing=True)
  142. remoteDir=fb.buildPathURL(setup['project'],config.getPathList(r,setup))
  143. for n in names:
  144. localPath=getData.getLocalPath(r,setup,n)
  145. if os.path.isfile(localPath) and not forceReload:
  146. continue
  147. remotePath='/'.join([remoteDir,'Segmentations',n])
  148. fb.readFileToFile(remotePath,localPath)
  149. def copyToServer(fb,r,setup,names):
  150. remoteDir=fb.buildPathURL(setup['project'],config.getPathList(r,setup))
  151. for n in names:
  152. localPath=getLocalPath(r,setup,n)
  153. remotePath='/'.join([remoteDir,'Segmentations',n])
  154. fb.writeFileToFile(localPath,remotePath)
  155. def writeSegmentation(db,fb,r,setup):
  156. if setup['segmentationMode']=='NRRD':
  157. print('Failed to load segmentation')
  158. return
  159. fileName=getSegmentationFileName(db,r,setup)
  160. idFilter={'variable':'PatientId','value':config.getPatientId(r,setup),'oper':'eq'}
  161. visitFilter={'variable':'visitCode','value':config.getVisitId(r,setup),'oper':'eq'}
  162. rows=getData.getSegmentation(db,setup,[idFilter,visitFilter])
  163. v=numpy.zeros((len(rows),3))
  164. for qr in rows:
  165. region=int(qr['regionId'])
  166. v[region,2]=float(qr['x'])
  167. v[region,1]=float(qr['y'])
  168. v[region,0]=float(qr['z'])
  169. #for i in range(len(rows)):
  170. # print(v[i,:])
  171. numpy.savetxt(getData.getLocalPath(r,setup,fileName),v)
  172. getData.copyToServer(fb,r,setup,[fileName])
  173. def getNC(r,xsetup):
  174. if xsetup['segmentationMode']=='TXT':
  175. getNCTxt(r,xsetup)
  176. if xsetup['segmentationMode']=='NRRD':
  177. return xsetup['NC']
  178. def getNCTxt(r,xsetup):
  179. sName=getSegmentationFileName(db=None,r=r,setup=xsetup)
  180. fName=getData.getLocalPath(r,xsetup,sName)
  181. x=numpy.loadtxt(fName)
  182. nc=x.shape[0]
  183. return nc
  184. def loadSegmentation(db,fb,r,setup):
  185. sName=getSegmentationFileName(db,r,setup)
  186. print(f'Looking for {sName}')
  187. fName=getData.getLocalPath(r,setup,sName)
  188. print(f'Local {fName}')
  189. if not os.path.isfile(fName):
  190. fURL=getData.getURL(fb,r,setup,sName)
  191. if fb.entryExists(fURL):
  192. getData.copyFromServer(fb,r,setup,[sName])
  193. if os.path.isfile(fName):
  194. print(f'Copied {fURL} to {fName}')
  195. else:
  196. print(f'Failed to load {fName} from {fURL}')
  197. else:
  198. #this creates local and global file
  199. writeSegmentation(db,fb,r,setup)
  200. if setup['segmentationMode']=='TXT':
  201. return numpy.loadtxt(fName)
  202. def getNRRDImage(r,setup,names=None):
  203. if names:
  204. localFile=getData.getLocalPath(r,setup,names['segmentation'][0])
  205. else:
  206. localFile=getData.getLocalPath(r,setup,getSegmentationFileName(r,setup))
  207. segImg=SimpleITK.ReadImage(localFile)
  208. seg=SimpleITK.GetArrayFromImage(segImg)
  209. return seg