Ejemplo n.º 1
0
def plotAnalyzeIterativeConvergence(dataman, pdfwriter, plotties):
  def plotIter(ax, group, **kwargs):
    iterations = plotsForPaper.GetConvergenceData(group)
    x = iterations['iteration']
    y = iterations['delta_vessM'] + iterations['delta_fieldM']
    ax.plot(x, y, **kwargs)
    
  fig, ax = pyplot.subplots(1,1, figsize = (mpl_utils.a4size[0]*0.4, mpl_utils.a4size[0]*0.4))
  mpl_utils.subplots_adjust_abs(fig, unit = 'mm', left = 15., right=-5., bottom = 10., top = -5.)
  
  ax.set(xlabel = 'iteration', ylabel = r'$|p(new) - p(old)|_\infty$', yscale = 'log')
  for i, plt in enumerate(plotties):
    plotIter(ax, plt.po2group, label = plt.label, **niceMarker(i, 'k'))
  ax.set(yscale = 'log', title = 'Convergence')
  ax.legend(loc = mpl_utils.loc.lower_left)
  axins = mpl_utils.inset_axes(ax,
                     width="30%", # width = 30% of parent_bbox
                     height="30%", # height : 1 inch
                     loc=mpl_utils.loc.upper_right)
  for i, plt in enumerate(plotties):
    marker = niceMarker(i, 'k')
    axins.plot([i], [plt.fluxes['e3']], **marker)
  axins.set(yscale = 'log', title = r'Error $e3$ [%]') #, ylim = (1.e-6, 100.0))
  #axins.xaxis.set(visible = False)    
  pdfwriter.savefig(fig, postfix='_iterations')
Ejemplo n.º 2
0
def plot_many(filenames, pdfpages):
    groups_by_time = defaultdict(list)
    files = [h5py.File(fn, 'r') for fn in filenames]
    for f in files:
        groups = myutils.getTimeSortedGroups(f['.'])
        for g in groups:
            groups_by_time[round(g.attrs['time'])].append(g)

    times = groups_by_time.keys()
    times.sort()
    times = np.asarray(times)

    radius, radius_std = averaged_global((groups_by_time, times),
                                         'geometry/radius')
    volume, volume_std = averaged_global((groups_by_time, times),
                                         'geometry/volume')
    sphere_equiv_radius, sphere_equiv_radius_std = averaged_global(
        (groups_by_time, times), 'geometry/sphere_equiv_radius')
    #sphere_equiv_radius, sphere_equiv_radius_std = averaged_global((groups_by_time, times), 'geometry/cylinder_equiv_radius')
    sphericity, sphericity_std = averaged_global((groups_by_time, times),
                                                 'geometry/sphericity')

    # estimate velocity
    data = np.asarray((times, radius))
    if len(data[0]) > 1:
        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]))
        velocity = p[0]
        print 'estimated velocity: %f' % velocity
        print 'fit params: %s' % str(p)
    else:
        velocity = 0.

    if 1:
        #plot by time
        fig, axes = pyplot.subplots(2,
                                    2,
                                    figsize=(mastersize[0] * 0.5,
                                             mastersize[0] * 0.5))
        mpl_utils.subplots_adjust_abs(
            fig,
            left=mpl_utils.mm_to_inch * 13,
            right=-mpl_utils.mm_to_inch * 5,
            top=-mpl_utils.mm_to_inch * 5,
            bottom=mpl_utils.mm_to_inch * 10,
            hspace=mpl_utils.mm_to_inch * 30,
            wspace=mpl_utils.mm_to_inch * 40,
        )
        axes = axes.ravel()

        def plt_rad(ax):
            ax.set(ylabel='[mm]', xlabel='t [h]')
            mpl_utils.errorbar(ax,
                               times,
                               1.e-3 * radius,
                               yerr=1.e-3 * radius_std,
                               label='r',
                               lw=0.,
                               marker='x',
                               color='k',
                               markersize=5.)
            label = u'$r_0 + v_{fit} t$\n$v_{fit} = %s$ [\u03BCm/h]' % f2s(
                velocity)
            ax.plot(times,
                    1.e-3 * (p[1] + p[0] * times),
                    label=label,
                    color='r')
            ax.legend()
            #ax.text(0.6, 0.2, r'$v_{fit} = %s$' % f2s(velocity), transform = ax.transAxes)

        def plt_vol(ax):
            ax.set(ylabel='volume', xlabel='t [h]')
            ax.errorbar(times, 1.e-9 * volume, yerr=1.e-9 * volume_std)

        def plt_sprad(ax):
            ax.set(ylabel='sphere equiv. radius', xlabel='t [h]')
            ax.errorbar(times,
                        1.e-3 * sphere_equiv_radius,
                        yerr=1.e-3 * sphere_equiv_radius_std)

        def plt_sphereicity(ax):
            ax.set(ylabel='sphericity', xlabel='t [h]')
            ax.errorbar(times, sphericity, yerr=sphericity_std)

        for ax, func in zip(axes,
                            [plt_rad, plt_vol, plt_sprad, plt_sphereicity]):
            l = MaxNLocator(nbins=4)
            ax.xaxis.set_major_locator(l)
            func(ax)

        pdfpages.savefig(fig)

    times = times[0::2]
    radial = averaged_radial((groups_by_time, times), 'vs_dr', [
        'phi_tumor', 'mvd', 'radius', 'shearforce', 'flow', 'sources', 'vel',
        'oxy', 'maturation'
    ])
    bins = np.asarray(groups_by_time[times[0]][0]['radial/vs_dr/bins'])
    bins *= 1. / 1000.
    xlim = -1.5, 1.0
    mask = np.logical_and(bins < xlim[1], bins >= xlim[0])

    def plot_times(ax, name, **kwargs):
        f = kwargs.pop('value_prefactor', 1.)
        colors = 'rgbmk'
        markers = 'os<>d'
        for i, t in enumerate(times):
            avg, std = radial[name, t]
            avg, std = avg[mask], std[mask]
            #ax.errorbar(bins[mask], f*avg, yerr=f*std, label = 't = %s' % f2s(t), **kwargs)
            mpl_utils.errorbar(ax,
                               bins[mask],
                               f * avg,
                               yerr=f * std,
                               label='t = $%s$' % f2s(t),
                               marker=markers[i],
                               color=colors[i],
                               every=5,
                               **kwargs)

    def text1(ax, txt):
        ax.text(0.95, 0.9, txt, ha="right", transform=ax.transAxes)

    def text2(ax, txt):
        ax.text(0.01, 0.9, txt, ha="left", transform=ax.transAxes)

    def mkfig(nrows, ncols):
        fig, axes = mpl_utils.subplots_abs_mm(
            (mastersize[0] / mpl_utils.mm_to_inch * 0.5 * ncols,
             mastersize[0] / mpl_utils.mm_to_inch * 0.2 * nrows), nrows, ncols,
            10, 20, a4size[0] / mpl_utils.mm_to_inch * 0.38,
            a4size[0] / mpl_utils.mm_to_inch * 0.16, 15, 5)
        return fig, axes


#  fig, axes = pyplot.subplots(4, 2, figsize = (mastersize[0], mastersize[0]*0.25*4.))
#  mpl_utils.subplots_adjust_abs(fig, left = mpl_utils.mm_to_inch*20,
#                                right = -mpl_utils.mm_to_inch*10,
#                                top  = -mpl_utils.mm_to_inch*5,
#                                bottom = mpl_utils.mm_to_inch*10,
#                                hspace = mpl_utils.mm_to_inch*30,)

    def plt_mvd(ax):
        # mvd can be written as N^3 * L0/N * 3 / V = (V=L0^3) ... = N^2 / L0^2
        ax.set(ylabel=ur'$\times 10^3$ [\u03BCm$^{-2}$]', xlim=xlim)
        plot_times(ax, 'mvd', value_prefactor=1e3)
        text1(ax, r'$L/V$')
        ax.legend(loc=mpl_utils.loc.lower_left, frameon=True)

    def plt_rad(ax):
        ax.set(ylabel=ur'[\u03BCm]', xlim=xlim)
        plot_times(ax, 'radius')
        text1(ax, r'$r_v$')

    def plt_vel(ax):
        ax.set(ylabel=ur'[\u03BCm/h]', xlim=xlim)
        text1(ax, r'$v_\phi$')
        plot_times(ax, 'vel')

    def plt_tum(ax):
        ax.set(ylabel=ur'', xlim=xlim, ylim=(-0.1, 0.7))
        plot_times(ax, 'phi_tumor')
        text1(ax, r'$\phi_t$')

    def plt_oxy(ax):
        ax.set(ylabel=ur'', xlim=xlim)
        plot_times(ax, 'oxy')
        text1(ax, r'$c_o$')

    def plt_sf(ax):
        ax.set(ylabel=ur'[Pa]', xlim=xlim)
        plot_times(ax, 'shearforce', value_prefactor=1e3)
        text1(ax, r'$f_v$')

    def plt_wall(ax):
        ax.set(ylabel=ur'[\u03BCm]', xlim=xlim)
        plot_times(ax, 'maturation')
        text1(ax, r'$w_v$')

    def plt_qv(ax):
        ax.set(ylabel=ur'[\u03BCm]', xlim=xlim)
        ax.set(xlabel=ur'$\theta$ [mm]')
        plot_times(ax, 'flow')
        text1(ax, r'$q_v$')

    fig, axes = mkfig(3, 2)
    plt_mvd(axes[0, 0])
    plt_rad(axes[0, 1])
    plt_vel(axes[1, 0])
    plt_oxy(axes[1, 1])
    plt_wall(axes[2, 0])
    plt_sf(axes[2, 1])

    for ax in axes[2, :]:
        ax.set(xlabel=ur'$\theta$ [mm]')

    axes = axes.ravel()
    for i, ax in enumerate(axes):
        ax.grid(linestyle=':', linewidth=0.5, color=gridcolor)
        mpl_utils.add_crosshair(ax, (0, 0), color=gridcolor)
        if not ax.get_xlabel():
            ax.set(xticklabels=[])
        text2(ax, '(%s)' % 'abcdefghij'[i])

    pdfpages.savefig(fig)
Ejemplo n.º 3
0
def PlotRadialCurves(pdfwriter, bins_spec, snapshotlist, measurementinfo,
                     world_size):
    charsize = 12 / 90.
    figscale = mpl_utils.a4size[0] * 0.33
    fig, axes = pyplot.subplots(2,
                                2,
                                dpi=90,
                                figsize=(figscale * 2, figscale * 1.5))
    mpl_utils.subplots_adjust_abs(fig,
                                  left=4 * charsize,
                                  right=-2 * charsize,
                                  top=-3. * charsize,
                                  bottom=5. * charsize,
                                  hspace=8. * charsize,
                                  wspace=12 * charsize)
    axes = axes.ravel()

    bins = bins_spec.arange() * 1.e-3

    FmtTime = lambda time: 't=' + f2l(round(time))

    default_colors = 'rgbcmyk'

    def plot(ax,
             name,
             scalefactor=1.,
             label=None,
             colors=default_colors,
             errorbars=True,
             zero_ylim=True):
        for color, i, (time, tumor_radius,
                       curves) in itertools.izip(itertools.cycle(colors),
                                                 itertools.count(),
                                                 snapshotlist):
            curve = myutils.MeanValueArray.fromSummation(
                map(lambda x: x.avg, curves[name]))
            label = FmtTime(time)
            mask = ~curve.avg.mask
            if errorbars:
                mpl_utils.errorbar(ax,
                                   bins[mask],
                                   scalefactor * curve.avg[mask],
                                   yerr=scalefactor * curve.std_mean[mask],
                                   label=label,
                                   marker=None,
                                   color=color,
                                   every=2)
            else:
                ax.plot(bins[mask],
                        scalefactor * curve.avg[mask],
                        label=label,
                        color=colors[i])
        if zero_ylim:
            _, ymax = ax.get_ylim()
            ax.set_ylim((0., ymax))
        if measurementinfo['distancemap_spec'] == 'levelset':
            ax.set(xlim=(-2., 2.))
            mpl_utils.add_crosshair(ax, (0., None), ls=':')
        else:
            mpl_utils.add_crosshair(ax, (0.5e-3 * world_size[0], None))
            ax.set(xlim=(0, 0.5e-3 * world_size[0]))
            for color, i, (time, tumor_radius,
                           curves) in itertools.izip(itertools.cycle(colors),
                                                     itertools.count(),
                                                     snapshotlist):
                mpl_utils.add_crosshair(ax, (tumor_radius * 1.e-3, None),
                                        ls=':',
                                        color=color)

    def fmt_axis_labels(ax, name, scalefactor=None, hidex=True):
        ax.set(
            ylabel=(r'$%s$ %s' %
                    (Prettyfier.get_sym(name), Prettyfier.get_bunit(name))) +
            ((r' $\times\, %s$' %
              f2l(scalefactor, exponential=True)) if scalefactor else ''),
            title=Prettyfier.get_label(name))
        if hidex: ax.set(xticklabels=[])
        else:
            xsym = r'\phi' if measurementinfo[
                'distancemap_spec'] == 'levelset' else r'|x|'
            ax.set(xlabel=r'$%s$ [$mm$]' % xsym)


#  if measurementinfo.distancemap_spec == 'radial':
#    axtwin = axes[0].twinx()
#    plot(axtwin, 'theta_tumor', colors = [(0.5,0.5,0.5)]*7, errorbars=False)

    plot(axes[0], 'mvd', label=True)
    fmt_axis_labels(axes[0], 'mvd')
    theLegend = axes[0].legend(loc='lower right', prop={'size': 6})
    #theLegend.get_title().set_fontsize('2')
    #pyplot.setp(axes[0].get_legend().get_texts(),fontsize='2')
    theLegend.__sizes = [1]

    plot(axes[1], 'phi_vessels')
    fmt_axis_labels(axes[1], 'phi_vessels')

    plot(axes[2], 'radius')
    fmt_axis_labels(axes[2], 'radius', hidex=False)

    plot(axes[3], 'velocity', scalefactor=1.0e-3)
    fmt_axis_labels(axes[3], 'velocity_mm', hidex=False)

    pdfwriter.savefig(fig, postfix='_o2radial')
Ejemplo n.º 4
0
                                         bins[mask],
                                         f * avg,
                                         yerr=f * std,
                                         **kwargs)
                return ret

            name = 'iff_pressure'
            avg, std = radial[name]
            avg, std = avg[mask], std[mask]

            fig, axes = pyplot.subplots(3, 1)
            axes = axes.ravel()
            mpl_utils.subplots_adjust_abs(
                fig,
                left=mpl_utils.mm_to_inch * 20,
                right=-mpl_utils.mm_to_inch * 10,
                top=-mpl_utils.mm_to_inch * 5,
                bottom=mpl_utils.mm_to_inch * 10,
                hspace=mpl_utils.mm_to_inch * 30,
            )

            ax = axes[0]
            ax.set(xticklabels=[])
            ax.set(ylabel=r'[kPa]')
            plot('iff_pressure', label=r'$p_i$', marker='o', color='r')
            #plot('ivp', label = '$p_v$', marker = 's', color = 'k')
            #plot('ivp_minus_ifp', label = '$p_v - p_i$', marker='>', color = 'b')
            #end pressure
            ax = axes[1]
            ax.set(ylabel=ur'[\u03BCm/s]'
                   )  #, xlabel = r'$\theta$ [mm]', title = 'velocity')
            ax.set(xticklabels=[])
Ejemplo n.º 5
0
def PlotRadial(pdfwriter, dataman, resultfiles, distance_distribution_name):
    binspec = BinsSpecRange(-10000., 10000., 100.)
    curves_by_path_and_name = myutils.MultiDict(list)
    for f in files:
        fm = myutils.MeasurementFile(f.f, h5files)
        for outgroup_name in f.groupnames:
            gvessels = f.f[outgroup_name]['vessels']
            gtumor = f.f[outgroup_name]['tumor']
            for name in [
                    'mvd', 'phi_vessels', 'shearforce', 'velocity', 'radius',
                    'maturation', 'flow'
            ]:
                d = dataman.obtain_data('basic_vessel_radial', name, gvessels,
                                        gtumor, 30., binspec,
                                        distance_distribution_name, None,
                                        (fm, outgroup_name))
                curves_by_path_and_name[outgroup_name, name].append(d)
            #tumor_radius = f.f[outgroup_name]['tumor'].attrs['TUMOR_RADIUS'] # this needs work ...
            tumor_radius = dataman.obtain_data('approximate_tumor_radius',
                                               gtumor)
            curves_by_path_and_name[outgroup_name,
                                    'approximate_tumor_radius'].append(
                                        myutils.MeanValueArray(
                                            1, tumor_radius, tumor_radius**2))
    for k, v in curves_by_path_and_name.items():
        curves_by_path_and_name[k] = myutils.MeanValueArray.fromSummation(
            v_.avg for v_ in v)
    # ---- here goes the plotting -----#
    charsize = 12 / 90.
    figscale = 1.8
    fig, axes = pyplot.subplots(3,
                                2,
                                dpi=90,
                                figsize=(7. * figscale, 5. * figscale))
    mpl_utils.subplots_adjust_abs(fig,
                                  left=6 * charsize,
                                  right=-2 * charsize,
                                  top=-3. * charsize,
                                  bottom=8. * charsize,
                                  hspace=8. * charsize,
                                  wspace=12 * charsize)
    axes = axes.ravel()

    default_colors = 'rgbcmykrgbcmykrgbcmyk'
    pathorder = resultfiles[0].groupnames
    labels_by_path = dict((g, 't=%s' % f2s(resultfiles[0].get_group_time(g)))
                          for g in resultfiles[0].groupnames)
    bins = binspec.arange()
    bins = 1.e-3 * np.average((bins[1:], bins[:-1]), axis=0)
    ld = dataman.obtain_data('ld', resultfiles[0].f)
    rmax = ld.GetWorldSize()[0] * 0.25 * 1.e-3

    def plot(ax,
             name,
             scalefactor=1.,
             label=None,
             colors=default_colors,
             errorbars=True,
             zero_ylim=True):
        for i, path in enumerate(pathorder):
            curve = curves_by_path_and_name[path, name]
            label = labels_by_path[path] if label else None
            mask = ~curve.avg.mask
            if errorbars:
                mpl_utils.errorbar(ax,
                                   bins[mask],
                                   scalefactor * curve.avg[mask],
                                   yerr=scalefactor * curve.std_mean[mask],
                                   label=label,
                                   marker=None,
                                   color=colors[i],
                                   every=2)
            else:
                ax.plot(bins[mask],
                        scalefactor * curve.avg[mask],
                        label=label,
                        color=colors[i])
        if zero_ylim:
            _, ymax = ax.get_ylim()
            ax.set_ylim((0., ymax))
        if distance_distribution_name == 'levelset':
            ax.set(xlim=(-2., 2.))
            mpl_utils.add_crosshair(ax, (0., None), ls=':')
        else:
            ax.set(xlim=(0., rmax))
            for i, path in enumerate(pathorder):
                mpl_utils.add_crosshair(
                    ax,
                    (curves_by_path_and_name[path,
                                             'approximate_tumor_radius'].avg *
                     1.e-3, None),
                    ls=':')

    def fmt_axis_labels(ax, name, scalefactor=None, hidex=True):
        ax.set(
            ylabel=(r'$%s$ %s' %
                    (Prettyfier.get_sym(name), Prettyfier.get_bunit(name))) +
            ((r' $\times\, %s$' %
              f2l(scalefactor, exponential=True)) if scalefactor else ''),
            title=Prettyfier.get_label(name))
        if hidex: ax.set(xticklabels=[])
        else:
            xsym = r'\phi' if distance_distribution_name == 'levelset' else r'|x|'
            ax.set(xlabel=r'$%s$ [$mm$]' % xsym)

    plot(axes[0], 'mvd', label=True, scalefactor=1.e6)
    fmt_axis_labels(axes[0], 'mvd')
    axes[0].legend()

    plot(axes[1], 'phi_vessels', scalefactor=1.)
    fmt_axis_labels(axes[1], 'phi_vessels', scalefactor=1)

    plot(axes[2], 'shearforce')
    fmt_axis_labels(
        axes[2],
        'shearforce',
    )

    plot(axes[3], 'velocity')
    fmt_axis_labels(
        axes[3],
        'velocity',
    )

    plot(axes[4], 'radius')
    fmt_axis_labels(axes[4], 'radius', hidex=False)

    plot(axes[5], 'flow', scalefactor=1)
    fmt_axis_labels(axes[5], 'flow', scalefactor=1, hidex=False)

    #plot(axes[5], 'maturation', scalefactor = 1)
    #fmt_axis_labels(axes[5], 'maturation', scalefactor = 1, hidex=False)

    pdfwriter.savefig(fig, postfix='_radial')