def test_serialize_deserialize(): """ test to_dict function for Ice object create a new ice object and make sure it has same properties """ ice_grid = IceMover(ice_file, topology_file) serial = ice_grid.serialize() ice2 = IceMover.deserialize(serial) assert ice_grid == ice2
def test_ice_fields(): """ test that data is loaded checks there is non-zero motion. """ pSpill = sample_sc_release(num_le, start_pos, rel_time) ice_mover = IceMover(ice_file, topology_file) vels = ice_mover.get_ice_velocities(test_time) frac, thick = ice_mover.get_ice_fields(test_time) # fraction values between 0 and 1 assert (np.all(frac[:] <= 1) and np.all(frac[:] >= 0) and not np.all(frac[:] == 0)) # thickness >= 0, < 10 in this example... assert (np.all(thick[:] <= 10) and np.all(thick[:] >= 0) and not np.all(thick[:] == 0))
def test_init(): 'simple initialization passes' c_ice_mover = IceMover(curr_file, topology_file) o = IceImageOutput(c_ice_mover) assert o.ice_movers[0] is c_ice_mover assert isinstance(o.map_canvas.projection, FlatEarthProjection) assert o.map_canvas.viewport == ((-180, -90), (180, 90))
def test_serialize_deserialize(): """ test to_dict function for Ice object create a new ice object and make sure it has same properties """ ice_grid = IceMover(ice_file, topology_file) serial = ice_grid.serialize('webapi') dict_ = IceMover.deserialize(serial) ice2 = IceMover.new_from_dict(dict_) assert ice_grid == ice2 ice_grid.update_from_dict(dict_) # tests no failures
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) ice_mover = IceMover(ice_file, topology_file) delta = _certain_loop(pSpill, ice_mover) _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 assert np.all(delta[:, 2] == 0) # 'z' is zeros return delta
def test_save_load_model(uncertain, zipsave, saveloc_): ''' create a model, save it, then load it back up and check it is equal to original model ''' model = make_model(uncertain) ice_mover = IceMover(testdata['IceMover']['ice_curr_curv'], testdata['IceMover']['ice_top_curv']) model.movers += ice_mover model.outputters += IceJsonOutput([ice_mover]) model.zipsave = zipsave print 'saving scenario to {}...'.format(saveloc_) _json_, savefile, _refs = model.save(saveloc_) print 'loading scenario ...' model2 = Model.load(savefile) assert model == model2
def test_save_load_model(uncertain, zipsave, saveloc_): ''' create a model, save it, then load it back up and check it is equal to original model ''' model = make_model(uncertain) ice_mover = IceMover(testdata['IceMover']['ice_curr_curv'], testdata['IceMover']['ice_top_curv']) model.movers += ice_mover model.outputters += IceGeoJsonOutput([ice_mover]) model.zipsave = zipsave print 'saving scenario ..' model.save(saveloc_) print 'loading scenario ..' model2 = load(zipname(saveloc_, model)) assert model == model2
def test_ice_image_mid_run(): ''' Test image outputter with a model NOTE: could it be tested with just a mover, and not a full model? -- that gets tricky with the cache and timesteps... ''' start_time = datetime(2015, 5, 14, 0) model = Model( time_step=3600 * 24, # one day start_time=start_time, duration=timedelta(days=3), ) model.cache_enabled = False model.uncertain = False c_ice_mover = IceMover(curr_file, topology_file) model.movers += c_ice_mover # run the model a couple steps step = model.step() step = model.step() # now add the outputter model.outputters += IceImageOutput(c_ice_mover, viewport=((-175.0, 65.0), (-145.0, 75.05))) # and run some more: step = model.step() step = model.step() # and check the output ice_output = step['IceImageOutput'] for key in ('time_stamp', 'thickness_image', 'concentration_image', 'bounding_box', 'projection'): assert key in ice_output print 'thickness img size:', len(ice_output['thickness_image']) print 'concentration img size:', len(ice_output['concentration_image'])
def test_init_with_viewport(): 'simple initialization passes' c_ice_mover = IceMover(curr_file, topology_file) o = IceImageOutput(c_ice_mover, viewport=((-90, -90), (90, 90))) assert o.map_canvas.viewport == ((-90, -90), (90, 90))
def test_init_with_image_size(): 'simple initialization passes' c_ice_mover = IceMover(curr_file, topology_file) o = IceImageOutput(c_ice_mover, image_size=(1000, 1000)) assert o.map_canvas.image_size == (1000, 1000)
# """ # # 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]) # uncertain_time_delay = 3 # u_delta = test_uncertain_loop(uncertain_time_delay) # print u_delta # assert np.all(delta[:, :2] == u_delta[:, :2]) # ice_grid = IceMover(ice_file, topology_file) # def test_default_props(): # """ # test default properties # """ # # assert ice_grid.current_scale == 1 # assert ice_grid.uncertain_time_delay == 0 # assert ice_grid.uncertain_duration == 24 # assert ice_grid.uncertain_cross == .25 # assert ice_grid.uncertain_along == .5 # assert ice_grid.extrapolate == False # assert ice_grid.time_offset == 0 #
def make_model(images_dir=os.path.join(base_dir, 'images')): print 'initializing the model' # set up the modeling environment start_time = datetime(2016, 9, 23, 0, 0) model = Model(start_time=start_time, duration=timedelta(days=2), time_step=30 * 60, uncertain=False) print 'adding the map' model.map = GnomeMap() # this is a "water world -- no land anywhere" # renderere is only top-down view on 2d -- but it's something renderer = Renderer( output_dir=images_dir, size=(1024, 768), output_timestep=timedelta(hours=1), ) renderer.viewport = ((196.14, 71.89), (196.18, 71.93)) print 'adding outputters' model.outputters += renderer # Also going to write the results out to a netcdf file netcdf_file = os.path.join(base_dir, 'script_arctic_plume.nc') scripting.remove_netcdf(netcdf_file) model.outputters += NetCDFOutput( netcdf_file, which_data='most', # output most of the data associated with the elements output_timestep=timedelta(hours=2)) print "adding Horizontal and Vertical diffusion" # Horizontal Diffusion model.movers += RandomMover(diffusion_coef=500) # vertical diffusion (different above and below the mixed layer) model.movers += RandomVerticalMover(vertical_diffusion_coef_above_ml=5, vertical_diffusion_coef_below_ml=.11, mixed_layer_depth=10) print 'adding Rise Velocity' # droplets rise as a function of their density and radius model.movers += TamocRiseVelocityMover() print 'adding a circular current and eastward current' fn = 'hycom_glb_regp17_2016092300_subset.nc' fn_ice = 'hycom-cice_ARCu0.08_046_2016092300_subset.nc' import pysgrid import netCDF4 as nc df = nc.Dataset(fn) lon = df['lon'][:] lat = df['lat'][:] grd = pysgrid.SGrid(node_lon=np.repeat(lon.reshape(1, -1), len(lat), axis=0), node_lat=np.repeat(lat.reshape(-1, 1), len(lon), axis=1)) print(grd.node_lon.shape) print(grd.node_lat.shape) gc = GridCurrent.from_netCDF(fn, units='m/s', grid=grd) model.movers += IceMover(fn_ice) model.movers += GridCurrentMover(fn) model.movers += SimpleMover(velocity=(0., 0., 0.)) model.movers += constant_wind_mover(20, 315, units='knots') # Now to add in the TAMOC "spill" print "Adding TAMOC spill" model.spills += tamoc_spill.TamocSpill( release_time=start_time, start_position=(196.16, 71.91, 40.0), num_elements=1000, end_release_time=start_time + timedelta(days=1), name='TAMOC plume', TAMOC_interval=None, # how often to re-run TAMOC ) model.spills[0].data_sources['currents'] = gc return model
import numpy as np import pytest # from gnome.basic_types import oil_status from gnome.utilities import time_utils from gnome.spill import SpatialRelease, Spill, point_line_release_spill from gnome.movers import IceMover from gnome.outputters import IceGeoJsonOutput, IceJsonOutput from ..conftest import testdata curr_file = testdata['IceMover']['ice_curr_curv'] topology_file = testdata['IceMover']['ice_top_curv'] c_ice_mover = IceMover(curr_file, topology_file) @pytest.fixture(scope='function') def model(sample_model, output_dir): model = sample_model['model'] rel_start_pos = sample_model['release_start_pos'] rel_end_pos = sample_model['release_end_pos'] model.start_time = datetime(2015, 5, 14, 0) model.cache_enabled = True model.uncertain = True N = 10 # a line of ten points line_pos = np.zeros((N, 3), dtype=np.float64) line_pos[:, 0] = np.linspace(rel_start_pos[0], rel_end_pos[0], N)
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=3600*2) mapfile = get_datafile(os.path.join(base_dir, 'arctic_coast3.bna')) print 'adding the map' model.map = MapFromBNA(mapfile, refloat_halflife=0.0) # seconds # model.map = GnomeMap() 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, 'script_old_TAPa.nc') scripting.remove_netcdf(netcdf_file) model.outputters += NetCDFOutput(netcdf_file, which_data='all') 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=(196.25, 69.75, 0.0), release_time=start_time) # # spill2 = point_line_release_spill(num_elements=5000, # start_position=(-163.75, # 69.5, # 0.0), # release_time=start_time) model.spills += spill1 # model.spills += spill2 print 'adding a RandomMover:' model.movers += RandomMover(diffusion_coef=1000) print 'adding a wind mover:' # winds from the ROMS Arctic run, provided by Walter Johnson wind_file = os.path.join(base_dir, 'arctic_filelist.txt') print wind_file topology_file = os.path.join(base_dir, 'arctic_subset_newtopo2.DAT') model.movers += IceWindMover(wind_file, topology_file) # 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, 'arctic_filelist.txt') topology_file = os.path.join(base_dir, 'arctic_subset_newtopo2.DAT') model.movers += IceMover(ice_file, topology_file) # model.movers += IceMover(ice_file) print ice_file print 'adding a current mover:' # # fn = ['N:\\Users\\Dylan.Righi\\OutBox\\ArcticROMS\\arctic_avg2_0001_gnome.nc', # 'N:\\Users\\Dylan.Righi\\OutBox\\ArcticROMS\\arctic_avg2_0002_gnome.nc'] # # gt = {'node_lon':'lon', # 'node_lat':'lat'} # # fn='arctic_avg2_0001_gnome.nc' # # ice_aware_curr = IceAwareCurrent.from_netCDF(filename=fn, # grid_topology=gt) # ice_aware_wind = IceAwareWind.from_netCDF(filename=fn, # grid = ice_aware_curr.grid,) # method = 'Trapezoid' # # # i_c_mover = PyGridCurrentMover(current=ice_aware_curr) # # i_c_mover = PyGridCurrentMover(current=ice_aware_curr, default_num_method='Euler') # i_c_mover = PyGridCurrentMover(current=ice_aware_curr, default_num_method=method) # i_w_mover = PyWindMover(wind = ice_aware_wind, default_num_method=method) # # ice_aware_curr.grid.node_lon = ice_aware_curr.grid.node_lon[:]-360 # # ice_aware_curr.grid.build_celltree() # model.movers += i_c_mover # model.movers += i_w_mover # renderer.add_grid(ice_aware_curr.grid) # renderer.add_vec_prop(ice_aware_curr) # renderer.set_viewport(((-190.9, 60), (-72, 89))) # curr_file = get_datafile(os.path.join(base_dir, 'COOPSu_CREOFS24.nc')) # c_mover = GridCurrentMover(curr_file) # model.movers += c_mover model.save('.') return model