Exemple #1
0
def run_mitgcm_zonally_reentrant(mode):
    """Function that shows how to load MITgcm data in a zonally periodic domain"""

    data_path = path.join(path.dirname(__file__), "MITgcm_example_data/")
    filenames = {
        "U": data_path + "mitgcm_UV_surface_zonally_reentrant.nc",
        "V": data_path + "mitgcm_UV_surface_zonally_reentrant.nc",
    }
    variables = {"U": "UVEL", "V": "VVEL"}
    dimensions = {
        "U": {
            "lon": "XG",
            "lat": "YG",
            "time": "time"
        },
        "V": {
            "lon": "XG",
            "lat": "YG",
            "time": "time"
        },
    }
    fieldset = FieldSet.from_mitgcm(filenames,
                                    variables,
                                    dimensions,
                                    mesh="flat")

    fieldset.add_periodic_halo(zonal=True)
    fieldset.add_constant('domain_width', 1000000)

    def periodicBC(particle, fieldset, time):
        if particle.lon < 0:
            particle.lon += fieldset.domain_width
        elif particle.lon > fieldset.domain_width:
            particle.lon -= fieldset.domain_width

    # Release particles 5 cells away from the Eastern boundary
    pset = ParticleSet.from_line(
        fieldset,
        pclass=ptype[mode],
        start=(fieldset.U.grid.lon[-5], fieldset.U.grid.lat[5]),
        finish=(fieldset.U.grid.lon[-5], fieldset.U.grid.lat[-5]),
        size=10,
    )
    pfile = ParticleFile("MIT_particles_" + str(mode) + ".nc",
                         pset,
                         outputdt=delta(days=1))
    kernels = AdvectionRK4 + pset.Kernel(periodicBC)
    pset.execute(kernels,
                 runtime=delta(days=5),
                 dt=delta(minutes=30),
                 output_file=pfile)
    pfile.close()
Exemple #2
0
def run_microbes_eac(outfile, startdate):
    fieldset = set_hycom_fieldset(t0=startdate)
    fieldset.add_constant('maxage', 90. * 86400)
    fieldset.Kh = 100.  # diffusion constant

    i0 = len(fieldset.U.time)

    nperloc = 100
    sitelat38 = np.tile([-32.788], [nperloc])
    sitelon38 = np.tile([153.785], [nperloc])
    sitelat40 = np.tile([-30.621], [nperloc])
    sitelon40 = np.tile([153.371], [nperloc])

    class MicrobeParticle(JITParticle):
        temp = Variable('temp', dtype=np.float32, initial=fieldset.temp)
        age = Variable('age', dtype=np.float32, initial=0.)

    pset = {}
    pfile = {}
    pset[40] = ParticleSet(fieldset=fieldset,
                           pclass=MicrobeParticle,
                           lon=sitelon40,
                           lat=sitelat40,
                           time=fieldset.U.time[-1])
    pfile[40] = ParticleFile(outfile + '40', pset[40])
    pfile[40].write(pset[40], pset[40][0].time)

    kernels = pset[40].Kernel(
        AdvectionRK4) + BrownianDiffusion + SampleTemp + Age

    for s in range(i0, 90, 1):
        if s is i0 + 1:
            pset[38] = ParticleSet(fieldset=fieldset,
                                   pclass=MicrobeParticle,
                                   lon=sitelon38,
                                   lat=sitelat38,
                                   time=fieldset.U.time[-1])
            pfile[38] = ParticleFile(outfile + '38', pset[38])
            pfile[38].write(pset[38], pset[38][0].time)
        for p in pset:
            pset[p].execute(
                kernels,
                starttime=pset[p][0].time,
                runtime=delta(days=1),
                dt=delta(minutes=-5),
                recovery={ErrorCode.ErrorOutOfBounds: DeleteParticle})
            pfile[p].write(pset[p], pset[p][0].time)
        fieldset.advancetime(set_hycom_fieldset(t0=startdate, t=s))
Exemple #3
0
def run_corefootprintparticles(dirwrite,outfile,lonss,lonsz,latss,latsz,dep):
    
    snapshots = snapshot_function(date(2000, 1, 3), date(2005, 12, 29), delta(days=3))
    fieldset = set_ofes_fieldset(snapshots)
    fieldset.add_periodic_halo(zonal=True)
    fieldset.add_constant('dwellingdepth', np.float(dd))
    fieldset.add_constant('maxage', 300000.*86400)
    fieldset.add_constant('surface', 2.6)

    class FixParticle(JITParticle):
        temp = Variable('temp', dtype=np.float32, initial=np.nan)
        age = Variable('age', dtype=np.float32, initial=0., to_write = False)
        salin = Variable('salin', dtype=np.float32, initial=np.nan)
  

    psets = ParticleSet.from_list(fieldset=fieldset, pclass=FixParticle, 
                                  lon=lonsz.tolist(), lat=latsz.tolist(),
                                     depth=dep, time = np.datetime64('2005-12-25'))#
    

    pfiles = ParticleFile(dirwrite + 'surface' + outfile, psets, outputdt=delta(days=3))

    kernelss =   psets.Kernel(SampleSurf) + psets.Kernel(Age) 

    psets.execute(kernelss, runtime=delta(days=2170), dt=delta(days=-1), output_file=pfiles, recovery={ErrorCode.ErrorOutOfBounds: DeleteParticle})
Exemple #4
0
def run_nemo_curvilinear(mode, outfile):
    """Function that shows how to read in curvilinear grids, in this case from NEMO"""
    data_path = path.join(path.dirname(__file__), 'NemoCurvilinear_data/')

    filenames = {'U': {'lon': data_path + 'mesh_mask.nc4',
                       'lat': data_path + 'mesh_mask.nc4',
                       'data': data_path + 'U_purely_zonal-ORCA025_grid_U.nc4'},
                 'V': {'lon': data_path + 'mesh_mask.nc4',
                       'lat': data_path + 'mesh_mask.nc4',
                       'data': data_path + 'V_purely_zonal-ORCA025_grid_V.nc4'}}
    variables = {'U': 'U', 'V': 'V'}
    dimensions = {'lon': 'glamf', 'lat': 'gphif'}
    field_set = FieldSet.from_nemo(filenames, variables, dimensions)

    # Now run particles as normal
    npart = 20
    lonp = 30 * np.ones(npart)
    latp = [i for i in np.linspace(-70, 88, npart)]

    def periodicBC(particle, fieldSet, time):
        if particle.lon > 180:
            particle.lon -= 360

    pset = ParticleSet.from_list(field_set, ptype[mode], lon=lonp, lat=latp)
    pfile = ParticleFile(outfile, pset, outputdt=delta(days=1))
    kernels = pset.Kernel(AdvectionRK4) + periodicBC
    pset.execute(kernels, runtime=delta(days=1)*160, dt=delta(hours=6),
                 output_file=pfile)
    assert np.allclose([pset[i].lat - latp[i] for i in range(len(pset))], 0, atol=2e-2)
def compute_OFAM_particle_advection(field_set, mode, lonp, latp):
    def DeleteParticle(particle, fieldset, time):
        particle.delete()

    def RenewParticle(particle, fieldset, time):
        # particle.lon = random.random() * 360.0
        particle.lon = -20.0 - 5.0 + random.random() * 2.0 * 5.0
        particle.lat = -75.0 + random.random() * 2.0 * 75.0
        particle.state = ErrorCode.Evaluate

    def periodicBC(particle, fieldSet, time):
        dlon = 360.0
        dlat = 75.0 + 75.0
        if particle.lon > 360.0:
            particle.lon -= dlon
        if particle.lon < 0.0:
            particle.lon += dlon
        if particle.lat > 75.0:
            particle.lat -= dlat
        if particle.lat < -75.0:
            particle.lat += dlat

    pset = ParticleSet.from_list(field_set, ptype[mode], lon=lonp, lat=latp)
    pfile = ParticleFile("OFAM_particles_chunk", pset, outputdt=delta(days=7))
    kernels = pset.Kernel(periodicBC) + pset.Kernel(AdvectionRK4_3D)
    pset.execute(kernels,
                 runtime=delta(days=60),
                 dt=delta(hours=12),
                 output_file=pfile,
                 recovery={ErrorCode.ErrorOutOfBounds: DeleteParticle})
    return pset
Exemple #6
0
def run_corefootprintparticles(outfile):
    snapshots = range(3165, 3288)
    fieldset = set_ofes_fieldset(snapshots)
    fieldset.add_constant('dwellingdepth', 50.)
    fieldset.add_constant('sinkspeed', 200. / 86400)
    fieldset.add_constant('maxage', 30. * 86400)

    corelon = [17.30]
    corelat = [-34.70]
    coredepth = [2440]

    class ForamParticle(JITParticle):
        temp = Variable('temp', dtype=np.float32, initial=fieldset.temp)
        age = Variable('age', dtype=np.float32, initial=0.)

    pset = ParticleSet(
        fieldset=fieldset,
        pclass=ForamParticle,
        lon=corelon,
        lat=corelat,
        depth=coredepth,
        time=fieldset.U.grid.time[-1],
        repeatdt=delta(days=3)
    )  # the new argument 'repeatdt' means no need to call pset.add() anymore in for-loop
    pfile = ParticleFile(outfile, pset, outputdt=delta(
        days=1))  # `interval` argument has changed to `outputdt`

    kernels = pset.Kernel(AdvectionRK4_3D) + Sink + SampleTemp + Age

    pset.execute(kernels,
                 dt=delta(minutes=-5),
                 output_file=pfile,
                 recovery={ErrorCode.ErrorOutOfBounds: DeleteParticle})
def run_corefootprintparticles(dirwrite,outfile,lonss,lonsz,latss,latsz,dep,time):
    
    snapshots = snapshot_function(date(2000, 1, 3), date(2005, 12, 29), delta(days=3))
    fieldset = set_ofes_fieldset(snapshots)
    fieldset.add_periodic_halo(zonal=True)
    fieldset.B.allow_time_extrapolation = True
    fieldset.add_constant('dwellingdepth', np.float(dd))
#constants needed for the sinking. Linear increase between 100m and 2000m from 6m/day to 45m/day 
    fieldset.add_constant('sp_depth1', np.float(increasedepth))
    fieldset.add_constant('sp_depth2', np.float(spconstantdepth))
    fieldset.add_constant('sinkspeed', sp/86400.)
    fieldset.add_constant('sinkspeed2', spd/86400.)

    fieldset.add_constant('maxage', 300000.*86400)
    fieldset.add_constant('surface', 2.6)

    class DinoOfesParticle(JITParticle):
        temp = Variable('temp', dtype=np.float32, initial=np.nan)
        age = Variable('age', dtype=np.float32, initial=0.)
        salin = Variable('salin', dtype=np.float32, initial=np.nan)
        lon0 = Variable('lon0', dtype=np.float32, initial=0.)
        lat0 = Variable('lat0', dtype=np.float32, initial=0.)
        depth0 = Variable('depth0',dtype=np.float32, initial=0., to_write=False)
        time0 = Variable('time0',dtype=np.float32, initial=0., to_write=False)
  
    pset = ParticleSet.from_list(fieldset=fieldset, pclass=DinoOfesParticle, lon=lonss.tolist(), lat=latss.tolist(), time = time) #depth=depths, 

    pfile = ParticleFile(dirwrite + outfile, pset, write_ondelete=True)

    kernels = pset.Kernel(initials) + Sink  + pset.Kernel(AdvectionRK4_3D) + Age + periodicBC 

    pset.execute(kernels, runtime=delta(days=2170), dt=delta(minutes=-60), output_file=pfile, recovery={ErrorCode.ErrorOutOfBounds: DeleteParticle})
Exemple #8
0
def convert_npydir_to_netcdf(tempwritedir):
    """Convert npy files in tempwritedir to a NetCDF file
    :param tempwritedir: directory where the temporary npy files are stored (can be obtained from ParticleFile.tempwritedir attribute)
    """

    pyset_file = path.join(tempwritedir, 'pset_info.npy')
    if not path.isdir(tempwritedir):
        raise ValueError('Output directory "%s" does not exist' % tempwritedir)
    if not path.isfile(pyset_file):
        raise ValueError(
            'Output directory "%s" does not contain a pset_info.npy file' %
            tempwritedir)

    pset_info = np.load(pyset_file, allow_pickle=True).item()
    pfile = ParticleFile(None, None, pset_info=pset_info)
    pfile.export()
    pfile.dataset.close()
Exemple #9
0
def convert_npydir_to_netcdf(tempwritedir_base, delete_tempfiles=False):
    """Convert npy files in tempwritedir to a NetCDF file
    :param tempwritedir_base: directory where the directories for temporary npy files
            are stored (can be obtained from ParticleFile.tempwritedir_base attribute)
    """

    tempwritedir = sorted(glob(path.join("%s" % tempwritedir_base, "*")),
                          key=lambda x: int(path.basename(x)))[0]
    pyset_file = path.join(tempwritedir, 'pset_info.npy')
    if not path.isdir(tempwritedir):
        raise ValueError('Output directory "%s" does not exist' % tempwritedir)
    if not path.isfile(pyset_file):
        raise ValueError('Output directory "%s" does not contain a pset_info.npy file' % tempwritedir)

    pset_info = np.load(pyset_file, allow_pickle=True).item()
    pfile = ParticleFile(None, None, pset_info=pset_info, tempwritedir=tempwritedir_base, convert_at_end=False)
    pfile.close(delete_tempfiles)
def compute_globcurrent_particle_advection(field_set, mode, lonp, latp):
    pset = ParticleSet(field_set, pclass=ptype[mode], lon=lonp, lat=latp)
    pfile = ParticleFile("globcurrent_particles_chunk",
                         pset,
                         outputdt=delta(hours=2))
    pset.execute(AdvectionRK4,
                 runtime=delta(days=1),
                 dt=delta(minutes=5),
                 output_file=pfile)
    return pset
def compute_pop_particle_advection(field_set, mode, lonp, latp):
    pset = ParticleSet.from_list(field_set, ptype[mode], lon=lonp, lat=latp)
    pfile = ParticleFile("globcurrent_particles_chunk",
                         pset,
                         outputdt=delta(days=15))
    pset.execute(AdvectionRK4,
                 runtime=delta(days=90),
                 dt=delta(days=2),
                 output_file=pfile)
    return pset
Exemple #12
0
def compute_ofam_particle_advection(field_set, mode, lonp, latp, depthp):
    pset = ParticleSet(field_set,
                       pclass=ptype[mode],
                       lon=lonp,
                       lat=latp,
                       depth=depthp)
    pfile = ParticleFile("ofam_particles_chunk", pset, outputdt=delta(days=1))
    pset.execute(AdvectionRK4,
                 runtime=delta(days=10),
                 dt=delta(minutes=5),
                 output_file=pfile)
    return pset
def compute_swash_particle_advection(field_set, mode, lonp, latp, depthp):
    pset = ParticleSet.from_list(field_set,
                                 ptype[mode],
                                 lon=lonp,
                                 lat=latp,
                                 depth=depthp)
    pfile = ParticleFile("swash_particles_chunk",
                         pset,
                         outputdt=delta(seconds=0.05))
    pset.execute(AdvectionRK4,
                 runtime=delta(seconds=0.2),
                 dt=delta(seconds=0.005),
                 output_file=pfile)
    return pset
Exemple #14
0
def run_corefootprintparticles(dirwrite,outfile,lonss,latss,dep):
    files = sorted(glob(dirread_pop+'control_PD_1egree_extra_BOLUS/tavg/t.*'))
    dfile = [dirread_pop+'control_PD_1egree/t.x1_SAMOC_flux.160001.interp.nc']
    bfile = [dirread_pop+'bathymetry_POP_lowres_320t384.nc']
    dimfile = [dirread_pop+'coordinates_curvilinear_pop_grid_320x384.nc']
    afile = [dirread_pop+'spinup_B_2000_cam5_f09_g16.pop.h.1000-01.nc']

    if(gmbol):
        fieldset = setf.set_pop_fieldset_bolus(files, dimfile, dfile, bfile,afile, indices = ind)
    else:
        fieldset = setf.set_pop_fieldset(files, dimfile, dfile, bfile, afile, indices = ind)

    fieldset.add_periodic_halo(zonal=True, halosize=20)
       
    fieldset.add_constant('dwellingdepth', np.float(dd))
    fieldset.add_constant('sinkspeed', sp/86400.)
    fieldset.add_constant('maxage', 300000.*86400)
    fieldset.add_constant('surface', 5.00622)
    fieldset.add_constant('gmbol', gmbol)

    fieldset.add_constant('Cs', Cs)

    class DinoParticle(JITParticle):
        temp = Variable('temp', dtype=np.float32, initial=np.nan)
        age = Variable('age', dtype=np.float32, initial=0.)
        salin = Variable('salin', dtype=np.float32, initial=np.nan)
        lon0 = Variable('lon0', dtype=np.float32, initial=0.)
        lat0 = Variable('lat0', dtype=np.float32, initial=0.)
        depth0 = Variable('depth0',dtype=np.float32, initial=0.) 
        beached = Variable('beached',dtype=np.float32, initial=0.) 

    pset = ParticleSet.from_list(fieldset=fieldset, pclass=DinoParticle, lon=lonss.tolist(), lat=latss.tolist(), 
                       time = time)

    pfile = ParticleFile(dirwrite + outfile, pset, write_ondelete=True)

    if(gmbol):
        advectionkernel = pset.Kernel(popk.AdvectionRK4_3D_addbolus)
        if(Cs>0):
            advectionkernel += popk.smagorinsky_bolus
    else:
        advectionkernel = pset.Kernel(AdvectionRK4_3D)
        if(Cs>0):
            advectionkernel += popk.smagorinsky

    kernels = pset.Kernel(popk.initials) + popk.Sink  + advectionkernel + popk.Age + popk.periodicBC  

    pset.execute(kernels, runtime=delta(days=5*365), dt=delta(minutes=-15), output_file=pfile, verbose_progress=False, recovery={ErrorCode.ErrorOutOfBounds: popk.DeleteParticle})

    print('Execution finished')
Exemple #15
0
def run_nemo_curvilinear(mode, outfile, advtype='RK4'):
    """Function that shows how to read in curvilinear grids, in this case from NEMO"""
    data_path = path.join(path.dirname(__file__), 'NemoCurvilinear_data/')

    filenames = {
        'U': {
            'lon': data_path + 'mesh_mask.nc4',
            'lat': data_path + 'mesh_mask.nc4',
            'data': data_path + 'U_purely_zonal-ORCA025_grid_U.nc4'
        },
        'V': {
            'lon': data_path + 'mesh_mask.nc4',
            'lat': data_path + 'mesh_mask.nc4',
            'data': data_path + 'V_purely_zonal-ORCA025_grid_V.nc4'
        }
    }
    variables = {'U': 'U', 'V': 'V'}
    dimensions = {'lon': 'glamf', 'lat': 'gphif'}
    field_chunksize = {'y': 2, 'x': 2}
    field_set = FieldSet.from_nemo(filenames,
                                   variables,
                                   dimensions,
                                   field_chunksize=field_chunksize)
    assert field_set.U.field_chunksize == field_chunksize

    # Now run particles as normal
    npart = 20
    lonp = 30 * np.ones(npart)
    if advtype == 'RK4':
        latp = np.linspace(-70, 88, npart)
        runtime = delta(days=160)
    else:
        latp = np.linspace(-70, 70, npart)
        runtime = delta(days=15)

    def periodicBC(particle, fieldSet, time):
        if particle.lon > 180:
            particle.lon -= 360

    pset = ParticleSet.from_list(field_set, ptype[mode], lon=lonp, lat=latp)
    pfile = ParticleFile(outfile, pset, outputdt=delta(days=1))
    kernels = pset.Kernel(advection[advtype]) + periodicBC
    pset.execute(kernels,
                 runtime=runtime,
                 dt=delta(hours=6),
                 output_file=pfile)
    assert np.allclose(pset.lat - latp, 0, atol=2e-2)
Exemple #16
0
def compute_nemo_particle_advection(field_set, mode, lonp, latp):

    def periodicBC(particle, fieldSet, time):
        if particle.lon > 15.0:
            particle.lon -= 15.0
        if particle.lon < 0:
            particle.lon += 15.0
        if particle.lat > 60.0:
            particle.lat -= 11.0
        if particle.lat < 49.0:
            particle.lat += 11.0

    pset = ParticleSet.from_list(field_set, ptype[mode], lon=lonp, lat=latp)
    pfile = ParticleFile("nemo_particles_chunk", pset, outputdt=delta(days=1))
    kernels = pset.Kernel(AdvectionRK4) + periodicBC
    pset.execute(kernels, runtime=delta(days=4), dt=delta(hours=6), output_file=pfile)
    return pset
def run_corefootprintparticles(dirwrite, outfile, lonss, latss, dep):
    ufiles = sorted(glob(dirread_top + 'means/ORCA0083-N06_200?????d05U.nc'))
    vfiles = sorted(glob(dirread_top + 'means/ORCA0083-N06_200?????d05V.nc'))
    wfiles = sorted(glob(dirread_top + 'means/ORCA0083-N06_200?????d05W.nc'))
    tfiles = sorted(glob(dirread_top + 'means/ORCA0083-N06_200?????d05T.nc'))
    bfile = dirread_top + 'domain/bathymetry_ORCA12_V3.3.nc'

    fieldset = set_nemo_fieldset(ufiles, vfiles, wfiles, tfiles, bfile,
                                 dirread_pal + 'domain/coordinates.nc')
    fieldset.B.allow_time_extrapolation = True

    fieldset.add_constant('dwellingdepth', np.float(dd))
    fieldset.add_constant('sinkspeed', sp / 86400.)
    fieldset.add_constant('maxage', 300000. * 86400)
    fieldset.add_constant('surface', 2.5)

    class DinoParticle(JITParticle):
        temp = Variable('temp', dtype=np.float32, initial=np.nan)
        age = Variable('age', dtype=np.float32, initial=0.)
        salin = Variable('salin', dtype=np.float32, initial=np.nan)
        lon0 = Variable('lon0', dtype=np.float32, initial=0.)
        lat0 = Variable('lat0', dtype=np.float32, initial=0.)
        depth0 = Variable('depth0', dtype=np.float32, initial=0.)

    pset = ParticleSet.from_list(fieldset=fieldset,
                                 pclass=DinoParticle,
                                 lon=lonss.tolist(),
                                 lat=latss.tolist(),
                                 time=time)

    pfile = ParticleFile(dirwrite + outfile, pset, write_ondelete=True)

    kernels = pset.Kernel(initials) + Sink + pset.Kernel(
        AdvectionRK4_3D) + Age + periodicBC

    pset.execute(kernels,
                 runtime=delta(days=2170),
                 dt=delta(minutes=-60),
                 output_file=pfile,
                 verbose_progress=False,
                 recovery={ErrorCode.ErrorOutOfBounds: DeleteParticle})

    print 'Execution finished'
Exemple #18
0
def run_corefootprintparticles(dirwrite, outfile, lonss, lonsz, latss, latsz,
                               startdep, time):
    snapshots = snapshot_function(date(2000, 1, 9), date(2010, 6, 15),
                                  delta(days=3))
    fieldset = set_ofes_fieldset(snapshots)
    fieldset.add_periodic_halo(zonal=True)
    fieldset.B.allow_time_extrapolation = True
    fieldset.add_constant('dwellingdepth', np.float(dd))
    fieldset.add_constant('sinkspeed', sp / 86400.)
    fieldset.add_constant('maxage', 30. * 86400)

    class ForamParticle(JITParticle):
        temp = Variable('temp', dtype=np.float32, initial=np.nan)
        age = Variable('age', dtype=np.float32, initial=0.)
        salin = Variable('salin', dtype=np.float32, initial=np.nan)
        lon0 = Variable('lon0', dtype=np.float32, initial=0.)
        lat0 = Variable('lat0', dtype=np.float32, initial=0.)
        depth0 = Variable('depth0',
                          dtype=np.float32,
                          initial=0.,
                          to_write=False)
        time0 = Variable('time0', dtype=np.float32, initial=0., to_write=False)
        shellage = Variable('shellage', dtype=np.float32, initial=0.)
        loctemp = Variable('loctemp', dtype=np.float32, initial=np.nan)

    pset = ParticleSet.from_list(fieldset=fieldset,
                                 pclass=ForamParticle,
                                 lon=lonss.tolist(),
                                 lat=latss.tolist(),
                                 time=time)

    pfile = ParticleFile(dirwrite + outfile, pset, outputdt=delta(days=1))

    kernels = pset.Kernel(
        initials
    ) + ShellAge + Age + Sink + AdvectionRK4_3D + SampleTemp + LocalConditions

    pset.execute(kernels,
                 runtime=delta(days=3650),
                 dt=delta(minutes=-5),
                 output_file=pfile,
                 recovery={ErrorCode.ErrorOutOfBounds: DeleteParticle})
Exemple #19
0
def run_corefootprintparticles(dirwrite, outfile, lonss, latss, dep):
    snapshots = snapshotfunction(range(0, 365 * 5 + 8,
                                       tempres))  #max is 365*5+7
    hormesh = mesh + 'grid_coordinates_pop_tx0.1.nc'
    Sdepth = mesh + 'bottom_cell.nc'
    fieldset = set_fieldset(snapshots, hormesh, Sdepth)
    fieldset.B.allow_time_extrapolation = True

    fieldset.add_periodic_halo(zonal=True)
    fieldset.add_constant('dwellingdepth', np.float(dd))
    fieldset.add_constant('sinkspeed', sp / 86400.)
    fieldset.add_constant('maxage', 300000. * 86400)
    fieldset.add_constant('surface', 5.00622)

    class DinoParticle(JITParticle):
        temp = Variable('temp', dtype=np.float32, initial=np.nan)
        age = Variable('age', dtype=np.float32, initial=0.)
        salin = Variable('salin', dtype=np.float32, initial=np.nan)
        lon0 = Variable('lon0', dtype=np.float32, initial=0.)
        lat0 = Variable('lat0', dtype=np.float32, initial=0.)
        depth0 = Variable('depth0', dtype=np.float32, initial=0.)

    pset = ParticleSet.from_list(fieldset=fieldset,
                                 pclass=DinoParticle,
                                 lon=lonss.tolist(),
                                 lat=latss.tolist(),
                                 time=time)

    pfile = ParticleFile(dirwrite + outfile, pset, write_ondelete=True)

    kernels = pset.Kernel(initials) + Sink + pset.Kernel(
        AdvectionRK4_3D) + Age + periodicBC

    pset.execute(kernels,
                 runtime=delta(days=365 * 5),
                 dt=delta(minutes=-5),
                 output_file=pfile,
                 verbose_progress=False,
                 recovery={ErrorCode.ErrorOutOfBounds: DeleteParticle})

    print('Execution finished')
def run_corefootprintparticles(dirwrite, outfile):
    snapshots = snapshot_function(date(2000, 1, 9), date(2010, 6, 15),
                                  delta(days=3))
    # one needs to uses the precise dates of the snapshots in the ofes-data
    fieldset = set_ofes_fieldset(snapshots)
    fieldset.add_periodic_halo(zonal=True)
    fieldset.add_constant('dwellingdepth', np.float(dd))
    fieldset.add_constant('sinkspeed', sp / 86400)
    fieldset.add_constant('maxage', ls * 86400)
    fieldset.add_constant('bottomlon', bottomlon)
    fieldset.add_constant('bottomlat', bottomlat)

    class ForamParticle(JITParticle):
        temp = Variable('temp', dtype=np.float32, initial=fieldset.temp)
        age = Variable('age', dtype=np.float32, initial=0.)
        salin = Variable('salin', dtype=np.float32, initial=np.nan)
        d18ow = Variable('d18ow', dtype=np.float32, initial=0.)
        d18oc = Variable('d18oc', dtype=np.float32, initial=0.)
        loctemp = Variable('loctemp', dtype=np.float32, initial=0)
        d18owL = Variable('d18owL', dtype=np.float32, initial=0.)
        d18ocL = Variable('d18ocL', dtype=np.float32, initial=0.)

    pset = ParticleSet(fieldset=fieldset,
                       pclass=ForamParticle,
                       lon=corelon,
                       lat=corelat,
                       depth=coredepth,
                       time=fieldset.U.grid.time[-1],
                       repeatdt=delta(days=3))
    pfile = ParticleFile(dirwrite + outfile, pset, outputdt=delta(days=1))

    kernels = pset.Kernel(
        AdvectionRK4_3D
    ) + Sink + SampleTemp + Age + Sampled18OLoc + LocalConditions

    pset.execute(kernels,
                 dt=delta(minutes=-5),
                 output_file=pfile,
                 recovery={ErrorCode.ErrorOutOfBounds: DeleteParticle})
def compute_MITgcm_particle_advection(field_set, mode, lonp, latp):
    def periodicBC(particle, fieldSet, time):
        dlon = -89.0 + 91.8
        dlat = 0.7 + 1.4
        if particle.lon > -89.0:
            particle.lon -= dlon
        if particle.lon < -91.8:
            particle.lon += dlon
        if particle.lat > 0.7:
            particle.lat -= dlat
        if particle.lat < -1.4:
            particle.lat += dlat

    pset = ParticleSet.from_list(field_set, ptype[mode], lon=lonp, lat=latp)
    pfile = ParticleFile("MITgcm_particles_chunk",
                         pset,
                         outputdt=delta(days=1))
    kernels = pset.Kernel(periodicBC) + pset.Kernel(AdvectionRK4)
    pset.execute(kernels,
                 runtime=delta(days=30),
                 dt=delta(hours=12),
                 output_file=pfile)
    return pset
Exemple #22
0
def run_corefootprintparticles(dirwrite, outfile, lonss, latss, dep):
    ufiles = sorted(glob(dirread_top + 'means/ORCA0083-N06_200?????d05U.nc'))
    vfiles = sorted(glob(dirread_top + 'means/ORCA0083-N06_200?????d05V.nc'))
    wfiles = sorted(glob(dirread_top + 'means/ORCA0083-N06_200?????d05W.nc'))
    tfiles = sorted(glob(dirread_top + 'means/ORCA0083-N06_200?????d05T.nc'))

    fieldset = set_nemo_fieldset(
        ufiles, vfiles, wfiles, tfiles, dirread_pal +
        'domain/coordinates.nc')  # coordinates.nc is the mesh mask here

    fieldset.add_constant('dwellingdepth', np.float(dd))
    fieldset.add_constant('maxage', 300000. * 86400)
    fieldset.add_constant('surface', 2.5)

    class FixParticle(JITParticle):
        temp = Variable('temp', dtype=np.float32, initial=np.nan)
        age = Variable('age', dtype=np.float32, initial=0.)
        salin = Variable('salin', dtype=np.float32, initial=np.nan)

    pset = ParticleSet.from_list(fieldset=fieldset,
                                 pclass=FixParticle,
                                 lon=lonss.tolist(),
                                 lat=latss.tolist(),
                                 time=time)

    pfile = ParticleFile(dirwrite + outfile, pset, outputdt=delta(days=6))

    kernels = pset.Kernel(SampleSurf) + Age

    pset.execute(kernels,
                 runtime=delta(days=2170),
                 dt=delta(days=-3),
                 output_file=pfile,
                 verbose_progress=False,
                 recovery={ErrorCode.ErrorOutOfBounds: DeleteParticle})

    print 'Execution finished'
def run_corefootprintparticles(dirwrite, outfile, lonss, latss, time):

    snapshots = snapshot_function(date(1980, 1, 3), date(2005, 12, 29),
                                  delta(days=3))
    fieldset = set_ofes_fieldset(snapshots)
    fieldset.add_periodic_halo(zonal=True)
    fieldset.B.allow_time_extrapolation = True
    fieldset.add_constant('maxage', 300000. * 86400)
    fieldset.add_constant('surface', 2.6)

    class DinoOfesParticle(JITParticle):
        temp = Variable('temp', dtype=np.float32, initial=np.nan)
        age = Variable('age', dtype=np.float32, initial=0.)
        salin = Variable('salin', dtype=np.float32, initial=np.nan)
        lon0 = Variable('lon0', dtype=np.float32, initial=0., to_write=False)
        lat0 = Variable('lat0', dtype=np.float32, initial=0., to_write=False)
        depth0 = Variable('depth0',
                          dtype=np.float32,
                          initial=0.,
                          to_write=False)
        time0 = Variable('time0', dtype=np.float32, initial=0., to_write=False)

    pset = ParticleSet.from_list(fieldset=fieldset,
                                 pclass=DinoOfesParticle,
                                 lon=lonss.tolist(),
                                 lat=latss.tolist(),
                                 time=time)  #depth=depths,

    pfile = ParticleFile(dirwrite + outfile, pset, outputdt=delta(days=6))

    kernels = pset.Kernel(initials) + Sink + Age + periodicBC

    pset.execute(kernels,
                 runtime=delta(days=7300),
                 dt=delta(days=-3),
                 output_file=pfile,
                 recovery={ErrorCode.ErrorOutOfBounds: DeleteParticle})
Exemple #24
0
def run_northsea_mp(outfile,
                    nemo_res='0083',
                    cmems=False,
                    stokes=False,
                    diffusion=0,
                    run3D=False):
    fieldset = get_nemo_fieldset(nemo_res, run3D)
    if cmems:
        set_cmems(fieldset)
    if stokes:
        set_stokes(fieldset)
    if diffusion > 0:
        set_diffusion(fieldset, diffusion)

    set_unbeaching(fieldset)
    pset = get_particle_set(fieldset, run3D)

    kernel = pset.Kernel(AdvectionRK4_3D) if run3D else pset.Kernel(
        AdvectionRK4)
    BeachTesting = BeachTesting_3D if run3D else BeachTesting_2D
    kernel += pset.Kernel(BeachTesting) + pset.Kernel(UnBeaching)
    if stokes:
        kernel += pset.Kernel(StokesDrag) + pset.Kernel(BeachTesting)
    if diffusion > 0:
        kernel += pset.Kernel(BrownianMotion2D) + pset.Kernel(BeachTesting)
    kernel += pset.Kernel(Ageing)

    pfile = ParticleFile(outfile, pset)
    pfile.write(pset, pset[0].time)

    tic = timelib.time()
    ndays = 365 * 4 + 100
    for d in range(ndays / 2):
        day = 2 * d
        print('running %d / %d [time %g s]: %d particles ' %
              (day, ndays, timelib.time() - tic, len(pset)))
        pset.execute(kernel,
                     runtime=delta(days=2),
                     dt=900,
                     verbose_progress=False,
                     recovery={ErrorCode.ErrorOutOfBounds: DeleteParticle})
        pfile.write(pset, pset[0].time)
lats = np.concatenate((lat_r.flatten(), lat_t.flatten()))
times = np.arange(np.datetime64('2000-01-05'), np.datetime64('2001-01-05'))

pset = ParticleSet.from_list(fieldset,
                             PlasticParticle,
                             lon=np.tile(lons, [len(times)]),
                             lat=np.tile(lats, [len(times)]),
                             time=np.repeat(times, len(lons)))

kernel = AdvectionRK4  #+ pset.Kernel(Ageing)

new_write = True

timer.particlefile = timer.Timer('ParticleFile', parent=timer.root)
outfile = './' + __file__[:-3]
pfile = ParticleFile(outfile, pset)

if new_write:
    pfile.write_pickle_per_tstep(pset, pset[0].time)
else:
    pfile.write(pset, pset[0].time)

timer.particlefile.stop()
tic = timelib.time()

ndays = 100
timer.run = timer.Timer('Execution', parent=timer.root, start=False)

for d in range(ndays / 2):
    day = 2 * d
    print('running %d / %d [time %g s]: %d particles ' %
time0 = field_set.U.grid.time[0]
lonv = np.arange(-6, 10.1, .2)
latv = np.arange(50, 63, .2)
lon, lat = np.meshgrid(lonv, latv)
lon = lon.flatten()
lat = lat.flatten()
time = time0 * np.ones(lon.shape)
pset = ParticleSet.from_list(field_set,
                             JITParticle,
                             lon=lon,
                             lat=lat,
                             time=time)
kernel = AdvectionRK4
timer.particlefile = timer.Timer('ParticleFile', parent=timer.root)
outfile = __file__[:-3]
pfile = ParticleFile(outfile, pset)
pfile.write(pset, pset[0].time)
timer.particlefile.stop()
tic = timelib.time()
ndays = 60
timer.run = timer.Timer('Execution', parent=timer.root, start=False)
for d in range(ndays):
    print('running %d / %d: time %g' % (d + 1, ndays, timelib.time() - tic))
    timer.run.start()
    pset.execute(
        kernel, runtime=86400,
        dt=900)  #, recovery={ErrorCode.ErrorOutOfBounds: DeleteParticle})
    timer.run.stop()
    timer.particlefile.start()
    pfile.write(pset, pset[0].time)
    timer.particlefile.stop()
    -18.78, -18.69, -18.56, -18.46, -18.41, -18.43, -18.42, -18.53, -18.75,
    -18.55, -18.6, -18.61, -18.54, -18.46, -18.32, -18.21, -18.13, -18.17
]

N = 100


def SampleWind(particle, fieldset, time):
    particle.uwind = fieldset.uwind[time, particle.depth, particle.lat,
                                    particle.lon]
    particle.vwind = fieldset.vwind[time, particle.depth, particle.lat,
                                    particle.lon]


class PumiceParticle(JITParticle):
    uwind = Variable('uwind', initial=fieldset.uwind)
    vwind = Variable('vwind', initial=fieldset.vwind)


pset = ParticleSet(fieldset=fieldset,
                   pclass=PumiceParticle,
                   lon=np.tile(obslon[0], N),
                   lat=np.tile(obslat[0], N),
                   time=np.tile(datetime(2019, 8, 7), N))

pfile = ParticleFile(fname, pset, outputdt=delta(days=1))
pset.execute(AdvectionRK4 + pset.Kernel(BrownianMotion2D) + SampleWind,
             dt=delta(hours=1),
             output_file=pfile)
pfile.close()
            depth=z_release,
            r_pl=r_pl * np.ones(np.array(lon_release).size),
            rho_pl=rho_pl * np.ones(np.array(lon_release).size),
            r_tot=r_pl * np.ones(np.array(lon_release).size),
            rho_tot=rho_pl * np.ones(np.array(lon_release).size)))
""" Kernal + Execution"""

kernels = pset.Kernel(AdvectionRK4) + pset.Kernel(
    PolyTEOS10_bsq) + pset.Kernel(Profiles) + pset.Kernel(
        Kooi)  #pset.Kernel(AdvectionRK4_3D_vert) pset.Kernel(periodicBC) +

outfile = '/home/dlobelle/Kooi_data/data_output/allrho/res_' + res + '/allr/3yr_uvAdvOnly_NPac_3D_grid' + res + '_allrho_allr_' + str(
    round(simdays, 2)) + 'days_' + str(secsdt) + 'dtsecs_' + str(
        round(hrsoutdt, 2)) + 'hrsoutdt'

pfile = ParticleFile(outfile, pset, outputdt=delta(hours=hrsoutdt))

pset.execute(kernels,
             runtime=delta(days=simdays),
             dt=delta(seconds=secsdt),
             output_file=pfile,
             verbose_progress=True,
             recovery={
                 ErrorCode.ErrorOutOfBounds: DeleteParticle,
                 ErrorCode.ErrorInterpolation: DeleteParticle
             })

pfile.close()

print('Execution finished')
    # Make particles initial position list
nc_fid = Dataset(grid_file, 'r') #open grid file nc to read
#lats = nc_fid.variables['nav_lat'][:]  # extract/copy the data
#lons = nc_fid.variables['nav_lon'][:]

#lonE=lons[:,169-3]
#latE=lats[:,169-3]

npart = 30
lonp = [i for i in np.linspace(-88.18, -88.20, npart)] 
latp = [i for i in np.linspace(17.52, 17.53, npart)] #this makes a list!

	
pset = ParticleSet.from_list(field_set, JITParticle, lon=lonp, lat=latp)
pfile = ParticleFile("tBelize_nemo_particles_30halfD", pset, outputdt=delta(hours=0.5))
kernels = pset.Kernel(AdvectionRK4)
#Plot initial positions
#pset.show()

pset.execute(kernels, runtime=delta(days=0.5), dt=delta(hours=0.1), output_file=pfile)
#plotTrajectoriesFile("Belize_nemo_particles_t2.nc");

#pset.show(domain={'N':-31, 'S':-35, 'E':33, 'W':26})
#pset.show(field=field_set.U)
#pset.show(field=fieldset.U, show_time=datetime(2002, 1, 10, 2))
#pset.show(field=fieldset.U, show_time=datetime(2002, 1, 10, 2), with_particles=False)


end = time.time()
print(end-start)