def plotgauge(gaugeno, plotdata, verbose=False): #========================================== """ Plot all requested plots for a single gauge from the computation. The plots are requested by setting attributes of plotdata to ClawPlotFigure objects with plot_type="each_gauge". """ if verbose: gaugesoln = plotdata.getgauge(gaugeno) print ' Plotting gauge %s at x = %g, y = %g ... ' \ % (gaugeno, gaugesoln.x, gaugesoln.y) if plotdata.mode() == 'iplotclaw': pylab.ion() try: plotfigure_dict = plotdata.plotfigure_dict except: print '*** Error in plotgauge: plotdata missing plotfigure_dict' print '*** This should not happen' return None if len(plotfigure_dict) == 0: print '*** Warning in plotgauge: plotdata has empty plotfigure_dict' print '*** Apparently no figures to plot' # initialize current_data containing data that will be passed # to beforegauge, aftergauge, afteraxes commands current_data = Data() current_data.user = Data() # for user specified attributes # to avoid potential conflicts current_data.plotdata = plotdata current_data.gaugeno = gaugeno # call beforegauge if present, which might define additional # attributes in current_data or otherwise set up plotting for this # gauge. beforegauge = getattr(plotdata, 'beforegauge', None) if beforegauge: if isinstance(beforegauge, str): # a string to be executed exec(beforegauge) else: # assume it's a function try: output = beforegauge(current_data) if output: current_data = output except: print '*** Error in beforegauge ***' raise # iterate over each single plot that makes up this gauge: # ------------------------------------------------------- if plotdata._mode == 'iplotclaw': gaugesoln = plotdata.getgauge(gaugeno) #import pdb; pdb.set_trace() print ' Plotting Gauge %s at x = %g, y = %g ... ' \ % (gaugeno, gaugesoln.x, gaugesoln.y) requested_fignos = plotdata.iplotclaw_fignos else: requested_fignos = plotdata.print_fignos plotted_fignos = [] plotdata = set_show(plotdata) # set _show attributes for which figures # and axes should be shown. # loop over figures to appear for this gauge: # ------------------------------------------- for figname in plotdata._fignames: plotfigure = plotdata.plotfigure_dict[figname] if (not plotfigure._show) or (plotfigure.type != 'each_gauge'): continue # skip to next figure figno = plotfigure.figno if requested_fignos != 'all': if figno not in requested_fignos: continue # skip to next figure plotted_fignos.append(figno) if not plotfigure.kwargs.has_key('facecolor'): # use Clawpack's default bg color (tan) plotfigure.kwargs['facecolor'] = '#ffeebb' # create figure and set handle: plotfigure._handle = pylab.figure(num=figno, **plotfigure.kwargs) pylab.ioff() if plotfigure.clf_each_gauge: pylab.clf() try: plotaxes_dict = plotfigure.plotaxes_dict except: print '*** Error in plotgauge: plotdata missing plotaxes_dict' print '*** This should not happen' return None if (len(plotaxes_dict) == 0) or (len(plotfigure._axesnames) == 0): print '*** Warning in plotgauge: plotdata has empty plotaxes_dict' print '*** Apparently no axes to plot in figno ', figno # loop over axes to appear on this figure: # ---------------------------------------- for axesname in plotfigure._axesnames: plotaxes = plotaxes_dict[axesname] if not plotaxes._show: continue # skip this axes if no items show # create the axes: axescmd = getattr(plotaxes, 'axescmd', 'subplot(1,1,1)') axescmd = 'plotaxes._handle = pylab.%s' % axescmd exec(axescmd) pylab.hold(True) # loop over items: # ---------------- for itemname in plotaxes._itemnames: plotitem = plotaxes.plotitem_dict[itemname] try: outdir = plotitem.outdir if outdir is None: outdir = plotdata.outdir gaugesoln = plotdata.getgauge(gaugeno, outdir) except: print '*** Cannot find gauge number ', gaugeno print '*** looking in directory ', outdir print '*** cwd = ', os.getcwd() return None #import pdb; pdb.set_trace() current_data.gaugesoln = gaugesoln current_data.q = gaugesoln.q current_data.t = gaugesoln.t if plotitem._show: try: output = plotgauge1(gaugesoln,plotitem,\ current_data) if output: current_data = output if verbose: print ' Plotted plotitem ', itemname except: print '*** Error in plotgauge: problem calling plotgauge1' traceback.print_exc() return None # end of loop over plotitems for itemname in plotaxes._itemnames: plotitem = plotaxes.plotitem_dict[itemname] if plotitem.afteritem: print "*** ClawPlotItem.afteritem is deprecated" print "*** use ClawPlotAxes.afteraxes " print "*** or ClawPlotItem.aftergrid instead" pylab.title("%s at gauge %s" % (plotaxes.title, gaugeno)) # call an afteraxes function if present: afteraxes = getattr(plotaxes, 'afteraxes', None) if afteraxes: if isinstance(afteraxes, str): # a string to be executed exec(afteraxes) else: # assume it's a function try: current_data.plotaxes = plotaxes current_data.plotfigure = plotaxes._plotfigure output = afteraxes(current_data) if output: current_data = output except: print '*** Error in afteraxes ***' raise if plotaxes.scaled: pylab.axis('scaled') # set axes limits: if (plotaxes.xlimits is not None) & (type(plotaxes.xlimits) is not str): try: pylab.xlim(plotaxes.xlimits[0], plotaxes.xlimits[1]) except: pass # let axis be set automatically if (plotaxes.ylimits is not None) & (type(plotaxes.ylimits) is not str): try: pylab.ylim(plotaxes.ylimits[0], plotaxes.ylimits[1]) except: pass # let axis be set automatically # end of loop over plotaxes # end of loop over plotfigures # call an aftergauge function if present: aftergauge = getattr(plotdata, 'aftergauge', None) if aftergauge: if isinstance(aftergauge, str): # a string to be executed exec(aftergauge) else: # assume it's a function try: output = aftergauge(current_data) if output: current_data = output except: print '*** Error in aftergauge ***' raise if plotdata.mode() == 'iplotclaw': pylab.ion() for figno in plotted_fignos: pylab.figure(figno) pylab.draw() if verbose: print ' Done with plotgauge for gauge %i' % (gaugeno) # print the figure(s) to file(s) if requested: if (plotdata.mode() != 'iplotclaw') & plotdata.printfigs: # iterate over all figures that are to be printed: for figno in plotted_fignos: printfig(gaugeno=gaugeno, figno=figno, \ format=plotdata.print_format, plotdir=plotdata.plotdir,\ verbose=verbose) return current_data
def plotgauge(gaugeno, plotdata, verbose=False): #========================================== """ Plot all requested plots for a single gauge from the computation. The plots are requested by setting attributes of plotdata to ClawPlotFigure objects with plot_type="each_gauge". """ if verbose: gaugesoln = plotdata.getgauge(gaugeno) print ' Plotting gauge %s at x = %g, y = %g ... ' \ % (gaugeno, gaugesoln.x, gaugesoln.y) if plotdata.mode() == 'iplotclaw': pylab.ion() try: plotfigure_dict = plotdata.plotfigure_dict except: print '*** Error in plotgauge: plotdata missing plotfigure_dict' print '*** This should not happen' return None if len(plotfigure_dict) == 0: print '*** Warning in plotgauge: plotdata has empty plotfigure_dict' print '*** Apparently no figures to plot' # initialize current_data containing data that will be passed # to beforegauge, aftergauge, afteraxes commands current_data = Data() current_data.user = Data() # for user specified attributes # to avoid potential conflicts current_data.plotdata = plotdata current_data.gaugeno = gaugeno # call beforegauge if present, which might define additional # attributes in current_data or otherwise set up plotting for this # gauge. beforegauge = getattr(plotdata, 'beforegauge', None) if beforegauge: if isinstance(beforegauge, str): # a string to be executed exec(beforegauge) else: # assume it's a function try: output = beforegauge(current_data) if output: current_data = output except: print '*** Error in beforegauge ***' raise # iterate over each single plot that makes up this gauge: # ------------------------------------------------------- if plotdata._mode == 'iplotclaw': gaugesoln = plotdata.getgauge(gaugeno) #import pdb; pdb.set_trace() print ' Plotting Gauge %s at x = %g, y = %g ... ' \ % (gaugeno, gaugesoln.x, gaugesoln.y) requested_fignos = plotdata.iplotclaw_fignos else: requested_fignos = plotdata.print_fignos plotted_fignos = [] plotdata = set_show(plotdata) # set _show attributes for which figures # and axes should be shown. # loop over figures to appear for this gauge: # ------------------------------------------- for figname in plotdata._fignames: plotfigure = plotdata.plotfigure_dict[figname] if (not plotfigure._show) or (plotfigure.type != 'each_gauge'): continue # skip to next figure figno = plotfigure.figno if requested_fignos != 'all': if figno not in requested_fignos: continue # skip to next figure plotted_fignos.append(figno) if not plotfigure.kwargs.has_key('facecolor'): # use Clawpack's default bg color (tan) plotfigure.kwargs['facecolor'] = '#ffeebb' # create figure and set handle: plotfigure._handle = pylab.figure(num=figno, **plotfigure.kwargs) pylab.ioff() if plotfigure.clf_each_gauge: pylab.clf() try: plotaxes_dict = plotfigure.plotaxes_dict except: print '*** Error in plotgauge: plotdata missing plotaxes_dict' print '*** This should not happen' return None if (len(plotaxes_dict) == 0) or (len(plotfigure._axesnames) == 0): print '*** Warning in plotgauge: plotdata has empty plotaxes_dict' print '*** Apparently no axes to plot in figno ',figno # loop over axes to appear on this figure: # ---------------------------------------- for axesname in plotfigure._axesnames: plotaxes = plotaxes_dict[axesname] if not plotaxes._show: continue # skip this axes if no items show # create the axes: axescmd = getattr(plotaxes,'axescmd','subplot(1,1,1)') axescmd = 'plotaxes._handle = pylab.%s' % axescmd exec(axescmd) pylab.hold(True) # loop over items: # ---------------- for itemname in plotaxes._itemnames: plotitem = plotaxes.plotitem_dict[itemname] try: outdir = plotitem.outdir if outdir is None: outdir = plotdata.outdir gaugesoln = plotdata.getgauge(gaugeno, outdir) except: print '*** Cannot find gauge number ',gaugeno print '*** looking in directory ', outdir print '*** cwd = ',os.getcwd() return None #import pdb; pdb.set_trace() current_data.gaugesoln = gaugesoln current_data.q = gaugesoln.q current_data.t = gaugesoln.t if plotitem._show: try: output = plotgauge1(gaugesoln,plotitem,\ current_data) if output: current_data = output if verbose: print ' Plotted plotitem ', itemname except: print '*** Error in plotgauge: problem calling plotgauge1' traceback.print_exc() return None # end of loop over plotitems for itemname in plotaxes._itemnames: plotitem = plotaxes.plotitem_dict[itemname] if plotitem.afteritem: print "*** ClawPlotItem.afteritem is deprecated" print "*** use ClawPlotAxes.afteraxes " print "*** or ClawPlotItem.aftergrid instead" pylab.title("%s at gauge %s" % (plotaxes.title,gaugeno)) # call an afteraxes function if present: afteraxes = getattr(plotaxes, 'afteraxes', None) if afteraxes: if isinstance(afteraxes, str): # a string to be executed exec(afteraxes) else: # assume it's a function try: current_data.plotaxes = plotaxes current_data.plotfigure = plotaxes._plotfigure output = afteraxes(current_data) if output: current_data = output except: print '*** Error in afteraxes ***' raise if plotaxes.scaled: pylab.axis('scaled') # set axes limits: if (plotaxes.xlimits is not None) & (type(plotaxes.xlimits) is not str): try: pylab.xlim(plotaxes.xlimits[0], plotaxes.xlimits[1]) except: pass # let axis be set automatically if (plotaxes.ylimits is not None) & (type(plotaxes.ylimits) is not str): try: pylab.ylim(plotaxes.ylimits[0], plotaxes.ylimits[1]) except: pass # let axis be set automatically # end of loop over plotaxes # end of loop over plotfigures # call an aftergauge function if present: aftergauge = getattr(plotdata, 'aftergauge', None) if aftergauge: if isinstance(aftergauge, str): # a string to be executed exec(aftergauge) else: # assume it's a function try: output = aftergauge(current_data) if output: current_data = output except: print '*** Error in aftergauge ***' raise if plotdata.mode() == 'iplotclaw': pylab.ion() for figno in plotted_fignos: pylab.figure(figno) pylab.draw() if verbose: print ' Done with plotgauge for gauge %i' % (gaugeno) # print the figure(s) to file(s) if requested: if (plotdata.mode() != 'iplotclaw') & plotdata.printfigs: # iterate over all figures that are to be printed: for figno in plotted_fignos: printfig(gaugeno=gaugeno, figno=figno, \ format=plotdata.print_format, plotdir=plotdata.plotdir,\ verbose=verbose) return current_data
def get_frame(self, frameno): if self.solutions.has_key(frameno): # don't read if already in dictionary: return self.grid, self.solutions[frameno] fname = "fort.fg%s_%s" % (str( self.fgno).zfill(2), str(frameno).zfill(4)) fname = os.path.join(self.outdir, fname) if not os.path.exists(fname): print "*** Did not find file ", fname, " in directory ", self.outdir raise IOError("Missing fixed grid output file") self.grid = Data() grid = self.grid # Read parameters from header: file = open(fname, 'r') line = file.readline() t = float(line.split()[0]) print "Reading fixed grid output from ", fname print ' Frame %s at t = %s' % (frameno, t) line = file.readline() grid.mx = int(line.split()[0]) line = file.readline() grid.my = int(line.split()[0]) line = file.readline() grid.xlow = float(line.split()[0]) line = file.readline() grid.ylow = float(line.split()[0]) line = file.readline() grid.xhi = float(line.split()[0]) line = file.readline() grid.yhi = float(line.split()[0]) file.close() grid.x = linspace(grid.xlow, grid.xhi, grid.mx + 1) grid.y = linspace(grid.ylow, grid.yhi, grid.my + 1) grid.dx = grid.x[1] - grid.x[0] grid.dy = grid.y[1] - grid.y[0] grid.xcenter = grid.x[:-1] + grid.dx / 2. grid.ycenter = grid.y[:-1] + grid.dy / 2. d = loadtxt(fname, skiprows=8) solution = Data() solution.t = t solution.ncols = d.shape[1] solution.h = reshape(d[:, 0], (grid.my, grid.mx)) solution.B = reshape(d[:, 3], (grid.my, grid.mx)) solution.eta = reshape(d[:, 4], (grid.my, grid.mx)) solution.surface = ma.masked_where(isnan(solution.eta), solution.eta) solution.land = ma.masked_where(solution.h > self.drytol, solution.B) solution.fg = empty((grid.my, grid.mx, solution.ncols), dtype=float) for col in range(solution.ncols): solution.fg[:, :, col] = reshape(d[:, col], (grid.my, grid.mx)) self.solutions[frameno] = solution return grid, solution
def get_frame(self, frameno): if self.solutions.has_key(frameno): # don't read if already in dictionary: return self.grid, self.solutions[frameno] fname = "fort.fg%s_%s" % (str(self.fgno).zfill(2), str(frameno).zfill(4)) fname = os.path.join(self.outdir,fname) if not os.path.exists(fname): print "*** Did not find file ",fname," in directory ",self.outdir raise IOError("Missing fixed grid output file") self.grid = Data() grid = self.grid # Read parameters from header: file = open(fname,'r') line = file.readline() t = float(line.split()[0]) print "Reading fixed grid output from ",fname print ' Frame %s at t = %s' % (frameno,t) line = file.readline() grid.mx = int(line.split()[0]) line = file.readline() grid.my = int(line.split()[0]) line = file.readline() grid.xlow = float(line.split()[0]) line = file.readline() grid.ylow = float(line.split()[0]) line = file.readline() grid.xhi = float(line.split()[0]) line = file.readline() grid.yhi = float(line.split()[0]) file.close() grid.x = linspace(grid.xlow, grid.xhi, grid.mx+1) grid.y = linspace(grid.ylow, grid.yhi, grid.my+1) grid.dx = grid.x[1]-grid.x[0] grid.dy = grid.y[1]-grid.y[0] grid.xcenter = grid.x[:-1] + grid.dx/2. grid.ycenter = grid.y[:-1] + grid.dy/2. d = loadtxt(fname, skiprows=8) solution = Data() solution.t = t solution.ncols = d.shape[1] solution.h = reshape(d[:,0], (grid.my,grid.mx)) solution.B = reshape(d[:,3], (grid.my,grid.mx)) solution.eta = reshape(d[:,4], (grid.my,grid.mx)) solution.surface = ma.masked_where(isnan(solution.eta),solution.eta) solution.land = ma.masked_where(solution.h>self.drytol,solution.B) solution.fg = empty((grid.my,grid.mx,solution.ncols), dtype=float) for col in range(solution.ncols): solution.fg[:,:,col] = reshape(d[:,col],(grid.my,grid.mx)) self.solutions[frameno] = solution return grid, solution
def read_dtopo(fname, topotype=1): header = read_header(fname) if (len(header["header_lines"]) == 0) and (abs(topotype) > 1): raise ValueError("*** topotype = %s but no header found" % topotype) if (len(header["header_lines"]) > 0) and (abs(topotype) == 1): raise ValueError("*** topotype = %s but header found" % topotype) header_length = header["header_lines"].count("\n") if topotype == 1: d = np.loadtxt(fname, skiprows=header_length) ncol = d.shape[1] if ncol == 3: tcol = None xcol = d[:, 0] ycol = d[:, 1] dzcol = d[:, 2] else: tcol = d[:, 0] xcol = d[:, 1] ycol = d[:, 2] dzcol = d[:, 3] xdiff = np.diff(xcol) inddiff = pylab.find(xdiff < 0) mx = inddiff[0] + 1 mt = 1 if tcol is not None: # check if there is more than one time in this file: tdiff = np.diff(tcol) inddiff = pylab.find(tdiff > 0) if len(inddiff) > 0: mt = len(inddiff) + 1 my = len(xcol) / (mx * mt) if my != int(len(xcol) / float(mx * mt)): print("*** found mx = %s, mt = %s" % (mx, mt)) raise ValueError("*** mx*mt does not divide length of data") print("Found mt = %s times with mx = %s, my = %s" % (mt, mx, my)) if tcol is None: t = [] else: t = tcol[0 :: mx * my] X = np.reshape(xcol[: mx * my], (my, mx)) Y = np.reshape(ycol[: mx * my], (my, mx)) dZ = np.reshape(dzcol, (mt, my, mx)) elif topotype == 3: try: my = header["nrows"] mx = header["ncols"] mt = header["mtimes"] xll = header["xll"] yll = header["yll"] t0 = header["t0"] dx = header["dx"] dy = header["dy"] dt = header["dt"] except: raise ValueError("*** Missing information from header") if (dt == 0) or (mt == 1): t = np.array([t0]) else: t = np.arange(t0, t0 + mt * dt, dt) x = np.linspace(xll, xll + mx * dx, mx) y = np.linspace(yll, yll + my * dy, my) X, Y = np.meshgrid(x, y) X = X.T Y = Y.T fdata = np.loadtxt(fname, skiprows=header_length) dzcol = np.reshape(fdata, (mx * my * mt, 1)) dZ = np.empty((mt, mx, my)) for i in range(mt): dzi = np.reshape(dzcol[i * mx * my : (i + 1) * mx * my], (my, mx)) dzi = np.flipud(dzi) dZ[i, :, :] = dzi.T else: raise ValueError("*** Cannot read topotype = " % topotype) dtopo = Data() dtopo.t = t dtopo.X = X dtopo.Y = Y dtopo.dZ = dZ return dtopo
def read_dtopo(fname, topotype=1): header = read_header(fname) if (len(header['header_lines']) == 0) and (abs(topotype)>1): raise ValueError("*** topotype = %s but no header found" % topotype) if (len(header['header_lines']) > 0) and (abs(topotype)==1): raise ValueError("*** topotype = %s but header found" % topotype) header_length = header['header_lines'].count('\n') if topotype==1: d = np.loadtxt(fname, skiprows=header_length) ncol = d.shape[1] if ncol == 3: tcol = None xcol = d[:,0] ycol = d[:,1] dzcol = d[:,2] else: tcol = d[:,0] xcol = d[:,1] ycol = d[:,2] dzcol = d[:,3] xdiff = np.diff(xcol) inddiff = pylab.find(xdiff<0) mx = inddiff[0]+1 mt = 1 if tcol is not None: # check if there is more than one time in this file: tdiff = np.diff(tcol) inddiff = pylab.find(tdiff>0) if len(inddiff) > 0: mt = len(inddiff)+1 my = len(xcol)/(mx*mt) if my != int(len(xcol)/float(mx*mt)): print "*** found mx = %s, mt = %s" % (mx,mt) raise ValueError("*** mx*mt does not divide length of data") print "Found mt = %s times with mx = %s, my = %s" % (mt,mx,my) if tcol is None: t = [] else: t = tcol[0::mx*my] X = np.reshape(xcol[:mx*my],(my,mx)) Y = np.reshape(ycol[:mx*my],(my,mx)) dZ = np.reshape(dzcol,(mt,my,mx)) elif topotype==3: try: my = header['nrows'] mx = header['ncols'] mt = header['mtimes'] xll = header['xll'] yll = header['yll'] t0 = header['t0'] dx = header['dx'] dy = header['dy'] dt = header['dt'] except: raise ValueError("*** Missing information from header") if (dt==0) or (mt==1): t = np.array([t0]) else: t = np.arange(t0,t0+mt*dt,dt) x = np.linspace(xll,xll + mx*dx, mx) y = np.linspace(yll,yll + my*dy, my) X,Y = np.meshgrid(x,y) X = X.T Y = Y.T fdata = np.loadtxt(fname, skiprows=header_length) dzcol = np.reshape(fdata,(mx*my*mt, 1)) dZ = np.empty((mt,mx,my)) for i in range(mt): dzi = np.reshape(dzcol[i*mx*my:(i+1)*mx*my], (my,mx)) dzi = np.flipud(dzi) dZ[i,:,:] = dzi.T else: raise ValueError("*** Cannot read topotype = " % topotype) dtopo = Data() dtopo.t = t dtopo.X = X dtopo.Y = Y dtopo.dZ = dZ return dtopo