def renderSliceWithDistribution(vesselgroup, imagefn, options):
    vessel_ld = krebsutils.read_lattice_data_from_hdf(
        vesselgroup['vessels/lattice'])
    vessel_graph = krebsutils.read_vessels_from_hdf(
        vesselgroup['vessels'],
        ['position', 'flags', 'radius', 'pressure', 'shearforce', 'nodeflags'],
        return_graph=True)
    vessel_graph.edges['radius'] *= 4.

    #kwargs = deepcopy(kwargs)
    wbbox = vessel_ld.worldBox
    trafo = calc_centering_normalization_trafo(wbbox)
    height = (wbbox[5] - wbbox[4]) * trafo.w

    print('Vessel BBox:' + str(vessel_ld.worldBox))
    print(vessel_ld)
    print('Post Trafo Ld BBox:' + str(transform_ld(trafo, vessel_ld).worldBox))

    hasGfField = 'field_ld' in vesselgroup and vessel_ld.shape[2] == 1
    #hasGfField = False
    if hasGfField:
        volume_ld = krebsutils.read_lattice_data_from_hdf(
            vesselgroup['field_ld'])
        print('Volume BBox:' + str(volume_ld.worldBox))
        print(volume_ld)
        volumedata = np.asarray(vesselgroup['gf'])
        #print volumedata.shape, volumedata.min(), volumedata.max()
        volume_ld = transform_ld(trafo, volume_ld)
        print('Post Trafo Volume BBox:' + str(volume_ld.worldBox))
        print('volume data bounds:' + str(volumedata.min()),
              str(volumedata.max()))

    colorfactory(vessel_graph)

    with EasyPovRayRender(**options) as epv:
        epv.setBackground(options.pop('background', 0.0))

        cam_fov = 60.
        cam_distance_factor = ComputeCameraDistanceFactor(
            cam_fov, options['res'], wbbox)

        epv.setCamera((0, 0, cam_distance_factor * 1.05),
                      lookat=(0, 0, 0),
                      fov=cam_fov,
                      up='y')

        epv.addLight(10. * Vec3(1, 0.5, 2), 1.2)

        cm = matplotlib.cm.ScalarMappable(cmap=cm_gf)
        cm.set_clim(-0.01, 1.01)
        pvcm = matplotlibColormapToPovray('DATACOLORMAP', cm)
        epv.declareColorMap(pvcm)

        if hasGfField:
            volumedata = epv.declareVolumeData(volumedata, volume_ld.worldBox,
                                               volume_ld)
            epv.addVolumeDataSlice(volumedata, (0, 0, 0), (0, 0, 1.), pvcm)
        addVesselTree(epv, vessel_graph, trafo=trafo, **options)

        imagefn = epv.render(imagefn)
示例#2
0
    def plot(filename):
        rc = matplotlib.rc
        rc('font', size=8.)
        rc('axes', titlesize=10., labelsize=10.)
        rc('figure', **{'subplot.wspace': 0.15, 'subplot.hspace': 0.15})
        rc('savefig', facecolor='white')
        dpi = 100.
        results = Results(filename)
        ld = krebsutils.read_lattice_data_from_hdf(results.f['field_ld'])
        size = ld.shape
        extent = ld.worldBox[:4]
        ldface = (krebsutils.read_lattice_data_from_hdf(
            results.f['face_ld_0']),
                  krebsutils.read_lattice_data_from_hdf(
                      results.f['face_ld_1']))
        extface = tuple(q.worldBox[:4] for q in ldface)
        data = collections.defaultdict(list)
        for idx, group in enumerate(results):

            def show(a, ext):
                pyplot.imshow(np.asarray(a[..., size[2] / 2]).transpose(),
                              extent=ext,
                              origin='bottom',
                              interpolation='nearest')

            def contour():
                return pyplot.contour(np.asarray(group['ls'][..., size[2] /
                                                             2]).transpose(),
                                      levels=[0.],
                                      extent=extent,
                                      origin='lower')

            print "plotting %i" % idx
            if 1:
                pyplot.figure(figsize=(1200. / dpi, 1000. / dpi))

                pyplot.subplot(221)
                show(group['ls'], extent)
                pyplot.colorbar()
                contour()
                pyplot.subplot(222)
                show(group['rho'], extent)
                pyplot.colorbar()
                contour()

                pyplot.subplot(223)
                show(group['force_0'], extface[0])
                pyplot.colorbar()
                contour()
                pyplot.subplot(224)
                show(group['force_1'], extface[1])
                pyplot.colorbar()
                contour()
                pyplot.savefig("%s_%i.png" % (filename, idx), dpi=dpi)

            data['time'].append(group.attrs['time'])
            data['mass'].append(group.attrs['mass'])
            data['area'].append(group.attrs['area'])
示例#3
0
def get_tumld(tumorgroup):
    p = tumorgroup['ptc'].attrs['LATTICE_PATH']
    tum_ld = krebsutils.read_lattice_data_from_hdf(tumorgroup.file[p])
    #field_ld is in root
    #tum_ld = krebsutils.read_lattice_data_from_hdf(tumorgroup.parent.parent['field_ld'])
    #tum_ld = krebsutils.read_lattice_data_from_hdf(tumorgroup.file[tumorgroup['conc'].attrs['LATTICE_PATH']])
    return tum_ld
示例#4
0
def computeO2Uptake(po2group, tumorgroup):
  po2field  = np.asarray(po2group['po2field'])
  po2ld = krebsutils.read_lattice_data_from_hdf(po2group['field_ld'])
  parameters = readParameters(po2group)
  uptake = pickDetailedO2Library(parameters).computeO2Uptake(po2field, po2ld, tumorgroup, parameters)
  uptake *= 60. # 1/s -> 1/min
  return uptake;
示例#5
0
 def asVtkDataSets(self, return_ld_path=False):
     import krebsutils
     result = {}
     for k, gg in self.data.iteritems():
         if k == VtkFiles:
             for g in gg:
                 #          ds = vtkcommon.vtkStringToDataset(
                 #            np.asarray(g).tostring(),
                 #            vtk.vtkDataSetReader if g.attrs['TYPE'] == 'VTK_FILE' else self.gridtype2vtureader[g.attrs.get('VTK_DATASET_TYPE', 'vtkUnstructuredGrid')]
                 #          )
                 ds = vtkcommon.vtkDatasetFromHdf5(g)
                 result[g.name] = ds
         else:
             #ds = vtkcommon.vtkImageDataFromLd(self.file[k].attrs)
             ld = krebsutils.read_lattice_data_from_hdf(self.file[k])
             ds = vtkcommon.vtkImageDataFromLd(ld)
             name = posixpath.commonprefix([q.name for q in gg])
             for q in gg:
                 # iterate over hdf datasets and add them to the image data
                 vtkcommon.vtkImageDataAddData(ds, q, 'CellData',
                                               posixpath.basename(q.name))
             if not return_ld_path:
                 result[name] = ds
             else:
                 result[name] = (ds, k)
     return result.values()
示例#6
0
def getDomainSizeFromVesselFile(fn):
    with h5files.open(fn, 'r') as f:
        ld = krebsutils.read_lattice_data_from_hdf(
            krebsutils.find_lattice_group_(f['vessels']))
        size = np.amax(ld.GetWorldSize())
    # longest axis times the lattice spacing
    return size
示例#7
0
  def __init__(self, dataman, group, label):
    self.label   = label
    self.dataman = dataman
    self.group   = group

    self.cachelocation = (group.file, group.name)
    self.po2group, self.vesselgroup = group['po2'], group['vessels']

    #self.po2vessels, self.po2fieldld, self.po2field, _ = dataman.obtain_data('detailedPO2', self.po2group)
    self.po2fieldld = krebsutils.read_lattice_data_from_hdf(self.po2group['field_ld'])
    self.po2vessels = self.po2group['po2vessels']
    self.po2field   = self.po2group['po2field']
    self.worldbb = self.po2fieldld.worldBox
    self.fluxes = dataman.obtain_data('detailedPO2_total_fluxes', '', self.po2group, sample_length, 1, self.cachelocation)
    self.samples = GenerateSingleCapillarySamples(dataman, self.po2group, self.cachelocation)
    self.samplesx = 1.e-3*self.samples['x']
    self.numSamples = len(self.samples['x'])

    ld = self.po2fieldld
    x0, x1, y0, y1, z0, z1 = ld.box
    self.x_field = np.linspace(ld.LatticeToWorld((x0, 0, 0))[0], ld.LatticeToWorld((x1,0,0))[0], x1-x0+1)
    self.y_field = np.linspace(ld.LatticeToWorld((0, y0, 0))[1], ld.LatticeToWorld((0, y1,0))[1], y1-y0+1)
    
    if not 'LIMITS' in self.po2field.attrs:
      self.po2field.attrs['LIMITS'] = (np.amin(self.po2field), np.amax(self.po2field))
    if not 'LIMITS' in self.po2vessels.attrs:
      self.po2vessels.attrs['LIMITS'] = (np.amin(self.po2vessels), np.amax(self.po2vessels))
    pf0, pf1 = self.po2field.attrs['LIMITS']
    pv0, pv1 = self.po2vessels.attrs['LIMITS']
    self.po2range = (min(pf0, pv0), max(pf1, pv1))
    self.params_ = None
示例#8
0
def ObtainDataOfVesselFile(f):
    dataman = myutils.DataManager(20, [
        krebs.analyzeGeneral.DataTumorTissueSingle(),
        krebs.analyzeGeneral.DataVesselRadial(),
        krebs.analyzeGeneral.DataDistanceFromCenter(),
        krebs.analyzeBloodFlow.DataTumorBloodFlow(),
        krebs.analyzeGeneral.DataBasicVessel(),
        krebs.analyzeGeneral.DataVesselSamples(),
    ])
    vesselgroup = f['vessels']
    ld = krebsutils.read_lattice_data_from_hdf(f['field_ld'])
    #print 'field_box = ', ld.worldBox
    #bins_spec   = krebs.analyzeGeneral.BinsSpecRange(100., 1000., 100.)
    bins_spec = krebs.analyzeGeneral.BinsSpecRange(100., 1000., 100.)
    mvd, mvd_bins = dataman.obtain_data('sphere_vessel_density', vesselgroup,
                                        None, bins_spec, 'radial', ld,
                                        (f, 'data'))
    rbf, rbf_bins = dataman.obtain_data('cum_rbf_radial', vesselgroup, None,
                                        bins_spec, 'radial', ld, (f, 'data'))
    rbv = dataman.obtain_data('basic_vessel_radial', 'phi_vessels',
                              vesselgroup, None, 50., bins_spec, 'radial', ld,
                              (f, 'data'))
    # rbv returns myutils.MeanValueArray
    scale = f['vessels/lattice'].attrs['SCALE']
    message = f['parameters'].attrs['MESSAGE']
    return dict(mvd=np.asarray(mvd),
                rbf=np.asarray(rbf),
                rbv=rbv.avg,
                bins=bins_spec.arange(),
                scale=scale,
                message=message)
示例#9
0
 def makeLD(self, vesselgroup):
     ldvessels = krebsutils.read_lattice_data_from_hdf(
         vesselgroup['lattice'])
     fieldld = krebsutils.SetupFieldLattice(ldvessels.worldBox, 3,
                                            self.bin_size, 0.)
     fieldldFine = krebsutils.SetupFieldLattice(
         fieldld.worldBox, 3, self.bin_size / self.fine_bin_subdivision, 0.)
     return fieldld, fieldldFine
示例#10
0
def from_vessel_file(filenames, grp_pattern):
    dirs = set()
    dataman = myutils.DataManager(20, [
        krebs.plotIff.DataTissue(),
        krebs.plotIff.DataGlobalIff(),
        krebs.plotIff.DataRadialIff(),
        krebs.analyzeGeneral.DataDistanceFromCenter(),
        krebs.analyzeGeneral.DataVesselSamples(),
        krebs.analyzeGeneral.DataBasicVessel(),
        o2analysis.DataDetailedPO2()
    ])
    f_measure = h5files.open('chache.h5', 'a', search=False)

    def cachelocation(g):
        path = posixpath.join(
            'FileCS_' + myutils.checksum(basename(g.file.filename)),
            g.name.strip(posixpath.sep))
        return (f_measure, path)

    #run with grp_pattern: iff/vessels
    for fn in filenames:
        with h5py.File(fn, 'r+') as f:
            d = myutils.walkh5(f, grp_pattern)
            assert len(d), 'you f****d up, pattern "%s" not found in "%s"!' % (
                grp_pattern, fn)
            dirs = set.union(dirs, d)
            for group_path in dirs:
                if 'vessel' in grp_pattern and not 'o2' in grp_pattern:
                    vesselgroup = f[group_path]
                    ldvessels = ku.read_lattice_data_from_hdf(
                        vesselgroup['lattice'])
                    fieldld = ku.SetupFieldLattice(ldvessels.worldBox, 3, 10,
                                                   0.)
                    phi_vessels = krebs.analyzeGeneral.CalcPhiVessels(
                        dataman,
                        vesselgroup,
                        fieldld,
                        scaling=1.,
                        samples_per_cell=5)
                    print('bla')
                    import nibabel as nib
                    new_image = nib.Nifti1Image(phi_vessels, affine=np.eye(4))
                    common_filename = os.path.splitext(os.path.basename(fn))[0]
                    new_image.to_filename(common_filename + '_vessels' +
                                          '.nii')
                if 'o2' in grp_pattern:
                    po2group = f[group_path]
                    #sample_length = 500.
                    #data = dataman.obtain_data('detailedPO2_global', 'po2_tissue', po2group, sample_length, cachelocation(po2group))
                    data = np.asarray(po2group['po2field'])
                    print('bla')
                    import nibabel as nib
                    new_image = nib.Nifti1Image(data, affine=np.eye(4))
                    common_filename = os.path.splitext(os.path.basename(fn))[0]
                    new_image.to_filename(common_filename + '_po2' + '.nii')
def CenterTheLattice(f, h5_path):
    """
      The histological MVD is determined for intersections of
      the vascular network with a number of concentric spheres.
      Therefore it is convenient to first move the system
      so that it is centered at the coordinate origin.
    """
    ld = krebsutils.read_lattice_data_from_hdf(f[h5_path])
    del f[h5_path]
    ld = ld.GetCentered()
    krebsutils.write_lattice_data_to_hdf(f, h5_path, ld)
示例#12
0
 def write(gmeasure, groupname):
     vessels = dataman.obtain_data('vessel_graph', vesselgroup,
                                   ['flags', 'flow'])
     arterialFlow, _ = GetRootVesselData(vessels, vessels['flow'])
     arterialFlow = np.sum(arterialFlow)
     ldvessels = krebsutils.read_lattice_data_from_hdf(
         vesselgroup['lattice'])
     totalVolume = np.cumprod(ldvessels.GetWorldSize())[2]
     perfusion = arterialFlow / totalVolume
     ds = gmeasure.create_dataset(groupname, data=perfusion)
     ds.attrs['unit'] = '1 / s'
class EnsembleFiles(object):
    def __init__(self, dataman, filenames, pattern):
        files = [h5files.open(fn, 'r+') for fn in filenames]
        items = []
        has_tumor = True
        for f in files:
            paths = myutils.walkh5(f['.'], pattern)
            for path in paths:
                g = f[path]
                if g.attrs.get('CLASS', None) == 'GRAPH':
                    gvessels = g
                    gtumor = None
                    try:
                        source = h5files.openLink(g, 'SOURCE')
                        gtumor = source.parent['tumor']
                        g = source.parent
                    except Exception, e:
                        raise RuntimeError(
                            'tried to get tumor data but failed:' + str(e))
                else:
                    gvessels, gtumor = g['vessels'], (g['tumor'] if 'tumor'
                                                      in g else None)
                e = EnsembleItem(path=path,
                                 gvessels=gvessels,
                                 gtumor=gtumor,
                                 group=g)
                e.time = g.attrs['time']
                has_tumor = has_tumor and gtumor is not None
                e.vessel_system_length = dataman.obtain_data(
                    'vessel_system_length', gvessels)
                items.append(e)
        if has_tumor:
            d = collections.defaultdict(list)  # path -> list of EnsembleItem
            for e in items:
                d[e.path].append(e)
            tumor_snapshot_times = dict(
                (k, np.average(map(lambda e: e.time, v)))
                for k, v in d.items())
            tumor_snapshot_order = sorted(
                tumor_snapshot_times.keys(),
                key=(lambda path: tumor_snapshot_times[path]))
            tumor_snapshots = [(d[path], path, tumor_snapshot_times[path])
                               for path in tumor_snapshot_order]
        self.files = files
        self.items = items
        self.tumor_snapshots = tumor_snapshots  # list of tuple(items, path, time)
        self.has_tumor = has_tumor
        ld = krebsutils.read_lattice_data_from_hdf(
            items[0].gvessels['lattice'])
        self.world_size = ld.GetWorldSize()
示例#14
0
def from_vessel_file(filenames, grp_pattern):
    dirs = set()
    dataman = myutils.DataManager(20, [
        krebs.plotIff.DataTissue(),
        krebs.plotIff.DataGlobalIff(),
        krebs.plotIff.DataRadialIff(),
        krebs.analyzeGeneral.DataDistanceFromCenter(),
        krebs.analyzeGeneral.DataBasicVessel()
    ])

    #run with grp_pattern: iff/vessels
    for fn in filenames:
        with h5py.File(fn, 'r') as f:
            d = myutils.walkh5(f, grp_pattern)
            assert len(d), 'you f****d up, pattern "%s" not found in "%s"!' % (
                grp_pattern, fn)
            dirs = set.union(dirs, d)
            for group_path in dirs:
                vesselgroup = f[group_path]
                ldvessels = ku.read_lattice_data_from_hdf(
                    vesselgroup['lattice'])
                fieldld = ku.SetupFieldLattice(ldvessels.worldBox, 3, 10, 0.)
                #fieldldFine = ku.SetupFieldLattice(fieldld.worldBox, 3, 50 / 10, 0.)
                phi_vessels = krebs.analyzeGeneral.CalcPhiVessels(
                    dataman,
                    f['iff/vessels'],
                    fieldld,
                    scaling=1.,
                    samples_per_cell=5)
                #a_abs = np.fabs(phi_vessels)
                #a_max = np.amax(a_abs)
                #n_phi = phi_vessels/a_max
                #visual =  (phi_vessels-phi_vessels.min())
                #inner1 = matplotlib.cm.gist_earth(n_phi)
                #inner2 = np.uint8(inner1*255)
                #result = Image.fromarray(inner2[:,:,:,0:2],mode='RGB')
                #result.save('out.tiff')
                print('bla')
                import nibabel as nib
                new_image = nib.Nifti1Image(phi_vessels, affine=np.eye(4))
                new_image.to_filename('myni')
                #for i in np.arange(0,phi_vessels.shape[2]):
                #  plt.imsave('img/%03i.png' % i,phi_vessels[:,:,i])
                #scipy.io.savemat('test.mat', phi_vessels)
                #np.save('mydata.tiff',phi_vessels)
                #pydicom.
                #pydicom.write_file('mydata.dcm', phi_vessels)
                plt.imshow(phi_vessels[:, :, 20])
                plt.show()
示例#15
0
def sampleVessels(po2group, vesselgroup, tumorgroup, sample_length):
  po2vessels  = np.asarray(po2group['po2vessels'])
  if po2vessels.shape[0] <> 2: po2vessels = np.transpose(po2vessels)
  po2field  = np.asarray(po2group['po2field'])
  ld = krebsutils.read_lattice_data_from_hdf(po2group['field_ld'])
  parameters = readParameters(po2group)
  # call thee c++ stuff
  samples, fluxes = pickDetailedO2Library(parameters).sampleVessels(vesselgroup, tumorgroup, parameters, po2vessels, po2field, ld, sample_length)
  # convert units to mlO2/s, and also return dicts
  fluxes = dict((k, f*60.e-12) for k,f in zip(('Jin_root', 'Jout_root', 'Jout_tv', 'tv_cons'), fluxes))
  samples = dict(
      po2    = samples[0],
      extpo2 = samples[1],
      jtv    = samples[2]*60.e-4,  # 1.e-4 to convert from mu m^3 O2 / um^2 / s to ml O2 / cm^2 / min
      dS_dx  = samples[3]*1.e3, # in 1/mmm
    )
  return samples, fluxes
示例#16
0
def CenterLattice(g):
    '''needs h5 goup g, which is deleted and rewritten where the new lattice is centered
  '''
    print '------', g.name + '--------'
    ld = krebsutils.read_lattice_data_from_hdf(g)
    #meanwhile worldBox is 3D
    thisBox = ld.worldBox
    bmin, bmax = thisBox[0:2]
    offset = -0.5 * (bmin + bmax)  # which is the negative center
    #offset[0] = 0 # don't move in x
    orig = ld.GetOriginPosition()
    orig += offset
    ld.SetOriginPosition(orig)
    parent = g.parent
    name = str(g.name)
    del g
    del parent[name]
    krebsutils.write_lattice_data_to_hdf(parent, name, ld)
    return offset
示例#17
0
def PrintGlobalData(pdfpages, vesselgroups, f_measure, dataman):
    from analyzeBloodVolumeSimple import cylinderCollectionVolumeDensity
    import detailedo2Analysis.plotsForPaper
    import detailedo2

    sample_length = detailedo2Analysis.plotsForPaper.sample_length

    def cachelocation(g):
        path = posixpath.join(
            'FileCS_' + myutils.checksum(basename(g.file.filename)),
            g.name.strip(posixpath.sep))
        return (f_measure, path)

    f2l = myutils.f2l

    bbox_vessels = list()
    data_by_name = collections.defaultdict(list)
    #prop_list = ['mvd', 'mvd_a', 'mvd_v', 'mvd_c', 'rBV', 'rBV_a', 'rBV_v', 'rBV_c', 'venous_rBV_fraction', 'rBF', 'meanCapillaryDistance', 'mean_r']
    #prop_list = ['rBV',  'rBF', ]
    #prop_list = 'phi_a phi_v phi_c mvd_a mvd_v mvd_c mean_r'.split()

    prop_list2 = [
        'radius', 'shearforce', 'velocity', 'flow', 'avg_cap_dist',
        'mvd_linedensity', 'mvd_sphere_sampling', 'mvd', 'mvd_a', 'mvd_v',
        'mvd_c', 'phi_vessels', 'phi_a', 'phi_v', 'phi_c', 'total_perfusion'
    ]
    #prop_list2 = ['radius','shearforce','velocity','flow','avg_cap_dist','mvd_linedensity','phi_vessels']
    prop_data_vessel_global = ['mvd']
    try:
        os.remove('initialvesseldata.h5')
    except OSError:
        pass
        with h5py.File('initialvesseldata.h5', 'w-') as f:
            for k, v in data_by_name.iteritems():
                f.create_dataset(k, data=v)

    result_string = []

    for name in prop_list2:
        data = []
        for gvessels in vesselgroups:
            data.append(
                dataman.obtain_data('basic_vessel_global', name, gvessels,
                                    cachelocation(gvessels)))
            ld_vessels = krebsutils.read_lattice_data_from_hdf(
                gvessels['lattice'])
            bbox_vessels.append(ld_vessels.worldBox)
        result_string.append(r'$<%s>$ = $%s$%s' %
                             (Prettyfier.get_sym(name), Format(
                                 name, data), Prettyfier.get_munit(name)))

    ld = krebsutils.read_lattice_data_from_hdf(vesselgroups[0]['lattice'])
    bbox_vessels.append(ld.worldBox)

    bbox_vessels = np.average(bbox_vessels, axis=0).reshape(3, 2).transpose()
    result_string += ['Vessel System Bounding Box'] + list(fmt_(bbox_vessels))

    fig, _ = mpl_utils.MakeTextPage(result_string,
                                    figsize=(mpl_utils.a4size[0],
                                             mpl_utils.a4size[0]))
    pdfpages.savefig(fig, postfix='_vesselsglobal')
示例#18
0
def PrintGlobalDataWithOxygen(pdfpages, po2groups, vesselgroups, f_measure,
                              dataman):
    from analyzeBloodVolumeSimple import cylinderCollectionVolumeDensity
    import detailedo2Analysis.plotsForPaper
    import detailedo2

    sample_length = detailedo2Analysis.plotsForPaper.sample_length

    def cachelocation(g):
        path = posixpath.join(
            'FileCS_' + myutils.checksum(basename(g.file.filename)),
            g.name.strip(posixpath.sep))
        return (f_measure, path)

    f2l = myutils.f2l

    bbox_vessels = list()
    bbox_field = list()
    data_by_name = collections.defaultdict(list)
    O2_prop_list = [
        'po2', 'sat', 'sat_via_hb_ratio', 'gtv', 'jtv', 'mro2', 'po2_tissue',
        'chb', 'chb_oxy', 'chb_deoxy', 'oef', 'e1', 'e3', 'Jin_root',
        'Jout_root', 'Jout_tv', 'Jout_cons', 'sat_vein', 'sat_art', 'sat_capi'
    ]
    prop_list = [
        'mvd', 'mvd_a', 'mvd_v', 'mvd_c', 'rBV', 'rBV_a', 'rBV_v', 'rBV_c',
        'venous_rBV_fraction', 'rBF', 'meanCapillaryDistance', 'mean_r'
    ]
    #prop_list2 = ['shearforce', 'velocity']
    #prop_list2 = ['velocity']

    for po2group in po2groups:
        for prop in O2_prop_list:
            data = dataman.obtain_data('detailedPO2_global', prop, po2group,
                                       sample_length, cachelocation(po2group))
            data_by_name[prop].append(data)
        ld = krebsutils.read_lattice_data_from_hdf(po2group['field_ld'])
        bbox_field.append(ld.worldBox)
        gvessels, _ = detailedo2.OpenVesselAndTumorGroups(po2group)
        #    for prop in prop_list2:
        #      data = dataman.obtain_data('basic_vessel_global', prop, gvessels, cachelocation(gvessels))
        #      data_by_name[prop].append(data)
        ld = krebsutils.read_lattice_data_from_hdf(gvessels['lattice'])
        bbox_vessels.append(ld.worldBox)
        rbv, a, v, c = cylinderCollectionVolumeDensity(gvessels)
        sa, sv, sc = data_by_name['sat_art'][-1], data_by_name['sat_vein'][
            -1], data_by_name['sat_capi'][-1]
        data_by_name['sat_estimated_by_acv'].append(
            (sa * a + sv * v + sc * c) / rbv)
    O2_prop_list.append('sat_estimated_by_acv')

    try:
        os.remove('initialvesseldata.h5')
    except OSError:
        pass
    with h5py.File('initialvesseldata.h5', 'w-') as f:
        for k, v in data_by_name.iteritems():
            f.create_dataset(k, data=v)

#  def fmt_(v, exponent=None, multi=1.):
#    avg, std = np.average(v, axis=0), np.std(v, axis=0)
#    if exponent is not None:
#      exponent_str = ('\,10^{%i}' % exponent) if exponent<>0 else ''
#      f = math.pow(10., exponent)
#      s = r'%s \pm %s%s' % (f2l(avg/f*multi, exponential=False), f2l(std/f*multi, exponential=False), exponent_str)
#    else:
#      s = r'%s \pm %s\,' % (f2l(avg*multi), f2l(std*multi))
#    return s

    result_string = []
    for name, v in myutils.iterate_items(data_by_name, O2_prop_list):
        result_string.append(r'$<%s>$ = $%s$%s' %
                             (Prettyfier.get_sym(name), Format(
                                 name, v), Prettyfier.get_munit(name)))

#  text = FormatGeometricAndPerfusionData()

    prop_list2 = ['avg_cap_dist', 'mvd_linedensity']
    #bbox_vessels = list()
    #bbox_field   = list()

    for name in prop_list2:
        data = []
        for gvessels in vesselgroups:
            data.append(
                dataman.obtain_data('basic_vessel_global', name, gvessels,
                                    cachelocation(gvessels)))
            #ld = krebsutils.read_lattice_data_from_hdf(vesselgroups[0]['lattice'])
            #bbox_vessels.append(ld.worldBox)
        result_string.append(r'$<%s>$ = $%s$%s' %
                             (Prettyfier.get_sym(name), Format(
                                 name, data), Prettyfier.get_munit(name)))

#""" some problems still exists here
#need field_ld which in not consistently stored"""
#  mvd_exp=[]
#  for (gvessels,po2group) in zip(vesselgroups,po2groups):
#    ld = krebsutils.read_lattice_data_from_hdf(po2group['field_ld'])
#    mvd_sampling_results, mvd_bins = dataman.obtain_data('sphere_vessel_density',  gvessels, None, suggest_bins_from_world(ld), 'radial', ld, cachelocation(gvessels))
#    mvd_exp.append(np.mean(np.asarray(mvd_sampling_results)*1e6))
#
#  result_string.append(r'$<%s>$ = $%s$%s' %
#    (Prettyfier.get_sym('mvd_exp'), Format('mvd_exp', mvd_exp), Prettyfier.get_munit('mvd_exp')))

    bbox_vessels = np.average(bbox_vessels, axis=0).reshape(3, 2).transpose()
    bbox_field = np.average(bbox_field, axis=0).reshape(3, 2).transpose()
    result_string += ['Vessel System Bounding Box'] + list(
        fmt_(bbox_vessels)) + ['FD-Grid Bounding Box'] + list(fmt_(bbox_field))

    fig, _ = mpl_utils.MakeTextPage(result_string,
                                    figsize=(mpl_utils.a4size[0],
                                             mpl_utils.a4size[0]))
    pdfpages.savefig(fig, postfix='_vesselsglobal')

    fig = matplotlib.figure.Figure(figsize=(mpl_utils.a4size[0] * 0.5,
                                            mpl_utils.a4size[0] * 0.5))
    ax = fig.add_axes([0.1, 0.2, 0.8, 0.75])
    for po2group in po2groups:
        iterations = detailedo2Analysis.plotsForPaper.GetConvergenceData(
            po2group)
        x = iterations['iteration']
        y = iterations['delta_vessM'] + iterations['delta_fieldM']
        ax.plot(x, y)
    ax.set(yscale='log',
           xlabel='iterations',
           ylabel=r'$|p(new) - p(old)|_\infty$')
    pdfpages.savefig(fig, postfix='_convergence')
示例#19
0
  def obtain_data(self, dataman, dataname, *args):
    if dataname == 'ld':
      f, = args
      ld = krebsutils.read_lattice_data_from_hdf(f['field_ld'])
      return ld

    ####
    if dataname == 'time':
      if len (args) == 1:
        group, = args
      else:
        group = args[0][args[1]] # f, group = args
      return group.attrs['time'] # in hours

    #####
    if dataname == 'fieldvariable':
      f, fieldname, group = args[:3]
      g = f[group] # group name to actual group
      tumor_path = tumor_path_(f, group)

      ld = dataman.obtain_data('ld', f)

      def get(name):
        return self.obtain_data(dataman, 'fieldvariable', f, name, group)

      if fieldname == 'phi_cells':
        data = f[tumor_path]['conc']
      elif fieldname == 'dist_tumor_':
        data = f[tumor_path]['ls']
      elif fieldname == 'theta_tumor':
        gtumor = f[tumor_path]
        if gtumor.attrs['TYPE'] == 'faketumor':
          data = gtumor['tc_density']
        else:
          data = gtumor['ptc']
      elif fieldname == 'phi_necro':
        data = f[tumor_path]['necro']
      elif fieldname in ('oxy'):
        try:
          data = g['oxy']
        except KeyError:
          data = g['fieldOxy']
      elif fieldname in ('gf'):
        data = g['fieldGf']
      elif fieldname in ('press', 'sources', 'vel'):
        data = f[tumor_path][fieldname]
      elif fieldname == 'phi_viabletumor':
        theta_tumor = get('theta_tumor')
        phi_cells = get('phi_cells')
        phi_necro = get('phi_necro')
        data = theta_tumor * (phi_cells - phi_necro)
      elif fieldname == 'phi_tumor':
        theta_tumor = get('theta_tumor')
        phi_cells = get('phi_cells')
        data = theta_tumor * phi_cells
      elif fieldname == 'dist_necro':
        phi_necro = get('phi_necro')
        phi_cells = get('phi_cells')
        tumor_contour_level = 0.5*np.average(phi_cells)
        data = calc_distmap(phi_necro, ld, tumor_contour_level)
      elif fieldname == 'dist_viabletumor':
        def read(gmeasure, dsname):
          return np.asarray(gmeasure[dsname])
        def write(gmeasure, dsname):
          dist_tumor = get('dist_tumor')
          dist_necro = get('dist_necro')
          data = np.maximum(dist_tumor, -dist_necro)
          gmeasure.create_dataset(dsname, data = data, compression = 9)
        fm = myutils.MeasurementFile(f, h5files)
        data = myutils.hdf_data_caching(read, write, fm, (tumor_path, 'dist_viabletumor'), (0,1))
      elif fieldname == 'phi_vessels':
        def read(gmeasure, name):
          return np.asarray(gmeasure[name])
        def write(gmeasure, name):
          phi_vessels = CalcPhiVessels(dataman, f[group]['vessels'], ld, scaling = 1.)
          gmeasure.create_dataset(name, data = phi_vessels, compression = 9)
        fm = myutils.MeasurementFile(f, h5files)
        data = myutils.hdf_data_caching(read, write, fm, (group, 'phi_vessels'), (0,1))
      elif fieldname == 'dist_tumor':
        def read(gmeasure, name):
          return np.asarray(gmeasure[name])
        def write(gmeasure, name):
          ls = get('dist_tumor_')
          ls = -ls
          dist = calc_distmap(np.asarray(ls < 0., dtype=np.float32), ld, 0.5)
          gmeasure.create_dataset(name, data = dist, compression = 9)
        fm = myutils.MeasurementFile(f, h5files)
        data = myutils.hdf_data_caching(read, write, fm, (tumor_path, 'dist_tumor_full'), (0,1))
      else:
        raise RuntimeError('unkown field %s' % fieldname)

      if len(args)>3 and args[3] == 'imslice':
        import plotBulkTissue
        return plotBulkTissue.imslice(data)
      else:
        return np.asarray(data)

    if dataname == 'fieldvariable_radial':
      property_name, tumorgroup, bins_spec, distance_distribution_name, cachelocation = args

      def write(gmeasure, groupname):
        distmap, ld = obtain_distmap_(dataman, tumorgroup, distance_distribution_name)
        data    = dataman.obtain_data('fieldvariable', tumorgroup.file, property_name, tumorgroup.name)
        bins    = bins_spec.arange()
        a = myutils.MeanValueArray.fromHistogram1d(bins, np.ravel(distmap), np.ravel(data))
        ds = a.write(gmeasure, groupname)
        ds.attrs['BINS_SPEC'] = str(bins_spec)

      def read(gmeasure, groupname):
        assert groupname == property_name
        return myutils.MeanValueArray.read(gmeasure, groupname)

      return HdfCacheRadialDistribution((read, write), property_name, bins_spec, distance_distribution_name, cachelocation, 1)

    if dataname == 'approximate_tumor_radius':
      tumorgroup, = args
      def write(gmeasure, groupname):
        rad = ApproximateTumorRadius(dataman, tumorgroup)
        ds = gmeasure.create_dataset(groupname, data = rad)
      def read(gmeasure, groupname):
        return np.asscalar(gmeasure[groupname][()])
      return myutils.hdf_data_caching(read, write, tumorgroup, ('approximate_tumor_radius',), (1,))
示例#20
0
 def __init__(self, name):
     f = h5py.File(name + '.h5', 'r')
     self.ld = ld = krebsutils.read_lattice_data_from_hdf(f['field_ld'])
     self.groups = myutils.getTimeSortedGroups(f['.'], 'out')
     self.f = f
示例#21
0
import mpl_utils

# blurring is used to actually compute the local average with the help of a box filter.
SHOW_BLURRED_IMAGES = False

if SHOW_BLURRED_IMAGES:
    import scipy.signal as sig
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,
示例#22
0
    def obtain_data(self, dataman, dataname, *args):
        if dataname == 'blood_flow':
            vesselgroup, tumorgroup, cachelocation = args
            has_tumor = tumorgroup is not None

            def read(gmeasure, groupname):
                return dict((k, float(v[...]))
                            for (k, v) in gmeasure[groupname].iteritems())

            def write(gmeasure, groupname):
                #vessels = krebsutils.read_vesselgraph(vesselgroup, ['flow', 'pressure', 'position', 'flags'])
                vessels = dataman.obtain_data('vessel_graph', vesselgroup,
                                              ['position', 'flags', 'flow'])
                pos = vessels['position']

                if has_tumor:
                    ldtumor = dataman.obtain_data('ld', tumorgroup.file)
                    dist = dataman.obtain_data('fieldvariable',
                                               tumorgroup.file, 'theta_tumor',
                                               tumorgroup.name)
                    dist = krebsutils.sample_field(pos,
                                                   dist,
                                                   ldtumor,
                                                   linear_interpolation=True)
                    res = ComputeIsosurfaceBloodFlow(dataman, vesselgroup,
                                                     dist, 0.5)
                    res.update(
                        DataTumorBloodFlow.ComputeTotalBloodFlow_(vessels))
                else:
                    res = DataTumorBloodFlow.ComputeTotalBloodFlow_(vessels)

                g = gmeasure.create_group(groupname)
                for k, v in res.iteritems():
                    g.create_dataset(k, data=v)

            #fm = myutils.MeasurementFile(f, h5files)
            ret = myutils.hdf_data_caching(
                read, write, cachelocation[0],
                ('global', cachelocation[1], 'tissue', 'blood_flow'),
                (1, 1, 1, 3))
            return ret

        if dataname == 'blood_flow_rbf':
            vesselgroup, tumorgroup, cachelocation = args

            has_tumor = tumorgroup is not None
            data = dataman.obtain_data('blood_flow', vesselgroup, tumorgroup,
                                       cachelocation).copy()
            ldvessels = krebsutils.read_lattice_data_from_hdf(
                vesselgroup['lattice'])
            total_flow = data['total_flow_in']
            total_volume = np.cumprod(ldvessels.GetWorldSize())[2]
            total_flow_p_volume = total_flow / total_volume
            data['rBF_total'] = total_flow_p_volume
            data['total_volume'] = total_volume
            if has_tumor:
                ldtumor = dataman.obtain_data('ld', tumorgroup.file)
                theta_tumor = dataman.obtain_data('fieldvariable',
                                                  tumorgroup.file,
                                                  'theta_tumor',
                                                  tumorgroup.name)
                tumor_volume = np.sum(theta_tumor) * (ldtumor.scale**3)
                tumor_flow = data['flow_in']
                tumor_flow_p_volume = tumor_flow / tumor_volume
                data['rBF_tumor'] = tumor_flow_p_volume
                data['tumor_volume'] = tumor_volume
                #print 'estimated tumor volume:', tumor_volume
                #print 'tumor flow:', tumor_flow
                #print 'rBF:', tumor_flow_p_volume*60.
            data = dict(map(DataTumorBloodFlow.FixUnit_, data.items()))
            return data

        if dataname in ('cum_rbf_radial', 'avg_surf_vessel_rad_radial',
                        'sphere_vessel_density'):
            vesselgroup, tumorgroup, bins_spec, distance_distribution_name, ld, cachelocation = args
            WorkerFunction = {
                'cum_rbf_radial': ComputeIsosurfaceRegionalBloodFlow,
                'avg_surf_vessel_rad_radial': ComputeIsosurfaceAvgRadius,
                'sphere_vessel_density': ComputeSphereVesselDensity,
            }[dataname]
            version = {
                'cum_rbf_radial': 4,
                'avg_surf_vessel_rad_radial': 3,
                'sphere_vessel_density': 1,
            }[dataname]

            def read(gmeasure, groupname):
                gmeasure = gmeasure[groupname]
                return gmeasure['values'], gmeasure['bins']

            def write(gmeasure, groupname):
                values, bins = ComputeIsosurfaceRadialCurve(
                    dataman, vesselgroup, tumorgroup, bins_spec,
                    distance_distribution_name, ld, cachelocation,
                    WorkerFunction)
                gmeasure = gmeasure.create_group(groupname)
                gmeasure.create_dataset('values', data=values)
                gmeasure.create_dataset('bins', data=bins)

            return krebs.analyzeGeneral.HdfCacheRadialDistribution(
                (read, write), dataname, bins_spec, distance_distribution_name,
                cachelocation, version)
示例#23
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
示例#24
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)
示例#25
0
def runSTFTest():
    params = dict(
        tend=0.01,
        out_intervall=0.0001,
        stepper='impeuler',
        fn_out='sfttest',
        num_threads=2,
        kdiff=10.,
        kstf=0.5,
    )
    ld = krebsutils.LatticeDataQuad3d((0, 49, 0, 49, 0, 0), 1. / 50.)
    ld.SetCellCentering((True, True, False))
    extent = ld.worldBox[:4]
    #f_conc = lambda x,y,z: zalesakDisk((x,y,z), 0.3, (0.5,0.5,0.))
    f_conc = lambda x, y, z: circle_distfunc(x, y, z, 0.3, (0.5, 0.5, 0.))
    if not os.path.isfile('sfttest.h5'):
        surfaceTensionForceTest(dicttoinfo(params), ld,
                                dict(conc_profile=f_conc))

    rc = matplotlib.rc
    rc('font', size=8.)
    rc('axes', titlesize=10., labelsize=10.)
    rc('figure', **{'subplot.wspace': 0.15, 'subplot.hspace': 0.15})
    rc('savefig', facecolor='white')
    dpi = 100.
    results = Results('sfttest')
    ldface = (krebsutils.read_lattice_data_from_hdf(results.f['face_ld_0']),
              krebsutils.read_lattice_data_from_hdf(results.f['face_ld_1']))
    extface = tuple(q.worldBox[:4] for q in ldface)
    data = collections.defaultdict(list)
    for idx, group in enumerate(results):

        def show(a, ext):
            pyplot.imshow(np.asarray(a[..., 0]).transpose(),
                          extent=ext,
                          origin='bottom',
                          interpolation='nearest')

        def contour():
            return pyplot.contour(np.asarray(group['ls'][..., 0]).transpose(),
                                  levels=[0.],
                                  extent=extent,
                                  origin='lower')

        print "plotting %i" % idx
        if 1:
            pyplot.figure(figsize=(1200. / dpi, 1000. / dpi))

            #        pyplot.subplot(221)
            #        show(group['ls'], extent)
            #        pyplot.colorbar()
            #        contour()
            #        pyplot.subplot(222)
            #        show(group['rho'], extent)
            #        pyplot.colorbar()
            #        contour()

            pyplot.subplot(221)
            pyplot.plot(np.linspace(extent[0], extent[1], 50),
                        group['ls'][:, 25, 0])
            pyplot.gca().set(xlabel='x', ylabel=r'$\phi$')
            pyplot.gca().grid(color=(0.5, ) * 3)

            pyplot.subplot(222)
            pyplot.plot(np.linspace(extent[0], extent[1], 50),
                        group['rho'][:, 25, 0])
            pyplot.gca().set(xlabel='x', ylabel=r'$\rho$')
            pyplot.gca().grid(color=(0.5, ) * 3)

            pyplot.subplot(223)
            show(group['force_0'], extface[0])
            pyplot.colorbar()
            contour()
            pyplot.subplot(224)
            show(group['force_1'], extface[1])
            pyplot.colorbar()
            contour()
            pyplot.savefig("sfttest%04i.png" % idx, dpi=dpi)

        data['time'].append(group.attrs['time'])
        data['mass'].append(group.attrs['mass'])
        data['area'].append(group.attrs['area'])

    pyplot.figure(figsize=(1200. / dpi, 600. / dpi))
    pyplot.subplot(121)
    pyplot.plot(data['time'], data['mass'], marker='x')
    pyplot.gca().set(xlabel='t', ylabel='mass')
    pyplot.subplot(122)
    pyplot.plot(data['time'], data['area'], marker='+')
    pyplot.gca().set(xlabel='t', ylabel='area')
    pyplot.savefig('vstime.png')
示例#26
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)
示例#27
0
    def obtain_data(self, dataman, dataname, *args):
        if dataname == 'detailedPO2Parameters':
            po2group, = args
            return detailedo2.readParameters(po2group)

        if dataname == 'detailedPO2':
            po2group, = args
            a = np.asarray(po2group['po2vessels'])
            if a.shape[0] <> 2: a = np.transpose(a)
            po2field = po2group['po2field']
            ld = krebsutils.read_lattice_data_from_hdf(po2group['field_ld'])
            parameters = dataman.obtain_data('detailedPO2Parameters', po2group)
            return a, ld, po2field, parameters

        if dataname == 'detailedPO2_consumption':
            po2group, tumorgroup = args
            return detailedo2.computeO2Uptake(po2group, tumorgroup)

        if dataname == 'detailedPO2_samples' or dataname == 'detailedPO2_total_fluxes':
            prop, po2group, sample_length, every, cachelocation = args

            def read(gmeasure, name):
                gmeasure = gmeasure[name]
                if dataname == 'detailedPO2_samples':
                    if prop == 'gtv':
                        parameters = dataman.obtain_data(
                            'detailedPO2Parameters', po2group)
                        #po2 = dataman.obtain_data('detailedPO2_samples','po2', *args[1:])
                        #extpo2 = dataman.obtain_data('detailedPO2_samples','extpo2', *args[1:])
                        #return (po2-extpo2)/(parameters['grid_lattice_const']*parameters.get('transvascular_ring_size',0.5))
                        gvessels, gtumor = detailedo2.OpenVesselAndTumorGroups(
                            po2group)
                        jtv = dataman.obtain_data('detailedPO2_samples', 'jtv',
                                                  *args[1:])
                        #radius = dataman.obtain_data('basic_vessel_samples', 'radius', gvessels, sample_length)
                        #radius = radius * (60.e-4*math.pi*2.* parameters['kD_tissue']*parameters['alpha_t'])
                        radius = (
                            60.e-4 *
                            parameters.get('D_tissue',
                                           parameters.get('kD_tissue', None)) *
                            parameters.get('solubility_tissue',
                                           parameters.get('alpha_t', None)))
                        gtv = jtv / radius
                        return gtv
                    elif prop == 'sat':
                        po2 = dataman.obtain_data('detailedPO2_samples', 'po2',
                                                  *args[1:])
                        parameters = dataman.obtain_data(
                            'detailedPO2Parameters', po2group)
                        return detailedo2.PO2ToSaturation(po2, parameters)
                    else:
                        ds = gmeasure['smpl_' + prop]
                        ds = ds[...] if every is None else ds[::every]
                        return ds
                else:
                    keys = filter(lambda k: k.startswith('flux_'),
                                  gmeasure.keys())
                    fluxes = dict(map(lambda k: (k[5:], gmeasure[k][()]),
                                      keys))
                    fluxes['e1'] = abs(
                        100. * (fluxes['Jin_root'] - fluxes['Jout_root'] -
                                fluxes['Jout_tv']) / fluxes['Jin_root'])
                    fluxes['e2'] = abs(
                        100. *
                        (fluxes['Jin_root'] - fluxes['Jout_root'] -
                         fluxes['Jout_cons'] - fluxes.get('tv_cons', 0.)) /
                        fluxes['Jin_root'])
                    fluxes['e3'] = abs(
                        100. * (fluxes['Jout_tv'] - fluxes['Jout_cons'] -
                                fluxes.get('tv_cons', 0.)) / fluxes['Jout_tv'])
                    return fluxes

            def write(gmeasure, name):
                # do the sampling
                gvessels, gtumor = detailedo2.OpenVesselAndTumorGroups(
                    po2group)
                smpl, fluxes = detailedo2.sampleVessels(
                    po2group, gvessels, gtumor, sample_length)
                #cons = dataman.detailedPO2_consumption(po2group, gtumor)
                cons = dataman.obtain_data('detailedPO2_consumption', po2group,
                                           gtumor)
                # get the raw data, just for the consumption flux
                po2vessels, ld, po2field, parameters = dataman.obtain_data(
                    'detailedPO2', po2group)
                avgCons = np.asarray(myutils.largeDatasetAverage(cons),
                                     dtype=np.float64)
                fluxes['Jout_cons'] = avgCons * np.product(
                    cons.shape) * (ld.scale * 1.e-4)**3
                del po2vessels, po2field, ld

                gmeasure = gmeasure.create_group(name)
                for k, v in smpl.iteritems():
                    gmeasure.create_dataset('smpl_' + k,
                                            data=v,
                                            compression=9,
                                            dtype=np.float32)
                for k, v in fluxes.iteritems():
                    gmeasure.create_dataset('flux_' + k,
                                            data=v)  # scalar dataset

            version_id = myutils.checksum(sample_length, 3, getuuid_(po2group))
            ret = myutils.hdf_data_caching(
                read, write, cachelocation[0],
                (cachelocation[1], 'samples_and_fluxes'), (None, version_id))
            return ret

        if dataname == 'detailedPO2_global':
            prop, po2group, sample_length, cachelocation = args
            samplelocation = MakeSampleLocation(po2group)

            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

            def read(gmeasure, measurename):
                d = np.asarray(gmeasure[measurename])
                if measurename in ('chb_oxy', 'chb', 'chb_deoxy'):
                    d *= 1.e6
                return d[0]  # its a tuple (avg, std), we want avg now.

            version_num = collections.defaultdict(lambda: 3)
            version_id = myutils.checksum(sample_length, version_num[prop],
                                          getuuid_(po2group))
            #version_id = myutils.checksum(sample_length, (2 if prop in  else 1))
            return myutils.hdf_data_caching(read, write, cachelocation[0],
                                            ('global', cachelocation[1], prop),
                                            (1, 1, version_id))

        if dataname == 'detailedPO2_radial':
            po2group, sample_length, bins_spec, distance_distribution_name, cachelocation = args
            samplelocation = MakeSampleLocation(po2group)

            # we assume that there is a tumor. without this measurement makes little sense

            def read(gmeasure, name):
                d = dict(gmeasure[name].items())
                d = dict(
                    (k, myutils.MeanValueArray.read(v)) for k, v in d.items())
                hbo = d['vfhb_oxy']
                hbd = d['vfhb_deoxy']
                hb = myutils.MeanValueArray(hbo.cnt, hbo.sum + hbd.sum,
                                            hbo.sqr + hbd.sqr)
                d['vfhb'] = hb
                sat = hbo.avg / hb.avg
                d['sat_via_hb_ratio'] = myutils.MeanValueArray(
                    np.ones_like(hb.cnt), sat, sat * sat)
                d['chb_oxy'] = d['vfhb_oxy'] * detailedo2.chb_of_rbcs * 1.e6
                d['chb_deoxy'] = d['vfhb_deoxy'] * detailedo2.chb_of_rbcs * 1.e6
                d['chb'] = d['vfhb'] * detailedo2.chb_of_rbcs * 1.e6
                return d

            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

            version = getuuid_(po2group)
            ret = analyzeGeneral.HdfCacheRadialDistribution(
                (read, write), 'po2', bins_spec, distance_distribution_name,
                cachelocation, version)
            return ret
        assert False
示例#28
0
def vess_size_to_tum_size(fn, tum_lattice_const):
    vesselgroup = h5files.open(fn, 'r')['/vessels']
    if __debug__:
        print("vesselgroup.id.id: %i" % vesselgroup.id.id)
    ld = krebsutils.read_lattice_data_from_hdf(
        krebsutils.find_lattice_group_(vesselgroup))
    ld_vessels = krebsutils.read_lattice_data_from_hdf(vesselgroup['lattice'])
    bbox = ld_vessels.worldBox
    boxLengths = ((bbox[1] - bbox[0]), (bbox[3] - bbox[2]),
                  (bbox[5] - bbox[4]))
    number_of_numerical_grid_points = np.ceil(
        (np.asarray(boxLengths) + .5) / tum_lattice_const)
    for (i, x) in enumerate(number_of_numerical_grid_points):
        if x == 1:
            number_of_numerical_grid_points[i] = 2

    del vesselgroup
    l = ld.shape
    s = int(ld.scale)
    """
  mapping from: latticesize initial vesselsnetwork 
  to numical lattice of tissue lattice
  first number: size x
  second number: size z
  third number: lattice constant
  """
    vs = {
        (9, 1, 130): (10, 10),  #div runtime test
        (100, 6, 80): (228, 10),  # 100x5.80
        (100, 62, 80): (196, 128),  #100x50.80
        (200, 6, 80): (384, 10),  #200x5.80
        (60, 75, 80): (128, 128),  #60x60.80
        # now hierarchical builds
        (167, 17, 80): (300, 34),
        (103, 121, 80): (150, 150),
        # with large lattice spacing
        (59, 69, 150): (160, 160),
        (63, 65, 150): (160, 160),
        #(103,121,80) : (200, 200), # a special extra large configuration
        # 7x7 * 2^3 hierarchical biulds
        (127, 129, 80): (150, 150),  # actual size could be 270**3
        # twodimensional system
        (160, 1, 80): (350, 1),
        # quasi twodimensional
        (163, 9, 80): (350, 24),
        (59, 9, 150): (250, 32),
        # small system
        (31, 5, 150): (80, 16),
        # 16 cm flat
        (111, 9, 150): (267, 32),
        # 8mm P10 3d
        #(55,61, 130) : (80,90),
        #(55,61, 130) : (155,155),
        (55, 61, 130): (100, 100),
        # 8mm P10 q2d
        (59, 5, 130): (100, 15),
        (47, 9, 130): (50, 20),
        # for testing 3d_mini_mini
        (14, 18, 130): (40, 40),
        # trastuzumab calibration growth
        (53, 65, 80): (100, 100),
        # 5mm P11 q2d, 5mm x 5mm x 0.3mm
        (59, 5, 90):
        (int(4000. / tum_lattice_const), int(300. / tum_lattice_const + 0.5)),
        # swine h1
        (17, 19, 75):
        (int(1200. / tum_lattice_const), int(1200. / tum_lattice_const)),
        # swine h2
        (35, 37, 75): (int(1400. / tum_lattice_const),
                       int(1400. / tum_lattice_const)),
        # swine h2 -big (67, 77, 75
        (67, 77, 75): (int(5000. / tum_lattice_const),
                       int(5000. / tum_lattice_const)),
        # 4mm x 0.3 P? ??
        (51, 57, 88): (int(4000. / tum_lattice_const),
                       int(4000. / tum_lattice_const)),
        #the vessBigTras
        (119, 141, 88): (int(10000. / tum_lattice_const),
                         int(10000. / tum_lattice_const)),
    }  #[(l[0],l[2],s)]
    theKey = (l[0], l[2], s)
    if theKey in vs:
        return (vs[theKey][0], vs[theKey][0], vs[theKey][1])
    else:
        print('Warning: Guessed tum grid size')
        return number_of_numerical_grid_points.astype(int)
示例#29
0
def renderScene(drug_grp, imagefn, options):
    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']
    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(drug_grp.parent['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_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)
示例#30
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)