Пример #1
0
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 surface2Volume(vesselgroup):
  vessels = krebsutils.read_vesselgraph(vesselgroup, ['flags', 'radius', 'length'])
  flags   = RemoveArteriovenousFlagsFromCapillaries(vessels['flags'])
  flags = flags[:,0]
  mask1 = myutils.bbitwise_and(flags, krebsutils.CIRCULATED)
  totalvol = totalLdVolume(vesselgroup)
  def compute(flagMask):
    if flagMask:
      mask = mask1 & myutils.bbitwise_and(flags, flagMask)
    else:
      mask = mask1
    length = np.asarray(vessels['length'][mask], dtype = np.float64)
    radius = np.asarray(vessels['radius'][mask], dtype = np.float64)
    radius = radius[:,0]
    vol = math.pi * np.power(radius, 2.) * length
    surface = 2* math.pi* radius* length
    #surface = np.sum(surface)
    #vol = np.sum(vol)
    s2v = surface/vol
    mystd = np.std(s2v)
    myavg = np.average(s2v)
    myrel = mystd/myavg
    print("spread: %f" % myrel)
    return np.average(surface/vol)
  return compute(0), compute(krebsutils.ARTERY), compute(krebsutils.VEIN), compute(krebsutils.CAPILLARY)
Пример #3
0
 def write(gmeasure, groupname):
     weight = dataman.obtain_data('basic_vessel_samples', 'weight',
                                  vesselgroup, self.sample_length)
     flags = dataman.obtain_data('basic_vessel_samples', 'flags',
                                 vesselgroup, self.sample_length)
     position = dataman.obtain_data('basic_vessel_samples',
                                    'position', vesselgroup,
                                    self.sample_length)
     mask = myutils.bbitwise_and(flags, krebsutils.CIRCULATED)
     flags = flags[mask]
     position = position[mask, ...]
     weight = weight[mask]
     ####### put into bins
     eps = 1.0 - 1.e-15
     x0, x1, y0, y1, z0, z1 = fieldLd.worldBox
     ranges = [
         np.arange(x0, x1, fieldLd.scale * eps),
         np.arange(y0, y1, fieldLd.scale * eps),
         np.arange(z0, z1, fieldLd.scale * eps),
     ]
     mvd, _ = np.histogramdd(position, bins=ranges, weights=weight)
     mvd *= 1.e6 / (fieldLd.scale**3)
     ####### save
     gmeasure.create_dataset(groupname,
                             data=mvd,
                             compression=9,
                             dtype=np.float32)
 def compute(flagMask):
     if flagMask:
         mask = mask1 & myutils.bbitwise_and(flags, flagMask)
     else:
         mask = mask1
     length = np.asarray(vessels['length'][mask], dtype=np.float64)
     total = np.sum(length)
     return total / totalvol
Пример #5
0
def render_different_data_types(vesselgroup, options):
    filenamepostfix = ''
    labels = {
        'flow': '$log_{10}$ Flow Rate',
        'shearforce': '$log_{10}$ Shear Force',
        'hematocrit': 'Hematocrit',
        'pressure': 'Blood Pressure $kPa$',
        'S_tot': 'Adaption Signal',
        'conductivitySignal': 'Conductivity Signal',
        'metabolicSignal': 'Metabolic Signal',
        'radius': 'Vesselradius $\mu$m',
    }
    graph = krebsutils.read_vessels_from_hdf(
        vesselgroup,
        ['position', 'flags', 'radius', 'nodeflags'] + options.datalist,
        return_graph=True)
    #nodeflags not good for apj.h5
    #numpy int64 bug!
    #graph = krebsutils.read_vessels_from_hdf(vesselgroup, ['position', 'flags', 'radius' ] + options.datalist, return_graph=True)
    #if vesselgroup.attrs.get('CLASS') == 'GRAPH':
    #  vessel_ld = krebsutils.read_lattice_data_from_hdf(vesselgroup['lattice'])
    #  options.wbbox = vessel_ld.GetWorldBox()
    #if vesselgroup.attrs.get('CLASS') == 'REALWORLD':
    #  options.wbbox = np.max(np.asarray(vesselgroup['nodes/world_pos']),0)
    options.wbbox = ComputeBoundingBox(vesselgroup, graph)
    if options.filteruncirculated:
        graph = graph.get_filtered(edge_indices=myutils.bbitwise_and(
            graph['flags'], krebsutils.CIRCULATED))
    if options.filterradiushighpass > 0:
        graph = graph.get_filtered(
            edge_indices=graph['radius'] > filterradiushighpass)
        filenamepostfix = '_rhp'
    if options.filterradiuslowpass > 0:
        print("lowpass filter activated:")
        graph = graph.get_filtered(
            edge_indices=graph['radius'] < filterradiuslowpass)
        filenamepostfix = '_rlp'
    for data_name in options.datalist:
        if 'colorfactory' in options:
            colors_factory = options.colorfactory
            colors_factory(graph)

        cm, (datamin, datamax) = make_any_color_arrays(graph, data_name,
                                                       options)
        fn = vesselgroup.file.filename
        options.imageFileName = splitext(
            basename(fn)
        )[0] + '_' + myutils.sanitize_posixpath(vesselgroup.name).replace(
            '/',
            '-') + '_' + data_name + filenamepostfix + '.' + options.format
        print(options.imageFileName)
        with EasyPovRayRender(options) as epv:
            CreateScene2(vesselgroup, epv, graph, options)
            if options.noOverlay:
                epv.render(imagefn)
            else:
                RenderImageWithOverlay(epv, cm, labels[data_name], options)
Пример #6
0
 def process(vesselgroups):
     bins = np.logspace(-1., 1.1, 50, base=10.)
     result = []
     for g in vesselgroups:
         r = dataman.obtain_data('basic_vessel_samples', 'radius', g, 30.)
         w = dataman.obtain_data('basic_vessel_samples', 'weight', g, 30.)
         f = dataman.obtain_data('basic_vessel_samples', 'flags', g, 30.)
         i = myutils.bbitwise_and(f, krebsutils.CIRCULATED)
         if filterflags is not None:
             i &= myutils.bbitwise_and(f, filterflags)
         h = myutils.MeanValueArray.fromHistogram1d(bins, r[i], w[i])
         result.append(h)
     result = myutils.MeanValueArray.fromSummation(result)
     #ax.bar(bins[:-1], result.sum, width=(bins[1]-bins[0]))
     y = result.sum
     y /= np.sum(y)
     y /= (bins[1:] - bins[:-1])
     return bins[:-1], y
 def compute(flagMask):
     if flagMask:
         mask = mask1 & myutils.bbitwise_and(flags, flagMask)
     else:
         mask = mask1
     length = np.asarray(vessels['length'][mask], dtype=np.float64)
     radius = np.asarray(vessels['radius'][mask], dtype=np.float64)
     vol = math.pi * np.power(radius, 2.) * length
     vol = np.sum(vol)
     return vol / totalvol
Пример #8
0
def PlotRadiusHistogram(ax, dataman, vesselgroups, filterflags=None):
    #bins = np.linspace(0., 200., 20)
    #bins = np.asarray([ 0., 4, 8, 16, 32, 64, 128, 256])
    bins = np.logspace(-1., 2., 50, base=10.)
    result = []
    for g in vesselgroups:
        r = dataman.obtain_data('basic_vessel_samples', 'radius', g, 30.)
        w = dataman.obtain_data('basic_vessel_samples', 'weight', g, 30.)
        f = dataman.obtain_data('basic_vessel_samples', 'flags', g, 30.)
        i = myutils.bbitwise_and(f, krebsutils.CIRCULATED)
        if filterflags is not None:
            i &= myutils.bbitwise_and(f, filterflags)
        h = myutils.MeanValueArray.fromHistogram1d(bins, r[i], w[i])
        result.append(h)
    result = myutils.MeanValueArray.fromSummation(result)
    #ax.bar(bins[:-1], result.sum, width=(bins[1]-bins[0]))
    y = result.sum
    y /= np.sum(y)
    y /= (bins[1:] - bins[:-1])
    ax.step(bins[:-1], y, where='post')
def cylinderCollectionLineDensity(vesselgroup):
  vessels = krebsutils.read_vesselgraph(vesselgroup, ['flags', 'length'])
  flags   = RemoveArteriovenousFlagsFromCapillaries(vessels['flags'])
  flags = flags[:,0]
  mask1 = myutils.bbitwise_and(flags, krebsutils.CIRCULATED)
  totalvol = totalLdVolume(vesselgroup)
  def compute(flagMask):
    if flagMask:
      mask = mask1 & myutils.bbitwise_and(flags, flagMask)
    else:
      mask = mask1
    length = np.asarray(vessels['length'][mask], dtype = np.float64)
    total = np.sum(length)
    return total/totalvol
  return compute(0), compute(krebsutils.ARTERY), compute(krebsutils.VEIN), compute(krebsutils.CAPILLARY)
Пример #10
0
 def compute(flagMask):
   if flagMask:
     mask = mask1 & myutils.bbitwise_and(flags, flagMask)
   else:
     mask = mask1
   length = np.asarray(vessels['length'][mask], dtype = np.float64)
   radius = np.asarray(vessels['radius'][mask], dtype = np.float64)
   radius = radius[:,0]
   vol = math.pi * np.power(radius, 2.) * length
   surface = 2* math.pi* radius* length
   #surface = np.sum(surface)
   #vol = np.sum(vol)
   s2v = surface/vol
   mystd = np.std(s2v)
   myavg = np.average(s2v)
   myrel = mystd/myavg
   print("spread: %f" % myrel)
   return np.average(surface/vol)
Пример #11
0
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)
Пример #12
0
def GenerateRadialDistributions(dataman, vesselgroup, tumorgroup, sample_length, bins_spec, distance_distribution_name, ld, sample_iterator):
  weight_smpl = dataman.obtain_data('basic_vessel_samples', 'weight', vesselgroup, sample_length)
  flags       = dataman.obtain_data('basic_vessel_samples', 'flags', vesselgroup, sample_length)
  # get the radial distance function (either distance from tumor border or distance from center)
  if distance_distribution_name =='levelset':
    dist_smpl, distmap, mask, tumor_ld   = dataman.obtain_data('distancemap_samples', vesselgroup, tumorgroup, sample_length, distance_distribution_name, ld)
    #filter uncirculated
    mask = mask & myutils.bbitwise_and(flags, krebsutils.CIRCULATED)
    dist_smpl   = dist_smpl[mask]
    weight_smpl = weight_smpl[mask]
#""" not yet ready!!!!    
#  if distance_distribution_name =='radial':
#    #ld = krebsutils.read_lattice_data_from_hdf(iff_file['field_ld'])
#    distmap          = dataman.obtain_data('distance_from_center_distribution', ld)
#    distmap          = distmap.ravel()
#    dist_smpl = distmap
#    mask             = distmap < tumor_center_distance
#    ifp_field        = ifp_field[mask]
#    ifp_histo        = myutils.MeanValueArray.fromHistogram1d(ifp_bins, ifp_field, np.ones_like(ifp_field))
#    dist_smpl = dataman.obtain_data('distance_from_center_distribution', ld)
#    dist_smpl = dist_smpl.ravel()
#    mask = dist_smpl>0 #everything
#    dist_smpl = dist_smpl[mask]
#    weight_smpl = weight_smpl[mask]
    #dist_smpl, distmap, mask, tumor_ld   = dataman.obtain_data('distance_from_center_distribution', vesselgroup, tumorgroup, sample_length, distance_distribution_name, ld)
  # note: tumor_ld might be another unrelated lattice
#"""
  res=[]
  for (smpl, avg_mode) in sample_iterator:
    bins = bins_spec.arange()
    if avg_mode is radialAvgPerVolume:
      a = myutils.MeanValueArray.fromHistogram1d(bins, dist_smpl, smpl[mask], weight_smpl) # integral over length within bins
      b = myutils.MeanValueArray.fromHistogram1d(bins, distmap.ravel(), np.ones_like(distmap.ravel())) # how much tissue volume in the bins
      a.cnt = b.cnt.copy()
      a.sum *= 1./(tumor_ld.scale**3)
      a.sqr *= a.sum**2  # length integral per tissue volume
      #a *= 1.e6
    elif avg_mode is radialAvgPerVessels:
      a = myutils.MeanValueArray.fromHistogram1d(bins, dist_smpl, smpl[mask], weight_smpl)
    else:
      assert (avg_mode is radialAvgPerVolume or avg_mode is radialAvgPerVessels)
    res.append(a)
  return res
Пример #13
0
def CalcPhiVessels(dataman, vesselgroup, ld, scaling, samples_per_cell = 5):
  '''samples per cell mean the lattice grid cell,
     the total number of samples for a vessel is determined by the ratio
     of its volume to the volume of a grid cell times the samples_per_cell'''
  graph = krebsutils.read_vessels_from_hdf(vesselgroup, ['position', 'radius', 'flags'] , return_graph=True)
  mask=myutils.bbitwise_and(graph['flags'], krebsutils.CIRCULATED)
  print(mask.shape)
  graph = graph.get_filtered(edge_indices = mask)
  print('vessels filtered before fraction calculation!')
  theRadii = np.asarray(graph['radius'])*scaling
  if(theRadii.ndim>1):
  	theRadii = theRadii[:,0]
  if theRadii.dtype == np.float32: 
    thePositions = np.asarray(graph['position'],dtype=np.float32)*scaling
  else:
    thePositions = np.asarray(graph['position'])*scaling
 
  theEdgeList = np.asarray(graph.edgelist)
  if sys.flags.debug:
    print(thePositions)
    print(thePositions.shape)
    print(type(thePositions))
    print("thepos: %s" % thePositions.dtype)

    print(theEdgeList)
    print(theEdgeList.shape)
    print(type(theEdgeList))
    print("theEd: %s" % theEdgeList.dtype)

    print(theRadii)
    print(theRadii.shape)
    print(type(theRadii))
    print('theRadii: %s' % theRadii.dtype)

    print(ld)
    print(type(ld))
    print(ld.GetScale())
    print(type(samples_per_cell))
  
  vessel_fraction = krebsutils.make_vessel_volume_fraction_field(thePositions,theEdgeList,theRadii,ld,samples_per_cell)
  
  return vessel_fraction
Пример #14
0
 def write(gmeasure, groupname):
     graph = dataman.obtain_data(
         'vessel_graph', vesselgroup,
         ['position', 'radius', 'flags', 'pressure'])
     graph = graph.get_filtered(
         myutils.bbitwise_and(graph['flags'],
                              krebsutils.CIRCULATED))
     edgevalues = graph['pressure']
     edgevalues = edgevalues[graph.edgelist]
     # main calculation
     thefield = krebsutils.CalcIntervascularInterpolationField(
         graph.edgelist, graph['radius'], graph['position'],
         edgevalues, fieldLdFine, 1.)
     del edgevalues
     # gradient of the interpolated blood pressure
     thegrad = scipy.ndimage.gaussian_filter(thefield,
                                             1.0,
                                             0,
                                             mode='nearest')
     gradfield_ = krebsutils.field_gradient(thegrad)
     thegrad = np.sum([np.square(g) for g in gradfield_], axis=0)
     thegrad = np.sqrt(thegrad)
     del gradfield_, thefield
     # now we scale down the highres version, TODO: make it work with other than 3 dimensions
     # first local average
     m = self.fine_bin_subdivision
     kernel = np.ones((m, m, m), dtype=np.float32)
     thegrad = scipy.signal.fftconvolve(thegrad,
                                        kernel,
                                        mode='valid')
     # then pick every m'th which contains the average of m finer boxes combined
     thegrad = np.ascontiguousarray(thegrad[::m, ::m, ::m])
     assert all(thegrad.shape == fieldLd.shape)
     gmeasure.create_dataset(groupname,
                             data=thegrad,
                             compression=9,
                             dtype=np.float32)
Пример #15
0
import scipy.ndimage as ndimage

if __name__ == '__main__':
    filename = sys.argv[1]
    grouppath = sys.argv[2]

    with h5py.File(filename, 'r') as file:
        vesselgroup = file[grouppath]
        ldvessels = krebsutils.read_lattice_data_from_hdf(
            vesselgroup['lattice'])
        wbbox = ldvessels.worldBox

        graph = krebsutils.read_vesselgraph(
            vesselgroup, ['position', 'radius', 'flags', 'pressure'])
        graph = graph.get_filtered(
            myutils.bbitwise_and(graph['flags'], krebsutils.CIRCULATED))

    fieldld = krebsutils.SetupFieldLattice(wbbox, 3, 50., 0.)
    print fieldld

    edgevalues = graph['pressure']
    edgevalues = edgevalues[graph.edgelist]

    thefield = krebsutils.CalcIntervascularInterpolationField(
        graph.edgelist, graph['radius'], graph['position'], edgevalues,
        fieldld, 1.)
    volfraction = krebsutils.make_vessel_volume_fraction_field(
        graph['position'], graph.edgelist, graph['radius'], fieldld, 5)
    thegrad = ndimage.gaussian_filter(thefield, 1.0, 0, mode='nearest')
    gradfield_ = krebsutils.field_gradient(thegrad)
    thegrad = np.sum([np.square(g) for g in gradfield_], axis=0)
Пример #16
0
def make_any_color_arrays(vesselgraph, data_name):
    edges = vesselgraph.edgelist
    num_nodes = len(vesselgraph.nodes['position'])
    flags = vesselgraph.edges['flags']
    nflags = krebsutils.edge_to_node_property(num_nodes, edges, flags, 'or')

    mask = myutils.bbitwise_and(flags, krebsutils.CIRCULATED)
    nmask = myutils.bbitwise_and(nflags, krebsutils.CIRCULATED)

    if data_name in vesselgraph.edges:
        edgedata = vesselgraph.edges[data_name]
        nodedata = krebsutils.edge_to_node_property(num_nodes, edges, edgedata,
                                                    'avg')
    else:
        nodedata = vesselgraph.nodes[data_name]
        edgedata = np.average((nodedata[edges[:, 0]], nodedata[edges[:, 1]]),
                              axis=0)

    gray = np.asarray((0.1, 0.1, 0.1))
    edgecolors = np.repeat(gray.reshape(1, -1), len(edgedata), axis=0)
    nodecolors = np.repeat(gray.reshape(1, -1), len(nodedata), axis=0)
    #colors = lambda arr: cm.to_rgba(arr)[:,:3]
    colors = lambda arr: np.power(cm.to_rgba(arr)[:, :3], 2.4)

    if data_name == 'hematocrit':
        cm = matplotlib.cm.ScalarMappable(cmap=cm_hematocrit)
        cm.set_clim(0, 1)
        unmapped_range = (0., 1.)
        edgecolors[mask] = colors(edgedata[mask])
        nodecolors[nmask] = colors(nodedata[nmask])
    elif data_name == 'pressure':
        p0 = np.amin(nodedata)
        p1 = np.amax(nodedata)
        unmapped_range = (p0, p1)
        cm = matplotlib.cm.ScalarMappable(cmap=cm_redblue)
        cm.set_clim(p0, p1)
        edgecolors[mask] = colors(edgedata[mask])
        nodecolors[nmask] = colors(nodedata[nmask])
    elif data_name == 'shearforce':
        mask = mask & (edgedata > 0)
        nmask = nmask & (nodedata > 0)
        edgedata = edgedata[mask]
        nodedata = nodedata[nmask]
        unmapped_range = edgedata.min(), edgedata.max()
        edgedata = np.log10(edgedata)
        nodedata = np.log10(nodedata)
        p0 = -4  #np.amin(edgedata)
        p1 = -1  #np.amax(edgedata)
        cm = matplotlib.cm.ScalarMappable(cmap=matplotlib.cm.spectral)
        cm.set_clim(p0, p1)
        edgecolors[mask] = colors(edgedata)
        nodecolors[nmask] = colors(nodedata)
    elif data_name == 'flow':
        mask = mask & (edgedata > 0)
        nmask = nmask & (nodedata > 0)
        edgedata = edgedata[mask]
        nodedata = nodedata[nmask]
        unmapped_range = edgedata.min(), edgedata.max()
        edgedata = np.log10(edgedata)
        nodedata = np.log10(nodedata)
        p0 = np.floor(np.amin(edgedata))
        p1 = np.ceil(np.amax(edgedata))
        cm = matplotlib.cm.ScalarMappable(cmap=matplotlib.cm.jet)
        cm.set_clim(p0, p1)
        edgecolors[mask] = colors(edgedata)
        nodecolors[nmask] = colors(nodedata)
    elif data_name == 'flags':
        unmapped_range = (0., 1.)
        mask = mask & (edgedata > 0)
        nmask = nmask & (nodedata > 0)
        edgedata = edgedata[mask]
        nodedata = nodedata[nmask]
        edgedata = np.bitwise_and(edgedata, krebsutils.ARTERY)
        cm = matplotlib.cm.ScalarMappable(cmap=matplotlib.cm.jet)
        edgecolors[mask] = colors(edgedata)
        nodecolors[nmask] = colors(nodedata)
    vesselgraph.edges['colors'] = edgecolors
    vesselgraph.nodes['colors'] = nodecolors
    return cm, unmapped_range
Пример #17
0
def InsertGraphColors(vesselgraph, po2field, data_name):
    edges = vesselgraph.edgelist
    if type(vesselgraph.nodes['position']) is tuple:
        num_nodes = len(vesselgraph.nodes['position'][0])
    else:
        num_nodes = len(vesselgraph.nodes['position'])

    if data_name in vesselgraph.edges:
        edgedata = data = vesselgraph.edges[data_name]
        nodedata = krebsutils.edge_to_node_property(num_nodes, edges, data,
                                                    'avg')
    else:
        nodedata = data = vesselgraph.nodes[data_name]
        edgedata = np.average((data[edges[:, 0]], data[edges[:, 1]]), axis=0)

    if data_name == 'po2_vessels':
        try:
            p1 = np.amax(data)
        except ValueError:
            print("p1 not found")
            pass
        if po2field is not None:
            p1 = max(p1, np.amax(po2field))
        try:
            p0 = np.amin(data)
        except ValueError:
            print("p0 not found")
            pass
        if po2field is not None:
            p0 = min(p0, np.amin(po2field))
        #p1 = math.ceil(p1/10.0)*10.0  # round to powers of something
        #p1 = 100.0
        value_range = (p0, p1)
        cm = matplotlib.cm.ScalarMappable(cmap=cm_po2)
    elif data_name == 'saturation':
        cm = matplotlib.cm.ScalarMappable(cmap=matplotlib.cm.Spectral)
        vesselgraph.edges['saturation']
        value_range = (np.min(vesselgraph.edges['saturation']),
                       np.max(vesselgraph.edges['saturation']))
        #value_range = (0,1.)
    elif data_name == 'hboconc':
        cm = matplotlib.cm.ScalarMappable(cmap=matplotlib.cm.gnuplot)
        p1 = math.ceil(np.amax(data))
        value_range = (0., p1)
    cm.set_clim(*value_range)

    colors = lambda arr: np.power(cm.to_rgba(arr)[:, :3], 2.4)
    if data_name in vesselgraph.edges:
        edgecolors = colors(data)
        nodecolors = colors(nodedata)
    else:
        edgecolors = colors(edgedata)
        nodecolors = colors(data)

    flags = vesselgraph.edges['flags']
    nflags = krebsutils.edge_to_node_property(num_nodes, edges, flags, 'or')
    #is_not_set = lambda flags_,flag: np.bitwise_not(np.asarray(np.bitwise_and(flags_, flag), np.bool))
    gray = np.asarray((0.3, 0.3, 0.3))
    circulated = myutils.bbitwise_and(flags, krebsutils.CIRCULATED)
    uncirculated = np.logical_not(circulated)
    node_circulated = myutils.bbitwise_and(nflags, krebsutils.CIRCULATED)
    node_uncirculated = np.logical_not(node_circulated)
    #nuncirculated = is_not_set(nflags,krebsutils.CIRCULATED)
    edgecolors[uncirculated] = gray
    nodecolors[node_uncirculated] = gray

    print 'colormap range ', cm.get_clim()

    vesselgraph.edges['colors'] = edgecolors
    vesselgraph.nodes['colors'] = nodecolors
    return cm
Пример #18
0
def RemoveArteriovenousFlagsFromCapillaries(flags):
  capil_mask = myutils.bbitwise_and(flags, krebsutils.CAPILLARY)
  flags[capil_mask] = np.bitwise_and(flags[capil_mask], np.asarray(~(krebsutils.ARTERY | krebsutils.VEIN), dtype=flags.dtype))
  return flags
Пример #19
0
            def write(gmeasure, measurename):
                assert prop == measurename
                gvessels, gtumor = detailedo2.OpenVesselAndTumorGroups(
                    po2group)
                if prop in ['po2', 'sat', 'gtv', 'jtv']:
                    w = dataman.obtain_data('basic_vessel_samples', 'weight',
                                            gvessels, sample_length)
                    d = dataman.obtain_data('detailedPO2_samples', prop,
                                            po2group, sample_length, 1,
                                            samplelocation)
                    gmeasure.create_dataset(prop,
                                            data=myutils.WeightedAverageStd(
                                                d, weights=w))
                elif prop in ['sat_vein', 'sat_capi', 'sat_art']:
                    w = dataman.obtain_data('basic_vessel_samples', 'weight',
                                            gvessels, sample_length)
                    d = dataman.obtain_data('detailedPO2_samples', 'sat',
                                            po2group, sample_length, 1,
                                            samplelocation)
                    f = dataman.obtain_data('basic_vessel_samples', 'flags',
                                            gvessels, sample_length)
                    mask = ~myutils.bbitwise_and(
                        f, krebsutils.WITHIN_TUMOR) & myutils.bbitwise_and(
                            f, krebsutils.CIRCULATED)
                    m = {
                        'sat_vein': krebsutils.VEIN,
                        'sat_capi': krebsutils.CAPILLARY,
                        'sat_art': krebsutils.ARTERY
                    }
                    mask &= myutils.bbitwise_and(f, m[prop])
                    d, w = d[mask], w[mask]
                    gmeasure.create_dataset(prop,
                                            data=myutils.WeightedAverageStd(
                                                d, weights=w))
                elif prop in [
                        'e1', 'e2', 'e3', 'Jin_root', 'Jout_root', 'Jout_tv',
                        'tv_cons', 'Jout_cons'
                ]:
                    d = dataman.obtain_data('detailedPO2_total_fluxes', prop,
                                            po2group, sample_length, 1,
                                            samplelocation)
                    gmeasure.create_dataset(prop, data=[d[prop], 0])
                elif prop == 'po2_tissue':
                    _, po2ld, po2field, parameters = dataman.obtain_data(
                        'detailedPO2', po2group)
                    d = myutils.largeDatasetAverageAndStd(po2field)
                    gmeasure.create_dataset(prop, data=d)
                elif prop == 'mro2':
                    uptakefield = detailedo2.computeO2Uptake(po2group, gtumor)
                    d = myutils.largeDatasetAverageAndStd(uptakefield)
                    gmeasure.create_dataset(prop, data=d)
                elif prop in ('sat_via_hb_ratio', 'vfhb_oxy', 'vfhb_deoxy',
                              'vfhb'):
                    weight = dataman.obtain_data('basic_vessel_samples',
                                                 'weight', gvessels,
                                                 sample_length)
                    flags = dataman.obtain_data('basic_vessel_samples',
                                                'flags', gvessels,
                                                sample_length)
                    mask = myutils.bbitwise_and(flags, krebsutils.CIRCULATED)
                    hema = dataman.obtain_data('basic_vessel_samples',
                                               'hematocrit', gvessels,
                                               sample_length)[mask]
                    sat = dataman.obtain_data('detailedPO2_samples', 'sat',
                                              po2group, sample_length, None,
                                              samplelocation)[mask]
                    rad = dataman.obtain_data('basic_vessel_samples', 'radius',
                                              gvessels, sample_length)[mask]
                    weight = weight[mask]
                    hbvolume = weight * rad * rad * math.pi * hema
                    ld = krebsutils.read_lattice_data_from_hdf(
                        po2group['field_ld'])
                    volume = np.product(ld.GetWorldSize())
                    if prop == 'sat_via_hb_ratio':
                        result = np.sum(hbvolume * sat) / np.sum(hbvolume)
                    elif prop == 'vfhb_oxy':
                        result = np.sum(hbvolume * sat) / volume
                    elif prop == 'vfhb_deoxy':
                        result = np.sum(hbvolume * (1. - sat)) / volume
                    elif prop == 'vfhb':
                        result = np.sum(hbvolume) / volume
                    gmeasure.create_dataset(prop, data=[result, 0.])
                elif prop in ('chb_oxy', 'chb_deoxy', 'chb'):
                    m = {
                        'chb_oxy': 'vfhb_oxy',
                        'chb_deoxy': 'vfhb_deoxy',
                        'chb': 'vfhb'
                    }
                    result = dataman.obtain_data('detailedPO2_global', m[prop],
                                                 po2group, sample_length,
                                                 cachelocation)
                    result = result * detailedo2.chb_of_rbcs
                    gmeasure.create_dataset(prop, data=[result, 0.])
                elif prop == 'mro2_by_j':
                    fluxes = dataman.obtain_data('detailedPO2_total_fluxes',
                                                 prop, po2group, sample_length,
                                                 1)
                    ld = krebsutils.read_lattice_data_from_hdf(
                        po2group['field_ld'])
                    worldbb = ld.worldBox
                    result = fluxes['Jout_tv'] / np.prod(worldbb[1] -
                                                         worldbb[0]) * 1.e12
                    gmeasure.create_dataset(prop, data=[result, 0.])
                elif prop == 'oef':
                    fluxes = dataman.obtain_data('detailedPO2_total_fluxes',
                                                 prop, po2group, sample_length,
                                                 1, samplelocation)
                    result = (fluxes['Jin_root'] -
                              fluxes['Jout_root']) / fluxes['Jin_root']
                    gmeasure.create_dataset(prop, data=[result, 0.])

                else:
                    assert False
Пример #20
0
            def write(gmeasure, name):
                gvessels, gtumor = detailedo2.OpenVesselAndTumorGroups(
                    po2group)
                weight_smpl = dataman.obtain_data('basic_vessel_samples',
                                                  'weight', gvessels,
                                                  sample_length)
                flags = dataman.obtain_data('basic_vessel_samples', 'flags',
                                            gvessels, sample_length)
                # get teh radial distance function (either distance from tumor border or distance from center)
                dist_smpl, distmap, mask, tumor_ld = dataman.obtain_data(
                    'distancemap_samples', gvessels, gtumor, sample_length,
                    distance_distribution_name, None)
                # tumor_ld might actually be a unrelated lattice

                #filter uncirculated
                mask = mask & myutils.bbitwise_and(flags,
                                                   krebsutils.CIRCULATED)
                dist_smpl = dist_smpl[mask]
                weight_smpl = weight_smpl[mask]

                bins = bins_spec.arange()
                gmeasure = gmeasure.create_group(name)

                for name in ['po2', 'extpo2', 'jtv', 'sat', 'gtv', 'dS_dx']:
                    smpl = dataman.obtain_data('detailedPO2_samples', name,
                                               po2group, sample_length, None,
                                               samplelocation)
                    myutils.MeanValueArray.fromHistogram1d(
                        bins, dist_smpl, smpl[mask],
                        w=weight_smpl).write(gmeasure, name)
                del smpl

                _, po2ld, po2field, parameters = dataman.obtain_data(
                    'detailedPO2', po2group)
                po2field = krebsutils.resample_field(np.asarray(po2field),
                                                     po2ld.worldBox,
                                                     tumor_ld.shape,
                                                     tumor_ld.worldBox,
                                                     order=1,
                                                     mode='nearest')
                myutils.MeanValueArray.fromHistogram1d(bins, distmap.ravel(),
                                                       po2field.ravel()).write(
                                                           gmeasure,
                                                           'po2_tissue')
                del po2field

                uptakefield = detailedo2.computeO2Uptake(po2group, gtumor)
                uptakefield = krebsutils.resample_field(uptakefield,
                                                        po2ld.worldBox,
                                                        tumor_ld.shape,
                                                        tumor_ld.worldBox,
                                                        order=1,
                                                        mode='nearest')
                myutils.MeanValueArray.fromHistogram1d(
                    bins, distmap.ravel(),
                    uptakefield.ravel()).write(gmeasure, 'mro2')
                del uptakefield

                hema = dataman.obtain_data('basic_vessel_samples',
                                           'hematocrit', gvessels,
                                           sample_length)[mask]
                sat = dataman.obtain_data('detailedPO2_samples', 'sat',
                                          po2group, sample_length, None,
                                          samplelocation)[mask]
                rad = dataman.obtain_data('basic_vessel_samples', 'radius',
                                          gvessels, sample_length)[mask]
                hbvolume = weight_smpl * rad * rad * math.pi * hema
                vol_per_bin = myutils.MeanValueArray.fromHistogram1d(
                    bins, distmap.ravel(), np.ones_like(
                        distmap.ravel())).cnt * (tumor_ld.scale**3)
                tmp = myutils.MeanValueArray.fromHistogram1d(
                    bins, dist_smpl, hbvolume * sat)
                tmp.cnt = vol_per_bin.copy()
                tmp.write(gmeasure, 'vfhb_oxy')
                tmp = myutils.MeanValueArray.fromHistogram1d(
                    bins, dist_smpl, hbvolume * (1. - sat))
                tmp.cnt = vol_per_bin.copy()
                tmp.write(gmeasure, 'vfhb_deoxy')
                del tmp, hbvolume, vol_per_bin
Пример #21
0
 def write(gmeasure, groupname):
   ld = krebsutils.read_lattice_data_from_hdf(vesselgroup['lattice'])
   volume = np.prod(ld.GetWorldSize())
   if property_name == 'mvd_linedensity':
     graph = dataman.obtain_data('vessel_graph', vesselgroup, ['length'])
     l = np.asarray(graph['length'], dtype=np.float64)
     data  = (np.sum(l) / volume, 0.)
     data  = [d*1e6 for d in data] #from 1/mum^2 to 1/mm^2
   elif property_name in 'phi_vessels phi_a phi_v phi_c'.split():
     from analyzeBloodVolumeSimple import cylinderCollectionVolumeDensity
     phi_vessels, phi_a, phi_v, phi_c = cylinderCollectionVolumeDensity(vesselgroup)
     if property_name == 'phi_vessels':
       data = [phi_vessels, 0.]
     if property_name == 'phi_a':
       data = [phi_a, 0.]
     if property_name == 'phi_v':
       data = [phi_v, 0.]
     if property_name == 'phi_c':
       data = [phi_c, 0.]
   elif property_name in 'mvd mvd_a mvd_v mvd_c'.split():
     from analyzeBloodVolumeSimple import cylinderCollectionLineDensity
     mvd, mvd_a, mvd_v, mvd_c = cylinderCollectionLineDensity(vesselgroup)
     if property_name == 'mvd':
       data = [mvd, 0.]
     if property_name == 'mvd_a':
       data = [mvd_a, 0.]
     if property_name == 'mvd_v':
       data = [mvd_v, 0.]
     if property_name == 'mvd_c':
       data = [mvd_c, 0.]
   elif property_name == 'mvd_sphere_sampling':
     ld = krebsutils.read_lattice_data_from_hdf(vesselgroup.parent['field_ld'])
     mvd_sampling_results, mvd_bins = dataman.obtain_data('sphere_vessel_density',  vesselgroup, None, suggest_bins_from_world(ld), 'radial', ld, cachelocation )
       #print(mvd_sampling_results)    
     data = [ np.mean(np.asarray(mvd_sampling_results)*1e6),
             np.std(np.asarray(mvd_sampling_results)*1e6)]
   elif property_name == 'avg_cap_dist':
     vessels = krebsutils.read_vesselgraph(vesselgroup, ['flags', 'length','radius'])
     flags   = RemoveArteriovenousFlagsFromCapillaries(vessels['flags'])
     mask1 = myutils.bbitwise_and(flags, krebsutils.CIRCULATED)
     #totalvol = totalLdVolume(vesselgroup)          
     def compute(flagMask):
       if flagMask:
         mask = mask1 & myutils.bbitwise_and(flags, flagMask)
       else:
         mask = mask1
       length = np.asarray(vessels['length'][mask], dtype = np.float64)
       total = np.sum(length)
       return total/volume
     '''luedemann et. al. assume capillaries are vessels
     smaller than this:
       see manuscript draft
     '''
     mvd_cap = compute((vessels['radius']<=4.0).all())
     data = (np.sqrt(1/mvd_cap), 0.)
   elif property_name == 'phi_vessels':
     graph = dataman.obtain_data('vessel_graph', vesselgroup, ['length','radius'])
     l = np.asarray(graph['length'], dtype=np.float64)
     r = np.asarray(graph['radius'], dtype=np.float64)
     data = l*np.square(r)*math.pi
     data = (np.sum(data) / volume, 0.)
   elif property_name == 'total_perfusion':
     data = getTotalPerfusion([vesselgroup])*60 #to minutes
   else:
     data   = dataman.obtain_data('basic_vessel_samples', property_name, vesselgroup, 30.)
     weight = dataman.obtain_data('basic_vessel_samples', 'weight', vesselgroup, 30.)
     data = myutils.WeightedAverageStd(data, weights=weight)
   gmeasure.create_dataset(groupname, data = data)
Пример #22
0
def render_different_data_types(vesselgroup,
                                tumorgroup,
                                imagefn,
                                options,
                                cell_group=None):
    filenamepostfix = ''
    labels = {
        'flow': '$log_{10}$ Flow Rate',
        'shearforce': '$log_{10}$ Shear Force',
        'hematocrit': 'Hematocrit',
        'pressure': 'Blood Pressure $kPa$',
        'S_tot': 'Adaption Signal',
        'conductivitySignal': 'Conductivity Signal',
        'metabolicSignal': 'Metabolic Signal',
        'radius': 'Vesselradius $\mu$m',
    }
    graph = krebsutils.read_vessels_from_hdf(
        vesselgroup,
        ['position', 'flags', 'radius', 'nodeflags'] + options.datalist,
        return_graph=True)

    options.wbbox = povrayRenderVessels.ComputeBoundingBox(vesselgroup, graph)
    if options.filteruncirculated:
        graph = graph.get_filtered(edge_indices=myutils.bbitwise_and(
            graph['flags'], krebsutils.CIRCULATED))
    if options.filterradiushighpass > 0:
        graph = graph.get_filtered(
            edge_indices=graph['radius'] > filterradiushighpass)
        filenamepostfix = '_rhp'
    if options.filterradiuslowpass > 0:
        print("lowpass filter activated:")
        graph = graph.get_filtered(
            edge_indices=graph['radius'] < filterradiuslowpass)
        filenamepostfix = '_rlp'
    for data_name in options.datalist:
        if 'colorfactory' in options:
            print('colorfactory in options')
            colors_factory = options.colorfactory
            colors_factory(graph)

        cm, (datamin, datamax) = povrayRenderVessels.make_any_color_arrays(
            graph, data_name, options)
        fn = vesselgroup.file.filename
        if cell_group is not None and options.cells:
            options.imageFileName = splitext(
                basename(fn)
            )[0] + '_' + myutils.sanitize_posixpath(vesselgroup.name).replace(
                '/', '-'
            ) + '_' + data_name + '_cell_' + options.cellsProperty + '_' + filenamepostfix  #+'.'+ options.format
        else:
            options.imageFileName = splitext(
                basename(fn)
            )[0] + '_' + myutils.sanitize_posixpath(vesselgroup.name).replace(
                '/',
                '-') + '_' + data_name + filenamepostfix  #+'.'+ options.format
        with povrayEasy.EasyPovRayRender(options) as epv:
            povrayEasy.CreateScene2(vesselgroup, epv, graph, options)
            if options.noOverlay:
                epv.render(options.imageFileName)
            else:
                if cell_group and options.cells:
                    cells_cm = povrayRenderCells.addVBLCells(
                        epv, options.cellsProperty, cell_group, options)
                    povrayEasy.RenderImageWithOverlay(epv,
                                                      cm,
                                                      labels[data_name],
                                                      options,
                                                      colormap_cells=cells_cm)
                else:
                    povrayEasy.RenderImageWithOverlay(epv, cm,
                                                      labels[data_name],
                                                      options)
Пример #23
0
def renderScene(vesselgroup, tumorgroup, imagefn, options):
    if vesselgroup is not None:
        vgrp = vesselgroup['lattice']
        wbbox = krebsutils.read_lattice_data_from_hdf_by_filename(
            str(vgrp.file.filename), str(vgrp.name)).worldBox
    else:
        wbbox = krebsutils.read_lattice_data_from_hdf(
            tumorgroup.file['field_ld']).worldBox
    trafo = calc_centering_normalization_trafo(wbbox)
    zsize = (wbbox[5] - wbbox[4])

    vessel_ld = krebsutils.read_lattice_data_from_hdf_by_filename(
        str(vesselgroup.file.filename),
        str(vesselgroup.name) + '/lattice')
    options.wbbox = vessel_ld.GetWorldBox()

    with EasyPovRayRender(options) as epv:
        epv.setBackground(options.background)
        cam = options.cam
        if cam in ('topdown', 'topdown_slice'):
            cam_fov = 60.
            cam_distance_factor = options.cam_distance_multiplier * ComputeCameraDistanceFactor(
                cam_fov, options.res, wbbox)
            epv.addLight(10 * Vec3(1.7, 1.2, 2),
                         1.,
                         area=(4, 4, 3, 3),
                         jitter=True)
            if cam == 'topdown_slice':
                imagefn += '_slice'
                options.vessel_clip = ('zslice', -201 * trafo.w, 201 * trafo.w)
                options.tumor_clip = ('zslice', -100 * trafo.w, 100 * trafo.w)
                epv.setCamera(
                    (0, 0, cam_distance_factor * 0.5 * (200. * trafo.w + 2.)),
                    (0, 0, 0),
                    cam_fov,
                    up='y')
            else:
                imagefn += '_top'
                epv.setCamera(
                    (0, 0, cam_distance_factor * 0.5 * (zsize * trafo.w + 2.)),
                    (0, 0, 0),
                    cam_fov,
                    up='y')
        else:
            imagefn += '_pie'
            cam_fov = 60.
            basepos = options.cam_distance_multiplier * np.asarray(
                (0.6, 0.7, 0.55)) * (1. / 1.4) * math.tan(
                    math.pi * 0.25) / math.tan(math.pi / 180. / 2. * cam_fov)
            epv.setCamera(basepos, (0, 0, 0), cam_fov, up=(0, 0, 1))
            num_samples_large_light = 4
            num_samples_small_light = 2
            epv.addLight(10 * Vec3(0.7, 1., 0.9),
                         0.8,
                         area=(1., 1., num_samples_small_light,
                               num_samples_small_light),
                         jitter=True)
            epv.addLight(10 * Vec3(0.5, 0.5, 0.5),
                         0.6,
                         area=(5., 5., num_samples_large_light,
                               num_samples_large_light),
                         jitter=True)
            options.vessel_clip = ('pie', 0.)
            options.tumor_clip = ('pie', -50 * trafo.w)

        if vesselgroup is not None:
            graph = krebsutils.read_vessels_from_hdf(
                vesselgroup, ['position', 'flags', 'radius', 'pressure'],
                return_graph=True)
            if options.filteruncirculated:
                graph = graph.get_filtered(edge_indices=myutils.bbitwise_and(
                    graph['flags'], krebsutils.CIRCULATED))
            if 'colorfactory' in options:
                print('colorfactory is in options')
                colorfactory = options.colorfactory
            else:
                print('colorfactory not in options')
                colorfactory = make_pressure_color_arrays
            colorfactory(graph)
            #addVesselTree(epv, graph, trafo, vesselgroup = vesselgroup, options)
            epv.addVesselTree2(epv, graph, trafo, options)

        if tumorgroup is not None and 'conc' in tumorgroup:
            addBulkTissueTumor(epv, tumorgroup, trafo, options)

        if (tumorgroup is not None
                and tumorgroup.attrs['TYPE'] == 'faketumor'):
            print('nix')

        if options.noOverlay:
            epv.render(imagefn + '.png')
        else:
            povrayEasy.RenderImageWithOverlay(epv, imagefn + '.png', None,
                                              'tumor', options)
Пример #24
0
                            'position', 'radius', 'hematocrit', 'pressure',
                            'flow', 'flags', 'shearforce', 'nodeflags',
                            'edge_boundary'
                        ] + datalist,
                        return_graph=True)
                else:
                    graph = krebsutils.read_vessels_from_hdf(
                        vesselgroup,
                        [
                            'position', 'radius', 'hematocrit', 'pressure',
                            'flow', 'flags', 'shearforce'
                        ] + datalist,
                        return_graph=True)
                if goodArguments.filteruncirculated:
                    graph = graph.get_filtered(
                        edge_indices=myutils.bbitwise_and(
                            graph['flags'], krebsutils.CIRCULATED))
                writeVessels_(graph, goodArguments)

            elif 'out' in d:
                vesselgroup = f[join('/', d + '/vessels')]['.']
                if '/parameters' in f:
                    useConstO2 = f['/parameters'].attrs['useConstO2']
                    # comes as string
                    useConstO2 = bool(useConstO2)
                else:
                    useConstO2 = False

                if useConstO2:
                    ''' the po2_node will not be present in this case '''
                    graph = krebsutils.read_vessels_from_hdf(
                        vesselgroup,
Пример #25
0
    dirs = myutils.walkh5(f['/'], pattern)
    if goodArguments.outfn:
      print("you chose: %s as outfilename" % goodArguments.outfn)
      goodArguments.outfn = goodArguments.outfn + '_%s.vtk'
    else:
      goodArguments.outfn = outfn = "%s-%%s.vtk" % (os.path.splitext(os.path.basename(fn))[0])
    for d in dirs:
      if 'vessels' in d and 'po2' not in d:
        vesselgroup = f[join('/',d)]['.']
        new = False
        if new:
          graph = krebsutils.read_vessels_from_hdf(vesselgroup, ['position', 'radius', 'hematocrit', 'pressure', 'flow', 'flags','shearforce','nodeflags','edge_boundary'] + datalist, return_graph=True)
        else:
          graph = krebsutils.read_vessels_from_hdf(vesselgroup, ['position', 'radius', 'hematocrit', 'pressure', 'flow', 'flags','shearforce'] + datalist, return_graph=True)
        if goodArguments.filteruncirculated:
          graph = graph.get_filtered(edge_indices = myutils.bbitwise_and(graph['flags'], krebsutils.CIRCULATED))      
        writeVessels_(graph, goodArguments)

      elif 'out' in d:
        vesselgroup = f[join('/',d+'/vessels')]['.']
        new = False
        if new:
          graph = krebsutils.read_vessels_from_hdf(vesselgroup, ['position', 'radius', 'hematocrit', 'pressure', 'flow', 'flags','shearforce','nodeflags','edge_boundary'] + datalist, return_graph=True)
        else:
          graph = krebsutils.read_vessels_from_hdf(vesselgroup, ['position', 'radius', 'hematocrit', 'pressure', 'flow', 'flags','shearforce'] + datalist, return_graph=True)
        if goodArguments.filteruncirculated:
          graph = graph.get_filtered(edge_indices = myutils.bbitwise_and(graph['flags'], krebsutils.CIRCULATED))
        hdftumor2vtk(graph, goodArguments)
      elif 'po2' in d:
        #vesselgroup = f[join('/',d+'/vessels')]['.']
        if 'adaption' in d:
Пример #26
0
def sample_vessel_system(goodArguments):
    filename = goodArguments.vesselFileNames
    grouppath = goodArguments.grp_pattern

    with h5py.File(filename, 'r') as file:
        if ('vessels' in grouppath):
            print('found vessels!')
            vesselgroup = file[grouppath]
        else:
            if ('out' in grouppath):
                outgroup = file[grouppath]
                print('found tumor of type: %s' %
                      str(outgroup['tumor'].attrs.get('TYPE')))
                vesselgroup = file[grouppath + '/vessels']
            else:
                print("unknown data structure!")
        ldvessels = krebsutils.read_lattice_data_from_hdf(
            vesselgroup['lattice'])
        wbbox = ldvessels.worldBox

        graph = krebsutils.read_vesselgraph(vesselgroup, ['position', 'flags'])
        graph = graph.get_filtered(
            myutils.bbitwise_and(graph['flags'], krebsutils.CIRCULATED))

    print 'vessel ld:'
    print ldvessels
    ''' this splits splits space in lattices of 300.
      the second 300 adds a 'safety layer of 100. mum
      so we do not consider the outermost data for calculating the
      actual mvd
  '''
    sampling_lattice_spacing = goodArguments.sampling_lattice_spacing
    fieldld = krebsutils.SetupFieldLattice(wbbox, 3, sampling_lattice_spacing,
                                           100.)
    wbbox = fieldld.worldBox
    print 'field ld:'
    print fieldld
    z = fieldld.shape[2] / 2

    longitudinal_sampling_distance = goodArguments.longitudinal
    weights = krebsutils.sample_edges_weights(graph.nodes['position'],
                                              graph.edgelist,
                                              longitudinal_sampling_distance)
    positions = krebsutils.sample_edges(
        graph.nodes['position'], graph.edgelist, graph.nodes['position'],
        longitudinal_sampling_distance,
        krebsutils.VesselSamplingFlags.DATA_PER_NODE
        | krebsutils.VesselSamplingFlags.DATA_LINEAR)

    eps = 1.0 - 1.e-15
    x0, x1, y0, y1, z0, z1 = wbbox
    ranges = [
        np.arange(x0, x1, fieldld.scale * eps),
        np.arange(y0, y1, fieldld.scale * eps),
        np.arange(z0, z1, fieldld.scale * eps),
    ]
    print 'histogram bin ends:', map(lambda r: (r.min(), r.max()), ranges)
    mvd, _ = np.histogramdd(positions, bins=ranges, weights=weights)
    mvd *= 1.e6 / (fieldld.scale**3)
    print 'result shape:', mvd.shape
    print('average mvd')
    print(np.mean(mvd[1:-1, 1:-1, 1:-1]))
    ''' new stuff '''
    from scipy import ndimage

    bool_field = mvd > 0
    bool_field = np.logical_not(bool_field)
    distance_map = ndimage.morphology.distance_transform_edt(bool_field)
    distance_map = distance_map * sampling_lattice_spacing

    #  fig, ax = pyplot.subplots(1)
    #  plt = ax.imshow(mvd[:,:,z], interpolation = 'none')
    #  ax.set(title = 'MVD')
    #  divider = mpl_utils.make_axes_locatable(ax)
    #  cax = divider.append_axes("right", size = "5%", pad = 0.05)
    #  fig.colorbar(plt, cax = cax)

    fig, ax = pyplot.subplots(1)
    plt = ax.imshow(distance_map[:, :, z], interpolation='none')
    #ax.set(title = 'Distance Map \n group: %s, file: %s' %(grouppath, filename))
    ax.set(title='Distance Map \n smp_logitudinal: %s, lattice_const: %s' %
           (longitudinal_sampling_distance, sampling_lattice_spacing))
    divider = mpl_utils.make_axes_locatable(ax)
    cax = divider.append_axes("right", size="5%", pad=0.05)
    fig.colorbar(plt, cax=cax)
    basename(filename)
    with PdfPages('distmap_' + basename(filename) + '_' + grouppath +
                  '.pdf') as pdf:
        pdf.savefig(fig)
Пример #27
0
def make_any_color_arrays(vesselgraph, data_name):
    edges = vesselgraph.edgelist
    num_nodes = len(vesselgraph.nodes['position'])
    flags = vesselgraph.edges['flags']
    flags = np.asarray(flags, dtype='uint32')
    nflags = krebsutils.edge_to_node_property(num_nodes, edges, flags, 'or')

    mask = myutils.bbitwise_and(flags, krebsutils.CIRCULATED)
    nmask = myutils.bbitwise_and(nflags, krebsutils.CIRCULATED)

    if data_name in vesselgraph.edges:
        edgedata = vesselgraph.edges[data_name]
        nodedata = krebsutils.edge_to_node_property(num_nodes, edges, edgedata,
                                                    'avg')
    else:
        nodedata = vesselgraph.nodes[data_name]
        edgedata = np.average((nodedata[edges[:, 0]], nodedata[edges[:, 1]]),
                              axis=0)

    gray = np.asarray((0.1, 0.1, 0.1))
    edgecolors = np.repeat(gray.reshape(1, -1), len(edgedata), axis=0)
    nodecolors = np.repeat(gray.reshape(1, -1), len(nodedata), axis=0)
    #colors = lambda arr: cm.to_rgba(arr)[:,:3]
    colors = lambda arr: np.power(cm.to_rgba(arr)[:, :3], 2.4)

    if data_name == 'hematocrit':
        cm = matplotlib.cm.ScalarMappable(cmap=cm_hematocrit)
        cm.set_clim(0, 1)
        unmapped_range = (0., 1.)
        edgecolors[mask] = colors(edgedata[mask])
        nodecolors[nmask] = colors(nodedata[nmask])
    elif data_name == 'pressure':
        #this looks really ugly if there is a zero pressure node
        #p0 = np.amin(nodedata)
        p0 = np.min(nodedata[np.nonzero(nodedata)])
        p1 = np.amax(nodedata)
        unmapped_range = (p0, p1)
        cm = matplotlib.cm.ScalarMappable(cmap=cm_redblue)
        cm.set_clim(p0, p1)
        edgecolors[mask] = colors(edgedata[mask])
        nodecolors[nmask] = colors(nodedata[nmask])
    elif data_name == 'shearforce':
        mask = mask & (edgedata > 0)
        nmask = nmask & (nodedata > 0)
        edgedata = edgedata[mask]
        nodedata = nodedata[nmask]
        unmapped_range = edgedata.min(), edgedata.max()
        edgedata = np.log10(edgedata)
        nodedata = np.log10(nodedata)
        p0 = -4  #np.amin(edgedata)
        p1 = -1  #np.amax(edgedata)
        cm = matplotlib.cm.ScalarMappable(cmap=matplotlib.cm.spectral)
        cm.set_clim(p0, p1)
        edgecolors[mask] = colors(edgedata)
        nodecolors[nmask] = colors(nodedata)
    elif data_name == 'S_tot':
        #mask = mask & (edgedata>0)
        #nmask = nmask & (nodedata>0)
        edgedata = edgedata[mask]
        nodedata = nodedata[nmask]
        unmapped_range = edgedata.min(), edgedata.max()
        p0 = np.amin(edgedata)
        p1 = np.amax(edgedata)
        #print("p0: %f, p1: %f" % (p0,p1))
        #unmapped_range = (p0, p1)
        cm = matplotlib.cm.ScalarMappable(cmap=matplotlib.cm.jet)
        cm.set_clim(p0, p1)
        #edgedata = np.log10(edgedata)
        #nodedata = np.log10(nodedata)
        #p0 = -4#np.amin(edgedata)
        #p1 = -1#np.amax(edgedata)
        #cm = matplotlib.cm.ScalarMappable(cmap=matplotlib.cm.spectral)
        #cm.set_clim(p0, p1)
        edgecolors[mask] = colors(edgedata)
        nodecolors[nmask] = colors(nodedata)
    elif data_name == 'flow':
        mask = mask & (edgedata > 0)
        nmask = nmask & (nodedata > 0)
        edgedata = edgedata[mask]
        nodedata = nodedata[nmask]
        unmapped_range = edgedata.min(), edgedata.max()
        edgedata = np.log10(edgedata)
        nodedata = np.log10(nodedata)
        p0 = np.floor(np.amin(edgedata))
        p1 = np.ceil(np.amax(edgedata))
        cm = matplotlib.cm.ScalarMappable(cmap=matplotlib.cm.jet)
        cm.set_clim(p0, p1)
        edgecolors[mask] = colors(edgedata)
        nodecolors[nmask] = colors(nodedata)
    elif data_name == 'conductivitySignal':
        edgedata = edgedata[mask]
        nodedata = nodedata[nmask]
        unmapped_range = edgedata.min(), edgedata.max()
        p0 = np.amin(edgedata)
        p1 = np.amax(edgedata)
        cm = matplotlib.cm.ScalarMappable(cmap=matplotlib.cm.jet)
        cm.set_clim(p0, p1)
        edgecolors[mask] = colors(edgedata)
        nodecolors[nmask] = colors(nodedata)
    elif data_name == 'metabolicSignal':
        edgedata = edgedata[mask]
        nodedata = nodedata[nmask]
        unmapped_range = edgedata.min(), edgedata.max()
        p0 = np.amin(edgedata)
        p1 = np.amax(edgedata)
        cm = matplotlib.cm.ScalarMappable(cmap=matplotlib.cm.jet)
        cm.set_clim(p0, p1)
        edgecolors[mask] = colors(edgedata)
        nodecolors[nmask] = colors(nodedata)
    elif data_name == 'flags':
        edgecolors[mask
                   & (flags & krebsutils.ARTERY).astype(np.bool)] = np.asarray(
                       (1., 0., 0.))
        nodecolors[nmask & (nflags
                            & krebsutils.ARTERY).astype(np.bool)] = np.asarray(
                                (1., 0., 0.))
        edgecolors[mask
                   & (flags & krebsutils.VEIN).astype(np.bool)] = np.asarray(
                       (0., 0., 1.))
        nodecolors[nmask
                   & (nflags & krebsutils.VEIN).astype(np.bool)] = np.asarray(
                       (0., 0., 1.))
        edgecolors[mask
                   & (flags
                      & krebsutils.CAPILLARY).astype(np.bool)] = np.asarray(
                          (0., 1., 0.))
        nodecolors[nmask
                   & (nflags
                      & krebsutils.CAPILLARY).astype(np.bool)] = np.asarray(
                          (0., 1., 0.))
        for idx in vesselgraph.roots:
            nodecolors[idx] = np.asarray((1., 1., 0.))
        cm, unmapped_range = None, (None, None)
    vesselgraph.edges['colors'] = edgecolors
    vesselgraph.nodes['colors'] = nodecolors
    return cm, unmapped_range
Пример #28
0
if 0:
    fig = pyplot.figure()
    ax = fig.add_axes([0.1, 0.1, 0.8, 0.8])
    plt = ax.scatter(position[:, 0],
                     position[:, 1],
                     c=weight_smpl,
                     s=5,
                     edgecolor=None,
                     cmap=matplotlib.cm.jet,
                     marker='o')
    ax.set_axis_bgcolor('k')
    fig.colorbar(plt)
    pyplot.show()

mask = mask & myutils.bbitwise_and(flags, krebsutils.CIRCULATED)
dist_smpl = dist_smpl[mask]
weight_smpl = weight_smpl[mask]

bins = BinsSpecRange(-10000., 10000., 100.).arange()
a = myutils.MeanValueArray.fromHistogram1d(
    bins, dist_smpl, weight_smpl, weight_smpl)  #np.ones_like(dist_smpl)
b = myutils.MeanValueArray.fromHistogram1d(bins, distmap.ravel(),
                                           np.ones_like(distmap.ravel()))
a.cnt = b.cnt.copy()
a.sum *= 1. / (tumor_ld.scale**3)
a.sqr *= a.sum**2

c = a.sum / (bins[1:]**2 - bins[:-1]**2)

fig, axes = pyplot.subplots(2, 1)