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_get_emulsification_wind(): wind = constant_wind(3., 0) water = Water() w = Waves(wind, water) print w.get_emulsification_wind(start_time) assert w.get_emulsification_wind(start_time) == 3.0
def test_call_no_fetch_or_height(): "fully developed seas" w = Waves(test_wind_5, default_water) H, T, Wf, De = w.get_value(start_time) print H, T, Wf, De print "Need to check reasonable numbers"
def test_compute_H(): """can it compute a wave height at all? fetch unlimited """ w = Waves(test_wind_5, default_water) H = w.compute_H(5) # five m/s wind print H
def test_pseudo_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.pseudo_wind(w.compute_H(U) / 0.707), 5) == round(U, 8)
def test_mean_wave_period(U): """ test the wave period """ w = Waves(test_wind_5, default_water) print "testing for U:", U f = w.mean_wave_period(U) print f
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_fetch(): water = copy(default_water) water.fetch = 1e4 # 10km w = Waves(test_wind_5, water) H, T, Wf, De = w.get_value(start_time) print H, T, Wf, De print "Need to check reasonable numbers"
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_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_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 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_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_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_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_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 build_waves_obj(wind_speed, wind_units, direction_deg, temperature): # also test with lower wind no dispersion wind = constant_wind(wind_speed, direction_deg, wind_units) water = Water(temperature=temperature) waves = Waves(wind, water) return waves
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 test_sort_order(): 'test sort order for Biodegradation weatherer' wind = constant_wind(15., 0) waves = Waves(wind, Water()) bio_deg = Biodegradation(waves) assert weatherer_sort(bio_deg) == 11
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
def test_sort_order(): 'test sort order for Dissolution weatherer' wind = constant_wind(15., 0) waves = Waves(wind, Water()) diss = Dissolution(waves) assert weatherer_sort(diss) == 8
def test_init(): wind = constant_wind(15., 0) waves = Waves(wind, Water()) bio_deg = Biodegradation(waves) print(bio_deg.array_types) assert all([(at in bio_deg.array_types) for at in ('mass', 'droplet_avg_size')])
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_init(): 'test initialization' wind = constant_wind(15., 0) waves = Waves(wind, Water()) diss = Dissolution(waves) print diss.array_types assert all([(at in diss.array_types) for at in ('mass', 'viscosity', 'density')])
def deserialize(cls, json_): """ ChemicalDispersion could include 'waves'. """ schema = cls._schema() _to_dict = schema.deserialize(json_) if "waves" in json_ and json_["waves"] is not None: _to_dict["waves"] = Waves.deserialize(json_["waves"]) return _to_dict
def deserialize(cls, json_): """ ChemicalDispersion could include 'waves'. """ schema = cls._schema() _to_dict = schema.deserialize(json_) if 'waves' in json_ and json_['waves'] is not None: _to_dict['waves'] = Waves.deserialize(json_['waves']) return _to_dict
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, low_wind) print ('Model start time: {}, Duration: {}, Time step: {}' .format(model.start_time, model.duration, model.time_step)) for sc in model.spills.items(): print '\nSpill dict keys: ', sc.__dict__.keys() print '\nSpill data arrays: ', sc._data_arrays print 'num spills:', len(sc.spills) print ('spill[0] amount: {} {} ({})' .format(sc.spills[0].amount, sc.spills[0].units, sc.spills[0].substance.name) ) 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_num, step in enumerate(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 ('\n#Step: {}'.format(step_num)) print ("Dissolved: {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_serialize_deseriailize(): "test serialize/deserialize for webapi" wind = constant_wind(1.0, 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__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 test_serialize_deseriailize(): 'test serialize/deserialize for webapi' wind = constant_wind(15., 0) water = Water() waves = Waves(wind, water) diss = Dissolution(waves) 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 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 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_get_emulsification_wind_with_wave_height(): wind = constant_wind(3., 0) water = Water() water.wave_height = 2.0 w = Waves(wind, water) print w.get_value(start_time) print w.get_emulsification_wind(start_time) # input wave height should hav overwhelmed assert w.get_emulsification_wind(start_time) > 3.0
def test_get_emulsification_wind_with_wave_height2(): wind = constant_wind(10., 0) water = Water() water.wave_height = 2.0 w = Waves(wind, water) print w.get_value(start_time) print w.get_emulsification_wind(start_time) # input wave height should not have overwhelmed wind speed assert w.get_emulsification_wind(start_time) == 10.0
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_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_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_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_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)