예제 #1
0
    def test_gen_varnames(self):
        import netCDF4 as nc4
        from gnome.environment import GridCurrent, GridWind, IceVelocity
        ds = nc4.Dataset('testname', 'w', diskless=True, persist=False)
        ds.createDimension('y', 5)
        ds.createDimension('x', 5)
        ds.createVariable('x', 'f8', dimensions=('x', 'y'))
        ds['x'].standard_name = 'eastward_sea_water_velocity'
        ds.createVariable('y', 'f8', dimensions=('x', 'y'))
        ds['y'].standard_name = 'northward_sea_water_velocity'
        ds.createVariable('xw', 'f8', dimensions=('x', 'y'))
        ds['xw'].long_name = 'eastward_wind'
        ds.createVariable('yw', 'f8', dimensions=('x', 'y'))
        ds['yw'].long_name = 'northward_wind'
        ds.createVariable('ice_u', 'f8', dimensions=('x', 'y'))
        ds.createVariable('ice_v', 'f8', dimensions=('x', 'y'))
        names = GridCurrent._gen_varnames(dataset=ds)
        assert names[0] == names.u == 'x'
        assert names[1] == names.v == 'y'
        names = GridWind._gen_varnames(dataset=ds)
        assert names[0] == names.u == 'xw'
        assert names[1] == names.v == 'yw'
        names = IceVelocity._gen_varnames(dataset=ds)
        assert names[0] == names.u == 'ice_u'
        assert names[1] == names.v == 'ice_v'

        curr_file = os.path.join(s_data, 'staggered_sine_channel.nc')
        gc = GridCurrent.from_netCDF(filename=curr_file)
        assert gc.u == gc.variables[0]
        assert gc.varnames[0] == 'u'
예제 #2
0
    def from_netCDF(cls,
                    filename=None,
                    name=None,
                    time_offset=0,
                    current_scale=1,
                    uncertain_duration=24 * 3600,
                    uncertain_time_delay=0,
                    uncertain_along=.5,
                    uncertain_across=.25,
                    uncertain_cross=.25,
                    **kwargs):
        """
        Function for specifically creating a PyCurrentMover from a file
        """
        current = GridCurrent.from_netCDF(filename, **kwargs)

        return cls(name=name,
                   current=current,
                   filename=filename,
                   time_offset=time_offset,
                   current_scale=current_scale,
                   uncertain_along=uncertain_along,
                   uncertain_across=uncertain_across,
                   uncertain_cross=uncertain_cross,
                   **kwargs)
예제 #3
0
    def from_netCDF(cls,
                    filename=None,
                    name=None,
                    time_offset=0,
                    current_scale=1,
                    uncertain_duration=24 * 3600,
                    uncertain_time_delay=0,
                    uncertain_along=.5,
                    uncertain_across=.25,
                    uncertain_cross=.25,
                    **kwargs):
        """
        Function for specifically creating a PyCurrentMover from a file
        """
        current = GridCurrent.from_netCDF(filename, **kwargs)

        return cls(name=name,
                   current=current,
                   filename=filename,
                   time_offset=time_offset,
                   current_scale=current_scale,
                   uncertain_along=uncertain_along,
                   uncertain_across=uncertain_across,
                   uncertain_cross=uncertain_cross,
                   **kwargs)
예제 #4
0
    def __init__(self,
                 filename=None,
                 current=None,
                 time_offset=0,
                 scale_value=1,
                 uncertain_duration=24 * 3600,
                 uncertain_time_delay=0,
                 uncertain_along=.5,
                 uncertain_across=.25,
                 uncertain_cross=.25,
                 default_num_method='RK2',
                 **kwargs):
        """
        Initialize a PyCurrentMover

        :param filename: absolute or relative path to the data file(s):
                         could be a string or list of strings in the
                         case of a multi-file dataset
        :param current: Environment object representing currents to be
                        used. If this is not specified, a GridCurrent object
                        will attempt to be instantiated from the file

        :param active_range: Range of datetimes for when the mover should be
                             active
        :type active_range: 2-tuple of datetimes

        :param scale_value: Value to scale current data
        :param uncertain_duration: how often does a given uncertain element
                                   get reset
        :param uncertain_time_delay: when does the uncertainly kick in.
        :param uncertain_cross: Scale for uncertainty perpendicular to the flow
        :param uncertain_along: Scale for uncertainty parallel to the flow
        :param time_offset: Time zone shift if data is in GMT
        :param num_method: Numerical method for calculating movement delta.
                           Choices:('Euler', 'RK2', 'RK4')
                           Default: RK2
        """

        (super(PyCurrentMover,
               self).__init__(default_num_method=default_num_method, **kwargs))
        self.filename = filename
        self.current = current

        if self.current is None:
            if filename is None:
                raise ValueError("must provide a filename or current object")
            else:
                self.current = GridCurrent.from_netCDF(filename=self.filename,
                                                       **kwargs)
        self.scale_value = scale_value

        self.uncertain_along = uncertain_along
        self.uncertain_across = uncertain_across
        self.uncertain_duration = uncertain_duration
        self.uncertain_time_delay = uncertain_time_delay

        self.model_time = 0

        # either a 1, or 2 depending on whether spill is certain or not
        self.spill_type = 0
예제 #5
0
    def test_gen_varnames(self):
        import netCDF4 as nc4
        from gnome.environment import GridCurrent, GridWind, IceVelocity

        ds = nc4.Dataset('testname', 'w', diskless=True, persist=False)
        ds.createDimension('y', 5)
        ds.createDimension('x', 5)

        ds.createVariable('x', 'f8', dimensions=('x', 'y'))
        ds['x'].standard_name = 'eastward_sea_water_velocity'

        ds.createVariable('y', 'f8', dimensions=('x', 'y'))
        ds['y'].standard_name = 'northward_sea_water_velocity'

        ds.createVariable('xw', 'f8', dimensions=('x', 'y'))
        ds['xw'].long_name = 'eastward_wind'

        ds.createVariable('yw', 'f8', dimensions=('x', 'y'))
        ds['yw'].long_name = 'northward_wind'

        ds.createVariable('ice_u', 'f8', dimensions=('x', 'y'))
        ds.createVariable('ice_v', 'f8', dimensions=('x', 'y'))

        names = GridCurrent._gen_varnames(dataset=ds)
        assert names[0] == names.u == 'x'
        assert names[1] == names.v == 'y'

        names = GridWind._gen_varnames(dataset=ds)
        assert names[0] == names.u == 'xw'
        assert names[1] == names.v == 'yw'

        names = IceVelocity._gen_varnames(dataset=ds)
        assert names[0] == names.u == 'ice_u'
        assert names[1] == names.v == 'ice_v'

        curr_file = os.path.join(s_data, 'staggered_sine_channel.nc')
        gc = GridCurrent.from_netCDF(filename=curr_file)
        assert gc.u == gc.variables[0]
        assert gc.varnames[0] == 'u'
예제 #6
0
 def from_netCDF(cls,
                 filename=None,
                 extrapolate=False,
                 time_offset=0,
                 current_scale=1,
                 uncertain_duration=24 * 3600,
                 uncertain_time_delay=0,
                 uncertain_along=.5,
                 uncertain_across=.25,
                 uncertain_cross=.25,
                 **kwargs):
     current = GridCurrent.from_netCDF(filename, **kwargs)
     return cls(current=current,
                filename=filename,
                extrapolate=extrapolate,
                time_offset=time_offset,
                current_scale=current_scale,
                uncertain_along=uncertain_along,
                uncertain_across=uncertain_across,
                uncertain_cross=uncertain_cross)
예제 #7
0
 def from_netCDF(
     cls,
     filename=None,
     extrapolate=False,
     time_offset=0,
     current_scale=1,
     uncertain_duration=24 * 3600,
     uncertain_time_delay=0,
     uncertain_along=0.5,
     uncertain_across=0.25,
     uncertain_cross=0.25,
     **kwargs
 ):
     current = GridCurrent.from_netCDF(filename, **kwargs)
     return cls(
         current=current,
         filename=filename,
         extrapolate=extrapolate,
         time_offset=time_offset,
         current_scale=current_scale,
         uncertain_along=uncertain_along,
         uncertain_across=uncertain_across,
         uncertain_cross=uncertain_cross,
     )
예제 #8
0
        assert objs[ix] in refs  # double check __contains__

    unknown = constant_wind_mover(0, 0)
    assert unknown not in refs  # check __contains__


'''
Run the following save/load test on multiple pygnome objects so collect tests
here and parametrize it by the objects
'''

base_dir = os.path.dirname(__file__)

# For WindMover test_save_load in test_wind_mover
g_objects = (
    GridCurrent.from_netCDF(testdata['GridCurrentMover']['curr_tri']),
    Tide(testdata['CatsMover']['tide']),
    Wind(filename=testdata['ComponentMover']['wind']),
    Wind(timeseries=(sec_to_date(24 * 60 * 60), (0, 0)), units='mps'),
    Water(temperature=273),
    RandomMover(),
    CatsMover(testdata['CatsMover']['curr']),
    CatsMover(testdata['CatsMover']['curr'],
              tide=Tide(testdata['CatsMover']['tide'])),
    ComponentMover(testdata['ComponentMover']['curr']),
    ComponentMover(testdata['ComponentMover']['curr'],
                   wind=Wind(filename=testdata['ComponentMover']['wind'])),
    RandomMover3D(),
    SimpleMover(velocity=(10.0, 10.0, 0.0)),
    map.MapFromBNA(testdata['MapFromBNA']['testmap'], 6),
    NetCDFOutput(os.path.join(base_dir, u'xtemp.nc')),
예제 #9
0
def make_model(images_dir=os.path.join(base_dir, 'images')):
    print 'initializing the model'

    start_time = datetime(2012, 10, 25, 0, 1)
    # start_time = datetime(2015, 12, 18, 06, 01)

    # 1 day of data in file
    # 1/2 hr in seconds
    model = Model(start_time=start_time,
                  duration=timedelta(hours=6),
                  time_step=900)

    mapfile = get_datafile(os.path.join(base_dir, 'nyharbor.bna'))

    print 'adding the map'
    '''TODO: sort out MapFromBna's map_bounds parameter...
    it does nothing right now, and the spill is out of bounds'''
    model.map = MapFromBNA(mapfile, refloat_halflife=0.0)  # seconds

    # draw_ontop can be 'uncertain' or 'forecast'
    # 'forecast' LEs are in black, and 'uncertain' are in red
    # default is 'forecast' LEs draw on top
    renderer = Renderer(mapfile, images_dir, image_size=(1024, 768))
    #     renderer.viewport = ((-73.5, 40.5), (-73.1, 40.75))
    #     renderer.viewport = ((-122.9, 45.6), (-122.6, 46.0))

    print 'adding outputters'
    model.outputters += renderer

    print 'adding a spill'
    # for now subsurface spill stays on initial layer
    # - will need diffusion and rise velocity
    # - wind doesn't act
    # - start_position = (-76.126872, 37.680952, 5.0),
    spill1 = point_line_release_spill(num_elements=1000,
                                      start_position=(-74.15, 40.5, 0.0),
                                      release_time=start_time)

    model.spills += spill1

    print 'adding a RandomMover:'
    model.movers += RandomMover(diffusion_coef=50000)

    print 'adding a wind mover:'

    model.movers += constant_wind_mover(4, 270, units='m/s')

    print 'adding a current mover:'

    url = (
        'http://geoport.whoi.edu/thredds/dodsC/clay/usgs/users/jcwarner/Projects/Sandy/triple_nest/00_dir_NYB05.ncml'
    )
    #     cf = roms_field('nos.tbofs.fields.n000.20160406.t00z_sgrid.nc')
    cf = GridCurrent.from_netCDF(url)
    renderer.add_grid(cf.grid)
    renderer.delay = 25
    u_mover = PyGridCurrentMover(cf)
    model.movers += u_mover

    # curr_file = get_datafile(os.path.join(base_dir, 'COOPSu_CREOFS24.nc'))
    # c_mover = GridCurrentMover(curr_file)
    # model.movers += c_mover

    return model
예제 #10
0
# vy = 1/y[np.newaxis,:]
# vx[vx == np.inf] = 0
# vy[vy == np.inf] = 0
# vx = vx/mag *30
# vy = vy/mag *30
# v_x = vx.copy()
# v_y - vy.copy()
# sl = [0,0:30,31:61]
# v_x = vx[:,0] * np.cos(angs) - value[:,1] * np.sin(angs)
# y = value[:,0] * np.sin(angs) + value[:,1] * np.cos(angs)
# value[:,0] = x
# value[:,1] = y

vels_x = Variable(name='v_x', units='m/s', time=[t], grid=g, data=vx)
vels_y = Variable(name='v_y', units='m/s', time=[t], grid=g, data=vy)
vg = GridCurrent(variables=[vels_y, vels_x], time=[t], grid=g, units='m/s')
point = np.zeros((1, 2))
print vg.at(point, t)

# define base directory
base_dir = os.path.dirname(__file__)

def make_model():
    duration_hrs = 48
    time_step = 900
    num_steps = duration_hrs * 3600 / time_step
    mod = Model(start_time=t,
                duration=timedelta(hours=duration_hrs),
                time_step=time_step)

    spill = point_line_release_spill(num_elements=1000,
예제 #11
0
# vy = 1/y[np.newaxis,:]
# vx[vx == np.inf] = 0
# vy[vy == np.inf] = 0
# vx = vx/mag *30
# vy = vy/mag *30
# v_x = vx.copy()
# v_y - vy.copy()
# sl = [0,0:30,31:61]
# v_x = vx[:,0] * np.cos(angs) - value[:,1] * np.sin(angs)
# y = value[:,0] * np.sin(angs) + value[:,1] * np.cos(angs)
# value[:,0] = x
# value[:,1] = y

vels_x = GriddedProp(name='v_x', units='m/s', time=[t], grid=g, data=vx)
vels_y = GriddedProp(name='v_y', units='m/s', time=[t], grid=g, data=vy)
vg = GridCurrent(variables=[vels_y, vels_x], time=[t], grid=g, units='m/s')
point = np.zeros((1, 2))
print vg.at(point, t)

# define base directory
base_dir = os.path.dirname(__file__)


def make_model():
    duration_hrs = 48
    time_step = 900
    num_steps = duration_hrs * 3600 / time_step
    mod = Model(start_time=t,
                duration=timedelta(hours=duration_hrs),
                time_step=time_step)
예제 #12
0
x = np.ascontiguousarray(x.T)
# y += np.sin(x) / 1
# x += np.sin(x) / 5
g = SGrid(node_lon=x, node_lat=y)
g.build_celltree()
t = datetime(2000, 1, 1, 0, 0)
angs = -np.arctan2(y, x)
mag = np.sqrt(x**2 + y**2)
vx = np.cos(angs) * mag
vy = np.sin(angs) * mag
vx = vx[np.newaxis, :] * 5
vy = vy[np.newaxis, :] * 5

vels_x = GriddedProp(name='v_x', units='m/s', time=[t], grid=g, data=vx)
vels_y = GriddedProp(name='v_y', units='m/s', time=[t], grid=g, data=vy)
vg = GridCurrent(variables=[vels_y, vels_x], time=[t], grid=g, units='m/s')


def make_model(images_dir=os.path.join(base_dir, 'images')):
    print 'initializing the model'

    # set up the modeling environment
    start_time = datetime(2016, 9, 23, 0, 0)
    model = Model(start_time=start_time,
                  duration=timedelta(days=2),
                  time_step=30 * 60,
                  uncertain=False)

    print 'adding the map'
    model.map = GnomeMap()  # this is a "water world -- no land anywhere"
예제 #13
0
def make_model(images_dir=os.path.join(base_dir, 'images')):
    print 'initializing the model'

    start_time = datetime(1985, 1, 1, 13, 31)

    # 1 day of data in file
    # 1/2 hr in seconds
    model = Model(start_time=start_time,
                  duration=timedelta(days=4),
                  time_step=7200)

    #     mapfile = get_datafile(os.path.join(base_dir, 'ak_arctic.bna'))
    mapfile = get_datafile('arctic_coast3.bna')

    print 'adding the map'
    model.map = MapFromBNA(mapfile, refloat_halflife=0.0)  # seconds

    print 'adding a spill'
    # for now subsurface spill stays on initial layer
    # - will need diffusion and rise velocity
    # - wind doesn't act
    # - start_position = (-76.126872, 37.680952, 5.0),
    #     spill1 = point_line_release_spill(num_elements=10000,
    #                                       start_position=(-163.75,
    #                                                       69.75,
    #                                                       0.0),
    #                                       release_time=start_time)
    #
    spill1 = point_line_release_spill(num_elements=50000,
                                      start_position=(196.25, 69.75, 0.0),
                                      release_time=start_time)

    model.spills += spill1
    #     model.spills += spill2

    print 'adding a wind mover:'

    #     model.movers += constant_wind_mover(0.5, 0, units='m/s')

    print 'adding a current mover:'

    fn = ['arctic_avg2_0001_gnome.nc', 'arctic_avg2_0002_gnome.nc']

    #     fn = ['C:\\Users\\jay.hennen\\Documents\\Code\\pygnome\\py_gnome\\scripts\\script_TAP\\arctic_avg2_0001_gnome.nc',
    #           'C:\\Users\\jay.hennen\\Documents\\Code\\pygnome\\py_gnome\\scripts\\script_TAP\\arctic_avg2_0002_gnome.nc']

    gt = {'node_lon': 'lon', 'node_lat': 'lat'}
    #     fn='arctic_avg2_0001_gnome.nc'

    wind_method = 'Euler'
    method = 'RK2'
    print 'adding outputters'

    # draw_ontop can be 'uncertain' or 'forecast'
    # 'forecast' LEs are in black, and 'uncertain' are in red
    # default is 'forecast' LEs draw on top
    renderer = Renderer(mapfile, images_dir, image_size=(1024, 768))
    model.outputters += renderer
    netcdf_file = os.path.join(base_dir,
                               str(model.time_step / 60) + method + '.nc')
    scripting.remove_netcdf(netcdf_file)

    print 'adding movers'
    model.outputters += NetCDFOutput(netcdf_file, which_data='all')

    print 'loading entire current data'
    ice_aware_curr = IceAwareCurrent.from_netCDF(filename=fn, grid_topology=gt)

    #     env1 = get_env_from_netCDF(filename)
    #     mov = PyCurrentMover.from_netCDF(filename)

    ice_aware_curr.ice_velocity.variables[0].dimension_ordering = [
        'time', 'x', 'y'
    ]
    ice_aware_wind = IceAwareWind.from_netCDF(
        filename=fn,
        ice_velocity=ice_aware_curr.ice_velocity,
        ice_concentration=ice_aware_curr.ice_concentration,
        grid=ice_aware_curr.grid)

    curr = GridCurrent.from_netCDF(filename=fn)
    #     GridCurrent.is_gridded()

    #     import pprint as pp
    #     from gnome.utilities.orderedcollection import OrderedCollection
    #     model.environment = OrderedCollection(dtype=Environment)
    #     model.environment.add(ice_aware_curr)
    #     from gnome.environment import WindTS

    print 'loading entire wind data'

    #     i_c_mover = PyCurrentMover(current=ice_aware_curr)
    #     i_c_mover = PyCurrentMover(current=ice_aware_curr, default_num_method='Euler')
    i_c_mover = PyCurrentMover(current=ice_aware_curr,
                               default_num_method=method,
                               extrapolate=True)
    i_w_mover = PyWindMover(wind=ice_aware_wind,
                            default_num_method=wind_method)

    #     ice_aware_curr.grid.node_lon = ice_aware_curr.grid.node_lon[:]-360
    #     ice_aware_curr.grid.build_celltree()
    model.movers += i_c_mover
    model.movers += i_w_mover

    print 'adding an IceAwareRandomMover:'
    model.movers += IceAwareRandomMover(
        ice_concentration=ice_aware_curr.ice_concentration,
        diffusion_coef=1000)
    #     renderer.add_grid(ice_aware_curr.grid)
    #     renderer.add_vec_prop(ice_aware_curr)

    # curr_file = get_datafile(os.path.join(base_dir, 'COOPSu_CREOFS24.nc'))
    # c_mover = GridCurrentMover(curr_file)
    # model.movers += c_mover
    #     model.environment.add(WindTS.constant(10, 300))
    #     print('Saving')
    #     model.environment[0].ice_velocity.variables[0].serialize()
    #     IceVelocity.deserialize(model.environment[0].ice_velocity.serialize())
    #     model.save('.')
    #     from gnome.persist.save_load import load
    #     print('Loading')
    #     model2 = load('./Model.zip')

    return model
예제 #14
0
def make_model(images_dir=os.path.join(base_dir, 'images')):
    print 'initializing the model'

    start_time = datetime(2012, 10, 25, 0, 1)
    # start_time = datetime(2015, 12, 18, 06, 01)

    # 1 day of data in file
    # 1/2 hr in seconds
    model = Model(start_time=start_time,
                  duration=timedelta(hours=2),
                  time_step=900)

    mapfile = get_datafile(os.path.join(base_dir, 'nyharbor.bna'))

    print 'adding the map'
    '''TODO: sort out MapFromBna's map_bounds parameter...
    it does nothing right now, and the spill is out of bounds'''
    model.map = MapFromBNA(mapfile, refloat_halflife=0.0)  # seconds

    # draw_ontop can be 'uncertain' or 'forecast'
    # 'forecast' LEs are in black, and 'uncertain' are in red
    # default is 'forecast' LEs draw on top
    renderer = Renderer(mapfile, images_dir, image_size=(1024, 768))
    #     renderer.viewport = ((-73.5, 40.5), (-73.1, 40.75))
    #     renderer.viewport = ((-122.9, 45.6), (-122.6, 46.0))

    print 'adding outputters'
    model.outputters += renderer

    netcdf_file = os.path.join(base_dir, 'script_ny_plume.nc')
    scripting.remove_netcdf(netcdf_file)

    model.outputters += NetCDFOutput(netcdf_file, which_data='all')

    print 'adding two spills'
    # Break the spill into two spills, first with the larger droplets
    # and second with the smaller droplets.
    # Split the total spill volume (100 m^3) to have most
    # in the larger droplet spill.
    # Smaller droplets start at a lower depth than larger

    end_time = start_time + model.duration
    #     wd = WeibullDistribution(alpha=1.8,
    #                              lambda_=.00456,
    #                              min_=.0002)  # 200 micron min
    #
    #     spill = subsurface_plume_spill(num_elements=10,
    #                                    start_position=(-74.15,
    #                                                    40.5,
    #                                                    7.2),
    #                                    release_time=start_time,
    #                                    distribution=wd,
    #                                    amount=90,  # default volume_units=m^3
    #                                    units='m^3',
    #                                    end_release_time=end_time,
    #                                    density=600)
    #
    #     model.spills += spill

    #     wd = WeibullDistribution(alpha=1.8,
    #                              lambda_=.00456,
    #                              max_=.0002)  # 200 micron max

    wd = UniformDistribution(low=.0002, high=.0002)

    spill = point_line_release_spill(
        num_elements=10,
        amount=90,
        units='m^3',
        start_position=(-74.15, 40.5, 7.2),
        release_time=start_time,
        element_type=plume(
            distribution=wd,
            substance_name='ALASKA NORTH SLOPE (MIDDLE PIPELINE, 1997)'))
    model.spills += spill

    print 'adding a RandomMover:'
    model.movers += RandomMover(diffusion_coef=50000)

    print 'adding a RiseVelocityMover:'
    model.movers += RiseVelocityMover()

    print 'adding a RandomVerticalMover:'
    #     model.movers += RandomVerticalMover(vertical_diffusion_coef_above_ml=5,
    #                                         vertical_diffusion_coef_below_ml=.11,
    #                                         mixed_layer_depth=10)

    url = (
        'http://geoport.whoi.edu/thredds/dodsC/clay/usgs/users/jcwarner/Projects/Sandy/triple_nest/00_dir_NYB05.ncml'
    )
    gc = GridCurrent.from_netCDF(url)
    u_mover = PyCurrentMover(gc, default_num_method='RK2')
    model.movers += u_mover
    # print 'adding a wind mover:'

    # series = np.zeros((2, ), dtype=gnome.basic_types.datetime_value_2d)
    # series[0] = (start_time, (30, 90))
    # series[1] = (start_time + timedelta(hours=23), (30, 90))

    # wind = Wind(timeseries=series, units='knot')
    #
    # default is .4 radians
    # w_mover = gnome.movers.WindMover(wind, uncertain_angle_scale=0)
    #
    # model.movers += w_mover

    print 'adding a simple mover:'
    #     s_mover = SimpleMover(velocity=(0.0, -.3, 0.0))
    #     model.movers += s_mover

    return model
예제 #15
0
    def __init__(self,
                 filename=None,
                 current=None,
                 time_offset=0,
                 current_scale=1,
                 uncertain_duration=24 * 3600,
                 uncertain_time_delay=0,
                 uncertain_along=.5,
                 uncertain_across=.25,
                 uncertain_cross=.25,
                 default_num_method='RK2',
                 extrapolation_is_allowed=False,
                 **kwargs
                 ):
        """
        Initialize a PyCurrentMover

        :param filename: absolute or relative path to the data file(s):
                         could be a string or list of strings in the
                         case of a multi-file dataset
        :param current: Environment object representing currents to be
                        used. If this is not specified, a GridCurrent object
                        will attempt to be instantiated from the file

        :param active_range: Range of datetimes for when the mover should be
                             active
        :type active_range: 2-tuple of datetimes

        :param current_scale: Value to scale current data
        :param uncertain_duration: how often does a given uncertain element
                                   get reset
        :param uncertain_time_delay: when does the uncertainly kick in.
        :param uncertain_cross: Scale for uncertainty perpendicular to the flow
        :param uncertain_along: Scale for uncertainty parallel to the flow
        :param time_offset: Time zone shift if data is in GMT
        :param num_method: Numerical method for calculating movement delta.
                           Choices:('Euler', 'RK2', 'RK4')
                           Default: RK2
        """
        self.filename = filename
        self.current = current

        if self.current is None:
            if filename is None:
                raise ValueError("must provide a filename or current object")
            else:
                self.current = GridCurrent.from_netCDF(filename=self.filename,
                                                       **kwargs)

        self.extrapolation_is_allowed = extrapolation_is_allowed
        self.current_scale = current_scale

        self.uncertain_along = uncertain_along
        self.uncertain_across = uncertain_across
        self.uncertain_duration = uncertain_duration
        self.uncertain_time_delay = uncertain_time_delay

        self.model_time = 0

        self.positions = np.zeros((0, 3), dtype=world_point_type)
        self.delta = np.zeros((0, 3), dtype=world_point_type)
        self.status_codes = np.zeros((0, 1), dtype=status_code_type)

        # either a 1, or 2 depending on whether spill is certain or not
        self.spill_type = 0
        (super(PyCurrentMover, self)
         .__init__(default_num_method=default_num_method, **kwargs))
예제 #16
0
        # set up model for this start_time/duration, adding required forcing files
        model = make_model(setup.RootDir)
        model.duration = run_time
        model.movers.clear()
        model.weatherers.clear()
        model.environment.clear()

        print 'creating curr MFDataset'
        ds_c = nc4.MFDataset(file_list)

        print 'adding a CurrentMover (Trapeziod/RK4):'
        g_curr = GridCurrent.from_netCDF(
            filename=file_list,
            # dataset=ds_c,
            grid_topology={
                'node_lon': 'lonc',
                'node_lat': 'latc'
            })
        c_mover = PyCurrentMover(current=g_curr, default_num_method='RK4')
        model.movers += c_mover

        print 'creating wind MFDataset'
        ds_w = nc4.MFDataset(file_list_w)

        print 'adding a WindMover (Euler):'
        g_wind = GridWind.from_netCDF(
            filename=file_list_w,
            # dataset=ds_w,
            grid_topology={
                'node_lon': 'lonc',
예제 #17
0
    unknown = constant_wind_mover(0, 0)
    assert unknown not in refs  # check __contains__


'''
Run the following save/load test on multiple pygnome objects so collect tests
here and parametrize it by the objects
'''


base_dir = os.path.dirname(__file__)


# For WindMover test_save_load in test_wind_mover
g_objects = (
    GridCurrent.from_netCDF(testdata['GridCurrentMover']['curr_tri']),
    Tide(testdata['CatsMover']['tide']),
    Wind(filename=testdata['ComponentMover']['wind']),
    Wind(timeseries=(sec_to_date(24 * 60 * 60),
                     (0, 0)), units='mps'),
    Water(temperature=273),

    RandomMover(),
    CatsMover(testdata['CatsMover']['curr']),
    CatsMover(testdata['CatsMover']['curr'],
              tide=Tide(testdata['CatsMover']['tide'])),
    ComponentMover(testdata['ComponentMover']['curr']),
    ComponentMover(testdata['ComponentMover']['curr'],
                   wind=Wind(filename=testdata['ComponentMover']['wind'])),
    RandomVerticalMover(),
    SimpleMover(velocity=(10.0, 10.0, 0.0)),
예제 #18
0
def make_model(images_dir=os.path.join(base_dir, 'images')):
    print 'initializing the model'

    # set up the modeling environment
    start_time = datetime(2016, 9, 18, 1, 0)
    model = Model(start_time=start_time,
                  duration=timedelta(days=3),
                  time_step=30 * 60,
                  uncertain=False)

    print 'adding the map'
    model.map = GnomeMap()  # this is a "water world -- no land anywhere"

    # renderere is only top-down view on 2d -- but it's something
    renderer = Renderer(output_dir=images_dir,
                        size=(1024, 768),
                        output_timestep=timedelta(hours=1),
                        )
    renderer.viewport = ((-87.095, 27.595), (-87.905, 28.405))

    print 'adding outputters'
    model.outputters += renderer

    # Also going to write the results out to a netcdf file
    netcdf_file = os.path.join(base_dir, 'gulf_tamoc.nc')
    scripting.remove_netcdf(netcdf_file)

    model.outputters += NetCDFOutput(netcdf_file,
                                     which_data='most',
                                     # output most of the data associated with the elements
                                     output_timestep=timedelta(hours=2))

    print "adding Horizontal and Vertical diffusion"

    # Horizontal Diffusion
    model.movers += RandomMover(diffusion_coef=100000)
    # vertical diffusion (different above and below the mixed layer)
    model.movers += RandomVerticalMover(vertical_diffusion_coef_above_ml=50,
                                        vertical_diffusion_coef_below_ml=10,
                                        horizontal_diffusion_coef_above_ml=100000,
                                        horizontal_diffusion_coef_below_ml=100,
                                        mixed_layer_depth=10)

    print 'adding Rise Velocity'
    # droplets rise as a function of their density and radius
    model.movers += TamocRiseVelocityMover()

    print 'adding the 3D current mover'
    gc = GridCurrent.from_netCDF('HYCOM_3d.nc')

    model.movers += GridCurrentMover('HYCOM_3d.nc')
#    model.movers += SimpleMover(velocity=(0., 0, 0.))
#    model.movers += constant_wind_mover(5, 315, units='knots')

    # Wind from a buoy
    w = Wind(filename='KIKT.osm')
    model.movers += WindMover(w)


    # Now to add in the TAMOC "spill"
    print "Adding TAMOC spill"

    model.spills += tamoc_spill.TamocSpill(release_time=start_time,
                                        start_position=(-87.5, 28.0, 2000),
                                        num_elements=30000,
                                        end_release_time=start_time + timedelta(days=2),
                                        name='TAMOC plume',
                                        TAMOC_interval=None,  # how often to re-run TAMOC
                                        )

    model.spills[0].data_sources['currents'] = gc

    return model
예제 #19
0
def make_model(images_dir=os.path.join(base_dir, 'images')):
    print 'initializing the model'

    start_time = datetime(2012, 10, 25, 0, 1)
    # start_time = datetime(2015, 12, 18, 06, 01)

    # 1 day of data in file
    # 1/2 hr in seconds
    model = Model(start_time=start_time,
                  duration=timedelta(hours=6),
                  time_step=900)

    mapfile = get_datafile(os.path.join(base_dir, 'nyharbor.bna'))

    print 'adding the map'
    '''TODO: sort out MapFromBna's map_bounds parameter...
    it does nothing right now, and the spill is out of bounds'''
    model.map = MapFromBNA(mapfile, refloat_halflife=0.0)  # seconds

    # draw_ontop can be 'uncertain' or 'forecast'
    # 'forecast' LEs are in black, and 'uncertain' are in red
    # default is 'forecast' LEs draw on top
    renderer = Renderer(mapfile, images_dir, image_size=(1024, 768))
#     renderer.viewport = ((-73.5, 40.5), (-73.1, 40.75))
#     renderer.viewport = ((-122.9, 45.6), (-122.6, 46.0))

    print 'adding outputters'
    model.outputters += renderer

    print 'adding a spill'
    # for now subsurface spill stays on initial layer
    # - will need diffusion and rise velocity
    # - wind doesn't act
    # - start_position = (-76.126872, 37.680952, 5.0),
    spill1 = point_line_release_spill(num_elements=1000,
                                      start_position=(-74.15,
                                                      40.5,
                                                      0.0),
                                      release_time=start_time)

    model.spills += spill1

    print 'adding a RandomMover:'
    model.movers += RandomMover(diffusion_coef=50000)

    print 'adding a wind mover:'

    model.movers += constant_wind_mover(4, 270, units='m/s')

    print 'adding a current mover:'

    url = ('http://geoport.whoi.edu/thredds/dodsC/clay/usgs/users/jcwarner/Projects/Sandy/triple_nest/00_dir_NYB05.ncml')
#     cf = roms_field('nos.tbofs.fields.n000.20160406.t00z_sgrid.nc')
    cf = GridCurrent.from_netCDF(url)
    renderer.add_grid(cf.grid)
    renderer.delay = 25
    u_mover = PyGridCurrentMover(cf, default_num_method='Euler')
    model.movers += u_mover

    # curr_file = get_datafile(os.path.join(base_dir, 'COOPSu_CREOFS24.nc'))
    # c_mover = GridCurrentMover(curr_file)
    # model.movers += c_mover

    return model
def gen_vortex_3D(filename=None):
    x, y = np.mgrid[-30:30:61j, -30:30:61j]

    y = np.ascontiguousarray(y.T)
    x = np.ascontiguousarray(x.T)

    x_size = 61
    y_size = 61

    g = Grid_S(node_lon=x, node_lat=y)
    g.build_celltree()

    lin_nodes = g._cell_trees['node'][1]
    lin_faces = np.array([
        np.array([([lx, lx + x_size + 1, lx + 1
                    ], [lx, lx + x_size, lx + x_size + 1])
                  for lx in range(0, x_size - 1, 1)]) + ly * x_size
        for ly in range(0, y_size - 1)
    ])
    lin_faces = lin_faces.reshape(-1, 3)

    # y += np.sin(x) / 1
    # x += np.sin(x) / 5

    t0 = datetime(2001, 1, 1, 0, 0)
    tarr = [t0 + timedelta(hours=i) for i in range(0, 11)]
    angs = -np.arctan2(y, x)
    mag = np.sqrt(x**2 + y**2)

    vx = np.cos(angs) * mag
    vy = np.sin(angs) * mag
    vx = vx[np.newaxis, :] * 20
    vy = vy[np.newaxis, :] * 20

    vw = -0.001

    d_scale = [1, 0.5, 0, -0.5, -1]
    t_scale = np.linspace(0, 1, 11)

    tvx = np.array([vx * t for t in t_scale]).squeeze()
    tvy = np.array([vy * t for t in t_scale]).squeeze()

    dvx = np.array([vx * s for s in d_scale]).squeeze()
    dvy = np.array([vy * s for s in d_scale]).squeeze()

    tdvx = np.array([dvx * t for t in t_scale]).squeeze()
    tdvy = np.array([dvy * t for t in t_scale]).squeeze()

    lin_vx = vx.reshape(-1)
    lin_vy = vy.reshape(-1)

    lin_tvx = np.array([lin_vx * t for t in t_scale])
    lin_tvy = np.array([lin_vy * t for t in t_scale])

    lin_dvx = np.array([lin_vx * s for s in d_scale])
    lin_dvy = np.array([lin_vy * s for s in d_scale])

    lin_tdvx = np.array([lin_dvx * t for t in t_scale])
    lin_tdvy = np.array([lin_dvy * t for t in t_scale])

    ds = None

    if filename is not None:
        ds = nc4.Dataset(filename, 'w', diskless=True, persist=True)

        ds.createDimension('y', y.shape[0])
        ds.createDimension('x', x.shape[1])
        ds.createDimension('time', len(tarr))
        ds.createDimension('depth', len(d_scale))

        ds.createVariable('x', 'f8', dimensions=('x', 'y'))
        ds['x'][:] = x

        ds.createVariable('y', 'f8', dimensions=('x', 'y'))
        ds['y'][:] = y

        ds.createVariable('time', 'f8', dimensions=('time'))
        ds['time'][:] = nc4.date2num(tarr, 'hours since {0}'.format(t0))
        ds['time'].setncattr('units', 'hours since {0}'.format(t0))

        ds.createVariable('vx', 'f8', dimensions=('x', 'y'))
        ds.createVariable('vy', 'f8', dimensions=('x', 'y'))
        ds['vx'][:] = vx
        ds['vy'][:] = vy

        ds.createVariable('tvx', 'f8', dimensions=('time', 'x', 'y'))
        ds.createVariable('tvy', 'f8', dimensions=('time', 'x', 'y'))
        ds['tvx'][:] = tvx
        ds['tvy'][:] = tvy

        ds.createVariable('dvx', 'f8', dimensions=('depth', 'x', 'y'))
        ds.createVariable('dvy', 'f8', dimensions=('depth', 'x', 'y'))
        ds['dvx'][:] = dvx
        ds['dvy'][:] = dvy

        ds.createVariable('tdvx', 'f8', dimensions=('time', 'depth', 'x', 'y'))
        ds.createVariable('tdvy', 'f8', dimensions=('time', 'depth', 'x', 'y'))
        ds['tdvx'][:] = tdvx
        ds['tdvy'][:] = tdvy

        for v in ds.variables:
            if 'v' in v:
                ds[v].units = 'm/s'

        ds.createDimension('nv', lin_nodes.shape[0])
        ds.createDimension('nele', lin_faces.shape[0])
        ds.createDimension('two', 2)
        ds.createDimension('three', 3)

        ds.createVariable('nodes', 'f8', dimensions=('nv', 'two'))
        ds.createVariable('faces', 'f8', dimensions=('nele', 'three'))
        ds.createVariable('lin_vx', 'f8', dimensions=('nv'))
        ds.createVariable('lin_vy', 'f8', dimensions=('nv'))
        ds.createVariable('lin_tvx', 'f8', dimensions=('time', 'nv'))
        ds.createVariable('lin_tvy', 'f8', dimensions=('time', 'nv'))
        ds.createVariable('lin_dvx', 'f8', dimensions=('depth', 'nv'))
        ds.createVariable('lin_dvy', 'f8', dimensions=('depth', 'nv'))
        ds.createVariable('lin_tdvx', 'f8', dimensions=('time', 'depth', 'nv'))
        ds.createVariable('lin_tdvy', 'f8', dimensions=('time', 'depth', 'nv'))

        for k, v in {
                'nodes': lin_nodes,
                'faces': lin_faces,
                'lin_vx': lin_vx,
                'lin_vy': lin_vy,
                'lin_tvx': lin_tvx,
                'lin_tvy': lin_tvy,
                'lin_dvx': lin_dvx,
                'lin_dvy': lin_dvy,
                'lin_tdvx': lin_tdvx,
                'lin_tdvy': lin_tdvy
        }.items():
            ds[k][:] = v

            if 'lin' in k:
                ds[k].units = 'm/s'

        PyGrid._get_grid_type(ds,
                              grid_topology={
                                  'node_lon': 'x',
                                  'node_lat': 'y'
                              })
        PyGrid._get_grid_type(ds)

        ds.setncattr('grid_type', 'sgrid')

    if ds is not None:
        # Need to test the dataset...
        sgt = {'node_lon': 'x', 'node_lat': 'y'}
        _sg = PyGrid.from_netCDF(dataset=ds,
                                 grid_topology=sgt,
                                 grid_type='sgrid')

        _sgc1 = GridCurrent.from_netCDF(dataset=ds,
                                        varnames=['vx', 'vy'],
                                        grid_topology=sgt)
        _sgc2 = GridCurrent.from_netCDF(dataset=ds,
                                        varnames=['tvx', 'tvy'],
                                        grid_topology=sgt)
        _sgc3 = GridCurrent.from_netCDF(dataset=ds,
                                        varnames=['dvx', 'dvy'],
                                        grid_topology=sgt)
        _sgc4 = GridCurrent.from_netCDF(dataset=ds,
                                        varnames=['tdvx', 'tdvy'],
                                        grid_topology=sgt)

        ugt = {'nodes': 'nodes', 'faces': 'faces'}
        #         ug = PyGrid_U(nodes=ds['nodes'][:], faces=ds['faces'][:])
        _ugc1 = GridCurrent.from_netCDF(dataset=ds,
                                        varnames=['lin_vx', 'lin_vy'],
                                        grid_topology=ugt)
        _ugc2 = GridCurrent.from_netCDF(dataset=ds,
                                        varnames=['lin_tvx', 'lin_tvy'],
                                        grid_topology=ugt)
        _ugc3 = GridCurrent.from_netCDF(dataset=ds,
                                        varnames=['lin_dvx', 'lin_dvy'],
                                        grid_topology=ugt)
        _ugc4 = GridCurrent.from_netCDF(dataset=ds,
                                        varnames=['lin_tdvx', 'lin_tdvy'],
                                        grid_topology=ugt)

        ds.close()

    return {
        'sgrid': (x, y),
        'sgrid_vel': (dvx, dvy),
        'sgrid_depth_vel': (tdvx, tdvy),
        'ugrid': (lin_nodes, lin_faces),
        'ugrid_depth_vel': (lin_tdvx, lin_tdvy)
    }
예제 #21
0
def make_model(images_dir=os.path.join(base_dir, 'images')):
    print 'initializing the model'

    # set up the modeling environment
    start_time = datetime(2016, 9, 18, 1, 0)
    model = Model(start_time=start_time,
                  duration=timedelta(days=3),
                  time_step=30 * 60,
                  uncertain=False)

    print 'adding the map'
    model.map = GnomeMap()  # this is a "water world -- no land anywhere"

    # renderere is only top-down view on 2d -- but it's something
    renderer = Renderer(
        output_dir=images_dir,
        size=(1024, 768),
        output_timestep=timedelta(hours=1),
    )
    renderer.viewport = ((-87.095, 27.595), (-87.905, 28.405))

    print 'adding outputters'
    model.outputters += renderer

    # Also going to write the results out to a netcdf file
    netcdf_file = os.path.join(base_dir, 'gulf_tamoc.nc')
    scripting.remove_netcdf(netcdf_file)

    model.outputters += NetCDFOutput(
        netcdf_file,
        which_data='most',
        # output most of the data associated with the elements
        output_timestep=timedelta(hours=2))

    print "adding Horizontal and Vertical diffusion"

    # Horizontal Diffusion
    model.movers += RandomMover(diffusion_coef=100000)
    # vertical diffusion (different above and below the mixed layer)
    model.movers += RandomVerticalMover(
        vertical_diffusion_coef_above_ml=50,
        vertical_diffusion_coef_below_ml=10,
        horizontal_diffusion_coef_above_ml=100000,
        horizontal_diffusion_coef_below_ml=100,
        mixed_layer_depth=10)

    print 'adding Rise Velocity'
    # droplets rise as a function of their density and radius
    model.movers += TamocRiseVelocityMover()

    print 'adding the 3D current mover'
    gc = GridCurrent.from_netCDF('HYCOM_3d.nc')

    model.movers += GridCurrentMover('HYCOM_3d.nc')
    #    model.movers += SimpleMover(velocity=(0., 0, 0.))
    #    model.movers += constant_wind_mover(5, 315, units='knots')

    # Wind from a buoy
    w = Wind(filename='KIKT.osm')
    model.movers += WindMover(w)

    # Now to add in the TAMOC "spill"
    print "Adding TAMOC spill"

    model.spills += tamoc_spill.TamocSpill(
        release_time=start_time,
        start_position=(-87.5, 28.0, 2000),
        num_elements=30000,
        end_release_time=start_time + timedelta(days=2),
        name='TAMOC plume',
        TAMOC_interval=None,  # how often to re-run TAMOC
    )

    model.spills[0].data_sources['currents'] = gc

    return model
예제 #22
0
def make_model(images_dir=os.path.join(base_dir, 'images')):
    print 'initializing the model'

    start_time = datetime(2016, 4, 5, 18, 0)


    model = Model(start_time=start_time,
                  duration=timedelta(hours=12),
                  time_step=.25 * 3600)

    mapfile = (os.path.join(base_dir, 'coast.bna'))

    print 'adding the map'
    '''TODO: sort out MapFromBna's map_bounds parameter...
    it does nothing right now, and the spill is out of bounds'''
    model.map = MapFromBNA(mapfile, refloat_halflife=0.0)  # seconds

    # draw_ontop can be 'uncertain' or 'forecast'
    # 'forecast' LEs are in black, and 'uncertain' are in red
    # default is 'forecast' LEs draw on top
    renderer = Renderer(mapfile, images_dir, image_size=(1024, 768))
#     renderer.viewport = ((-73.5, 40.5), (-73.1, 40.75))
#     renderer.viewport = ((-122.9, 45.6), (-122.6, 46.0))

    print 'adding outputters'
    model.outputters += renderer

    print 'adding a spill'
    # for now subsurface spill stays on initial layer
    # - will need diffusion and rise velocity
    # - wind doesn't act
    # - start_position = (-76.126872, 37.680952, 5.0),
    spill1 = point_line_release_spill(num_elements=500,
                                      start_position=(-82.73888,
                                                      27.5475,
                                                      0.0),
                                      release_time=start_time,
                                      end_release_time=start_time + timedelta(hours=24))
    spill2 = point_line_release_spill(num_elements=500,
                                      start_position=(-82.73888,
                                                      27.545,
                                                      0.0),
                                      release_time=start_time,
                                      end_release_time=start_time + timedelta(hours=24))
    spill3 = point_line_release_spill(num_elements=500,
                                      start_position=(-82.73888,
                                                      27.5425,
                                                      0.0),
                                      release_time=start_time,
                                      end_release_time=start_time + timedelta(hours=24))
    spill4 = point_line_release_spill(num_elements=500,
                                      start_position=(-82.73988,
                                                      27.5475,
                                                      0.0),
                                      release_time=start_time,
                                      end_release_time=start_time + timedelta(hours=24))

    spill5 = point_line_release_spill(num_elements=500,
                                      start_position=(-82.73988,
                                                      27.5450,
                                                      0.0),
                                      release_time=start_time,
                                      end_release_time=start_time + timedelta(hours=24))

    spill6 = point_line_release_spill(num_elements=500,
                                      start_position=(-82.73988,
                                                      27.5425,
                                                      0.0),
                                      release_time=start_time,
                                      end_release_time=start_time + timedelta(hours=24))


    model.spills += spill1
    model.spills += spill2
    model.spills += spill3
    model.spills += spill4
    model.spills += spill5
    model.spills += spill6
    model.spills._spill_container.spills.remove(0)


    print 'adding a current mover:'

    fn = 'nos.tbofs.fields.n000.20160406.t00z_sgrid.nc'
    # fn = 'dbofs_newFormat.nc'

    cf = GridCurrent.from_netCDF(filename=fn)
    u_mover = PyCurrentMover(cf, extrapolate=True)
    # u_mover = GridCurrentMover(fn)
    renderer.add_grid(cf.grid)
#     renderer.add_vec_prop(cf)
    model.movers += u_mover

    # curr_file = get_datafile(os.path.join(base_dir, 'COOPSu_CREOFS24.nc'))
    # c_mover = GridCurrentMover(curr_file)
    # model.movers += c_mover

    return model
예제 #23
0
def make_model(images_dir=os.path.join(base_dir, 'images')):
    print 'initializing the model'

    start_time = datetime(2012, 10, 25, 0, 1)
    # start_time = datetime(2015, 12, 18, 06, 01)

    # 1 day of data in file
    # 1/2 hr in seconds
    model = Model(start_time=start_time,
                  duration=timedelta(hours=2),
                  time_step=900)

    mapfile = get_datafile(os.path.join(base_dir, 'nyharbor.bna'))

    print 'adding the map'
    '''TODO: sort out MapFromBna's map_bounds parameter...
    it does nothing right now, and the spill is out of bounds'''
    model.map = MapFromBNA(mapfile, refloat_halflife=0.0)  # seconds

    # draw_ontop can be 'uncertain' or 'forecast'
    # 'forecast' LEs are in black, and 'uncertain' are in red
    # default is 'forecast' LEs draw on top
    renderer = Renderer(mapfile, images_dir, image_size=(1024, 768))
#     renderer.viewport = ((-73.5, 40.5), (-73.1, 40.75))
#     renderer.viewport = ((-122.9, 45.6), (-122.6, 46.0))

    print 'adding outputters'
    model.outputters += renderer

    netcdf_file = os.path.join(base_dir, 'script_ny_plume.nc')
    scripting.remove_netcdf(netcdf_file)

    model.outputters += NetCDFOutput(netcdf_file, which_data='all')

    print 'adding two spills'
    # Break the spill into two spills, first with the larger droplets
    # and second with the smaller droplets.
    # Split the total spill volume (100 m^3) to have most
    # in the larger droplet spill.
    # Smaller droplets start at a lower depth than larger

    end_time = start_time + model.duration
#     wd = WeibullDistribution(alpha=1.8,
#                              lambda_=.00456,
#                              min_=.0002)  # 200 micron min
# 
#     spill = subsurface_plume_spill(num_elements=10,
#                                    start_position=(-74.15,
#                                                    40.5,
#                                                    7.2),
#                                    release_time=start_time,
#                                    distribution=wd,
#                                    amount=90,  # default volume_units=m^3
#                                    units='m^3',
#                                    end_release_time=end_time,
#                                    density=600)
# 
#     model.spills += spill

#     wd = WeibullDistribution(alpha=1.8,
#                              lambda_=.00456,
#                              max_=.0002)  # 200 micron max

    wd = UniformDistribution(low=.0002,
                             high=.0002)

    spill = point_line_release_spill(num_elements=10, amount=90,
                                     units='m^3',
                                     start_position=(-74.15,
                                                     40.5,
                                                     7.2),
                                     release_time=start_time,
                                     element_type=plume(distribution=wd,
                                                        substance_name='ALASKA NORTH SLOPE (MIDDLE PIPELINE)')
                                     )
    model.spills += spill

    print 'adding a RandomMover:'
    model.movers += RandomMover(diffusion_coef=50000)

    print 'adding a RiseVelocityMover:'
    model.movers += RiseVelocityMover()

    print 'adding a RandomVerticalMover:'
#     model.movers += RandomVerticalMover(vertical_diffusion_coef_above_ml=5,
#                                         vertical_diffusion_coef_below_ml=.11,
#                                         mixed_layer_depth=10)

    url = ('http://geoport.whoi.edu/thredds/dodsC/clay/usgs/users/jcwarner/Projects/Sandy/triple_nest/00_dir_NYB05.ncml')
    gc = GridCurrent.from_netCDF(url)
    u_mover = PyGridCurrentMover(gc, default_num_method='Trapezoid')
    model.movers += u_mover
    # print 'adding a wind mover:'

    # series = np.zeros((2, ), dtype=gnome.basic_types.datetime_value_2d)
    # series[0] = (start_time, (30, 90))
    # series[1] = (start_time + timedelta(hours=23), (30, 90))

    # wind = Wind(timeseries=series, units='knot')
    #
    # default is .4 radians
    # w_mover = gnome.movers.WindMover(wind, uncertain_angle_scale=0)
    #
    # model.movers += w_mover

    print 'adding a simple mover:'
#     s_mover = SimpleMover(velocity=(0.0, -.3, 0.0))
#     model.movers += s_mover

    return model
def gen_vortex_3D(filename=None):
    x, y = np.mgrid[-30:30:61j, -30:30:61j]

    y = np.ascontiguousarray(y.T)
    x = np.ascontiguousarray(x.T)

    x_size = 61
    y_size = 61

    g = Grid_S(node_lon=x,
               node_lat=y)
    g.build_celltree()

    lin_nodes = g._cell_trees['node'][1]
    lin_faces = np.array([np.array([([lx, lx + x_size + 1, lx + 1],
                                     [lx, lx + x_size, lx + x_size + 1])
                                    for lx in range(0, x_size - 1, 1)]) + ly * x_size
                          for ly in range(0, y_size - 1)])
    lin_faces = lin_faces.reshape(-1, 3)

    # y += np.sin(x) / 1
    # x += np.sin(x) / 5

    t0 = datetime(2001, 1, 1, 0, 0)
    tarr = [t0 + timedelta(hours=i) for i in range(0, 11)]
    angs = -np.arctan2(y, x)
    mag = np.sqrt(x ** 2 + y ** 2)

    vx = np.cos(angs) * mag
    vy = np.sin(angs) * mag
    vx = vx[np.newaxis, :] * 20
    vy = vy[np.newaxis, :] * 20

    vw = -0.001

    d_scale = [1, 0.5, 0, -0.5, -1]
    t_scale = np.linspace(0, 1, 11)

    tvx = np.array([vx * t for t in t_scale]).squeeze()
    tvy = np.array([vy * t for t in t_scale]).squeeze()

    dvx = np.array([vx * s for s in d_scale]).squeeze()
    dvy = np.array([vy * s for s in d_scale]).squeeze()

    tdvx = np.array([dvx * t for t in t_scale]).squeeze()
    tdvy = np.array([dvy * t for t in t_scale]).squeeze()

    lin_vx = vx.reshape(-1)
    lin_vy = vy.reshape(-1)

    lin_tvx = np.array([lin_vx * t for t in t_scale])
    lin_tvy = np.array([lin_vy * t for t in t_scale])

    lin_dvx = np.array([lin_vx * s for s in d_scale])
    lin_dvy = np.array([lin_vy * s for s in d_scale])

    lin_tdvx = np.array([lin_dvx * t for t in t_scale])
    lin_tdvy = np.array([lin_dvy * t for t in t_scale])

    ds = None

    if filename is not None:
        ds = nc4.Dataset(filename, 'w', diskless=True, persist=True)

        ds.createDimension('y', y.shape[0])
        ds.createDimension('x', x.shape[1])
        ds.createDimension('time', len(tarr))
        ds.createDimension('depth', len(d_scale))

        ds.createVariable('x', 'f8', dimensions=('x', 'y'))
        ds['x'][:] = x

        ds.createVariable('y', 'f8', dimensions=('x', 'y'))
        ds['y'][:] = y

        ds.createVariable('time', 'f8', dimensions=('time'))
        ds['time'][:] = nc4.date2num(tarr, 'hours since {0}'.format(t0))
        ds['time'].setncattr('units', 'hours since {0}'.format(t0))

        ds.createVariable('vx', 'f8', dimensions=('x', 'y'))
        ds.createVariable('vy', 'f8', dimensions=('x', 'y'))
        ds['vx'][:] = vx
        ds['vy'][:] = vy

        ds.createVariable('tvx', 'f8', dimensions=('time', 'x', 'y'))
        ds.createVariable('tvy', 'f8', dimensions=('time', 'x', 'y'))
        ds['tvx'][:] = tvx
        ds['tvy'][:] = tvy

        ds.createVariable('dvx', 'f8', dimensions=('depth', 'x', 'y'))
        ds.createVariable('dvy', 'f8', dimensions=('depth', 'x', 'y'))
        ds['dvx'][:] = dvx
        ds['dvy'][:] = dvy

        ds.createVariable('tdvx', 'f8', dimensions=('time', 'depth', 'x', 'y'))
        ds.createVariable('tdvy', 'f8', dimensions=('time', 'depth', 'x', 'y'))
        ds['tdvx'][:] = tdvx
        ds['tdvy'][:] = tdvy

        for v in ds.variables:
            if 'v' in v:
                ds[v].units = 'm/s'

        ds.createDimension('nv', lin_nodes.shape[0])
        ds.createDimension('nele', lin_faces.shape[0])
        ds.createDimension('two', 2)
        ds.createDimension('three', 3)

        ds.createVariable('nodes', 'f8', dimensions=('nv', 'two'))
        ds.createVariable('faces', 'f8', dimensions=('nele', 'three'))
        ds.createVariable('lin_vx', 'f8', dimensions=('nv'))
        ds.createVariable('lin_vy', 'f8', dimensions=('nv'))
        ds.createVariable('lin_tvx', 'f8', dimensions=('time', 'nv'))
        ds.createVariable('lin_tvy', 'f8', dimensions=('time', 'nv'))
        ds.createVariable('lin_dvx', 'f8', dimensions=('depth', 'nv'))
        ds.createVariable('lin_dvy', 'f8', dimensions=('depth', 'nv'))
        ds.createVariable('lin_tdvx', 'f8', dimensions=('time', 'depth', 'nv'))
        ds.createVariable('lin_tdvy', 'f8', dimensions=('time', 'depth', 'nv'))

        for k, v in {'nodes': lin_nodes,
                     'faces': lin_faces,
                     'lin_vx': lin_vx,
                     'lin_vy': lin_vy,
                     'lin_tvx': lin_tvx,
                     'lin_tvy': lin_tvy,
                     'lin_dvx': lin_dvx,
                     'lin_dvy': lin_dvy,
                     'lin_tdvx': lin_tdvx,
                     'lin_tdvy': lin_tdvy
                     }.items():
            ds[k][:] = v

            if 'lin' in k:
                ds[k].units = 'm/s'

        PyGrid._get_grid_type(ds,
                              grid_topology={'node_lon': 'x', 'node_lat': 'y'})
        PyGrid._get_grid_type(ds)

        ds.setncattr('grid_type', 'sgrid')

    if ds is not None:
        # Need to test the dataset...
        sgt = {'node_lon': 'x', 'node_lat': 'y'}
        _sg = PyGrid.from_netCDF(dataset=ds, grid_topology=sgt,
                                 grid_type='sgrid')

        _sgc1 = GridCurrent.from_netCDF(dataset=ds, varnames=['vx', 'vy'],
                                        grid_topology=sgt)
        _sgc2 = GridCurrent.from_netCDF(dataset=ds, varnames=['tvx', 'tvy'],
                                        grid_topology=sgt)
        _sgc3 = GridCurrent.from_netCDF(dataset=ds, varnames=['dvx', 'dvy'],
                                        grid_topology=sgt)
        _sgc4 = GridCurrent.from_netCDF(dataset=ds, varnames=['tdvx', 'tdvy'],
                                        grid_topology=sgt)

        ugt = {'nodes': 'nodes', 'faces': 'faces'}
#         ug = PyGrid_U(nodes=ds['nodes'][:], faces=ds['faces'][:])
        _ugc1 = GridCurrent.from_netCDF(dataset=ds,
                                        varnames=['lin_vx', 'lin_vy'],
                                        grid_topology=ugt)
        _ugc2 = GridCurrent.from_netCDF(dataset=ds,
                                        varnames=['lin_tvx', 'lin_tvy'],
                                        grid_topology=ugt)
        _ugc3 = GridCurrent.from_netCDF(dataset=ds,
                                        varnames=['lin_dvx', 'lin_dvy'],
                                        grid_topology=ugt)
        _ugc4 = GridCurrent.from_netCDF(dataset=ds,
                                        varnames=['lin_tdvx', 'lin_tdvy'],
                                        grid_topology=ugt)

        ds.close()

    return {'sgrid': (x, y),
            'sgrid_vel': (dvx, dvy),
            'sgrid_depth_vel': (tdvx, tdvy),
            'ugrid': (lin_nodes, lin_faces),
            'ugrid_depth_vel': (lin_tdvx, lin_tdvy)}
예제 #25
0
def make_model(images_dir=os.path.join(base_dir, 'images')):
    print 'initializing the model'

    # set up the modeling environment
    start_time = datetime(2016, 9, 23, 0, 0)
    model = Model(start_time=start_time,
                  duration=timedelta(days=2),
                  time_step=30 * 60,
                  uncertain=False)

    print 'adding the map'
    model.map = GnomeMap()  # this is a "water world -- no land anywhere"

    # renderere is only top-down view on 2d -- but it's something
    renderer = Renderer(
        output_dir=images_dir,
        size=(1024, 768),
        output_timestep=timedelta(hours=1),
    )
    renderer.viewport = ((196.14, 71.89), (196.18, 71.93))

    print 'adding outputters'
    model.outputters += renderer

    # Also going to write the results out to a netcdf file
    netcdf_file = os.path.join(base_dir, 'script_arctic_plume.nc')
    scripting.remove_netcdf(netcdf_file)

    model.outputters += NetCDFOutput(
        netcdf_file,
        which_data='most',
        # output most of the data associated with the elements
        output_timestep=timedelta(hours=2))

    print "adding Horizontal and Vertical diffusion"

    # Horizontal Diffusion
    model.movers += RandomMover(diffusion_coef=500)
    # vertical diffusion (different above and below the mixed layer)
    model.movers += RandomVerticalMover(vertical_diffusion_coef_above_ml=5,
                                        vertical_diffusion_coef_below_ml=.11,
                                        mixed_layer_depth=10)

    print 'adding Rise Velocity'
    # droplets rise as a function of their density and radius
    model.movers += TamocRiseVelocityMover()

    print 'adding a circular current and eastward current'
    fn = 'hycom_glb_regp17_2016092300_subset.nc'
    fn_ice = 'hycom-cice_ARCu0.08_046_2016092300_subset.nc'
    import pysgrid
    import netCDF4 as nc
    df = nc.Dataset(fn)
    lon = df['lon'][:]
    lat = df['lat'][:]
    grd = pysgrid.SGrid(node_lon=np.repeat(lon.reshape(1, -1),
                                           len(lat),
                                           axis=0),
                        node_lat=np.repeat(lat.reshape(-1, 1),
                                           len(lon),
                                           axis=1))
    print(grd.node_lon.shape)
    print(grd.node_lat.shape)
    gc = GridCurrent.from_netCDF(fn, units='m/s', grid=grd)

    model.movers += IceMover(fn_ice)
    model.movers += GridCurrentMover(fn)
    model.movers += SimpleMover(velocity=(0., 0., 0.))
    model.movers += constant_wind_mover(20, 315, units='knots')

    # Now to add in the TAMOC "spill"
    print "Adding TAMOC spill"

    model.spills += tamoc_spill.TamocSpill(
        release_time=start_time,
        start_position=(196.16, 71.91, 40.0),
        num_elements=1000,
        end_release_time=start_time + timedelta(days=1),
        name='TAMOC plume',
        TAMOC_interval=None,  # how often to re-run TAMOC
    )

    model.spills[0].data_sources['currents'] = gc

    return model
예제 #26
0
def make_model(images_dir=os.path.join(base_dir, 'images')):
    print 'initializing the model'

    start_time = datetime(2016, 4, 5, 18, 0)


    model = Model(start_time=start_time,
                  duration=timedelta(hours=12),
                  time_step=.25 * 3600)

    mapfile = (os.path.join(base_dir, 'coast.bna'))

    print 'adding the map'
    '''TODO: sort out MapFromBna's map_bounds parameter...
    it does nothing right now, and the spill is out of bounds'''
    model.map = MapFromBNA(mapfile, refloat_halflife=0.0)  # seconds

    # draw_ontop can be 'uncertain' or 'forecast'
    # 'forecast' LEs are in black, and 'uncertain' are in red
    # default is 'forecast' LEs draw on top
    renderer = Renderer(mapfile, images_dir, image_size=(1024, 768))
#     renderer.viewport = ((-73.5, 40.5), (-73.1, 40.75))
#     renderer.viewport = ((-122.9, 45.6), (-122.6, 46.0))

    print 'adding outputters'
    model.outputters += renderer

    print 'adding a spill'
    # for now subsurface spill stays on initial layer
    # - will need diffusion and rise velocity
    # - wind doesn't act
    # - start_position = (-76.126872, 37.680952, 5.0),
    spill1 = point_line_release_spill(num_elements=500,
                                      start_position=(-82.73888,
                                                      27.5475,
                                                      0.0),
                                      release_time=start_time,
                                      end_release_time=start_time + timedelta(hours=24))
    spill2 = point_line_release_spill(num_elements=500,
                                      start_position=(-82.73888,
                                                      27.545,
                                                      0.0),
                                      release_time=start_time,
                                      end_release_time=start_time + timedelta(hours=24))
    spill3 = point_line_release_spill(num_elements=500,
                                      start_position=(-82.73888,
                                                      27.5425,
                                                      0.0),
                                      release_time=start_time,
                                      end_release_time=start_time + timedelta(hours=24))
    spill4 = point_line_release_spill(num_elements=500,
                                      start_position=(-82.73988,
                                                      27.5475,
                                                      0.0),
                                      release_time=start_time,
                                      end_release_time=start_time + timedelta(hours=24))

    spill5 = point_line_release_spill(num_elements=500,
                                      start_position=(-82.73988,
                                                      27.5450,
                                                      0.0),
                                      release_time=start_time,
                                      end_release_time=start_time + timedelta(hours=24))

    spill6 = point_line_release_spill(num_elements=500,
                                      start_position=(-82.73988,
                                                      27.5425,
                                                      0.0),
                                      release_time=start_time,
                                      end_release_time=start_time + timedelta(hours=24))


    model.spills += spill1
    model.spills += spill2
    model.spills += spill3
    model.spills += spill4
    model.spills += spill5
    model.spills += spill6
    model.spills._spill_container.spills.remove(0)


    print 'adding a current mover:'

    fn = 'nos.tbofs.fields.n000.20160406.t00z_sgrid.nc'
    # fn = 'dbofs_newFormat.nc'

    cf = GridCurrent.from_netCDF(filename=fn)
    u_mover = PyCurrentMover(cf, extrapolate=True)
    # u_mover = GridCurrentMover(fn)
    renderer.add_grid(cf.grid)
#     renderer.add_vec_prop(cf)
    model.movers += u_mover

    # curr_file = get_datafile(os.path.join(base_dir, 'COOPSu_CREOFS24.nc'))
    # c_mover = GridCurrentMover(curr_file)
    # model.movers += c_mover

    return model
예제 #27
0
def make_model(images_dir=os.path.join(base_dir, 'images')):
    print 'initializing the model'

    start_time = datetime(1985, 1, 1, 13, 31)

    # 1 day of data in file
    # 1/2 hr in seconds
    model = Model(start_time=start_time,
                  duration=timedelta(days=4),
                  time_step=7200)

#     mapfile = get_datafile(os.path.join(base_dir, 'ak_arctic.bna'))
    mapfile = get_datafile('arctic_coast3.bna')

    print 'adding the map'
    model.map = MapFromBNA(mapfile, refloat_halflife=0.0)  # seconds

    print 'adding a spill'
    # for now subsurface spill stays on initial layer
    # - will need diffusion and rise velocity
    # - wind doesn't act
    # - start_position = (-76.126872, 37.680952, 5.0),
#     spill1 = point_line_release_spill(num_elements=10000,
#                                       start_position=(-163.75,
#                                                       69.75,
#                                                       0.0),
#                                       release_time=start_time)
#
    spill1 = point_line_release_spill(num_elements=50000,
                                      start_position=(196.25,
                                                      69.75,
                                                      0.0),
                                      release_time=start_time)

    model.spills += spill1
#     model.spills += spill2

    print 'adding a wind mover:'

#     model.movers += constant_wind_mover(0.5, 0, units='m/s')

    print 'adding a current mover:'

    fn = ['arctic_avg2_0001_gnome.nc',
          'arctic_avg2_0002_gnome.nc']

#     fn = ['C:\\Users\\jay.hennen\\Documents\\Code\\pygnome\\py_gnome\\scripts\\script_TAP\\arctic_avg2_0001_gnome.nc',
#           'C:\\Users\\jay.hennen\\Documents\\Code\\pygnome\\py_gnome\\scripts\\script_TAP\\arctic_avg2_0002_gnome.nc']

    gt = {'node_lon': 'lon',
          'node_lat': 'lat'}
#     fn='arctic_avg2_0001_gnome.nc'

    wind_method = 'Euler'
    method = 'RK2'
    print 'adding outputters'

    # draw_ontop can be 'uncertain' or 'forecast'
    # 'forecast' LEs are in black, and 'uncertain' are in red
    # default is 'forecast' LEs draw on top
    renderer = Renderer(mapfile, images_dir, image_size=(1024, 768))
    model.outputters += renderer
    netcdf_file = os.path.join(base_dir, str(model.time_step / 60) + method + '.nc')
    scripting.remove_netcdf(netcdf_file)

    print 'adding movers'
    model.outputters += NetCDFOutput(netcdf_file, which_data='all')


    print 'loading entire current data'
    ice_aware_curr = IceAwareCurrent.from_netCDF(filename=fn,
                                                 grid_topology=gt)

#     env1 = get_env_from_netCDF(filename)
#     mov = PyCurrentMover.from_netCDF(filename)

    ice_aware_curr.ice_velocity.variables[0].dimension_ordering = ['time', 'x', 'y']
    ice_aware_wind = IceAwareWind.from_netCDF(filename=fn,
                                              ice_velocity=ice_aware_curr.ice_velocity,
                                              ice_concentration=ice_aware_curr.ice_concentration,
                                              grid=ice_aware_curr.grid)

    curr = GridCurrent.from_netCDF(filename=fn)
#     GridCurrent.is_gridded()

#     import pprint as pp
#     from gnome.utilities.orderedcollection import OrderedCollection
#     model.environment = OrderedCollection(dtype=Environment)
#     model.environment.add(ice_aware_curr)
#     from gnome.environment import WindTS

    print 'loading entire wind data'

#     i_c_mover = PyCurrentMover(current=ice_aware_curr)
#     i_c_mover = PyCurrentMover(current=ice_aware_curr, default_num_method='Euler')
    i_c_mover = PyCurrentMover(current=ice_aware_curr, default_num_method=method, extrapolate=True)
    i_w_mover = PyWindMover(wind=ice_aware_wind, default_num_method=wind_method)

#     ice_aware_curr.grid.node_lon = ice_aware_curr.grid.node_lon[:]-360
#     ice_aware_curr.grid.build_celltree()
    model.movers += i_c_mover
    model.movers += i_w_mover

    print 'adding an IceAwareRandomMover:'
    model.movers += IceAwareRandomMover(ice_concentration=ice_aware_curr.ice_concentration,
                                        diffusion_coef=1000)
#     renderer.add_grid(ice_aware_curr.grid)
#     renderer.add_vec_prop(ice_aware_curr)


    # curr_file = get_datafile(os.path.join(base_dir, 'COOPSu_CREOFS24.nc'))
    # c_mover = GridCurrentMover(curr_file)
    # model.movers += c_mover
#     model.environment.add(WindTS.constant(10, 300))
#     print('Saving')
#     model.environment[0].ice_velocity.variables[0].serialize()
#     IceVelocity.deserialize(model.environment[0].ice_velocity.serialize())
#     model.save('.')
#     from gnome.persist.save_load import load
#     print('Loading')
#     model2 = load('./Model.zip')

    return model
예제 #28
0
def make_model(images_dir=os.path.join(base_dir, 'images')):
    print 'initializing the model'

    start_time = datetime(2015, 9, 24, 1, 1)
    # start_time = datetime(2015, 12, 18, 06, 01)

    # 1 day of data in file
    # 1/2 hr in seconds
    model = Model(start_time=start_time,
                  duration=timedelta(hours=47),
                  time_step=300)

    mapfile = get_datafile(os.path.join(base_dir, 'columbia_river.bna'))

    print 'adding the map'
    model.map = MapFromBNA(mapfile, refloat_halflife=0.0)  # seconds

    # draw_ontop can be 'uncertain' or 'forecast'
    # 'forecast' LEs are in black, and 'uncertain' are in red
    # default is 'forecast' LEs draw on top
    renderer = Renderer(
        mapfile, images_dir, image_size=(600, 1200))
    renderer.delay = 15
#     renderer.viewport = ((-123.35, 45.6), (-122.68, 46.13))
#     renderer.viewport = ((-122.9, 45.6), (-122.6, 46.0))

    print 'adding outputters'
    model.outputters += renderer

    print 'adding a spill'
    # for now subsurface spill stays on initial layer
    # - will need diffusion and rise velocity
    # - wind doesn't act
    # - start_position = (-76.126872, 37.680952, 5.0),
    spill1 = continuous_release_spill(initial_elements=10000,
                                      num_elements=400,
                                      start_position=(-122.625,
                                                      45.609,
                                                      0.0),
                                      release_time=start_time,
                                      end_position=(-122.6, 45.605, 0.0),
                                      end_release_time=start_time + timedelta(seconds=36000))

    model.spills += spill1

    print 'adding a RandomMover:'
#     model.movers += RandomMover(diffusion_coef=10000)

    print 'adding a wind mover:'
    series = []
    for i in [(1, (5, 90)), (7, (5, 180)), (13, (5, 270)), (19, (5, 0)), (25, (5, 90))]:
        series.append((start_time + timedelta(hours=i[0]), i[1]))

    wind1 = WindTS.constant_wind('wind1', 0.5, 0, 'm/s')
    wind2 = WindTS(timeseries=series, units='knots', extrapolate=True)

#     wind = Wind(timeseries=series, units='knots')

    model.movers += PyWindMover(wind=wind1)

    print 'adding a current mover:'

#     url = ('http://geoport.whoi.edu/thredds/dodsC/clay/usgs/users/jcwarner/Projects/Sandy/triple_nest/00_dir_NYB05.ncml')
#     test = GridCurrent.from_netCDF(name='gc1', filename=url)

    curr_file = get_datafile('COOPSu_CREOFS24.nc')
    curr = GridCurrent.from_netCDF(name='gc2', filename=curr_file,)

    c_mover = PyCurrentMover(curr, extrapolate=True, default_num_method='Trapezoid')

#     renderer.add_grid(curr.grid)
#     renderer.add_vec_prop(curr)
    model.movers += c_mover

    print 'adding a random mover'
    model.movers += RandomMover(diffusion_coef=1000)


    # curr_file = get_datafile(os.path.join(base_dir, 'COOPSu_CREOFS24.nc'))
    # c_mover = GridCurrentMover(curr_file)
    # model.movers += c_mover

    return model