Ejemplo n.º 1
0
def test(mfault):

    from clawpack.clawutil.data import ClawData

    probdata = ClawData()
    probdata.read('setprob.data',force=True)

    fault = dtopotools.Fault(coordinate_specification='top_center')
    fault.read('fault.data')

    mapping = Mapping(fault)

    domain_depth = probdata.domain_depth
    domain_width = probdata.domain_width
    # num of cells here determined in a similar fashion to that in setrun.py
    dx = mapping.fault_width/mfault
    num_cells_above = numpy.rint(mapping.fault_depth/dx)
    dy = mapping.fault_depth/num_cells_above
    mx = int(numpy.ceil(domain_width/dx)) # mx
    my = int(numpy.ceil(domain_depth/dy)) # my
    mr = mx - mfault

    x = linspace(mapping.xcenter-0.5*mapping.fault_width - numpy.floor(mr/2.0)*dx, mapping.xcenter+0.5*mapping.fault_width + numpy.ceil(mr/2.0)*dx, mx+1)
    y = linspace(-my*dy, 0.0, my+1)
    xc,yc = meshgrid(x,y)
    xp,yp = mapping.mapc2p(xc,yc)
    figure()
    plot(xp,yp,'k-')
    plot(xp.T,yp.T,'k-')
    plot((mapping.xp1,mapping.xp2),(mapping.yp1,mapping.yp2),'-g')
    axis('scaled')
Ejemplo n.º 2
0
def test(mfault):

    from clawpack.clawutil.data import ClawData

    length_scale = 1.e-3 # m to km
    probdata = ClawData()
    probdata.read('setprob.data',force=True)

    fault = dtopotools.Fault()
    fault.read('fault.data')

    mapping = Mapping(fault)

    domain_depth = probdata.domain_depth
    domain_width = probdata.domain_width

    # num of cells here determined in a similar fashion to that in setrun.py
    dx = mapping.fault_width/mfault
    num_cells_above = numpy.rint(mapping.fault_depth/dx)
    dy = mapping.fault_depth/num_cells_above
    mx = int(numpy.ceil(domain_width/dx)) # mx
    my = int(numpy.ceil(domain_depth/dy)) # my
    mr = mx - mfault

    x = linspace(mapping.xcenter-0.5*mapping.fault_width - numpy.floor(mr/2.0)*dx, mapping.xcenter+0.5*mapping.fault_width + numpy.ceil(mr/2.0)*dx, mx+1)
    y = linspace(-my*dy, 0.0, my+1)
    xc,yc = meshgrid(x,y)
    xp,yp = mapping.mapc2p(xc,yc)
    figure()
    plot(xp*length_scale,yp*length_scale,'k-')
    plot(xp.T*length_scale,yp.T*length_scale,'k-')
    plot((mapping.xp1*length_scale,mapping.xp2*length_scale),
            (mapping.yp1*length_scale,mapping.yp2*length_scale),'-g',linewidth=3)
    axis('scaled')
Ejemplo n.º 3
0

from pylab import *
from clawpack.visclaw.data import ClawPlotData
from clawpack.clawutil.data import ClawData

comparison_data_dir = '../../all_data/2_Hilo_2011_Field/comparison_data/'

geodata = ClawData()
geodata.read('geoclaw.data', force=True)
sea_level = geodata.sea_level
print "GeoClaw simulation at sea_level = %g relative to MHW" % sea_level


plotdata = ClawPlotData()

plotdata.outdir = '_output'
#toffset = 7. # hours
toffset = 6.6 # hours fits data at 7760 better

figure(3333, figsize=(12,5))
clf()

# ---  Specified control point ---

CP = loadtxt('../se.dat')
CP_t = CP[:,0] / 60.  # hours since EQ
CP_eta = CP[:,1] + 0.13 + sea_level # adjust to match geoclaw run

g3333 = plotdata.getgauge(3333)
t = g3333.t / 3600. + 7.
Ejemplo n.º 4
0
def setplot(plotdata):
#--------------------------

    """
    Specify what is to be plotted at each frame.
    Input:  plotdata, an instance of clawpack.visclaw.data.ClawPlotData.
    Output: a modified version of plotdata.

    """
    slice_number = 1 # set to surface slice number
    os.chdir(plotdata.outdir)
    for filename in os.listdir('.'):
        if (filename.startswith('slice_%d' % slice_number)):
            shutil.copyfile(filename,filename.replace('slice_%d' % slice_number,'fort',1))

    os.chdir('..')

    fault = dtopotools.Fault()
    fault.read('fault.data')

    mapping = Mapping(fault)

    xp1 = mapping.xp1
    xp2 = mapping.xp2
    zp1 = mapping.zp1
    zp2 = mapping.zp2
    xcenter = mapping.xcenter
    ycenter = mapping.ycenter

    probdata = ClawData()
    probdata.read('setprob.data',force=True)
    probdata.read(plotdata.outdir + '/setprob.data',force=True)
    xlimits = [xcenter-0.5*probdata.domain_width,xcenter+0.5*probdata.domain_width]
    ylimits = [ycenter-0.5*probdata.domain_length,ycenter+0.5*probdata.domain_length]

    from clawpack.visclaw import colormaps

    xc = np.linspace(-150e3,200e3,350)
    yc = np.linspace(-87.5e3,87.5e3,175)
    fault.create_dtopography(xc/LAT2METER,yc/LAT2METER.e3,[1.0])

    okada_max = np.max(fault.dtopo.dZ[0,:,:])
    clevels = np.linspace(-okada_max,okada_max,10)

    plotdata.clearfigures()  # clear any old figures,axes,items data
    plotdata.format = 'binary'

    def plot_okada_contour(current_data):
        from pylab  import gca

        kwargs = {'levels':clevels,'colors':'g'}
        ax = gca()
        fault.plot_okada_contour(axes=ax,kwargs=kwargs)

    def plot_okada(current_data):
        from pylab import gca

        kwargs = {'cmap':colormaps.blue_white_red,'vmin':clevels[0],'vmax':clevels[-1]}
        ax = gca()
        fault.plot_okada(axes=ax,dim=2,kwargs=kwargs)
        kwargs = {'levels':clevels,'colors':'g','linewidths':3}
        fault.plot_okada_contour(axes=ax,kwargs=kwargs)

    # Figure for vertical displacement
    plotfigure = plotdata.new_plotfigure(name='trace', figno=1)
    plotfigure.kwargs = {'figsize':(10,8)}

    # Set axes for numerical solution:
    plotaxes = plotfigure.new_plotaxes()
    plotaxes.axescmd = 'subplot(211)'
    plotaxes.xlimits = xlimits
    plotaxes.ylimits = ylimits
    plotaxes.title = 'Numerical solution'
    plotaxes.scaled = True
    plotaxes.afteraxes = plot_okada_contour

    # Set up for item on these axes:
    plotitem = plotaxes.new_plotitem(plot_type='2d_pcolor')
    plotitem.plot_var = 9
    plotitem.pcolor_cmap = colormaps.blue_white_red
    plotitem.pcolor_cmin = clevels[0]
    plotitem.pcolor_cmax = clevels[-1]
    plotitem.add_colorbar = False
    plotitem.amr_celledges_show = [0]
    plotitem.amr_patchedges_show = [0]

    # Set up for item on these axes:
    plotitem = plotaxes.new_plotitem(plot_type='2d_contour')
    plotitem.plot_var = 9
    plotitem.contour_colors = 'k'
    plotitem.contour_levels = clevels
    plotitem.kwargs = {'linewidths':3}
    plotitem.amr_contour_show = [0,0,0,1]
    plotitem.amr_celledges_show = [0]
    plotitem.amr_patchedges_show = [0]

    # Set axes for Okada solution:
    plotaxes = plotfigure.new_plotaxes()
    plotaxes.axescmd = 'subplot(212)'
    plotaxes.xlimits = xlimits
    plotaxes.ylimits = ylimits
    plotaxes.title_with_t = False
    plotaxes.title = 'Okada solution'
    plotaxes.scaled = True
    plotaxes.afteraxes = plot_okada

    # Figure for grid cells
    plotfigure = plotdata.new_plotfigure(name='cells', figno=2)

    # Set up for axes in this figure:
    plotaxes = plotfigure.new_plotaxes()
    plotaxes.xlimits = xlimits
    plotaxes.ylimits = ylimits
    plotaxes.title = 'Level 4 grid patches'
    plotaxes.scaled = True

    # Set up for item on these axes:
    plotitem = plotaxes.new_plotitem(plot_type='2d_patch')
    plotitem.amr_patch_bgcolor = ['#ffeeee', '#eeeeff', '#eeffee', '#ffffff']
    plotitem.amr_celledges_show = [0]
    plotitem.amr_patchedges_show = [0,0,0,1]

    # Parameters used only when creating html and/or latex hardcopy
    # e.g., via clawpack.visclaw.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.html_homelink = '../README.html'   # pointer for top of index
    plotdata.latex = True                    # 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?
#    plotdata.parallel = True

    return plotdata
Ejemplo n.º 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 clawpack.clawutil.data import ClawData
setprob_data = ClawData()
setprob_data.add_attribute('gamma')
setprob_data.read('setprob.data')
gamma = setprob_data.gamma

def pressure(current_data):
    q = current_data.q
    rho = q[0,:,:]
    u = q[1,:,:] / rho
    v = q[2,:,:] / rho
    E = q[3,:,:]
    p = (gamma - 1.) * (E - 0.5*rho*(u**2 + v**2))
    return p


#--------------------------
def setplot(plotdata):
#--------------------------
    
    """ 
    Specify what is to be plotted at each frame.
Ejemplo n.º 6
0
def setplot(plotdata):
#--------------------------

    """
    Specify what is to be plotted at each frame.
    Input:  plotdata, an instance of clawpack.visclaw.data.ClawPlotData.
    Output: a modified version of plotdata.

    """
    fault = dtopotools.Fault()
    fault.read(plotdata.outdir + '/fault.data')

    mapping = Mapping(fault)
    fault_width = mapping.fault_width
    xcenter = mapping.xcenter
    ycenter = mapping.ycenter
    xp1 = mapping.xp1
    xp2 = mapping.xp2
    yp1 = mapping.yp1
    yp2 = mapping.yp2

    probdata = ClawData()
    probdata.read('setprob.data',force=True)
    xlimits = [xcenter-0.5*probdata.domain_width,xcenter+0.5*probdata.domain_width]
    ylimits = [-probdata.domain_depth,0.0]

    from clawpack.visclaw import colormaps

    plotdata.clearfigures()  # clear any old figures,axes,items data
    plotdata.format = 'binary'

    gaugedata = ClawData()
    gaugedata.read('gauges.data',force=True)
    ngauges = gaugedata.ngauges
    xc = np.zeros(ngauges)
    for j in range(ngauges):
        g = plotdata.getgauge(j)
        xc[j] = g.location[0]
    fault.create_dtopography(xc/LAT2METER,np.array([0.]),[1.0],y_disp=True)

    def plot_vertical_displacement(current_data):
        from pylab import plot,zeros,gca
        t = current_data.t

        ys = zeros(ngauges)
        for gaugeno in range(ngauges):
            g = plotdata.getgauge(gaugeno)
            for k in range(1,len(g.t)):
                if g.t[k] > t:
                    break
                dt = g.t[k] - g.t[k-1]
                v = 0.5*(g.q[4,k]+g.q[4,k-1])
                ys[gaugeno] += dt*v
        ax = gca()
        kwargs ={'linestyle':'-','color':'blue','label':'numerical'}
        plot(xc[:ngauges],ys,**kwargs)
        kwargs = {'linestyle':'--','color':'r','label':'Okada'}
        fault.plot_okada(ax,displacement='vertical',kwargs=kwargs)

    def plot_interfaces(current_data):
        from pylab import plot,zeros,gca,tick_params
        t = current_data.t

        ys = zeros(ngauges)
        for gaugeno in range(ngauges):
            g = plotdata.getgauge(gaugeno)
            for k in range(1,len(g.t)):
                if g.t[k] > t:
                    break
                dt = g.t[k] - g.t[k-1]
                v = 0.5*(g.q[4,k]+g.q[4,k-1])
                ys[gaugeno] += dt*v
        ax = gca()
        plot(xc[:ngauges],ys,linewidth=3)
        kwargs = {'linestyle':'--','color':'r','linewidth':3}
        fault.plot_okada(ax,displacement='vertical',kwargs=kwargs)
        tick_params(labelsize=20)


    def plot_fault(current_data):
        from pylab import linspace, plot
        xl = linspace(xp1,xp2,100)
        yl = linspace(yp1,yp2,100)
        plot(xl,yl,'k')

    def sigmatr(current_data):
        # return -trace(sigma)
        q = current_data.q
        return -(q[0,:,:] + q[1,:,:])

    # Figure for surfaces and p-waves
    plotfigure = plotdata.new_plotfigure(name='surface_and_p_waves', figno=1)
    plotfigure.kwargs = {'figsize':(8,8)}

    # Set axes for vertical displacement:
    plotaxes = plotfigure.new_plotaxes()
    plotaxes.axescmd = 'subplot(211)'
    plotaxes.xlimits = xlimits
    plotaxes.ylimits = [-0.3, 0.5]
    plotaxes.title = 'vertical displacement'
    plotaxes.scaled = False
    plotaxes.afteraxes = plot_vertical_displacement

    # Set axes for p waves:
    plotaxes = plotfigure.new_plotaxes()
    plotaxes.axescmd = 'subplot(212)'
    plotaxes.xlimits = xlimits
    plotaxes.ylimits = ylimits
    plotaxes.title = '-trace(sigma)'
    plotaxes.scaled = True
    plotaxes.afteraxes = plot_fault

    # Set up for item on these axes:
    plotitem = plotaxes.new_plotitem(plot_type='2d_pcolor')
    plotitem.plot_var = sigmatr
    plotitem.pcolor_cmap = colormaps.blue_white_red
    plotitem.pcolor_cmin = -1e6
    plotitem.pcolor_cmax = 1e6
    plotitem.add_colorbar = False
    plotitem.amr_celledges_show = [0]
    plotitem.amr_patchedges_show = [0]
    plotitem.MappedGrid = True
    plotitem.mapc2p = mapping.mapc2p



    # Figure for grid cells
    plotfigure = plotdata.new_plotfigure(name='cells', figno=2)

    # Set up for axes in this figure:
    plotaxes = plotfigure.new_plotaxes()
    plotaxes.xlimits = xlimits
    plotaxes.ylimits = ylimits
    plotaxes.title = 'Level 4 grid patches'
    plotaxes.scaled = True

    # Set up for item on these axes:
    plotitem = plotaxes.new_plotitem(plot_type='2d_patch')
    plotitem.amr_patch_bgcolor = ['#ffeeee', '#effeee', '#eeffee', '#eeeffe',
                                  '#eeeeff', '#ffffff']
    plotitem.amr_celledges_show = [0]
    plotitem.amr_patchedges_show = [0,0,0,0,0,1]
    plotitem.MappedGrid = True
    plotitem.mapc2p = mapping.mapc2p

    # Parameters used only when creating html and/or latex hardcopy
    # e.g., via clawpack.visclaw.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.html_homelink = '../README.html'   # pointer for top of index
    plotdata.latex = True                    # 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?
    plotdata.parallel = True

    return plotdata
Ejemplo n.º 7
0
def plot_topo_file(topoplotdata):
    """
    Read in a topo or bathy file and produce a pcolor map.
    """

    deprecation_msg = "This function is being deprecated in favor of the " + \
                      "Topography class in clawpack.geoclaw.topotools and " + \
                      "plotting tools associated with it."
    warnings.filterwarnings('default', category=DeprecationWarning)
    warnings.warn(deprecation_msg, DeprecationWarning, stacklevel=2)
    warnings.resetwarnings()

    import os
    import pylab
    from clawpack.clawutil.data import ClawData

    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
    cmap = topoplotdata.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 cmap is None:
        cmap = colormaps.make_colormap({-1:[0.3,0.2,0.1],
                                           -0.00001:[0.95,0.9,0.7],
                                           0.00001:[.5,.7,0],
                                           1:[.2,.5,.2]})
        #cmap = colormaps.make_colormap({-1:[0,0,1],0:[1,1,1],1:[1,0,0]})

    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)
            #pylab.clim([cmin,cmax])
            if addcolorbar:
                pylab.colorbar()
    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')

    patchedges_show = True
    if patchedges_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 = ClawData()
    topodata.x = x
    topodata.y = y
    topodata.topo = topo

    return topodata
Ejemplo n.º 8
0
def runclaw(xclawcmd=None, outdir=None, overwrite=True, restart=None, 
            rundir=None, print_git_status=False, nohup=False, nice=None,
            xclawout=None, xclawerr=None, verbose=True):
    """
    Run the Fortran version of Clawpack using executable xclawcmd, which is
    typically set to 'xclaw', 'xamr', etc.

    If it is not set by the call, get it from the environment variable
    CLAW_EXE.  Default to 'xclaw' if that's not set.

    If overwrite is True, it's ok to zap current contents of the outdir.
    If overwrite is False, move the outdir (or copy in the case of a restart)
    to a backup directory with a unique name based on time executed.

    If restart is None, determine whether this is a restart from claw.data
    (as set in setrun.py).  Can remove setting RESTART in Makefiles.
    
    If rundir is None, all *.data is copied from current directory, if a path 
    is given, data files are copied from there instead.

    If print_git_status is True, print a summary of the git status of all
    clawpack repositories in the file claw_git_status.txt in outdir.

    If nohup is True, run the xclawcmd in nohup mode:  runs in background and
    output goes into nohup.out file in the directory specified by outdir,
    rather than all output going to the screen.  The job keeps running if user 
    logs off.  Useful for scripts starting long jobs in batch mode.

    If type(nice) is int, runs the code using "nice -n "
    with this nice value so it doesn't hog computer resources.
    
    xclawout and xclawerr define the locations of stdout and stderr for the 
    execution of CLAW_EXE. They should be strings to filepaths or open file
    objects or ``subprocess.PIPE`` or ``subprocess.STDOUT``. To pass both
    to the same file, specify ``xclawout`` as the filepath and 
    ``xclawerr=subprocess.STDOUT``.

    """
    
    if nice is not None:
        try:
            nice = int(nice)
        except:
            nice = None

    # convert strings passed in from Makefile to boolean:
    if type(overwrite) is str:
        overwrite = (overwrite.lower() in ['true','t'])
    if type(restart) is str:
        if restart == 'None':
            restart = None
        else:
            restart = (restart.lower() in ['true','t'])
    if type(print_git_status) is str:
        print_git_status = (print_git_status.lower() in ['true','t'])
    if type(nohup) is str:
        nohup = (nohup.lower() in ['true','t'])
    

    if xclawcmd is None:
        # Determine what executable to use from environment variable CLAW_EXE
        # Default to 'xclaw' if it's not set:
        xclawcmd = os.environ.get('CLAW_EXE', 'xclaw')
    

    if outdir is None:
        outdir = '.'

    if rundir is None:
        rundir = os.getcwd()
    rundir = os.path.abspath(rundir)
    print("==> runclaw: Will take data from ", rundir)

    # directory for fort.* files:
    outdir = os.path.abspath(outdir)
    print('==> runclaw: Will write output to ',outdir)
    
    if restart is None:
        # Added option to determine restart from claw.data (i.e. setrun.py)
        clawdata = ClawData()
        clawdata.read(os.path.join(rundir,'claw.data'), force=True) 
        restart = clawdata.restart
        
    xclawcmd = os.path.abspath(xclawcmd)

    if os.path.isfile(outdir):
        print("==> runclaw: Error: outdir specified is a file")
        return

    if (os.path.isdir(outdir) & (not overwrite)):
        # copy the old outdir before possibly overwriting
        tm = time.localtime(os.path.getmtime(outdir))
        year = str(tm[0]).zfill(4)
        month = str(tm[1]).zfill(2)
        day = str(tm[2]).zfill(2)
        hour = str(tm[3]).zfill(2)
        minute = str(tm[4]).zfill(2)
        second = str(tm[5]).zfill(2)
        outdir_backup = outdir + '_%s-%s-%s-%s%s%s' \
              % (year,month,day,hour,minute,second)
        if verbose:
            print("==> runclaw: Directory already exists: ",os.path.split(outdir)[1])
            if restart:
                print("==> runclaw: Copying directory to:      ",os.path.split(outdir_backup)[1])
            else:
                print("==> runclaw: Moving directory to:      ",os.path.split(outdir_backup)[1])
            time.sleep(1)

        try:
            shutil.move(outdir,outdir_backup)
            if restart:
                shutil.copytree(outdir_backup,outdir)
        except:
            print("==> runclaw: Could not move directory... copy already exists?")

    if six.PY2:
        if (not os.path.isdir(outdir)):
            try:
                os.mkdir(outdir)
            except:
                print("Cannot make directory ",outdir)
                return
    else:
        os.makedirs(outdir, exist_ok=True)

    if print_git_status not in [False,'False']:
        # create files claw_git_status.txt and claw_git_diffs.txt in
        # outdir:
        make_git_status_file(outdir=outdir)

    # old fort.* files to be removed for new run?
    fortfiles = glob.glob(os.path.join(outdir,'fort.*'))
    # also need to remove gauge*.txt output files now that the gauge
    # output is no longer in fort.gauge  (but don't remove new gauges.data)
    gaugefiles = glob.glob(os.path.join(outdir,'gauge*.txt'))

    if (overwrite and (not restart)):
        # remove any old versions:
        if verbose:
            print("==> runclaw: Removing all old fort/gauge files in ", outdir)
        for file in fortfiles + gaugefiles:
            os.remove(file)
    elif restart:
        if verbose:
            print("==> runclaw: Restart: leaving original fort/gauge files in ", outdir)
    else:
        # this should never be reached: 
        # if overwrite==False then outdir has already been moved
        if len(fortfiles+gaugefiles) > 1:
            print("==> runclaw: *** Remove fort.* and gauge*.txt")
            print("  from output directory %s and try again," % outdir)
            print("  or use overwrite=True in call to runclaw")
            print("  e.g., by setting OVERWRITE = True in Makefile")
            return

    datafiles = glob.glob(os.path.join(rundir,'*.data'))
    if datafiles == ():
        print("==> runclaw: Warning: no data files found in directory ",rundir)
    else:
        if rundir != outdir:
            for file in datafiles:
                shutil.copy(file, os.path.join(outdir,os.path.basename(file)))

    b4run = None
    if os.path.isfile('b4run.py'):
        b4run_file = os.path.abspath('b4run.py')
    else:
        b4run_file = os.environ.get('B4RUN', '')

    if os.path.isfile(b4run_file):
        try:
            file_globals = runpy.run_path(b4run_file)
            b4run = file_globals.get('b4run', None)
        except:
            w = r"*** WARNING: problem running b4run_file = %s" % b4run_file
            warnings.warn(w, UserWarning)
            b4run = None
        
    if b4run is not None:
        try:
            b4run(rundir, outdir)
            print('Executed b4run function from %s' % b4run_file)
        except:
            w = r"*** WARNING: problem executing b4run from %s" % b4run_file
            warnings.warn(w, UserWarning)

    # execute command to run fortran program:
    if nohup:
        # run in nohup mode:
        print("\n==> Running in nohup mode, output will be sent to:")
        print("      %s/nohup.out" % outdir)
        if type(nice) is int:
            cmd = "nohup time nice -n %s %s " % (nice,xclawcmd)
        else:
            cmd = "nohup time %s " % xclawcmd
        print("\n==> Running with command:\n   ", cmd)
    else:
        if type(nice) is int:
            cmd = "nice -n %s %s " % (nice,xclawcmd)
        else:
            cmd = xclawcmd
        print("\n==> Running with command:\n   ", cmd)

    cmd_split = shlex.split(cmd)
    if isinstance(xclawout, str):
        xclawout = open(xclawout,'w', encoding='utf-8',
                        buffering=1)
    if isinstance(xclawerr, str):
        xclawerr = open(xclawerr,'w', encoding='utf-8',
                        buffering=1)
    try:
        proc = subprocess.check_call(cmd_split,
                                     cwd=outdir,
                                     stdout=xclawout,
                                     stderr=xclawerr)

    except subprocess.CalledProcessError as cpe:
        exe_error_str = "\n\n*** FORTRAN EXE FAILED ***\n"
        raise ClawExeError(exe_error_str, cpe.returncode, cpe.cmd,
                           output=cpe.output, 
                           stderr=cpe.stderr)
    
    print('==> runclaw: Done executing %s via clawutil.runclaw.py' %\
                xclawcmd)
    print('==> runclaw: Output is in ', outdir)

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

    """

    fault = dtopotools.Fault()
    fault.read(plotdata.outdir + '/fault.data')
    gdata = ClawData()
    gdata.read(plotdata.outdir + '/gauges.data', force=True)
    ngauges = gdata.ngauges
    xc = np.zeros(ngauges)
    for j in range(ngauges):
        g = plotdata.getgauge(j)
        xc[j] = g.location[0]

    fault.create_dtopography(xc / LAT2METER,
                             np.array([0.]), [1.0],
                             y_disp=True)

    from clawpack.visclaw import colormaps

    plotdata.clearfigures()  # clear any old figures,axes,items data
    plotdata.format = 'binary'

    def plot_vertical_displacement(current_data):
        from pylab import plot, zeros, xlabel, ylabel, tick_params
        t = current_data.t

        ys = zeros(ngauges)
        for gaugeno in range(ngauges):
            g = plotdata.getgauge(gaugeno)
            for k in range(1, len(g.t)):
                if g.t[k] > t:
                    break
                dt = g.t[k] - g.t[k - 1]
                v = 0.5 * (g.q[4, k] + g.q[4, k - 1])
                ys[gaugeno] += dt * v
        plot(xc[:ngauges] * length_scale, ys, linewidth=3)
        plot(xc * length_scale,
             fault.dtopo.dZ[0, 0, :],
             linestyle='--',
             color='r',
             linewidth=3)
        tick_params(labelsize=25)
        xlabel('kilometers', fontsize=25)
        ylabel('meters', fontsize=25)

    def plot_horizontal_displacement(current_data):
        from pylab import plot, zeros, xlabel, ylabel, tick_params
        t = current_data.t

        xs = zeros(ngauges)
        for gaugeno in range(ngauges):
            g = plotdata.getgauge(gaugeno)
            for k in range(1, len(g.t)):
                if g.t[k] > t:
                    break
                dt = g.t[k] - g.t[k - 1]
                u = 0.5 * (g.q[3, k] + g.q[3, k - 1])
                xs[gaugeno] += dt * u

        plot(xc[:ngauges] * length_scale, xs, linewidth=3)
        plot(xc * length_scale,
             fault.dtopo.dY[0, 0, :],
             linestyle='--',
             color='r',
             linewidth=3)
        tick_params(labelsize=25)
        xlabel('kilometers', fontsize=25)
        ylabel('meters', fontsize=25)

    # Figure for vertical displacement
    plotfigure = plotdata.new_plotfigure(name='vertical', figno=1)
    plotfigure.kwargs = {'figsize': (11, 8)}

    # Set up for axes in this figure:
    plotaxes = plotfigure.new_plotaxes()
    plotaxes.xlimits = xlimits
    plotaxes.ylimits = ylimits
    plotaxes.title_with_t = False
    plotaxes.title = ''
    plotaxes.scaled = False
    plotaxes.afteraxes = plot_vertical_displacement

    # Figure for horizontal displacement
    plotfigure = plotdata.new_plotfigure(name='horizontal', figno=2)
    plotfigure.kwargs = {'figsize': (11, 8)}

    # Set up for axes in this figure:
    plotaxes = plotfigure.new_plotaxes()
    plotaxes.xlimits = xlimits
    plotaxes.ylimits = ylimits
    plotaxes.title_with_t = False
    plotaxes.title = ''
    plotaxes.scaled = False
    plotaxes.afteraxes = plot_horizontal_displacement

    # Parameters used only when creating html and/or latex hardcopy
    # e.g., via clawpack.visclaw.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.html_homelink = '../README.html'  # pointer for top of index
    plotdata.latex = True  # 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?
    plotdata.parallel = True

    return plotdata
def write_nc_output(fname_nc,
                    fgm,
                    new=False,
                    force=False,
                    outdir='Unknown',
                    verbose=True):

    import netCDF4
    import time
    import os
    from clawpack.clawutil.data import ClawData

    fv = -9999.  # fill_value for netcdf4

    if new:
        # first create a new .nc file with X,Y,fgmax_point,force_dry_init:
        result = make_nc_input(fname_nc, fgm, force=force, verbose=verbose)
        if result == -1:
            print('*** make_nc_input failed, not appending output')
            return

    if outdir is 'Unknown':
        # Cannot determine tfinal or run_finished time
        tfinal = fv
        run_finished = 'Unknown'
    else:
        claw = ClawData()
        claw.read(outdir + '/claw.data', force=True)
        tfinal = claw.tfinal

        try:
            mtime = os.path.getmtime(outdir + '/timing.txt')
            run_finished = time.ctime(mtime)
        except:
            run_finished = 'Unknown'

    # add fgmax output results to existing file
    with netCDF4.Dataset(fname_nc, 'a') as rootgrp:
        if verbose:
            print('Appending data from fgm to nc file', fname_nc)
            print('        nc file description: ', rootgrp.description)
            print('        fgm.id: ', fgm.id)

        h = rootgrp.variables.get('h', None)
        if (h is not None) and (not force):
            print('*** netCDF file already contains output,\n'\
                + '*** NOT overwriting '\
                + '--- use force==True to overwrite' )
            return

        x = numpy.array(rootgrp.variables['lon'])
        y = numpy.array(rootgrp.variables['lat'])
        X, Y = numpy.meshgrid(x, y)
        Z = numpy.array(rootgrp.variables['Z'])
        fgmax_point = numpy.array(rootgrp.variables['fgmax_point'])
        bounding_box = [x.min(), x.max(), y.min(), y.max()]

        dx = x[1] - x[0]
        Xclose = numpy.allclose(fgm.X, X, atol=0.1 * dx)
        Yclose = numpy.allclose(fgm.Y, Y, atol=0.1 * dx)

        if (fgm.X.shape != X.shape):
            # for now raise an exception, might want to extent to allow
            # filling only part of input arrays
            print('*** Mismatch of fgm with data in nc file:')
            print('fgm.X.shape = ', fgm.X.shape)
            print('nc  X.shape = ', X.shape)
            print('fgm.bounding_box = ', fgm.bounding_box())
            print('nc  bounding_box = ', bounding_box)
            raise ValueError('*** Mismatch of fgm with data in nc file')

        Xclose = numpy.allclose(fgm.X, X, atol=0.1 * dx)
        Yclose = numpy.allclose(fgm.Y, Y, atol=0.1 * dx)
        if (not (Xclose and Yclose)):
            raise ValueError(
                '*** Mismatch of fgm.X or fgm.Y with data in nc file')

        rootgrp.history += "Added output " + time.ctime(time.time())
        rootgrp.history += " in %s;  " % os.getcwd()

        rootgrp.tfinal = tfinal
        rootgrp.outdir = os.path.abspath(outdir)
        rootgrp.run_finished = run_finished

        fgmax_point = rootgrp.variables.get('fgmax_point', None)

        if fgm.dz is not None:
            try:
                dz = rootgrp.variables['dz']
            except:
                dz = rootgrp.createVariable('dz',
                                            'f4', (
                                                'lat',
                                                'lon',
                                            ),
                                            fill_value=fv)
            dz[:, :] = fgm.dz
            dz.units = 'meters'
            if verbose: print('    Adding fgm.dz to nc file')
        else:
            if verbose: print('fgm.dz is None, not adding')

        if fgm.B is not None:
            try:
                B = rootgrp.variables['B']
            except:
                B = rootgrp.createVariable('B',
                                           'f4', (
                                               'lat',
                                               'lon',
                                           ),
                                           fill_value=fv)
            B[:, :] = fgm.B
            B.units = 'meters'
            if verbose: print('    Adding fgm.B to nc file')
        else:
            if verbose: print('fgm.B is None, not adding')

        if fgm.h is not None:
            try:
                h = rootgrp.variables['h']
            except:
                h = rootgrp.createVariable('h',
                                           'f4', (
                                               'lat',
                                               'lon',
                                           ),
                                           fill_value=fv)
            h[:, :] = fgm.h
            h.units = 'meters'
            if verbose: print('    Adding fgm.h to nc file')
        else:
            if verbose: print('fgm.h is None, not adding')

        if fgm.s is not None:
            try:
                s = rootgrp.variables['s']
            except:
                s = rootgrp.createVariable('s',
                                           'f4', (
                                               'lat',
                                               'lon',
                                           ),
                                           fill_value=fv)
            s[:, :] = fgm.s
            s.units = 'meters/second'
            if verbose: print('    Adding fgm.s to nc file')
        else:
            if verbose: print('fgm.s is None, not adding')

        if fgm.hss is not None:
            try:
                hss = rootgrp.variables['hss']
            except:
                hss = rootgrp.createVariable('hss',
                                             'f4', (
                                                 'lat',
                                                 'lon',
                                             ),
                                             fill_value=fv)
            hss[:, :] = fgm.hss
            hss.units = 'meters^3/sec^2'
            if verbose: print('    Adding fgm.hss to nc file')
        else:
            if verbose: print('fgm.hss is None, not adding')

        if fgm.hmin is not None:
            try:
                hmin = rootgrp.variables['hmin']
            except:
                hmin = rootgrp.createVariable('hmin',
                                              'f4', (
                                                  'lat',
                                                  'lon',
                                              ),
                                              fill_value=fv)
            # negate hmin so that it is minimum flow depth min(h):
            hmin[:, :] = -fgm.hmin
            hmin.units = 'meters'
            if verbose: print('    Adding fgm.hmin to nc file')
        else:
            if verbose: print('fgm.hmin is None, not adding')

        if fgm.arrival_time is not None:
            try:
                arrival_time = rootgrp.variables['arrival_time']
            except:
                arrival_time = rootgrp.createVariable('arrival_time',
                                                      'f4', (
                                                          'lat',
                                                          'lon',
                                                      ),
                                                      fill_value=fv)
            arrival_time[:, :] = fgm.arrival_time
            arrival_time.units = 'seconds'
            if verbose: print('    Adding fgm.arrival_time to nc file')
        else:
            if verbose: print('fgm.arrival_time is None, not adding')

        print('Created %s' % fname_nc)
        if verbose:
            print('History:  ', rootgrp.history)
            print('\nMetadata:')
            print('  outdir:  ', rootgrp.outdir)
            print('  run_finished:  ', rootgrp.run_finished)
            print('  tfinal:  ', rootgrp.tfinal)
Ejemplo n.º 11
0
    def get_frame(self, frameno):

        if frameno in self.solutions:
            # 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 = ClawData()
        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 = ClawData()
        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((solution.ncols, grid.my, grid.mx), 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
Ejemplo n.º 12
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 pylab import *

from clawpack.clawutil.data import ClawData

setprob_data = ClawData()
setprob_data.read('setprob.data', force=True)


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

    from clawpack.visclaw.colormaps import yellow_red_blue as yrb

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

    def compute_approx_Rsoln(current_data):
Ejemplo n.º 13
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 pylab import *

from clawpack.clawutil.data import ClawData
setprob_data = ClawData()
setprob_data.read('setprob.data', force=True)

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

    from clawpack.visclaw.colormaps import yellow_red_blue as yrb

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

    def compute_approx_Rsoln(current_data):
Ejemplo n.º 14
0
def setplot(plotdata):
#--------------------------

    """
    Specify what is to be plotted at each frame.
    Input:  plotdata, an instance of clawpack.visclaw.data.ClawPlotData.
    Output: a modified version of plotdata.

    """
    slice_number = 3
    os.chdir(plotdata.outdir)
    for filename in os.listdir('.'):
        if (filename.startswith('slice_%d' % slice_number)):
            shutil.copyfile(filename,filename.replace('slice_%d' % slice_number,'fort',1))

    os.chdir('..')

    fault = dtopotools.Fault()
    fault.read('fault.data')

    mapping = Mapping(fault)

    xp1 = mapping.xp1
    xp2 = mapping.xp2
    zp1 = mapping.zp1
    zp2 = mapping.zp2
    xcenter = mapping.xcenter
    ycenter = mapping.ycenter

    probdata = ClawData()
    probdata.read('setprob.data',force=True)
    probdata.read(plotdata.outdir + '/setprob.data',force=True)
    xlimits = [xcenter-0.5*probdata.domain_width,xcenter+0.5*probdata.domain_width]
    ylimits = [ycenter-0.5*probdata.domain_length,ycenter+0.5*probdata.domain_length]
    zlimits = [-probdata.domain_depth,0.0]

    def plot_fault_xz(current_data):
        from pylab import linspace, plot
        xl = linspace(xp1,xp2,100)
        zl = linspace(zp1,zp2,100)
        plot(xl,zl,'k')

    if (slice_number is 1):
        x1limits = xlimits
        x2limits = ylimits
        mapc2p = mapping.mapc2p_xy
        plot_fault = None
    elif (slice_number is 2):
        x1limits = ylimits
        x2limits = zlimits
        mapping.set_slice_xval(0.0)
        mapc2p = mapping.mapc2p_yz
        plot_fault = None
    elif (slice_number is 3):
        x1limits = xlimits
        x2limits = zlimits
        mapc2p = mapping.mapc2p_xz
        plot_fault = plot_fault_xz

    from clawpack.visclaw import colormaps

    plotdata.clearfigures()  # clear any old figures,axes,items data
#    plotdata.format = 'binary'

    def sigmatr(current_data):
        # return -trace(sigma)
        q = current_data.q
        return -(q[0,:,:] + q[1,:,:] + q[2,:,:])

    # Figure for trace(sigma)
    plotfigure = plotdata.new_plotfigure(name='trace', figno=1)
    plotfigure.kwargs = {'figsize':(10,8)}

    # Set up for axes in this figure:
    plotaxes = plotfigure.new_plotaxes()
    plotaxes.axescmd = 'subplot(211)'
    plotaxes.xlimits = x1limits
    plotaxes.ylimits = x2limits
    plotaxes.title = '-trace(sigma)'
    plotaxes.scaled = True
    plotaxes.afteraxes = plot_fault

    # Set up for item on these axes:
    plotitem = plotaxes.new_plotitem(plot_type='2d_pcolor')
    plotitem.plot_var = sigmatr
    plotitem.pcolor_cmap = colormaps.blue_white_red
    plotitem.pcolor_cmin = -1e6
    plotitem.pcolor_cmax = 1e6
    plotitem.add_colorbar = False
    plotitem.amr_celledges_show = [0]
    plotitem.amr_patchedges_show = [0]
    plotitem.MappedGrid = True
    plotitem.mapc2p = mapc2p

    # Set up for axes in this figure:
    plotaxes = plotfigure.new_plotaxes()
    plotaxes.axescmd = 'subplot(212)'
    plotaxes.xlimits = x1limits
    plotaxes.ylimits = x2limits
    plotaxes.title = 'x-velocity'
    plotaxes.scaled = True
    plotaxes.afteraxes = plot_fault
    
    # Set up for item on these axes:
    plotitem = plotaxes.new_plotitem(plot_type='2d_pcolor')
    plotitem.plot_var = 6
    plotitem.pcolor_cmap = colormaps.blue_white_red
    plotitem.pcolor_cmin = -1e-1
    plotitem.pcolor_cmax = 1e-1
    plotitem.add_colorbar = False
    plotitem.amr_celledges_show = [0]
    plotitem.amr_patchedges_show = [0]
    plotitem.MappedGrid = True
    plotitem.mapc2p = mapc2p

    # Figure for grid cells
    plotfigure = plotdata.new_plotfigure(name='cells', figno=2)

    # Set up for axes in this figure:
    plotaxes = plotfigure.new_plotaxes()
    plotaxes.xlimits = x1limits
    plotaxes.ylimits = x2limits
    plotaxes.title = 'Level 4 grid patches'
    plotaxes.scaled = True

    # Set up for item on these axes:
    plotitem = plotaxes.new_plotitem(plot_type='2d_patch')
    plotitem.amr_patch_bgcolor = ['#ffeeee', '#eeeeff', '#eeffee', '#ffffff']
    plotitem.amr_celledges_show = [0]
    plotitem.amr_patchedges_show = [0,0,0,1]
    plotitem.MappedGrid = True
    plotitem.mapc2p = mapc2p

    # Parameters used only when creating html and/or latex hardcopy
    # e.g., via clawpack.visclaw.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.html_homelink = '../README.html'   # pointer for top of index
    plotdata.latex = True                    # 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?
#    plotdata.parallel = True

    return plotdata
Ejemplo n.º 15
0
def setplot(plotdata):
    #--------------------------
    """
    Specify what is to be plotted at each frame.
    Input:  plotdata, an instance of clawpack.visclaw.data.ClawPlotData.
    Output: a modified version of plotdata.

    """
    slice_number = 3
    os.chdir(plotdata.outdir)
    for filename in os.listdir('.'):
        if (filename.startswith('slice_%d' % slice_number)):
            shutil.copyfile(
                filename, filename.replace('slice_%d' % slice_number, 'fort',
                                           1))

    os.chdir('..')

    fault = dtopotools.Fault()
    fault.read('fault.data')

    mapping = Mapping(fault)

    xp1 = mapping.xp1
    xp2 = mapping.xp2
    zp1 = mapping.zp1
    zp2 = mapping.zp2
    xcenter = mapping.xcenter
    ycenter = mapping.ycenter

    probdata = ClawData()
    probdata.read('setprob.data', force=True)
    probdata.read(plotdata.outdir + '/setprob.data', force=True)
    xlimits = [
        xcenter - 0.5 * probdata.domain_width,
        xcenter + 0.5 * probdata.domain_width
    ]
    ylimits = [
        ycenter - 0.5 * probdata.domain_length,
        ycenter + 0.5 * probdata.domain_length
    ]
    zlimits = [-probdata.domain_depth, 0.0]

    def plot_fault_xz(current_data):
        from pylab import linspace, plot
        xl = linspace(xp1, xp2, 100)
        zl = linspace(zp1, zp2, 100)
        plot(xl, zl, 'k')

    if (slice_number is 1):
        x1limits = xlimits
        x2limits = ylimits
        mapc2p = mapping.mapc2p_xy
        plot_fault = None
    elif (slice_number is 2):
        x1limits = ylimits
        x2limits = zlimits
        mapping.set_slice_xval(0.0)
        mapc2p = mapping.mapc2p_yz
        plot_fault = None
    elif (slice_number is 3):
        x1limits = xlimits
        x2limits = zlimits
        mapc2p = mapping.mapc2p_xz
        plot_fault = plot_fault_xz

    from clawpack.visclaw import colormaps

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

    #    plotdata.format = 'binary'

    def sigmatr(current_data):
        # return -trace(sigma)
        q = current_data.q
        return -(q[0, :, :] + q[1, :, :] + q[2, :, :])

    # Figure for trace(sigma)
    plotfigure = plotdata.new_plotfigure(name='trace', figno=1)
    plotfigure.kwargs = {'figsize': (10, 8)}

    # Set up for axes in this figure:
    plotaxes = plotfigure.new_plotaxes()
    plotaxes.axescmd = 'subplot(211)'
    plotaxes.xlimits = x1limits
    plotaxes.ylimits = x2limits
    plotaxes.title = '-trace(sigma)'
    plotaxes.scaled = True
    plotaxes.afteraxes = plot_fault

    # Set up for item on these axes:
    plotitem = plotaxes.new_plotitem(plot_type='2d_pcolor')
    plotitem.plot_var = sigmatr
    plotitem.pcolor_cmap = colormaps.blue_white_red
    plotitem.pcolor_cmin = -1e6
    plotitem.pcolor_cmax = 1e6
    plotitem.add_colorbar = False
    plotitem.amr_celledges_show = [0]
    plotitem.amr_patchedges_show = [0]
    plotitem.MappedGrid = True
    plotitem.mapc2p = mapc2p

    # Set up for axes in this figure:
    plotaxes = plotfigure.new_plotaxes()
    plotaxes.axescmd = 'subplot(212)'
    plotaxes.xlimits = x1limits
    plotaxes.ylimits = x2limits
    plotaxes.title = 'x-velocity'
    plotaxes.scaled = True
    plotaxes.afteraxes = plot_fault

    # Set up for item on these axes:
    plotitem = plotaxes.new_plotitem(plot_type='2d_pcolor')
    plotitem.plot_var = 6
    plotitem.pcolor_cmap = colormaps.blue_white_red
    plotitem.pcolor_cmin = -1e-1
    plotitem.pcolor_cmax = 1e-1
    plotitem.add_colorbar = False
    plotitem.amr_celledges_show = [0]
    plotitem.amr_patchedges_show = [0]
    plotitem.MappedGrid = True
    plotitem.mapc2p = mapc2p

    # Figure for grid cells
    plotfigure = plotdata.new_plotfigure(name='cells', figno=2)

    # Set up for axes in this figure:
    plotaxes = plotfigure.new_plotaxes()
    plotaxes.xlimits = x1limits
    plotaxes.ylimits = x2limits
    plotaxes.title = 'Level 4 grid patches'
    plotaxes.scaled = True

    # Set up for item on these axes:
    plotitem = plotaxes.new_plotitem(plot_type='2d_patch')
    plotitem.amr_patch_bgcolor = ['#ffeeee', '#eeeeff', '#eeffee', '#ffffff']
    plotitem.amr_celledges_show = [0]
    plotitem.amr_patchedges_show = [0, 0, 0, 1]
    plotitem.MappedGrid = True
    plotitem.mapc2p = mapc2p

    # Parameters used only when creating html and/or latex hardcopy
    # e.g., via clawpack.visclaw.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.html_homelink = '../README.html'  # pointer for top of index
    plotdata.latex = True  # 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?
    #    plotdata.parallel = True

    return plotdata
Ejemplo n.º 16
0
print "Read qxt and qa"

if any(abs(T-Ta)>1e-12) or any(abs(X-Xa)>1e-12):
    raise Exception("*** X and Xa or T and Ta do not match")

tmax = T.max()

# Time region where solution is of interest
# Set t1 = t2 = tmax if only the final time, 
#     t1 = 0, t2 = tmax if the [x1,x2] region is of interest for all time
t1 = 3800.0
t2 = 4200.0

# Read region where adjoint functional is nonzero
# Used to plot box below.
adjoint_setprobdata = ClawData()
adjoint_setprobdata.read('adjoint/setprob.data', force=True)
x1 = adjoint_setprobdata.x1
x2 = adjoint_setprobdata.x2

figure(1,(10,8))
clf()
axes([0.08,0.09,0.42,0.83])
etanorm = abs(qxt[:,0,:])
contourf(X,T,etanorm,[.01,1.0],colors=['r'])

q_innerprod = qxt[:,0,:] * qa[:,0,:] + qxt[:,1,:]*qa[:,1,:]

t = T[:,0]
num_t = len(t)
# Shift adjoint solution in time downwards between t1 and t2 and
Ejemplo n.º 17
0
def setplot(plotdata):
    #--------------------------
    """
    Specify what is to be plotted at each frame.
    Input:  plotdata, an instance of clawpack.visclaw.data.ClawPlotData.
    Output: a modified version of plotdata.

    """
    slice_number = 1  # set to surface slice number
    os.chdir(plotdata.outdir)
    for filename in os.listdir('.'):
        if (filename.startswith('slice_%d' % slice_number)):
            shutil.copyfile(
                filename, filename.replace('slice_%d' % slice_number, 'fort',
                                           1))

    os.chdir('..')

    fault = dtopotools.Fault()
    fault.read('fault.data')

    mapping = Mapping(fault)

    xp1 = mapping.xp1
    xp2 = mapping.xp2
    zp1 = mapping.zp1
    zp2 = mapping.zp2
    xcenter = mapping.xcenter
    ycenter = mapping.ycenter

    probdata = ClawData()
    probdata.read('setprob.data', force=True)
    probdata.read(plotdata.outdir + '/setprob.data', force=True)
    xlimits = [
        xcenter - 0.5 * probdata.domain_width,
        xcenter + 0.5 * probdata.domain_width
    ]
    ylimits = [
        ycenter - 0.5 * probdata.domain_length,
        ycenter + 0.5 * probdata.domain_length
    ]

    from clawpack.visclaw import colormaps

    xc = np.linspace(-150e3, 200e3, 350)
    yc = np.linspace(-87.5e3, 87.5e3, 175)
    fault.create_dtopography(xc / LAT2METER, yc / LAT2METER.e3, [1.0])

    okada_max = np.max(fault.dtopo.dZ[0, :, :])
    clevels = np.linspace(-okada_max, okada_max, 10)

    plotdata.clearfigures()  # clear any old figures,axes,items data
    plotdata.format = 'binary'

    def plot_okada_contour(current_data):
        from pylab import gca

        kwargs = {'levels': clevels, 'colors': 'g'}
        ax = gca()
        fault.plot_okada_contour(axes=ax, kwargs=kwargs)

    def plot_okada(current_data):
        from pylab import gca

        kwargs = {
            'cmap': colormaps.blue_white_red,
            'vmin': clevels[0],
            'vmax': clevels[-1]
        }
        ax = gca()
        fault.plot_okada(axes=ax, dim=2, kwargs=kwargs)
        kwargs = {'levels': clevels, 'colors': 'g', 'linewidths': 3}
        fault.plot_okada_contour(axes=ax, kwargs=kwargs)

    # Figure for vertical displacement
    plotfigure = plotdata.new_plotfigure(name='trace', figno=1)
    plotfigure.kwargs = {'figsize': (10, 8)}

    # Set axes for numerical solution:
    plotaxes = plotfigure.new_plotaxes()
    plotaxes.axescmd = 'subplot(211)'
    plotaxes.xlimits = xlimits
    plotaxes.ylimits = ylimits
    plotaxes.title = 'Numerical solution'
    plotaxes.scaled = True
    plotaxes.afteraxes = plot_okada_contour

    # Set up for item on these axes:
    plotitem = plotaxes.new_plotitem(plot_type='2d_pcolor')
    plotitem.plot_var = 9
    plotitem.pcolor_cmap = colormaps.blue_white_red
    plotitem.pcolor_cmin = clevels[0]
    plotitem.pcolor_cmax = clevels[-1]
    plotitem.add_colorbar = False
    plotitem.amr_celledges_show = [0]
    plotitem.amr_patchedges_show = [0]

    # Set up for item on these axes:
    plotitem = plotaxes.new_plotitem(plot_type='2d_contour')
    plotitem.plot_var = 9
    plotitem.contour_colors = 'k'
    plotitem.contour_levels = clevels
    plotitem.kwargs = {'linewidths': 3}
    plotitem.amr_contour_show = [0, 0, 0, 1]
    plotitem.amr_celledges_show = [0]
    plotitem.amr_patchedges_show = [0]

    # Set axes for Okada solution:
    plotaxes = plotfigure.new_plotaxes()
    plotaxes.axescmd = 'subplot(212)'
    plotaxes.xlimits = xlimits
    plotaxes.ylimits = ylimits
    plotaxes.title_with_t = False
    plotaxes.title = 'Okada solution'
    plotaxes.scaled = True
    plotaxes.afteraxes = plot_okada

    # Figure for grid cells
    plotfigure = plotdata.new_plotfigure(name='cells', figno=2)

    # Set up for axes in this figure:
    plotaxes = plotfigure.new_plotaxes()
    plotaxes.xlimits = xlimits
    plotaxes.ylimits = ylimits
    plotaxes.title = 'Level 4 grid patches'
    plotaxes.scaled = True

    # Set up for item on these axes:
    plotitem = plotaxes.new_plotitem(plot_type='2d_patch')
    plotitem.amr_patch_bgcolor = ['#ffeeee', '#eeeeff', '#eeffee', '#ffffff']
    plotitem.amr_celledges_show = [0]
    plotitem.amr_patchedges_show = [0, 0, 0, 1]

    # Parameters used only when creating html and/or latex hardcopy
    # e.g., via clawpack.visclaw.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.html_homelink = '../README.html'  # pointer for top of index
    plotdata.latex = True  # 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?
    #    plotdata.parallel = True

    return plotdata
Ejemplo n.º 18
0
def setplot(plotdata):
#--------------------------

    """
    Specify what is to be plotted at each frame.
    Input:  plotdata, an instance of clawpack.visclaw.data.ClawPlotData.
    Output: a modified version of plotdata.

    """

    fault = dtopotools.Fault()
    fault.read(plotdata.outdir + '/fault.data')

    mapping = Mapping(fault)

    xp1 = mapping.xp1*length_scale
    xp2 = mapping.xp2*length_scale
    yp1 = mapping.yp1*length_scale
    yp2 = mapping.yp2*length_scale

    gaugedata = ClawData()
    gaugedata.read(plotdata.outdir + '/gauges.data', force=True)
    ngauges = gaugedata.ngauges
    xc = np.zeros(ngauges)
    for j in range(ngauges):
        g = plotdata.getgauge(j)
        xc[j] = g.location[0]
    fault.create_dtopography(xc/LAT2METER,np.array([0.]),[1.0],y_disp=True)


    from clawpack.visclaw import colormaps

    plotdata.clearfigures()  # clear any old figures,axes,items data
    plotdata.format = 'binary'

    def mapc2p(xc,yc):
        xp,yp = mapping.mapc2p(xc,yc)
        return xp*length_scale,yp*length_scale

    def plot_fault(current_data):
        from pylab import linspace, plot, xlabel, ylabel, tick_params
        xl = linspace(xp1,xp2,100)
        yl = linspace(yp1,yp2,100)
        plot(xl,yl,'k',linewidth=3)
        tick_params(labelsize=25)
        xlabel('kilometers',fontsize=25)
        ylabel('kilometers',fontsize=25)

    def sigmatr(current_data):
        # return -trace(sigma)
        q = current_data.q
        return -(q[0,:,:] + q[1,:,:])

    def plot_vertical_displacement(current_data):
        from pylab import plot,zeros,ylabel,tick_params
        t = current_data.t

        ys = zeros(ngauges)
        for gaugeno in range(ngauges):
            g = plotdata.getgauge(gaugeno)
            for k in range(1,len(g.t)):
                if g.t[k] > t:
                    break
                dt = g.t[k] - g.t[k-1]
                v = 0.5*(g.q[4,k]+g.q[4,k-1])
                ys[gaugeno] += dt*v
        plot(xc[:ngauges]*length_scale,ys,linewidth=3)
        plot(xc*length_scale,fault.dtopo.dZ[0,0,:],linestyle='--',color='r',linewidth=3)
        tick_params(labelsize=25)
        ylabel('meters',fontsize=25)

    # Figure for surface
    plotfigure = plotdata.new_plotfigure(name='surface', figno=1)
    plotfigure.kwargs = {'figsize':(11,4)}

    # Set up for axes in this figure:
    plotaxes = plotfigure.new_plotaxes()
    plotaxes.xlimits = xlimits
    plotaxes.ylimits = ylimits_surface
    plotaxes.title_with_t = False
    plotaxes.title = ''
    plotaxes.scaled = False
    plotaxes.afteraxes = plot_vertical_displacement

    # Figure for fault
    plotfigure = plotdata.new_plotfigure(name='fault', figno=2)
    plotfigure.kwargs = {'figsize':(11,6)}

    # Set up for axes in this figure:
    plotaxes = plotfigure.new_plotaxes()
    plotaxes.xlimits = xlimits
    plotaxes.ylimits = ylimits_fault
    plotaxes.title = ''
    plotaxes.title_with_t = False
    plotaxes.scaled = True
    plotaxes.afteraxes = plot_fault

    # Set up for item on these axes:
    plotitem = plotaxes.new_plotitem(plot_type='2d_pcolor')
    plotitem.plot_var = sigmatr
    plotitem.pcolor_cmap = colormaps.blue_white_red
    plotitem.pcolor_cmin = -1e6
    plotitem.pcolor_cmax = 1e6
    plotitem.add_colorbar = False
    plotitem.amr_celledges_show = [0]
    plotitem.amr_patchedges_show = [0]
    plotitem.MappedGrid = True
    plotitem.mapc2p = mapc2p

    # Parameters used only when creating html and/or latex hardcopy
    # e.g., via clawpack.visclaw.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.html_homelink = '../README.html'   # pointer for top of index
    plotdata.latex = True                    # 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?
    plotdata.parallel = True

    return plotdata
Ejemplo n.º 19
0
def setplot(plotdata):
    # --------------------------

    """ 
    Specify what is to be plotted at each frame.
    Input:  plotdata, an instance of clawpack.visclaw.data.ClawPlotData.
    Output: a modified version of plotdata.
    
    """
    from clawpack.visclaw import colormaps

    plotdata.outdir = "./_output"
    plotdata.clearfigures()  # clear any old figures,axes,items data

    #   copy slice files to fort files
    if slice_type == 1:
        prefix = "slice_xy1"
    elif slice_type == 2:
        prefix = "slice_xz1"
    elif slice_type == 3:
        prefix = "slice_yz1"

    os.chdir(plotdata.outdir)
    for filename in os.listdir("."):
        if filename.startswith(prefix):
            shutil.copyfile(filename, filename.replace(prefix, "fort", 1))
    os.chdir("..")

    probdata = ClawData()
    probdata.read("setprob.data", force=True)
    griddata = ClawData()
    griddata.read("claw.data", force=True)

    # Plot outline of interface
    def interface(current_data):
        from pylab import linspace, plot, xlabel, ylabel
        from numpy import cos, sin, ones

        if slice_type == 1:
            y = linspace(griddata.lower[1], griddata.upper[1], 1000)
        elif slice_type == 2:
            y = linspace(griddata.lower[2], griddata.upper[2], 1000)
        if slice_type in [1, 2]:
            x1 = probdata.pipe_inner_radius * ones((1000, 1))
            x2 = probdata.pipe_outer_radius * ones((1000, 1))
            plot(x1, y, "g", linewidth=2.0)
            plot(x2, y, "g", linewidth=2.0)

        if slice_type == 1:
            xlabel("x")
            ylabel("y")
        elif slice_type == 2:
            xlabel("x")
            ylabel("z")
        elif slice_type == 3:
            xlabel("y")
            ylabel("z")

    # Outputs the trace of the stress tensor
    def sigmatr(current_data):
        q = current_data.q
        return -(q[0, :, :] + q[1, :, :] + q[2, :, :]) / 3.0

    # Figure for stress trace - pcolor
    plotfigure = plotdata.new_plotfigure(name="Minus stress trace", figno=1)
    # plotfigure.show = False

    # Set up for axes in this figure:
    plotaxes = plotfigure.new_plotaxes()
    plotaxes.xlimits = "auto"  # [-0.02,0.04] #'auto'
    plotaxes.ylimits = "auto"  # [-0.00,0.1]
    plotaxes.title = "Stress trace"
    plotaxes.afteraxes = "pylab.axis('scaled')"
    plotaxes.scaled = True  # so aspect ratio is 1
    plotaxes.afteraxes = interface

    # Set up for item on these axes:
    plotitem = plotaxes.new_plotitem(plot_type="2d_pcolor")
    plotitem.show = True
    plotitem.plot_var = sigmatr
    plotitem.pcolor_cmap = colormaps.blue_white_red
    plotitem.pcolor_cmin = -9e-6
    plotitem.pcolor_cmax = 9e-6
    plotitem.add_colorbar = True
    # plotitem.amr_patchedges_show = [1]
    # plotitem.amr_celledges_show = [0]
    if slice_type == 1:
        plotitem.MappedGrid = True
        plotitem.mapc2p = mapc2p
    # Figure for stress trace - pcolor
    plotfigure = plotdata.new_plotfigure(name="Minus stress trace (scale)", figno=2)
    plotfigure.show = False

    # Set up for axes in this figure:
    plotaxes = plotfigure.new_plotaxes()
    plotaxes.xlimits = "auto"  # [-0.02,0.04] #'auto'
    plotaxes.ylimits = "auto"  # [-0.00,0.1]
    plotaxes.title = "Stress trace"
    plotaxes.afteraxes = "pylab.axis('scaled')"
    plotaxes.scaled = True  # so aspect ratio is 1
    plotaxes.afteraxes = interface

    # Set up for item on these axes:
    plotitem = plotaxes.new_plotitem(plot_type="2d_pcolor")
    plotitem.show = True
    plotitem.plot_var = sigmatr
    plotitem.pcolor_cmap = colormaps.blue_white_red
    plotitem.pcolor_cmin = -3e-7
    plotitem.pcolor_cmax = 3e-7
    plotitem.add_colorbar = True
    # plotitem.amr_patchedges_show = [1]
    # plotitem.amr_celledges_show = [0]
    if slice_type == 1:
        plotitem.MappedGrid = True
        plotitem.mapc2p = mapc2p

    ## Figure for grid cells
    plotfigure = plotdata.new_plotfigure(name="cells", figno=3)
    # plotfigure.show = False

    # Set up for axes in this figure:
    plotaxes = plotfigure.new_plotaxes()
    plotaxes.title = "Grid patches"
    plotaxes.scaled = True
    plotaxes.afteraxes = interface
    plotaxes.xlimits = "auto"  # [.06,.09]
    plotaxes.ylimits = "auto"  # [0.0,0.1]

    # Set up for item on these axes:
    plotitem = plotaxes.new_plotitem(plot_type="2d_patch")
    # plotitem.amr_patch_bgcolor = ['#ffeeee', '#eeeeff', '#eeffee']
    plotitem.amr_celledges_show = [1, 1]
    plotitem.amr_patchedges_show = [1]
    if slice_type == 1:
        plotitem.MappedGrid = True
        plotitem.mapc2p = mapc2p

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

    plotdata.printfigs = True  # print figures
    plotdata.print_format = "png"  # file format
    plotdata.print_framenos = "all"  # range(37)          # list of frames to print
    plotdata.print_fignos = "all"  # list of figures to print
    plotdata.html = True  # create html files of plots?
    plotdata.html_homelink = "../README.html"  # pointer for top of index
    plotdata.html_movie = "JSAnimation"  # new style, or "4.x" for old style
    plotdata.latex = True  # 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
Ejemplo n.º 20
0
def setplot(plotdata):
#--------------------------

    """
    Specify what is to be plotted at each frame.
    Input:  plotdata, an instance of clawpack.visclaw.data.ClawPlotData.
    Output: a modified version of plotdata.

    """

    fault = dtopotools.Fault()
    fault.read(plotdata.outdir + '/fault.data')

    mapping = Mapping(fault)
    fault_width = mapping.fault_width
    xcenter = mapping.xcenter
    ycenter = mapping.ycenter
    xp1 = mapping.xp1
    xp2 = mapping.xp2
    yp1 = mapping.yp1
    yp2 = mapping.yp2

    probdata = ClawData()
    probdata.read('setprob.data',force=True)
    xlimits = [xcenter-0.5*probdata.domain_width,xcenter+0.5*probdata.domain_width]
    ylimits = [-probdata.domain_depth,0.0]

    from clawpack.visclaw import colormaps

    plotdata.clearfigures()  # clear any old figures,axes,items data
    plotdata.format = 'binary'

    def plot_fault(current_data):
        from pylab import linspace, plot
        xl = linspace(xp1,xp2,100)
        yl = linspace(yp1,yp2,100)
        plot(xl,yl,'k')

    def sigmatr(current_data):
        # return -trace(sigma)
        q = current_data.q
        return -(q[0,:,:] + q[1,:,:])

    def slip_direction_vel(current_data):
        # return vel dot tau, where tau is tangent to fault
        tau_x = (xp2 - xp1)/fault_width
        tau_y = (yp2 - yp1)/fault_width
        tau_x = np.where(current_data.y > ycenter, -tau_x, tau_x)
        tau_y = np.where(current_data.y > ycenter, -tau_y, tau_y)
        u = current_data.q[3,:,:]
        v = current_data.q[4,:,:]
        return u*tau_x + v*tau_y

    # Figure for waves
    plotfigure = plotdata.new_plotfigure(name='waves', figno=1)
    plotfigure.kwargs = {'figsize':(10,8)}

    # Set up axes for trace(sigma):
    plotaxes = plotfigure.new_plotaxes()
    plotaxes.axescmd = 'subplot(211)'
    plotaxes.xlimits = xlimits
    plotaxes.ylimits = ylimits
    plotaxes.title = '-trace(sigma)'
    plotaxes.scaled = True
    plotaxes.afteraxes = plot_fault

    # Set up for item on these axes:
    plotitem = plotaxes.new_plotitem(plot_type='2d_pcolor')
    plotitem.plot_var = sigmatr
    plotitem.pcolor_cmap = colormaps.blue_white_red
    plotitem.pcolor_cmin = -1e6
    plotitem.pcolor_cmax = 1e6
    plotitem.add_colorbar = False
    plotitem.amr_celledges_show = [0]
    plotitem.amr_patchedges_show = [0]
    plotitem.MappedGrid = True
    plotitem.mapc2p = mapping.mapc2p

    # Set up axes for slip_direction_velocity:
    plotaxes = plotfigure.new_plotaxes()
    plotaxes.axescmd = 'subplot(212)'
    plotaxes.xlimits = xlimits
    plotaxes.ylimits = ylimits
    plotaxes.title = 'slip-direction-velocity'
    plotaxes.scaled = True
    plotaxes.afteraxes = plot_fault

    # Set up for item on these axes:
    plotitem = plotaxes.new_plotitem(plot_type='2d_pcolor')
    plotitem.plot_var = slip_direction_vel
    plotitem.pcolor_cmap = colormaps.blue_white_red
    plotitem.pcolor_cmin = -0.1
    plotitem.pcolor_cmax = 0.1
    plotitem.add_colorbar = False
    plotitem.amr_celledges_show = [0]
    plotitem.amr_patchedges_show = [0]
    plotitem.MappedGrid = True
    plotitem.mapc2p = mapping.mapc2p

    # Figure for grid cells
    plotfigure = plotdata.new_plotfigure(name='cells', figno=2)

    # Set up for axes in this figure:
    plotaxes = plotfigure.new_plotaxes()
    plotaxes.xlimits = xlimits
    plotaxes.ylimits = ylimits
    plotaxes.title = 'Level 6 grid patches'
    plotaxes.scaled = True

    # Set up for item on these axes:
    plotitem = plotaxes.new_plotitem(plot_type='2d_patch')
    plotitem.amr_patch_bgcolor = ['#ffeeee', '#effeee', '#eeffee', '#eeeffe',
                                  '#eeeeff', '#ffffff']
    plotitem.amr_celledges_show = [0]
    plotitem.amr_patchedges_show = [0,0,0,0,0,1]
    plotitem.MappedGrid = True
    plotitem.mapc2p = mapping.mapc2p

    # Parameters used only when creating html and/or latex hardcopy
    # e.g., via clawpack.visclaw.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.html_homelink = '../README.html'   # pointer for top of index
    plotdata.latex = True                    # 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?
#    plotdata.parallel = True

    return plotdata
Ejemplo n.º 21
0
    def get_frame(self, frameno):

        if frameno in self.solutions:
            # 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 = ClawData()
        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 = ClawData()
        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((solution.ncols,grid.my,grid.mx), 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
Ejemplo n.º 22
0
def plot_topo_file(topoplotdata):
    """
    Read in a topo or bathy file and produce a pcolor map.
    """

    deprecation_msg = "This function is being deprecated in favor of the " + \
                      "Topography class in clawpack.geoclaw.topotools and " + \
                      "plotting tools associated with it."
    warnings.filterwarnings('default', category=DeprecationWarning)
    warnings.warn(deprecation_msg, DeprecationWarning, stacklevel=2)
    warnings.resetwarnings()

    import os
    import pylab
    from clawpack.clawutil.data import ClawData

    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
    cmap = topoplotdata.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 cmap is None:
        cmap = colormaps.make_colormap({
            -1: [0.3, 0.2, 0.1],
            -0.00001: [0.95, 0.9, 0.7],
            0.00001: [.5, .7, 0],
            1: [.2, .5, .2]
        })
        #cmap = colormaps.make_colormap({-1:[0,0,1],0:[1,1,1],1:[1,0,0]})

    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)
        #pylab.clim([cmin,cmax])
        if addcolorbar:
            pylab.colorbar()
    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')

    patchedges_show = True
    if patchedges_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 = ClawData()
    topodata.x = x
    topodata.y = y
    topodata.topo = topo

    return topodata
Ejemplo n.º 23
0

from pylab import *
from clawpack.visclaw.data import ClawPlotData
from clawpack.clawutil.data import ClawData
from clawpack.geoclaw import topotools

comparison_data_dir = '/Users/rjl/git/tsunami_benchmarks/nthmp_currents_2015/all_data/3_Tauranga_2011_Field/comparison_data/'

geodata = ClawData()
geodata.read('geoclaw.data', force=True)
sea_level = geodata.sea_level
print "GeoClaw simulation at sea_level = %g relative to MHW" % sea_level


plotdata = ClawPlotData()

#plotdata.outdir = '_output_1_3sec'
plotdata.outdir = '_output'
toffset = 0.2

port_data = loadtxt(comparison_data_dir + 'port_data.txt')
tAB = port_data[:,0] - toffset
zAB = port_data[:,1] # tsunami only
tTug = port_data[:,3] - toffset
zTug = port_data[:,4] # tsunami only

figure(1, figsize=(12,5))
clf()

Ejemplo n.º 24
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.

"""

import numpy as np
from mapc2p import mapc2p
from clawpack.clawutil.data import ClawData
cscale = 8  # scale color limits

probdata = ClawData()
probdata.read('setprob.data', force=True)

width = probdata.fault_width
theta = probdata.fault_dip
xcenter = probdata.fault_center
ycenter = -probdata.fault_depth

xp1 = xcenter - 0.5 * width * np.cos(theta)
xp2 = xcenter + 0.5 * width * np.cos(theta)
yp1 = ycenter + 0.5 * width * np.sin(theta)
yp2 = ycenter - 0.5 * width * np.sin(theta)

xlimits = [
    xcenter - 0.5 * probdata.domain_width,
    xcenter + 0.5 * probdata.domain_width
]
ylimits = [-probdata.domain_depth, probdata.water_depth]
Ejemplo n.º 25
0
def runclaw(xclawcmd=None, outdir=None, overwrite=True, restart=None, 
            rundir=None, print_git_status=False, nohup=False, nice=None):
    """
    Run the Fortran version of Clawpack using executable xclawcmd, which is
    typically set to 'xclaw', 'xamr', etc.

    If it is not set by the call, get it from the environment variable
    CLAW_EXE.  Default to 'xclaw' if that's not set.

    If overwrite is True, it's ok to zap current contents of the outdir.
    If overwrite is False, move the outdir (or copy in the case of a restart)
    to a backup directory with a unique name based on time executed.

    If restart is None, determine whether this is a restart from claw.data
    (as set in setrun.py).  Can remove setting RESTART in Makefiles.
    
    If rundir is None, all *.data is copied from current directory, if a path 
    is given, data files are copied from there instead.

    If print_git_status is True, print a summary of the git status of all
    clawpack repositories in the file claw_git_status.txt in outdir.

    If nohup is True, run the xclawcmd in nohup mode:  runs in background and
    output goes into nohup.out file in the directory specified by outdir,
    rather than all output going to the screen.  The job keeps running if user 
    logs off.  Useful for scripts starting long jobs in batch mode.

    If type(nice) is int, runs the code using "nice -n "
    with this nice value so it doesn't hog computer resources.

    """
    
    from clawpack.clawutil.data import ClawData
    import os,glob,shutil,time
    verbose = True
    xclawout = None
    xclawerr = None

    try:
        nice = int(nice)
    except:
        nice = None

    # convert strings passed in from Makefile to boolean:
    if type(overwrite) is str:
        overwrite = (overwrite.lower() in ['true','t'])
    if type(restart) is str:
        if restart == 'None':
            restart = None
        else:
            restart = (restart.lower() in ['true','t'])
    if type(print_git_status) is str:
        print_git_status = (print_git_status.lower() in ['true','t'])
    if type(nohup) is str:
        nohup = (nohup.lower() in ['true','t'])
    

    if xclawcmd is None:
        # Determine what executable to use from environment variable CLAW_EXE
        # Default to 'xclaw' if it's not set:
        xclawcmd = os.environ.get('CLAW_EXE', 'xclaw')
    

    if outdir is None:
        outdir = '.'
        
    if rundir is None:
        rundir = os.getcwd()
    rundir = os.path.abspath(rundir)
    print("==> runclaw: Will take data from ", rundir)

    # directory for fort.* files:
    outdir = os.path.abspath(outdir)
    print('==> runclaw: Will write output to ',outdir)
    
    if restart is None:
        # Added option to determine restart from claw.data (i.e. setrun.py)
        clawdata = ClawData()
        clawdata.read(os.path.join(rundir,'claw.data'), force=True) 
        restart = clawdata.restart
        #print '+++ From claw.data determined restart = %s' % restart

    
    #returncode = clawjob.runxclaw()

    if 1:
        startdir = os.getcwd()
        xdir = os.path.abspath(startdir)
        outdir = os.path.abspath(outdir)
        rundir = os.path.abspath(rundir)
        xclawcmd = os.path.join(xdir,xclawcmd)
        
        try:
            os.chdir(xdir)
        except:
            raise Exception( "==> runclaw: Cannot change to directory xdir = %s" %xdir)
            return 
    
    
        if os.path.isfile(outdir):
            print("==> runclaw: Error: outdir specified is a file")
            return
        
        if (os.path.isdir(outdir) & (not overwrite)):
            # copy the old outdir before possibly overwriting
            tm = time.localtime(os.path.getmtime(outdir))
            year = str(tm[0]).zfill(4)
            month = str(tm[1]).zfill(2)
            day = str(tm[2]).zfill(2)
            hour = str(tm[3]).zfill(2)
            minute = str(tm[4]).zfill(2)
            second = str(tm[5]).zfill(2)
            outdir_backup = outdir + '_%s-%s-%s-%s%s%s' \
                  % (year,month,day,hour,minute,second)
            if verbose:
                print("==> runclaw: Directory already exists: ",os.path.split(outdir)[1])
                if restart:
                    print("==> runclaw: Copying directory to:      ",os.path.split(outdir_backup)[1])
                else:
                    print("==> runclaw: Moving directory to:      ",os.path.split(outdir_backup)[1])
                time.sleep(1)
            
            try:
                shutil.move(outdir,outdir_backup)
                if restart:
                    shutil.copytree(outdir_backup,outdir)
            except:
                print("==> runclaw: Could not move directory... copy already exists?")
            
            
        if (not os.path.isdir(outdir)):
            try:
                os.mkdir(outdir)
            except:
                print("Cannot make directory ",outdir)
                return
    
        try:
            os.chdir(outdir)
        except:
            print('==> runclaw: *** Error in runxclaw: cannot move to outdir = ',\
                  outdir)
            raise
            return
    
        if print_git_status not in [False,'False']:
            make_git_status_file()

        fortfiles = glob.glob(os.path.join(outdir,'fort.*'))
        if (overwrite and (not restart)):
            # remove any old versions:
            if verbose:
                print("==> runclaw: Removing all old fort files in ", outdir)
            for file in fortfiles:
                os.remove(file)
        elif restart:
            if verbose:
                print("==> runclaw: Restart: leaving original fort files in ", outdir)
        else:
            if len(fortfiles) > 1:
                print("==> runclaw: *** Remove fort.* and try again,")
                print("  or use overwrite=True in call to runxclaw")
                print("  e.g., by setting CLAW_OVERWRITE = True in Makefile")
                return
            
        
        try:
            os.chdir(rundir)
        except:
            raise Exception("Cannot change to directory %s" % rundir)
            return 
    
        datafiles = glob.glob('*.data')
        if datafiles == ():
            print("==> runclaw: Warning: no data files found in directory ",rundir)
        else:
            if rundir != outdir:
                for file in datafiles:
                    shutil.copy(file,os.path.join(outdir,file))
    
        if xclawout:
            xclawout = open(xclawout,'wb')
        if xclawerr:
            xclawerr = open(xclawerr,'wb')
    
        os.chdir(outdir)
    
        #print "\nIn directory outdir = ",outdir,"\n"
    
        # execute command to run fortran program:
    
        try:
            #print "\nExecuting ",xclawcmd, "  ...  "
            #pclaw = subprocess.Popen(xclawcmd,stdout=xclawout,stderr=xclawerr)
            #print '+++ pclaw started'
                #pclaw.wait()   # wait for code to run
            #returncode = pclaw.returncode
            #print '+++ pclaw done'
            
            if nohup:
                # run in nohup mode:
                print("\n==> Running in nohup mode, output will be sent to:")
                print("      %s/nohup.out" % outdir)
                if type(nice) is int:
                    cmd = "nohup time nice -n %s %s " % (nice,xclawcmd)
                else:
                    cmd = "nohup time %s " % xclawcmd
                print("\n==> Running with command:\n   ", cmd)
                returncode = os.system(cmd)
            else:
                if type(nice) is int:
                    cmd = "nice -n %s %s " % (nice,xclawcmd)
                else:
                    cmd = xclawcmd
                print("\n==> Running with command:\n   ", cmd)
                returncode = os.system(cmd)
    
            if returncode == 0:
                print("\n==> runclaw: Finished executing\n")
            else:
                print("\n ==> runclaw: *** Runtime error: return code = %s\n "\
                        % returncode)
            print('==> runclaw: Done executing %s via clawutil.runclaw.py' %\
                        xclawcmd)
            print('==> runclaw: Output is in ', outdir)
            
        except:
            raise Exception("Could not execute command %s" % xclawcmd)
    
        os.chdir(startdir)

    if returncode != 0:
        print('==> runclaw: *** fortran returncode = ', returncode, '   aborting')
Ejemplo n.º 26
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.

"""

import numpy as np
from mapc2p import mapc2p
from plot_okada import plot_okada_surface
from clawpack.clawutil.data import ClawData


cscale = 8 # scale color limits

probdata = ClawData()
probdata.read('setprob.data',force=True)

width = probdata.fault_width
theta = probdata.fault_dip
xcenter = probdata.fault_center
ycenter = -probdata.fault_depth

xp1 = xcenter - 0.5*width*np.cos(theta)
xp2 = xcenter + 0.5*width*np.cos(theta)
yp1 = ycenter + 0.5*width*np.sin(theta)
yp2 = ycenter - 0.5*width*np.sin(theta)

xlimits = [xcenter-0.5*probdata.domain_width,xcenter+0.5*probdata.domain_width]
ylimits = [-probdata.domain_depth,probdata.water_depth]
Ejemplo n.º 27
0
print "Read qxt and qa"

if any(abs(T-Ta)>1e-12) or any(abs(X-Xa)>1e-12):
    raise Exception("*** X and Xa or T and Ta do not match")

tmax = T.max()

# Time region where solution is of interest
# Set t1 = t2 = tmax if only the final time, 
#     t1 = 0, t2 = tmax if the [x1,x2] region is of interest for all time
t1 = 18.0
t2 = 20.0

# Read region where adjoint functional is nonzero
# Used to plot box below.
adjoint_setprobdata = ClawData()
adjoint_setprobdata.read('adjoint/setprob.data', force=True)
x1 = adjoint_setprobdata.x1
x2 = adjoint_setprobdata.x2

figure(1,(10,8))
clf()
axes([0.05,0.05,0.42,0.9])
qnorm = abs(qxt[:,0,:]) + abs(qxt[:,1,:])
contourf(X,T,qnorm,[.01,10],colors=['r'])

q_innerprod = qxt[:,0,:] * qa[:,0,:] + qxt[:,1,:]*qa[:,1,:]

t = T[:,0]
num_t = len(t)
# Shift adjoint solution in time downwards between t1 and t2 and