statUtils.py 8.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244
  1. #load required libraries
  2. import sys
  3. import os
  4. import SimpleITK
  5. import json
  6. import chardet
  7. import numpy
  8. def connectDB(server):
  9. #you should get nixSuite via git clone https://git0.fmf.uni-lj.si/studen/nixSuite.git
  10. #if you don't put it to $HOME/software/src/, you should update the path
  11. nixSuite=os.path.join(os.path.expanduser('~'),'software','src','nixSuite')
  12. if not os.path.isdir(nixSuite):
  13. nixSuite=os.path.join(os.path.expanduser('~'),'software','src','nixsuite')
  14. sys.path.append(os.path.join(nixSuite,'wrapper'))
  15. import nixWrapper
  16. nixWrapper.loadLibrary('labkeyInterface')
  17. import labkeyInterface
  18. import labkeyDatabaseBrowser
  19. import labkeyFileBrowser
  20. #check connectivity. This checks the configuration in $HOME/.labkey/network.json,
  21. #where paths to certificates are stored
  22. net=labkeyInterface.labkeyInterface()
  23. fconfig=os.path.join(os.path.expanduser('~'),'.labkey','{}.json'.format(server))
  24. net.init(fconfig)
  25. #this reports the certificate used
  26. try:
  27. print('Using: {}'.format(net.connectionConfig['SSL']['user']))
  28. except KeyError:
  29. pass
  30. #This gets a deafult CSRF code; It should report user name plus a long string of random hex numbers
  31. net.getCSRF()
  32. db=labkeyDatabaseBrowser.labkeyDB(net)
  33. fb=labkeyFileBrowser.labkeyFileBrowser(net)
  34. return db,fb
  35. def getUsers(db,project):
  36. ds=db.selectRows(project,'core','Users',[])
  37. users={x['UserId']:x['DisplayName'] for x in ds['rows']}
  38. for u in users:
  39. print('{} {}'.format(u,users[u]))
  40. return users
  41. def getImage(setup, row, field, extraPath=None):
  42. fb=setup['fb']
  43. pathList=[setup['imageDir'],row['patientCode'],row['visitCode']]
  44. if extraPath!=None:
  45. pathList.append(extraPath)
  46. pathList.append(row[field])
  47. remotePath='/'.join(pathList)
  48. urlPath=fb.formatPathURL(setup['project'],remotePath)
  49. localPath=os.path.join(setup['localDir'],row[field])
  50. if os.path.isfile(localPath):
  51. pass
  52. #print('{} done'.format(localPath))
  53. else:
  54. if not fb.entryExists(urlPath):
  55. print('No file {}'.format(urlPath))
  56. return "NONE"
  57. fb.readFileToFile(urlPath,localPath)
  58. print('Copying remote {} -> {} done'.format(urlPath,localPath))
  59. return localPath
  60. def getSegmentations(setup,row):
  61. idField=setup['idField']
  62. visitField=setup['visitField']
  63. qFilter=[{'variable':x,'value':row[x],'oper':'eq'} for x in [idField,visitField]]
  64. dsSeg=setup['db'].selectRows(setup['project'],'study','Segmentations',qFilter)
  65. if len(dsSeg['rows'])<1:
  66. print('Failed to find segmentation for {}/{}'.format(row[idField],row[visitField]))
  67. return {0:"NONE"}
  68. return {r['User']:getImage(setup,r,'latestFile',extraPath='Segmentations') for r in dsSeg['rows']}
  69. def loadSetup(path):
  70. with open(path,'r') as f:
  71. setup=json.load(f)
  72. fC=[x for x in setup.keys() if x.find('Dir')>-1]
  73. for q in fC:
  74. setup[q]=setup[q].replace('_home_',os.path.expanduser('~'))
  75. return setup
  76. def getSegments(image):
  77. keys=image.GetMetaDataKeys()
  78. i=0
  79. ids={}
  80. while True:
  81. id='Segment{}_ID'.format(i)
  82. value='Segment{}_LabelValue'.format(i)
  83. try:
  84. ids[image.GetMetaData(id)]=int(image.GetMetaData(value))
  85. except RuntimeError:
  86. break
  87. i+=1
  88. return ids
  89. def getStats(image):
  90. print(image.GetSize())
  91. print(image.GetOrigin())
  92. print(image.GetSpacing())
  93. print(image.GetNumberOfComponentsPerPixel())
  94. def getSegmentStats(pet,seg,label):
  95. o=getComponents(seg,label)
  96. cc=o['image']
  97. shape_stats = SimpleITK.LabelShapeStatisticsImageFilter()
  98. #shape_stats.ComputeOrientedBoundingBoxOn()
  99. shape_stats.Execute(cc)
  100. intensity_stats = SimpleITK.LabelIntensityStatisticsImageFilter()
  101. intensity_stats.Execute(cc,pet)
  102. #output
  103. out=[(shape_stats.GetPhysicalSize(i),
  104. intensity_stats.GetMean(i),
  105. intensity_stats.GetStandardDeviation(i),
  106. intensity_stats.GetSkewness(i)) for i in shape_stats.GetLabels()]
  107. print(out)
  108. def getComponents(seg,label):
  109. cc=SimpleITK.Threshold(seg,lower=label,upper=label)
  110. ccFilter=SimpleITK.ConnectedComponentImageFilter()
  111. cc1=ccFilter.Execute(cc)
  112. return {'image':cc1, 'count':ccFilter.GetObjectCount()}
  113. def drop_array(v):
  114. return float(v)
  115. #if type(v) is numpy.ndarray:
  116. # return v[0]
  117. #return v
  118. def getSUVmax(vals):
  119. return drop_array(vals['original_firstorder_Maximum'])
  120. def getSUVmean(vals):
  121. return drop_array(vals['original_firstorder_Mean'])
  122. def getSUVSD(vals):
  123. return numpy.sqrt(drop_array(vals['original_firstorder_Variance']))
  124. def getMTV(vals):
  125. try:
  126. return drop_array(vals['original_shape_MeshVolume'])
  127. except KeyError:
  128. return drop_array(vals['original_shape_VoxelVolume'])
  129. def getTLG(vals):
  130. V=vals['original_shape_VoxelVolume']
  131. return V*getSUVmean(vals)
  132. def getCOM(vals):
  133. return vals['diagnostics_Mask-original_CenterOfMassIndex']
  134. def getNVoxels(vals):
  135. return drop_array(vals['original_shape_VoxelVolume']/8)
  136. def getValue(vals,valueName):
  137. if valueName=='SUVmean':
  138. return getSUVmean(vals)
  139. if valueName=='SUVmax':
  140. return getSUVmax(vals)
  141. if valueName=='SUVSD':
  142. return getSUVSD(vals)
  143. if valueName=='MTV':
  144. return getMTV(vals)
  145. if valueName=='TLG':
  146. return getTLG(vals)
  147. if valueName=='COM':
  148. return getCOM(vals)
  149. if valueName=='voxelCount':
  150. return getNVoxels(vals)
  151. return 0
  152. def getRadiomicsStats(setup,pet,seg,label):
  153. o=getComponents(seg,label)
  154. cc=o['image']
  155. n=o['count']
  156. output={}
  157. for i in range(n):
  158. output[i]=getRadiomicsComponentStats(setup,pet,seg,label)
  159. return output
  160. def getRadiomicsComponentStats(setup,pet,cc,label):
  161. vals=setup['featureExtractor'].execute(pet,cc,label=label)
  162. output={x:getValue(vals,x) for x in setup['values']}
  163. #for v in vals:
  164. # print('{}: {}'.format(v,vals[v]))
  165. for c in output:
  166. print('{}: {}'.format(c,output[c]))
  167. return output
  168. def findMatchingComponent(o,a,b,label):
  169. statFilter=SimpleITK.StatisticsImageFilter()
  170. overlap_measures_filter = SimpleITK.LabelOverlapMeasuresImageFilter()
  171. print('{}: [{}]:{} [{}]:{}'.format(label,a,o[a]['count'],b,o[b]['count']))
  172. comps={v:{x+1:o[v]['image']==x+1 for x in range(o[v]['count'])} for v in [a,b]}
  173. stat={}
  174. for comp in comps:
  175. stat[comp]={}
  176. for x in comps[comp]:
  177. cc=comps[comp][x]
  178. statFilter.Execute(cc)
  179. stat[comp][x]={'sum':statFilter.GetSum()}
  180. for c in comps[a]:
  181. cc=comps[a][c]
  182. print('{}:{}'.format(c,stat[a][c]['sum']))
  183. for d in comps[b]:
  184. cc1=comps[b][d]
  185. overlap_measures_filter.Execute(cc, cc1)
  186. print('\t {}:{} {}'.format(d,stat[b][d]['sum'],overlap_measures_filter.GetDiceCoefficient()))
  187. def evaluateByLesions(pet,seg,ids):
  188. for id in ids:
  189. print('{}: {}'.format(id,ids[id]))
  190. o={x:getComponents(seg[x],ids[id]) for x in seg}
  191. a=segKeys[0]
  192. for x in segKeys[1:]:
  193. findMatchingComponent(o,a,x,ids[id])
  194. def updateDatasetRows(db,project,dataset,rows,filterVars=['ParticipantId','SequenceNum','User']):
  195. for r in rows:
  196. r['SequenceNum']+=r['segment']*0.01
  197. qFilter=[{'variable':x,'value':'{}'.format(r[x]),'oper':'eq'} for x in filterVars]
  198. ds=db.selectRows(project,'study',dataset,qFilter)
  199. if len(ds['rows'])>0:
  200. row=ds['rows'][0]
  201. row.update({x:r[x] for x in r if x not in filterVars})
  202. mode='update'
  203. resp=db.modifyRows('update',project,'study',dataset,[row])
  204. else:
  205. mode='insert'
  206. resp=db.modifyRows('insert',project,'study',dataset,[r])
  207. #encoding=chardet.detect(resp)['encoding']
  208. #respJSON=json.loads(resp.decode(encoding))
  209. try:
  210. print(resp['exception'])
  211. print(f'Using mode={mode}')
  212. except KeyError:
  213. pass