def test_serialize_deseriailize(): 'test serialize/deserialize for webapi' wind = constant_wind(1., 0) water = Water() w = Waves(wind, water) json_ = w.serialize() # deserialize and ensure the dict's are correct w2 = Waves.deserialize(json_) assert w2.wind == Wind.deserialize(json_['wind']) assert w2.water == Water.deserialize(json_['water']) assert w == w2
def test_period(U): """ test the wave period """ w = Waves(test_wind_5, default_water) print "testing for U:", U f = w.comp_period(U) print f
def test_psuedo_wind(U): """ should reverse the wave height computation at least for fetch-unlimited """ w = Waves(test_wind_5, default_water) print "testing for U:", U ## 0.707 compensates for RMS wave height assert round(w.comp_psuedo_wind(w.compute_H(U) / 0.707), 5) == round(U, 8)
def test_compute_H_fetch_huge(): """ With a huge fetch, should be same as fetch-unlimited """ water = copy(default_water) water.fetch = 1e100 # 10km w = Waves(test_wind_5, water) H_f = w.compute_H(5) # five m/s wind w.fetch = None H_nf = w.compute_H(5) assert H_f == H_nf
def test_exception(): w = Waves() # wind object undefined with pytest.raises(ReferencedObjectNotSet): w.prepare_for_model_run(start_time) w.wind = test_wind_0 # water object undefined with pytest.raises(ReferencedObjectNotSet): w.prepare_for_model_run(start_time)
def test_compute_H_fetch(): """ can it compute a wave height at all? fetch limited case """ water = copy(default_water) water.fetch = 10000 # 10km w = Waves(test_wind_5, water) # 10km H = w.compute_H(5) # five m/s wind print H
def test_call_height(): """ call with specified wave height """ water = copy(default_water) water.wave_height = 1.0 w = Waves(test_wind_5, water) H, T, Wf, De = w.get_value(None, start_time) print H, T, Wf, De assert H == .707 # returns root mean square wave height
def make_model_incomplete_waves(self): ''' create a model with waves objects with no referenced wind, water. Include Spill so we don't get warnings for it ''' model = Model(start_time=self.start_time) model.spills += Spill(Release(self.start_time, 1)) waves = Waves() model.environment += waves return (model, waves)
def test_call_height(): """ call with specified wave height """ water = copy(default_water) water.wave_height = 1.0 w = Waves(test_wind_5, water) H, T, Wf, De = w.get_value(start_time) print H, T, Wf, De assert H == 1.0
def test_peak_wave_period(wind_speed, expected): "fully developed seas" series = np.array((start_time, (wind_speed, 45)), dtype=datetime_value_2d).reshape((1, )) test_wind = Wind(timeseries=series, units='meter per second') w = Waves(test_wind, default_water) print 'Wind speed:', w.wind.get_value(start_time) T_w = w.peak_wave_period(start_time) assert np.isclose(T_w, expected)
def test_mean_wave_period_with_fetch(U): """ Test the wave period """ print "testing for U:", U water = copy(default_water) water.fetch = 1e4 # 10km w = Waves(test_wind_5, water) # 10km fetch T = w.mean_wave_period(U) print T
def test_make_default_refs(): ''' ensure make_default_refs is a thread-safe operation once object is instantiated, object.make_default_refs is an attribute of instance ''' model = Model() model1 = Model() wind = Wind(timeseries=[(t, (0, 1))], units='m/s') water = Water() waves = Waves(name='waves') waves1 = Waves(name='waves1', make_default_refs=False) model.environment += [wind, water, waves] model1.environment += waves1 # waves should get auto hooked up/waves1 should not model.step() assert waves.wind is wind assert waves.water is water with pytest.raises(ReferencedObjectNotSet): model1.step()
def test_period_fetch(U): """ Test the wave period """ water = copy(default_water) water.fetch = 1e4 # 10km w = Waves(test_wind_5, water) # 10km fetch print "testing for U:", U T = w.comp_period(U) print T
def test_weatherer_sort(): ''' Sample model with weatherers - only tests sorting of weathereres. The Model will likely not run ''' model = Model() skimmer = Skimmer(100, 'kg', efficiency=0.3, active_start=datetime(2014, 1, 1, 0, 0), active_stop=datetime(2014, 1, 1, 0, 3)) burn = Burn(100, 1, active_start=datetime(2014, 1, 1, 0, 0)) c_disp = ChemicalDispersion(.3, active_start=datetime(2014, 1, 1, 0, 0), active_stop=datetime(2014, 1, 1, 0, 3), efficiency=0.2) weatherers = [Emulsification(), Evaporation(Water(), constant_wind(1, 0)), burn, c_disp, skimmer] exp_order = [weatherers[ix] for ix in (3, 4, 2, 1, 0)] model.environment += [Water(), constant_wind(5, 0), Waves()] model.weatherers += weatherers # WeatheringData and FayGravityViscous automatically get added to # weatherers. Only do assertion on weatherers contained in list above assert model.weatherers.values()[:len(exp_order)] != exp_order model.setup_model_run() assert model.weatherers.values()[:len(exp_order)] == exp_order # check second time around order is kept model.rewind() assert model.weatherers.values()[:len(exp_order)] == exp_order # Burn, ChemicalDispersion are at same sorting level so appending # another Burn to the end of the list will sort it to be just after # ChemicalDispersion so index 2 burn = Burn(50, 1, active_start=datetime(2014, 1, 1, 0, 0)) exp_order.insert(3, burn) model.weatherers += exp_order[3] # add this and check sorting still works assert model.weatherers.values()[:len(exp_order)] != exp_order model.setup_model_run() assert model.weatherers.values()[:len(exp_order)] == exp_order
def test_serialize_deseriailize(): 'test serialize/deserialize for webapi' wind = constant_wind(15., 0) waves = Waves(wind, Water()) e = NaturalDispersion(waves) json_ = e.serialize() json_['waves'] = waves.serialize() # deserialize and ensure the dict's are correct d_ = NaturalDispersion.deserialize(json_) assert d_['waves'] == Waves.deserialize(json_['waves']) d_['waves'] = waves e.update_from_dict(d_) assert e.waves is waves
def test_sort_order(): 'test sort order for Dissolution weatherer' wind = constant_wind(15., 0) waves = Waves(wind, Water()) diss = Dissolution(waves, wind) disp = NaturalDispersion(waves=waves, water=waves.water) weathering_data = WeatheringData(water=waves.water) # dissolution is dependent upon droplet distribution generated by # natural dispersion assert weatherer_sort(disp) < weatherer_sort(diss) # dissolution needs to happen before we treat our weathering data assert weatherer_sort(diss) < weatherer_sort(weathering_data)
def test_set_efficiency(self): ''' for wave height > 6.4 m, efficiency goes to 0 ''' # make wind large so efficiency goes to 0 waves = Waves(constant_wind(0, 0), water=Water()) c_disp = ChemicalDispersion(self.spill_pct, active_range, waves=waves) pts = np.array([[0, 0], [0, 0]]) c_disp._set_efficiency(pts, self.spill.release_time) assert c_disp.efficiency == 1.0 c_disp.efficiency = 0 waves.wind.timeseries = (waves.wind.timeseries[0]['time'], (100, 0)) c_disp._set_efficiency(pts, self.spill.release_time) assert np.all(c_disp.efficiency == 0)
def test_full_run_no_evap(sample_model_fcn2, oil, temp, expected_balance): ''' test dissolution outputs post step for a full run of model. Dump json for 'weathering_model.json' in dump directory ''' low_wind = constant_wind(1., 270, 'knots') low_waves = Waves(low_wind, Water(temp)) model = sample_model_weathering2(sample_model_fcn2, oil, temp) model.environment += [Water(temp), low_wind, low_waves] # model.weatherers += Evaporation(Water(temp), low_wind) model.weatherers += NaturalDispersion(low_waves, Water(temp)) model.weatherers += Dissolution(low_waves) for sc in model.spills.items(): print sc.__dict__.keys() print sc._data_arrays print 'num spills:', len(sc.spills) print 'spill[0] amount:', sc.spills[0].amount original_amount = sc.spills[0].amount # set make_default_refs to True for objects contained in model after adding # objects to the model model.set_make_default_refs(True) model.setup_model_run() dissolved = [] for step in model: for sc in model.spills.items(): if step['step_num'] > 0: assert (sc.mass_balance['dissolution'] > 0) assert (sc.mass_balance['natural_dispersion'] > 0) assert (sc.mass_balance['sedimentation'] > 0) dissolved.append(sc.mass_balance['dissolution']) print("\nDissolved: {0}".format(sc.mass_balance['dissolution'])) print("Mass: {0}".format(sc._data_arrays['mass'])) print("Mass Components: {0}".format( sc._data_arrays['mass_components'])) print('Fraction dissolved after full run: {}'.format(dissolved[-1] / original_amount)) assert dissolved[0] == 0.0 assert np.isclose(dissolved[-1], expected_balance)
def test_set_efficiency(self): ''' for wave height > 6.4 m, efficiency goes to 0 ''' # make wind large so efficiency goes to 0 waves = Waves(constant_wind(0, 0), water=Water()) c_disp = ChemicalDispersion(self.spill_pct, active_start, active_stop, waves=waves) c_disp._set_efficiency(self.spill.release_time) assert c_disp.efficiency == 1.0 c_disp.efficiency = None waves.wind.timeseries = (waves.wind.timeseries[0]['time'], (100, 0)) c_disp._set_efficiency(self.spill.release_time) assert c_disp.efficiency == 0
def test_whitecap_fraction(U): """ Fraction whitcapping -- doesn't really check values but should catch gross errors! """ print "testing for U:", U w = Waves(test_wind_5, default_water) f = w.whitecap_fraction(U) assert f >= 0.0 assert f <= 1.0 if U == 4.0: # assert round(f, 8) == round(0.05 / 3.85, 8) # included the .5 factor from ADIOS2 assert round(f, 8) == round(0.05 / 3.85 / 2, 8)
def test_wave_energy(H, expected): """ Test the dissipative wave energy """ print "testing for H:", H water = copy(default_water) water.fetch = 1e4 # 10km w = Waves(test_wind_5, water) # 10km fetch De = w.dissipative_wave_energy(H) print De # Note: Right now we are just documenting the results that we are # getting. The expected values need to be checked for validity. assert np.isclose(De, expected, rtol=0.01)
def test_serialize_deseriailize(): 'test serialize/deserialize for webapi' wind = constant_wind(1., 0) water = Water() w = Waves(wind, water) json_ = w.serialize() json_['wind'] = wind.serialize() json_['water'] = water.serialize() # deserialize and ensure the dict's are correct d_ = Waves.deserialize(json_) print 'd_' print d_ assert d_['wind'] == Wind.deserialize(json_['wind']) assert d_['water'] == Water.deserialize(json_['water']) d_['wind'] = wind d_['water'] = water w.update_from_dict(d_) assert w.wind is wind assert w.water is water
def test_full_run(sample_model_fcn, oil, temp): ''' test emulsification outputs post step for a full run of model. Dump json for 'weathering_model.json' in dump directory ''' model = sample_model_weathering2(sample_model_fcn, oil, temp) model.environment += [Waves(), wind, Water(temp)] model.weatherers += Evaporation() model.weatherers += Emulsification() model.set_make_default_refs(True) for step in model: for sc in model.spills.items(): # need or condition to account for water_content = 0.9000000000012 # or just a little bit over 0.9 assert (sc.mass_balance['water_content'] <= .9 or np.isclose(sc.mass_balance['water_content'], 0.9)) print("Water fraction: {0}".format( sc.mass_balance['water_content'])) print "Completed step: {0}\n".format(step['step_num'])
def test__deserialize(): 'test serialize/deserialize for webapi' wind = constant_wind(15., 0) water = Water() waves = Waves(wind, water) diss = Dissolution(waves, wind) json_ = diss.serialize() pp.pprint(json_) assert json_['waves'] == waves.serialize() # deserialize and ensure the dict's are correct d_ = Dissolution.deserialize(json_) assert d_['waves'] == Waves.deserialize(json_['waves']) d_['waves'] = waves diss.update_from_dict(d_) assert diss.waves is waves
def base_environment(water_temp=280.928, salinity=34.5, wind_speed=5., wind_dir=117.): """ Create a minimalist ocean environment that allows for surface weathering Create a water, wind, and waves environment for a GNOME simulation that allows for surface weathering processes Parameters ---------- water_temp : float Temperature of the surface water (K) salinity : float Salinity of the surface ocean water (psu) wind_speed : float Wind speed (kt) wind_dir : float Wind direction (deg from North). Per atmospheric modeling convention, this points in the direction from which the wind is coming. Returns ------- water : gnome.environment.Water GNOME environment object that contains the water temperature (K) wind : gnome.environment.constant_wind GNOME environment object that contains the local wind (speed in knots and direction in deg from North) waves : gnome.environment.Waves GNOME environment object that uses the wind and water objects to predict the wave conditions. """ # Create an ocean environment using GNOME environment objects water = Water(temperature=water_temp, salinity=salinity) wind = gs.constant_wind(wind_speed, wind_dir, 'knots') waves = Waves(wind, water) return (water, wind, waves)
def test_serialize_deseriailize(): 'test serialize/deserialize for webapi' wind = constant_wind(15., 0) water = Water() waves = Waves(wind, water) bio_deg = Biodegradation(waves) json_ = bio_deg.serialize() pp.pprint(json_) assert json_['waves'] == waves.serialize() # deserialize and ensure the dict's are correct d_ = Biodegradation.deserialize(json_) assert d_['waves'] == Waves.deserialize(json_['waves']) d_['waves'] = waves bio_deg.update_from_dict(d_) assert bio_deg.waves is waves
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 sample_model_weathering(sample_model_fcn, oil, temp=311.16, num_les=10): model = sample_model_fcn['model'] rel_pos = sample_model_fcn['release_start_pos'] # update model the same way for multiple tests model.uncertain = False # fixme: with uncertainty, copying spill fails! model.duration = timedelta(hours=4) et = gnome.spill.elements.floating(substance=oil) start_time = model.start_time + timedelta(hours=1) end_time = start_time + timedelta(seconds=model.time_step * 3) spill = gnome.spill.point_line_release_spill(num_les, rel_pos, start_time, end_release_time=end_time, element_type=et, amount=100, units='kg') model.spills += spill # define environment objects that weatherers require model.environment += [constant_wind(1, 0), Water(), Waves()] return model
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
from ..conftest import (test_oil, sample_model_weathering2) import pprint as pp delay = 1. time_step = 900 rel_time = datetime(2012, 9, 15, 12, 0) active_start = rel_time + timedelta(seconds=time_step) active_stop = active_start + timedelta(hours=24.) amount = 36000. units = 'kg' wind = constant_wind(15., 0) water = Water() waves = Waves(wind, water) class ROCTests: @classmethod def mk_objs(cls, sample_model_fcn2): model = sample_model_weathering2(sample_model_fcn2, test_oil, 333.0) model.set_make_default_refs(True) model.environment += [waves, wind, water] model.weatherers += Evaporation(wind=wind, water=water) model.weatherers += Emulsification(waves=waves) return (model.spills.items()[0], model)