コード例 #1
0
ファイル: test_grid.py プロジェクト: dham/parcels
def test_moving_eddies_file_subsettime(
        indstime, gridfile='examples/MovingEddies_data/moving_eddies'):
    gridfull = Grid.from_nemo(gridfile, extra_vars={'P': 'P'})
    gridsub = Grid.from_nemo(gridfile,
                             extra_vars={'P': 'P'},
                             indices={'time': indstime})
    assert np.allclose(gridsub.P.time, gridfull.P.time[indstime])
    assert np.allclose(gridsub.P.data, gridfull.P.data[indstime, :, :])
コード例 #2
0
def test_delay_start_example(mode, npart=10, show_movie=False):
    """Example script that shows how to 'delay' the start of particle advection.
    This is useful for example when particles need to be started at different times

    In this example, we use pset.add statements to add one particle every hour
    in the peninsula grid. Note that the title in the movie may not show correct time"""

    grid = Grid.from_nemo('examples/Peninsula_data/peninsula', extra_vars={'P': 'P'})

    # Initialise particles as in the Peninsula example
    x = 3. * (1. / 1.852 / 60)  # 3 km offset from boundary
    y = (grid.U.lat[0] + x, grid.U.lat[-1] - x)  # latitude range, including offsets

    lat = np.linspace(y[0], y[1], npart, dtype=np.float32)
    pset = grid.ParticleSet(0, lon=[], lat=[], pclass=ptype[mode])

    delaytime = delta(hours=1)  # delay time between particle releases
    for t in range(npart):
        pset.add(ptype[mode](lon=x, lat=lat[t], grid=grid))
        pset.execute(AdvectionRK4, runtime=delaytime, dt=delta(minutes=5),
                     interval=delta(hours=1), show_movie=show_movie)

    # Note that time on the movie is not parsed correctly
    pset.execute(AdvectionRK4, runtime=delta(hours=24)-npart*delaytime,
                 dt=delta(minutes=5), interval=delta(hours=1), show_movie=show_movie)

    londist = np.array([(p.lon - x) for p in pset])
    assert(londist > 0.1).all()
コード例 #3
0
def test_peninsula_file(gridfile, mode):
    """Open grid files and execute"""
    grid = Grid.from_nemo(gridfile, extra_vars={'P': 'P'})
    pset = pensinsula_example(grid, 100, mode=mode, degree=1)
    # Test advection accuracy by comparing streamline values
    err_adv = np.array([abs(p.p_start - p.p) for p in pset])
    assert(err_adv <= 1.e-3).all()
    # Test grid sampling accuracy by comparing kernel against grid sampling
    err_smpl = np.array([abs(p.p - pset.grid.P[0., p.lon, p.lat]) for p in pset])
    assert(err_smpl <= 1.e-3).all()
コード例 #4
0
def test_delay_start_example(mode, npart=10, show_movie=False):
    """Example script that shows how to 'delay' the start of particle advection.
    This is useful for example when particles need to be started at different times

    In this example, we use pset.add statements to add one particle every hour
    in the peninsula grid. Note that the title in the movie may not show correct time"""

    grid = Grid.from_nemo('examples/Peninsula_data/peninsula',
                          extra_vars={'P': 'P'},
                          allow_time_extrapolation=True)

    # Initialise particles as in the Peninsula example
    x = 3. * (1. / 1.852 / 60)  # 3 km offset from boundary
    y = (grid.U.lat[0] + x, grid.U.lat[-1] - x
         )  # latitude range, including offsets

    lat = np.linspace(y[0], y[1], npart, dtype=np.float32)
    pset = ParticleSet(grid, lon=[], lat=[], pclass=ptype[mode])

    delaytime = delta(hours=1)  # delay time between particle releases

    # Since we are going to add particles during runtime, we need "indexed" NetCDF file
    output_file = pset.ParticleFile(name="DelayParticle", type="indexed")

    for t in range(npart):
        pset.add(ptype[mode](lon=x, lat=lat[t], grid=grid))
        pset.execute(AdvectionRK4,
                     runtime=delaytime,
                     dt=delta(minutes=5),
                     interval=delta(hours=1),
                     show_movie=show_movie,
                     starttime=delaytime * t,
                     output_file=output_file)

    # Note that time on the movie is not parsed correctly
    pset.execute(AdvectionRK4,
                 runtime=delta(hours=24) - npart * delaytime,
                 starttime=delaytime * npart,
                 dt=delta(minutes=5),
                 interval=delta(hours=1),
                 show_movie=show_movie,
                 output_file=output_file)

    londist = np.array([(p.lon - x) for p in pset])
    assert (londist > 0.1).all()

    # Test whether time was written away correctly in file
    pfile = Dataset("DelayParticle.nc", 'r')
    id = pfile.variables['trajectory'][:]
    time = pfile.variables['time'][id == id[0]]
    assert all(time[1:] - time[0:-1] == time[1] - time[0])
    pfile.close()
コード例 #5
0
def test_grid_from_nemo(xdim, ydim, tmpdir, filename='test_nemo'):
    """ Simple test for grid initialisation from NEMO file format. """
    filepath = tmpdir.join(filename)
    u, v, lon, lat, depth, time = generate_grid(xdim, ydim)
    grid_out = Grid.from_data(u, lon, lat, v, lon, lat, depth, time)
    grid_out.write(filepath)
    grid = Grid.from_nemo(filepath)
    u_t = np.transpose(u).reshape((lat.size, lon.size))
    v_t = np.transpose(v).reshape((lat.size, lon.size))
    assert len(grid.U.data.shape) == 3  # Will be 4 once we use depth
    assert len(grid.V.data.shape) == 3
    assert np.allclose(grid.U.data[0, :], u_t, rtol=1e-12)
    assert np.allclose(grid.V.data[0, :], v_t, rtol=1e-12)
コード例 #6
0
ファイル: test_grid.py プロジェクト: dham/parcels
def test_grid_from_nemo(xdim, ydim, tmpdir, filename='test_nemo'):
    """ Simple test for grid initialisation from NEMO file format. """
    filepath = tmpdir.join(filename)
    u, v, lon, lat, depth, time = generate_grid(xdim, ydim)
    grid_out = Grid.from_data(u, lon, lat, v, lon, lat, depth, time)
    grid_out.write(filepath)
    grid = Grid.from_nemo(filepath)
    u_t = np.transpose(u).reshape((lat.size, lon.size))
    v_t = np.transpose(v).reshape((lat.size, lon.size))
    assert len(grid.U.data.shape) == 3  # Will be 4 once we use depth
    assert len(grid.V.data.shape) == 3
    assert np.allclose(grid.U.data[0, :], u_t, rtol=1e-12)
    assert np.allclose(grid.V.data[0, :], v_t, rtol=1e-12)
コード例 #7
0
ファイル: test_grid.py プロジェクト: dham/parcels
def test_grid_from_file_subsets(indslon,
                                indslat,
                                tmpdir,
                                filename='test_subsets'):
    """ Test for subsetting grid from file using indices dict. """
    u, v, lon, lat, depth, time = generate_grid(100, 100)
    filepath = tmpdir.join(filename)
    gridfull = Grid.from_data(u, lon, lat, v, lon, lat, depth, time)
    gridfull.write(filepath)
    indices = {'lon': indslon, 'lat': indslat}
    gridsub = Grid.from_nemo(filepath, indices=indices)
    assert np.allclose(gridsub.U.lon, gridfull.U.lon[indices['lon']])
    assert np.allclose(gridsub.U.lat, gridfull.U.lat[indices['lat']])
    assert np.allclose(gridsub.V.lon, gridfull.V.lon[indices['lon']])
    assert np.allclose(gridsub.V.lat, gridfull.V.lat[indices['lat']])

    ixgrid = np.ix_([0], indices['lat'], indices['lon'])
    assert np.allclose(gridsub.U.data, gridfull.U.data[ixgrid])
    assert np.allclose(gridsub.V.data, gridfull.V.data[ixgrid])
コード例 #8
0
def test_moving_eddies_file(gridfile, mode):
    grid = Grid.from_nemo(gridfile, extra_vars={'P': 'P'})
    pset = moving_eddies_example(grid, 2, mode=mode)
    assert (pset[0].lon < 0.5 and 46.0 < pset[0].lat < 46.35)
    assert (pset[1].lon < 0.5 and 49.4 < pset[1].lat < 49.8)
コード例 #9
0
                   help='Generate grid file with given dimensions')
    p.add_argument('-m',
                   '--method',
                   choices=('RK4', 'EE', 'RK45'),
                   default='RK4',
                   help='Numerical method used for advection')
    args = p.parse_args()
    filename = 'examples/MovingEddies_data/moving_eddies'

    # Generate grid files according to given dimensions
    if args.grid is not None:
        grid = moving_eddies_grid(args.grid[0], args.grid[1])
        grid.write(filename)

    # Open grid files
    grid = Grid.from_nemo(filename, extra_vars={'P': 'P'})

    if args.profiling:
        from cProfile import runctx
        from pstats import Stats
        runctx(
            "moving_eddies_example(grid, args.particles, mode=args.mode, \
                              verbose=args.verbose, method=method[args.method])",
            globals(), locals(), "Profile.prof")
        Stats("Profile.prof").strip_dirs().sort_stats("time").print_stats(10)
    else:
        moving_eddies_example(grid,
                              args.particles,
                              mode=args.mode,
                              verbose=args.verbose,
                              method=method[args.method])
コード例 #10
0
                   help='Generate grid file with given dimensions')
    p.add_argument('-m',
                   '--method',
                   choices=('RK4', 'EE', 'RK45'),
                   default='RK4',
                   help='Numerical method used for advection')
    args = p.parse_args()
    filename = 'stommel'

    # Generate grid files according to given dimensions
    if args.grid is not None:
        grid = stommel_grid(args.grid[0], args.grid[1])
        grid.write(filename)

    # Open grid files
    grid = Grid.from_nemo(filename)

    if args.profiling:
        from cProfile import runctx
        from pstats import Stats
        runctx(
            "stommel_example(grid, args.particles, mode=args.mode, \
                              verbose=args.verbose)", globals(), locals(),
            "Profile.prof")
        Stats("Profile.prof").strip_dirs().sort_stats("time").print_stats(10)
    else:
        stommel_example(grid,
                        args.particles,
                        mode=args.mode,
                        verbose=args.verbose,
                        method=method[args.method])
コード例 #11
0
def test_moving_eddies_file(gridfile, mode):
    grid = Grid.from_nemo(gridfile, extra_vars={'P': 'P'})
    pset = moving_eddies_example(grid, 2, mode=mode)
    assert(pset[0].lon < 0.5 and 46.0 < pset[0].lat < 46.35)
    assert(pset[1].lon < 0.5 and 49.4 < pset[1].lat < 49.8)
コード例 #12
0
                   help='Number of particles to advect')
    p.add_argument('-v', '--verbose', action='store_true', default=False,
                   help='Print particle information before and after execution')
    p.add_argument('--profiling', action='store_true', default=False,
                   help='Print profiling information after run')
    p.add_argument('-g', '--grid', type=int, nargs=2, default=None,
                   help='Generate grid file with given dimensions')
    p.add_argument('-m', '--method', choices=('RK4', 'EE', 'RK45'), default='RK4',
                   help='Numerical method used for advection')
    args = p.parse_args()
    filename = 'examples/MovingEddies_data/moving_eddies'

    # Generate grid files according to given dimensions
    if args.grid is not None:
        grid = moving_eddies_grid(args.grid[0], args.grid[1])
        grid.write(filename)

    # Open grid files
    grid = Grid.from_nemo(filename, extra_vars={'P': 'P'})

    if args.profiling:
        from cProfile import runctx
        from pstats import Stats
        runctx("moving_eddies_example(grid, args.particles, mode=args.mode, \
                              verbose=args.verbose, method=method[args.method])",
               globals(), locals(), "Profile.prof")
        Stats("Profile.prof").strip_dirs().sort_stats("time").print_stats(10)
    else:
        moving_eddies_example(grid, args.particles, mode=args.mode,
                              verbose=args.verbose, method=method[args.method])
コード例 #13
0
    p.add_argument('-o', '--nooutput', action='store_true', default=False,
                   help='Suppress trajectory output')
    p.add_argument('--profiling', action='store_true', default=False,
                   help='Print profiling information after run')
    p.add_argument('-g', '--grid', type=int, nargs=2, default=None,
                   help='Generate grid file with given dimensions')
    p.add_argument('-m', '--method', choices=('RK4', 'EE', 'RK45'), default='RK4',
                   help='Numerical method used for advection')
    args = p.parse_args()

    if args.grid is not None:
        filename = 'peninsula'
        grid = peninsula_grid(args.grid[0], args.grid[1])
        grid.write(filename)

    # Open grid file set
    grid = Grid.from_nemo('peninsula', extra_vars={'P': 'P'})

    if args.profiling:
        from cProfile import runctx
        from pstats import Stats
        runctx("pensinsula_example(grid, args.particles, mode=args.mode,\
                                   degree=args.degree, verbose=args.verbose,\
                                   output=not args.nooutput, method=method[args.method])",
               globals(), locals(), "Profile.prof")
        Stats("Profile.prof").strip_dirs().sort_stats("time").print_stats(10)
    else:
        pensinsula_example(grid, args.particles, mode=args.mode,
                           degree=args.degree, verbose=args.verbose,
                           output=not args.nooutput, method=method[args.method])
コード例 #14
0
                   help='Number of particles to advect')
    p.add_argument('-v', '--verbose', action='store_true', default=False,
                   help='Print particle information before and after execution')
    p.add_argument('--profiling', action='store_true', default=False,
                   help='Print profiling information after run')
    p.add_argument('-g', '--grid', type=int, nargs=2, default=None,
                   help='Generate grid file with given dimensions')
    p.add_argument('-m', '--method', choices=('RK4', 'EE', 'RK45'), default='RK4',
                   help='Numerical method used for advection')
    args = p.parse_args()
    filename = 'stommel'

    # Generate grid files according to given dimensions
    if args.grid is not None:
        grid = stommel_grid(args.grid[0], args.grid[1])
        grid.write(filename)

    # Open grid files
    grid = Grid.from_nemo(filename)

    if args.profiling:
        from cProfile import runctx
        from pstats import Stats
        runctx("stommel_example(grid, args.particles, mode=args.mode, \
                              verbose=args.verbose)",
               globals(), locals(), "Profile.prof")
        Stats("Profile.prof").strip_dirs().sort_stats("time").print_stats(10)
    else:
        stommel_example(grid, args.particles, mode=args.mode,
                        verbose=args.verbose, method=method[args.method])
コード例 #15
0
ファイル: example_peninsula.py プロジェクト: dham/parcels
    p.add_argument('-o', '--nooutput', action='store_true', default=False,
                   help='Suppress trajectory output')
    p.add_argument('--profiling', action='store_true', default=False,
                   help='Print profiling information after run')
    p.add_argument('-g', '--grid', type=int, nargs=2, default=None,
                   help='Generate grid file with given dimensions')
    p.add_argument('-m', '--method', choices=('RK4', 'EE', 'RK45'), default='RK4',
                   help='Numerical method used for advection')
    args = p.parse_args()

    if args.grid is not None:
        filename = 'peninsula'
        grid = peninsula_grid(args.grid[0], args.grid[1])
        grid.write(filename)

    # Open grid file set
    grid = Grid.from_nemo('peninsula', extra_vars={'P': 'P'}, allow_time_extrapolation=True)

    if args.profiling:
        from cProfile import runctx
        from pstats import Stats
        runctx("pensinsula_example(grid, args.particles, mode=args.mode,\
                                   degree=args.degree, verbose=args.verbose,\
                                   output=not args.nooutput, method=method[args.method])",
               globals(), locals(), "Profile.prof")
        Stats("Profile.prof").strip_dirs().sort_stats("time").print_stats(10)
    else:
        pensinsula_example(grid, args.particles, mode=args.mode,
                           degree=args.degree, verbose=args.verbose,
                           output=not args.nooutput, method=method[args.method])