Esempio n. 1
0
def plot_channel_transport(simulation=None):
    h_files = sorted(glob.glob("{0}output/snap.h.*".format(simulation)))
    v_files = sorted(glob.glob("{0}output/snap.v.*".format(simulation)))

    transport = np.zeros(len(h_files))

    for i in xrange(len(v_files)):
        h = aro.interpret_raw_file(h_files[i], 102, 182, 1)
        v = aro.interpret_raw_file(v_files[i], 102, 182, 1)


        transport[i] = np.sum(h[:,70,0]*(v[:,53,0]+v[:,54,0])/2.)*grid.dx/1e6

    plt.figure()

    if simulation == 'control_final_five/':
        plt.plot(np.arange(360.)*5./360., transport)
        plt.hlines(0,0,5)
        plt.xlabel('Time (years)')
    else:
        plt.plot(transport)
    plt.ylabel('Transport through the channel (Sv)')
    plt.savefig('{0}figures/transport.png'.format(simulation), dpi=150,
        bbox_inches='tight')
    plt.close()
def assert_volume_conservation(nx, ny, layers, rtol):
    hfiles = sorted(glob.glob("output/snap.h.*"))

    h_0 = aro.interpret_raw_file(hfiles[0], nx, ny, layers)
    h_final = aro.interpret_raw_file(hfiles[-1], nx, ny, layers)

    volume_0 = np.zeros((layers))
    volume_final = np.zeros((layers))

    for k in range(layers):
        volume_0[k] = np.sum(h_0[k, :, :])
        volume_final[k] = np.sum(h_final[k, :, :])

        assert np.abs((volume_0[k] - volume_final[k]) / volume_0[k]) < rtol
Esempio n. 3
0
def plt_vort(simulation=None):
    u_files = sorted(glob.glob("{0}output/snap.u.*".format(simulation)))
    v_files = sorted(glob.glob("{0}output/snap.v.*".format(simulation)))

    c_lim = 1

    coriolis = 4.99e-5 + Y_zeta[1:-1, 1:-1] * 2.15e-11

    for i in range(0, len(v_files)):
        u = aro.interpret_raw_file(u_files[i], nx, ny, layers)
        v = aro.interpret_raw_file(v_files[i], nx, ny, layers)

        zeta = (v[0, 1:-1, 1:] - v[0, 1:-1, :-1]) / dx - (u[0, 1:, 1:-1] -
                                                          u[0, :-1, 1:-1]) / dy

        f, ax1 = plt.subplots(1, 1, figsize=(5, 5))

        im = ax1.pcolormesh(X_zeta[1:-1, 1:-1],
                            Y_zeta[1:-1, 1:-1],
                            zeta / coriolis,
                            cmap='RdBu_r',
                            vmin=-c_lim,
                            vmax=c_lim)
        CB = plt.colorbar(im, ax=ax1, orientation='vertical')
        CB.set_label('vorticity/f')

        # ax1.plot(500, 500, 'ro', ms=8)
        # ax1.set_xlim(0,1000)
        ax1.plot(200 * dx / 1e3, 864 * dy / 1e3, 'ko', ms=3)
        ax1.set_aspect('equal')
        ax1.set_xlabel('x (km)')
        ax1.set_ylabel('y (km)')

        plt.title('Year {:02d} Day {:03d}'.format(int(np.floor(i / 4 / 360)),
                                                  int(np.mod(i / 4, 360))))

        f.savefig('{}figures/vort_{:06d}.png'.format(simulation, i),
                  dpi=300,
                  bbox_inches='tight')
        plt.close('all')

    try:
        sub.check_call([
            "ffmpeg", "-pattern_type", "glob", "-i",
            "{0}/figures/vort_*.png".format(simulation), "-vcodec", "libx264",
            "-s", "2400x1540", "-pix_fmt", "yuv420p",
            "{0}/{1}.mp4".format(simulation, 'anim_vort')
        ])
    except:
        print("failed to make vort animation")
def assert_outputs_close(nx, ny, layers, rtol):

    # collct all files with a number in them (i.e. all outputs
    # other than the diagnostic files)
    outfiles = sorted(glob.glob("output/*.0*"))
    good_outfiles = sorted(glob.glob("good-output/*.0*"))

    # assert p.basename(outfiles) == p.basename(good_outfiles)
    test_passes = True
    for i, outfile in enumerate(outfiles):
        ans = aro.interpret_raw_file(outfile, nx, ny, layers)
        good_ans = aro.interpret_raw_file(good_outfiles[i], nx, ny, layers)
        relerr = np.amax(array_relative_error(ans, good_ans))
        if (relerr >= rtol or np.isnan(relerr)):
            print('test failed at {0}'.format(outfile))
            print('rtol = {0}: relerr = {1}'.format(rtol, relerr))
            # print ans
            # print good_ans
            test_passes = False

            fig = plt.figure()
            ax = fig.add_subplot(111)
            plt.pcolormesh(ans[0, :, :])
            plt.colorbar()
            plt.title(outfile)
            ax.set_aspect('equal', 'datalim')
            plt.savefig('current_output_{0}.png'.format(outfile[12:]))
            plt.close()

            fig = plt.figure()
            ax = fig.add_subplot(111)
            plt.pcolormesh(good_ans[0, :, :])
            plt.colorbar()
            plt.title(outfile)
            ax.set_aspect('equal', 'datalim')
            plt.savefig('blessed_output_{0}.png'.format(outfile[12:]))
            plt.close()

            fig = plt.figure()
            ax = fig.add_subplot(111)
            plt.pcolormesh(ans[0, :, :] - good_ans[0, :, :], cmap='RdBu_r')
            plt.colorbar()
            plt.title('current - blessed at {0}'.format(outfile[12:]))
            ax.set_aspect('equal', 'datalim')
            plt.savefig('difference_{0}.png'.format(outfile[12:]))
            plt.close()

    assert test_passes
Esempio n. 5
0
def plt_output(grid, sim_name, colour_lim=2):
    h_files = sorted(glob.glob("../output/snap.h.*"))
    v_files = sorted(glob.glob("../output/snap.v.*"))

    # plot each state of the run

    for i in range(len(v_files)):
        h = aro.interpret_raw_file(h_files[i], grid.nx, grid.ny, grid.layers)
        v = aro.interpret_raw_file(v_files[i], grid.nx, grid.ny, grid.layers)

        X, Y = np.meshgrid(grid.x / 1e3, grid.y / 1e3)

        plt.figure()
        CS = plt.contour(X, Y, h[0, :, :], colors='k')
        plt.clabel(CS, inline=1, inline_spacing=17, fontsize=10, fmt=r'%3.0f')
        X, Y = np.meshgrid(grid.x / 1e3, grid.yp1 / 1e3)

        im = plt.pcolormesh(X,
                            Y,
                            v[0, :, :] * 100.,
                            cmap='RdBu_r',
                            vmin=-colour_lim,
                            vmax=colour_lim)
        im.set_edgecolor('face')
        CB = plt.colorbar()
        CB.set_label('y component of velocity (cm / s)')
        plt.axes().set_aspect('equal')
        plt.xlabel('x coordinate (km)')
        plt.ylabel('y coordinate (km)')
        plt.title('timestep {0}'.format(v_files[i][-10:]))

        plt.savefig('state_{0}.png'.format(v_files[i][-10:]),
                    dpi=150,
                    bbox_inches='tight')
        if i == len(v_files) - 1:
            plt.savefig('{0}.pdf'.format(sim_name),
                        dpi=150,
                        bbox_inches='tight')
        plt.close()

    try:
        sub.check_call([
            "convert", "-delay", "30", "-loop", "0", "state_*.png",
            "{0}.gif".format(sim_name)
        ])
    except:
        print("failed to make animation")
Esempio n. 6
0
def plt_h_cross_section(simulation=None):
    h_files = sorted(glob.glob("{0}output/snap.h.*".format(simulation)))
    h_final = aro.interpret_raw_file(h_files[-1],102,182,1,)

    plt.figure()
    for i in xrange(100,160):
        plt.plot(h_final[:,i,0])
    plt.savefig('{0}figures/h_final.png'.format(simulation))
    plt.close()
Esempio n. 7
0
def plt_state(simulation=None):
    h_files = sorted(glob.glob("{0}output/snap.h.*".format(simulation)))
    v_files = sorted(glob.glob("{0}output/snap.v.*".format(simulation)))

    h_max = np.zeros(len(h_files))

    for i in range(len(v_files)):
        h = aro.interpret_raw_file(h_files[i], 102, 182, 1)
        h_max[i] = np.max(h)

    # plot the final state of the run
    i = len(h_files) - 1
    v = aro.interpret_raw_file(v_files[i], 102, 182, 1)

    X, Y = np.meshgrid(grid.x / 1e3, grid.y / 1e3)

    plt.figure()
    CS = plt.contour(X, Y, h[0, :, :], colors='k')
    plt.clabel(CS, inline=1, fontsize=10)
    X, Y = np.meshgrid(grid.x / 1e3, grid.yp1 / 1e3)

    plt.pcolormesh(X, Y, v[0, :, :] * 100., cmap='RdBu_r', vmin=-2, vmax=2)
    CB = plt.colorbar()
    CB.set_label('y component of velocity (cm / s)')
    plt.xlim(0, 1500)
    plt.axes().set_aspect('equal')
    plt.xlabel('x coordinate (km)')
    plt.ylabel('y coordinate (km)')

    plt.savefig('{0}figures/state_{1}.png'.format(simulation,
                                                  v_files[i][-10:]),
                dpi=150,
                bbox_inches='tight')
    plt.close()

    plt.figure()
    if simulation == 'control_final_five/':
        plt.plot(np.arange(360.) * 5. / 360., h_max)
        plt.xlabel('Time (years)')
    else:
        plt.plot(h_max)
    plt.ylabel('Depth at centre of gyre (m)')
    plt.savefig('{0}figures/h_max.png'.format(simulation), dpi=150)
    plt.close()
Esempio n. 8
0
def plt_h_cross_section(simulation=None):
    h_files = sorted(glob.glob("{0}output/snap.h.*".format(simulation)))
    h_final = aro.interpret_raw_file(h_files[-1], nx, ny, layers)

    plt.figure()
    for i in range(100,160):
        plt.plot(-h_final[0,i,:])
    plt.title('Timestep {}: Day {:05d}'.format(h_files[-1][-10:], len(h_files)))
    plt.savefig('{0}figures/h_final.png'.format(simulation))
    plt.close()

    plt.pcolormesh(X_h, Y_h, h_final[0,:,:])
    plt.colorbar()
    plt.contour(X_h, Y_h, h_final[0,:,:], np.arange(0,800,50), colors='k')
    plt.title('Timestep {}: Day {:05d}'.format(h_files[-1][-10:], len(h_files)))
    plt.savefig('{0}figures/h_final_pcolor.png'.format(simulation))
    plt.close()
Esempio n. 9
0
def test_f_plane_Hypre_botDrag(botDrag=1e-5, layers=1):

    test_executable = "aronnax_external_solver_test"

    dt = 100

    nx = 10
    ny = 10
    dx = 1e3
    dy = 1e3

    rho0 = 1035.

    grid = aro.Grid(nx, ny, layers, dx, dy)

    def init_U(X, Y, *arg):
        init_u = np.zeros(Y.shape, dtype=np.float64)
        init_u[:, :] = 3e-5

        return init_u

    def dbl_periodic_wetmask(X, Y):
        return np.ones(X.shape, dtype=np.float64)

    with working_directory(p.join(self_path, "bot_drag")):

        if layers == 1:
            drv.simulate(initHfile=[400.],
                         initUfile=[init_U],
                         depthFile=[layers * 400],
                         exe=test_executable,
                         wetMaskFile=[dbl_periodic_wetmask],
                         nx=nx,
                         ny=ny,
                         dx=dx,
                         dy=dy,
                         dt=dt,
                         dumpFreq=200,
                         diagFreq=dt,
                         botDrag=botDrag,
                         nTimeSteps=400)
        else:
            drv.simulate(initHfile=[400. for i in range(layers)],
                         initUfile=[init_U for i in range(layers)],
                         depthFile=[layers * 400],
                         exe=test_executable,
                         wetMaskFile=[dbl_periodic_wetmask],
                         nx=nx,
                         ny=ny,
                         layers=layers,
                         dx=dx,
                         dy=dy,
                         dt=dt,
                         dumpFreq=200,
                         diagFreq=dt,
                         botDrag=botDrag,
                         nTimeSteps=400)

        hfiles = sorted(glob.glob("output/snap.h.*"))
        ufiles = sorted(glob.glob("output/snap.u.*"))
        vfiles = sorted(glob.glob("output/snap.v.*"))

        model_iteration = np.zeros(len(hfiles))

        momentum = np.zeros(len(hfiles))
        momentum_expected = np.zeros(len(hfiles))

        for counter, ufile in enumerate(ufiles):

            h = aro.interpret_raw_file(hfiles[counter], nx, ny, layers)
            u = aro.interpret_raw_file(ufile, nx, ny, layers)
            v = aro.interpret_raw_file(vfiles[counter], nx, ny, layers)

            model_iteration[counter] = float(ufile[-10:])

            momentum[counter] = (
                nx * ny * dx * dy * rho0 *
                (np.mean(h[-1, :, :]) *
                 (np.mean(u[-1, :, :]) + np.mean(v[-1, :, :]))))

        opt.assert_volume_conservation(nx, ny, layers, 1e-9)

        init_h = 400
        X, Y = np.meshgrid(grid.x, grid.yp1)
        init_u = init_U(X, Y)

        momentum_expected[:] = (nx * ny * dx * dy * rho0 *
                                (np.mean(init_h) * np.mean(init_u[:, :])) *
                                np.exp(-model_iteration * dt * botDrag))

        test_passes = True

        try:
            np.testing.assert_allclose(momentum,
                                       momentum_expected,
                                       rtol=2e-3,
                                       atol=0)
            return
        except AssertionError as error:
            test_passes = False

            # plot output for visual inspection
            plt.figure()
            plt.plot(model_iteration * dt / (86400),
                     momentum,
                     '-',
                     alpha=1,
                     label='Simulated momentum')
            plt.plot(model_iteration * dt / (86400),
                     momentum_expected,
                     '-',
                     alpha=1,
                     label='Expected momentum')
            plt.legend()
            plt.xlabel('Time (days)')
            plt.ylabel('Momentum')
            plt.savefig('f_plane_momentum_test.png', dpi=150)

            plt.figure()
            plt.plot(model_iteration, momentum / momentum_expected)
            plt.xlabel('timestep')
            plt.ylabel('simulated/expected')
            plt.savefig('momentum_ratio.png')
            plt.close()

            plt.figure()
            plt.plot(model_iteration * dt / (86400),
                     100. * (momentum - momentum_expected) / momentum_expected)
            plt.xlabel('Time (days)')
            plt.ylabel('percent error')
            plt.ylim(-20, 80)
            plt.savefig('momentum_percent_error.png')
            plt.close()

        assert test_passes
Esempio n. 10
0
def plt_state(simulation=None):
    h_files = sorted(glob.glob("{0}output/snap.h.*".format(simulation)))
    v_files = sorted(glob.glob("{0}output/snap.v.*".format(simulation)))

    h_max = np.zeros(len(h_files))

    for i in range(len(v_files)):
        h = aro.interpret_raw_file(h_files[i], nx, ny, layers)
        h_max[i] = h[0,100,100] #np.max(h[0,:,:])
    
    years = np.arange(len(h_max))/360
    plt.figure()
    plt.plot(years, h_max)
    plt.ylabel('Depth at centre of gyre (m)')
    plt.xlabel('Time (years)')
    plt.savefig('{0}figures/h_max.png'.format(simulation), dpi=300)
    plt.close()

    for i in range(0, len(v_files)):
        h = aro.interpret_raw_file(h_files[i], nx, ny, layers)

        v = aro.interpret_raw_file(v_files[i], nx, ny, layers)

        f, (ax1, ax2) = plt.subplots(1, 2, figsize=(10,5))
        ax1.pcolormesh(X_h, Y_h, np.ma.masked_where(mask_h==1, mask_h), cmap='YlOrBr_r',
            vmin=0, vmax=1)
        ax1.contour(X_h, Y_h, h[0,:,:], np.arange(0,800,50), colors='k')

        im = ax1.pcolormesh(X_v, Y_v, np.ma.masked_where(mask_v==0, v[0,:,:]*100.),
            cmap='RdBu_r', vmin = -75, vmax = 75)
        CB = plt.colorbar(im, ax=ax1, orientation='horizontal')
        CB.set_label('y component of velocity (cm / s)')

        ax1.plot(500, 500, 'ro', ms=8)
        ax1.set_xlim(0,1000)
        ax1.set_aspect('equal')
        ax1.set_xlabel('x coordinate (km)')
        ax1.set_ylabel('y coordinate (km)')

        ax2.plot(years, h_max)
        ax2.plot(years[i], h_max[i], 'ro', ms=8)
        ax2.set_ylabel('Depth at centre of gyre (m)')
        ax2.set_xlabel('Time (years)')

        f.suptitle('Year {:02d} Day {:03d} (Timestep {})'.format(
            int(np.floor(i/360)), int(np.mod(i, 360)), v_files[i][-10:]))

        f.savefig('{}figures/state_L0_{:06d}.png'.format(simulation,i), dpi=300,
            bbox_inches='tight')
        plt.close('all')


        plt.figure()
        plt.pcolormesh(X_h, Y_h, np.ma.masked_where(mask_h==1, mask_h), cmap='YlOrBr_r',
            vmin=0, vmax=1)
        plt.contour(X_h, Y_h, h[1,:,:], np.arange(0,5000,500),
            colors='k')

        plt.pcolormesh(X_v, Y_v, np.ma.masked_where(mask_v==0, v[1,:,:]*100.),
            cmap='RdBu_r', vmin = -15, vmax = 15)
        CB = plt.colorbar()
        CB.set_label('y component of velocity (cm / s)')
        plt.xlim(0,1500)
        plt.axes().set_aspect('equal')
        plt.xlabel('x coordinate (km)')
        plt.ylabel('y coordinate (km)')
        plt.title('Timestep {}: Day {:05d}'.format(v_files[i][-10:], i))

        plt.savefig('{}figures/state_L1_{:06d}.png'.format(simulation,i), dpi=300,
            bbox_inches='tight')
        plt.close()

    try:
        sub.check_call(["ffmpeg", "-pattern_type", "glob", "-i",
            "{0}/figures/state_L0_*.png".format(simulation),
            "{0}/{1}.mp4".format(simulation, 'anim_L0')])
    except:
        print("failed to make L0 animation")

    try:
        sub.check_call(["ffmpeg", "-pattern_type", "glob", "-i",
            "{0}/figures/state_L1_*.png".format(simulation),
            "{0}/{1}.mp4".format(simulation, 'anim_L1')])
    except:
        print("failed to make L1 animation")
Esempio n. 11
0
def f_plane_init_u_test(physics, aro_exec, dt):
    nx = 100
    ny = 100
    layers = 1

    dx = 10e3
    dy = 10e3

    rho0 = 1035.

    grid = aro.Grid(nx, ny, layers, dx, dy)

    def init_U(X, Y, *arg):
        init_u = np.zeros(Y.shape, dtype=np.float64)
        init_u[int(grid.nx / 2), int(grid.ny / 2)] = 3e-5
        init_u[:, :] = 3e-5

        if not arg:
            plt.figure()
            plt.pcolormesh(init_u)
            plt.colorbar()
            plt.savefig('init_u.png')
        return init_u

    def init_V(X, Y, *arg):
        init_v = np.zeros(X.shape, dtype=np.float64)
        init_v[int(nx / 2), int(ny / 2)] = 3e-5
        init_v[:, :] = 3e-5

        if not arg:
            plt.figure()
            plt.pcolormesh(init_v)
            plt.colorbar()
            plt.savefig('init_v.png')
        return init_v

    def dbl_periodic_wetmask(X, Y):
        return np.ones(X.shape, dtype=np.float64)

    with working_directory(
            p.join(self_path,
                   "physics_tests/f_plane_{0}_init_u".format(physics))):

        sub.check_call(["rm", "-rf", "output/"])
        drv.simulate(
            initHfile=[400.],
            initUfile=[init_U],
            # initVfile=[init_V], valgrind=False,
            wetMaskFile=[dbl_periodic_wetmask],
            nx=nx,
            ny=ny,
            exe=aro_exec,
            dx=dx,
            dy=dy,
            nTimeSteps=40000)

        hfiles = sorted(glob.glob("output/snap.h.*"))
        ufiles = sorted(glob.glob("output/snap.u.*"))
        vfiles = sorted(glob.glob("output/snap.v.*"))

        model_iteration = np.zeros(len(hfiles))

        energy = np.zeros(len(hfiles))
        energy_expected = np.zeros(len(hfiles))

        momentum = np.zeros(len(hfiles))
        momentum_expected = np.zeros(len(hfiles))

        volume = np.zeros(len(hfiles))

        for counter, ufile in enumerate(ufiles):

            h = aro.interpret_raw_file(hfiles[counter], nx, ny, layers)
            u = aro.interpret_raw_file(ufile, nx, ny, layers)
            v = aro.interpret_raw_file(vfiles[counter], nx, ny, layers)

            model_iteration[counter] = float(ufile[-10:])

            # plt.figure()
            # plt.pcolormesh(grid.xp1,grid.y,u[:,:,0].transpose())
            # plt.colorbar()
            # plt.savefig('u.{0}.png'.format(ufile[-10:]),dpi=150)
            # plt.close()

            # plt.figure()
            # plt.pcolormesh(grid.x,grid.y,h[:,:,0].transpose())
            # plt.colorbar()
            # plt.savefig('h.{0}.png'.format(ufile[-10:]),dpi=150)
            # plt.close()

            energy[counter] = nx * ny * (dx * dy * rho0 * (np.sum(
                np.absolute(h * (u[:, :, 1:]**2 + u[:, :, :-1]**2) / 4.) /
                2.) + np.sum(
                    np.absolute(h *
                                (v[:, 1:, :]**2 + v[:, :-1, :]**2) / 4.) / 2.))
                                         + dx * dy * rho0 * 0.01 *
                                         np.sum(np.absolute(h - 400.)))

            momentum[counter] = nx * ny * dx * dy * rho0 * (
                np.sum(np.absolute(h * (u[:, :, 1:] + u[:, :, :-1]) / 2.)) +
                np.sum(np.absolute(h * (v[:, 1:, :] + v[:, :-1, :]) / 2.)))

            volume[counter] = np.sum(h)

            # plt.figure()
            # plt.pcolormesh(grid.xp1, grid.y, np.transpose(u[:,:,0]))
            # plt.colorbar()
            # plt.savefig('output/u.{0}.png'.format(model_iteration[counter]),dpi=100)
            # plt.close()

        opt.assert_volume_conservation(nx, ny, layers, 1e-9)

        X, Y = np.meshgrid(grid.xp1, grid.y)
        init_u = aro.interpret_raw_file(ufiles[1], nx, ny,
                                        layers)  #init_U(X, Y, True)

        X, Y = np.meshgrid(grid.x, grid.yp1)
        init_v = aro.interpret_raw_file(vfiles[1], nx, ny,
                                        layers)  #init_V(X, Y, True)

        energy_expected[:] = nx * ny * (dx * dy * rho0 * (np.sum(
            np.absolute(400. *
                        (init_u[:, :, 1:]**2 + init_u[:, :, :-1]**2) / 4.) /
            2.) + np.sum(
                np.absolute(400. *
                            (init_v[:, 1:, :]**2 + init_v[:, :-1, :]**2) / 4.)
                / 2.)))

        momentum_expected[:] = nx * ny * dx * dy * rho0 * (
            np.sum(np.absolute(h *
                               (init_u[:, :, 1:] + init_u[:, :, :-1]) / 2.)) +
            np.sum(np.absolute(h *
                               (init_v[:, 1:, :] + init_v[:, :-1, :]) / 2.)))

        # print momentum[0]/momentum_expected[0]

        #assert np.amax(array_relative_error(ans, good_ans)) < rtol
        plt.figure()
        #plt.plot(model_iteration, energy_expected, '-o', alpha=0.5,
        #        label='Expected energy')
        plt.plot(model_iteration * dt / (86400),
                 energy,
                 '-',
                 alpha=1,
                 label='Simulated energy')
        plt.legend()
        plt.xlabel('Time (days)')
        plt.ylabel('Energy')
        plt.savefig('f_plane_energy_test.png', dpi=150)

        plt.figure()
        plt.plot(model_iteration * dt / (86400), energy / energy_expected)
        plt.xlabel('timestep')
        plt.ylabel('simulated/expected')
        plt.savefig('energy_ratio.png')
        plt.close()

        plt.figure()
        plt.plot(model_iteration, volume)
        plt.ylabel('Volume')
        plt.xlabel('timestep')
        plt.savefig('volume.png')
        plt.close()

        plt.figure()
        plt.plot(model_iteration * dt / (86400),
                 momentum,
                 '-',
                 alpha=1,
                 label='Simulated momentum')
        plt.legend()
        plt.xlabel('Time (days)')
        plt.ylabel('Momentum')
        plt.savefig('f_plane_momentum_test.png', dpi=150)

        plt.figure()
        plt.plot(model_iteration, momentum / momentum_expected)
        plt.xlabel('timestep')
        plt.ylabel('simulated/expected')
        plt.savefig('momentum_ratio.png')
        plt.close()

        plt.figure()
        plt.plot(model_iteration * dt / (86400),
                 100. * (momentum - momentum_expected) / momentum_expected)
        plt.xlabel('Time (days)')
        plt.ylabel('percent error')
        plt.ylim(-20, 80)
        plt.savefig('momentum_percent_error.png')
        plt.close()
Esempio n. 12
0
def f_plane_wind_test(physics, aro_exec, nx, ny, dx, dy, dt, nTimeSteps):

    layers = 1
    grid = aro.Grid(nx, ny, layers, dx, dy)

    rho0 = 1035.

    def wind_x(X, Y, *arg):
        wind_x = np.zeros(Y.shape, dtype=np.float64)
        wind_x[int(grid.nx / 2), int(grid.ny / 2)] = 1e-5

        if not arg:
            plt.figure()
            plt.pcolormesh(X / 1e3, Y / 1e3, wind_x)
            plt.colorbar()
            plt.savefig('wind_x.png')
            plt.close()
        return wind_x

    def wind_y(X, Y, *arg):
        wind_y = np.zeros(X.shape, dtype=np.float64)
        wind_y[int(grid.nx / 2), int(grid.ny / 2)] = 1e-5

        if not arg:
            plt.figure()
            plt.pcolormesh(X / 1e3, Y / 1e3, wind_y)
            plt.colorbar()
            plt.savefig('wind_y.png')
            plt.close()
        return wind_y

    def dbl_periodic_wetmask(X, Y):
        return np.ones(X.shape, dtype=np.float64)

    with opt.working_directory(
            p.join(self_path,
                   "physics_tests/f_plane_{0}_wind".format(physics))):

        sub.check_call(["rm", "-rf", "output/"])
        drv.simulate(initHfile=[400.],
                     zonalWindFile=[wind_x],
                     meridionalWindFile=[wind_y],
                     valgrind=False,
                     nx=nx,
                     ny=ny,
                     exe=aro_exec,
                     dx=dx,
                     dy=dy,
                     wetMaskFile=[dbl_periodic_wetmask],
                     dt=dt,
                     dumpFreq=int(dt * nTimeSteps / 50),
                     nTimeSteps=nTimeSteps)

        hfiles = sorted(glob.glob("output/snap.h.*"))
        ufiles = sorted(glob.glob("output/snap.u.*"))
        vfiles = sorted(glob.glob("output/snap.v.*"))

        # expect the momentum to grow according to u*h*rho0 = delta_t * wind
        # F = m * a
        # m * v = h * rho0 * xlen * ylen * v
        #       = m * a * dt
        #       = F * dt
        #       = wind * dx * dy * dt

        momentum = np.zeros(len(hfiles), dtype=np.float64)
        model_iteration = np.zeros(len(hfiles), dtype=np.float64)

        momentum_expected = np.zeros(len(hfiles), dtype=np.float64)

        volume = np.zeros(len(hfiles))

        for counter, ufile in enumerate(ufiles):

            h = aro.interpret_raw_file(hfiles[counter], nx, ny, layers)
            u = aro.interpret_raw_file(ufile, nx, ny, layers)
            v = aro.interpret_raw_file(vfiles[counter], nx, ny, layers)

            model_iteration[counter] = float(ufile[-10:])

            # plt.figure()
            # plt.pcolormesh(grid.xp1,grid.y,u[:,:,0].transpose())
            # plt.colorbar()
            # plt.savefig('u.{0}.png'.format(ufile[-10:]),dpi=150)
            # plt.close()

            # plt.figure()
            # plt.pcolormesh(grid.x,grid.y,h[:,:,0].transpose())
            # plt.colorbar()
            # plt.savefig('h.{0}.png'.format(ufile[-10:]),dpi=150)
            # plt.close()

            momentum[counter] = dx * dy * rho0 * (
                np.sum(np.absolute(h * (u[:, :, 1:] + u[:, :, :-1]) / 2.)) +
                np.sum(np.absolute(h * (v[:, 1:, :] + v[:, :-1, :]) / 2.)))

            momentum_expected[counter] = 2. * dx * dy * 1e-5 * (
                model_iteration[counter] + 2) * dt

            volume[counter] = np.sum(dx * dy * h)

            # plt.figure()
            # plt.pcolormesh(grid.xp1, grid.y, np.transpose(u[:,:,0]))
            # plt.colorbar()
            # plt.savefig('output/u.{0}.png'.format(model_iteration[counter]),dpi=100)
            # plt.close()

        opt.assert_volume_conservation(nx, ny, layers, 1e-9)

        plt.figure()
        plt.plot(model_iteration * dt / (30 * 86400),
                 momentum_expected,
                 '-',
                 alpha=1,
                 label='Expected momentum')
        plt.plot(model_iteration * dt / (30 * 86400),
                 momentum,
                 '-',
                 alpha=1,
                 label='Simulated momentum')
        plt.legend()
        plt.xlabel('Time (months)')
        plt.ylabel('Momentum')
        plt.savefig('f_plane_momentum_test.png', dpi=150)
        plt.close()

        plt.figure()
        plt.plot(model_iteration, momentum / momentum_expected)
        plt.xlabel('timestep')
        plt.ylabel('simulated/expected')
        plt.title('final ratio = {0}'.format(
            str(momentum[-1] / momentum_expected[-1])))
        plt.savefig('ratio.png')
        plt.close()

        plt.figure()
        plt.plot(model_iteration,
                 100. * (momentum - momentum_expected) / momentum_expected)
        plt.xlabel('timestep')
        plt.ylabel('percent error')
        plt.ylim(-4, 4)
        plt.savefig('percent_error.png')
        plt.close()

        plt.figure()
        plt.plot(model_iteration, momentum - momentum_expected)
        plt.xlabel('timestep')
        plt.ylabel('simulated - expected')
        plt.savefig('difference.png')
        plt.close()

        plt.figure()
        plt.plot(model_iteration, volume)
        plt.ylabel('Volume')
        plt.xlabel('timestep')
        plt.ylim(np.min(volume), np.max(volume))
        plt.savefig('volume.png')
        plt.close()

        percent_error = 100. * (momentum -
                                momentum_expected) / momentum_expected

        return percent_error[-1]
X_h, Y_h = np.meshgrid(grid.x, grid.y)
mask_h = wetmask(X_h, Y_h)
X_v, Y_v = np.meshgrid(grid.x, grid.yp1)
mask_v = wetmask(X_v, Y_v)

depth = bathymetry(X_h, Y_h)

file_path = "/Users/doddridge/Documents/Edward/Code/aronnax/reproductions/Yang_et_al_2016/spin_up/output/"

h_files = sorted(glob.glob(p.join(file_path, 'snap.h.*')))
eta_files = sorted(glob.glob(p.join(file_path, 'snap.eta.*')))
u_files = sorted(glob.glob(p.join(file_path, 'snap.u.*')))
v_files = sorted(glob.glob(p.join(file_path, 'snap.v.*')))

h_final = aro.interpret_raw_file(h_files[-1], nx, ny, layers)
h_masked = np.ma.masked_where(mask_h == 0, h_final[0, :, :])
u_final = aro.interpret_raw_file(u_files[-1], nx, ny, layers)
v_final = aro.interpret_raw_file(v_files[-1], nx, ny, layers)

speed = np.sqrt((u_final[0, :, :-1] + u_final[0, :, 1:])**2 +
                (v_final[0, 1:, :] + v_final[0, :-1, :])**2)
speed[mask_h == 0] = np.nan

eta_final = aro.interpret_raw_file(eta_files[-1], nx, ny, 1)
eta_masked = np.ma.masked_where(mask_h == 0, eta_final[0, :, :]) * 1e2
eta_masked = eta_masked - np.min(eta_masked)

data = [
    go.Surface(x=grid.x / 1e3,
               y=grid.y / 1e3,