Example #1
0
    def test_serialize_deserialize(self):
        """
        test create new object from to_dict
        """
        gmap = MapFromBNA(testbnamap, 6)

        serial = gmap.serialize()
        map2 = MapFromBNA.deserialize(serial)

        assert gmap == map2
Example #2
0
    def test_update_from_dict_MapFromBNA(self):
        'test update_from_dict for MapFromBNA'
        gmap = MapFromBNA(testbnamap, 6)

        dict_ = {}
        dict_['map_bounds'] = [(-10, 10), (10, 10), (10, -10), (-10, -10)]
        dict_['spillable_area'] = [[(-5, 5), (5, 5), (5, -5), (-5, -5)]]
        dict_['refloat_halflife'] = 2
        assert np.all(gmap.map_bounds != dict_['map_bounds'])

        gmap.update_from_dict(dict_)
        assert gmap.map_bounds is not dict_['map_bounds']
        assert np.all(gmap.map_bounds == dict_['map_bounds'])
Example #3
0
def test_in_water_resolution():
    '''
    Test the limits of the precision, to within an order of magnitude,
    defining whether a point is in or out of water.
    '''

    # Create an 500x500 pixel map, with an LE refloat half-life of 2 hours
    # (specified here in seconds).
    m = MapFromBNA(filename=testbnamap,
                   refloat_halflife=2,
                   raster_size=500 * 500)

    # Specify coordinates of the two points that make up the
    # southeastern coastline segment of the island in the BNA map.

    x1 = -126.78709
    y1 = 47.666667
    x2 = -126.44218
    y2 = 47.833333

    # Define a point on the line formed by this coastline segment.

    slope = (y2 - y1) / (x2 - x1)
    b = y1 - slope * x1
    py = 47.7
    px = (py - b) / slope

    # Find the order of magnitude epsilon change in the latitude that causes
    # the given point to "move" from water to land.
    # eps == Distance between 1 and the nearest floating point number.

    eps = np.spacing(1)
    mag = 0.
    running = True
    while running:
        mag = mag + 1.
        print 'Order of magnitude: %g' % mag
        running = m.in_water((px, py + eps * 10.0**mag, 0.))

    # Difference in position within an order of magnitude in
    # degrees of latitude necessary to "move" point from water to land.

    dlatO0 = eps * 10.0**(mag - 1.)
    dlatO1 = eps * 10.0**mag

    msg = \
        '''A particle positioned on a coastline segment must be moved
    something more than {0} meters, but less than {1} meters,
    inland before pyGNOME acknowledges it's no longer in water.'''
    print msg.format(dlatO0 * 1852.0, dlatO1 * 1852.0)
Example #4
0
    def test_deserialize(self):
        ## fixme: this should fail with no spillable area ?!?
        jsblob = self.map.serialize()

        jsblob['spillable_area'] = None

        pprint(jsblob)

        # {'approximate_raster_interval': 53.9608870724,
        #  'filename': u'/Users/chris.barker/Hazmat/GitLab/pygnome/py_gnome/tests/unit_tests/sample_data/florida_with_lake_small.bna',
        #  'id': u'b3590b7d-aab1-11ea-8899-1e00b098d304',
        #  'map_bounds': [(-82.8609915978, 24.5472415066),
        #                 (-82.8609915978, 28.1117673335),
        #                 (-80.0313642811, 28.1117673335),
        #                 (-80.0313642811, 24.5472415066)],
        #  'name': u'MapFromBNA_8',
        #  'obj_type': u'gnome.maps.map.MapFromBNA',
        #  'raster_size': 16777216.0,
        #  'refloat_halflife': 1.0}

        map = MapFromBNA.deserialize(jsblob)

        print map.spillable_area
        print map.land_polys

        assert map.spillable_area is None
        assert len(map.map_bounds) == 4
Example #5
0
def make_model(images_dir=os.path.join(base_dir, 'images')):
    print 'initializing the model'

    start_time = datetime(2012, 9, 15, 12, 0)
    mapfile = get_datafile(os.path.join(base_dir, './LongIslandSoundMap.BNA'))

    gnome_map = MapFromBNA(mapfile, refloat_halflife=6)  # hours

    # # the image output renderer
    # global renderer

    # one hour timestep
    model = Model(start_time=start_time,
                  duration=timedelta(hours=48),
                  time_step=3600,
                  map=gnome_map,
                  uncertain=True,
                  cache_enabled=True)

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

    print 'adding outputters'
    model.outputters += Renderer(mapfile, images_dir, size=(800, 600))
    model.outputters += NetCDFOutput(netcdf_file, which_data='all')

    print 'adding a spill'
    spill = point_line_release_spill(num_elements=1000,
                                     start_position=(-72.419992, 41.202120,
                                                     0.0),
                                     release_time=start_time)
    model.spills += spill

    print 'adding a RandomMover:'
    model.movers += RandomMover(diffusion_coef=500000, uncertain_factor=2)

    print 'adding a wind mover:'
    series = np.zeros((5, ), dtype=datetime_value_2d)
    series[0] = (start_time, (10, 45))
    series[1] = (start_time + timedelta(hours=18), (10, 90))
    series[2] = (start_time + timedelta(hours=30), (10, 135))
    series[3] = (start_time + timedelta(hours=42), (10, 180))
    series[4] = (start_time + timedelta(hours=54), (10, 225))

    wind = Wind(timeseries=series, units='m/s')
    model.movers += WindMover(wind)

    print 'adding a cats mover:'
    curr_file = get_datafile(os.path.join(base_dir, r"./LI_tidesWAC.CUR"))
    tide_file = get_datafile(os.path.join(base_dir, r"./CLISShio.txt"))

    c_mover = CatsMover(curr_file, tide=Tide(tide_file))
    model.movers += c_mover
    model.environment += c_mover.tide

    print 'viewport is:', [
        o.viewport for o in model.outputters if isinstance(o, Renderer)
    ]

    return model
Example #6
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 is broken, fix and include the following section
    #     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 = PyCurrentMover(cf, default_num_method='Euler')
    #     model.movers += u_mover
    #

    return model
Example #7
0
def simple_model(output_dir):
    start_time = "2018-09-20T12:00"
    model = gs.Model(
        start_time=start_time,
        duration=gs.days(1),
        time_step=gs.minutes(30),
        name="test model for tideflats",
    )
    model.map = MapFromBNA(bna_file)
    model.movers += gs.constant_wind_mover(10, 300, "m/s")

    model.spills += gs.surface_point_line_spill(
        num_elements=100,
        start_position=(5.4, 53.38, 0),
        end_position=(5.8, 53.4, 0),
        release_time=start_time,
    )
    model.outputters += gs.Renderer(
        output_timestep=gs.hours(1),
        map_filename=bna_file,
        output_dir=output_dir,
        formats=['gif'],  # ['gif', 'png']
        image_size=(800, 400),
        # viewport=((4.5, 53.0),
        #           (5.5, 53.5)),
    )

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

    start_time = datetime(2015, 9, 24, 3, 0)

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

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

    print 'adding the map'
    model.map = MapFromBNA(mapfile, refloat_halflife=1, raster_size=1024*1024)  # 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=(800, 600),
                        output_timestep=timedelta(hours=1),
                        timestamp_attrib={'size': 'medium', 'color':'uncert_LE'})
    renderer.set_timestamp_attrib(format='%a %c')
    renderer.graticule.set_DMS(True)
#     renderer.viewport = ((-124.25, 47.5), (-122.0, 48.70))


    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=5000,
                                     start_position=(0.0,
                                                     0.0,
                                                     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(13, 270, units='m/s')

    print 'adding a current mover:'
#     curr_file = get_datafile(os.path.join(base_dir, 'COOPSu_CREOFS24.nc'))
#
#     # uncertain_time_delay in hours
#     c_mover = GridCurrentMover(curr_file)
#     c_mover.uncertain_cross = 0  # default is .25
#
#     model.movers += c_mover

    return model
Example #9
0
def sample_model2_fixture_base():
    """
    sample model with no outputter and no spills. Use this as a template for
    fixtures to add spills
    Uses:
        sample_data/MapBounds_Island.bna
        Contains: gnome.movers.SimpleMover(velocity=(1.0, -1.0, 0.0))
        duration is 1 hour with 15min intervals so 5 timesteps total,
        including initial condition,
        model is uncertain and cache is not enabled
        No spills or outputters defined

    To use:
        add a spill and run

    :returns: It returns a dict -
        {'model':model,
         'release_start_pos':start_points,
         'release_end_pos':end_points}
        The release_start_pos and release_end_pos can be used by test to define
        the spill's 'start_position' and 'end_position'
    """

    release_time = datetime(2012, 9, 15, 12, 0)

    # the image output map

    mapfile = os.path.join(os.path.dirname(__file__),
                           './sample_data/long_island_sound',
                           'LongIslandSoundMap.BNA')

    # the land-water map

    map_ = MapFromBNA(mapfile, refloat_halflife=06)  # seconds

    model = Model(
        time_step=timedelta(minutes=10),
        start_time=release_time,
        duration=timedelta(hours=1),
        map=map_,
        uncertain=True,
        cache_enabled=False,
    )

    # model.movers += SimpleMover(velocity=(1., -1., 0.0))

    # model.uncertain = True

    start_points = np.zeros((3, ), dtype=np.float64)
    end_points = np.zeros((3, ), dtype=np.float64)

    start_points[:] = (-72.83, 41.13, 0)
    end_points[:] = (-72.83, 41.13, 0)

    return {
        'model': model,
        'release_start_pos': start_points,
        'release_end_pos': end_points
    }
def make_model(images_dir=os.path.join(base_dir, 'images')):

    print 'creating the maps'
    mapfile = get_datafile(os.path.join(base_dir, 'LowerMississippiMap.bna'))
    gnome_map = MapFromBNA(mapfile, refloat_halflife=6)  # hours

    print 'initializing the model'
    start_time = datetime(2012, 9, 15, 12, 0)

    # default to now, rounded to the nearest hour
    model = Model(time_step=600,
                  start_time=start_time,
                  duration=timedelta(days=1),
                  map=gnome_map,
                  uncertain=True)

    print 'adding outputters'
    model.outputters += Renderer(mapfile, images_dir, image_size=(800, 600))

    netcdf_file = os.path.join(base_dir, 'script_lower_mississippi.nc')
    scripting.remove_netcdf(netcdf_file)
    model.outputters += NetCDFOutput(netcdf_file, which_data='all')

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

    print 'adding a wind mover:'

    series = np.zeros((5, ), dtype=datetime_value_2d)
    series[0] = (start_time, (2, 45))
    series[1] = (start_time + timedelta(hours=18), (2, 90))
    series[2] = (start_time + timedelta(hours=30), (2, 135))
    series[3] = (start_time + timedelta(hours=42), (2, 180))
    series[4] = (start_time + timedelta(hours=54), (2, 225))

    w_mover = WindMover(Wind(timeseries=series, units='m/s'))
    model.movers += w_mover

    print 'adding a cats mover:'
    curr_file = get_datafile(os.path.join(base_dir, 'LMiss.CUR'))
    c_mover = CatsMover(curr_file)

    # but do need to scale (based on river stage)
    c_mover.scale = True
    c_mover.scale_refpoint = (-89.699944, 29.494558)

    # based on stage height 10ft (range is 0-18)
    c_mover.scale_value = 1.027154

    model.movers += c_mover

    print 'adding a spill'
    spill = point_line_release_spill(num_elements=1000,
                                     start_position=(-89.699944, 29.494558,
                                                     0.0),
                                     release_time=start_time)
    model.spills += spill

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

    start_time = datetime(2015, 9, 24, 1, 1)

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

    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.graticule.set_DMS(True)
    #     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 = point_line_release_spill(num_elements=1000,
                                      start_position=(-122.625, 45.609, 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(0.5, 0, units='m/s')

    print 'adding a current mover:'
    curr_file = get_datafile(os.path.join(base_dir, 'COOPSu_CREOFS24.nc'))

    # uncertain_time_delay in hours
    # vec_field = TriVectorField('COOPSu_CREOFS24.nc')
    # u_mover = UGridCurrentMover(vec_field)
    c_mover = GridCurrentMover(curr_file)
    # c_mover.uncertain_cross = 0  # default is .25

    # model.movers += u_mover
    model.movers += c_mover
    model.save

    return model
Example #12
0
    def test_update_spillable_area_polygons(self):
        map = MapFromBNA(bna_with_lake)

        map.update_from_dict({
            'spillable_area': [
                [(-82.86099, 24.54724), (-82.86099, 28.11176),
                 (-80.03136, 28.11176), (-80.03136, 24.54724)],
                [
                    (-82.86099, 24.54724),
                    (-82.86099, 28.11176),
                    (-80.03136, 28.11176),
                    (-80.03136, 24.54724),
                    (-80.03136, 28.11176),
                    (-80.03136, 24.54724),
                ],
            ]
        })

        assert len(map.spillable_area) == 2
        assert len(map.spillable_area[1]) == 6
Example #13
0
def make_model(images_dir=os.path.join(base_dir, 'images')):
    print 'initializing the model'
    start_time = datetime(2006, 3, 31, 20, 0)
    model = Model(start_time=start_time,
                  duration=timedelta(days=3), time_step=30 * 60,
                  uncertain=True)

    print 'adding the map'
    mapfile = get_datafile(os.path.join(base_dir, 'coastSF.bna'))
    model.map = MapFromBNA(mapfile, refloat_halflife=1)  # seconds

    renderer = Renderer(mapfile, images_dir, image_size=(800, 600),
                        draw_ontop='forecast')
    renderer.viewport = ((-124.5, 37.), (-120.5, 39))

    print 'adding outputters'
    model.outputters += renderer

    netcdf_file = os.path.join(base_dir, 'script_sf_bay.nc')
    scripting.remove_netcdf(netcdf_file)
    model.outputters += NetCDFOutput(netcdf_file, which_data='all')

    print 'adding a spill'
    spill = point_line_release_spill(num_elements=1000,
                                     start_position=(-123.57152, 37.369436,
                                                     0.0),
                                     release_time=start_time,
                                     substance=NonWeatheringSubstance(windage_range=(0.01,.04))
                                     #element_type=floating(windage_range=(0.01,
                                     #                                     0.04)
                                     #                      )
                                     )
    model.spills += spill

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

    print 'adding a grid wind mover:'
    wind_file = get_datafile(os.path.join(base_dir, 'WindSpeedDirSubset.nc'))
    topology_file = get_datafile(os.path.join(base_dir,
                                              'WindSpeedDirSubsetTop.dat'))
    w_mover = GridWindMover(wind_file, topology_file)

    # w_mover.uncertain_time_delay = 6
    # w_mover.uncertain_duration = 6
    w_mover.uncertain_speed_scale = 1
    w_mover.uncertain_angle_scale = 0.2  # default is .4
    w_mover.wind_scale = 2

    model.movers += w_mover

    return model
Example #14
0
def make_models():
    print 'initializing the model'

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

    # 1 day of data in file
    # 1/2 hr in seconds
    models = []
    start_time = datetime(2012, 10, 27, 0, 30)
    duration_hrs = 23
    time_step = 450
    num_steps = duration_hrs * 3600 / time_step
    names = [
        'Euler',
        'Trapezoid',
        'RK4',
    ]

    mapfile = get_datafile(os.path.join(base_dir, 'long_beach.bna'))
    print 'gen map'
    map = MapFromBNA(mapfile, refloat_halflife=0.0)  # seconds
    fn = ('00_dir_roms_display.ncml.nc4')
    curr = GridCurrent.from_netCDF(filename=fn)
    models = []
    for method in names:

        mod = Model(start_time=start_time,
                    duration=timedelta(hours=duration_hrs),
                    time_step=time_step)

        mod.map = map
        spill = point_line_release_spill(num_elements=1000,
                                         start_position=(-74.1, 39.7525, 0.0),
                                         release_time=start_time)
        mod.spills += spill
        mod.movers += RandomMover(diffusion_coef=100)
        mod.movers += PyCurrentMover(current=curr, default_num_method=method)

        images_dir = method + '-' + str(
            time_step / 60) + 'min-' + str(num_steps) + 'steps'
        renderer = Renderer(mapfile, images_dir, image_size=(1024, 768))
        renderer.delay = 25
        #         renderer.add_grid(curr.grid)
        mod.outputters += renderer

        netCDF_fn = os.path.join(base_dir, images_dir + '.nc')
        mod.outputters += NetCDFOutput(netCDF_fn, which_data='all')
        models.append(mod)

    print 'returning models'
    return models
Example #15
0
def test_bna_no_map_bounds():
    """
    tests that the map bounds will get expanded to include
    the bounding box of the land and spillable area.
    """
    test_no_bounds_bna = os.path.join(datadir, 'no_map_bounds.bna')
    m = MapFromBNA(test_no_bounds_bna)

    assert np.array_equal(m.map_bounds, [
        (3., 10.),
        (3., 11.),
        (6., 11.),
        (6., 10.),
    ])
Example #16
0
class Test_lake():
    """
    tests for handling a BNA with a lake

    The code should now return a polygon with a hole for lakes.

    And render properly both with the py_gnome renderer and the json output.

    """
    map = MapFromBNA(bna_with_lake)

    def test_polys(self):
        """
        Once loaded, polygons should be there
        """
        # There should always be map bounds
        assert self.map.map_bounds is not None

        # no spillable area in this one
        assert self.map.spillable_area is None

        # NOTE: current version puts land and lakes in the land_polys set
        assert len(self.map.land_polys) == 2

    def test_to_geojson(self):
        """
        make sure geojson is right
        """

        gj = self.map.to_geojson()

        # print gj.keys()
        # print gj['features'][0].keys()
        # print len(gj.features)

        # has only the land polys in there.
        assert len(gj['features']) == 2

        land_polys = gj['features'][0]
        assert land_polys['geometry']['type'] == "MultiPolygon"
        assert land_polys["properties"]["name"] == "Shoreline Polys"

        import json
        outfilename = os.path.join(output_dir, "florida_geojson.json")
        with open(outfilename, 'w') as outfile:
            json.dump(gj, outfile, indent=2)
def make_model(images_dir=os.path.join(base_dir, 'images')):
    print 'initializing the model'

    start_time = datetime(2014, 6, 9, 0, 0)
    mapfile = get_datafile(os.path.join(base_dir, 'PassamaquoddyMap.bna'))

    gnome_map = MapFromBNA(mapfile, refloat_halflife=1)  # hours

    # # the image output renderer
    # global renderer

    # one hour timestep
    model = Model(start_time=start_time,
                  duration=timedelta(hours=24),
                  time_step=360,
                  map=gnome_map,
                  uncertain=False,
                  cache_enabled=True)

    print 'adding outputters'
    renderer = Renderer(
        mapfile,
        images_dir,
        image_size=(800, 600),
        # output_timestep=timedelta(hours=1),
        draw_ontop='uncertain')
    renderer.viewport = ((-67.15, 45.), (-66.9, 45.2))

    model.outputters += renderer

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

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

    print 'adding a spill'
    spill = point_line_release_spill(num_elements=1000,
                                     start_position=(-66.991344, 45.059316,
                                                     0.0),
                                     release_time=start_time)
    model.spills += spill

    print 'adding a RandomMover:'
    model.movers += RandomMover(diffusion_coef=30000, uncertain_factor=2)

    print 'adding a wind mover:'
    series = np.zeros((5, ), dtype=datetime_value_2d)
    series[0] = (start_time, (5, 90))
    series[1] = (start_time + timedelta(hours=18), (5, 180))
    series[2] = (start_time + timedelta(hours=30), (5, 135))
    series[3] = (start_time + timedelta(hours=42), (5, 180))
    series[4] = (start_time + timedelta(hours=54), (5, 225))

    wind = Wind(timeseries=series, units='m/s')
    model.movers += WindMover(wind)

    print 'adding a current mover:'
    curr_file = get_datafile(os.path.join(base_dir, 'PQBayCur.nc4'))
    topology_file = get_datafile(os.path.join(base_dir,
                                              'PassamaquoddyTOP.dat'))
    tide_file = get_datafile(os.path.join(base_dir, 'EstesHead.txt'))

    cc_mover = CurrentCycleMover(curr_file,
                                 topology_file,
                                 tide=Tide(tide_file))

    model.movers += cc_mover
    model.environment += cc_mover.tide

    print 'viewport is:', [
        o.viewport for o in model.outputters if isinstance(o, Renderer)
    ]

    return model
Example #18
0
 Tide(testdata['CatsMover']['tide']),
 #Wind(filename=testdata['ComponentMover']['wind']),
 constant_wind(5., 270, 'knots'),
 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=constant_wind(5., 270, 'knots')),
 #wind=Wind(filename=testdata['ComponentMover']['wind'])),
 RandomMover3D(),
 SimpleMover(velocity=(10.0, 10.0, 0.0)),
 MapFromBNA(testdata['MapFromBNA']['testmap'], 6),
 NetCDFOutput(os.path.join(base_dir, u'xtemp.nc')),
 Renderer(testdata['Renderer']['bna_sample'],
          os.path.join(base_dir, 'output_dir')),
 WeatheringOutput(),
 spill.PointLineRelease(release_time=datetime.now(),
                        num_elements=10,
                        start_position=(0, 0, 0)),
 spill.point_line_release_spill(10, (0, 0, 0), datetime.now()),
 spill.substance.Substance(windage_range=(0.05, 0.07)),
 spill.substance.GnomeOil(test_oil, windage_range=(0.05, 0.07)),
 spill.substance.NonWeatheringSubstance(windage_range=(0.05, 0.07)),
 Skimmer(amount=100,
         efficiency=0.3,
         active_range=(datetime(2014, 1, 1, 0,
                                0), datetime(2014, 1, 1, 4, 0)),
def make_model(images_dir=os.path.join(base_dir, 'images')):

    # create the maps:

    print 'creating the maps'
    mapfile = get_datafile(os.path.join(base_dir, 'DelawareRiverMap.bna'))
    gnome_map = MapFromBNA(mapfile, refloat_halflife=1)  # hours

    renderer = Renderer(mapfile,
                        images_dir,
                        image_size=(800, 800),
                        projection_class=GeoProjection)

    print 'initializing the model'
    start_time = datetime(2012, 8, 20, 13, 0)

    # 15 minutes in seconds
    # Default to now, rounded to the nearest hour
    model = Model(time_step=900,
                  start_time=start_time,
                  duration=timedelta(days=1),
                  map=gnome_map,
                  uncertain=False)

    print 'adding outputters'
    model.outputters += renderer

    netcdf_file = os.path.join(base_dir, 'script_delaware_bay.nc')
    scripting.remove_netcdf(netcdf_file)
    model.outputters += NetCDFOutput(netcdf_file, which_data='all')

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

    print 'adding a wind mover:'

    # wind_file = get_datafile(os.path.join(base_dir, 'ConstantWind.WND'))
    # wind = Wind(filename=wind_file)

    series = np.zeros((2, ), dtype=datetime_value_2d)
    series[0] = (start_time, (5, 270))
    series[1] = (start_time + timedelta(hours=25), (5, 270))

    wind = Wind(timeseries=series, units='m/s')

    # w_mover = WindMover(Wind(timeseries=series, units='knots'))
    w_mover = WindMover(wind)
    model.movers += w_mover

    print 'adding a cats shio mover:'

    curr_file = get_datafile(os.path.join(base_dir, 'FloodTides.cur'))
    tide_file = get_datafile(os.path.join(base_dir, 'FloodTidesShio.txt'))

    c_mover = CatsMover(curr_file, tide=Tide(tide_file))

    # this is the value in the file (default)
    c_mover.scale_refpoint = (-75.081667, 38.7995)
    c_mover.scale = True
    c_mover.scale_value = 1

    model.movers += c_mover

    # TODO: cannot add this till environment base class is created
    model.environment += c_mover.tide

    print 'adding a cats mover:'

    curr_file = get_datafile(os.path.join(base_dir, 'Offshore.cur'))
    c_mover = CatsMover(curr_file)

    # but do need to scale (based on river stage)

    c_mover.scale = True
    c_mover.scale_refpoint = (-74.7483333, 38.898333)
    c_mover.scale_value = .03
    model.movers += c_mover
    #
    # these are from windows they don't match Mac values...
    # pat1Angle 315;
    # pat1Speed 30; pat1SpeedUnits knots;
    # pat1ScaleToValue 0.314426
    #
    # pat2Angle 225;
    # pat2Speed 30; pat2SpeedUnits knots;
    # pat2ScaleToValue 0.032882
    # scaleBy WindStress

    print 'adding a component mover:'

    # if only using one current pattern
    # comp_mover = ComponentMover(curr_file1, None, wind)
    #
    # todo: following is not working when model is saved out - fix
    # comp_mover = ComponentMover(curr_file1, curr_file2,
    #                             Wind(timeseries=series, units='m/s'))
    # comp_mover = ComponentMover(curr_file1, curr_file2,
    #                             wind=Wind(filename=wind_file))

    curr_file1 = get_datafile(os.path.join(base_dir, 'NW30ktwinds.cur'))
    curr_file2 = get_datafile(os.path.join(base_dir, 'SW30ktwinds.cur'))
    comp_mover = ComponentMover(curr_file1, curr_file2, wind)

    comp_mover.scale_refpoint = (-75.263166, 39.1428333)

    comp_mover.pat1_angle = 315
    comp_mover.pat1_speed = 30
    comp_mover.pat1_speed_units = 1
    # comp_mover.pat1ScaleToValue = .314426
    comp_mover.pat1_scale_to_value = .502035

    comp_mover.pat2_angle = 225
    comp_mover.pat2_speed = 30
    comp_mover.pat2_speed_units = 1
    # comp_mover.pat2ScaleToValue = .032882
    comp_mover.pat2_scale_to_value = .021869

    model.movers += comp_mover

    print 'adding a spill'

    end_time = start_time + timedelta(hours=12)
    spill = point_line_release_spill(
        num_elements=1000,
        release_time=start_time,
        # end_release_time=end_time,
        start_position=(-75.262319, 39.142987, 0.0),
    )

    model.spills += spill

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

    print('get contiguous')

    kml_file = os.path.join(base_dir, 'contigua.kml')
    with open(kml_file) as f:
        contiguous = parser.parse(f).getroot().Document

    coordinates = contiguous.Placemark.LineString.coordinates.text.split(' ')
    cont_coord = []
    for x in coordinates:
        x = x.split(',')
        if len(x) > 1 and float(x[1]) > -12 and float(x[1]) < -3:
            cont_coord.append([float(x[0]), float(x[1])])

    print('initializing the model')

    start_time = datetime(2022, 1, 22, 12, 0)
    mapfile = get_datafile(os.path.join(base_dir, './brazil-coast.BNA'))

    gnome_map = MapFromBNA(mapfile, refloat_halflife=6)  # hours

    duration = timedelta(days=1)
    timestep = timedelta(minutes=5)
    end_time = start_time + duration

    steps = duration.total_seconds() / timestep.total_seconds()

    print("Total step: %.4i " % (steps))

    # one hour timestep
    model = Model(start_time=start_time,
                  duration=duration,
                  time_step=timestep,
                  map=gnome_map,
                  uncertain=False,
                  cache_enabled=False)

    oil_name = 'GENERIC MEDIUM CRUDE'

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

    subs = GnomeOil(oil_name, initializers=plume_initializers(distribution=wd))

    #model.spills += point_line_release_spill(release_time=start_time, start_position=(-35.153, -8.999, 0.0), num_elements=1000, end_release_time=end_time, substance= subs, units='kg')
    #model.spills += point_line_release_spill(release_time=start_time, start_position=(-35.176, -9.135, 0.0), num_elements=1000, end_release_time=end_time, substance= subs, units='kg')
    #model.spills += point_line_release_spill(release_time=start_time, start_position=(-35.062, -9.112, 0.0), num_elements=1000, end_release_time=end_time, substance= subs, units='kg')
    #model.spills += point_line_release_spill(release_time=start_time, start_position=(-34.994, -9.248, 0.0), num_elements=1000, end_release_time=end_time, substance= subs, units='kg')

    for idx in range(0, len(cont_coord)):
        model.spills += point_line_release_spill(
            num_elements=500,
            start_position=(cont_coord[idx][0], cont_coord[idx][1], 0.0),
            release_time=start_time,
            end_release_time=start_time + timedelta(days=1),
            amount=500,
            substance=subs,
            units='kg')

    #shp_file = os.path.join(base_dir, 'surface_concentration')
    #scripting.remove_netcdf(shp_file + ".zip")
    #model.outputters += ShapeOutput(shp_file,
    #                                zip_output=False,
    #                                surface_conc="kde",
    #                                )

    print('adding movers:')

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

    print('adding a current mover:')

    # # this is HYCOM currents
    curr_file = get_datafile(os.path.join(base_dir, 'currents.nc'))
    model.movers += GridCurrentMover(curr_file, num_method='Euler')

    print('adding a grid wind mover:')
    wind_file = get_datafile(os.path.join(base_dir, 'wind.nc'))
    #topology_file = get_datafile(os.path.join(base_dir, 'WindSpeedDirSubsetTop.dat'))
    #w_mover = GridWindMover(wind_file, topology_file)
    w_mover = GridWindMover(wind_file)
    w_mover.uncertain_speed_scale = 1
    w_mover.uncertain_angle_scale = 0.2  # default is .4
    w_mover.wind_scale = 2

    model.movers += w_mover

    print('adding outputters')

    renderer = Renderer(mapfile,
                        images_dir,
                        image_size=(900, 600),
                        output_timestep=timestep,
                        draw_ontop='forecast')
    #set the viewport to zoom in on the map:
    #renderer.viewport = ((-37, -11), (-34, -8)) #alagoas
    renderer.viewport = ((-36, -10), (-30, 5))
    model.outputters += renderer

    netcdf_file = os.path.join(base_dir, 'contigua.nc')
    scripting.remove_netcdf(netcdf_file)
    model.outputters += NetCDFOutput(netcdf_file,
                                     which_data='standard',
                                     surface_conc='kde')

    return model
Example #21
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=24),
                  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:'

    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', 5, 270, 'knots')
    wind2 = WindTS(timeseries=series, units='knots', extrapolate=True)

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

    model.movers += PyWindMover(wind=wind2)
    #     model.movers += WindMover(wind)

    #     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 = roms_field(url)
    #     cf.set_appearance(on=True)
    #     renderer.grids += [cf]
    #     renderer.delay = 25
    #     u_mover = UGridCurrentMover(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
def make_model(images_dir=os.path.join(base_dir, 'images')):
    print 'initializing the model'

    start_time = datetime(2012, 9, 15, 12, 0)
    mapfile = get_datafile(os.path.join(base_dir, './LongIslandSoundMap.BNA'))

    gnome_map = MapFromBNA(mapfile, refloat_halflife=6)  # hours

    # # the image output renderer
    # global renderer

    # one hour timestep
    model = Model(start_time=start_time,
                  duration=timedelta(hours=48),
                  time_step=3600,
                  map=gnome_map,
                  uncertain=False,
                  cache_enabled=False)

    print 'adding a spill'
    et = floating_weathering(substance='FUEL OIL NO.6')
    spill = point_line_release_spill(num_elements=1000,
                                     start_position=(-72.419992, 41.202120,
                                                     0.0),
                                     release_time=start_time,
                                     amount=1000,
                                     units='kg',
                                     element_type=et)
    spill.amount_uncertainty_scale = 1.0
    model.spills += spill

    print 'adding a RandomMover:'
    model.movers += RandomMover(diffusion_coef=500000, uncertain_factor=2)

    print 'adding a wind mover:'
    series = np.zeros((5, ), dtype=datetime_value_2d)
    series[0] = (start_time, (10, 45))
    series[1] = (start_time + timedelta(hours=18), (10, 90))
    series[2] = (start_time + timedelta(hours=30), (10, 135))
    series[3] = (start_time + timedelta(hours=42), (10, 180))
    series[4] = (start_time + timedelta(hours=54), (10, 225))

    wind = Wind(timeseries=series, units='m/s', speed_uncertainty_scale=0.5)
    model.movers += WindMover(wind)

    print 'adding a cats mover:'
    curr_file = get_datafile(os.path.join(base_dir, r"./LI_tidesWAC.CUR"))
    tide_file = get_datafile(os.path.join(base_dir, r"./CLISShio.txt"))

    c_mover = CatsMover(curr_file, tide=Tide(tide_file))
    model.movers += c_mover

    model.environment += c_mover.tide

    print 'adding Weatherers'
    water_env = Water(311.15)
    model.environment += water_env
    model.weatherers += [
        Evaporation(water_env, wind),
        Dispersion(),
        Burn(), Skimmer()
    ]

    print 'adding outputters'
    model.outputters += WeatheringOutput()

    return model
Example #23
0
def make_model(images_dir=os.path.join(base_dir, 'images')):

    # create the maps:
    print 'creating the maps'
    mapfile = get_datafile(os.path.join(base_dir, './MassBayMap.bna'))
    gnome_map = MapFromBNA(
        mapfile,
        refloat_halflife=1,  # hours
        raster_size=2048 * 2048  # about 4 MB
    )

    renderer = Renderer(
        mapfile,
        images_dir,
        image_size=(800, 800),
    )

    print 'initializing the model'
    start_time = datetime(2016, 3, 9, 15)

    # 1 hour in seconds
    # Default to now, rounded to the nearest hour
    model = Model(time_step=3600,
                  start_time=start_time,
                  duration=timedelta(days=6),
                  map=gnome_map,
                  uncertain=True)

    print 'adding outputters'
    model.outputters += renderer

    # netcdf_file = os.path.join(base_dir, 'script_boston.nc')
    # scripting.remove_netcdf(netcdf_file)
    # model.outputters += NetCDFOutput(netcdf_file, which_data='all')

    # model.outputters += KMZOutput(os.path.join(base_dir, 'script_boston.kmz'))

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

    print 'adding a wind mover:'

    series = np.zeros((2, ), dtype=datetime_value_2d)
    series[0] = (start_time, (5, 180))
    series[1] = (start_time + timedelta(hours=18), (5, 180))
    w = Wind(filename=os.path.join(base_dir, '22NM_WNW_PortAngelesWA.nws'))
    w_mover = WindMover(w)
    model.movers += w_mover
    model.environment += w_mover.wind

    # print 'adding a cats shio mover:'

    # curr_file = get_datafile(os.path.join(base_dir, r"./EbbTides.cur"))
    # tide_file = get_datafile(os.path.join(base_dir, r"./EbbTidesShio.txt"))

    # c_mover = CatsMover(curr_file, tide=Tide(tide_file))

    # # this is the value in the file (default)
    # c_mover.scale_refpoint = (-70.8875, 42.321333)
    # c_mover.scale = True
    # c_mover.scale_value = -1

    # model.movers += c_mover

    # # TODO: cannot add this till environment base class is created
    # model.environment += c_mover.tide

    print 'adding a spill'

    end_time = start_time + timedelta(hours=12)
    spill = point_line_release_spill(num_elements=100,
                                     start_position=(-70.911432, 42.369142,
                                                     0.0),
                                     release_time=start_time,
                                     end_release_time=end_time)

    model.spills += spill

    return model
Example #24
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

    oil_name = 'ALASKA NORTH SLOPE (MIDDLE PIPELINE, 1997)'
    
    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,
                                     substance = GnomeOil(oil_name,initializers=plume_initializers(distribution=wd))
                                     #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 RandomMover3D:'
#     model.movers += RandomMover3D(vertical_diffusion_coef_above_ml=5,
#                                         vertical_diffusion_coef_below_ml=.11,
#                                         mixed_layer_depth=10)

    # the url is broken, update and include the following four lines
#     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
Example #25
0
def make_model(images_dir=os.path.join(base_dir, 'images')):
    print 'initializing the model'

    start_time = datetime(2013, 5, 18, 0)

    model = Model(start_time=start_time, duration=timedelta(days=8),
                  time_step=4 * 3600, uncertain=False)

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

    print 'adding the map'
    model.map = MapFromBNA(mapfile, refloat_halflife=6)  # hours

    #
    # Add the outputters -- render to images, and save out as netCDF
    #

    print 'adding renderer'
    model.outputters += Renderer(mapfile,
                                 images_dir,
                                 image_size=(800, 600),
                                 )
#                                 draw_back_to_fore=True)

    # print "adding netcdf output"
    # netcdf_output_file = os.path.join(base_dir,'mariana_output.nc')
    # scripting.remove_netcdf(netcdf_output_file)
    # model.outputters += NetCDFOutput(netcdf_output_file, which_data='all')

    #
    # Set up the movers:
    #

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

    print 'adding a simple wind mover:'
    model.movers += constant_wind_mover(5, 315, units='m/s')

    print 'adding a current mover:'

    # # this is HYCOM currents
    curr_file = get_datafile(os.path.join(base_dir, 'HYCOM.nc'))
    model.movers += GridCurrentMover(curr_file,
                                     num_method='Euler');

    # #
    # # Add some spills (sources of elements)
    # #

    print 'adding four spill'
    model.spills += point_line_release_spill(num_elements=NUM_ELEMENTS // 4,
                                             start_position=(145.25, 15.0,
                                                             0.0),
                                             release_time=start_time)
    model.spills += point_line_release_spill(num_elements=NUM_ELEMENTS // 4,
                                             start_position=(146.25, 15.0,
                                                             0.0),
                                             release_time=start_time)
    model.spills += point_line_release_spill(num_elements=NUM_ELEMENTS // 4,
                                             start_position=(145.75, 15.25,
                                                             0.0),
                                             release_time=start_time)
    model.spills += point_line_release_spill(num_elements=NUM_ELEMENTS // 4,
                                             start_position=(145.75, 14.75,
                                                             0.0),
                                             release_time=start_time)

    return model
Example #26
0
    def make_model():
        print ('initializing the model')

        #print (start_date)

        start_time = startday

        model = Model(start_time=start_time, duration=timedelta(days=30), 
                      #weathering_substeps = 6,
                      time_step=24 * 3600,
                      uncertain=False)

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

        #mapfile='gulf.bna'

        print ('adding the map')
        model.map = MapFromBNA(mapfile, refloat_halflife=6)  # hours

        #
        # Add the outputters -- render to images, and save out as netCDF
        #

        

        

        print ("adding shapefile output")

         # with open("Result {}".format(spill_num), "w") as fp:
         # fp.write("text")
        
        dir_name = os.path.join (base_dir, season, str(position), "Spillnum {}".format(spill_num))
        
        if not os.path.exists(dir_name):
            os.makedirs(dir_name)
        
        #os.makedirs(dir_name, exist_ok =True)

        for i in range(1, 31, 1):
            model.outputters += ShapeOutput(os.path.join(dir_name, 'gnome_result {id}'.format(id=i)),
                                        zip_output=False,
                                        output_timestep=timedelta(days=i)) 
        images_dir = os.path.join(dir_name, 'image')
        # print 'adding renderer'
        # model.outputters += Renderer(mapfile,
        #                         images_dir,
        #                         image_size=(800, 600))
                                 
        # print ('adding renderer')
        # dir_image = os.path.join(dir_name)
        # model.outputters += Renderer(mapfile,
        #                            dir_image,
        #                             size=(800, 600))
                              

        #
        # Set up the movers:
        #

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

        print ('adding a simple wind mover:')
    

        
        wind_file = get_datafile(os.path.join(base_dir, 'ECMWF.nc'))
        model.movers += GridWindMover(wind_file)

                                                  

        print ('adding a current mover:')

        # # this is NEMO currents

        curr_file = get_datafile(os.path.join(base_dir, Currents))
        model.movers += GridCurrentMover(curr_file,
                                         num_method='Euler');


        
        # # Add some spills (sources of elements)
        

        print ('adding one spill')

        
       
        spill = point_line_release_spill(num_elements=1000,
                                                 amount=  3200000000 * spilldur , units='grams',
                                                 start_position = position,
                                                 release_time = start_time,
                                                 substance = (sub))
        model.spills += spill

        ####### open excel file 
        print ('adding Excel file')
      
        workbook = xlsxwriter.Workbook(os.path.join(dir_name, 'Result {}_{}.xlsx'.format(spill_num, position)))
        worksheet = workbook.add_worksheet () 
        a = ((spilldur*3200)**(-0.3))*0.000069
        worksheet.write ('A1', a)
        workbook.close()

        
        print ('adding weatherers and cleanup options:')

        model.environment += [water,wind,waves]
        model.weatherers += Evaporation()
        model.weatherers += Emulsification()
        model.weatherers += NaturalDispersion()
        print ('model full run:')
        model.full_run()
        return model
def make_model(images_dir=os.path.join(base_dir, 'images')):
    print 'initializing the model'

    start_time = datetime(2013, 2, 13, 9, 0)

    # 1/2 hr in seconds
    model = Model(start_time=start_time,
                  duration=timedelta(days=2),
                  time_step=30 * 60,
                  uncertain=False)

    print 'adding the map'
    mapfile = get_datafile(os.path.join(base_dir, 'GuamMap.bna'))
    model.map = MapFromBNA(mapfile, refloat_halflife=6)  # hours

    print 'adding outputters'
    renderer = Renderer(mapfile, images_dir, image_size=(800, 600))
    renderer.viewport = ((144.6, 13.4), (144.7, 13.5))
    model.outputters += renderer

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

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

    print 'adding a spill'
    end_time = start_time + timedelta(hours=6)
    spill = point_line_release_spill(num_elements=20,
                                     start_position=(144.664166,
                                                     13.441944, 0.0),
                                     release_time=start_time,
                                     end_release_time=end_time)
    model.spills += spill

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

    print 'adding a wind mover:'
    series = np.zeros((4, ), dtype=datetime_value_2d)
    series[0] = (start_time, (5, 135))
    series[1] = (start_time + timedelta(hours=23), (5, 135))
    series[2] = (start_time + timedelta(hours=25), (5, 0))
    series[3] = (start_time + timedelta(hours=48), (5, 0))

    wind = Wind(timeseries=series, units='knot')
    w_mover = WindMover(wind)
    model.movers += w_mover
    model.environment += w_mover.wind

    print 'adding a cats mover:'
    curr_file = get_datafile(os.path.join(base_dir, 'OutsideWAC.cur'))
    c_mover = CatsMover(curr_file)

    c_mover.scale = True
    c_mover.scale_refpoint = (144.601, 13.42)
    c_mover.scale_value = .15

    model.movers += c_mover

    print 'adding a cats shio mover:'
    curr_file = get_datafile(os.path.join(base_dir, 'WACFloodTide.cur'))
    tide_file = get_datafile(os.path.join(base_dir, 'WACFTideShioHts.txt'))

    c_mover = CatsMover(curr_file, tide=Tide(tide_file))

    # this is different from the value in the file!
    c_mover.scale_refpoint = (144.621667, 13.45)

    c_mover.scale = True
    c_mover.scale_value = 1

    # will need the fScaleFactor for heights files
    # c_mover.time_dep.scale_factor = 1.1864
    c_mover.tide.scale_factor = 1.1864

    model.movers += c_mover
    model.environment += c_mover.tide

    return model
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
Example #29
0
def make_model(uncertain=False, mode='gnome'):
    '''
    Create a model from the data in sample_data/boston_data
    It contains:
      - the GeoProjection
      - wind mover
      - random mover
      - cats shio mover
      - cats ossm mover
      - plain cats mover
    '''
    start_time = datetime(2013, 2, 13, 9, 0)
    model = Model(start_time=start_time,
                  duration=timedelta(days=2),
                  time_step=timedelta(minutes=30).total_seconds(),
                  uncertain=uncertain,
                  map=MapFromBNA(testdata['boston_data']['map'],
                                 refloat_halflife=1),
                  mode=mode)

    print 'adding a spill'
    start_position = (144.664166, 13.441944, 0.0)
    end_release_time = start_time + timedelta(hours=6)
    spill_amount = 1000.0
    spill_units = 'kg'
    model.spills += point_line_release_spill(num_elements=1000,
                                             start_position=start_position,
                                             release_time=start_time,
                                             end_release_time=end_release_time,
                                             amount=spill_amount,
                                             units=spill_units,
                                             substance=test_oil)
    spill = model.spills[-1]
    spill_volume = spill.get_mass() / spill.substance.density_at_temp()
    # need a scenario for SimpleMover
    # model.movers += SimpleMover(velocity=(1.0, -1.0, 0.0))

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

    print 'adding a wind mover:'

    series = np.zeros((2, ), dtype=datetime_value_2d)
    series[0] = (start_time, (5, 180))
    series[1] = (start_time + timedelta(hours=18), (5, 180))

    w_mover = WindMover(Wind(timeseries=series, units='m/s'))

    model.movers += w_mover
    model.environment += w_mover.wind

    print 'adding a cats shio mover:'

    c_mover = CatsMover(testdata['boston_data']['cats_curr2'],
                        tide=Tide(testdata['boston_data']['cats_shio']))

    # c_mover.scale_refpoint should automatically get set from tide object
    c_mover.scale = True  # default value
    c_mover.scale_value = -1

    # tide object automatically gets added by model
    model.movers += c_mover

    print 'adding a cats ossm mover:'

    c_mover = CatsMover(testdata['boston_data']['cats_curr2'],
                        tide=Tide(testdata['boston_data']['cats_ossm']))

    c_mover.scale = True  # but do need to scale (based on river stage)
    c_mover.scale_refpoint = (-70.65, 42.58333, 0.0)
    c_mover.scale_value = 1.

    print 'adding a cats mover:'

    c_mover = CatsMover(testdata['boston_data']['cats_curr3'])
    c_mover.scale = True  # but do need to scale (based on river stage)
    c_mover.scale_refpoint = (-70.78333, 42.39333, 0.0)

    # the scale factor is 0 if user inputs no sewage outfall effects
    c_mover.scale_value = .04
    model.movers += c_mover

    # TODO: seg faulting for component mover - comment test for now
    # print "adding a component mover:"
    # comp_mover = ComponentMover(testdata['boston_data']['component_curr1'],
    #                             testdata['boston_data']['component_curr2'],
    #                             w_mover.wind)
    # TODO: callback did not work correctly below - fix!
    # comp_mover = ComponentMover(component_file1,
    #                             component_file2,
    #                             Wind(timeseries=series, units='m/s'))

    # comp_mover.ref_point = (-70.855, 42.275)
    # comp_mover.pat1_angle = 315
    # comp_mover.pat1_speed = 19.44
    # comp_mover.pat1_speed_units = 1
    # comp_mover.pat1ScaleToValue = .138855
    # comp_mover.pat2_angle = 225
    # comp_mover.pat2_speed = 19.44
    # comp_mover.pat2_speed_units = 1
    # comp_mover.pat2ScaleToValue = .05121

    # model.movers += comp_mover

    print 'adding a Weatherer'
    model.environment += Water(311.15)
    skim_start = start_time + timedelta(hours=3)
    model.weatherers += [
        Evaporation(),
        Skimmer(spill_amount * .5,
                spill_units,
                efficiency=.3,
                active_range=(skim_start, skim_start + timedelta(hours=2))),
        Burn(0.2 * spill_volume,
             1.0, (skim_start, InfDateTime('inf')),
             efficiency=0.9)
    ]

    model.outputters += \
        CurrentJsonOutput(model.find_by_attr('_ref_as', 'current_movers',
                                             model.movers, allitems=True))

    return model
Example #30
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_c_mover = PyCurrentMover(current=ice_aware_curr,
                               default_num_method=method)
    i_w_mover = PyWindMover(wind=ice_aware_wind,
                            default_num_method=wind_method)

    i_c_mover.current.grid.extrapolation_is_allowed = True

    #     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