def estimate_ratio_hypoxic(oxy_grp,threshold): dataman = myutils.DataManager(2, [DataDetailedPO2(), DataBasicVessel()]) gvessels, gtumor = OpenVesselAndTumorGroups(oxy_grp) po2vessels, po2field_ld, po2field, parameters = dataman('detailedPO2', oxy_grp) po2vessels = np.average(po2vessels, axis=0) print 'po2vessels:', po2vessels.min(), po2vessels.max() print 'po2field:', np.amin(po2field), np.amax(po2field) #tissueOxygen = np.asarray(oxy_grp['po2field']) #print(tissueOxygen) #I neglect 5 entries from the boarder oxy_np_field= np.asarray(po2field) border=15 cropped_oxy = oxy_np_field[border:-border,border:-border,border:-border] hypoxic_Tissue = cropped_oxy<threshold hypoxic_counts = np.sum(hypoxic_Tissue[:]) number_of_boxes = cropped_oxy.shape[0]*cropped_oxy.shape[1]*cropped_oxy.shape[2] #times volume of each box cropped_volume = number_of_boxes*np.power(po2field_ld.scale,3) print('considerd volume of: %f mum^3' % cropped_volume) print('considerd volume of: %f mm^3' % (cropped_volume/1e9)) hypoxic_fraction = float(hypoxic_counts)/float(number_of_boxes) print('hypoxic fraction: %s ' % hypoxic_fraction) hypoxic_volume = hypoxic_counts*np.power(po2field_ld.scale,3) #to mm hypoxic_volume = hypoxic_volume/1e9 return hypoxic_fraction,hypoxic_volume
def ProduceData(fitParameters, filename): from krebs.analyzeGeneral import DataBasicVessel, DataVesselSamples, DataVesselGlobal from krebs.detailedo2Analysis import DataDetailedPO2 import krebs.detailedo2Analysis.singleVesselCases as singleVesselCases paramspo2Override = dict( massTransferCoefficientModelNumber=1, conductivity_coeff1=fitParameters[0], conductivity_coeff2=fitParameters[1], conductivity_coeff3=fitParameters[2], ) f = h5files.open(filename, 'a') krebsutils.set_num_threads(2) dataman = myutils.DataManager(20, [ DataDetailedPO2(), DataBasicVessel(), DataVesselSamples(), DataVesselGlobal() ]) for k, params in fitCases: params = deepcopy(params) params.paramspo2.update(paramspo2Override) singleVesselCases.GenerateSingleCapillaryWPo2(dataman, f, k, 16, params) return f
def renderScene(drug_grp, imagefn, options): imagefn, ext = splitext(imagefn) ext = '.' + options.format options.imageFileName = imagefn+'_iff_drug'+ext max_conc = getMaxConcentration(drug_grp.file) dataman = myutils.DataManager(2, [DataBasicVessel()]) timepoint = drug_grp.attrs['time'] #comes in seconds timepoint = timepoint/3600. #gvessels = drug_grp.parent['iff/vessels'] gvessels = drug_grp.parent['vessels'] iff_pressure_field = drug_grp.parent['iff/iff_pressure'] drug_conc_field = drug_grp['conc'] cell_drug_conc_field = drug_grp['conc_cell'] ex_drug_conc_field = drug_grp['conc_ex'] #ex_drug_auc_field = drug_grp.parent['measurements/drug_local_integral']['auc_ex'] #in_drug_auc_field = drug_grp.parent['measurements/drug_local_integral']['auc_in'] #iff_ld = krebsutils.read_lattice_data_from_hdf_by_filename(drug_grp.parent['field_ld']) iff_ld = krebsutils.read_lattice_data_from_hdf_by_filename(str(drug_grp.file.filename),str(drug_grp.parent.name)+'field_ld') #ld = iffgroup['lattice'] #po2vessels, po2field_ld, po2field, parameters = dataman('detailedPO2', po2group) #po2vessels = np.average(po2vessels, axis=0) #print 'po2vessels:', po2vessels.min(), po2vessels.max() print 'ifpfield:', np.amin(iff_pressure_field), np.amax(iff_pressure_field) print 'drug_conc_field:', np.amin(drug_conc_field), np.amax(drug_conc_field) #vessel_ld = krebsutils.read_lattice_data_from_hdf(gvessels['lattice']) vessel_ld = krebsutils.read_lattice_data_from_hdf_by_filename(str(gvessels.file.filename),str(gvessels.name)+'/lattice') vessel_graph = dataman('vessel_graph', gvessels, ['position', 'flags', 'radius']) #vessel_graph.edges['po2vessels'] = po2vessels #vessel_graph.edges['saturation'] = PO2ToSaturation(po2vessels, parameters) #vessel_graph.edges['hboconc'] = vessel_graph.edges['saturation']*vessel_graph.edges['hematocrit']*chb_of_rbcs*1.0e3 vessel_graph = vessel_graph.get_filtered(edge_indices = myutils.bbitwise_and(vessel_graph['flags'], krebsutils.CIRCULATED)) if options.filterradiuslowpass>0.0: print("lowpass filter activated:") vessel_graph = vessel_graph.get_filtered(edge_indices = vessel_graph['radius']< kwargs['filterradiuslowpass']) imagefn, ext = splitext(imagefn) ext = '.' + options.format if 1: if timepoint==0: renderSliceWithDistribution((vessel_ld, vessel_graph, 'iff_pressure'), (iff_ld, iff_pressure_field), (imagefn+'_iff_pressure_t%0.1fh'%timepoint )+ext, 'IF pressure t=%.1f h'%timepoint, options, max_conc=max_conc) renderSliceWithDistribution((vessel_ld, vessel_graph, 'drug_conc'), (iff_ld, drug_conc_field), (imagefn+'_iff_drug_t%0.1fh'%timepoint )+ext, '%s t=%.1f h'%(drug_grp.file.attrs.get('MESSAGE'),timepoint), options, max_conc=max_conc) #renderSliceWithDistribution((vessel_ld, vessel_graph, 'drug_conc'), (iff_ld, cell_drug_conc_field), (imagefn+'_iff_drug_incell_t%0.1fh'%timepoint)+ext, 'Tr. intr. t=%.1f h'%timepoint, kwargs) #renderSliceWithDistribution((vessel_ld, vessel_graph, 'drug_conc'), (iff_ld, ex_drug_conc_field), (imagefn+'_iff_drug_excell_t%0.1fh'%timepoint)+ext, 'Tr. extr. t=%.1f h'%timepoint, kwargs) if options.plot_auc: renderSliceWithDistribution((vessel_ld, vessel_graph, 'auc'), (iff_ld, ex_drug_auc_field), imagefn+'_iff_ex_drug_auc'+ext, 'Tr. extr. t=%.1f h'%timepoint, options, max_conc=max_conc) #renderSliceWithDistribution((vessel_ld, vessel_graph, 'auc'), (iff_ld, in_drug_auc_field), imagefn+'_iff_in_drug_auc'+ext, 'Tr. intr. t=%.1f h'%timepoint, kwargs) if 0: renderSlice((vessel_ld, vessel_graph, 'radius'), (iff_ld, iff_pressure_field), imagefn+'_iff_pressure'+ext, '', options) renderSlice((vessel_ld, vessel_graph, 'radius'), (iff_ld, drug_conc_field), imagefn+'_iff_drug'+ext, '', options) renderSlice((vessel_ld, vessel_graph, 'radius'), (iff_ld, cell_drug_conc_field), imagefn+'_iff_drug_incell'+ext, '', options) renderSlice((vessel_ld, vessel_graph, 'radius'), (iff_ld, ex_drug_conc_field), imagefn+'_iff_drug_excell'+ext, '', options)
def estimate_annoxic_hypoxic_normoxic(oxy_grp, tumorradius,threshold1,threshold2): dataman = myutils.DataManager(2, [DataDetailedPO2(), DataBasicVessel()]) gvessels, gtumor = OpenVesselAndTumorGroups(oxy_grp) po2vessels, po2field_ld, po2field, parameters = dataman('detailedPO2', oxy_grp) po2vessels = np.average(po2vessels, axis=0) print 'po2vessels:', po2vessels.min(), po2vessels.max() print 'po2field:', np.amin(po2field), np.amax(po2field) #tissueOxygen = np.asarray(oxy_grp['po2field']) #print(tissueOxygen) #I neglect 5 entries from the boarder oxy_np_field= np.asarray(po2field) #find minimal dimension min_dim = np.min(oxy_np_field.shape) print("tumorradius: %f, ld: %f" %(tumorradius,po2field_ld.scale)) border0=int(np.floor(oxy_np_field.shape[0]/2)-np.ceil(tumorradius/po2field_ld.scale)) border1=int(np.floor(oxy_np_field.shape[1]/2)-np.ceil(tumorradius/po2field_ld.scale)) border2=int(np.floor(oxy_np_field.shape[2]/2)-np.ceil(tumorradius/po2field_ld.scale)) print("border0: %i" %border0) print("border1: %i" %border1) print("border2: %i" %border2) cropped_oxy = oxy_np_field[border0:-border0,border1:-border1,border2:-border2] annoxic_Tissue = cropped_oxy<threshold1 annoxic_counts = np.sum(annoxic_Tissue[:]) hypoxic_Tissue = np.logical_and(cropped_oxy<threshold2, cropped_oxy>threshold1) #hypoxic_Tissue = hypoxic_Tissue>threshold1 hypoxic_counts = np.sum(hypoxic_Tissue[:]) normoxic_Tissue = cropped_oxy>threshold2 normoxic_counts = np.sum(normoxic_Tissue[:]) number_of_boxes = cropped_oxy.shape[0]*cropped_oxy.shape[1]*cropped_oxy.shape[2] ''' volume correction for not sampling a sphere, but a cube \frac{volume(sphere)}{volume(cube of 2 times radius)} = \pi/6 ''' volume_correction_factor = np.pi/6. #volume_correction_factor = 1. #times volume of each box cropped_volume = number_of_boxes*np.power(po2field_ld.scale,3) print('considerd volume of: %f mum^3' % cropped_volume) print('considerd volume of: %f mm^3' % (cropped_volume/1e9)) hypoxic_fraction = float(hypoxic_counts)/float(number_of_boxes) print('hypoxic fraction: %s ' % hypoxic_fraction) annoxic_volume = annoxic_counts*np.power(po2field_ld.scale,3) * volume_correction_factor #to mm annoxic_volume = annoxic_volume/1e9 normoxic_volume = normoxic_counts*np.power(po2field_ld.scale,3) * volume_correction_factor #to mm normoxic_volume = normoxic_volume/1e9 hypoxic_volume = hypoxic_counts*np.power(po2field_ld.scale,3) * volume_correction_factor #to mm hypoxic_volume = hypoxic_volume/1e9 #return hypoxic_fraction,hypoxic_volume return annoxic_volume,hypoxic_volume,normoxic_volume
def AddAverageConductivity(vesselgroup, parameters): dataman = myutils.DataManager(100, [DataBasicVessel()]) vessels = dataman.obtain_data('vessel_graph', vesselgroup, ['flow', 'pressure', 'flags', 'radius','nodeflags']) def DoBC(): conductivities, avgVenousPressure, avgArterialPressure, totalFlow = ComputeVascularTreeBloodFlowResistances(vessels) avgConductivity = (totalFlow/(avgArterialPressure-avgVenousPressure)) print 'avgVenousPressure', avgVenousPressure print 'avgArterialPressure', avgArterialPressure print 'totalFlow', totalFlow print 'avgConductivity', avgConductivity return avgConductivity avgConductivity = DoBC() parameters['adaption']['avgRootNodeConductivity'] = avgConductivity return parameters
def renderScene(po2group, imagefn, options): dataman = myutils.DataManager(2, [DataDetailedPO2(), DataBasicVessel()]) gvessels, gtumor = OpenVesselAndTumorGroups(po2group) po2vessels, po2field_ld, po2field, parameters = dataman( 'detailedPO2', po2group) po2vessels = np.average(po2vessels, axis=0) print 'po2vessels:', po2vessels.min(), po2vessels.max() print 'po2field:', np.amin(po2field), np.amax(po2field) #vessel_ld = krebsutils.read_lattice_data_from_hdf(gvessels['lattice']) vessel_graph = dataman('vessel_graph', gvessels, ['position', 'flags', 'radius', 'hematocrit']) vessel_graph.edges['po2_vessels'] = po2vessels print(parameters) vessel_graph.edges['saturation'] = PO2ToSaturation(po2vessels, parameters) vessel_graph.edges['hboconc'] = vessel_graph.edges[ 'saturation'] * vessel_graph.edges['hematocrit'] * chb_of_rbcs * 1.0e3 vessel_graph = vessel_graph.get_filtered(edge_indices=myutils.bbitwise_and( vessel_graph['flags'], krebsutils.CIRCULATED)) if options.filterradiuslowpass > 0: print("lowpass filter activated:") vessel_graph = vessel_graph.get_filtered( edge_indices=vessel_graph['radius'] < options.filterradiuslowpass) imagefn, ext = splitext(imagefn) ext = '.' + options.format #renderSliceWithDistribution((vessel_ld, vessel_graph, 'po2vessels'), (po2field_ld, po2field), imagefn+'_po2vessels'+ext, '', options) #renderSlice((vessel_ld, vessel_graph, 'saturation'), (None, None), imagefn+'_saturation'+ext, '', options) #renderSlice((vessel_ld, vessel_graph, 'hboconc'), (None, None), imagefn+'_hboconc'+ext, 'HbO [mmol/l blood]', options) #try world options.imageFileName = imagefn + '_po2vessels' + ext renderSliceWithDistribution((po2field_ld, vessel_graph, 'po2_vessels'), (po2field_ld, po2field), '', options) options.imageFileName = imagefn + '_saturation' + ext renderSlice((po2field_ld, vessel_graph, 'saturation'), (None, None), '', options) options.imageFileName = imagefn + '_hboconc' + ext renderSlice((po2field_ld, vessel_graph, 'hboconc'), (None, None), 'HbO [mmol/l blood]', options)
plotAnalyzeConvergence(dataman, pdfwriter, plotties) plotties[0].AddStatsPage(pdfwriter) plotAnalyzeIterativeConvergence(dataman, pdfwriter, plotties) pyplot.close('all') if __name__ == '__main__': krebsutils.set_num_threads(2) dataman = myutils.DataManager(20, [DataDetailedPO2(),DataBasicVessel(), DataVesselSamples(), DataVesselGlobal()]) fn = 'vessel-single-all.h5' #os.unlink(fn) f = h5files.open(fn,'a') GenerateSingleCapillaryWPo2(dataman, f, 'nair_uptake', 14, singleVesselParameterSets.nair_uptake) plot_single_capillary(dataman, f['nair_uptake'], useInsets = True) GenerateSingleCapillaryWPo2(dataman, f, 'nair_release', 14, singleVesselParameterSets.nair_release) plot_single_capillary(dataman, f['nair_release'], useInsets = True) grouplist = [] for name in [ 'moschandreou_case%02i' % i for i in xrange(6) ]: params = getattr(singleVesselParameterSets, name) r = params.paramsTube['r']
pdfwriter.savefig(fig, postfix='_curves') plotAnalyzeConvergence(dataman, pdfwriter, plotties) plotties[0].AddStatsPage(pdfwriter) plotAnalyzeIterativeConvergence(dataman, pdfwriter, plotties) pyplot.close('all') if __name__ == '__main__': krebsutils.set_num_threads(2) dataman = myutils.DataManager(20, [ DataDetailedPO2(), DataBasicVessel(), DataVesselSamples(), DataVesselGlobal() ]) fn = 'vessel-single-all.h5' #os.unlink(fn) f = h5files.open(fn, 'a') GenerateSingleCapillaryWPo2(dataman, f, 'nair_uptake', 14, singleVesselParameterSets.nair_uptake) plot_single_capillary(dataman, f['nair_uptake'], useInsets=True) GenerateSingleCapillaryWPo2(dataman, f, 'nair_release', 14, singleVesselParameterSets.nair_release) plot_single_capillary(dataman, f['nair_release'], useInsets=True)
def doit(filenames, pattern): dataman = myutils.DataManager(20, [ DataTumorTissueSingle(), DataDistanceFromCenter(), DataBasicVessel(), DataVesselSamples(), DataVesselRadial(), DataVesselGlobal(), DataTumorBloodFlow() ]) ensemble = EnsembleFiles(dataman, filenames, pattern) if ensemble.has_tumor: print 'paths: ', map(lambda (_t0, path, _t1): path, ensemble.tumor_snapshots) else: print 'paths: ', set(map(lambda e: e.path, ensemble.items)) prefix, suffix = myutils.splitcommonpresuffix( map(lambda s: basename(s), filenames)) outputbasename, _ = splitext(prefix + suffix) fn_measure = outputbasename + '-radial-cache.h5' f_measure = h5files.open(fn_measure, 'a') def cachelocation(g): path = posixpath.join( 'FileCS_' + myutils.checksum(basename(g.file.filename)), g.name.strip(posixpath.sep)) return (f_measure, path) #name = ensemble.items[0].path.split('/')[-1] measurementinfo = dict(sample_length=30., cachelocation_callback=cachelocation, distancemap_spec='radial') print 'getting radial curves' stuff = [] stuff2 = [] for items, path, time in ensemble.tumor_snapshots: bins_spec, curves = CollectAllRadialData(dataman, items, measurementinfo) tumorradius = GetAverageApproximateTumorRadius(dataman, ensemble, items) stuff.append((time, tumorradius, curves)) stuff2.append((time, tumorradius, curves, path)) #output_filename+= '_'+name with mpl_utils.PdfWriter(outputbasename + '-radial.pdf') as pdfwriter: PlotRadialCurves(pdfwriter, bins_spec, stuff, measurementinfo, ensemble.world_size) with h5py.File(outputbasename + '-radial.h5', 'w') as f: f.attrs['COMMONPREFIX'] = os.path.commonprefix( map(lambda s: basename(s), filenames)) f.create_dataset('files', data=filenames) f.create_dataset('groups', data=np.asarray(set( map(lambda item: item.path, ensemble.items)), dtype=np.str)) for i, (time, tumorradius, curves, path) in enumerate(stuff2): g = f.create_group(path.strip('/').replace('/', '-')) g.attrs['TUMORRADIUS'] = tumorradius g.attrs['TIME'] = time for name, curve in curves.iteritems(): curve = myutils.MeanValueArray.fromSummation( map(lambda x: x.avg, curve)) g.create_dataset(name + '/avg', data=np.asarray(curve.avg)) g.create_dataset(name + '/std', data=np.asarray(curve.std)) g.create_dataset(name + '/mask', data=~curve.avg.mask) g.create_dataset(name + '/std_mean', data=np.asarray(curve.std_mean)) g.create_dataset('bins', data=bins_spec.arange())