コード例 #1
0
def read_lab_data(d_param=None):
    #import pdb; pdb.set_trace()
    if d_param == None:
        probdata = Data(os.path.join(datadir, 'setprob.data'))
        d_param = probdata.d

    print '+++ d_param = ', d_param
    if d_param == 0.061: fname = 'd61g1234-new.txt'
    if d_param == 0.080: fname = 'd80g1234-new.txt'
    if d_param == 0.100: fname = 'd100g124-new.txt'
    if d_param == 0.120: fname = 'd120g124-new.txt'
    if d_param == 0.140: fname = 'd140g1234-new.txt'
    if d_param == 0.149: fname = 'd149g124-new.txt'
    if d_param == 0.189: fname = 'd189g1234-new.txt'

    try:
        print "Reading gauge data from ", fname
    except:
        print "*** No gauge data for d_param = ", d_param

    try:
        fname = os.path.join(datadir, fname)
        gaugedata = loadtxt(fname)
    except:
        raise Exception("*** Cannot read file %s ", fname)
    gauget = gaugedata[:, 0]
    gauge_ave = {}
    for gaugeno in [1, 2, 3, 4]:
        try:
            gauge_ave[gaugeno] = gaugedata[:, 3 * gaugeno] * 0.001
        except:
            # If fails for gaugeno==4 then it is gauge 3 that's missing:
            gauge_ave[3] = None
            #import pdb; pdb.set_trace()
            try:
                gauge_ave[4] = gaugedata[:, 9] * 0.001
            except:
                gauge_ave[2] = gaugedata[:, 4] * 0.001
                gauge_ave[4] = gaugedata[:, 5] * 0.001

    return d_param, gauget, gauge_ave
コード例 #2
0
ファイル: gaugetools.py プロジェクト: mparsani/visclaw
def read_setgauges(datadir):
    """
    Read the info from setgauges.data.
    """
    import os
    import numpy as np
    from pyclaw.data import Data
    from matplotlib.mlab import find

    setgauges = Data()

    # default values if no gauges found:
    setgauges.numgauges = 0
    setgauges.gaugenos = []
    setgauges.x = {}
    setgauges.y = {}
    setgauges.t1 = {}
    setgauges.t2 = {}

    fname = os.path.join(datadir, 'setgauges.data')
    if not os.path.isfile(fname):
        #print "*** Warning in read_setgauges: missing file ",fname
        return setgauges

    sgfile = open(fname, 'r')
    lines = sgfile.readlines()
    sgfile.close()

    lineno = 0
    ignore_line = True
    while ignore_line:
        line = lines[lineno] + "#"
        #print "+++ lineno = %s, line = %s" % (lineno,line)
        if line.split()[0][0] == "#":
            lineno = lineno + 1
        else:
            ignore_line = False

    try:
        numgauges = int(line.split()[0])
    except:
        print "*** error setting numgauges"
        return

    if numgauges == 0:
        return setgauges

    #print '+++ ignoring %s lines, numgauges = %s' %(lineno, numgauges)
    try:
        sgno, x, y, t1, t2 = np.loadtxt(fname, unpack=True, skiprows=lineno+1, \
                                usecols=range(5))
        if numgauges == 1:
            # loadtxt returns numbers rather than arrays in this case:
            sgno = [sgno]
            x = [x]
            y = [y]
            t1 = [t1]
            t2 = [t2]

    except:
        print "*** problem reading gauges from setgauges.data"
        return setgauges

    sgno = np.array(sgno, dtype=int)  # convert to int
    setgauges.gaugenos = sgno
    setgauges.numgauges = numgauges

    for n in sgno:
        nn = find(sgno == n)
        if len(nn) > 1:
            print "*** Warning: found more than one gauge numbered ", n

        if len(nn) == 0:
            print "*** Error: didn't find gauge number %s in %s" % (n, fname)
        else:
            nn = nn[0]
            setgauges.x[n] = x[nn]
            setgauges.y[n] = y[nn]
            setgauges.t1[n] = t1[nn]
            setgauges.t2[n] = t2[nn]

    return setgauges
コード例 #3
0
ファイル: gaugetools.py プロジェクト: mparsani/visclaw
def plotgauge(gaugeno, plotdata, verbose=False):
    #==========================================
    """
    Plot all requested plots for a single gauge from the computation.
    The plots are requested by setting attributes of plotdata
    to ClawPlotFigure objects with plot_type="each_gauge".

    """

    if verbose:
        gaugesoln = plotdata.getgauge(gaugeno)
        print '    Plotting gauge %s  at x = %g, y = %g ... '  \
                 % (gaugeno, gaugesoln.x, gaugesoln.y)

    if plotdata.mode() == 'iplotclaw':
        pylab.ion()

    try:
        plotfigure_dict = plotdata.plotfigure_dict
    except:
        print '*** Error in plotgauge: plotdata missing plotfigure_dict'
        print '*** This should not happen'
        return None

    if len(plotfigure_dict) == 0:
        print '*** Warning in plotgauge: plotdata has empty plotfigure_dict'
        print '*** Apparently no figures to plot'

    # initialize current_data containing data that will be passed
    # to beforegauge, aftergauge, afteraxes commands
    current_data = Data()
    current_data.user = Data()  # for user specified attributes
    # to avoid potential conflicts
    current_data.plotdata = plotdata
    current_data.gaugeno = gaugeno

    # call beforegauge if present, which might define additional
    # attributes in current_data or otherwise set up plotting for this
    # gauge.

    beforegauge = getattr(plotdata, 'beforegauge', None)
    if beforegauge:
        if isinstance(beforegauge, str):
            # a string to be executed
            exec(beforegauge)
        else:
            # assume it's a function
            try:
                output = beforegauge(current_data)
                if output: current_data = output
            except:
                print '*** Error in beforegauge ***'
                raise

    # iterate over each single plot that makes up this gauge:
    # -------------------------------------------------------

    if plotdata._mode == 'iplotclaw':
        gaugesoln = plotdata.getgauge(gaugeno)
        #import pdb; pdb.set_trace()
        print '    Plotting Gauge %s  at x = %g, y = %g ... '  \
                 % (gaugeno, gaugesoln.x, gaugesoln.y)
        requested_fignos = plotdata.iplotclaw_fignos
    else:
        requested_fignos = plotdata.print_fignos
    plotted_fignos = []

    plotdata = set_show(plotdata)  # set _show attributes for which figures
    # and axes should be shown.

    # loop over figures to appear for this gauge:
    # -------------------------------------------

    for figname in plotdata._fignames:
        plotfigure = plotdata.plotfigure_dict[figname]
        if (not plotfigure._show) or (plotfigure.type != 'each_gauge'):
            continue  # skip to next figure

        figno = plotfigure.figno
        if requested_fignos != 'all':
            if figno not in requested_fignos:
                continue  # skip to next figure

        plotted_fignos.append(figno)

        if not plotfigure.kwargs.has_key('facecolor'):
            # use Clawpack's default bg color (tan)
            plotfigure.kwargs['facecolor'] = '#ffeebb'

        # create figure and set handle:
        plotfigure._handle = pylab.figure(num=figno, **plotfigure.kwargs)

        pylab.ioff()
        if plotfigure.clf_each_gauge:
            pylab.clf()

        try:
            plotaxes_dict = plotfigure.plotaxes_dict
        except:
            print '*** Error in plotgauge: plotdata missing plotaxes_dict'
            print '*** This should not happen'
            return None

        if (len(plotaxes_dict) == 0) or (len(plotfigure._axesnames) == 0):
            print '*** Warning in plotgauge: plotdata has empty plotaxes_dict'
            print '*** Apparently no axes to plot in figno ', figno

        # loop over axes to appear on this figure:
        # ----------------------------------------

        for axesname in plotfigure._axesnames:
            plotaxes = plotaxes_dict[axesname]
            if not plotaxes._show:
                continue  # skip this axes if no items show

            # create the axes:
            axescmd = getattr(plotaxes, 'axescmd', 'subplot(1,1,1)')
            axescmd = 'plotaxes._handle = pylab.%s' % axescmd
            exec(axescmd)
            pylab.hold(True)

            # loop over items:
            # ----------------

            for itemname in plotaxes._itemnames:

                plotitem = plotaxes.plotitem_dict[itemname]
                try:
                    outdir = plotitem.outdir
                    if outdir is None:
                        outdir = plotdata.outdir
                    gaugesoln = plotdata.getgauge(gaugeno, outdir)
                except:
                    print '*** Cannot find gauge number ', gaugeno
                    print '*** looking in directory ', outdir
                    print '*** cwd = ', os.getcwd()
                    return None

                #import pdb; pdb.set_trace()
                current_data.gaugesoln = gaugesoln
                current_data.q = gaugesoln.q
                current_data.t = gaugesoln.t

                if plotitem._show:
                    try:
                        output = plotgauge1(gaugesoln,plotitem,\
                            current_data)
                        if output: current_data = output
                        if verbose:
                            print '      Plotted  plotitem ', itemname
                    except:
                        print '*** Error in plotgauge: problem calling plotgauge1'
                        traceback.print_exc()
                        return None

            # end of loop over plotitems

        for itemname in plotaxes._itemnames:
            plotitem = plotaxes.plotitem_dict[itemname]
            if plotitem.afteritem:
                print "*** ClawPlotItem.afteritem is deprecated"
                print "*** use ClawPlotAxes.afteraxes "
                print "*** or  ClawPlotItem.aftergrid instead"

        pylab.title("%s at gauge %s" % (plotaxes.title, gaugeno))

        # call an afteraxes function if present:
        afteraxes = getattr(plotaxes, 'afteraxes', None)
        if afteraxes:
            if isinstance(afteraxes, str):
                # a string to be executed
                exec(afteraxes)
            else:
                # assume it's a function
                try:
                    current_data.plotaxes = plotaxes
                    current_data.plotfigure = plotaxes._plotfigure
                    output = afteraxes(current_data)
                    if output: current_data = output
                except:
                    print '*** Error in afteraxes ***'
                    raise

        if plotaxes.scaled:
            pylab.axis('scaled')

        # set axes limits:
        if (plotaxes.xlimits is not None) & (type(plotaxes.xlimits)
                                             is not str):
            try:
                pylab.xlim(plotaxes.xlimits[0], plotaxes.xlimits[1])
            except:
                pass  # let axis be set automatically
        if (plotaxes.ylimits is not None) & (type(plotaxes.ylimits)
                                             is not str):
            try:
                pylab.ylim(plotaxes.ylimits[0], plotaxes.ylimits[1])
            except:
                pass  # let axis be set automatically

            # end of loop over plotaxes

        # end of loop over plotfigures

    # call an aftergauge function if present:
    aftergauge = getattr(plotdata, 'aftergauge', None)
    if aftergauge:
        if isinstance(aftergauge, str):
            # a string to be executed
            exec(aftergauge)
        else:
            # assume it's a function
            try:
                output = aftergauge(current_data)
                if output: current_data = output
            except:
                print '*** Error in aftergauge ***'
                raise

    if plotdata.mode() == 'iplotclaw':
        pylab.ion()
    for figno in plotted_fignos:
        pylab.figure(figno)
        pylab.draw()

    if verbose:
        print '    Done with plotgauge for gauge %i' % (gaugeno)

    # print the figure(s) to file(s) if requested:
    if (plotdata.mode() != 'iplotclaw') & plotdata.printfigs:
        # iterate over all figures that are to be printed:
        for figno in plotted_fignos:
            printfig(gaugeno=gaugeno, figno=figno, \
                    format=plotdata.print_format, plotdir=plotdata.plotdir,\
                    verbose=verbose)

    return current_data
コード例 #4
0
ファイル: dplot.py プロジェクト: dlgeorge/digclaw-4.x
def plot_topo_file(topoplotdata):
    """
    Read in a topo or bathy file and produce a pcolor map.
    """

    import os
    import pylab
    from pyclaw.data import Data

    fname = topoplotdata.fname
    topotype = topoplotdata.topotype
    if topoplotdata.climits:
        # deprecated option
        cmin = topoplotdata.climits[0]
        cmax = topoplotdata.climits[1]
    else:
        cmin = topoplotdata.cmin
        cmax = topoplotdata.cmax
    figno = topoplotdata.figno
    addcolorbar = topoplotdata.addcolorbar
    addcontour = topoplotdata.addcontour
    contour_levels = topoplotdata.contour_levels
    xlimits = topoplotdata.xlimits
    ylimits = topoplotdata.ylimits
    coarsen = topoplotdata.coarsen
    imshow = topoplotdata.imshow
    gridedges_show = topoplotdata.gridedges_show
    neg_cmap = topoplotdata.neg_cmap
    pos_cmap = topoplotdata.pos_cmap
    print_fname = topoplotdata.print_fname


    if neg_cmap is None:
        neg_cmap = colormaps.make_colormap({cmin:[0.3,0.2,0.1],
                                                0:[0.95,0.9,0.7]})
    if pos_cmap is None:
        pos_cmap = colormaps.make_colormap({    0:[.5,.7,0],
                                              cmax:[.2,.5,.2]})

    if abs(topotype) == 1:

        X,Y,topo = topotools.topofile2griddata(fname, topotype)
        topo = pylab.flipud(topo)
        Y = pylab.flipud(Y)
        x = X[0,:]
        y = Y[:,0]
        xllcorner = x[0]
        yllcorner = y[0]
        cellsize = x[1]-x[0]


    elif abs(topotype) == 3:

        file = open(fname, 'r')
        lines = file.readlines()
        ncols = int(lines[0].split()[0])
        nrows = int(lines[1].split()[0])
        xllcorner = float(lines[2].split()[0])
        yllcorner = float(lines[3].split()[0])
        cellsize = float(lines[4].split()[0])
        NODATA_value = int(lines[5].split()[0])

        print "Loading file ",fname
        print "   nrows = %i, ncols = %i" % (nrows,ncols)
        topo = pylab.loadtxt(fname,skiprows=6,dtype=float)
        print "   Done loading"

        if 0:
            topo = []
            for i in range(nrows):
                topo.append(pylab.array(lines[6+i],))
            print '+++ topo = ',topo
            topo = pylab.array(topo)

        topo = pylab.flipud(topo)

        x = pylab.linspace(xllcorner, xllcorner+ncols*cellsize, ncols)
        y = pylab.linspace(yllcorner, yllcorner+nrows*cellsize, nrows)
        print "Shape of x, y, topo: ", x.shape, y.shape, topo.shape

    else:
        raise Exception("*** Only topotypes 1 and 3 supported so far")


    if coarsen > 1:
        topo = topo[slice(0,nrows,coarsen), slice(0,ncols,coarsen)]
        x = x[slice(0,ncols,coarsen)]
        y = y[slice(0,nrows,coarsen)]
        print "Shapes after coarsening: ", x.shape, y.shape, topo.shape


    if topotype < 0:
        topo = -topo

    if figno:
        pylab.figure(figno)

    if topoplotdata.imshow:
            color_norm = Normalize(cmin,cmax,clip=True)
            xylimits = (x[0],x[-1],y[0],y[-1])
            #pylab.imshow(pylab.flipud(topo.T), extent=xylimits, \
            pylab.imshow(pylab.flipud(topo), extent=xylimits, \
                    cmap=cmap, interpolation='nearest', \
                    norm=color_norm)
    else:
        neg_topo = ma.masked_where(topo>0., topo)
        all_masked = (ma.count(neg_topo) == 0)
        if not all_masked:
            pylab.pcolormesh(x,y,neg_topo,cmap=neg_cmap)
            pylab.clim([cmin,0])
            if addcolorbar:
                pylab.colorbar()

        pos_topo = ma.masked_where(topo<0., topo)
        all_masked = (ma.count(pos_topo) == 0)
        if not all_masked:
            pylab.pcolormesh(x,y,pos_topo,cmap=pos_cmap)
            pylab.clim([0,cmax])
            if addcolorbar:
                pylab.colorbar()

    pylab.axis('scaled')


    if addcontour:
        pylab.contour(x,y,topo,levels=contour_levels,colors='k')

    if gridedges_show:
        pylab.plot([x[0],x[-1]],[y[0],y[0]],'k')
        pylab.plot([x[0],x[-1]],[y[-1],y[-1]],'k')
        pylab.plot([x[0],x[0]],[y[0],y[-1]],'k')
        pylab.plot([x[-1],x[-1]],[y[0],y[-1]],'k')

    if print_fname:
        fname2 = os.path.splitext(fname)[0]
        pylab.text(xllcorner+cellsize, yllcorner+cellsize, fname2, color='m')

    topodata = Data()
    topodata.x = x
    topodata.y = y
    topodata.topo = topo

    return topodata
コード例 #5
0
ファイル: geoplot.py プロジェクト: mparsani/visclaw
def plot_topo_file(topoplotdata):
    """
    Read in a topo or bathy file and produce a pcolor map.
    """

    import os
    import pylab
    from pyclaw.data import Data

    fname = topoplotdata.fname
    topotype = getattr(topoplotdata, 'topotype', 3)
    cmap = getattr(topoplotdata, 'cmap', bathy3_colormap)
    climits = getattr(topoplotdata, 'climits', [-50, 50])
    figno = getattr(topoplotdata, 'figno', 200)
    addcolorbar = getattr(topoplotdata, 'addcolorbar', True)
    addcontour = getattr(topoplotdata, 'addcontour', False)
    contour_levels = getattr(topoplotdata, 'contour_levels', [0, 0])
    xlimits = getattr(topoplotdata, 'xlimits', None)
    ylimits = getattr(topoplotdata, 'ylimits', None)
    coarsen = getattr(topoplotdata, 'coarsen', 1)

    if abs(topotype) != 3:
        print "*** Only topotype = 3, -3 implemented so far."
        return

    file = open(fname, 'r')
    lines = file.readlines()
    ncols = int(lines[0].split()[0])
    nrows = int(lines[1].split()[0])
    xllcorner = float(lines[2].split()[0])
    yllcorner = float(lines[3].split()[0])
    cellsize = float(lines[4].split()[0])
    NODATA_value = int(lines[5].split()[0])

    print "Loading file ", fname
    print "   nrows = %i, ncols = %i" % (nrows, ncols)
    topo = pylab.loadtxt(fname, skiprows=6, dtype=float)
    print "   Done loading"

    if 0:
        topo = []
        for i in range(nrows):
            topo.append(pylab.array(lines[6 + i], ))
        print '+++ topo = ', topo
        topo = pylab.array(topo)

    topo = pylab.flipud(topo)
    if topotype < 0:
        topo = -topo

    x = pylab.linspace(xllcorner, xllcorner + ncols * cellsize, ncols)
    y = pylab.linspace(yllcorner, yllcorner + nrows * cellsize, nrows)
    print "Shape of x, y, topo: ", x.shape, y.shape, topo.shape

    if coarsen > 1:
        topo = topo[slice(0, nrows, coarsen), slice(0, ncols, coarsen)]
        x = x[slice(0, ncols, coarsen)]
        y = y[slice(0, nrows, coarsen)]
        print "Shapes after coarsening: ", x.shape, y.shape, topo.shape

    #import pdb; pdb.set_trace()

    if figno:
        pylab.figure(figno)

    pylab.pcolor(x, y, topo, cmap=cmap)
    pylab.clim(climits)
    pylab.axis('scaled')

    if addcolorbar:
        pylab.colorbar()

    if addcontour:
        pylab.contour(x, y, topo, levels=contour_levels, colors='k')

    gridedges_show = True
    if gridedges_show:
        pylab.plot([x[0], x[-1]], [y[0], y[0]], 'k')
        pylab.plot([x[0], x[-1]], [y[-1], y[-1]], 'k')
        pylab.plot([x[0], x[0]], [y[0], y[-1]], 'k')
        pylab.plot([x[-1], x[-1]], [y[0], y[-1]], 'k')

    fname2 = os.path.splitext(fname)[0]
    pylab.text(xllcorner + cellsize, yllcorner + cellsize, fname2, color='m')

    topodata = Data()
    topodata.x = x
    topodata.y = y
    topodata.topo = topo

    return topodata
コード例 #6
0
""" 
Set up the plot figures, axes, and items to be done for each frame.

This module is imported by the plotting routines and then the
function setplot is called to set the plot parameters.
    
""" 

from pyclaw.data import Data
userdata = Data(['claw.data','setprob.data'])

#--------------------------
def setplot(plotdata):
#--------------------------
    
    """ 
    Specify what is to be plotted at each frame.
    Input:  plotdata, an instance of pyclaw.plotters.data.ClawPlotData.
    Output: a modified version of plotdata.
    
    """ 

    plotdata.clearfigures()  # clear any old figures,axes,items data

    

    # Figure for q[0]
    plotfigure = plotdata.new_plotfigure(name='q[0]', figno=0)

    # Set up for axes in this figure:
コード例 #7
0
ファイル: dplot_preseg.py プロジェクト: rypjones/D-Claw
def plot_topo_file(topoplotdata):
    """
    Read in a topo or bathy file and produce a pcolor map.
    """

    import os
    import pylab
    from pyclaw.data import Data

    fname = topoplotdata.fname
    topotype = topoplotdata.topotype
    if topoplotdata.climits:
        # deprecated option
        cmin = topoplotdata.climits[0]
        cmax = topoplotdata.climits[1]
    else:
        cmin = topoplotdata.cmin
        cmax = topoplotdata.cmax
    figno = topoplotdata.figno
    addcolorbar = topoplotdata.addcolorbar
    addcontour = topoplotdata.addcontour
    contour_levels = topoplotdata.contour_levels
    xlimits = topoplotdata.xlimits
    ylimits = topoplotdata.ylimits
    coarsen = topoplotdata.coarsen
    imshow = topoplotdata.imshow
    gridedges_show = topoplotdata.gridedges_show
    neg_cmap = topoplotdata.neg_cmap
    pos_cmap = topoplotdata.pos_cmap
    print_fname = topoplotdata.print_fname

    if neg_cmap is None:
        neg_cmap = colormaps.make_colormap({
            cmin: [0.3, 0.2, 0.1],
            0: [0.95, 0.9, 0.7]
        })
    if pos_cmap is None:
        pos_cmap = colormaps.make_colormap({
            0: [.5, .7, 0],
            cmax: [.2, .5, .2]
        })

    if abs(topotype) == 1:

        X, Y, topo = topotools.topofile2griddata(fname, topotype)
        topo = pylab.flipud(topo)
        Y = pylab.flipud(Y)
        x = X[0, :]
        y = Y[:, 0]
        xllcorner = x[0]
        yllcorner = y[0]
        cellsize = x[1] - x[0]

    elif abs(topotype) == 3:

        file = open(fname, 'r')
        lines = file.readlines()
        ncols = int(lines[0].split()[0])
        nrows = int(lines[1].split()[0])
        xllcorner = float(lines[2].split()[0])
        yllcorner = float(lines[3].split()[0])
        cellsize = float(lines[4].split()[0])
        NODATA_value = int(lines[5].split()[0])

        print "Loading file ", fname
        print "   nrows = %i, ncols = %i" % (nrows, ncols)
        topo = pylab.loadtxt(fname, skiprows=6, dtype=float)
        print "   Done loading"

        if 0:
            topo = []
            for i in range(nrows):
                topo.append(pylab.array(lines[6 + i], ))
            print '+++ topo = ', topo
            topo = pylab.array(topo)

        topo = pylab.flipud(topo)

        x = pylab.linspace(xllcorner, xllcorner + ncols * cellsize, ncols)
        y = pylab.linspace(yllcorner, yllcorner + nrows * cellsize, nrows)
        print "Shape of x, y, topo: ", x.shape, y.shape, topo.shape

    else:
        raise Exception("*** Only topotypes 1 and 3 supported so far")

    if coarsen > 1:
        topo = topo[slice(0, nrows, coarsen), slice(0, ncols, coarsen)]
        x = x[slice(0, ncols, coarsen)]
        y = y[slice(0, nrows, coarsen)]
        print "Shapes after coarsening: ", x.shape, y.shape, topo.shape

    if topotype < 0:
        topo = -topo

    if figno:
        pylab.figure(figno)

    if topoplotdata.imshow:
        color_norm = Normalize(cmin, cmax, clip=True)
        xylimits = (x[0], x[-1], y[0], y[-1])
        #pylab.imshow(pylab.flipud(topo.T), extent=xylimits, \
        pylab.imshow(pylab.flipud(topo), extent=xylimits, \
                cmap=cmap, interpolation='nearest', \
                norm=color_norm)
    else:
        neg_topo = ma.masked_where(topo > 0., topo)
        all_masked = (ma.count(neg_topo) == 0)
        if not all_masked:
            pylab.pcolormesh(x, y, neg_topo, cmap=neg_cmap)
            pylab.clim([cmin, 0])
            if addcolorbar:
                pylab.colorbar()

        pos_topo = ma.masked_where(topo < 0., topo)
        all_masked = (ma.count(pos_topo) == 0)
        if not all_masked:
            pylab.pcolormesh(x, y, pos_topo, cmap=pos_cmap)
            pylab.clim([0, cmax])
            if addcolorbar:
                pylab.colorbar()

    pylab.axis('scaled')

    if addcontour:
        pylab.contour(x, y, topo, levels=contour_levels, colors='k')

    if gridedges_show:
        pylab.plot([x[0], x[-1]], [y[0], y[0]], 'k')
        pylab.plot([x[0], x[-1]], [y[-1], y[-1]], 'k')
        pylab.plot([x[0], x[0]], [y[0], y[-1]], 'k')
        pylab.plot([x[-1], x[-1]], [y[0], y[-1]], 'k')

    if print_fname:
        fname2 = os.path.splitext(fname)[0]
        pylab.text(xllcorner + cellsize,
                   yllcorner + cellsize,
                   fname2,
                   color='m')

    topodata = Data()
    topodata.x = x
    topodata.y = y
    topodata.topo = topo

    return topodata
コード例 #8
0
ファイル: setplot_6.py プロジェクト: geoflows/geoclaw-4.x
Specifying a function plot_var for the plotting variable
========================================================

The pressure q[0] and q[1] are plotted on two sets of axes in a single
figure. 

The Riemann invariants R1 = (-p+Z*u)/2*Z and R2 = (p-Z*u)/2*Z
are plotted in a second figure.

This illustrates how to specify plot_var as a function.

"""

from numpy import sqrt
from pyclaw.data import Data
probdata = Data('setprob.data')  # read problem data values
Z = sqrt(probdata.rho * probdata.K)  # impedance used in R1 and R2


#--------------------------
def setplot(plotdata):
    #--------------------------
    """ 
    Specify what is to be plotted at each frame.
    Input:  plotdata, an instance of pyclaw.plotters.data.ClawPlotData.
    Output: a modified version of plotdata.
    
    """

    plotdata.clearfigures()  # clear any old figures,axes,items data
コード例 #9
0
def read_setgauges(datadir):
    """
    Read the info from setgauges.data.
    """
    import os
    import numpy as np
    from pyclaw.data import Data
    from matplotlib.mlab import find

    setgauges = Data()

    # default values if no gauges found:
    setgauges.numgauges = 0
    setgauges.gaugenos = []
    setgauges.x = {}
    setgauges.y = {}
    setgauges.t1 = {}
    setgauges.t2 = {}

    fname = os.path.join(datadir, 'setgauges.data')
    if not os.path.isfile(fname):
        #print "*** Warning in read_setgauges: missing file ",fname
        return setgauges

    sgfile = open(fname,'r')
    lines = sgfile.readlines()
    sgfile.close()

    lineno = 0
    ignore_line = True
    while ignore_line:
        line = lines[lineno] + "#"
        #print "+++ lineno = %s, line = %s" % (lineno,line)
        if line.split()[0][0]=="#":
            lineno = lineno+1
        else:
            ignore_line = False

    try:
        numgauges = int(line.split()[0])
    except:
        print "*** error setting numgauges"
        return

    if numgauges==0:
        return setgauges
        
    #print '+++ ignoring %s lines, numgauges = %s' %(lineno, numgauges)
    try:
        sgno, x, y, t1, t2 = np.loadtxt(fname, unpack=True, skiprows=lineno+1, \
                                usecols=range(5))
        if numgauges==1:
            # loadtxt returns numbers rather than arrays in this case:
            sgno = [sgno]; x = [x]; y = [y]; t1 = [t1]; t2 = [t2]

    except:
        print "*** problem reading gauges from setgauges.data"
        return setgauges

    sgno = np.array(sgno, dtype=int)  # convert to int
    setgauges.gaugenos = sgno
    setgauges.numgauges = numgauges

    for n in sgno:
        nn = find(sgno==n)
        if len(nn) > 1:
            print "*** Warning: found more than one gauge numbered ",n

        if len(nn) == 0:
            print "*** Error: didn't find gauge number %s in %s" % (n,fname)
        else:
            nn = nn[0]
            setgauges.x[n] = x[nn]
            setgauges.y[n] = y[nn]
            setgauges.t1[n] = t1[nn]
            setgauges.t2[n] = t2[nn]

    return setgauges
コード例 #10
0
def plotgauge(gaugeno, plotdata, verbose=False):
#==========================================

    """
    Plot all requested plots for a single gauge from the computation.
    The plots are requested by setting attributes of plotdata
    to ClawPlotFigure objects with plot_type="each_gauge".

    """


    if verbose:  
        gaugesoln = plotdata.getgauge(gaugeno)
        print '    Plotting gauge %s  at x = %g, y = %g ... '  \
                 % (gaugeno, gaugesoln.x, gaugesoln.y)

    if plotdata.mode() == 'iplotclaw':
        pylab.ion()

        
    try:
        plotfigure_dict = plotdata.plotfigure_dict
    except:
        print '*** Error in plotgauge: plotdata missing plotfigure_dict'
        print '*** This should not happen'
        return None

    if len(plotfigure_dict) == 0:
        print '*** Warning in plotgauge: plotdata has empty plotfigure_dict'
        print '*** Apparently no figures to plot'




    # initialize current_data containing data that will be passed
    # to beforegauge, aftergauge, afteraxes commands
    current_data = Data()
    current_data.user = Data()   # for user specified attributes
                                 # to avoid potential conflicts
    current_data.plotdata = plotdata
    current_data.gaugeno = gaugeno

    # call beforegauge if present, which might define additional 
    # attributes in current_data or otherwise set up plotting for this
    # gauge.

    beforegauge =  getattr(plotdata, 'beforegauge', None)
    if beforegauge:
        if isinstance(beforegauge, str):
            # a string to be executed
            exec(beforegauge)
        else:
            # assume it's a function
            try:
                output = beforegauge(current_data)
                if output: current_data = output
            except:
                print '*** Error in beforegauge ***'
                raise



    # iterate over each single plot that makes up this gauge:
    # -------------------------------------------------------
 
    if plotdata._mode == 'iplotclaw':
        gaugesoln = plotdata.getgauge(gaugeno)
        #import pdb; pdb.set_trace()
        print '    Plotting Gauge %s  at x = %g, y = %g ... '  \
                 % (gaugeno, gaugesoln.x, gaugesoln.y)
        requested_fignos = plotdata.iplotclaw_fignos
    else:
        requested_fignos = plotdata.print_fignos
    plotted_fignos = []

    plotdata = set_show(plotdata)   # set _show attributes for which figures
                                    # and axes should be shown.

    # loop over figures to appear for this gauge: 
    # -------------------------------------------

    for figname in plotdata._fignames:
        plotfigure = plotdata.plotfigure_dict[figname]
        if (not plotfigure._show) or (plotfigure.type != 'each_gauge'):
            continue  # skip to next figure 

        figno = plotfigure.figno
        if requested_fignos != 'all':
            if figno not in requested_fignos:
                continue # skip to next figure

        plotted_fignos.append(figno)


        if not plotfigure.kwargs.has_key('facecolor'):
            # use Clawpack's default bg color (tan)
            plotfigure.kwargs['facecolor'] = '#ffeebb'   

        # create figure and set handle:
        plotfigure._handle = pylab.figure(num=figno, **plotfigure.kwargs)

        pylab.ioff()
        if plotfigure.clf_each_gauge:
            pylab.clf()

        try:
            plotaxes_dict = plotfigure.plotaxes_dict
        except:
            print '*** Error in plotgauge: plotdata missing plotaxes_dict'
            print '*** This should not happen'
            return  None

        if (len(plotaxes_dict) == 0) or (len(plotfigure._axesnames) == 0):
            print '*** Warning in plotgauge: plotdata has empty plotaxes_dict'
            print '*** Apparently no axes to plot in figno ',figno

        # loop over axes to appear on this figure:
        # ----------------------------------------

        for axesname in plotfigure._axesnames:
            plotaxes = plotaxes_dict[axesname]
            if not plotaxes._show:
                continue   # skip this axes if no items show

            # create the axes:
            axescmd = getattr(plotaxes,'axescmd','subplot(1,1,1)')
            axescmd = 'plotaxes._handle = pylab.%s' % axescmd
            exec(axescmd)
            pylab.hold(True)



            # loop over items:
            # ----------------

            for itemname in plotaxes._itemnames:
                
                plotitem = plotaxes.plotitem_dict[itemname]
                try:
                    outdir = plotitem.outdir
                    if outdir is None:
                        outdir = plotdata.outdir
                    gaugesoln = plotdata.getgauge(gaugeno, outdir)
                except:
                    print '*** Cannot find gauge number ',gaugeno
                    print '*** looking in directory ', outdir
                    print '*** cwd = ',os.getcwd()
                    return None

                #import pdb; pdb.set_trace()
                current_data.gaugesoln = gaugesoln
                current_data.q = gaugesoln.q
                current_data.t = gaugesoln.t

                if plotitem._show:
                    try:
                        output = plotgauge1(gaugesoln,plotitem,\
                            current_data)
                        if output: current_data = output
                        if verbose:  
                                print '      Plotted  plotitem ', itemname
                    except:
                        print '*** Error in plotgauge: problem calling plotgauge1'
                        traceback.print_exc()
                        return None

            # end of loop over plotitems


        for itemname in plotaxes._itemnames:
            plotitem = plotaxes.plotitem_dict[itemname]
            if plotitem.afteritem:
                print "*** ClawPlotItem.afteritem is deprecated"
                print "*** use ClawPlotAxes.afteraxes "
                print "*** or  ClawPlotItem.aftergrid instead"


        pylab.title("%s at gauge %s" % (plotaxes.title,gaugeno))


        # call an afteraxes function if present:
        afteraxes =  getattr(plotaxes, 'afteraxes', None)
        if afteraxes:
            if isinstance(afteraxes, str):
                # a string to be executed
                exec(afteraxes)
            else:
                # assume it's a function
                try:
                    current_data.plotaxes = plotaxes
                    current_data.plotfigure = plotaxes._plotfigure
                    output = afteraxes(current_data)
                    if output: current_data = output
                except:
                    print '*** Error in afteraxes ***'
                    raise

        if plotaxes.scaled:
            pylab.axis('scaled')

        # set axes limits:
        if (plotaxes.xlimits is not None) & (type(plotaxes.xlimits) is not str):
            try:
                pylab.xlim(plotaxes.xlimits[0], plotaxes.xlimits[1])
            except:
                pass  # let axis be set automatically
        if (plotaxes.ylimits is not None) & (type(plotaxes.ylimits) is not str):
            try:
                pylab.ylim(plotaxes.ylimits[0], plotaxes.ylimits[1])
            except:
                pass  # let axis be set automatically


            # end of loop over plotaxes
            
        # end of loop over plotfigures


    # call an aftergauge function if present:
    aftergauge =  getattr(plotdata, 'aftergauge', None)
    if aftergauge:
        if isinstance(aftergauge, str):
            # a string to be executed
            exec(aftergauge)
        else:
            # assume it's a function
            try:
                output = aftergauge(current_data)
                if output: current_data = output
            except:
                print '*** Error in aftergauge ***'
                raise


    if plotdata.mode() == 'iplotclaw':
        pylab.ion()
    for figno in plotted_fignos:
        pylab.figure(figno)
        pylab.draw()

    if verbose:
        print '    Done with plotgauge for gauge %i' % (gaugeno)

    
    # print the figure(s) to file(s) if requested:
    if (plotdata.mode() != 'iplotclaw') & plotdata.printfigs:
        # iterate over all figures that are to be printed:
        for figno in plotted_fignos:
            printfig(gaugeno=gaugeno, figno=figno, \
                    format=plotdata.print_format, plotdir=plotdata.plotdir,\
                    verbose=verbose)

    return current_data
コード例 #11
0
ファイル: plotfg.py プロジェクト: MohitsSingh/clawpack-4.x
    def get_frame(self, frameno):

        if self.solutions.has_key(frameno):
            # don't read if already in dictionary:
            return self.grid, self.solutions[frameno]

        fname = "fort.fg%s_%s" % (str(
            self.fgno).zfill(2), str(frameno).zfill(4))
        fname = os.path.join(self.outdir, fname)
        if not os.path.exists(fname):
            print "*** Did not find file ", fname, " in directory ", self.outdir
            raise IOError("Missing fixed grid output file")

        self.grid = Data()
        grid = self.grid

        # Read parameters from header:

        file = open(fname, 'r')

        line = file.readline()
        t = float(line.split()[0])
        print "Reading fixed grid output from ", fname
        print '   Frame %s at t = %s' % (frameno, t)

        line = file.readline()
        grid.mx = int(line.split()[0])

        line = file.readline()
        grid.my = int(line.split()[0])

        line = file.readline()
        grid.xlow = float(line.split()[0])

        line = file.readline()
        grid.ylow = float(line.split()[0])

        line = file.readline()
        grid.xhi = float(line.split()[0])

        line = file.readline()
        grid.yhi = float(line.split()[0])

        file.close()

        grid.x = linspace(grid.xlow, grid.xhi, grid.mx + 1)
        grid.y = linspace(grid.ylow, grid.yhi, grid.my + 1)
        grid.dx = grid.x[1] - grid.x[0]
        grid.dy = grid.y[1] - grid.y[0]
        grid.xcenter = grid.x[:-1] + grid.dx / 2.
        grid.ycenter = grid.y[:-1] + grid.dy / 2.

        d = loadtxt(fname, skiprows=8)

        solution = Data()
        solution.t = t
        solution.ncols = d.shape[1]
        solution.h = reshape(d[:, 0], (grid.my, grid.mx))
        solution.B = reshape(d[:, 3], (grid.my, grid.mx))
        solution.eta = reshape(d[:, 4], (grid.my, grid.mx))
        solution.surface = ma.masked_where(isnan(solution.eta), solution.eta)
        solution.land = ma.masked_where(solution.h > self.drytol, solution.B)
        solution.fg = empty((grid.my, grid.mx, solution.ncols), dtype=float)
        for col in range(solution.ncols):
            solution.fg[:, :, col] = reshape(d[:, col], (grid.my, grid.mx))

        self.solutions[frameno] = solution
        return grid, solution
コード例 #12
0
ファイル: plotfg.py プロジェクト: dlgeorge/clawpack-4.x
    def get_frame(self, frameno):

        if self.solutions.has_key(frameno):
            # don't read if already in dictionary:
            return self.grid, self.solutions[frameno]

        fname = "fort.fg%s_%s" % (str(self.fgno).zfill(2), str(frameno).zfill(4))
        fname = os.path.join(self.outdir,fname)
        if not os.path.exists(fname):
            print "*** Did not find file ",fname," in directory ",self.outdir
            raise IOError("Missing fixed grid output file")
        

        self.grid = Data()
        grid = self.grid

        # Read parameters from header:

        file = open(fname,'r')

        line = file.readline()
        t = float(line.split()[0])
        print "Reading fixed grid output from ",fname
        print '   Frame %s at t = %s' % (frameno,t)

        line = file.readline()
        grid.mx = int(line.split()[0])

        line = file.readline()
        grid.my = int(line.split()[0])

        line = file.readline()
        grid.xlow = float(line.split()[0])

        line = file.readline()
        grid.ylow = float(line.split()[0])

        line = file.readline()
        grid.xhi = float(line.split()[0])

        line = file.readline()
        grid.yhi = float(line.split()[0])

        file.close()

        grid.x = linspace(grid.xlow, grid.xhi, grid.mx+1)
        grid.y = linspace(grid.ylow, grid.yhi, grid.my+1)
        grid.dx = grid.x[1]-grid.x[0]
        grid.dy = grid.y[1]-grid.y[0]
        grid.xcenter = grid.x[:-1] + grid.dx/2.
        grid.ycenter = grid.y[:-1] + grid.dy/2.

        d = loadtxt(fname, skiprows=8)

        solution = Data()
        solution.t = t
        solution.ncols = d.shape[1]
        solution.h = reshape(d[:,0], (grid.my,grid.mx))
        solution.B = reshape(d[:,3], (grid.my,grid.mx))
        solution.eta = reshape(d[:,4], (grid.my,grid.mx))
        solution.surface = ma.masked_where(isnan(solution.eta),solution.eta)
        solution.land = ma.masked_where(solution.h>self.drytol,solution.B)
        solution.fg = empty((grid.my,grid.mx,solution.ncols), dtype=float)
        for col in range(solution.ncols):
            solution.fg[:,:,col] = reshape(d[:,col],(grid.my,grid.mx))
        
        self.solutions[frameno] = solution
        return grid, solution
コード例 #13
0
def read_dtopo(fname, topotype=1):
    header = read_header(fname)
    if (len(header["header_lines"]) == 0) and (abs(topotype) > 1):
        raise ValueError("*** topotype = %s but no header found" % topotype)
    if (len(header["header_lines"]) > 0) and (abs(topotype) == 1):
        raise ValueError("*** topotype = %s but header found" % topotype)
    header_length = header["header_lines"].count("\n")

    if topotype == 1:
        d = np.loadtxt(fname, skiprows=header_length)
        ncol = d.shape[1]
        if ncol == 3:
            tcol = None
            xcol = d[:, 0]
            ycol = d[:, 1]
            dzcol = d[:, 2]
        else:
            tcol = d[:, 0]
            xcol = d[:, 1]
            ycol = d[:, 2]
            dzcol = d[:, 3]
        xdiff = np.diff(xcol)
        inddiff = pylab.find(xdiff < 0)
        mx = inddiff[0] + 1
        mt = 1
        if tcol is not None:
            # check if there is more than one time in this file:
            tdiff = np.diff(tcol)
            inddiff = pylab.find(tdiff > 0)
            if len(inddiff) > 0:
                mt = len(inddiff) + 1
        my = len(xcol) / (mx * mt)
        if my != int(len(xcol) / float(mx * mt)):
            print("*** found mx = %s, mt = %s" % (mx, mt))
            raise ValueError("*** mx*mt does not divide length of data")
        print("Found mt = %s times with mx = %s, my = %s" % (mt, mx, my))
        if tcol is None:
            t = []
        else:
            t = tcol[0 :: mx * my]

        X = np.reshape(xcol[: mx * my], (my, mx))
        Y = np.reshape(ycol[: mx * my], (my, mx))
        dZ = np.reshape(dzcol, (mt, my, mx))

    elif topotype == 3:
        try:
            my = header["nrows"]
            mx = header["ncols"]
            mt = header["mtimes"]
            xll = header["xll"]
            yll = header["yll"]
            t0 = header["t0"]
            dx = header["dx"]
            dy = header["dy"]
            dt = header["dt"]
        except:
            raise ValueError("*** Missing information from header")
        if (dt == 0) or (mt == 1):
            t = np.array([t0])
        else:
            t = np.arange(t0, t0 + mt * dt, dt)
        x = np.linspace(xll, xll + mx * dx, mx)
        y = np.linspace(yll, yll + my * dy, my)
        X, Y = np.meshgrid(x, y)
        X = X.T
        Y = Y.T

        fdata = np.loadtxt(fname, skiprows=header_length)
        dzcol = np.reshape(fdata, (mx * my * mt, 1))
        dZ = np.empty((mt, mx, my))
        for i in range(mt):
            dzi = np.reshape(dzcol[i * mx * my : (i + 1) * mx * my], (my, mx))
            dzi = np.flipud(dzi)
            dZ[i, :, :] = dzi.T

    else:
        raise ValueError("*** Cannot read topotype = " % topotype)

    dtopo = Data()
    dtopo.t = t
    dtopo.X = X
    dtopo.Y = Y
    dtopo.dZ = dZ
    return dtopo
コード例 #14
0
def setplot(plotdata):
    #--------------------------
    """
    Specify what is to be plotted at each frame.
    Input:  plotdata, an instance of pyclaw.plotters.data.ClawPlotData.
    Output: a modified version of plotdata.

    """

    from pyclaw.plotters import colormaps, geoplot
    from numpy import linspace

    plotdata.clearfigures()  # clear any old figures,axes,items data
    probdata = Data(os.path.join(datadir, 'setprob.data'))
    d = probdata.d
    clawdata = Data(os.path.join(datadir, 'amr2ez.data'))
    my = clawdata.my
    print "+++ in setplot d = ", d
    print "+++ in setplot my = ", my

    def set_drytol(current_data):
        # The drytol parameter is used in masking land and water and
        # affects what color map is used for cells with small water depth h.
        # The cell will be plotted as dry if h < drytol.
        # The best value to use often depends on the application and can
        # be set here (measured in meters):
        current_data.user.drytol = 1.e-3

    plotdata.beforeframe = set_drytol

    # To plot gauge locations on imshow or contour plot, use this as
    # an afteraxis function:

    figkwargs = dict(figsize=(18, 9), dpi=800)
    #-----------------------------------------
    # Figure for imshow plot
    #-----------------------------------------
    plotfigure = plotdata.new_plotfigure(name='imshow', figno=0)
    plotfigure.show = True
    #plotfigure.kwargs = figkwargs
    # Set up for axes in this figure:
    plotaxes = plotfigure.new_plotaxes('imshow')
    plotaxes.title = 'Case 1'
    plotaxes.scaled = True

    def addgauges(current_data, fnt=14):
        from pyclaw.plotters import gaugetools
        gaugetools.plot_gauge_locations(current_data.plotdata, \
                gaugenos='all', format_string='ko', add_labels=True,markersize=8,fontsize=fnt)

    def fixup(current_data):
        import pylab
        t = current_data.t
        pylab.title('Case 1: surface at %4.2f seconds' % t, fontsize=14)
        #pylab.xticks([141.0325-.03,141.0325,141.0325+.03],fontsize=15)
        #pylab.yticks(fontsize=15)
        #pylab.plot([139.7],[35.6],'wo',markersize=10)
        #pylab.text(138.2,35.9,'Tokyo',color='w',fontsize=25)
        #x_fukushima = 141.0325
        #y_fukushima = 37.421389
        #pylab.plot([x_fukushima],[y_fukushima],'wo',markersize=8)
        #pylab.text(x_fukushima-.015,y_fukushima+.004,'Fukushima',color='w',fontsize=15)
        addgauges(current_data)

    plotaxes.afteraxes = fixup

    # Water
    plotitem = plotaxes.new_plotitem(plot_type='2d_imshow')
    plotitem.show = True
    #plotitem.plot_var = geoplot.surface
    plotitem.plot_var = geoplot.surface_or_depth
    plotitem.imshow_cmap = geoplot.tsunami_colormap
    plotitem.imshow_cmin = -.02
    plotitem.imshow_cmax = .02
    plotitem.add_colorbar = False
    plotitem.amr_gridlines_show = [0, 0, 0]
    plotitem.gridedges_show = 1

    # Add contour lines of bathymetry:
    plotitem = plotaxes.new_plotitem(plot_type='2d_contour')
    #plotitem.show = False
    plotitem.plot_var = geoplot.topo
    from numpy import arange, linspace
    plotitem.contour_levels = arange(-2.5, 1, .01)
    plotitem.amr_contour_colors = ['k']  # color on each level
    plotitem.kwargs = {'linestyles': 'solid'}
    plotitem.amr_contour_show = [2]  # show contours only on finest level
    plotitem.gridlines_show = 0
    plotitem.gridedges_show = 0

    # Land
    plotitem = plotaxes.new_plotitem(plot_type='2d_imshow')
    plotitem.show = True
    plotitem.plot_var = geoplot.land
    plotitem.imshow_cmap = geoplot.land1_colormap
    plotitem.imshow_cmin = 0.0
    plotitem.imshow_cmax = 1.0
    plotitem.add_colorbar = False
    plotitem.amr_gridlines_show = [0, 0, 0]
    plotitem.gridedges_show = 1
    #dx2 = .04
    #dy2 = .08

    plotaxes.xlimits = [-1.0, 3.0]
    #   plotaxes.xlimits = [-1.0,2.0]

    plotaxes.ylimits = [0, 1.]
    #   plotaxes.ylimits = [-1.,1.]

    #-----------------------------------------
    # Figure for line plot
    #-----------------------------------------
    #    plotfigure = plotdata.new_plotfigure(name='line', figno=500)

    # Set up for axes in this figure:
    #    plotaxes = plotfigure.new_plotaxes()
    #    plotaxes.xlimits = [-12,12]
    #    plotaxes.ylimits = [-12, 12]
    #    plotaxes.title = 'Surface'

    # Plot surface as blue curve:
    #    plotitem = plotaxes.new_plotitem(plot_type='1d_plot')
    #    plotitem.plotstyle = 'b-'

    # Plot Runup
    #    t,x1,x2 = loadtxt('_output/fort.runup',unpack=True)
    #    plot(t,x1)
    #    plot(t,x2)

    #-----------------------------------------
    # Figure for cross section of surface
    #-----------------------------------------

    #    plotfigure = plotdata.new_plotfigure(name='surface', figno=200)
    #    plotaxes = plotfigure.new_plotaxes('surface')
    #    plotitem = plotaxes.new_plotitem(plot_type='1d_from_2d_data')
    #    def crosssec(current_data):
    #        q = current_data.q
    #        x = current_data.x
    #        return x[:,50], q[:,50,3]

    #    plotitem.map_2d_to_1d = crosssec
    #    def plot_beach(current_data):
    #        import pylab
    #        x = current_data.x[:,50]
    #        pylab.plot(x, -0.5*x,'k')

    #    plotaxes.ylimits = [-0.5,0.5]
    #    plotaxes.afteraxes = plot_beach

    #-----------------------------------------
    # Figures for gauges
    #-----------------------------------------

    plotfigure = plotdata.new_plotfigure(name='Surface & topo', figno=300, \
                    type='each_gauge')

    # Set up for axes in this figure:
    plotaxes = plotfigure.new_plotaxes()
    plotaxes.xlimits = [0, 5.0]
    #plotaxes.ylimits = [-0.03,0.03]
    plotaxes.title = 'Surface'

    # Plot surface as blue curve:
    plotitem = plotaxes.new_plotitem(plot_type='1d_plot')
    plotitem.plot_var = 3
    plotitem.plotstyle = 'b-'

    # Plot fine grid as red curve:
    plotitem = plotaxes.new_plotitem(plot_type='1d_plot')
    plotitem.show = False
    #plotitem.outdir = '_output_fine'
    plotitem.plot_var = 3
    plotitem.plotstyle = '-'
    plotitem.color = 'r'

    # Plot topo as green curve:
    #plotitem = plotaxes.new_plotitem(plot_type='1d_plot')

    def gaugetopo(current_data):
        q = current_data.q
        h = q[:, 0]
        eta = q[:, 3]
        topo = eta - h
        return eta

    plotitem.plot_var = gaugetopo
    plotitem.clf_each_gauge = False
    plotitem.plotstyle = 'b-'

    def add_zeroline(current_data):
        from pylab import plot, legend, xticks, floor
        t = current_data.t
        #legend(('surface','topography'),loc='lower left')
        plot(t, 0 * t, 'k')
        #n = floor(t.max()/3600.) + 2
        xticks([range(10)])

    #plotaxes.afteraxes = add_zeroline

    def plot_labData(current_data):
        import pylab
        gaugeno = current_data.gaugeno
        try:
            d_param = d
            print "+++ d_param = ", d_param
        except:
            print "+++ d not set"
            d_param = None
        d, gauget, gauge_ave = read_lab_data(d_param)
        try:
            pylab.plot(gauget, gauge_ave[gaugeno], 'k')
            pylab.legend(('GeoClaw', 'Lab Data'), loc='lower right')
            #pylab.legend(('GeoClaw coarse', 'GeoClaw fine', 'Lab Data'), loc='lower right')
        except:
            print "No data for gauge ", gaugeno
        #gaugeTime

        print "+++ for gauges, my = ", my
        if my:
            pylab.title("Gauge %s for d = %4.3f with my = %s" %
                        (gaugeno, d, my))
        else:
            pylab.title("Gauge %s for d = %4.3f" % (gaugeno, d))

    plotaxes.afteraxes = plot_labData

    def add_tankdata(datafile):
        from pylab import plot
        import numpy as np
        ts = np.loadtxt(datafile)
        plot(ts[:, 0], ts[:, 1], 'k-')

    #-----------------------------------------

    # Parameters used only when creating html and/or latex hardcopy
    # e.g., via pyclaw.plotters.frametools.printframes:

    plotdata.printfigs = True  # print figures
    plotdata.print_format = 'png'  # file format
    plotdata.print_framenos = [0]  # list of frames to print
    plotdata.print_gaugenos = 'all'  # list of gauges to print
    plotdata.print_fignos = [300]  # list of figures to print
    plotdata.html = True  # create html files of plots?
    plotdata.html_homelink = '../README.html'  # pointer for top of index
    plotdata.latex = False  # create latex file of plots?
    plotdata.latex_figsperline = 2  # layout of plots
    plotdata.latex_framesperline = 1  # layout of plots
    plotdata.latex_makepdf = False  # also run pdflatex?

    return plotdata
コード例 #15
0
ファイル: setplot.py プロジェクト: mandli/storm_surge
def setplot(plotdata):
#--------------------------
    
    """ 
    Specify what is to be plotted at each frame.
    Input:  plotdata, an instance of pyclaw.plotters.data.ClawPlotData.
    Output: a modified version of plotdata.
    
    """ 

    import os

    import numpy as np
    import matplotlib.pyplot as plt

    from pyclaw.plotters import colormaps, geoplot
    from pyclaw.data import Data

    amrdata = Data(os.path.join(plotdata.outdir,'amr2ez.data'))
    hurricane_data = Data(os.path.join(plotdata.outdir,'hurricane.data'))
    multilayer_data = Data(os.path.join(plotdata.outdir,'multilayer.data'))
    
    if multilayer_data.bathy_type == 1:
        ref_lines = [multilayer_data.bathy_location]
    elif multilayer_data.bathy_type == 2:
        ref_lines = [multilayer_data.x0,multilayer_data.x1,multilayer_data.x2]
    else:
        ref_lines = []
    
    plotdata.clearfigures()
    plotdata.clear_frames = False
    plotdata.clear_figs = True
    
    plotdata.save_frames = False
    
    # ========================================================================
    #  Generic helper functions
    # ========================================================================        
    def bathy_ref_lines(current_data):
        plt.hold(True)
        y = [amrdata.ylower,amrdata.yupper]
        for ref_line in ref_lines:
            plt.plot([ref_line,ref_line],y,'y--')
        plt.hold(False)
        
    def day_figure_title(current_data):
        t = current_data.t
        title = current_data.plotaxes.title
        plt.title('%s at time t = %s days' % (title,str(t/(3600.0*24.0))))
        
    def m_to_km_labels(current_data=None):
        plt.xlabel('km')
        plt.ylabel('km')
        locs,labels = plt.xticks()
        labels = locs/1.e3
        plt.xticks(locs,labels)
        locs,labels = plt.yticks()
        labels = locs/1.e3
        plt.yticks(locs,labels)
    
    def pcolor_afteraxes(current_data):
        day_figure_title(current_data)
        m_to_km_labels()
        bathy_ref_lines(current_data)
        # gauge_locations(current_data)
        
    def contour_afteraxes(current_data):
        day_figure_title(current_data)
        m_to_km_labels()
        bathy_ref_lines(current_data)

    # ========================================================================
    # Gauge functions
    # ========================================================================
    def gauge_locations(current_data,gaugenos='all'):
        from pyclaw.plotters import gaugetools
        plt.hold(True)
        gaugetools.plot_gauge_locations(current_data.plotdata, \
             gaugenos=gaugenos, format_string='kx', add_labels=True)
        plt.hold(False)

    def gaugetopo(current_data):
        q = current_data.q
        h = q[:,0]
        eta = q[:,3]
        topo = eta - h
        return topo
        
    def gauge_afteraxes(current_data):
        # Change time to hours
        plt.xlabel('t (days)')
        plt.ylabel('m')
        locs,labels = plt.xticks()
        # import pdb; pdb.set_trace()
        labels = np.trunc(locs/(24.0*3600.0))
        # locs = np.linspace(-12.0,40,52)
        # labels = range(-12,41)
        plt.xticks(locs,labels)
        
        # Add sea level line
        # t = current_data.t
        plt.hold(True)
        plt.plot([0,0],[0,40],'k-')
        plt.hold(False)
        
    # ========================================================================
    #  Water helper functions
    # ========================================================================
    def b(cd):
        return cd.q[:,:,3] - cd.q[:,:,0]
        
    def extract_eta(h,eta,DRY_TOL=10**-3):
        index = np.nonzero((np.abs(h) < DRY_TOL) + (h == np.nan))
        eta[index[0],index[1]] = np.nan
        return eta
    
    def extract_velocity(h,hu,DRY_TOL=10**-8):
        # u = np.ones(hu.shape) * np.nan
        u = np.zeros(hu.shape)
        index = np.nonzero((np.abs(h) > DRY_TOL) * (h != np.nan))
        u[index[0],index[1]] = hu[index[0],index[1]] / h[index[0],index[1]]
        return u
    
    def eta(cd):
        return extract_eta(cd.q[:,:,0],cd.q[:,:,3])
        
    def water_u(cd):
        # index = np.nonzero(current_data.q[:,:,0] > 1e-6)
        # u = np.zeros(current_data.q[:,:,1].shape)
        # u[index] = current_data.q[index,1] / current_data.q[index,0]
        # return u
        return extract_velocity(cd.q[:,:,0],cd.q[:,:,1])
        # return np.where(abs(current_data.q[:,:,0]) > 10**-16,
        #     current_data.q[:,:,1] / current_data.q[:,:,0],
        #     0.0)
        
    def water_v(cd):
        # index = np.nonzero(current_data.q[:,:,0] > 1e-6)
        # v = np.zeros(current_data.q[:,:,2].shape)
        # v[index] = current_data.q[index,2] / current_data.q[index,0]
        # return u
        return extract_velocity(cd.q[:,:,0],cd.q[:,:,2])
        # return np.where(abs(current_data.q[:,:,0]) > 10**-16,
        #     current_data.q[:,:,2] / current_data.q[:,:,0],
        #     0.0)
        
    def water_speed(current_data):
        u = water_u(current_data)
        v = water_v(current_data)
            
        return np.sqrt(u**2+v**2)
        
    def water_quiver(current_data):
        u = water_u(current_data)
        v = water_v(current_data)
            
        plt.hold(True)
        Q = plt.quiver(current_data.x[::2,::2],current_data.y[::2,::2],
                        u[::2,::2],v[::2,::2])
        max_speed = np.max(np.sqrt(u**2+v**2))
        label = r"%s m/s" % str(np.ceil(0.5*max_speed))
        plt.quiverkey(Q,0.15,0.95,0.5*max_speed,label,labelpos='W')
        plt.hold(False)
            
    def wind_x(cd):
        return cd.q[:,:,4]
    def wind_y(cd):
        return cd.q[:,:,5]
    def wind_speed(cd):
        return np.sqrt(wind_x(cd)**2 + wind_y(cd)**2)

    # ========================================================================
    #  Profile functions
    # ========================================================================
    class PlotProfile(object):
    
        def __init__(self,slice_value = 0.0):
            self.slice_value = slice_value
    
        def slice_index(self,cd):
            if cd.grid.y.lower < self.slice_value < cd.grid.y.upper:
                return int((self.slice_value - cd.grid.y.lower) / cd.dy - 0.5)
            else:
                return None
    
        def bathy_profile(self,current_data):
            index = self.slice_index(current_data)
            if index:
                return current_data.x[:,index], b(current_data)[:,index]
            else:
                return None, None
        
        def surface_profile(self,current_data):
            index = self.slice_index(current_data)
            if index:
                return current_data.x[:,index], eta(current_data)[:,index]
            else:
                return None, None

    # ========================================================================
    #  Plot items
    # ========================================================================
    def add_surface_elevation(plotaxes,bounds=None,plot_type='pcolor'):
        if plot_type == 'pcolor' or plot_type == 'imshow':            
            plotitem = plotaxes.new_plotitem(plot_type='2d_imshow')
            # plotitem.plotvar = eta
            plotitem.plot_var = geoplot.surface
            plotitem.imshow_cmap = colormaps.make_colormap({1.0:'r',0.5:'w',0.0:'b'})
            if bounds is not None:
                plotitem.imshow_cmin = bounds[0]
                plotitem.imshow_cmax = bounds[1]
            plotitem.add_colorbar = True
            plotitem.amr_gridlines_show = [0,0,0]
            plotitem.amr_gridedges_show = [1,1,1]
        elif plot_type == 'contour':            
            plotitem = plotaxes.new_plotitem(plot_type='2d_contour')
            plotitem.plot_var = geoplot.surface
            if bounds is None:
                plotitem.contour_levels = [-2.5,-1.5,-0.5,0.5,1.5,2.5]
            # plotitem.contour_nlevels = 21
            # plotitem.contour_min = -2.0
            # plotitem.contour_max = 2.0
            # plotitem.kwargs = {''}
            plotitem.amr_contour_show = [1,1,1]
            plotitem.amr_gridlines_show = [0,0,0]
            plotitem.amr_gridedges_show = [1,1,1]
            plotitem.amr_contour_colors = 'k'
            # plotitem.amr_contour_colors = ['r','k','b']  # color on each level
            # plotitem.amr_grid_bgcolor = ['#ffeeee', '#eeeeff', '#eeffee']
    
    def add_speed(plotaxes,bounds=None,plot_type='pcolor'):
        if plot_type == 'pcolor' or plot_type == 'imshow':
            plotitem = plotaxes.new_plotitem(plot_type='2d_imshow')
            plotitem.plot_var = water_speed
            # plotitem.plot_var = 1
            plotitem.imshow_cmap = plt.get_cmap('PuBu')
            if bounds is not None:
                plotitem.imshow_cmin = bounds[0]
                plotitem.imshow_cmax = bounds[1]
            plotitem.add_colorbar = True
            plotitem.amr_gridlines_show = [0,0,0]
            plotitem.amr_gridedges_show = [1]
        elif plot_type == 'quiver':
            plotitem = plotaxes.new_plotitem(plot_type='2d_quiver')
            plotitem.quiver_var_x = water_u
            plotitem.quiver_var_y = water_v
            plotitem.amr_quiver_show = [4,10,10]
            plotitem.amr_show_key = [True,True,False]
            plotitem.key_units = 'm/s'
            
        elif plot_type == 'contour':
            plotitem = plotaxes.new_plotitem(plot_type='2d_contour')
            plotitem.plot_var = water_speed
            plotitem.kwargs = {'linewidths':1}
            # plotitem.contour_levels = [1.0,2.0,3.0,4.0,5.0,6.0]
            plotitem.contour_levels = [0.5,1.5,3,4.5,6.0]
            plotitem.amr_contour_show = [1,1,1]
            plotitem.amr_gridlines_show = [0,0,0]
            plotitem.amr_gridedges_show = [1,1,1]
            plotitem.amr_contour_colors = 'k'
            # plotitem.amr_contour_colors = ['r','k','b']  # color on each level
            # plotitem.amr_grid_bgcolor = ['#ffeeee', '#eeeeff', '#eeffee']
            

    def add_x_velocity(plotaxes,plot_type='pcolor',bounds=None):
        if plot_type == 'pcolor' or plot_type == 'imshow':
            plotitem = plotaxes.new_plotitem(plot_type='2d_imshow')
            plotitem.plot_var = water_u
            if bounds is not None:
                plotitem.imshow_cmin = bounds[0]
                plotitem.imshow_cmax = bounds[1]
            plotitem.add_colorbar = True
            plotitem.imshow_cmap = plt.get_cmap('PiYG')
            plotitem.amr_gridlines_show = [0,0,0]
            plotitem.amr_gridedges_show = [1]
        elif plot_type == 'contour':
            pass
    
    def add_y_velocity(plotaxes,plot_type='pcolor',bounds=None):
        if plot_type == 'pcolor' or plot_type == 'imshow':
            plotitem = plotaxes.new_plotitem(plot_type='2d_imshow')
            plotitem.plot_var = water_v
            if bounds is not None:
                plotitem.imshow_cmin = bounds[0]
                plotitem.imshow_cmax = bounds[1]
            plotitem.imshow_cmap = plt.get_cmap('PiYG')
            plotitem.add_colorbar = True
            plotitem.amr_gridlines_show = [0,0,0]
            plotitem.amr_gridedges_show = [1]
        elif plot_type == 'contour':
            pass
            
    def add_wind(plotaxes,bounds=None,plot_type='pcolor'):
        if plot_type == 'pcolor' or plot_type == 'imshow':
            plotitem = plotaxes.new_plotitem(plot_type='2d_imshow')
            plotitem.plot_var = wind_speed
            plotitem.imshow_cmap = plt.get_cmap('PuBu')
            if bounds is not None:
                plotitem.imshow_cmin = bounds[0]
                plotitem.imshow_cmax = bounds[1]
            plotitem.add_colorbar = True
            plotitem.amr_imshow_show = [1,1,1]
            plotitem.amr_gridlines_show = [0,0,0]
            plotitem.amr_gridedges_show = [1,1,1]
        elif plot_type == 'contour':
            plotitem = plotaxes.new_plotitem(plot_type='2d_contour')
            plotitem.plot_var = wind_speed
            plotitem.contour_nlevels = hurricane_data.max_wind_nest
            plotitem.countour_min = hurricane_data.wind_refine[0]
            plotitem.gridedges_show = 1
        elif plot_type == 'quiver':
            plotitem = plotaxes.new_plotitem(plot_type='2d_quiver')
            plotitem.quiver_var_x = wind_x
            plotitem.quiver_var_y = wind_y
            plotitem.amr_quiver_show = [0,0,1]
            plotitem.amr_quiver_key_show = [True,False,False]
            plotitem.amr_quiver_key_units = 'm/s'
            
    def add_vorticity(plotaxes,bounds=None,plot_type="pcolor"):
        if plot_type == 'pcolor' or plot_type == 'imshow':            
            plotitem = plotaxes.new_plotitem(plot_type='2d_imshow')
            plotitem.plot_var = 9
            plotitem.imshow_cmap = plt.get_cmap('PRGn')
            if bounds is not None:
                plotitem.imshow_cmin = bounds[0]
                plotitem.imshow_cmax = bounds[1]
            plotitem.add_colorbar = True
            plotitem.amr_gridlines_show = [0,0,0]
            plotitem.amr_gridedges_show = [1]
            
    def add_land(plotaxes,plot_type='pcolor'):
        if plot_type == 'pcolor':
            plotitem = plotaxes.new_plotitem(plot_type='2d_pcolor')
            plotitem.show = True
            plotitem.plot_var = geoplot.land
            plotitem.pcolor_cmap = geoplot.land_colors
            plotitem.pcolor_cmin = 0.0
            plotitem.pcolor_cmax = 80.0
            plotitem.add_colorbar = False
            plotitem.amr_gridlines_show = [0,0,0]
            plotitem.amr_gridedges_show = [1,1,1]
        elif plot_type == 'contour':            
            plotitem = plotaxes.new_plotitem(plot_type='2d_contour')
            plotitem.plot_var = geoplot.land
            plotitem.contour_nlevels = 40
            plotitem.contour_min = 0.0
            plotitem.contour_max = 100.0
            plotitem.amr_contour_colors = ['g']  # color on each level
            plotitem.amr_grid_bgcolor = ['#ffeeee', '#eeeeff', '#eeffee']
            plotitem.gridlines_show = 0
            plotitem.gridedges_show = 0

    # Limits
    xlimits = [amrdata.xlower,amrdata.xupper]
    ylimits = [amrdata.ylower,amrdata.yupper]
    multilayer_data.eta = eta
    # surface_limits = [-0.15,0.15]
    # speed_limits = [0.0,0.1]
    surface_limits = None
    speed_limits = None
    
    vorticity_limits = [-1.e-2,1.e-2]
    
    # ========================================================================
    #  Surface Elevation
    # ========================================================================
    plotfigure = plotdata.new_plotfigure(name='Surface', figno=0)
    plotfigure.show = True

    # Set up for axes in this figure:
    plotaxes = plotfigure.new_plotaxes()
    plotaxes.title = 'Surface'
    plotaxes.scaled = True
    plotaxes.xlimits = xlimits
    plotaxes.ylimits = ylimits
    plotaxes.afteraxes = pcolor_afteraxes
    
    add_surface_elevation(plotaxes,bounds=surface_limits)
    add_land(plotaxes)
    
    # ========================================================================
    #  Water Speed
    # ========================================================================
    plotfigure = plotdata.new_plotfigure(name='speed', figno=100)
    plotfigure.show = False

    # Set up for axes in this figure:
    plotaxes = plotfigure.new_plotaxes()
    plotaxes.title = 'Currents'
    plotaxes.scaled = True
    plotaxes.xlimits = xlimits
    plotaxes.ylimits = ylimits
    plotaxes.afteraxes = pcolor_afteraxes

    # Speed
    add_speed(plotaxes,bounds=speed_limits)

    # Land
    add_land(plotaxes)
    
    # X-Velocity
    plotfigure = plotdata.new_plotfigure(name='velocity_x',figno=101)
    plotfigure.show = True
    plotfigure.kwargs = {'figsize':(14,4)}

    # X Velocity
    plotaxes = plotfigure.new_plotaxes()
    plotaxes.axescmd = 'subplot(121)'
    plotaxes.title = 'X-Velocity'
    plotaxes.scaled = True
    plotaxes.xlimits = xlimits
    plotaxes.ylimits = ylimits
    plotaxes.afteraxes = pcolor_afteraxes

    add_x_velocity(plotaxes,bounds=speed_limits)
    add_land(plotaxes)
    
    # Y Velocity
    plotaxes = plotfigure.new_plotaxes()
    plotaxes.axescmd = 'subplot(122)'
    plotaxes.title = 'Y-Velocity'
    plotaxes.scaled = True
    plotaxes.xlimits = xlimits
    plotaxes.ylimits = ylimits
    plotaxes.afteraxes = pcolor_afteraxes

    add_y_velocity(plotaxes,bounds=speed_limits)
    add_land(plotaxes)
    
    
    # ========================================================================
    #  Wind speed
    # ========================================================================
    plotfigure = plotdata.new_plotfigure(name='wind',figno=2)
    plotfigure.show = True
    
    plotaxes = plotfigure.new_plotaxes()
    plotaxes.title = "Wind"
    plotaxes.scaled = True
    plotaxes.xlimits = xlimits
    plotaxes.ylimits = ylimits
    plotaxes.afteraxes = pcolor_afteraxes
    
    # Wind
    add_wind(plotaxes)
    add_land(plotaxes)

    # ========================================================================
    #  Profile Plots
    # ========================================================================
    # Profile variables
            
    def profile_afteraxes(current_data):
        day_figure_title(current_data)
        loc,label = plt.xticks()
        label = loc/1.e3
        plt.xticks(loc,label)
        plt.xlabel('km')
        if current_data.plotaxes.title == 'Wind':
            plt.ylabel('m/s')
        else:
            plt.ylabel('m')
            
        t = current_data.t
        # Hurricane eye
        x = t * hurricane_data.hurricane_velocity[0] + hurricane_data.R_eye_init[0]
        plt.hold(True)
        plt.plot(x,0.0,'r+')
        plt.hold(False)
            
    def remove_labels_profile(cd,direction='x'):
        plt.hold(True)
        if direction == 'x':
            plt.xlabel('')
            locs,labels = plt.xticks()
            # labels = np.flipud(locs)/1.e3
            labels = ['' for i in xrange(len(locs))]
            plt.xticks(locs,labels)
            plt.ylabel('m')
        elif direction == 'y':
            plt.ylabel('')
            locs,labels = plt.yticks()
            # labels = np.flipud(locs)/1.e3
            labels = ['' for i in xrange(len(locs))]
            plt.yticks(locs,labels)
            plt.xlabel('m')
        plt.hold(False)
        
    def labels_profile(cd,direction='x'):
        if direction == 'x':
            loc,label = plt.xticks()
            label = loc/1.e3
            plt.xticks(loc,label)
            plt.xlabel('km')
            if cd.plotaxes.title == 'Wind':
                plt.ylabel('m/s')
            else:
                plt.ylabel('m')
        elif direction == 'y':
            loc,label = plt.yticks()
            label = loc/1.e3
            plt.yticks(loc,label)
            plt.ylabel('km')
            if cd.plotaxes.title == 'Wind':
                plt.xlabel('m/s')
            else:
                plt.xlabel('m')
        
    def profile_afteraxes(current_data):
        day_figure_title(current_data)
        labels_profile(current_data)
        # bathy_ref_lines_profile(current_data,surface_limits)
    
    
    plotfigure = plotdata.new_plotfigure(name='profile', figno=4)
    plotfigure.show = False
        
    plotaxes = plotfigure.new_plotaxes()
    plotaxes.title = 'Profiles'
    plotaxes.xlimits = xlimits
    # plotaxes.ylimits = surface_limits
    plotaxes.afteraxes = profile_afteraxes
    
    profile_plot = PlotProfile(0.0)
    plotitem = plotaxes.new_plotitem(plot_type="1d_from_2d_data")
    plotitem.map_2d_to_1d = profile_plot.surface_profile
    plotitem.amr_plotstyle = ['-','-.','+','x','.']
    plotitem.color = 'b'#(0.2,0.8,1.0)
    plotitem = plotaxes.new_plotitem(plot_type='1d_from_2d_data')
    plotitem.map_2d_to_1d = profile_plot.bathy_profile
    plotitem.amr_plotstyle = ['-','-.','+','x','.']  
    plotitem.color = 'k'
        
    # ========================================================================
    #  Bathy Profile
    # ========================================================================
    plotfigure = plotdata.new_plotfigure(name='bathy_profile',figno=20)
    plotfigure.show = False
    
    plotaxes = plotfigure.new_plotaxes()
    plotaxes.xlimits = [amrdata.xlower,amrdata.xupper]
    plotaxes.title = "Bathymetry Profile"
    plotaxes.scaled = 'equal'
    
    plotitem = plotaxes.new_plotitem(plot_type='2d_imshow')
    plotitem.plot_var = b
    plotitem.imshow_cmap = plt.get_cmap('earth')
    plotitem.imshow_cmin = -3300
    plotitem.imshow_cmax = 100.0
    plotitem.add_colorbar = True
    plotitem.amr_imshow_show = [1,1,1]
    plotitem.amr_gridlines_show = [0,0,0]
    plotitem.amr_gridedges_show = [1,1,1]
    plotitem.show = True
    
    # ========================================================================
    # Figure for grids alone
    # ========================================================================
    plotfigure = plotdata.new_plotfigure(name='grids', figno=11)
    plotfigure.show = False
    
    # Set up for axes in this figure:
    plotaxes = plotfigure.new_plotaxes()
    plotaxes.xlimits = [amrdata.xlower,amrdata.xupper]
    plotaxes.xlimits = [amrdata.ylower,amrdata.yupper]
    plotaxes.title = 'grids'
    plotaxes.afteraxes = pcolor_afteraxes
    plotaxes.scaled = True
    
    # Set up for item on these axes:
    plotitem = plotaxes.new_plotitem(plot_type='2d_grid')
    # plotitem.amr_grid_bgcolor = ['#ffeeee', '#eeeeff', '#eeffee']
    plotitem.amr_grid_bgcolor = ['blue','red','green','cyan','yellow']
    plotitem.amr_gridlines_show = [1,1,0,0,0,0]   
    plotitem.amr_gridedges_show = 1
    
    # ========================================================================
    # Figures for momentum
    # ========================================================================
    plotfigure = plotdata.new_plotfigure(name='x-momentum', figno=13)
    plotfigure.show = False

    # Set up for axes in this figure:
    plotaxes = plotfigure.new_plotaxes()
    plotaxes.title = 'X-Velocity'
    plotaxes.scaled = True
    plotaxes.xlimits = [amrdata.xlower,amrdata.xupper]
    plotaxes.ylimits = [amrdata.ylower,amrdata.yupper]
    plotaxes.afteraxes = pcolor_afteraxes
    
    # Water
    plotitem = plotaxes.new_plotitem(plot_type='2d_pcolor')
    # plotitem.plot_var = geoplot.surface
    plotitem.plot_var = water_u
    plotitem.pcolor_cmap = colormaps.make_colormap({1.0:'r',0.5:'w',0.0:'b'})
    # plotitem.pcolor_cmin = -1.e-10
    # plotitem.pcolor_cmax = 1.e-10
    # plotitem.pcolor_cmin = -2.5 # -3.0
    # plotitem.pcolor_cmax = 2.5 # 3.0
    plotitem.add_colorbar = True
    plotitem.amr_gridlines_show = [0,0,0]
    plotitem.amr_gridedges_show = [1,1,1]

    # Land
    plotitem = plotaxes.new_plotitem(plot_type='2d_pcolor')
    plotitem.show = True
    plotitem.plot_var = geoplot.land
    plotitem.pcolor_cmap = geoplot.land_colors
    plotitem.pcolor_cmin = 0.0
    plotitem.pcolor_cmax = 80.0
    plotitem.add_colorbar = False
    plotitem.amr_gridlines_show = [0,0,0]
    plotitem.amr_gridedges_show = [1,1,1]
    
    plotfigure = plotdata.new_plotfigure(name='y-momentum', figno=14)
    plotfigure.show = False

    # Set up for axes in this figure:
    plotaxes = plotfigure.new_plotaxes()
    plotaxes.title = 'Y-Velocity'
    plotaxes.scaled = True
    plotaxes.xlimits = [amrdata.xlower,amrdata.xupper]
    plotaxes.ylimits = [amrdata.ylower,amrdata.yupper]
    plotaxes.afteraxes = pcolor_afteraxes
    
    # Water
    plotitem = plotaxes.new_plotitem(plot_type='2d_pcolor')
    # plotitem.plot_var = geoplot.surface
    plotitem.plot_var = water_v
    plotitem.pcolor_cmap = colormaps.make_colormap({1.0:'r',0.5:'w',0.0:'b'})
    # plotitem.pcolor_cmin = -1.e-10
    # plotitem.pcolor_cmax = 1.e-10
    # plotitem.pcolor_cmin = -2.5 # -3.0
    # plotitem.pcolor_cmax = 2.5 # 3.0
    plotitem.add_colorbar = True
    plotitem.amr_gridlines_show = [0,0,0]
    plotitem.amr_gridedges_show = [1,1,1]

    # Land
    plotitem = plotaxes.new_plotitem(plot_type='2d_pcolor')
    plotitem.show = True
    plotitem.plot_var = geoplot.land
    plotitem.pcolor_cmap = geoplot.land_colors
    plotitem.pcolor_cmin = 0.0
    plotitem.pcolor_cmax = 80.0
    plotitem.add_colorbar = False
    plotitem.amr_gridlines_show = [0,0,0]
    plotitem.amr_gridedges_show = [1,1,1]
    
    # ========================================================================
    #  Contour plot for surface
    # ========================================================================
    plotfigure = plotdata.new_plotfigure(name='contour_surface',figno=15)
    plotfigure.show = False
    
    # Set up for axes in this figure:
    plotaxes = plotfigure.new_plotaxes()
    plotaxes.title = 'Surface'
    plotaxes.scaled = True
    plotaxes.xlimits = [amrdata.xlower,amrdata.xupper]
    plotaxes.ylimits = [amrdata.ylower,amrdata.yupper]
    plotaxes.afteraxes = contour_afteraxes
    
    # Surface
    add_surface_elevation(plotaxes,plot_type='contour')
    
    # Land
    add_land(plotaxes,plot_type='contour')
    
    # ========================================================================
    #  Contour plot for speed
    # ========================================================================
    plotfigure = plotdata.new_plotfigure(name='contour_speed',figno=16)
    plotfigure.show = False
    
    # Set up for axes in this figure:
    plotaxes = plotfigure.new_plotaxes()
    plotaxes.title = 'Current'
    plotaxes.scaled = True
    plotaxes.xlimits = [amrdata.xlower,amrdata.xupper]
    plotaxes.ylimits = [amrdata.ylower,amrdata.yupper]
    plotaxes.afteraxes = contour_afteraxes
    
    # Surface
    add_surface_elevation(plotaxes,plot_type="contour")
    
    # Land
    add_land(plotaxes,plot_type='contour')
    
    # ========================================================================
    #  Vorticity Plot
    # ========================================================================
    plotfigure = plotdata.new_plotfigure(name='vorticity',figno=17)
    plotfigure.show = False
    plotaxes = plotfigure.new_plotaxes()
    plotaxes.title = "Vorticity"
    plotaxes.scaled = True
    plotaxes.xlimits = [amrdata.xlower,amrdata.xupper]
    plotaxes.ylimits = [amrdata.ylower,amrdata.yupper]
    plotaxes.afteraxes = pcolor_afteraxes
    
    # Vorticity
    add_vorticity(plotaxes)

    # Land
    add_land(plotaxes)
    
    
    # ========================================================================
    #  Figures for gauges
    # ========================================================================
    plotfigure = plotdata.new_plotfigure(name='Surface & topo', figno=300, \
                    type='each_gauge')
    plotfigure.show = False
    plotfigure.clf_each_gauge = True

    # Set up for axes in this figure:
    plotaxes = plotfigure.new_plotaxes()
    plotaxes.xlimits = [0.0,40.0*3600.0]
    # plotaxes.ylimits = [0,150.0]
    plotaxes.ylimits = [-3.0, 3.0]
    plotaxes.title = 'Surface'
    plotaxes.afteraxes = gauge_afteraxes

    # Plot surface as blue curve:
    plotitem = plotaxes.new_plotitem(plot_type='1d_plot')
    plotitem.plot_var = 3
    plotitem.plotstyle = 'r-'

    # # Plot topo as green curve:
    # plotitem = plotaxes.new_plotitem(plot_type='1d_plot')
    # plotitem.plot_var = gaugetopo
    # plotitem.plotstyle = 'g+'

    #-----------------------------------------
    
    # Parameters used only when creating html and/or latex hardcopy
    # e.g., via pyclaw.plotters.frametools.printframes:

    plotdata.printfigs = True                # print figures
    plotdata.print_format = 'png'            # file format
    plotdata.print_framenos = 'all'          # list of frames to print
    plotdata.print_fignos = 'all'            # list of figures to print
    plotdata.html = True                    # create html files of plots?
    plotdata.latex = False                   # create latex file of plots?
    plotdata.latex_figsperline = 2           # layout of plots
    plotdata.latex_framesperline = 1         # layout of plots
    plotdata.latex_makepdf = False           # also run pdflatex?

    return plotdata
コード例 #16
0
ファイル: topotools_new.py プロジェクト: ahmadia/geoclaw
def read_dtopo(fname, topotype=1):
    header = read_header(fname)
    if (len(header['header_lines']) == 0) and (abs(topotype)>1):
        raise ValueError("*** topotype = %s but no header found" % topotype)
    if (len(header['header_lines']) > 0) and (abs(topotype)==1):
        raise ValueError("*** topotype = %s but header found" % topotype)
    header_length = header['header_lines'].count('\n')
    
    if topotype==1:
        d = np.loadtxt(fname, skiprows=header_length)
        ncol = d.shape[1]
        if ncol == 3:
            tcol = None
            xcol = d[:,0]
            ycol = d[:,1]
            dzcol = d[:,2]
        else:
            tcol = d[:,0]
            xcol = d[:,1]
            ycol = d[:,2]
            dzcol = d[:,3]
        xdiff = np.diff(xcol)
        inddiff = pylab.find(xdiff<0)
        mx = inddiff[0]+1
        mt = 1
        if tcol is not None:
            # check if there is more than one time in this file:
            tdiff = np.diff(tcol)
            inddiff = pylab.find(tdiff>0)
            if len(inddiff) > 0:
                mt = len(inddiff)+1
        my = len(xcol)/(mx*mt)
        if my != int(len(xcol)/float(mx*mt)):
            print "*** found mx = %s, mt = %s" % (mx,mt)
            raise ValueError("*** mx*mt does not divide length of data")
        print "Found mt = %s times with mx = %s, my = %s" % (mt,mx,my)
        if tcol is None:
            t = []
        else:
            t = tcol[0::mx*my]

        X = np.reshape(xcol[:mx*my],(my,mx))
        Y = np.reshape(ycol[:mx*my],(my,mx))
        dZ = np.reshape(dzcol,(mt,my,mx))

    elif topotype==3:
        try:
            my = header['nrows']
            mx = header['ncols']
            mt = header['mtimes']
            xll = header['xll']
            yll = header['yll']
            t0 = header['t0']
            dx = header['dx']
            dy = header['dy']
            dt = header['dt']
        except:
            raise ValueError("*** Missing information from header")
        if (dt==0) or (mt==1):
            t = np.array([t0])
        else:
            t = np.arange(t0,t0+mt*dt,dt)
        x = np.linspace(xll,xll + mx*dx, mx)
        y = np.linspace(yll,yll + my*dy, my)
        X,Y = np.meshgrid(x,y)
        X = X.T
        Y = Y.T

        fdata = np.loadtxt(fname, skiprows=header_length)
        dzcol = np.reshape(fdata,(mx*my*mt, 1))
        dZ = np.empty((mt,mx,my))
        for i in range(mt):
            dzi = np.reshape(dzcol[i*mx*my:(i+1)*mx*my], (my,mx))
            dzi = np.flipud(dzi)
            dZ[i,:,:] = dzi.T

    else:
        raise ValueError("*** Cannot read topotype = " % topotype)

    dtopo = Data()
    dtopo.t = t
    dtopo.X = X
    dtopo.Y = Y
    dtopo.dZ = dZ
    return dtopo