Esempio n. 1
0
def read_q(path='./_output',frame=0,read_aux=False,read_grid=False,read_q=True,qi=[0,1,2],sampling=[1,1],loc_max=True):
    solution = Solution()
    
    solution.read(frame,path=path,file_format='petsc',read_aux=read_aux)
    sol_compilation = {}
    sol_compilation['sampling'] = sampling

    if read_grid:
        x,y,dimension = get_grid(solution,sampling)
        dict2 = {'x':x,'y':y,'nodes':dimension[0:2,:],'num_cells':dimension[-1,:]}
        sol_compilation.update(dict2)
    
    if read_aux:
        sol_compilation.update({'aux':solution.state.get_aux_global()[0:3,::sampling[0],::sampling[1]]})

    if read_q:
        q_all = solution.state.get_q_global()[:,::sampling[0],::sampling[1]]
        for qn in qi:
            q = solution.state.get_q_global()[qn,::sampling[0],::sampling[1]]
            sol_compilation.update({'q'+str(qn):q})
            if loc_max:
                if not read_grid:
                    x,y,dimension = get_grid(solution,sampling)
                indmax = q[:,:]==q[:,:].max()
                sol_compilation.update({'indmax'+str(qn):indmax})
                sol_compilation.update({'xmax':x[indmax],'ymax':y[indmax]})

    sol_compilation.update({'t':solution.t})        

    return sol_compilation if not read_q else q_all,sol_compilation
Esempio n. 2
0
    def getAux(self,dirs,frame=None,qn=None):
        if frame is None:
            frame = self.frame
        if qn is None:
            qn = self.qn

        solution = Solution()
        solution.read(frame,path=dirs,file_format=self.file_format,read_aux=True)

        auxclaw  = solution.state.get_aux_global()[qn]
        xclaw    = solution.state.grid.x.centers
        delta    = solution.state.grid.delta

        return auxclaw,xclaw,delta
Esempio n. 3
0
    def verify_sedov(controller):
        import os
        from clawpack.pyclaw.util import check_diff
        from clawpack.pyclaw import Solution
        
        thisdir = os.path.dirname(__file__)
        verify_dir = os.path.join(thisdir,'./Sedov_regression')

        # Expected solution
        sol_expected = Solution()
        sol_expected.read(1,path=verify_dir,file_format='hdf',read_aux=False)
        assert sol_expected.t == 0.1
        expected_q = sol_expected.state.q

        # Test solution
        sol_test = Solution()
        sol_test.read(1,path=controller.outdir,
                        file_format=controller.output_format,
                        read_aux=False,
                        options=controller.output_options)
        test_q = sol_test.state.get_q_global()


        if test_q is not None:
            q_err = check_diff(expected_q, test_q, reltol=1e-6)
            if q_err is not None:
                return q_err
        else:
            return
Esempio n. 4
0
def read_fortq(frame):
    """
    Import fort.q files to get x,y,z data
    """
    fortq = Solution(frame, file_format='ascii')
    patch_dict = {}
    for stateno, state in enumerate(fortq.states):
        patch = state.patch
        level = patch.level
        Xc, Yc = state.grid.c_centers
        h = state.q[0, :, :]
        eta = state.q[3, :, :]
        drytol_default = 0.001
        water = np.copy(eta)
        idx = np.where((h <= drytol_default) & (h >= -drytol_default))
        water[idx] = np.nan
        #         idx2 = np.where(eta==0)
        #         water[idx2] = np.nan

        # Save variables to dictionary
        long = Xc[:, 0]
        lat = Yc[0]
        patch_dict[stateno] = {
            "lat": lat,
            'long': long,
            'eta': eta,
            'amr_level': level,
            'Xc': Xc,
            'Yc': Yc,
            'water': water
        }
    return patch_dict, water, h, Xc, Yc, eta
Esempio n. 5
0
    def getAux(self, dirs, frame=None, qn=None):
        if frame is None:
            frame = self.frame
        if qn is None:
            qn = self.qn

        solution = Solution()
        solution.read(frame,
                      path=dirs,
                      file_format=self.file_format,
                      read_aux=True)

        auxclaw = solution.state.get_aux_global()[qn]
        xclaw = solution.state.grid.x.centers
        delta = solution.state.grid.delta

        return auxclaw, xclaw, delta
Esempio n. 6
0
def read_q(path='./_output',
           frame=0,
           read_aux=False,
           read_grid=False,
           read_q=True,
           qi=[0, 1, 2],
           sampling=[1, 1],
           loc_max=True):
    solution = Solution()

    solution.read(frame, path=path, file_format='petsc', read_aux=read_aux)
    sol_compilation = {}
    sol_compilation['sampling'] = sampling

    if read_grid:
        x, y, dimension = get_grid(solution, sampling)
        dict2 = {
            'x': x,
            'y': y,
            'nodes': dimension[0:2, :],
            'num_cells': dimension[-1, :]
        }
        sol_compilation.update(dict2)

    if read_aux:
        sol_compilation.update({
            'aux':
            solution.state.get_aux_global()[0:3, ::sampling[0], ::sampling[1]]
        })

    if read_q:
        q_all = solution.state.get_q_global()[:, ::sampling[0], ::sampling[1]]
        for qn in qi:
            q = solution.state.get_q_global()[qn, ::sampling[0], ::sampling[1]]
            sol_compilation.update({'q' + str(qn): q})
            if loc_max:
                if not read_grid:
                    x, y, dimension = get_grid(solution, sampling)
                indmax = q[:, :] == q[:, :].max()
                sol_compilation.update({'indmax' + str(qn): indmax})
                sol_compilation.update({'xmax': x[indmax], 'ymax': y[indmax]})

    sol_compilation.update({'t': solution.t})

    return sol_compilation if not read_q else q_all, sol_compilation
Esempio n. 7
0
    def getClaw(self,dirs,frame=None,qn=None,homogeneous=None):
        if frame is None:
            frame = self.frame
        if qn is None:
            qn = self.qn
        if homogeneous is None:
            homogeneous = self.homogeneous

        solution = Solution()

        solution.read(frame,path=dirs,file_format=self.file_format,read_aux=self.homogeneous)

        qclaw  = solution.state.get_q_global()[qn]
        xclaw  = solution.state.grid.x.centers
        delta  = solution.state.grid.delta

        if homogeneous:
            print 'dividing by aux'
            qclaw = qclaw/(solution.state.get_aux_global()[qn])

        return qclaw,xclaw,delta
Esempio n. 8
0
    def verify_sedov(controller):
        import os
        from clawpack.pyclaw.util import check_diff
        from clawpack.pyclaw import Solution
        
        thisdir = os.path.dirname(__file__)
        verify_dir = os.path.join(thisdir,'./Sedov_regression')
        
        # Expected solution
        sol_expected = Solution()
        sol_expected.read(1,path=verify_dir,file_format='hdf',read_aux=False)
        expected_q = sol_expected.state.q

        # Test solution
        sol_test = Solution()
        sol_test.read(1,path=controller.outdir,
                        file_format=controller.output_format,
                        read_aux=False,
                        options=controller.output_options)
        test_q = sol_test.state.get_q_global()


        if test_q is not None:
            q_err = check_diff(expected_q, test_q, reltol=1e-6)
            if q_err is not None:
                return q_err
        else:
            return
Esempio n. 9
0
    def getClaw(self, dirs, frame=None, qn=None, homogeneous=None):
        if frame is None:
            frame = self.frame
        if qn is None:
            qn = self.qn
        if homogeneous is None:
            homogeneous = self.homogeneous

        solution = Solution()

        solution.read(frame,
                      path=dirs,
                      file_format=self.file_format,
                      read_aux=self.homogeneous)

        qclaw = solution.state.get_q_global()[qn]
        xclaw = solution.state.grid.x.centers
        delta = solution.state.grid.delta

        if homogeneous:
            print 'dividing by aux'
            qclaw = qclaw / (solution.state.get_aux_global()[qn])

        return qclaw, xclaw, delta
Esempio n. 10
0
def plot_transect(ylat, frameno, fg, xcutoff, trname, plotdir):

    figure(20, figsize=(10, 3))
    clf()

    xout = linspace(xlimits[0], xlimits[1], 1000)
    yout = ylat * ones(xout.shape)

    framesoln = Solution(frameno, path=outdir, file_format=format)
    eta = gridtools.grid_output_2d(framesoln, 3, xout, yout)
    topo = gridtools.grid_output_2d(framesoln, B, xout, yout)

    fill_between(xout, eta, topo, color=[.5, .5, 1])
    fill_between(xout, topo, -10000, color=[.5, 1, .5])
    plot(xout, eta, 'b')
    plot(xout, topo, 'g')
    grid(True)

    eta = fg.B + fg.h
    eta_max = where(fg.X < xcutoff, eta, nan)
    plot(fg.X, eta_max, 'r', label='wave height')
    xlim(xlimits)
    ylim(zlimits)
    timestr = timeformat(framesoln.t)
    title('Transect of wave at latitude %.1f at time %s' % (ylat, timestr),
          fontsize=15)
    ticklabel_format(format='plain', useOffset=False)
    xticks([-127, -126, -125, -124], fontsize=15)
    yticks(linspace(-0.2, 0.6, 5), fontsize=15)
    #xlabel('Longitude')
    ylabel('meters', fontsize=15)
    hl = 3000.
    A0 = 0.1328
    z = where(topo < -10, -topo, nan)
    AG = A0 * (hl / z)**0.25
    plot(xout, AG, 'g--', label="Green's Law")
    ctx = A0 * 2 * sqrt(hl) / (sqrt(hl) + sqrt(z))
    plot(xout, ctx, 'b--', label='Transmission')
    legend(loc='upper left', fontsize=15, framealpha=1)

    fname = '%s_%s' % (trname, str(frameno).zfill(4))
    save_figure(fname)
Esempio n. 11
0
def get_max_boundary_fluxes(model_output_dir,
                            max_refinement_depth_to_check=None,
                            frames_to_check=1):
    """A common cause of instability is a persistant normal flux at the boundary.
    This code checks the last frame(s) of a model output and returns the maximum
    magnitude normal fluxes and currents at each boundary, as well as the maximum 
    magnitude fluxes and currents observed within the entire domain.
    
    :Input:
    - *model_output_dir* (str) Path to the output directory for a given model
    - *max_refinement_depth_to_check* (int or None, optional) How many refinement levels to 
        loop through to find max values. Runs quicker when just checking level 1, but
        you may find higher max values at higher refinement levels. None (default)
        means check all levels
    - *frames_to_check* (int) How many of the last output frames to check for max. Default
        is just one.
    """

    # find which frame is last
    output_files = glob(join(model_output_dir, 'fort.q*'))
    frames = [int(i.split('/')[-1][-4:]) for i in output_files]
    last_frame = max(frames)

    # get domain and file format
    with open(join(model_output_dir, 'claw.data'), 'r') as f:
        for l in f:
            if '=: lower' in l:
                xl, yl = [float(i) for i in l.strip().split()[:2]]
            elif '=: upper' in l:
                xu, yu = [float(i) for i in l.strip().split()[:2]]
            elif '=: output_format' in l:
                of = int(l.strip().split()[0]) - 1
    file_format = ['ascii', 'netcdf', 'binary'][of]

    maxhxl = -np.inf
    maxhyl = -np.inf
    maxcurrxl = -np.inf
    maxcurryl = -np.inf
    maxhxu = -np.inf
    maxhyu = -np.inf
    maxcurrxu = -np.inf
    maxcurryu = -np.inf
    maxhx_overall = -np.inf
    maxhy_overall = -np.inf
    maxcurrx_overall = -np.inf
    maxcurry_overall = -np.inf

    for f in range(last_frame + 1 - frames_to_check, last_frame + 1):

        soln = Solution()
        soln.read(f,
                  path=model_output_dir,
                  file_format=file_format,
                  read_aux=False)

        for s in soln.states:

            # only looking at lowest AMR levels
            if max_refinement_depth_to_check is not None:
                if s.patch.level > max_refinement_depth_to_check:
                    continue

            # get rounding error tolerance
            delta = s.grid.dimensions[0].delta
            edge_tol = delta * .001

            x = s.grid.c_centers[0]
            xedges = s.grid.c_nodes[0]
            y = s.grid.c_centers[1]
            yedges = s.grid.c_nodes[1]

            eta = s.q[3, :, :]
            h = s.q[0, :, :]
            hx = s.q[1, :, :]
            curr_x = hx / h
            hy = s.q[2, :, :]
            curr_y = hy / h
            topo = eta - s.q[0, :, :]
            maxhx_overall = np.nanmax([np.abs(hx).max(), maxhx_overall])
            maxhy_overall = np.nanmax([np.abs(hy).max(), maxhy_overall])
            maxcurrx_overall = np.nanmax(
                [np.nanmax(np.abs(curr_x)), maxcurrx_overall])
            maxcurry_overall = np.nanmax(
                [np.nanmax(np.abs(curr_y)), maxcurry_overall])

            if abs(xedges[0, 0] - xl) < edge_tol:
                maxhxl = np.nanmax([maxhxl, np.nanmax(np.abs(hx[0, :]))])
                maxcurrxl = np.nanmax(
                    [maxcurrxl, np.nanmax(np.abs(curr_x[0, :]))])
            if abs(xedges[-1, 0] - xu) < edge_tol:
                maxhxu = np.nanmax([maxhxu, np.nanmax(np.abs(hx[-1, :]))])
                maxcurrxu = np.nanmax(
                    [maxcurrxu, np.nanmax(np.abs(curr_x[-1, :]))])
            if abs(yedges[0, 0] - yl) < edge_tol:
                maxhyl = np.nanmax([maxhyl, np.nanmax(np.abs(hy[:, 0]))])
                maxcurryl = np.nanmax(
                    [maxcurryl, np.nanmax(np.abs(curr_y[:, 0]))])
            if abs(yedges[0, -1] - yu) < edge_tol:
                maxhyu = np.nanmax([maxhyu, np.nanmax(np.abs(hy[:, -1]))])
                maxcurryu = np.nanmax(
                    [maxcurryu, np.nanmax(np.abs(curr_y[:, -1]))])

    return ({
        'max_normal_fluxes': {
            'W': maxhxl,
            'E': maxhxu,
            'N': maxhyu,
            'S': maxhyl
        },
        'max_normal_currents': {
            'W': maxcurrxl,
            'E': maxcurrxu,
            'N': maxcurryu,
            'S': maxcurryl
        },
        'domain_maxs': {
            'hu': maxhx_overall,
            'hv': maxhy_overall,
            'u': maxcurrx_overall,
            'v': maxcurry_overall
        }
    })
Esempio n. 12
0
def quality_check(
        model_output_dir,
        regions_to_check=[
            [-81, 22, -40, 55],  # atlantic
            [-100, 15, -82, 32],  # gulf
            [-88.5, 13.25, -70, 19.75]
        ],  # carribean
        frames_to_check=4,
        mean_tol_abs=.01,
        min_depth=300):
    """Run a simple check to flag runs that were potentially numerically unstable.
    This function looks through the final *frames_to_check* frames of a model output
    and checks all cells in AMR level 1 that are below *min_depth* and 
    fall within each region in the *regions_to_check* list (which are intended 
    to encompass individual basins). If the absolute value of the mean surface height
    for these cells, which should not really have much surge, is above/mean_tol_abs, 
    it raises an error.
    
    :Input:
    - *model_output_dir* (str) Path to the output directory for a given model
    - *regions_to_check* (list of lists of floats) A list of 4-element lists
        which define the (left, bottom, right, top) of regions to check within.
    - *frames_to_check* (int) The number of final frames of the model output to check
    - *mean_tol_abs* (float) Model is flagged if the absolute value of the mean surface
        height within any region in *regions_to_check* is above this value (meters).
    - *min_depth* (float) Only cells that are below *min_depth* (meters) are checked, in 
        order to avoid including cells that potentially should have large surge values.
        
    :Raises:
    - InstabilityError if the model is flagged as potentially unstable in one of the regions.
    """

    # find which frame is last
    output_files = glob(join(model_output_dir, 'fort.b*'))
    last_frame = int(output_files[-1].split('/')[-1][-4:])

    # get sl_init
    with open(join(model_output_dir, 'geoclaw.data'), 'r') as f:
        for l in f:
            if '=: sea_level' in l:
                sl_init = float(l.strip().split()[0])

    # bring in solution
    soln = Solution()
    for frame in range(last_frame - frames_to_check + 1, last_frame + 1):
        soln.read(frame,
                  path=model_output_dir,
                  file_format='binary',
                  read_aux=False)

        for r in regions_to_check:
            all_vals = np.array([])
            for s in soln.states:

                # only looking at lowest AMR level
                if s.patch.level > 1:
                    continue

                x = s.grid.c_centers[0]
                y = s.grid.c_centers[1]
                eta = s.q[3, :, :]
                topo = eta - s.q[0, :, :]

                # only count
                eta = np.where(topo < (-min_depth), eta, np.nan)
                in_reg = eta[np.ix_((x[:, 0] >= r[0]) & (x[:, 0] <= r[2]),
                                    (y[0, :] >= r[1]) & (y[0, :] <= r[3]))]
                all_vals = np.concatenate([all_vals, in_reg.flatten()])

            # adjust for sl_init
            all_vals = all_vals - sl_init

            if all_vals.shape[0] > 0:
                if abs(np.nanmean(all_vals)) > mean_tol_abs:
                    raise InstabilityError(
                        "Model possibly unstable due to large magnitude deep "
                        "ocean surge at end of run ({:.1f} cm in region {})".
                        format(np.nanmean(all_vals) * 100, r))
    def verify_acoustics_io(controller):
        """ Verifies I/O on 2d variable-coefficient acoustics application"""
        import os
        from clawpack.pyclaw.util import check_diff
        from clawpack.pyclaw import Solution

        thisdir = os.path.dirname(__file__)
        verify_dir = os.path.join(thisdir, './io_test_verification')

        # Expected solution
        sol_0_expected = Solution()
        sol_0_expected.read(0,
                            path=verify_dir,
                            file_format='ascii',
                            file_prefix=None,
                            read_aux=True)
        expected_aux = sol_0_expected.state.aux

        sol_20_expected = Solution()
        sol_20_expected.read(20,
                             path=verify_dir,
                             file_format='ascii',
                             file_prefix=None,
                             read_aux=False)
        expected_q = sol_20_expected.state.q

        # Test solution
        sol_0_test = Solution()
        sol_0_test.read(0,
                        path=controller.outdir,
                        file_format=controller.output_format,
                        file_prefix=None,
                        read_aux=True,
                        options=controller.output_options)
        test_aux = sol_0_test.state.get_aux_global()

        sol_20_test = Solution()
        sol_20_test.read(20,
                         path=controller.outdir,
                         file_format=controller.output_format,
                         file_prefix=None,
                         read_aux=False,
                         options=controller.output_options)
        test_q = sol_20_test.state.get_q_global()

        if test_q is not None:
            q_err = check_diff(expected_q, test_q, reltol=1e-6)
            if q_err is not None:
                return q_err
        else:
            return

        if test_aux is not None:
            aux_err = check_diff(expected_aux, test_aux, reltol=1e-6)
            if aux_err is not None:
                return aux_err
        else:
            return
import os
from numpy import ma
from clawpack.pyclaw import Solution
import subprocess
import numpy as np
#
file_path = os.path.join('c:/', 'fortranprograms', 'plots', '_output')  #
# '''''/Users/jeffriesc/clawpack-5.4.1/geoclaw/examples/tsunami/TestingLinearity/SF_8_1m/_output'
solution = Solution()

drytol_default = .001
x = Solution(1, file_format='ascii')

for stateno, state in enumerate(x.states):
    # state = x.states[stateno]
    patch = state.patch
    level = patch.level
    print(stateno, patch.level)

    Xc, Yc = state.grid.c_centers
    xc = Xc[:, 0]
    yc = Yc[0, :]
    h = state.q[0, :, :]
    eta = state.q[3, :, :]
    if (np.isnan(eta).any()) == True:

        print(np.isnan(eta).any())
    topo = eta - h
    # water = np.ma.masked_where(h <= drytol_default, eta)
    water = eta
    ind = np.where(h <= drytol_default)
Esempio n. 15
0
def assemble_q(path='./_output',
               frame_plot_range=[0],
               poynting=True,
               read_aux=False,
               qi=[0, 1, 2],
               update_aux=False,
               sampling=[1, 1],
               frame_split=False,
               split_q=False,
               figspath='./',
               binpath='./',
               cut=True):
    # create instance of solution object
    num_frames = len(frame_plot_range)
    solution = Solution()
    Q_map_temp = [[], []]
    d_map_temp = [[], []]
    sol = {}

    # print frame_plot_range
    sampled = np.zeros([num_frames, 9])
    plot_aux = True
    # load the frames and assemble values
    for f, frame in enumerate(frame_plot_range):
        # print frame
        ql = [[], []]
        dl = [[], []]
        if f == 0:
            q, grid = read_q(path=path,
                             frame=frame,
                             read_q=False,
                             read_grid=True,
                             sampling=sampling)
            sol['grid'] = grid

        if read_aux:
            if f == 0 or update_aux:
                q, aux = read_q(path=path,
                                frame=frame,
                                read_q=False,
                                read_aux=True,
                                qi=[1, 2],
                                sampling=sampling)
                sol['aux' + str(f)] = aux

                if plot_aux:
                    plt.close('all')
                    plt.figure()
                    fig, axes = plt.subplots(nrows=1)
                    axes.pcolormesh(grid['x'],
                                    grid['y'],
                                    aux['aux'][1, :, :],
                                    cmap='jet')
                    axes.set_xlabel('$x$')
                    axes.set_ylabel('$y$')
                    aux_name = 'aux' + str(frame).zfill(4)
                    plt.savefig(os.path.join(figspath, aux_name + '.png'),
                                format='png',
                                dpi=320,
                                bbox_inches='tight')
                    plt.close()
                    plot_aux = update_aux

        q, solution = read_q(path=path, frame=frame, qi=qi, sampling=sampling)

        for k in xrange(1, 3, 1):
            dl[k - 1], ql[k - 1] = extract_cut_line(
                q[k],
                grid['x'],
                grid['y'],
                plot=cut,
                num_points=1000,
                outdir=os.path.join(figspath, 'cut_x'),
                outname='cut_q' + str(k - 1) + '_' + str(frame).zfill(4),
                format='png')

            Q_map_temp[k - 1] = np.append(Q_map_temp[k - 1], ql[k - 1])
            d_map_temp[k - 1] = np.append(d_map_temp[k - 1], dl[k - 1])

        sol['q' + str(f)] = q

        sampled[f, 0] = solution['t']
        sampled[f, 1] = solution['xmax'].max()
        sampled[f, 2] = solution['ymax'].max()
        sampled[f, 3] = solution['q1'].max()
        sampled[f, 4] = solution['q2'].max()

        if poynting:
            p1 = q.shape[1] / 100
            p2 = q.shape[2] / 50
            Sx, Sy = Poynting(q[:, ::p1, ::p2],
                              plot=True,
                              streamline=True,
                              x=grid['x'][::p1, ::p2],
                              y=grid['y'][::p1, ::p2],
                              outdir=os.path.join(figspath, 'Poyinting'),
                              suffix=str(frame).zfill(4),
                              format='png',
                              cut_long=True)

        if split_q:
            for qn in range(0, len(q)):
                q_temp = q[qn, :, :, np.newaxis]
                aux_temp = aux['aux'][qn, :, :, np.newaxis]
                q_temp.tofile(
                    os.path.join(binpath,
                                 '3D_q' + str(qn) + '.' + str(frame).zfill(4)))
                aux_temp.tofile(
                    os.path.join(
                        binpath,
                        '3D_aux' + str(qn) + '.' + str(frame).zfill(4)))

        if frame_split:
            sol['Sx' + str(f)] = Sx
            sol['Sy' + str(f)] = Sy
            sol['sampled' + str(f)] = sampled
            savemat(os.path.join(figspath, 'sol' + str(frame).zfill(4)), sol)

    Q = np.reshape(Q_map_temp,
                   (2, num_frames, np.shape(Q_map_temp)[1] / num_frames))
    d = np.reshape(d_map_temp,
                   (2, num_frames, np.shape(d_map_temp)[1] / num_frames))

    sol['sampled'] = sampled
    sol['num_frames'] = num_frames

    return Q, d, sol
Esempio n. 16
0
def assemble_q(path='./_output',
               frame_plot_range=[0],
               vecmagnitude=True,
               poynting=True,
               poly_verts=True):
    # create instance of solution object
    num_frames = len(frame_plot_range)
    solution = Solution()
    Q_map_temp = []
    aux_map_temp = []
    derived_quantities = {}
    if vecmagnitude: I_map_temp = []
    if poynting: S_map_temp = []
    if poly_verts: verts = []

    sampled = np.zeros([len(frame_plot_range), 12])

    # load the frames and assemble values
    for f, frame in enumerate(frame_plot_range):

        solution = Solution()
        solution.read(frame, path=path, file_format='petsc', read_aux=True)

        x = solution.state.grid.x.centers
        q = solution.state.get_q_global()
        aux = solution.state.get_aux_global()[0:2, :]

        for n, qn in enumerate(q):
            Q_map_temp = np.append(Q_map_temp, qn)

        for n, auxn in enumerate(aux):
            aux_map_temp = np.append(aux_map_temp, auxn)

        sampled[f, 0] = solution.t
        if len(x[q[0] == q[0].max()]) == 1:
            it = np.sqrt(q[0]**2 + q[1]**2)
            # print x[np.where(it==it.max())]
            sampled[f, 1] = x[np.where(it == it.max())]

        if len(x[q[0] == q[0].max()]) >= 2:
            sampled[f, 1] = x[q[0] == q[0].max()][-1]
            print(len(x[q[0] == q[0].max()]))
        sampled[f, 3] = q[0].max()
        sampled[f, 4] = q[1].max()

        if poynting:
            S = q[0] * q[1]
            S_map_temp = np.append(S_map_temp, S, axis=0)

        if vecmagnitude:
            I = np.sqrt(q[0]**2 + q[1]**2)
            sampled[f, 6] = I.max()
            I_map_temp = np.append(I_map_temp, I, axis=0)

        if poly_verts:
            verts.append(list(zip(x, I)))

    Q = Q_map_temp.reshape(
        (num_frames, len(q), Q_map_temp.size / (len(q) * num_frames)))
    A = aux_map_temp.reshape(
        (num_frames, len(aux), aux_map_temp.size / (len(aux) * num_frames)))

    if vecmagnitude:
        I = (I_map_temp.reshape((num_frames, I_map_temp.size / num_frames)))
        derived_quantities['I'] = I

    if poynting:
        S = (S_map_temp.reshape((num_frames, S_map_temp.size / num_frames)))
        derived_quantities['S'] = S

    if poly_verts:
        derived_quantities['vertices'] = verts

    derived_quantities['x'] = x
    derived_quantities['t'] = sampled[:, 0]
    derived_quantities['sampled'] = sampled

    return Q, A, num_frames, derived_quantities
Esempio n. 17
0
def assemble_q(path='./_output',frame_plot_range=[0],vecmagnitude=True,poynting=True,poly_verts=True):
    # create instance of solution object
    num_frames = len(frame_plot_range)
    solution = Solution()
    Q_map_temp = []
    aux_map_temp = []
    derived_quantities = {}
    if vecmagnitude: I_map_temp = []
    if poynting: S_map_temp = []
    if poly_verts: verts = []
    
    sampled = np.zeros([len(frame_plot_range),12])
    
    # load the frames and assemble values
    for f,frame in enumerate(frame_plot_range):

        solution = Solution()
        solution.read(frame,path=path,file_format='petsc',read_aux=True)

        x = solution.state.grid.x.centers;
        q = solution.state.get_q_global()
        aux = solution.state.get_aux_global()[0:2,:]

        for n,qn in enumerate(q):
            Q_map_temp = np.append(Q_map_temp,qn)

        for n,auxn in enumerate(aux):
            aux_map_temp = np.append(aux_map_temp,auxn)

        sampled[f,0] = solution.t
        if len(x[q[0]==q[0].max()])==1:
            it = np.sqrt(q[0]**2 + q[1]**2)
            # print x[np.where(it==it.max())]
            sampled[f,1] = x[np.where(it==it.max())]

        if len(x[q[0]==q[0].max()])>=2:
            sampled[f,1] = x[q[0]==q[0].max()][-1]
            print len(x[q[0]==q[0].max()])
        sampled[f,3] = q[0].max()
        sampled[f,4] = q[1].max()

        if poynting:
            S = q[0]*q[1]
            S_map_temp = np.append(S_map_temp,S,axis=0)

        if vecmagnitude:
            I = np.sqrt(q[0]**2 + q[1]**2)
            sampled[f,6] = I.max()
            I_map_temp = np.append(I_map_temp,I,axis=0)

        if poly_verts:
            verts.append(list(zip(x,I)))

    Q = Q_map_temp.reshape((num_frames,len(q),Q_map_temp.size/(len(q)*num_frames)))
    A = aux_map_temp.reshape((num_frames,len(aux),aux_map_temp.size/(len(aux)*num_frames)))

    if vecmagnitude:
        I = (I_map_temp.reshape((num_frames,I_map_temp.size/num_frames)))
        derived_quantities['I'] = I
    
    if poynting:
        S = (S_map_temp.reshape((num_frames,S_map_temp.size/num_frames)))
        derived_quantities['S'] = S

    if poly_verts:
        derived_quantities['vertices'] = verts

    derived_quantities['x'] = x
    derived_quantities['t'] = sampled[:,0]
    derived_quantities['sampled'] = sampled

    return Q,A,num_frames,derived_quantities
Esempio n. 18
0
def load_frame(frame_number):
    from clawpack.pyclaw import Solution

    return Solution(frame_number)
Esempio n. 19
0
 def solution(self):
     return Solution()
    def verify_acoustics_io(controller):
        """ Verifies I/O on 2d variable-coefficient acoustics application"""
        import os
        from clawpack.pyclaw.util import check_diff
        from clawpack.pyclaw import Solution
        
        thisdir = os.path.dirname(__file__)
        verify_dir = os.path.join(thisdir,'./io_test_verification')
        
        # Expected solution
        sol_0_expected = Solution()
        sol_0_expected.read(0,path=verify_dir,file_format='ascii',
                               file_prefix=None,read_aux=True)
        expected_aux = sol_0_expected.state.aux

        sol_20_expected = Solution()
        sol_20_expected.read(20,path=verify_dir,file_format='ascii',
                               file_prefix=None,read_aux=False)
        expected_q = sol_20_expected.state.q

        # Test solution
        sol_0_test = Solution()
        sol_0_test.read(0,path=controller.outdir,
                        file_format=controller.output_format,
                        file_prefix=None,read_aux=True,
                        options=controller.output_options)
        test_aux = sol_0_test.state.get_aux_global()

        sol_20_test = Solution()
        sol_20_test.read(20,path=controller.outdir,
                        file_format=controller.output_format,
                        file_prefix=None,read_aux=False,
                        options=controller.output_options)
        test_q = sol_20_test.state.get_q_global()


        if test_q is not None:
            q_err = check_diff(expected_q, test_q, reltol=1e-6)
            if q_err is not None:
                return q_err
        else:
            return

        if test_aux is not None:
            aux_err = check_diff(expected_aux, test_aux, reltol=1e-6)
            if aux_err is not None:
                return aux_err
        else:
            return
Esempio n. 21
0
def quality_check(model_output_dir,
                  regions_to_check = [[-81,22,-40,55], # atlantic
                                      [-100,15,-82,32], # gulf
                                      [-88.5,13.25,-70,19.75]], # carribean
                  frames_to_check = 4,
                  mean_tol_abs = .01,
                  min_depth = 300):
    """Run a simple check to flag runs that were potentially numerically unstable.
    This function looks through the final *frames_to_check* frames of a model output
    and checks all cells in AMR level 1 that are below *min_depth* and 
    fall within each region in the *regions_to_check* list (which are intended 
    to encompass individual basins). If the absolute value of the mean surface height
    for these cells, which should not really have much surge, is above/mean_tol_abs, 
    it raises an error.
    
    :Input:
    - *model_output_dir* (str) Path to the output directory for a given model
    - *regions_to_check* (list of lists of floats) A list of 4-element lists
        which define the (left, bottom, right, top) of regions to check within.
    - *frames_to_check* (int) The number of final frames of the model output to check
    - *mean_tol_abs* (float) Model is flagged if the absolute value of the mean surface
        height within any region in *regions_to_check* is above this value (meters).
    - *min_depth* (float) Only cells that are below *min_depth* (meters) are checked, in 
        order to avoid including cells that potentially should have large surge values.
        
    :Raises:
    - InstabilityError if the model is flagged as potentially unstable in one of the regions.
    """
    
    # find which frame is last
    output_files = glob(join(model_output_dir,'fort.b*'))
    last_frame = int(output_files[-1].split('/')[-1][-4:])

    # get sl_init
    with open(join(model_output_dir,'geoclaw.data'),'r') as f:
        for l in f:
            if '=: sea_level' in l:
                sl_init = float(l.strip().split()[0])

    # bring in solution
    soln = Solution()
    for frame in range(last_frame-frames_to_check+1, last_frame+1):
        soln.read(frame, path = model_output_dir, file_format='binary', read_aux=False)

        for r in regions_to_check:
            all_vals = np.array([])
            for s in soln.states:

                # only looking at lowest AMR level
                if s.patch.level >1:
                    continue

                x = s.grid.c_centers[0]
                y = s.grid.c_centers[1]
                eta = s.q[3,:,:]
                topo = eta - s.q[0,:,:]
                
                # only count 
                eta = np.where(topo<(-min_depth),eta,np.nan)
                in_reg = eta[np.ix_((x[:,0]>=r[0]) & (x[:,0]<=r[2]),
                             (y[0,:]>=r[1]) & (y[0,:]<=r[3]))]
                all_vals = np.concatenate([all_vals,in_reg.flatten()])

            # adjust for sl_init
            all_vals = all_vals - sl_init

            if all_vals.shape[0]>0:
                if abs(np.nanmean(all_vals)) > mean_tol_abs:
                    raise InstabilityError("Model possibly unstable due to large magnitude deep "
                                           "ocean surge at end of run ({:.1f} cm in region {})".format(
                                           np.nanmean(all_vals)*100, r))