statUtils.py 7.3 KB

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