def test_rewind(): """ Test rewinding spill containter rewinds the spills. - SpillContainer should reset its the data_arrays to empty and num_released to 0 - it should reset num_released = 0 for all spills and reset start_time_invalid flag to True. Basically all spills are rewound """ num_elements = 100 release_time = datetime(2012, 1, 1, 12) release_time2 = release_time + timedelta(hours=24) start_position = (23.0, -78.5, 0.0) sc = SpillContainer() spills = [point_line_release_spill(num_elements, start_position, release_time), point_line_release_spill(num_elements, start_position, release_time2)] sc.spills.add(spills) sc.prepare_for_model_run(windage_at) for time in [release_time, release_time2]: sc.release_elements(3600, time) assert sc.num_released == num_elements * len(spills) for spill in spills: assert spill.num_released == spill.release.num_elements sc.rewind() assert sc.num_released == 0 assert_dataarray_shape_size(sc) for spill in spills: assert spill.num_released == 0 assert spill.release.start_time_invalid is None
def test_spills_different_substance_release(self): ''' Test data structure gets correctly set/updated after release_elements is invoked ''' sc = SpillContainer() rel_time = datetime(2014, 1, 1, 12, 0, 0) end_time = rel_time + timedelta(hours=1) time_step = 900 splls0 = [point_line_release_spill(100, (1, 1, 1), rel_time, end_release_time=end_time, element_type=floating(substance=test_oil), amount=100, units='kg'), point_line_release_spill(50, (2, 2, 2), rel_time + timedelta(seconds=900), element_type=floating(substance=test_oil), amount=150, units='kg'), ] sc.spills += splls0 splls1 = point_line_release_spill(10, (0, 0, 0), rel_time, element_type=floating(substance=None)) with pytest.raises(ValueError): # when you add a spill with another substance, you should get an error. sc.spills += splls1
def test_to_dict(self): c_spill = [point_line_release_spill(self.num_elements, self.start_position, self.start_time) for i in range(2)] u_spill = [point_line_release_spill(self.num_elements, self.start_position2, self.start_time2) for i in range(2)] scp = SpillContainerPair(True) for sp_tuple in zip(c_spill, u_spill): scp += sp_tuple dict_ = scp.to_dict() for key in dict_.keys(): if key == 'certain_spills': enum_spill = c_spill elif key == 'uncertain_spills': enum_spill = u_spill for (i, spill) in enumerate(enum_spill): assert dict_[key]['items'][i][0] \ == '{0}.{1}'.format(spill.__module__, spill.__class__.__name__) assert dict_[key]['items'][i][1] == i
def test_cont_not_valid_times_exception(self): """ Check exception raised if end_release_time < release_time """ with pytest.raises(ValueError): point_line_release_spill(num_elements=100, start_position=self.start_position, release_time=self.release_time, end_release_time=self.release_time - timedelta(seconds=1))
def test_to_dict(self, json_): c_spill = [point_line_release_spill(self.num_elements, self.start_position, self.start_time) for i in range(2)] u_spill = [point_line_release_spill(self.num_elements, self.start_position2, self.start_time2) for i in range(2)] scp = SpillContainerPair(True) for sp_tuple in zip(c_spill, u_spill): scp += sp_tuple toserial = scp.to_dict() assert 'spills' in toserial assert 'uncertain_spills' in toserial for key in ('spills', 'uncertain_spills'): if key == 'spills': check = c_spill else: check = u_spill alltrue = [check[ix].id == spill['id'] \ for ix, spill in enumerate(toserial[key])] assert all(alltrue) alltrue = [check[ix].obj_type == spill['obj_type'] \ for ix, spill in enumerate(toserial[key])] assert all(alltrue)
def test_model_release_after_start(): ''' This runs the model for a simple spill, that starts after the model starts ''' units = 'meter per second' seconds_in_minute = 60 start_time = datetime(2013, 2, 22, 0) model = Model(time_step=30 * seconds_in_minute, start_time=start_time, duration=timedelta(hours=3)) # add a spill that starts after the run begins. release_time = start_time + timedelta(hours=1) model.spills += point_line_release_spill(num_elements=5, start_position=(0, 0, 0), release_time=release_time) # and another that starts later.. model.spills += point_line_release_spill(num_elements=4, start_position=(0, 0, 0), release_time=start_time + timedelta(hours=2)) # Add a Wind mover: series = np.array((start_time, (10, 45)), dtype=datetime_value_2d).reshape((1, )) model.movers += WindMover(Wind(timeseries=series, units=units)) for step in model: print 'running a step' assert step['step_num'] == model.current_time_step for sc in model.spills.items(): print 'num_LEs', len(sc['positions'])
def test_weathering_data_attr(): ''' mass_balance is initialized/written if we have weatherers ''' ts = 900 s1_rel = datetime.now().replace(microsecond=0) s2_rel = s1_rel + timedelta(seconds=ts) s = [point_line_release_spill(10, (0, 0, 0), s1_rel), point_line_release_spill(10, (0, 0, 0), s2_rel)] model = Model(time_step=ts, start_time=s1_rel) model.spills += s model.step() for sc in model.spills.items(): assert len(sc.mass_balance) == 2 for key in ('beached', 'off_maps'): assert key in sc.mass_balance model.environment += [Water(), constant_wind(0., 0)] model.weatherers += [Evaporation(model.environment[0], model.environment[1])] # use different element_type and initializers for both spills s[0].amount = 10.0 s[0].units = 'kg' model.rewind() model.step() for sc in model.spills.items(): # since no substance is defined, all the LEs are marked as # nonweathering assert sc.mass_balance['non_weathering'] == sc['mass'].sum() assert sc.mass_balance['non_weathering'] == s[0].amount s[1].amount = 5.0 s[1].units = 'kg' model.rewind() exp_rel = 0.0 for ix in range(2): model.step() exp_rel += s[ix].amount for sc in model.spills.items(): assert sc.mass_balance['non_weathering'] == sc['mass'].sum() assert sc.mass_balance['non_weathering'] == exp_rel model.rewind() assert sc.mass_balance == {} # weathering data is now empty for all steps del model.weatherers[0] for ix in xrange(2): model.step() for sc in model.spills.items(): assert len(sc.mass_balance) == 2 assert (len(set(sc.mass_balance.keys()) - {'beached', 'off_maps'}) == 0)
def test_exception_uncertainty(self): spill = point_line_release_spill(self.num_elements, self.start_position, self.start_time) sp2 = point_line_release_spill(self.num_elements, self.start_position2, self.start_time2) scp = SpillContainerPair(False) with raises(ValueError): scp += (spill, sp2)
def test_exception_tuple(self): """ tests that spills can be added to SpillContainerPair object """ spill = point_line_release_spill(self.num_elements, self.start_position, self.start_time) sp2 = point_line_release_spill(self.num_elements, self.start_position2, self.start_time2) scp = SpillContainerPair(True) with raises(ValueError): scp += (spill, sp2, spill)
def test_spill_by_index(self): 'test spill_by_index returns the correct spill object' spill = [point_line_release_spill(self.num_elements, self.start_position, self.start_time), point_line_release_spill(self.num_elements, self.start_position, self.start_time)] scp = SpillContainerPair(True) scp += spill[0] scp += spill[1] for ix in range(2): assert scp.spill_by_index(ix) is spill[ix] u_spill = scp.spill_by_index(ix, uncertain=True) assert u_spill is not spill[ix] assert scp.items()[1].spills[ix] is u_spill
def test_multiple_spills(uncertain): """ SpillContainer initializes correct number of elements in data_arrays. Use Multiple spills with different release times. Also, deleting a spill shouldn't change data_arrays for particles already released. """ sc = SpillContainer(uncertain) spills = [point_line_release_spill(num_elements, start_position, release_time), point_line_release_spill(num_elements, start_position, release_time + timedelta(hours=1), end_position, end_release_time) ] sc.spills.add(spills) assert len(sc.spills) == 2 for spill in spills: assert sc.spills[spill.id] == spill assert sc.uncertain == uncertain time_step = 3600 num_steps = ((spills[-1].release.end_release_time - spills[-1].release.release_time).seconds / time_step + 1) sc.prepare_for_model_run(windage_at) for step in range(num_steps): current_time = release_time + timedelta(seconds=time_step * step) sc.release_elements(time_step, current_time) total_elements = sum(s.num_elements for s in spills) assert sc.num_released == total_elements assert_dataarray_shape_size(sc) sc.spills.remove(spills[0].id) with raises(KeyError): # it shouldn't be there anymore. assert sc.spills[spills[0].id] is None # however, the data arrays of released particles should be unchanged assert sc.num_released == spill.release.num_elements * len(spills) assert_dataarray_shape_size(sc)
def get_eq_spills(): """ returns a tuple of identical point_line_release_spill objects Set the spill's element_type is to floating(windage_range=(0, 0)) since the default, floating(), uses randomly generated values for initial data array values and these will not match for the two spills. TODO: Currently does not persist the element_type object. spill.to_dict('create') does not persist this attribute - Fix this. """ num_elements = 10 release_time = datetime(2000, 1, 1, 1) spill = point_line_release_spill(num_elements, (28, -75, 0), release_time, element_type=floating(windage_range=(0, 0))) dict_ = spill.to_dict('create') spill2 = spill.new_from_dict(dict_) # check here if equal spills didn't get created - fail this function assert spill == spill2 return (spill, spill2)
def model(sample_model, output_dir): model = sample_model_weathering(sample_model, test_oil) rel_start_pos = sample_model['release_start_pos'] rel_end_pos = sample_model['release_end_pos'] model.cache_enabled = True model.uncertain = True water, wind = Water(), constant_wind(1., 0) model.environment += [water, wind] model.weatherers += Evaporation(water=water, wind=wind) et = model.spills[0].element_type 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) line_pos[:, 1] = np.linspace(rel_start_pos[1], rel_end_pos[1], N) # print start_points model.spills += point_line_release_spill(1, start_position=rel_start_pos, release_time=model.start_time, end_position=rel_end_pos, element_type=et, amount=100, units='tons') model.outputters += TrajectoryGeoJsonOutput(output_dir=output_dir) model.rewind() return model
def make_model(img_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=3), time_step=3600, uncertain=False) print 'adding the map' p_map = model.map = ParamMap(center = (0,0), distance=20, bearing = 20, units='km' ) # hours # # Add the outputters -- render to images, and save out as netCDF # print 'adding renderer' rend = Renderer( output_dir=img_dir, image_size=(800, 600), map_BB=p_map.get_map_bounds(), land_polygons=p_map.get_land_polygon(), ) rend.graticule.set_DMS(True) model.outputters += rend # 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=100000) print 'adding a simple wind mover:' model.movers += constant_wind_mover(10, 225, 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=numerical_methods.euler); # # # # Add some spills (sources of elements) # # print 'adding four spill' model.spills += point_line_release_spill(num_elements=NUM_ELEMENTS // 4, start_position=(0.0,0.0, 0.0), release_time=start_time) return model
def test_set_end_to_none(): ''' for two different spills, ensure that release_time and end_release_time all work, even if end_release_tiem is None. ''' rel_time = datetime.now().replace(microsecond=0) end_time = rel_time + timedelta(hours=1) # (sc, wd, spread) = self.sample_sc_wd_spreading(1, rel_time) # sc.spills[0].end_release_time = None spill = point_line_release_spill(1, (0, 0, 0), rel_time, end_release_time=end_time, amount=100, units='kg', ) print "release is", spill.release print spill.release.release_time # now change the end_release_time spill.end_release_time = None num_new_particles = 10 current_time = rel_time time_step = 900 data_arrays = {'mass': np.zeros((num_new_particles,), dtype=np.float64), 'positions': np.zeros((num_new_particles, 3), dtype=np.float64), } print "release_duration:", spill.release_duration print "current_time:", current_time print "release_time:", spill.release.release_time, spill.release_time spill.set_newparticle_values(num_new_particles, current_time, time_step, data_arrays)
def test_load_location_file(self, saveloc_, model): ''' create a model load save file from script_boston which contains a spill. Then merge the created model into the model loaded from save file ''' m = Model() m.environment += [Water(), constant_wind(1., 0.)] m.weatherers += Evaporation(m.environment[0], m.environment[-1]) m.spills += point_line_release_spill(10, (0, 0, 0), datetime(2014, 1, 1, 12, 0)) # create save model sample_save_file = os.path.join(saveloc_, 'SampleSaveModel.zip') model.save(saveloc_, name='SampleSaveModel.zip') if os.path.exists(sample_save_file): model = load(sample_save_file) model.merge(m) for oc in m._oc_list: for item in getattr(m, oc): model_oc = getattr(model, oc) assert item is model_oc[item.id] for spill in m.spills: assert spill is model.spills[spill.id] # merge the other way and ensure model != m m.merge(model) assert model != m
def test_line_release_with_big_timestep(): """ a line release: where the timestep spans before to after the release time """ release_time = datetime(2012, 1, 1) end_time = release_time + timedelta(seconds=100) time_step = timedelta(seconds=300) start_pos = np.array((0., 0., 0.)) end_pos = np.array((1.0, 2.0, 0.)) sp = point_line_release_spill(num_elements=10, start_position=start_pos, release_time=release_time, end_position=end_pos, end_release_time=end_time) num = sp.num_elements_to_release(release_time - timedelta(seconds=100), time_step.total_seconds()) assert num == sp.release.num_elements data_arrays = mock_append_data_arrays(arr_types, num) sp.set_newparticle_values(num, release_time - timedelta(seconds=100), time_step.total_seconds(), data_arrays) # all axes should release particles with same, evenly spaced delta_position for ix in range(3): assert np.allclose(data_arrays['positions'][:, ix], np.linspace(start_pos[ix], end_pos[ix], sp.release.num_elements))
def mk_test_objs(cls, water=None): ''' create SpillContainer and test WeatheringData object test objects so we can run Skimmer, Burn like a model without using a full on Model NOTE: Use this function to define class level objects. Other methods in this class expect sc, and weatherers to be class level objects ''' # spreading does not need to be initialized correctly for these tests, # but since we are mocking the model, let's do it correctly if water is None: water = Water() # keep this order weatherers = [WeatheringData(water), FayGravityViscous(water)] weatherers.sort(key=weatherer_sort) sc = SpillContainer() print "******************" print "Adding a spill to spill container" sc.spills += point_line_release_spill(10, (0, 0, 0), rel_time, substance=test_oil, amount=amount, units='kg', water=water) print "spill container substance is:", sc.substance return (sc, weatherers)
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
def test_data_setting_new(): """ Can add a new item to data_arrays. This will automatically update SpillContainer's array_types dict No rewind necessary. Subsequent releases will initialize the newly added numpy array for newly released particles """ spill = point_line_release_spill(20, start_position, release_time, end_release_time=end_release_time) # release 10 particles time_step = (end_release_time - release_time) / 2 sc = sample_sc_release(time_step=time_step.seconds, spill=spill) released = sc.num_released new_arr = np.ones((sc.num_released, 3), dtype=np.float64) sc['new_name'] = new_arr assert 'new_name' in sc.data_arrays assert 'new_name' in sc.array_types assert sc['new_name'] is new_arr assert sc.array_types['new_name'].name == 'new_name' assert_dataarray_shape_size(sc) # now release remaining particles and check to see new_name is populated # with zeros - default initial_value sc.release_elements(time_step.seconds, spill.release.release_time + time_step) new_released = sc.num_released - released assert_dataarray_shape_size(sc) # shape is consistent for all arrays assert sc.num_released == spill.release.num_elements # release all elems assert np.all(sc['new_name'][-new_released:] == # initialized to 0! (0.0, 0.0, 0.0))
def test_setget(): """ set a couple of properties of release object and windages initializer to test that it works """ rel_time = datetime.now() spill = point_line_release_spill(10, (0, 0, 0), rel_time) assert len(spill.get()) > 1 assert spill.get('num_elements') == 10 assert spill.get('release_time') == rel_time spill.set('num_elements', 100) assert spill.get('num_elements') == 100 new_time = datetime(2014, 1, 1, 0, 0, 0) spill.set('release_time', new_time) assert spill.get('release_time') == new_time spill.set('windage_persist', -1) assert spill.get('windage_persist') == -1 spill.set('windage_range', (0.4, 0.4)) assert spill.get('windage_range') == (0.4, 0.4) spill.set('windage_range', [0.4, 0.4]) assert spill.get('windage_range') == [0.4, 0.4]
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.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) line_pos[:, 1] = np.linspace(rel_start_pos[1], rel_end_pos[1], N) # print start_points model.spills += point_line_release_spill(1, start_position=rel_start_pos, release_time=model.start_time, end_position=rel_end_pos) release = SpatialRelease(start_position=line_pos, release_time=model.start_time) model.spills += Spill(release) model.outputters += TrajectoryGeoJsonOutput(output_dir=output_dir) model.rewind() return model
def sample_sc_intrinsic(self, num_elements, rel_time, add_at=None): ''' initialize Sample SC and WeatheringData object objects are constructed and prepare_for_model_run() is invoked on all ''' wd = WeatheringData(Water()) end_time = rel_time + timedelta(hours=1) spills = [point_line_release_spill(num_elements, (0, 0, 0), rel_time, end_release_time=end_time, amount=100, units='kg', substance=test_oil)] sc = SpillContainer() sc.spills += spills at = wd.array_types if add_at is not None: at.update(add_at) sc.prepare_for_model_run(at) # test initialization as well wd.prepare_for_model_run(sc) for val in sc.mass_balance.values(): assert val == 0.0 # test initialization as well return (sc, wd)
def test_noparticles_model_run_after_release_time(self): """ Tests that the spill doesn't release anything if the first call to release elements is after the release time. This so that if the user sets the model start time after the spill, they don't get anything. """ sp = point_line_release_spill(num_elements=self.num_elements, start_position=self.start_position, release_time=self.release_time) # Test no particles released for following conditions # current_time > spill's release_time # current_time + timedelta > spill's release_time for rel_delay in range(1, 3): num = sp.num_elements_to_release(self.release_time + timedelta(hours=rel_delay), time_step=30 * 60) #assert num is None assert num == 0 # rewind and it should work sp.rewind() data_arrays = self.release_and_assert(sp, self.release_time, 30 * 60, {}, self.num_elements) assert np.alltrue(data_arrays['positions'] == self.start_position)
def test_simple_run_with_map(): ''' pretty much all this tests is that the model will run ''' start_time = datetime(2012, 9, 15, 12, 0) model = Model() model.map = gnome.map.MapFromBNA(testmap, refloat_halflife=6) # hours a_mover = SimpleMover(velocity=(1., 2., 0.)) model.movers += a_mover assert len(model.movers) == 1 spill = point_line_release_spill(num_elements=10, start_position=(0., 0., 0.), release_time=start_time) model.spills += spill assert len(model.spills) == 1 model.start_time = spill.release.release_time # test iterator for step in model: print 'just ran time step: %s' % step assert step['step_num'] == model.current_time_step # reset and run again model.reset() # test iterator is repeatable for step in model: print 'just ran time step: %s' % step assert step['step_num'] == model.current_time_step
def test_cont_line_release_first_timestep(self, start_position, end_position): """ testing a release that is releasing while moving over time; however, all particles are released in 1st timestep In this one it all gets released in the first time step. """ sp = point_line_release_spill(num_elements=11, start_position=start_position, release_time=self.release_time, end_position=end_position, end_release_time=self.release_time + timedelta(minutes=100)) timestep = 100 * 60 # the full release over one time step # (plus a tiny bit to get the last one) data_arrays = self.release_and_assert(sp, self.release_time, timestep + 1, {}, sp.release.num_elements) assert data_arrays['positions'].shape == (11, 3) assert np.array_equal(data_arrays['positions'][:, 0], np.linspace(-128, -129, 11)) assert np.array_equal(data_arrays['positions'][:, 1], np.linspace(28, 29, 11)) assert sp.get('num_released') == 11
def get_eq_spills(): """ returns a tuple of identical point_line_release_spill objects Set the spill's element_type is to floating(windage_range=(0, 0)) since the default, floating(), uses randomly generated values for initial data array values and these will not match for the two spills. """ num_elements = 10 release_time = datetime(2000, 1, 1, 1) spill = point_line_release_spill(num_elements, (28, -75, 0), release_time, element_type=floating(windage_range=(0, 0))) #dict_ = spill.to_dict('save') #spill2 = spill.new_from_dict(dict_) spill2 = copy.deepcopy(spill) # IDs will not match! force this so our tests work spill2._id = spill.id # check here if equal spills didn't get created - fail this function assert spill == spill2 return (spill, spill2)
def model(sample_model_fcn, output_filename): """ Use fixture model_surface_release_spill and add a few things to it for the test """ model = sample_model_fcn['model'] model.cache_enabled = True model.spills += \ point_line_release_spill(num_elements=5, start_position=sample_model_fcn['release_start_pos'], release_time=model.start_time, end_release_time=model.start_time + model.duration, substance=test_oil, amount=1000, units='kg') water = Water() model.movers += RandomMover(diffusion_coef=100000) model.movers += constant_wind_mover(1.0, 0.0) model.weatherers += Evaporation(water, model.movers[-1].wind) model.outputters += NetCDFOutput(output_filename) model.rewind() return model
def test_line_release_with_one_element(): """ one element with a line release -- doesn't really make sense, but it shouldn't crash """ release_time = datetime(2012, 1, 1) end_time = release_time + timedelta(seconds=100) time_step = timedelta(seconds=10) start_pos = np.array((0., 0., 0.)) end_pos = np.array((1.0, 2.0, 0.)) sp = point_line_release_spill(num_elements=1, start_position=start_pos, release_time=release_time, end_position=end_pos, end_release_time=end_time) num = sp.num_elements_to_release(release_time, time_step.total_seconds()) data_arrays = mock_append_data_arrays(arr_types, num) assert num == 1 sp.set_newparticle_values(num, release_time, time_step.total_seconds(), data_arrays) assert sp.get('num_released') == 1 assert np.array_equal(data_arrays['positions'], [start_pos])
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) line_pos[:, 1] = np.linspace(rel_start_pos[1], rel_end_pos[1], N) start_pos = (-164.01696, 72.921024, 0) model.spills += point_line_release_spill(1, start_position=start_pos, release_time=model.start_time, end_position=start_pos) release = SpatialRelease(start_position=line_pos, release_time=model.start_time) model.spills += Spill(release) model.movers += c_ice_mover model.outputters += IceGeoJsonOutput([c_ice_mover]) model.rewind() return model
def test_split_element(): ''' test split_element() method ''' sc = SpillContainer() o_sc = SpillContainer() reltime = datetime(2015, 1, 1, 12, 0, 0) num_les = 10 sc.spills += point_line_release_spill(num_les, (1, 1, 1), reltime, amount=100, units='kg', substance=test_oil) o_sc.spills += copy.deepcopy(sc.spills[0]) sc.prepare_for_model_run({'fate_status'}) sc.release_elements(900, reltime) o_sc.prepare_for_model_run({'fate_status'}) o_sc.release_elements(900, reltime) # now do a split at element - fate data is not being initialized; however # we want to make sure fate_data arrays are sync'd with sc data arrays so # test for fate=non_weather num = 2 l_frac = (.65, .35) subs = sc.get_substances(complete=False)[0] data = sc.substancefatedata(subs, {'fate_status'}, fate='non_weather') assert 'id' in data ix = data['id'][0] sc.split_element(ix, num, l_frac) for name in sc._data_arrays: split = sc[name] d_split = data[name] idx = np.where(sc['id'] == ix)[0][0] orig = o_sc[name] assert len(split) == num_les + num - 1 assert len(d_split) == num_les + num - 1 at = sc.array_types[name] if isinstance(at, array_types.ArrayTypeDivideOnSplit): assert np.allclose(split[idx:idx + num].sum(0), orig[idx]) assert np.allclose(split[idx], l_frac[0] * orig[idx]) else: assert np.all(split[idx:idx + num] == orig[idx]) # fatedata copy of sc data is also updated assert np.allclose(d_split, split)
def test_model_release_after_start(): ''' This runs the model for a simple spill, that starts after the model starts ''' units = 'meter per second' seconds_in_minute = 60 start_time = datetime(2013, 2, 22, 0) model = Model(time_step=30 * seconds_in_minute, start_time=start_time, duration=timedelta(hours=3)) # add a spill that starts after the run begins. release_time = start_time + timedelta(hours=1) model.spills += point_line_release_spill(num_elements=5, start_position=(0, 0, 0), release_time=release_time) # and another that starts later.. model.spills += point_line_release_spill(num_elements=4, start_position=(0, 0, 0), release_time=(start_time + timedelta(hours=2))) # Add a Wind mover: series = np.array((start_time, (10, 45)), dtype=datetime_value_2d).reshape( (1, )) model.movers += WindMover(Wind(timeseries=series, units=units)) for step in model: print 'running a step' assert step['step_num'] == model.current_time_step for sc in model.spills.items(): print 'num_LEs', len(sc['positions'])
def setup_test(self, end_time_delay, num_les, ts=900.): stime = datetime(2015, 1, 1, 12, 0) etime = stime + end_time_delay st_pos = (0, 0, 0) oil = test_oil m1 = Model(start_time=stime, time_step=ts) m1.environment += [constant_wind(0, 0), Water()] m1.weatherers += Evaporation() m1.spills += point_line_release_spill(num_les[0], st_pos, stime, end_release_time=etime, substance=oil, amount=36000, units='kg') m1.outputters += WeatheringOutput() m2 = Model(start_time=stime, time_step=ts) m2.environment += [constant_wind(0, 0), Water()] m2.weatherers += Evaporation() m2.spills += point_line_release_spill(num_les[1], st_pos, stime, end_release_time=etime, substance=oil, amount=36000, units='kg') m2.outputters += WeatheringOutput() return (m1, m2)
def make_model(images_dir=os.path.join(base_dir,"images")): print "initializing the model" start_time = datetime(2013, 7, 23, 0) model = Model(start_time = start_time, duration = timedelta(hours=47), # n+1 of data in file time_step = 900, # 4 hr in seconds uncertain = False, ) mapfile = os.path.join(base_dir, './coast.bna') print "adding the map" gnome_map = MapFromBNA(mapfile, refloat_halflife=6) # hours print "adding renderer" model.outputters += Renderer(mapfile, images_dir, size=(1800, 1600)) print "adding a wind mover from a time-series" ## this is wind wind_file=get_datafile(os.path.join(base_dir, 'wind.WND')) wind = Wind(filename=wind_file) w_mover = WindMover(wind) model.movers += w_mover print "adding a current mover:" ## this is currents curr_file = get_datafile(os.path.join(base_dir, 'current.txt')) model.movers += GridCurrentMover(curr_file) ## ## Add some spills (sources of elements) ## print "adding 13 points in a cluster that has some small initial separation as the source of spill" for i in range(len(coor)): aaa=utmToLatLng(14,coor[i][0],coor[i][1],northernHemisphere=True) model.spills += point_line_release_spill(num_elements=1, start_position = (aaa[1],aaa[0], 0.0), release_time = start_time, ) print "adding netcdf output" netcdf_output_file = os.path.join(base_dir,'GNOME_output.nc') scripting.remove_netcdf(netcdf_output_file) model.outputters += NetCDFOutput(netcdf_output_file, which_data='all') return model
def model(sample_model): """ Use fixture sample_model and add a few things to it for the test """ model = sample_model['model'] model.cache_enabled = True model.spills += point_line_release_spill(num_elements=5, start_position=sample_model['release_start_pos'], release_time=model.start_time, end_release_time=model.start_time + model.duration, element_type=floating(windage_persist=-1)) return model
def test_release_end_of_step(duration): ''' - Tests that elements released at end of step are recorded with their initial conditions with correct timestamp - Also tests the age is set correctly. todo: write separate test for checking age ''' model = Model(time_step=timedelta(minutes=15), duration=timedelta(hours=duration)) end_release_time = model.start_time + model.duration model.spills += point_line_release_spill(10, (0.0, 0.0, 0.0), model.start_time, end_release_time=end_release_time) model.movers += SimpleMover(velocity=(1., -1., 0.0)) print '\n---------------------------------------------' print 'model_start_time: {0}'.format(model.start_time) prev_rel = len(model.spills.LE('positions')) for step in model: new_particles = len(model.spills.LE('positions')) - prev_rel if new_particles > 0: assert np.all( model.spills.LE('positions')[-new_particles:, :] == 0) assert np.all(model.spills.LE('age')[-new_particles:] == 0) # assert np.all(model.spills.LE('age')[-new_particles:] == # (model.model_time + timedelta(seconds=model.time_step) # - model.start_time).seconds) if prev_rel > 0: assert np.all(model.spills.LE('positions')[:prev_rel, :2] != 0) assert np.all(model.spills.LE('age')[:prev_rel] >= model.time_step) prev_rel = len(model.spills.LE('positions')) print('current_time_stamp: {0}'.format( model.spills.LE('current_time_stamp'))) print 'particle ID: {0}'.format(model.spills.LE('id')) print 'positions: \n{0}'.format(model.spills.LE('positions')) print 'age: \n{0}'.format(model.spills.LE('age')) print 'just ran: %s' % step print 'particles released: %s' % new_particles print '---------------------------------------------' print '\n==============================================='
def test_init(self): """ Tests object initializes correctly. - self.end_position == self.start_position if it is not given as input - self.end_release_time == self.release_time if not given as input """ sp = point_line_release_spill(num_elements=self.num_elements, start_position=self.start_position, release_time=self.release_time) release = sp.release assert release.num_elements == self.num_elements assert (np.all(release.start_position == self.start_position) and np.all(release.end_position is None)) assert (np.all(release.release_time == self.release_time) and release.end_release_time is None) assert sp.get('release_duration') == 0
def test_bulk_init_volume_fay_area_two_spills(self): ''' for two different spills, ensure bulk_init_volume and fay_area is set correctly based on the blob of volume released from each spill. The volume of the blob should be associated only with its own spill and it should be based on water temperature at release time. ''' rel_time = datetime.now().replace(microsecond=0) (sc, wd, spread) = self.sample_sc_wd_spreading(100, rel_time) sc.spills[0].end_release_time = None sc.spills += point_line_release_spill(100, (0, 0, 0), rel_time, amount=10, units='kg', substance=test_oil) op = sc.spills[0].substance rho = op.density_at_temp(wd.water.temperature) b_init_vol = [spill.get_mass() / rho for spill in sc.spills] sc.prepare_for_model_run(wd.array_types) for w in (wd, spread): w.prepare_for_model_run(sc) # release elements num = sc.release_elements(default_ts, rel_time) if num > 0: for w in (wd, spread): w.initialize_data(sc, num) # bulk_init_volume is set in same order as b_init_vol print sc['bulk_init_volume'] print b_init_vol mask = sc['spill_num'] == 0 assert np.all(sc['bulk_init_volume'][mask] == b_init_vol[0]) assert np.all(sc['bulk_init_volume'][~mask] == b_init_vol[1]) assert np.all(sc['fay_area'][mask] != sc['fay_area'][~mask]) i_area = sc['fay_area'].copy() # update age and test fay_area update remains unequal sc['age'][:] = default_ts for w in (wd, spread): self.step(w, sc, rel_time) assert np.all(sc['fay_area'][mask] != sc['fay_area'][~mask]) assert np.all(sc['fay_area'] > i_area)
def test_release_at_right_time(): ''' Tests that the elements get released when they should There are issues in that we want the elements to show up in the output for a given time step if they were supposed to be released then. Particularly for the first time step of the model. ''' # default to now, rounded to the nearest hour seconds_in_minute = 60 minutes_in_hour = 60 seconds_in_hour = seconds_in_minute * minutes_in_hour start_time = datetime(2013, 1, 1, 0) time_step = 2 * seconds_in_hour model = Model(time_step=time_step, start_time=start_time, duration=timedelta(hours=12)) # add a spill that starts right when the run begins model.spills += point_line_release_spill(num_elements=12, start_position=(0, 0, 0), release_time=datetime(2013, 1, 1, 0), end_release_time=datetime(2013, 1, 1, 6) ) # before the run - no elements present since data_arrays get defined after # 1st step (prepare_for_model_run): assert model.spills.items()[0].num_released == 0 model.step() assert model.spills.items()[0].num_released == 4 model.step() assert model.spills.items()[0].num_released == 8 model.step() assert model.spills.items()[0].num_released == 12 model.step() assert model.spills.items()[0].num_released == 12
def test_end_position(self): """ Define a point release since end_position is not given. Now if start_position is changed, the end_position is still None, unless user explicitly changes it. If we started out with Point release, it continues to be a Point release until end_position attribute is modified """ sp = point_line_release_spill(num_elements=self.num_elements, start_position=self.start_position, release_time=self.release_time) assert sp.release.end_position is None sp.release.start_position = (0, 0, 0) assert np.all(sp.release.start_position == (0, 0, 0)) assert sp.release.end_position is None
def test_end_release_time(self): """ similar to test_end_position - if end_release_time is None, user defined an instantaneous release and varying the release_time will not effect end_release_time. User must explicitly change end_release_time if we want to make this time varying """ sp = point_line_release_spill(num_elements=self.num_elements, start_position=self.start_position, release_time=self.release_time) assert sp.end_release_time is None new_time = (self.release_time + timedelta(hours=20)) sp.release.release_time = new_time assert sp.release_time == new_time assert sp.end_release_time is None
def test_simple_run_rewind(): ''' Pretty much all this tests is that the model will run and the seed is set during first run, then set correctly after it is rewound and run again ''' start_time = datetime(2012, 9, 15, 12, 0) model = Model() model.map = gnome.map.GnomeMap() a_mover = SimpleMover(velocity=(1., 2., 0.)) model.movers += a_mover assert len(model.movers) == 1 spill = point_line_release_spill(num_elements=10, start_position=(0., 0., 0.), release_time=start_time) model.spills += spill assert len(model.spills) == 1 # model.add_spill(spill) model.start_time = spill.release.release_time # test iterator for step in model: print 'just ran time step: %s' % model.current_time_step assert step['step_num'] == model.current_time_step pos = np.copy(model.spills.LE('positions')) # rewind and run again: print 'rewinding' model.rewind() # test iterator is repeatable for step in model: print 'just ran time step: %s' % model.current_time_step assert step['step_num'] == model.current_time_step assert np.all(model.spills.LE('positions') == pos)
def model(sample_model, output_filename): model = sample_model['model'] rel_start_pos = sample_model['release_start_pos'] rel_end_pos = sample_model['release_end_pos'] model.cache_enabled = True model.uncertain = True model.spills += point_line_release_spill(2, start_position=rel_start_pos, release_time=model.start_time, end_position=rel_end_pos) model.time_step = 3600 model.duration = timedelta(hours=1) model.rewind() return model
def test_spills_same_substance_init(self): sc = SpillContainer() et = floating(substance=test_oil) sp_add = [ point_line_release_spill(3, (1, 1, 1), datetime.now(), element_type=et), Spill(Release(datetime.now(), 10), amount=100, units='kg', element_type=floating(substance=test_oil)), Spill(Release(datetime.now(), 10), element_type=floating(substance=et.substance)) ] sc.spills += sp_add assert len(sc.get_substances()) == 1 sc.prepare_for_model_run() assert all([sp_add == spills for spills in sc.iterspillsbysubstance()])
def test_windage_index(): """ A very simple test to make sure windage is set for the correct sc if staggered release """ sc = SpillContainer() rel_time = datetime(2013, 1, 1, 0, 0) timestep = 30 for i in range(2): spill = point_line_release_spill(num_elements=5, start_position=(0., 0., 0.), release_time=rel_time + i * timedelta(hours=1), element_type=floating(windage_range=(i * .01 + .01, i * .01 + .01), windage_persist=900) ) sc.spills.add(spill) windage = ['windages', 'windage_range', 'windage_persist'] sc.prepare_for_model_run(array_types=windage) sc.release_elements(timestep, rel_time) wm = constant_wind_mover(5, 0) wm.prepare_for_model_step(sc, timestep, rel_time) wm.model_step_is_done() # need this to toggle _windage_is_set_flag def _check_index(sc): ''' internal function for doing the test after windage is set - called twice so made a function ''' # only 1st sc is released for sp in sc.spills: mask = sc.get_spill_mask(sp) if np.any(mask): assert np.all(sc['windages'][mask] == sp.windage_range[0]) # only 1st spill is released _check_index(sc) # 1st ASSERT sc.release_elements(timestep, rel_time + timedelta(hours=1)) wm.prepare_for_model_step(sc, timestep, rel_time) _check_index(sc) # 2nd ASSERT
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
def test_spills_different_substance_init(self): sc = SpillContainer() splls0 = [ point_line_release_spill( 3, (1, 1, 1), datetime.now(), element_type=floating(substance=test_oil)), Spill(Release(datetime.now(), 10), element_type=floating(substance=test_oil)), ] sc.spills += splls0 splls1 = [ Spill(Release(datetime.now(), 10), element_type=floating(substance='oil_crude')) ] sc.spills += splls1 assert (len(sc.get_substances()) == 2 and len(sc.iterspillsbysubstance()) == 2)
def test_uncertain_copy(): """ only tests a few things... """ spill = point_line_release_spill( num_elements=100, start_position=(28, -78, 0.), release_time=datetime.now(), end_position=(29, -79, 0.), end_release_time=(datetime.now() + timedelta(hours=24)), element_type=floating(windage_range=(.02, .03), windage_persist=-1)) u_spill = spill.uncertain_copy() assert u_spill is not spill assert np.array_equal(u_spill.release.start_position, spill.release.start_position) del spill del u_spill
def test_inst_line_release(self, start_position, end_position): """ release all elements instantaneously but start_position != end_position so they are released along a line """ sp = point_line_release_spill(num_elements=11, start_position=start_position, release_time=self.release_time, end_position=end_position) data_arrays = self.release_and_assert(sp, self.release_time, 600, {}, sp.release.num_elements) assert data_arrays['positions'].shape == (11, 3) assert np.array_equal(data_arrays['positions'][:, 0], np.linspace(-128, -129, 11)) assert np.array_equal(data_arrays['positions'][:, 1], np.linspace(28, 29, 11)) assert sp.num_released == 11
def test_serialization_deserialization(self, json_, amount, units): """ tests serializatin/deserialization of the Spill object """ spill = point_line_release_spill(num_elements=self.num_elements, start_position=self.start_position, release_time=self.release_time, amount=amount, units=units) dict_ = Spill.deserialize(spill.serialize(json_)) if json_ == 'save': new_spill = Spill.new_from_dict(dict_) assert spill == new_spill else: # for webapi, make new objects from nested objects before creating # new element_type dict_['element_type'] = spill.element_type dict_['release'] = spill.release new_spill = Spill.new_from_dict(dict_) assert True
def test_release_particles(self): '''test that the 'id' for uncertain spill container's data is starting from 0''' spill = [ point_line_release_spill(self.num_elements, self.start_position, self.start_time) for i in range(2) ] scp = SpillContainerPair(True) scp += spill[0] scp += spill[1] for sc in scp.items(): sc.prepare_for_model_run(windage_at) # model sets this for each step sc.current_time_stamp = self.start_time sc.release_elements(100, self.start_time) for key in ['id', 'spill_num', 'age']: c_val = scp.LE(key) u_val = scp.LE(key, 'uncertain') assert np.all(c_val == u_val)
def test_noparticles_model_run_before_release_time(self): """ Tests that the spill doesn't release anything if the first call to num_elements_to_release is before the release_time + timestep. """ sp = point_line_release_spill(num_elements=self.num_elements, start_position=self.start_position, release_time=self.release_time) print 'release_time:', self.release_time timestep = 360 # seconds # right before the release num = sp.num_elements_to_release( self.release_time - timedelta(seconds=360), timestep) assert num == 0 # right after the release data_arrays = self.release_and_assert( sp, self.release_time - timedelta(seconds=1), timestep, {}, self.num_elements) assert np.alltrue(data_arrays['positions'] == self.start_position)
def test_serialize_deserialize(json_, output_filename): ''' todo: this behaves in unexpected ways when using the 'model' testfixture. For now, define a model in here for the testing - not sure where the problem lies ''' s_time = datetime(2014, 1, 1, 1, 1, 1) model = Model(start_time=s_time) model.spills += point_line_release_spill(num_elements=5, start_position=(0, 0, 0), release_time=model.start_time) o_put = NetCDFOutput(output_filename) model.outputters += o_put model.movers += RandomMover(diffusion_coef=100000) # ========================================================================== # o_put = [model.outputters[outputter.id] # for outputter in model.outputters # if isinstance(outputter, NetCDFOutput)][0] # ========================================================================== model.rewind() print "step: {0}, _start_idx: {1}".format(-1, o_put._start_idx) for ix in range(2): model.step() print "step: {0}, _start_idx: {1}".format(ix, o_put._start_idx) dict_ = o_put.deserialize(o_put.serialize(json_)) o_put2 = NetCDFOutput.new_from_dict(dict_) if json_ == 'save': assert o_put == o_put2 else: # _start_idx and _middle_of_run should not match assert o_put._start_idx != o_put2._start_idx assert o_put._middle_of_run != o_put2._middle_of_run assert o_put != o_put2 if os.path.exists(o_put.netcdf_filename): print '\n{0} exists'.format(o_put.netcdf_filename)
def test_single_line(num_elements): """ various numbers of elemenets over ten time steps, so release is less than one, one and more than one per time step. """ print 'using num_elements:', num_elements release_time = datetime(2012, 1, 1) end_time = release_time + timedelta(seconds=100) time_step = timedelta(seconds=10) start_pos = np.array((0., 0., 0.)) end_pos = np.array((1.0, 2.0, 0.)) sp = point_line_release_spill(num_elements=num_elements, start_position=start_pos, release_time=release_time, end_position=end_pos, end_release_time=end_time) time = release_time data_arrays = {} while time <= end_time + time_step * 2: # data = sp.release_elements(time, time_step.total_seconds()) num = sp.num_elements_to_release(time, time_step.total_seconds()) data_arrays = mock_append_data_arrays(arr_types, num, data_arrays) if num > 0: sp.set_newparticle_values(num, time, time_step.total_seconds(), data_arrays) time += time_step assert len(data_arrays['positions']) == num_elements assert np.allclose(data_arrays['positions'][0], start_pos) assert np.allclose(data_arrays['positions'][-1], end_pos) # all axes should release particles with same, evenly spaced delta_position for ix in range(3): assert np.allclose( data_arrays['positions'][:, ix], np.linspace(start_pos[ix], end_pos[ix], num_elements))
def test_rewind_change_spill_attribute(self): ''' check that if an attribute of forcast spillcontainer is updated, the uncertain spill container creates a new copy of uncertain spills ''' num_elements = 100 release_time = datetime(2012, 1, 1, 12) start_position = (23.0, -78.5, 0.0) scp = SpillContainerPair(uncertain=True) scp += point_line_release_spill(num_elements, start_position, release_time) (forecast_sc, uncertain_sc) = scp.items() assert forecast_sc.spills == uncertain_sc.spills forecast_sc.spills[0].release_time = release_time + timedelta(hours=1) (forecast_sc, uncertain_sc) = scp.items() assert forecast_sc.spills != uncertain_sc.spills scp.rewind() (forecast_sc, uncertain_sc) = scp.items() assert forecast_sc.spills == uncertain_sc.spills
def test_propeties(): """ NOTE: this is not longer set and get -- it's propeties instead set a couple of properties of release object and windages initializer to test that it works # fixme -- maybe this should be a complete test! """ rel_time = datetime.now() spill = point_line_release_spill(10, (0, 0, 0), rel_time) assert spill.num_elements == 10 assert spill.release_time == rel_time spill.num_elements = 100 assert spill.num_elements == 100 new_time1 = datetime(2014, 1, 1, 0, 0, 0) spill.release_time = new_time1 assert spill.release_time == new_time1 new_time2 = datetime(2014, 1, 1, 2, 0, 0) spill.end_release_time = new_time2 assert spill.end_release_time == new_time2 assert spill.release_duration == (new_time2 - new_time1).total_seconds() spill.start_position = (1, 2, 3) assert np.all(spill.start_position == (1, 2, 3)) spill.end_position = (2, 2, 3) assert np.all(spill.end_position == (2, 2, 3)) spill.windage_persist = -1 assert spill.windage_persist == -1 spill.windage_range = (0.4, 0.4) assert spill.windage_range == (0.4, 0.4)
def test_inst_point_release(self): """ Test all particles for an instantaneous point release are released correctly. - also tests that once all particles have been released, no new particles are released in subsequent steps """ sp = point_line_release_spill(num_elements=self.num_elements, start_position=self.start_position, release_time=self.release_time, amount=100, units='kg') assert sp.release_duration == 0 timestep = 3600 # seconds # release all particles data_arrays = self.release_and_assert(sp, self.release_time, timestep, {}, self.num_elements) assert np.alltrue(data_arrays['positions'] == self.start_position) # no more particles to release since all particles have been released num = sp.num_elements_to_release(self.release_time + timedelta(10), timestep) assert num == 0 # reset and try again sp.rewind() assert sp.num_released == 0 num = sp.num_elements_to_release(self.release_time - timedelta(10), timestep) assert num == 0 assert sp.num_released == 0 # release all particles data_arrays = self.release_and_assert(sp, self.release_time, timestep, {}, self.num_elements) assert np.alltrue(data_arrays['positions'] == self.start_position) assert data_arrays['mass'].sum() == sp.get_mass('kg')
def mk_test_objs(cls, water=None): ''' create SpillContainer and test WeatheringData object test objects so we can run Skimmer, Burn like a model without using a full on Model NOTE: Use this function to define class level objects. Other methods in this class expect sc, and weatherers to be class level objects ''' # spreading does not need to be initialized correctly for these tests, # but since we are mocking the model, let's do it correctly if water is None: water = Water() # keep this order weatherers = [WeatheringData(water), FayGravityViscous(water)] weatherers.sort(key=weatherer_sort) sc = SpillContainer() sc.spills += point_line_release_spill(10, (0, 0, 0), rel_time, substance=test_oil, amount=amount, units='kg') return (sc, weatherers)
def model(sample_model): model = sample_model['model'] model.make_default_refs = True rel_start_pos = sample_model['release_start_pos'] rel_end_pos = sample_model['release_end_pos'] # model.cache_enabled = True # why use the cache -- it'll just slow things down!!! model.uncertain = False wind = constant_wind(1.0, 0.0) water = Water(311.15) model.environment += water waves = Waves(wind, water) model.environment += waves print "the environment:", model.environment start_time = model.start_time model.duration = gs.days(1) end_time = start_time + gs.hours(1) spill = point_line_release_spill(100, start_position=rel_start_pos, release_time=start_time, end_release_time=start_time + gs.hours(1), end_position=rel_end_pos, substance=test_oil, amount=1000, units='kg') model.spills += spill model.add_weathering(which='standard') return model
def make_model(): duration_hrs = 48 time_step = 900 num_steps = duration_hrs * 3600 / time_step mod = Model(start_time=t, duration=timedelta(hours=duration_hrs), time_step=time_step) spill = point_line_release_spill(num_elements=1000, amount=1600, units='kg', start_position=(0.5, 0.5, 0.0), release_time=t, end_release_time=t + timedelta(hours=4)) mod.spills += spill method = 'Trapezoid' images_dir = method + '-' + str( time_step / 60) + 'min-' + str(num_steps) + 'steps' renderer = Renderer(output_dir=images_dir, image_size=(800, 800)) renderer.delay = 5 renderer.add_grid(g) renderer.add_vec_prop(vg) renderer.graticule.set_max_lines(max_lines=0) mod.outputters += renderer mod.movers += PyCurrentMover(current=vg, default_num_method=method, extrapolate=True) mod.movers += RandomMover(diffusion_coef=10) netCDF_fn = os.path.join(base_dir, images_dir + '.nc') mod.outputters += NetCDFOutput(netCDF_fn, which_data='all') return mod