Exemple #1
0
def CurrentsAndWinds(timeStep, start_time, duration, weatheringSteps, mapfile, uncertain, data_path, curr_path, wind_path, map_path, reFloatHalfLife, windFile, currFile, tidalFile, num_elements, depths, lat, lon, output_path, wind_scale, save_nc, timestep_outputs, weatherers, td):
    print 'initializing the model:'
    model = Model(time_step=timeStep, start_time=start_time, duration=duration)
    print 'adding the map:'
    print (data_path, map_path, mapfile)
    mapfile = get_datafile(os.path.join(data_path, map_path, mapfile))
    model.map = MapFromBNA(mapfile, refloat_halflife=reFloatHalfLife)
    print 'adding a renderer'
    model.outputters += Renderer(mapfile, output_path, size=(800, 600), output_timestep=timedelta(hours=timestep_outputs))
    if save_nc:
        nc_outputter = NetCDFOutput('currentsAndWinds_example.nc', which_data='standard', output_timestep=timedelta(hours=timestep_outputs))
        model.outputters += nc_outputter
    print 'adding a wind mover:'
    wind_file = get_datafile(os.path.join(data_path, wind_path, windFile))
    wind = GridWindMover(wind_file)
    wind.wind_scale = wind_scale
    model.movers += wind
    print 'adding a current mover: '
    curr_file = get_datafile(os.path.join(data_path, curr_path, currFile))
    model.movers += GridCurrentMover(curr_file, num_method='RK4')
    if td:
        random_mover = RandomMover(diffusion_coef=10000)
        model.movers += random_mover
    print 'adding spill'
    model.spills += point_line_release_spill(num_elements=num_elements, start_position=(lon, lat, 0), release_time=start_time, end_release_time=start_time + duration)
    return model
Exemple #2
0
def allWeatherers(timeStep, start_time, duration, weatheringSteps, map, uncertain, data_path, curr_path, wind_path, map_path, reFloatHalfLife, windFile, currFile, tidalFile, num_elements, depths, lat, lon, output_path, wind_scale, save_nc, timestep_outputs, weatherers, td):
    print 'initializing the model:'
    model = Model(time_step=timeStep, start_time=start_time, duration=duration)
    print 'adding the map:'
    map_folder = os.path.join(data_path, map_path)
    if not(os.path.exists(map_folder)):
        print('The map folder is incorrectly set:', map_folder)
    mapfile = get_datafile( os.path.join(map_folder,map) )
    model.map = MapFromBNA(mapfile, refloat_halflife=reFloatHalfLife)
    print 'adding a renderer'
    model.outputters += Renderer(mapfile, output_path, size=(800, 600), output_timestep=timedelta(hours=1))
    if save_nc:
        nc_outputter = NetCDFOutput(netcdf_file, which_data='most', output_timestep=timedelta(hours=1))
        model.outputters += nc_outputter
    print 'adding a wind mover:'
    wind_file = get_datafile(os.path.join(data_path, wind_path, windFile))
    wind = GridWindMover(wind_file)
    wind.wind_scale = wind_scale
    model.movers += wind
    print 'adding a current mover: '
    curr_file = get_datafile(os.path.join(data_path, curr_path, currFile))
    model.movers += GridCurrentMover(curr_file, num_method='RK4')
    if td:
        random_mover = RandomMover(diffusion_coef=10000)
        model.movers += random_mover
    print 'adding spill'
    model.spills += point_line_release_spill(num_elements=num_elements, start_position=(lon, lat, 0), release_time=start_time, end_release_time=start_time + duration)
    print 'adding weatherers'
    water = Water(280.92)
    wind = constant_wind(20.0, 117, 'knots')
    waves = Waves(wind, water)
    model.weatherers += Evaporation(water, wind)
    model.weatherers += Emulsification(waves)
    model.weatherers += NaturalDispersion(waves, water)
    return model
Exemple #3
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
Exemple #4
0
def test_new_from_dict():
    """
    test to_dict function for GridWind object
    create a new grid_wind object and make sure it has same properties
    """

    grid_wind = GridWindMover(wind_file,topology_file)
    dict_ = grid_wind.to_dict('create')
    gw2 = GridWindMover.new_from_dict(dict_)
    assert grid_wind == gw2
Exemple #5
0
def test_serialize_deserialize():
    """
    test to_dict function for GridWind object
    create a new grid_wind object and make sure it has same properties
    """

    grid_wind = GridWindMover(wind_file, topology_file)
    serial = grid_wind.serialize()
    gw2 = GridWindMover.deserialize(serial)

    assert grid_wind == gw2
def test_serialize_deserialize():
    """
    test to_dict function for GridWind object
    create a new grid_wind object and make sure it has same properties
    """

    grid_wind = GridWindMover(wind_file, topology_file)
    serial = grid_wind.serialize()
    gw2 = GridWindMover.deserialize(serial)

    assert grid_wind == gw2
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, 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,
                                     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, r"./WindSpeedDirSubset.nc")
                             )
    topology_file = get_datafile(os.path.join(base_dir,
                                              r"./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
Exemple #8
0
def test_exceptions():
    """
    Test correct exceptions are raised
    """
    with pytest.raises(TypeError):
        GridWindMover()

    with pytest.raises(ValueError):
        'file not found'
        GridWindMover(os.path.join('./', 'WindSpeedDirSubset.CUR'))

    with pytest.raises(TypeError):
        GridWindMover(wind_file, topology_file=10)
Exemple #9
0
def make_model(timeStep,start_time, duration, weatheringSteps, map, uncertain, data_path, reFloatHalfLife, windFile, currFile, tidalFile,
               num_elements, depths, lat, lon, output_path, evaporation):
    #initalizing the model
    print 'initializing the model:'
    # model = Model(time_step = timeStep, start_time= start_time, duration=duration, uncertain = uncertain)
    model = Model(time_step = timeStep, start_time= start_time, duration=duration)

    #adding the map
    print 'adding the map:'
    print 'pinche path', data_path
    mapfile = get_datafile(os.path.join(data_path, map))
    model.map = MapFromBNA(mapfile, refloat_halflife = reFloatHalfLife)
    #model.map = GnomeMap()


    print 'adding a renderer'
    # renderer is a class that writes map images for GNOME results
    model.outputters += Renderer(mapfile, output_path, size=(800, 600), output_timestep=timedelta(hours=1))
    ##scripting.remove_netcdf(netcdf_file)
    #nc_outputter = NetCDFOutput(netcdf_file, which_data='most', output_timestep=timedelta(hours=1))
    #model.outputters += nc_outputter
    #adding the movers

    print 'adding a wind mover:'
    wind_file = get_datafile(os.path.join(data_path, windFile))
    wind = GridWindMover(wind_file)
    wind.wind_scale = 2
    model.movers += wind

    print 'adding a current mover: '
    curr_file = get_datafile(os.path.join(data_path,currFile))
    model.movers+= GridCurrentMover(curr_file, num_method='RK4')
    #random_mover = RandomMover(diffusion_coef=10000) #in cm/sdfd
    #model.movers += random_mover

    if evaporation:
    
     #wind for evaporation
	print'adding evaporation'
    	wind = constant_wind(1, 0, 'knots')
    	water = Water(temperature=300.0, salinity=35.0)
    	model.weatherers += Evaporation(wind=wind, water=water)
    #

    print 'adding a spill'
    # for i in depths:
    #     model.spills+= point_line_release_spill(num_elements=num_elements, start_position=(lon,lat,i), release_time=start_time)
    model.spills+= point_line_release_spill(num_elements=num_elements, start_position=(lon,lat,0), release_time=start_time,
                                            end_release_time=start_time+timedelta(days=93))

    return model
Exemple #10
0
def test_loop():
    """
    test one time step with no uncertainty on the spill
    - checks there is non-zero motion.
    - also checks the motion is same for all LEs

    - Uncertainty needs to be off.
    - Windage needs to be set to not vary or each particle will have a
      different position,  This is done by setting the windage range to have
      all the same values (min == max).
    """
    pSpill = sample_sc_release(num_elements=num_le,
                               start_pos=start_pos,
                               release_time=rel_time,
                               windage_range=(0.01, 0.01))

    wind = GridWindMover(wind_file, topology_file)

    delta = _certain_loop(pSpill, wind)
    _assert_move(delta)

    assert np.all(delta[:, 0] == delta[0, 0])  # lat move matches for all LEs
    assert np.all(delta[:, 1] == delta[0, 1])  # long move matches for all LEs

    # returned delta is used in test_certain_uncertain test
    return delta
Exemple #11
0
def test_exceptions():
    """
    Test correct exceptions are raised
    """
    with pytest.raises(TypeError):
        # we need to supply at least a filename
        GridWindMover()

    with pytest.raises(ValueError):
        # wind file not found
        GridWindMover('bogus')

    with pytest.raises(ValueError):
        # topology file not found
        GridWindMover(wind_file, topology_file='bogus')

    with pytest.raises(TypeError):
        # topology file needs to be a string filename
        GridWindMover(wind_file, topology_file=10)
Exemple #12
0
def test_string_repr_no_errors():
    gw = GridWindMover(wind_file, topology_file)
    print
    print '======================'
    print 'repr(WindMover): '
    print repr(gw)
    print
    print 'str(WindMover): '
    print str(gw)
    assert True
Exemple #13
0
def only_Winds(timeStep, start_time, duration, weatheringSteps, map, uncertain, data_path, curr_path, wind_path, map_path, reFloatHalfLife, windFile, currFile, tidalFile, num_elements, depths, lat, lon, output_path, wind_scale, save_nc, timestep_outputs, weatherers, td):
    print 'initializing the model:'
    model = Model(time_step=timeStep, start_time=start_time, duration=duration)
    print 'adding the map:'
    mapfile = get_datafile(os.path.join(data_path, map_path, map))
    model.map = MapFromBNA(mapfile, refloat_halflife=reFloatHalfLife)
    print 'adding a renderer'
    model.outputters += Renderer(mapfile, output_path, size=(800, 600), output_timestep=timedelta(hours=timestep_outputs))
    if save_nc:
        nc_outputter = NetCDFOutput(netcdf_file, which_data='most', output_timestep=timedelta(hours=timestep_outputs))
        model.outputters += nc_outputter
    print 'adding a wind mover:'
    wind_file = get_datafile(os.path.join(data_path, wind_path, windFile))
    wind = GridWindMover(wind_file)
    wind.wind_scale = wind_scale
    model.movers += wind
    print 'adding a spill'
    model.spills += point_line_release_spill(num_elements=num_elements, start_position=(lon, lat, 0), release_time=start_time, end_release_time=start_time + duration)
    return model
Exemple #14
0
def test_exceptions():
    """
    Test correct exceptions are raised
    """
    with pytest.raises(TypeError):
        GridWindMover()

    bad_file = os.path.join(wind_dir, 'WindSpeedDirSubset.CUR')
    with pytest.raises(ValueError):
        GridWindMover(bad_file)

    with pytest.raises(TypeError):
        GridWindMover(wind_file, topology_file=10)

    with pytest.raises(ValueError):
        # todo: Following fails - cannot raise exception during initialize
        # Need to look into this issue
        #gw = GridWindMover(grid_file, uncertain_angle_units='xyz')
        gw = GridWindMover(wind_file,topology_file)   # todo: why does this fail
        gw.set_uncertain_angle(.4, 'xyz')
Exemple #15
0
def test_string_repr_no_errors():
    gw = GridWindMover(wind_file, topology_file)
    print
    print '======================'
    print 'repr(WindMover): '
    print repr(gw)
    print
    print 'str(WindMover): '
    print str(gw)

    # TODO, FIXME: We need a way of validating this if we really care what
    #              the str() and repr() methods are doing.
    assert True
Exemple #16
0
def test_uncertain_loop():
    """
    test one time step with uncertainty on the spill
    checks there is non-zero motion.
    """

    pSpill = sample_sc_release(num_le, start_pos, rel_time, uncertain=True)
    wind = GridWindMover(wind_file, topology_file)
    u_delta = _uncertain_loop(pSpill, wind)

    _assert_move(u_delta)

    # returned delta is used in test_certain_uncertain test
    return u_delta
Exemple #17
0
def test_loop():
    """
    test one time step with no uncertainty on the spill
    checks there is non-zero motion.
    also checks the motion is same for all LEs
    """

    pSpill = sample_sc_release(num_le, start_pos, rel_time)
    wind = GridWindMover(wind_file, topology_file)
    delta = _certain_loop(pSpill, wind)

    _assert_move(delta)

    # set windage to be constant or each particle has a different position,
    # doesn't work with uncertainty on
    # assert np.all(delta[:, 0] == delta[0, 0])  # lat move matches for all LEs
    # assert np.all(delta[:, 1] == delta[0, 1])  # long move matches for all LEs

    # returned delta is used in test_certain_uncertain test
    return delta
Exemple #18
0
def test_loop_gridwind():
    """
    test one time step with no uncertainty on the spill
    checks there is non-zero motion.
    also checks the motion is same for all LEs
    """

    pSpill = sample_sc_release(num_le, start_pos, rel_time, windage_range=(0.03, 0.03))
    wind = GridWindMover(ice_file, topology_file)
    delta = _certain_loop(pSpill, wind)

    _assert_move(delta)

    # the LEs are NOT all the same -- at all!
    print delta[:, 0]
    assert np.all(delta[:, 0] == delta[0, 0])  # lat move matches for all LEs
    assert np.all(delta[:, 1] == delta[0, 1])  # long move matches for all LEs
    assert np.all(delta[:, 2] == 0)  # 'z' is zeros

    return delta
def test_gridded_wind():
    """
    does a gridded wind mover move the elements?
    """
    start_pos = (-123.57152, 37.369436, 0.0)
    rel_time = datetime(2006, 3, 31, 21, 0)
    time_step = 30 * 60  # seconds
    model_time = rel_time

    sc = sample_sc_release(
        10,
        start_pos=start_pos,
        release_time=rel_time,
        windage_range=(0.01, 0.01),
    )

    wm = GridWindMover(wind_file, topology_file)

    delta = run_one_timestep(sc, wm, time_step, model_time)

    assert np.all(delta[:, 0] == delta[0, 0])  # lat move matches for all LEs
    assert np.all(delta[:, 1] == delta[0, 1])  # lon move matches for all LEs

    # set the on_tideflat flag

    # now set the on_tideflat code on half the elements
    sc['status_codes'][5:] = oil_status.on_tideflat

    delta = run_one_timestep(sc, wm, time_step, model_time)

    # only the first 5 should move
    assert np.all(delta[:5, 0] != 0.0)
    assert np.all(delta[:5, 1] != 0.0)

    assert np.all(delta[5:, 0] == 0.0)
    assert np.all(delta[5:, 1] == 0.0)

    # no change to depth
    assert np.all(delta[:, 2] == 0.0)
Exemple #20
0
def make_modelF(timeStep, start_time, duration, weatheringSteps, map, uncertain, data_path, curr_path, wind_path, map_path, reFloatHalfLife, windFile, currFile, num_elements, depths, lat, lon, output_path, wind_scale, save_nc, timestep_outputs, weatherers, td, dif_coef,temp_water):
    print 'initializing the model:'
    model = Model(time_step=timeStep, start_time=start_time, duration=duration, uncertain=uncertain)
    print 'adding the map:'
    mapfile = get_datafile(os.path.join(data_path, map_path, map))
    model.map = MapFromBNA(mapfile, refloat_halflife=reFloatHalfLife)
    print 'adding a renderer'

    if save_nc:
        scripting.remove_netcdf(output_path+'/'+'output.nc')
        nc_outputter = NetCDFOutput(output_path+'/'+'output.nc', which_data='standard', output_timestep=timedelta(hours=timestep_outputs))
        model.outputters += nc_outputter

    print 'adding a wind mover:'
    wind_file = get_datafile(os.path.join(data_path, wind_path, windFile))
    wind = GridWindMover(wind_file)
    # wind.wind_scale = wind_scale
    model.movers += wind
    print 'adding a current mover:'
    curr_file = get_datafile(os.path.join(data_path, curr_path, currFile))
    model.movers += GridCurrentMover(curr_file, num_method='RK4')
    if td:
        random_mover = RandomMover(diffusion_coef=dif_coef)
        model.movers += random_mover
    print 'adding spill'
    model.spills += point_line_release_spill(num_elements=num_elements, start_position=(lon, lat, 0), release_time=start_time, end_release_time=start_time + duration)#, substance='AD04001', amount=9600000, units='kg')

    if weatherers:
        print 'adding weatherers'
        water = Water(temp_water)
        wind = constant_wind(0.0001, 0, 'knots')
        waves = Waves(wind, water)
        model.weatherers += Evaporation(water, wind)
    # model.weatherers += Emulsification(waves)
        model.weatherers += NaturalDispersion(waves, water)
    return model
Exemple #21
0
    def make_model(images_dir=os.path.join(base_dir, 'images')):
        print('initializing the model')

        #print (start_date)

        start_time = new_start_date

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

        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 renderer')
        #model.outputters += Renderer(mapfile,
        # images_dir,
        #size=(800, 600),
        #draw_back_to_fore=True)

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

        print("adding shapefile output")

        # with open("Result {}".format(spill_num), "w") as fp:
        # fp.write("text")

        dir_name = os.path.join(base_dir,
                                "Result{}_{}".format(spill_num, position))
        if not os.path.exists(dir_name):
            os.mkdir(dir_name)

        for i in range(1, 31, 1):
            model.outputters += ShapeOutput(os.path.join(
                dir_name,
                'gnome_result{id}_{spillnum}'.format(id=i,
                                                     spillnum=spill_num)),
                                            zip_output=False,
                                            output_timestep=timedelta(days=i))

        #
        # 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')

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

        #water = Water (temperature=290.367946, salinity=35.0)
        #wind = GridWindMover (wind_file)
        #waves = Waves ()

        print('adding a current mover:')

        # # this is NEMO currents

        curr_file = get_datafile(os.path.join(base_dir, 'current2016nc3.nc'))
        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=4000 * spilldur,
                                         units='m^3',
                                         start_position=position,
                                         release_time=start_time,
                                         substance=(u'BAHRGANSAR, OIL & GAS'))
        model.spills += spill

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

        #workbook.close()

        print('adding weatherers and cleanup options:')

        model.environment += [water, wind, waves]
        model.add_weathering()

        #model.weatherers += Evaporation()
        #model.weatherers += Emulsification()
        #model.weatherers += NaturalDispersion()
        model.full_run()
        return model
Exemple #22
0
def test_certain_uncertain():
    """
    make sure certain and uncertain loop results in different deltas
    """

    delta = test_loop()
    u_delta = test_uncertain_loop()
    print
    print delta
    print u_delta
    assert np.all(delta[:, :2] != u_delta[:, :2])
    assert np.all(delta[:, 2] == u_delta[:, 2])


w_grid = GridWindMover(wind_file, topology_file)


def test_default_props():
    """
    test default properties
    use _defaults helper function defined in test_wind_mover.py
    """
    # ==========================================================================
    # assert w_grid.active == True  # timespan is as big as possible
    # assert w_grid.uncertain_duration == 3.0
    # assert w_grid.uncertain_time_delay == 0
    # assert w_grid.uncertain_speed_scale == 2
    # assert w_grid.uncertain_angle_scale == 0.4
    # assert w_grid.uncertain_angle_units == 'rad'
    # ==========================================================================
Exemple #23
0
def test_init_defaults():
    gw = GridWindMover(wind_file)

    assert gw.name == os.path.split(wind_file)[1]
    assert gw.filename == wind_file
    assert gw.topology_file is None
    assert obj == obj2


# Following movers fail on windows with fixture. This is causing an issue in
# windows for the NetCDF files - for some reason it is not able to delete the
# netcdf data files. All files are being closed in C++.
l_movers2 = (
    CurrentCycleMover(testdata['CurrentCycleMover']['curr'],
                      topology_file=testdata['CurrentCycleMover']['top'],
                      tide=Tide(testdata['CurrentCycleMover']['tide'])),
    CurrentCycleMover(testdata['CurrentCycleMover']['curr'],
                      topology_file=testdata['CurrentCycleMover']['top']),
    GridCurrentMover(testdata['GridCurrentMover']['curr_tri'],
                     testdata['GridCurrentMover']['top_tri']),
    GridWindMover(testdata['GridWindMover']['wind_curv'],
                  testdata['GridWindMover']['top_curv']),
)


@pytest.mark.parametrize("obj", l_movers2)
def test_serialize_deserialize_grids(saveloc_, obj):
    'test serialize/deserialize functionality'
    json_ = obj.serialize()
    obj2 = obj.__class__.deserialize(json_)

    assert obj == obj2


@pytest.mark.parametrize("obj", l_movers2)
def test_save_load_grids(saveloc_, obj):
    'test save/load functionality'
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
    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
Exemple #27
0
        # for i in range(0, 1000 ):
        #     curr_t, curr_fn = setup.Time_Map[i]
        #     file_list.append( curr_fn )

        # set up model for this start_time/duration, adding required forcing files
        model = make_model(setup.RootDir)
        model.duration = run_time
        # model.movers.clear()

        print 'adding a GridCurrentMover:'
        c_mover = GridCurrentMover(filename=setup.c_filelist,
                                   topology_file=setup.c_Topology)
        model.movers += c_mover

        print 'adding a GridWindMover:'
        w_mover = GridWindMover(wind_file=setup.w_filelist,
                                topology_file=setup.w_Topology)
        # w_mover = GridWindMover(wind_file=setup.w_filelist)
        model.movers += w_mover

        print 'adding a RandomMover:'
        random_mover = RandomMover(diffusion_coef=10000)  #in cm/s
        model.movers += random_mover

        # # print 'creating MFDataset'
        # ds = nc4.MFDataset(file_list)

        # # print 'adding a PyGridCurrentMover (Trapeziod/RLK4)::'
        # curr = GridCurrent.from_netCDF(data_file=file_list,grid_file=gfile,
        #                                 dataset=ds)
        # curr_mover = PyGridCurrentMover(current=curr,default_num_method='Trapeziod')
        # # curr_mover = PyGridCurrentMover(current=curr)
Exemple #28
0
        #                             dataset=ds_w,
        #                             grid_topology={'node_lon':'lonc','node_lat':'latc'})
        # w_mover = PyWindMover(wind = g_wind, default_num_method='Euler')
        # model.movers += w_mover

        print 'adding a CurrentMover (Trapeziod/RK4):'
        c_mover = GridCurrentMover(os.path.join(setup.Data_Dir,
                                                setup.CurrCatFile),
                                   os.path.join(setup.Data_Dir,
                                                setup.CurrTopoFile),
                                   num_method='RK4')
        model.movers += c_mover

        print 'adding a WindMover (Euler):'
        w_mover = GridWindMover(
            os.path.join(setup.Data_DirW, setup.WindCatFile),
            os.path.join(setup.Data_DirW, setup.WindTopoFile))
        model.movers += w_mover

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

        # for pos_idx, start_position in enumerate(start_positions):
        for pos_idx in setup.RunSites:
            start_position = start_positions[pos_idx]

            OutDir = os.path.join(setup.RootDir, setup.TrajectoriesPath,
                                  SeasonName, 'pos_%03i' % (pos_idx + 1))
            make_dir(OutDir)

            print pos_idx, time_idx
Exemple #29
0
def make_model(images_dir=os.path.join(base_dir, 'images')):
    print 'initializing the model'

    # start_time = datetime(1985, 7, 1, 13, 30)
    start_time = datetime(1985, 1, 2, 0, 0)

    # model time-step in seconds
    model = Model(start_time=start_time,
                  duration=timedelta(hours=3 * 24 + 23),
                  time_step=15 * 60,
                  uncertain=False)

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

    print 'adding outputters'
    renderer = Renderer(mapfile, images_dir, size=(800, 600))
    renderer.viewport = ((-122, 33), (-117, 35))
    model.outputters += renderer

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

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

    print 'adding a spill'
    end_time = start_time + timedelta(hours=24)
    spill = point_line_release_spill(num_elements=1000,
                                     start_position=(202.294666, 71.922333,
                                                     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 current mover:'
    # currents from ROMS Santa Barbara run, provided by UCLA
    curr_file = os.path.join(base_dir, 'BOEM', 'Currentfilelist.txt')
    print curr_file
    topology_file = os.path.join(base_dir, 'TopologyCurrent.DAT')
    model.movers += GridCurrentMover(curr_file, topology_file)
    # model.movers += GridCurrentMover(curr_file)

    print 'adding a wind mover:'
    # winds from the ROMS Arctic run, provided by Walter Johnson
    wind_file = os.path.join(base_dir, 'BOEM', 'Windfilelist.txt')
    print wind_file
    topology_file = os.path.join(base_dir, 'TopologyCurrent.DAT')
    model.movers += GridWindMover(wind_file, topology_file)
    # model.movers += GridWindMover(wind_file, topology_file)

    #  print 'adding an ice mover:'
    #  ice from the ROMS Arctic run, provided by Walter Johnson
    #  ice_file = os.path.join(base_dir, 'data_gnome', 'ROMS_h2ouv', 'arctic_filelist.txt')
    #  topology_file = os.path.join(base_dir, 'data_gnome', 'arctic_subset_newtopo2.DAT')
    #  model.movers += IceMover(ice_file, topology_file)
    #  model.movers += IceMover(ice_file)
    #  print ice_file

    return model
Exemple #30
0
def make_model(images_dir=os.path.join(base_dir, 'images2')):
    print('initializing the model')

    start_time = datetime(int(sys.argv[1]), int(sys.argv[2]), int(sys.argv[3]),
                          int(sys.argv[4]), int(sys.argv[5]))
    mapfile = get_datafile(os.path.join(base_dir, './brazil-coast.bna'))

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

    # # the image output renderer
    # global renderer
    #duration = timedelta(minutes=5)
    #timestep = timedelta(minutes=5)
    duration = timedelta(minutes=5)
    timestep = timedelta(minutes=5)
    endtime = start_time + duration

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

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

    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))

    #print 'adding a spill'
    #spill = point_line_release_spill(num_elements=122,
    #                                 start_position=(-35.14,
    #                                                 -9.40, 0.0),
    #                                 release_time=start_time)
    #model.spills += spill

    #spill2 = spatial_release_spill(-35.14,-9.40, 0.0, start_time)
    #model.spills += spill2

    #print 'load nc'
    #netcdf_file = os.path.join(base_dir, 'maceio.nc')
    #relnc = InitElemsFromFile(netcdf_file,release_time=start_time)
    #relnc = InitElemsFromFile(netcdf_file,index=5)
    #spillnc = Spill(release=relnc)
    #print spillnc.release.num_elements
    #print spillnc.release.name
    #print spillnc.substance
    #print relnc._init_data['age']
    #print relnc.release_time

    #model.spills += spillnc

    #model._load_spill_data()

    #for sc in model.spills.items():
    #    sc.prepare_for_model_run()

    #print(relnc.num_elements)
    #print(relnc.num_released)

    # add particles - it works
    print('adding particles')
    # Persistent oil spill in contiguous zone border
    if int(sys.argv[6]) == 1:
        release = release_from_splot_data(start_time, 'contiguous.txt')
        print("Adding new particles")
        model.spills += Spill(release=release, substance=subs)

    # Particles from previows simulation step
    try:
        f = open('step.txt')
        f.close()
        release2 = release_from_splot_data(start_time, 'step.txt')
        model.spills += Spill(release=release2, substance=subs)
    except IOError:
        print('No previous step, using only contiguous.txt')

    #assert rel.num_elements == exp_num_elems
    #assert len(rel.start_position) == exp_num_elems
    #cumsum = np.cumsum(exp)
    #for ix in xrange(len(cumsum) - 1):
    #    assert np.all(rel.start_position[cumsum[ix]] ==
    #                  rel.start_position[cumsum[ix]:cumsum[ix + 1]])
    #assert np.all(rel.start_position[0] == rel.start_position[:cumsum[0]])

    #spnc = Spill(release=None)
    #spnc.release = relnc

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

    print('adding a current mover:')

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

    print('adding a grid wind mover:')
    wind_file = get_datafile(os.path.join(base_dir, 'vento15a28de09.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 = ((-55, -34), (-30, 5))  #1/4 N alagoas
    model.outputters += renderer

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

    return model