def DoIt_single(filenames, options): fn_measure = basename(commonprefix(filenames)) fn_measure = myutils.strip_from_end(fn_measure, '.h5') fn_measure = myutils.strip_from_end(fn_measure, '-type') f_measure = h5files.open('adaption_common.h5', 'a', search = False) files = [h5files.open(fn, 'r') for fn in filenames] groups_without_adaption = [f['/adaption/recomputed'] for f in files] groups_with_adaption = [f['/adaption/vessels_after_adaption'] for f in files] import analyzeGeneral dataman = myutils.DataManager(20, [ analyzeGeneral.DataBasicVessel(), analyzeGeneral.DataVesselSamples(), analyzeGeneral.DataVesselGlobal()]) with mpl_utils.PdfWriter(fn_measure+'flow_hist.pdf') as pdfpages: if 1: plotFlowHistogram(dataman, f_measure, filenames, options, pdfpages) with mpl_utils.PdfWriter(fn_measure+'radius_hist.pdf') as pdfpages: if 1: plotRadiusHistogram(dataman, f_measure, filenames, options, pdfpages) with mpl_utils.PdfWriter(fn_measure+'cap_flow_hist.pdf') as pdfpages: if 1: plotCapillaryFlowHistogram(dataman, f_measure, filenames, options, pdfpages) with mpl_utils.PdfWriter(fn_measure+'cap_radius_hist.pdf') as pdfpages: if 1: plotCapillaryRadiusHistogram(dataman, f_measure, filenames, options, pdfpages)
def DoIt(filenames, options): fn_measure = basename(commonprefix(filenames)) fn_measure = myutils.strip_from_end(fn_measure, '.h5') fn_measure = myutils.strip_from_end(fn_measure, '-type') f_measure = h5files.open('adaption_common.h5', 'a', search = False) files = [h5files.open(fn, 'r') for fn in filenames] groups_without_adaption = [f['/adaption/recomputed'] for f in files] groups_with_adaption = [f['/adaption/vessels_after_adaption'] for f in files] with mpl_utils.PdfWriter(fn_measure+'caps.pdf') as pdfpages: import analyzeGeneral dataman = myutils.DataManager(20, [ analyzeGeneral.DataBasicVessel(), analyzeGeneral.DataVesselSamples(), analyzeGeneral.DataVesselGlobal()]) # vesselgroups_without = groups_without_adaption # vesselgroups_with = groups_with_adaption # geometric_data_before = getGeometricData(groups_without_adaption) # perfusion_data_before = getTotalPerfusion(groups_without_adaption)*60 # geometric_data_after = getGeometricData(groups_with_adaption) # perfusion_data_after = getTotalPerfusion(groups_with_adaption)*60 if 1: plotFlowHistogram(dataman, f_measure, filenames, options, pdfpages) if 1: plotRadiusHistogram(dataman, f_measure, filenames, options, pdfpages) if 1: plotCapillaryFlowHistogram(dataman, f_measure, filenames, options, pdfpages) if 1: plotCapillaryRadiusHistogram(dataman, f_measure, filenames, options, pdfpages)
def plot_single_capillary(dataman, group, useInsets = False): # used to plot reproduction cases of nair 1989 plt = Plotty(dataman, group, '') with mpl_utils.PdfWriter('sv-'+os.path.basename(group.name)+'.pdf') as pdfwriter: fig0, (ax0, ax2) = pyplot.subplots(2,1, figsize = (mpl_utils.a4size[0]*0.35, mpl_utils.a4size[1]*0.30)) fig1, ax1 = pyplot.subplots(1,1, figsize = (mpl_utils.a4size[0]*0.35, mpl_utils.a4size[1]*0.15)) plt.PlotSamples(ax0,'po2', label = 'P', **niceMarker(0, 'k')) plt.PlotSamples(ax0,'extpo2', label = 'P$_t$', **niceMarker(1, 'k')) plt.PlotSamples(ax2,'sat', label = None, **niceMarker(2,'k')) c = niceColors(3) plt.PlotField(ax1, xcoord = 200, color = c[0], addXMark = True, addYMark = True, marker = 1, label = 'x = 0.2 mm') plt.PlotField(ax1, xcoord = 2000, color = c[1], addXMark = True, addYMark = True, marker = 1, label = 'x = 1 mm') plt.PlotField(ax1, xcoord = 3800, color = c[2], addXMark = True, addYMark = True, marker = 1, label = 'x = 3.8 mm') ax0.legend() ax1.legend() ax2.set(xlabel = 'x [mm]', ylabel = 'S') ax0.set(xlabel = 'x [mm]', ylabel = 'PO$_2$ [mmHg]') ax1.set(xlabel = 'y$_1$ [$\mu$m]', ylabel = 'PO$_2$ [mmHg]', xlim = (-200., 200.)) #title = 'Tissue $PO_2$ - Transversal' ylim = (40., 100.) for ax in [ax0, ax1, ax2]: ax.yaxis.grid(True, which='major', color = '#f0f0f0', ls = '-') mpl_utils.tight_layout(fig0) mpl_utils.tight_layout(fig1) pdfwriter.savefig(fig0, postfix='_long') pdfwriter.savefig(fig1, postfix='_trans') plt.AddStatsPage(pdfwriter) pyplot.close('all')
def plot_single_capillary_long(dataman, group, useInsets = False): plt = Plotty(dataman, group, '') with mpl_utils.PdfWriter('sv-'+os.path.basename(group.name)+'.pdf') as pdfwriter: fig0, ax0 = pyplot.subplots(1,1, figsize = (mpl_utils.a4size[0]*0.35, mpl_utils.a4size[1]*0.15)) fig1, ax1 = pyplot.subplots(1,1, figsize = (mpl_utils.a4size[0]*0.35, mpl_utils.a4size[1]*0.15)) plt.PlotSamples(ax0,'po2', label = 'P', **niceMarker(0, 'k')) plt.PlotSamples(ax0,'extpo2', label = 'P$_t$', **niceMarker(1, 'k')) c = niceColors(4) plt.PlotField(ax1, xcoord = 100, color = c[0], addXMark = True, addYMark = True, marker = 1, label = 'x = 0.1 mm') plt.PlotField(ax1, xcoord = 1000, color = c[1], addXMark = True, addYMark = True, marker = 1, label = 'x = 1 mm') plt.PlotField(ax1, xcoord = 4000, color = c[2], addXMark = True, addYMark = True, marker = 1, label = 'x = 4 mm') plt.PlotField(ax1, xcoord = 48000, color = c[3], addXMark = True, addYMark = True, marker = 1, label = 'x = 48 mm') ax0.legend() ax1.legend() #plt.StyleSamplePlot(ax0, title = '$PO_2$ Longitudinal', yquantity = 'po2') #plt.StyleTransversalPlot(ax1, title = 'Tissue $PO_2$ - Transversal') ax0.set(xlabel = 'x [mm]', ylabel = 'PO$_2$ [mmHg]') ax1.set(xlabel = 'y$_1$ [$\mu$m]', ylabel = 'PO$_2$ [mmHg]', ylim = (40., 100.), xlim = (-200., 200.)) #title = 'Tissue $PO_2$ - Transversal' for ax in [ax0, ax1]: ax.yaxis.grid(True, which='major', color = '#f0f0f0', ls = '-') mpl_utils.tight_layout(fig0) mpl_utils.tight_layout(fig1) pdfwriter.savefig(fig0, postfix='_long') pdfwriter.savefig(fig1, postfix='_trans') plt.AddStatsPage(pdfwriter) pyplot.close('all')
def compare_single_capillary3(dataman, outfilename, grouplist, axisticks): plotties = [] for group, label in grouplist: plotties.append(Plotty(dataman, group, label)) colors = niceColors(len(grouplist)) with mpl_utils.PdfWriter('comp-' + outfilename + '.pdf') as pdfwriter: fig, axes = pyplot.subplots(3, 1, figsize=(mpl_utils.a4size[0] * 0.4, mpl_utils.a4size[1] * 0.5)) axes = axes.ravel() for i, plt in enumerate(plotties): plt.PlotSamples(axes[0], 'extpo2', colors[i], 0, None) plt.PlotSamples(axes[0], 'po2', colors[i], 1, plt.label) axes[0].legend(loc=mpl_utils.loc.lower_left) axes[0].set(xlabel='x [$\mu$m]', ylabel='mmHg', title='PO$_2$ - Longitudinal') axes[0].set(ylim=(50., 100.)) #axes[1].set(xlabel = 'x [$\mu m$]', ylabel = Prettyfier.get_bunit('sat'), title = Prettyfier.get_msym('sat')+' - Longitudinal') for i, plt in enumerate(plotties): plt.PlotFieldLongitudinal(axes[1], color=colors[i]) plt.PlotSamples(axes[1], 'po2', colors[i], 1, None) axes[1].legend(loc=mpl_utils.loc.lower_left) axes[1].set(xlabel='x [$\mu$m]', ylabel='mmHg', title='PO$_2$ - Longitudinal') for i, plt in enumerate(plotties): plt.PlotField(axes[2], sampleIndex=plt.numSamples / 2, color=colors[i], addXMark=True, addYMark=True, marker=True) #xcoord = 500 #axins.xaxis.set_major_locator(matplotlib.ticker.MaxNLocator(nbins = 3)) #axins.yaxis.set_major_locator(matplotlib.ticker.MaxNLocator(nbins = 3)) axes[2].set(title=r'P$_t$ Transv.') axes[2].tick_params(axis='both', which='major', labelsize=8) axes[2].set(xlabel='y$_1$ [$\mu$m]', ylabel='mmHg', title='Tissue PO$_2$ - Transversal', ylim=(0., 100.)) for ax in axes: ax.yaxis.grid(True, which='major', color='#f0f0f0', ls='-') pyplot.tight_layout() pdfwriter.savefig(fig, postfix='_curves') plotAnalyzeConvergence(dataman, pdfwriter, plotties) plotties[0].AddStatsPage(pdfwriter) plotAnalyzeIterativeConvergence(dataman, pdfwriter, plotties) pyplot.close('all')
def plotit(fn): out_fn = os.path.splitext(fn)[0] fd = Filedata1d(fn) if 1: data = [(g.attrs['time'], g.attrs['tumor_radius']) for g in [fd.f[gn] for gn in fd.groupnames]] if len(fd.groupnames) >= 2: maxv = max( np.amax(np.abs(fd.f[gn]['vel_0'])) for gn in fd.groupnames[2:]) data = np.asarray(data).transpose() from scipy.optimize import leastsq func = lambda p, x, y: (x * p[0] + p[1] - y) p, success = leastsq(func, (1, 0), args=(data[0], data[1])) estv = p[0] print 'estimated velocity: %f, max vel.: %f' % (estv, maxv) else: estv, maxv = 0, 0 if 0: rc = matplotlib.rc rc('figure', figsize=(8.3, 11.7)) rc('font', size=13) #rc('axes', titlesize = 12., labelsize = 12.) rc('legend', fontsize='small') else: dpi = 80 rc = matplotlib.rc rc('figure', figsize=list(0.75 / dpi * np.asarray([1024, 768])), dpi=dpi) rc('font', size=12.) rc('axes') #, titlesize = 12., labelsize = 12.) rc('pdf', compression=6, fonttype=42) rc( 'figure', **{ 'subplot.left': 0.04, 'subplot.right': 1. - 0.04, 'subplot.bottom': 0.06, 'subplot.top': 1. - 0.06, 'subplot.wspace': 0.1, 'subplot.hspace': 0.1 }) rc('savefig', facecolor='none', edgecolor='none', dpi=dpi) rc('font', **{'family': 'sans-serif'}) #,'sans-serif':['Helvetica']}) rc('path', simplify_threshold=0.01) with mpl_utils.PdfWriter(out_fn) as pdf: for g in fd.groupnames: print fn, g #title = r'%s ($v_e = %s, v_{max} = %s$)' % (splitext(basename(fn))[0], myutils.f2s(estv), myutils.f2s(maxv)) title = '' fig = simplePlot(fd, g, title) pdf.savefig(fig) plt.close()
def compare_single_capillary2(dataman, outfilename, grouplist, axisticks): plotties = [] for group, label in grouplist: plotties.append(Plotty(dataman, group, label)) colors = niceColors(len(grouplist)) with mpl_utils.PdfWriter('comp-'+outfilename+'.pdf') as pdfwriter: fig, axes = pyplot.subplots(3,1, figsize = (mpl_utils.a4size[0]*0.35, mpl_utils.a4size[1]*0.45)) axes = axes.ravel() for i, plt in enumerate(plotties): plt.PlotSamples(axes[0], 'po2', label = plt.label, **niceMarker(0, colors[i])) plt.PlotSamples(axes[1], 'extpo2', **niceMarker(1, colors[i])) plt.PlotSamples(axes[2], 'sat', label = plt.label, **niceMarker(2, colors[i])) axes[0].legend(loc = mpl_utils.loc.lower_left) axes[0].set(ylabel = r'P [mmHg]') axes[1].set(ylabel = r'P$_t$ [mmHg]') axes[2].set(ylabel = r'S') axes[2].set(ylim = (0.80, 1.), xlabel = '$x$ [mm]') for ax in axes[0:2]: ax.set(ylim = (50., 100.)) #ax.xaxis.set(visible=False) ax.set(xticklabels = []) for ax in axes: ax.yaxis.grid(True, which='major', color = '#f0f0f0', ls = '-') pyplot.tight_layout() pdfwriter.savefig(fig, postfix='_po2') fig, ax = pyplot.subplots(1,1, figsize = (mpl_utils.a4size[0]*0.35, mpl_utils.a4size[1]*0.15)) for i, plt in enumerate(plotties): plt.PlotField(ax, sampleIndex = plt.numSamples/2, color = colors[i], addXMark = False, addYMark = True, marker = True) #xcoord = 500 #ax.set(title = r'$P_t$ Transv.') #ax.tick_params(axis='both', which='major', labelsize=8) ax.set(xlabel = 'y$_1$ [$\mu$ m]', ylabel = 'PO$_2$ [mmHg]', ylim = (40., 100.), xlim = (-200., 200.)) #title = 'Tissue $PO_2$ - Transversal' ax.yaxis.grid(True, which='major', color = '#f0f0f0', ls = '-') pyplot.tight_layout() pdfwriter.savefig(fig, postfix='_transv') # axins = mpl_utils.inset_axes(axes[0], # width="60%", # width = 30% of parent_bbox # height="30%", # height : 1 inch # loc=mpl_utils.loc.upper_right) # axins.xaxis.set_major_locator(matplotlib.ticker.MaxNLocator(nbins = 3)) # axins.yaxis.set_major_locator(matplotlib.ticker.MaxNLocator(nbins = 3)) # axins.set(title = r'$P_t$ Transv.') # axins.tick_params(axis='both', which='major', labelsize=8) plotties[0].AddStatsPage(pdfwriter) plotAnalyzeIterativeConvergence(dataman, pdfwriter, plotties) pyplot.close('all')
def plotSingleRun(fn): out = splitext(basename(fn))[0] f = h5files.open(fn, 'r') rc = matplotlib.rc rc('figure', figsize=(7, 7), dpi=100) rc('font', size=8.) rc('axes', titlesize=10., labelsize=10.) rc('pdf', compression=6, fonttype=42) rc( 'figure', **{ 'subplot.left': 0.02, 'subplot.right': 1. - 0.05, 'subplot.bottom': 0.01, 'subplot.top': 1. - 0.05, 'subplot.wspace': 0.1, 'subplot.hspace': 0.1 }) #rc('savefig', facecolor='none', edgecolor='none', dpi=100) rc('savefig', dpi=100) rc('font', **{'family': 'sans-serif'}) #,'sans-serif':['Helvetica']}) rc('path', simplify_threshold=0.01) #rc('text', usetex=True, **{ 'latex.unicode' : True }) with mpl_utils.PdfWriter(out + ".pdf") as pdfpages: dataman = myutils.DataManager(100, [ DataTumorTissueSingle(), DataTumorMeasureCurvature(), DataTumor3dRendering(), DataTissueRadial(), DataTissueRadialAveraged() ]) resultfile = ResultFile(f, dataman) is3d = resultfile.obtain_data('ld').shape[2] > 1 if is3d: plot3dRendering(resultfile, pdfpages, showVessels=True, showTumor=False) plot3dRendering(resultfile, pdfpages) plot3dRendering(resultfile, pdfpages, showVessels=True) plotSnapshots(resultfile, pdfpages)
def run_numerical_tests(): convergence_step_widths = [ 0.01, 0.02, 0.04, 0.08, 0.16, 0.32, 0.64, 1. ] stepper_methods = [ 'euler', 'impeuler', 'vsimexbdf2', 'rk3', 'rk4' ] gridsizes = [ 30, 5, 1 ] def run_different_steppers(name, cc): for stepper in stepper_methods: c = deepcopy(cc) c['stepper'] = stepper if stepper == 'vsimexbdf2': c['tumor']['timestep_factor'] = 0.2 run(name+'-'+stepper, c) def run_3d(name, cc, size, stepper): c = deepcopy(cc) c['tumor']['timestep_factor'] = 0.1 if (stepper == 'vsimexbdf2') else 1. c['stepper'] = stepper c['lattice_size'] = Vec((size,)*3) c['tumor']['interface_width'] = 30. c['tend'] = 20 c['out_intervall'] = 20 c['tumor']['write_face_velocities'] = False run(name+"-s%03i-%s" % (size, stepper), c) def run_3d_performance_tests(): for l in [ 40, 70, 100, 120, 150 ]: run_3d('prez3d', cfg, l, 'vsimexbdf2') run_3d('prez3d', cfg, l, 'impeuler') def run_lattice_and_stepwidth(name, cc, s, h, stepper): c = deepcopy(cc) c['tend'] = 1000. c['lattice_size'] = Vec((int(100*30/s), 1, 1)) c['lattice_scale'] = s c['stepper'] = stepper c['tumor']['timestep_factor'] = h c['tumor']['elliptic_solver_params'] = { 'use_multigrid' : True } run(name+"-conv-s%02i-h%0.3f-%s" % (s,h,stepper), c) def run_convergence_test(name, cc): cc = deepcopy(cc) cc['o2_rel_tumor_source_density'] = 1. name = name+'-maxo2' for lw in [ 5, 10, 15, 30, 60 ]: run_lattice_and_stepwidth(name, cc, lw, 1, 'impeuler') run_lattice_and_stepwidth(name, cc, 5, 1, 'rk4') # cc['tumor']['interface_width'] = 60. # for lw in [ 5, 10, 15, 30, 60 ]: # run_lattice_and_stepwidth(name+'-reg30', cc, lw, 1, 'impeuler') # run_lattice_and_stepwidth(name+'-reg30', cc, 5, 1, 'rk4') # # cc['tumor']['interface_width'] = 120. # for lw in [ 5, 10, 15, 30, 60 ]: # run_lattice_and_stepwidth(name+'-reg60', cc, lw, 1, 'impeuler') # run_lattice_and_stepwidth(name+'-reg60', cc, 5, 1, 'rk4') if 0: # test steppers #run_different_steppers('prez1d', cfg) #run_3d_performance_tests() # check how the solution depends on the lattice spacing and time step length run_convergence_test('prez1d', cfg) if 1: rc = matplotlib.rc rc('font', size = 12) rc('axes', titlesize = 12., labelsize = 12.) rc('legend', fontsize = 9) plt.subplots_adjust(wspace=0.5) if 0: # plot individuals for fn in ['prez1d-%s.h5' % n for n in stepper_methods]: print 'plotting', fn pdf = mpl_utils.PdfWriter(splitext(fn)[0] + ".pdf") fd = Filedata1d(fn) for g in fd.groupnames: simplePlot(pdf, fd, g, fd.f['parameters'].attrs['stepper']) pdf.close() if 0: # plot comparison of different methods pdf = mpl_utils.PdfWriter("compare1.pdf") fdnames = ['euler', 'vsimexbdf2', 'rk3'] fds = [ Filedata1d('prez1d-%s.h5' % n) for n in fdnames ] for g in fds[0].groupnames[-1:]: print 'plotting', g comparePlot(pdf, fds, fdnames, g, ['ptc', 'ls', 'vel_0', 'press'], 'Methods') pdf.close() if 1: # plot comparison of different time steps pdf = mpl_utils.PdfWriter("compare3.pdf") fd_ref = Filedata1d('prez1d-maxo2-conv-s05-h1.000-rk4.h5') grp_name = fd_ref.groupnames[-1] def compare(name, title, configs): title_format = r'$l$=%i, $h=%.1f h_{euler}$, %s' fds, fdtitles = [], [] for s, h, m in configs: fn ="%s-conv-s%02i-h%0.3f-%s.h5" % (name, s,h,m) print 'plotting', fn fds.append(Filedata1d(fn)) fdtitles.append(title_format % (s,h,m)) iwidth = float(fds[0].f['parameters']['tumor'].attrs.get('interface_width',-1)) iwidth = r"$4 \cdot l$" if iwidth < 0 else (r"$%.1f \mu m$" % iwidth) fig = comparePlot(fds, fdtitles, grp_name, ['ptc', 'ls', 'vel_0', 'press', 'conc'], 'Stepwidths'+title+(' $\delta=$%s ' % iwidth)) pdf.savefig(fig) # compare('prez1d', '', [ # (1,1,'vsimexbdf2'), # (5,1,'vsimexbdf2'), # (30, 1, 'vsimexbdf2') # ]) # # compare('prez1d', '', [ # (1,1.,'vsimexbdf2'), # (10,1.,'rk4'), # (30,1., 'rk4')]) stepper = 'impeuler' stepw = 1. compare('prez1d-maxo2', ' $max_{o2}$ ', [ (5,stepw,stepper), (10,stepw,stepper), (15,stepw,stepper), (30,stepw,stepper), (60,stepw,stepper), (5,1,'rk4'), ]) compare('prez1d-maxo2-reg30', r' $max_{o2}$ ', [ (5,stepw,stepper), (10,stepw,stepper), (15,stepw,stepper), (30,stepw,stepper), (60,stepw,stepper), (5,1,'rk4'), ]) compare('prez1d-maxo2-reg60', r' $max_{o2}$ ', [ (5,stepw,stepper), (10,stepw,stepper), (15,stepw,stepper), (30,stepw,stepper), (60,stepw,stepper), (5,1,'rk4'), ]) pdf.close() if 0: # memory and runtime pdf = mpl_utils.PdfWriter("performance1.pdf") data = [] for fn in glob.glob('prez3d-*.h5'): print fn fd = Filedata1d(fn) g = fd.f[fd.groupnames[-1]] s = Struct(dict( (k, g.attrs[k]) for k in ['mem_vsize', 'mem_rss', 'real_time', 'time'], )) s['stepper'] = fd.f.attrs['stepper'] s['size'] = fd.f['field_ld'].attrs['SIZEX'] data.append(s) data2 = collections.defaultdict(list) for d in data: data2[(d['stepper'])].append(d) for k, l in data2.iteritems(): l.sort(key = lambda d: d.size) l = myutils.zipListOfDicts(l, numpy_output=True) l['mem_rss'] /= (1024.**2) l['mem_vsize'] /= (1024.**2) l['real_time'] /= 1000. l['dofs'] = l['size']**3 data2[k] = l fig = plt.figure() plt.xlabel('lateral size') plt.ylabel('mem [Mb]') for stepper, l in data2.iteritems(): plt.plot(l['size'], l['mem_vsize'], label='%s, rss' % (stepper)) plt.plot(l['size'], l['mem_rss'], label='%s, vsize' % (stepper)) plt.legend() pdf.savefig(fig) fig = plt.figure() plt.xlabel('lateral size') plt.ylabel('mem / sites [bytes]') for stepper, l in data2.iteritems(): plt.plot(l['size'], l['mem_vsize']*(1024**2)/l['dofs'], label='%s, rss' % (stepper)) plt.plot(l['size'], l['mem_rss']*(1024**2)/l['dofs'], label='%s, vsize' % (stepper)) plt.legend() pdf.savefig(fig) fig = plt.figure() plt.xlabel('lateral size') plt.ylabel('run time / sim time [s]') for stepper, l in data2.iteritems(): plt.plot(l['size'], l['real_time']/l['time'], label='%s' % (stepper)) plt.legend() pdf.savefig(fig) fig = plt.figure() plt.xlabel('lateral size') plt.ylabel('run time / (sim time $\cdot$ sites) [$\mu$s]') for stepper, l in data2.iteritems(): plt.plot(l['size'], l['real_time']*(1000**2)/l['dofs']/l['time'], label='%s' % (stepper)) plt.legend() pdf.savefig(fig) pdf.close()
def DoIt(filenames, options): fn_measure = basename(commonprefix(filenames)) fn_measure = myutils.strip_from_end(fn_measure, '.h5') fn_measure = myutils.strip_from_end(fn_measure, '-type') f_measure = h5files.open('adaption_common.h5', 'a', search = False) files = [h5files.open(fn, 'r') for fn in filenames] groups_with_adaption = [f['/vessels_after_adaption'] for f in files] #this data is stored with the adaption files_without_adaption = [] for afile in files: completeFilename=str(afile['/vessels_after_adaption/parameters'].attrs['cwd'])+'/'+str(afile['/vessels_after_adaption/parameters'].attrs['vesselFileName']) files_without_adaption.append( h5files.open(completeFilename)) groups_without_adaption = [f['vessels'] for f in files_without_adaption] with mpl_utils.PdfWriter('adaption_' + fn_measure+'.pdf') as pdfpages: import analyzeGeneral dataman = myutils.DataManager(20, [ analyzeGeneral.DataBasicVessel(), analyzeGeneral.DataVesselSamples(), analyzeGeneral.DataVesselGlobal()]) # vesselgroups_without = groups_without_adaption # vesselgroups_with = groups_with_adaption geometric_data_before = getGeometricData(groups_without_adaption) perfusion_data_before = getTotalPerfusion(groups_without_adaption)*60 geometric_data_after = getGeometricData(groups_with_adaption) perfusion_data_after = getTotalPerfusion(groups_with_adaption)*60 if 1: res_without = getMultiScatter(300. * len(filenames), groups_without_adaption) plotMultiScatterBeauty(res_without, pdfpages) res_with = getMultiScatter(300. * len(filenames), groups_with_adaption) plotMultiScatterBeauty(res_with, pdfpages, withRadiusPressureRelation=False) # if 0: # PlotRadiusHistogram2(dataman, groups_without_adaption, pdfpages) # PlotRadiusHistogram2(dataman, groups_with_adaption, pdfpages) # if 0: #printBarPlot_rBV(filenames, pdfpages) -->alt printBarPlot_rBV(dataman, f_measure, filenames, options, pdfpages) #-->mw enginered if 0: printBarPlot_rBF(dataman, f_measure, filenames, options, pdfpages) if 0: PlotRadiusHistogram_with_cache_by_RC(dataman, f_measure, filenames, options, pdfpages) #PlotRadiusHistogram_with_cache(dataman, f_measure, filenames, options, pdfpages) if 0: printBarPlot_vesseltype_on_root_node_configuration(filenames, pdfpages) ## is it worth to update this ??? if 1: #importing the murray thing #DoGetMurray(filenames, pdfpages) printMurray(dataman, f_measure, filenames, options, pdfpages) if 1: printMurray_alphas_effective(dataman, f_measure, filenames, options, pdfpages) if 1: text = ["Before adaption"] text2 = FormatGeometricAndPerfusionData(geometric_data_before, perfusion_data_before) text = text+text2 def cachelocation(g): path = posixpath.join('FileCS_'+myutils.checksum(basename(g.file.filename)), g.name.strip(posixpath.sep)) return (f_measure, path) prop_list2 = ['shearforce', 'velocity'] for name in prop_list2: data = [] for gvessels in groups_without_adaption: data.append(dataman.obtain_data('basic_vessel_global', name, gvessels, cachelocation(gvessels))) text.append(r'$<%s>$ = $%s$%s' % (Prettyfier.get_sym(name), Format(name, data), Prettyfier.get_munit(name))) fig, _ = mpl_utils.MakeTextPage(text,figsize = (mpl_utils.a4size[0]*0.8, mpl_utils.a4size[0]*0.8)) pdfpages.savefig(fig, postfix='_vesselsglobal') text = FormatParameters(groups_without_adaption[0].file) fig, _ = mpl_utils.MakeTextPage(text,figsize = (mpl_utils.a4size[0]*0.8, mpl_utils.a4size[0]*0.8)) pdfpages.savefig(fig, postfix='_vesselsparams') text = ["After adaption"] text2 = FormatGeometricAndPerfusionData(geometric_data_after, perfusion_data_after) text = text+text2 def cachelocation(g): path = posixpath.join('FileCS_'+myutils.checksum(basename(g.file.filename)), g.name.strip(posixpath.sep)) return (f_measure, path) prop_list2 = ['shearforce', 'velocity'] for name in prop_list2: data = [] for gvessels in groups_with_adaption: data.append(dataman.obtain_data('basic_vessel_global', name, gvessels, cachelocation(gvessels))) text.append(r'$<%s>$ = $%s$%s' % (Prettyfier.get_sym(name), Format(name, data), Prettyfier.get_munit(name))) fig, _ = mpl_utils.MakeTextPage(text,figsize = (mpl_utils.a4size[0]*0.8, mpl_utils.a4size[0]*0.8)) pdfpages.savefig(fig, postfix='_vesselsglobal') text = FormatParameters(groups_without_adaption[0].file) fig, _ = mpl_utils.MakeTextPage(text,figsize = (mpl_utils.a4size[0]*0.8, mpl_utils.a4size[0]*0.8)) pdfpages.savefig(fig, postfix='_vesselsparams') if 0 and all(map(lambda g: 'data' in g.parent, groups_without_adaption)): data = VesselData() for g in groups_without_adaption: data.add(g.parent['data']) plot_topological_stats_avg(data, pdfpages) if 1: #PlotQdevs_unnormalized(filenames, pdfpages) PlotQdevs_normalized(filenames, options, pdfpages)
def DoIt(filenames, pattern, with_o2): fn_measure = basename(commonprefix(filenames)) fn_measure = myutils.strip_from_end(fn_measure, '.h5') fn_measure = myutils.strip_from_end(fn_measure, '-type') def cachelocation(g): path = posixpath.join( 'FileCS_' + myutils.checksum(basename(g.file.filename)), g.name.strip(posixpath.sep)) return (f_measure, path) if with_o2: fn_measure = myutils.strip_from_end(fn_measure, '_detailedpo2') files = [h5files.open(fn, 'a') for fn in filenames] f_measure = h5files.open('plotVessels_chache.h5', 'a', search=False) groups = list( itertools.chain.from_iterable( myutils.walkh5(f, pattern, return_h5objects=True) for f in files)) if len(groups) <= 0: print 'no matching groups in hdf file(s)' sys.exit(0) if with_o2: name = posixpath.commonprefix(map(lambda g: g.name, groups)) name = myutils.strip_from_start(name, '/po2/vessels').replace('/', '-') fn_measure += name with mpl_utils.PdfWriter(fn_measure + '.pdf') as pdfpages: rc = matplotlib.rc rc('font', size=8.) rc('axes', titlesize=10., labelsize=8.) if with_o2: import detailedo2Analysis as o2analysis import detailedo2Analysis.plotsForPaper import detailedo2 dataman = myutils.DataManager(20, [ o2analysis.DataDetailedPO2(), analyzeGeneral.DataTumorTissueSingle(), analyzeGeneral.DataDistanceFromCenter(), analyzeGeneral.DataBasicVessel(), analyzeGeneral.DataVesselSamples(), analyzeBloodFlow.DataTumorBloodFlow(), analyzeGeneral.DataVesselRadial(), analyzeGeneral.DataVesselGlobal() ]) vesselgroups = list( detailedo2.OpenVesselAndTumorGroups(g)[0] for g in groups) #original_vesselgroups = list(h5files.openLink(g, 'SOURCE') for g in vesselgroups) if 1: PrintGlobalDataWithOxygen(pdfpages, groups, vesselgroups, f_measure, dataman) '''FormatParameters makes the network creation parameters that does not work, if we have an o2 file''' #text = FormatParameters(original_vesselgroups[0].file) text = [' '] text += detailedo2Analysis.plotsForPaper.FormatParameters( groups[0]) fig, _ = mpl_utils.MakeTextPage(text, figsize=(mpl_utils.a4size[0], mpl_utils.a4size[0])) pdfpages.savefig(fig, postfix='_vesselsparams') if 1: res = getMultiScatter(300. * len(filenames), vesselgroups) plotMultiScatterBeauty(res, pdfpages) else: dataman = myutils.DataManager(20, [ analyzeGeneral.DataTumorTissueSingle(), analyzeGeneral.DataVesselRadial(), analyzeGeneral.DataDistanceFromCenter(), analyzeBloodFlow.DataTumorBloodFlow(), analyzeGeneral.DataBasicVessel(), analyzeGeneral.DataVesselSamples(), analyzeGeneral.DataVesselGlobal() ]) #dataman = myutils.DataManager(20, [ analyzeGeneral.DataBasicVessel(), analyzeGeneral.DataVesselSamples(), analyzeGeneral.DataVesselGlobal()]) vesselgroups = groups if 0: res = getMultiScatter(300. * len(filenames), vesselgroups) plotMultiScatterBeauty(res, pdfpages) if 0: PlotRadiusHistogram2(dataman, vesselgroups, pdfpages) if 0 and all(map(lambda g: 'data' in g.parent, vesselgroups)): data = VesselData() for g in vesselgroups: data.add(g.parent['data']) plot_topological_stats_avg(data, pdfpages) if 0: #reproduce swine plot_geometric_stuff_on_RC(dataman, f_measure, filenames, options, pdfpages) if 1: PrintGlobalData(pdfpages, vesselgroups, f_measure, dataman)
tumorVolumes.append(tumorVolumes_per_time) fig1 = plt.figure() ax1 = fig1.add_subplot(111) # ax1.scatter(timepoints,np.mean(hypoxicVolumes,0),color='r',label=r"hypoxic($PO_2$<%.1f mmHg)" %threshold) # ax1.scatter(timepoints,np.mean(tumorVolumes,0),color='b',label=r"tumor radius") ax1.errorbar(timepoints,np.mean(hypoxicVolumes,0),np.std(hypoxicVolumes,0),color='r',label=r"hypoxic($PO_2$<%.1f mmHg)" %threshold) ax1.scatter(timepoints,np.mean(tumorVolumes,0),color='b',label=r"tumor radius") ax1.set_xlabel('time/ s') ax1.set_ylabel(r"volume/$mm^3$") #ax1.set_ylabel(r"hypoxic volume ($PO_2$<%.1f mmHg)/$mm^3$" %threshold) ax1.legend(loc=2) common = os.path.commonprefix([afile.name for afile in goodArguments.oxygenFiles]) ax1.set_title('file: %s' % common) with mpl_utils.PdfWriter('hypoxic_%s.pdf' % common) as pdfpages: pdfpages.savefig(fig1, postfix='_vesselsglobal') def run_out_in_single_file(goodArguments): print('starting with arguments: %s' % goodArguments) no_files = len(goodArguments.oxygenFiles) annoxicVolumes=[] hypoxicVolumes=[] normoxicVolumes=[] tumorVolumes=[] #threshold = 15 threshold1 = 0.1 threshold2 = 2.5 test = myutils.MeanValueArray.empty()
raise AssertionError('pattern "%s" not found in "%s"!' % (grp_pattern, fn)) else: dirs = set.union(dirs, d) except Exception, e: print e.message sys.exit(-1) print('Resolved groups: %s' % ','.join(dirs)) #create filename due to former standards filenames = [] for fn in goodArguments.vesselFileNames: filenames.append(fn.name) #either specify group, like in tumor simuations or take all from the ensemble if 0: for afilename in filenames: print("got file: %s" % afilename) if not filenames: print("python2 got no filenames") with mpl_utils.PdfWriter('murray' + '.pdf') as pdfpages: DoGetMurray(filenames, pdfpages) else: pattern = goodArguments.grp_pattern print(pattern) print(filenames[0]) outfilename = 'murray_for_file_%s' % basename(filenames[0]) with mpl_utils.PdfWriter(outfilename + '.pdf') as pdfpages: DoGetMurrayForSingleFileGENERAL(filenames[0], pattern, pdfpages) DoGetMurrayForSingleFileGENERALtwoSingleFigs( filenames[0], pattern, pdfpages)
'r', linewidth=1., label=(r'$\propto \epsilon ^ {- %s \pm %s }$' % (myutils.f2s(avg_df, latex=True), myutils.f2s(std_df, latex=True, prec=1)))) #label = df_formula(avg_df)) ax.plot(dflist[0].bs, dflist[0].getY((-avg_df + std_df, avg_y0)), 'r', linewidth=1.) ax.set(xscale='log', yscale='log', xlabel=r'boxsize $\epsilon$', ylabel=r'boxcount', xlim=(10., 10000.)) ax.grid(linestyle=':', linewidth=0.5, color=(0.7, 0.7, 0.7)) ax.legend(loc=3) # dslee gets 2.52 +/- 0.05 print 'df = %f +/- %f' % (avg_df, std_df) pyplot.show() fig.subplots_adjust(left=0.3, right=1. - 0.3, top=1. - 0.3, bottom=0.3) commonpath = os.path.commonprefix(goodArguments.files) with mpl_utils.PdfWriter(commonpath + '.pdf') as pdfpages: pdfpages.savefig(fig, )
(f[g] for g in groupnames) for f in files)) # determination of storage file, copied from analyzeVesselsBulkTumor prefix, suffix = myutils.splitcommonpresuffix( map(lambda s: basename(s), filenames)) outputbasename, _ = splitext(prefix + suffix) fn_measure = 'common-radial-cache.h5' f_measure = h5files.open(fn_measure, 'a') def cachelocation(g): path = posixpath.join( 'FileCS_' + myutils.checksum(basename(g.file.filename)), g.name.strip(posixpath.sep)) return (f_measure, path) with mpl_utils.PdfWriter('bloodFlow-%s.pdf' % outputbasename) as pdfpages: def bloodflow(group): bv = obtain_averaged_blood_flow(dataman, files, group, cachelocation) print 'of ', group, 'bf = ', bv def printit(id, label, unit): s = r'$%s$ = $%s \pm %s$ [$%s$]' % ( label, myutils.f2s(bv[id][0], latex=True), myutils.f2s(bv[id][1], latex=True), unit) return s s = '\n'.join([ GetTimeLabel(files[0][group]), #printit('flow_in', r'\tilde{BF}_{tumor}', '\mu m^3\,Blood\,/\,min'),
if not ax.get_xlabel(): ax.set(xticklabels=[]) text2(ax, '(%s)' % 'abcdefghij'[i]) pdfpages.savefig(fig) if __name__ == '__main__': filenames = sys.argv[1:] if not myutils.is_measurement_file(filenames[0]): for fn in filenames: with h5py.File(fn, 'r') as f: with myutils.MeasurementFile(f, h5files) as fdst: grps = myutils.getTimeSortedGroups(f['.'], "out") for grp in grps: dstgroup = myutils.require_snapshot_group_(fdst, grp) generate_data(grp, dstgroup) else: rc = matplotlib.rc rc( 'figure', **{ 'subplot.left': 0.15, 'subplot.right': 1. - 0.15, 'subplot.bottom': 0.2, 'subplot.top': 1. - 0.1, 'subplot.wspace': 0.2, 'subplot.hspace': 0.2 }) fnmeasure = commonOutputName(filenames) with mpl_utils.PdfWriter(fnmeasure + '.pdf') as pdfpages: plot_many(filenames, pdfpages)
parser.add_argument('FileNames', nargs='*', type=argparse.FileType('r'), default=sys.stdin, help='Vessel file to calculate') goodArguments, otherArguments = parser.parse_known_args() #create filename due to former standards filenames = [] for fn in goodArguments.FileNames: filenames.append(fn.name) for fn in filenames: f = h5py.File(fn) no_of_iterations = '1' vesselgrp = f['vessels_after_adaption'] common_filename = os.path.splitext(os.path.basename(fn))[0] with mpl_utils.PdfWriter(no_of_iterations + '_' + common_filename + '_stimulies.pdf') as pp: rc = matplotlib.rc rc('font', size=8.) rc('axes', titlesize=10., labelsize=8.) hydrodynamic_fig = plot_hydrodynamic_stimuli(vesselgrp, pp) plot_conductive_stimuli(vesselgrp, pp) plot_hydorodynamic_charicteristics(vesselgrp, pp) #plot_movie(f,pp=None) #plot_movie_typeE(f,pp=None) f.close
default=False, action='store_true') goodArguments, otherArguments = parser.parse_known_args() #create filename due to former standards filenames = [] for fn in goodArguments.FileNames: filenames.append(fn.name) rc = matplotlib.rc rc('font', size=8.) rc('axes', titlesize=10., labelsize=8.) for fn in filenames: with h5py.File(fn) as f: no_of_iterations = '' vesselgrp = f['vessels_after_adaption'] common_filename = os.path.splitext(os.path.basename(fn))[0] with mpl_utils.PdfWriter(no_of_iterations + '_' + common_filename + '_hydrodynamic_stimulies.pdf') as pp: hydrodynamic_fig = plot_hydrodynamic_stimuli(vesselgrp, pp) with mpl_utils.PdfWriter(no_of_iterations + '_' + common_filename + '_conductive_stimulies.pdf') as pp: plot_conductive_stimuli(vesselgrp, pp) with mpl_utils.PdfWriter(no_of_iterations + '_' + common_filename + '_hydrodynamics.pdf') as pp: plot_hydorodynamic_charicteristics(vesselgrp, pp) #plot_movie(f,pp=None) #plot_movie_typeE(f,pp=None)
def doit(filenames, pattern): dataman = myutils.DataManager(20, [ DataTumorTissueSingle(), DataDistanceFromCenter(), DataBasicVessel(), DataVesselSamples(), DataVesselRadial(), DataVesselGlobal(), DataTumorBloodFlow() ]) ensemble = EnsembleFiles(dataman, filenames, pattern) if ensemble.has_tumor: print 'paths: ', map(lambda (_t0, path, _t1): path, ensemble.tumor_snapshots) else: print 'paths: ', set(map(lambda e: e.path, ensemble.items)) prefix, suffix = myutils.splitcommonpresuffix( map(lambda s: basename(s), filenames)) outputbasename, _ = splitext(prefix + suffix) fn_measure = outputbasename + '-radial-cache.h5' f_measure = h5files.open(fn_measure, 'a') def cachelocation(g): path = posixpath.join( 'FileCS_' + myutils.checksum(basename(g.file.filename)), g.name.strip(posixpath.sep)) return (f_measure, path) #name = ensemble.items[0].path.split('/')[-1] measurementinfo = dict(sample_length=30., cachelocation_callback=cachelocation, distancemap_spec='radial') print 'getting radial curves' stuff = [] stuff2 = [] for items, path, time in ensemble.tumor_snapshots: bins_spec, curves = CollectAllRadialData(dataman, items, measurementinfo) tumorradius = GetAverageApproximateTumorRadius(dataman, ensemble, items) stuff.append((time, tumorradius, curves)) stuff2.append((time, tumorradius, curves, path)) #output_filename+= '_'+name with mpl_utils.PdfWriter(outputbasename + '-radial.pdf') as pdfwriter: PlotRadialCurves(pdfwriter, bins_spec, stuff, measurementinfo, ensemble.world_size) with h5py.File(outputbasename + '-radial.h5', 'w') as f: f.attrs['COMMONPREFIX'] = os.path.commonprefix( map(lambda s: basename(s), filenames)) f.create_dataset('files', data=filenames) f.create_dataset('groups', data=np.asarray(set( map(lambda item: item.path, ensemble.items)), dtype=np.str)) for i, (time, tumorradius, curves, path) in enumerate(stuff2): g = f.create_group(path.strip('/').replace('/', '-')) g.attrs['TUMORRADIUS'] = tumorradius g.attrs['TIME'] = time for name, curve in curves.iteritems(): curve = myutils.MeanValueArray.fromSummation( map(lambda x: x.avg, curve)) g.create_dataset(name + '/avg', data=np.asarray(curve.avg)) g.create_dataset(name + '/std', data=np.asarray(curve.std)) g.create_dataset(name + '/mask', data=~curve.avg.mask) g.create_dataset(name + '/std_mean', data=np.asarray(curve.std_mean)) g.create_dataset('bins', data=bins_spec.arange())
arglist = [] for ii in np.ndindex(shape): arglist.append(tuple(args[j][i] for j, i in enumerate(ii))) q = krebsutils.calcBulkTissueSourceTerm(arglist, param_string) for i, ii in enumerate(np.ndindex(shape)): q[i] /= args[1][ii[1]] return q if __name__ == '__main__': #print args #d = generate_data(*args, params=dict()) #print d with mpl_utils.PdfWriter('bulktissuesources_new.pdf') as pdfpages: params = dict(source_model_version=3, o2_necro_threshold=0.1, o2_prol_threshold=0.4, time_necrosis=48, time_death_tumor=240000., use_necrotic_regions=False) if 1: o2values = [0., 0.11, 0.041, 1.] fig = pyplot.figure() plot = fig.add_subplot( 111, xlabel='$\phi$',
def runStepperConvergenceTests(): out_fn = "stepper_test" steppersConvergenceTest(out_fn + '.h5') pdf = mpl_utils.PdfWriter(out_fn + ".pdf") f = h5py.File(out_fn + '.h5', 'r') # model_lambda = f.attrs['lambda'] bytime = collections.defaultdict(list) bymethod = collections.defaultdict(list) for g in f['/'].itervalues(): if g.name == '/exact': exact = g else: bytime[g.attrs['dt']].append(g) bymethod[g.attrs['method']].append(g) for dt, groups in sorted(bytime.iteritems(), key=lambda (k, v): k): if dt < exact['x'][-1] * 0.01: continue fig = pyplot.figure(figsize=(11.7, 8.3)) fig.suptitle('dt = %f' % dt) plot = fig.add_subplot(1, 1, 1) plot.set_yscale("log") plot.set_xlabel('x') plot.set_ylabel('y') for marker, g in zip(markers, groups): plot.plot(np.asarray(g['x']), np.asarray(g['y']), label=g.attrs['method'], marker=marker) plot.plot(np.asarray(exact['x']), np.asarray(exact['y']), label='exact', linewidth=2) plot.legend(loc='upper left') pdf.savefig(fig) err = collections.defaultdict(collections.defaultdict) for g in f['/'].itervalues(): if g.name == '/exact': continue val = abs(g['y'][-1] - exact['y'][-1]) m, t = g.attrs['method'], g.attrs['dt'] err[m][t] = val print m, t, val for k, d in err.iteritems(): err[k] = np.asarray(sorted(d.iteritems(), key=lambda (k, v): k)).transpose() fig = pyplot.figure(figsize=(11.7, 8.3)) plot = fig.add_subplot(1, 1, 1) plot.set_yscale("log") plot.set_xscale("log") plot.set_xlabel('dt') plot.set_ylabel('e') for marker, (method, (t, y)) in zip(markers, err.iteritems()): plot.plot(t, y, label=method, marker=marker) plot.legend(loc='lower right') pdf.savefig(fig) pdf.close()
if __name__ == '__main__': filenames = sys.argv[1:] files = [h5files.open(fn, 'r') for fn in filenames] fmeasure = h5files.open('analyzeBloodVolumeMeasurements.h5', 'a') dataman = myutils.DataManager(10, [ DataTumorTissueSingle(), DataVesselRadial(), DataVesselSamples(), DataBasicVessel(), DataDistanceFromCenter() ]) #allgroups = sorted(filter(lambda k: k.startswith('out'), files[0].keys())) allgroups = defaultdict(list) for f in files: keys = filter(lambda k: k.startswith('out'), f.keys()) for k in keys: allgroups[k].append(f[k]) allgroups = [(k, allgroups[k]) for k in sorted(allgroups.keys())] groupslist = [allgroups[-1], allgroups[len(allgroups) / 2]] outfn = 'bloodVolume-%s.pdf' % splitext(basename(filenames[0]))[0] pprint(groupslist) print '-> %s' % (outfn) with mpl_utils.PdfWriter(outfn) as pdfpages: if 0: plot_mvd_in_large_bins1(pdfpages, groupslist) else: plot_mvd_in_large_bins2(pdfpages, groupslist)
def analyzeO2_with_tumor(f): dataman = myutils.DataManager(100, [plotBulkTissue2d.DataTumorTissueSingle()]) resultfile = plotBulkTissue2d.ResultFile(f, dataman) group = resultfile.groupnames[-1] ld = resultfile.obtain_data('ld') print group arterial_reference = 12. theta_tumor = resultfile.obtain_data('fieldvariable', 'theta_tumor', group) o2 = arterial_reference * resultfile.obtain_data('fieldvariable', 'oxy', group) dist_tumor = resultfile.obtain_data('fieldvariable', 'dist_tumor', group) def tumorAndTissueAverages(field): tumor = field[theta_tumor > 0.5] normal = field[theta_tumor < 0.5] tissueavg = (np.average(normal), np.std(normal)) tumoravg = (np.average(tumor), np.std(tumor)) return tissueavg, tumoravg cons_rate_normal = float(f['parameters'].attrs['o2_cons_coeff_normal']) cons_rate_tumor = float(f['parameters'].attrs['o2_cons_coeff_tumor']) consumption = (theta_tumor * cons_rate_tumor + (1. - theta_tumor) * cons_rate_normal) * o2 solubility = 0.00021 # ml O2 / ml Tissue / kPa consfactors = 2000. * 60 * solubility * 1.e2 # 2000. from diff koff, 60 from s to min conversion. consumption *= consfactors avgStr = lambda t: r'$%s \pm %s$' % tuple(f2l(q) for q in t) outfn = 'oxycheck-' + splitext(basename(str(f.filename)))[0] + '.pdf' with mpl_utils.PdfWriter(outfn) as pdfwriter: fig = pyplot.figure(figsize=(5, 5)) ax = fig.add_axes([0.05, 0.05, 4.2 / 5, 4.2 / 5]) img = plotBulkTissue.imshow(ax, plotBulkTissue.imslice(o2), ld, vmin=0., vmax=9., cmap=matplotlib.cm.Reds, worldscaling=1.e-3) plotBulkTissue.colorbar(ax.get_figure(), ax, img) plotBulkTissue.contour(ax, plotBulkTissue.imslice(dist_tumor), ld, levels=[0.], colors=['k'], worldscaling=1.e-3) tissueavg, tumoravg = tumorAndTissueAverages(o2) print 'normal po2: %f +/- %f' % tissueavg print 'tumor po2: %f +/- %f' % tumoravg fig.suptitle(r'O2 [kPa] (arterial $P_{O_2} = 12 kPa$)') fig.text( 0.1, 0.90, '<tissue> ' + avgStr(tissueavg) + '\n' + '<tumor> ' + avgStr(tumoravg)) pdfwriter.savefig(fig) fig = pyplot.figure(figsize=(5, 5)) ax = fig.add_axes([0.05, 0.05, 4.2 / 5, 4.2 / 5]) img = plotBulkTissue.imshow(ax, plotBulkTissue.imslice(consumption), ld, vmin=consumption.min(), vmax=consumption.max(), cmap=matplotlib.cm.Reds, worldscaling=1.e-3) plotBulkTissue.colorbar(ax.get_figure(), ax, img) plotBulkTissue.contour(ax, plotBulkTissue.imslice(dist_tumor), ld, levels=[0.], colors=['k'], worldscaling=1.e-3) tissueavg, tumoravg = tumorAndTissueAverages(consumption) print 'mro2 normal o2: %f +/- %f' % tissueavg print 'mro2 tumor o2: %f +/- %f' % tumoravg fig.suptitle(r'$MRO_2$ [ml $O_2$ / 100 ml Tissue min]') fig.text( 0.1, 0.90, '<tissue> ' + avgStr(tissueavg) + '\n' + '<tumor> ' + avgStr(tumoravg)) pdfwriter.savefig(fig)