Beispiel #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
Beispiel #2
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
Beispiel #3
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
Beispiel #4
0
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
Beispiel #5
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:
Beispiel #6
0
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
Beispiel #7
0
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
Beispiel #8
0
    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
Beispiel #9
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
Beispiel #10
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