def test_density_error(self, l): ''' log error if init density is less than water todo: should this raise a runtime error. May want to change how this works ''' l.uninstall() rel_time = datetime.now().replace(microsecond=0) (sc, wd) = self.sample_sc_intrinsic(100, rel_time) wd.water.set('temperature', 288, 'K') wd.water.set('salinity', 0, 'psu') new_subs = GnomeOil('TEXTRACT, STAR ENTERPRISE') new_subs.water = wd.water sc.spills[0].substance = new_subs ats = {} ats.update(sc.spills[0].all_array_types) ats.update(wd.all_array_types) # substance changed - do a rewind sc.rewind() sc.prepare_for_model_run(ats) l.install() num = sc.release_elements(default_ts, rel_time) # only capture and test density error if num > 0: wd.initialize_data(sc, num) msg = ("{0} will sink at given water temperature: {1} {2}. " "Set density to water density".format(new_subs.name, 288.0, 'K')) l.check_present(('gnome.spill.substance.GnomeOil', 'ERROR', msg))
def test_serialization(self): oil1 = GnomeOil(u'oil_ans_mp', windage_range=(0.05, 0.07)) ser = oil1.serialize() deser = GnomeOil.deserialize(ser) assert deser == oil1 assert deser.initializers[0].windage_range == oil1.windage_range assert deser.standard_density == oil1.standard_density
def test_bulltime(): ''' user set time to start emulsification ''' oil = GnomeOil(test_oil) assert oil.bulltime == -999 oil.bulltime = 3600 assert oil.bulltime == 3600
def test_save_load(self, saveloc_): ''' test save/load for initializers and for ElementType objects containing each initializer. Tests serialize/deserialize as well. These are stored as nested objects in the Spill but this should also work so test it here ''' test_obj = GnomeOil(u'oil_ans_mp', windage_range=(0.05, 0.07)) json_, savefile, refs = test_obj.save(saveloc_) test_obj2 = test_obj.__class__.load(savefile) assert test_obj == test_obj2
def test_bullwinkle(): ''' user set emulsion constant ''' oil = GnomeOil(test_oil) # our test_oil is the sample oile assert np.isclose(oil.bullwinkle, 0.1937235) oil.bullwinkle = .4 assert oil.bullwinkle == .4
def test_init(self): oil1 = GnomeOil(u'oil_ans_mp', windage_range=(0.05, 0.07)) assert oil1.windage_range == (0.05, 0.07) #assert isinstance(oil1.record, Oil) #GnomeOil doesn't have a record assert isinstance(oil1.initializers[0], InitWindages) initw = oil1.initializers[0] assert all([atype in oil1.array_types for atype in initw.array_types])
def weathering_data_arrays(n_arrays, water=None, time_step=15. * 60, substance=None, langmuir=False, num_elements=2, units='g', amount_per_element=1.0): ''' function to initialize data_arrays set by WeatheringData. Weatherer tests can use this function to release elements and initialize data without defining a model ''' if water is None: water = Water() rqd_weatherers = [WeatheringData(water), FayGravityViscous(water)] arrays = dict() arrays.update(n_arrays) for wd in rqd_weatherers: arrays.update(wd.array_types) if isinstance(substance, six.string_types): substance = GnomeOil(substance) if substance is None: substance = GnomeOil(test_oil) arrays.update(substance.array_types) sc = sample_sc_release(num_elements=num_elements, substance=substance, arr_types=arrays, time_step=time_step, units=units, amount_per_element=amount_per_element) for wd in rqd_weatherers: wd.prepare_for_model_run(sc) wd.initialize_data(sc, sc.num_released) return (sc, time_step, rqd_weatherers)
def test_set_emulsification_constants(self): test_obj = GnomeOil(u'oil_ans_mp') assert test_obj._bulltime is None assert test_obj.bullwinkle < 0.5 #assert test_obj.bullwinkle < 0.5 and test_obj.bullwinkle is test_obj.record.bullwinkle_fraction d = test_obj.serialize() d['bullwinkle_time'] = 60 d['bullwinkle_fraction'] = 0.7 test_obj.update_from_dict(d) assert test_obj.bullwinkle == 0.7 assert test_obj.serialize()['bullwinkle_fraction'] == 0.7 assert test_obj.bulltime == 60 assert test_obj.serialize()['bullwinkle_time'] == 60
def substance(self, val): ''' first try to use get_oil_props using 'val'. If this fails, then assume user has provided a valid OilProps object and use it as is ''' if val is None: self._substance = NonWeatheringSubstance() return elif isinstance(val, Substance): self._substance = val try: self._substance = GnomeOil.get_GnomeOil(val) except Exception: if isinstance(val, basestring): raise self.logger.info('Failed to get_oil_props for {0}. Use as is ' 'assuming has OilProps interface'.format(val)) self._substance = val
from datetime import datetime import numpy as np from gnome.utilities.inf_datetime import InfDateTime from gnome.environment import Water from gnome.spill.substance import GnomeOil from conftest import weathering_data_arrays, test_oil from gnome.weatherers import (Weatherer, HalfLifeWeatherer, NaturalDispersion, Dissolution, weatherer_sort) subs = GnomeOil(test_oil) rel_time = datetime(2012, 8, 20, 13) # yyyy/month/day/hr/min/sec class TestWeatherer: def test_init(self): weatherer = Weatherer() print weatherer assert weatherer.on assert weatherer.active assert weatherer.active_range == (InfDateTime('-inf'), InfDateTime('inf')) def test_one_weather(self): '''
def make_model(images_dir=os.path.join(base_dir, 'images')): print('get contiguous') kml_file = os.path.join(base_dir, 'contigua.kml') with open(kml_file) as f: contiguous = parser.parse(f).getroot().Document coordinates = contiguous.Placemark.LineString.coordinates.text.split(' ') cont_coord = [] for x in coordinates: x = x.split(',') if len(x) > 1 and float(x[1]) > -12 and float(x[1]) < -3: cont_coord.append([float(x[0]), float(x[1])]) print('initializing the model') start_time = datetime(2022, 1, 22, 12, 0) mapfile = get_datafile(os.path.join(base_dir, './brazil-coast.BNA')) gnome_map = MapFromBNA(mapfile, refloat_halflife=6) # hours duration = timedelta(days=1) timestep = timedelta(minutes=5) end_time = start_time + duration steps = duration.total_seconds() / timestep.total_seconds() print("Total step: %.4i " % (steps)) # one hour timestep model = Model(start_time=start_time, duration=duration, time_step=timestep, map=gnome_map, uncertain=False, cache_enabled=False) oil_name = 'GENERIC MEDIUM CRUDE' wd = UniformDistribution(low=.0002, high=.0002) subs = GnomeOil(oil_name, initializers=plume_initializers(distribution=wd)) #model.spills += point_line_release_spill(release_time=start_time, start_position=(-35.153, -8.999, 0.0), num_elements=1000, end_release_time=end_time, substance= subs, units='kg') #model.spills += point_line_release_spill(release_time=start_time, start_position=(-35.176, -9.135, 0.0), num_elements=1000, end_release_time=end_time, substance= subs, units='kg') #model.spills += point_line_release_spill(release_time=start_time, start_position=(-35.062, -9.112, 0.0), num_elements=1000, end_release_time=end_time, substance= subs, units='kg') #model.spills += point_line_release_spill(release_time=start_time, start_position=(-34.994, -9.248, 0.0), num_elements=1000, end_release_time=end_time, substance= subs, units='kg') for idx in range(0, len(cont_coord)): model.spills += point_line_release_spill( num_elements=500, start_position=(cont_coord[idx][0], cont_coord[idx][1], 0.0), release_time=start_time, end_release_time=start_time + timedelta(days=1), amount=500, substance=subs, units='kg') #shp_file = os.path.join(base_dir, 'surface_concentration') #scripting.remove_netcdf(shp_file + ".zip") #model.outputters += ShapeOutput(shp_file, # zip_output=False, # surface_conc="kde", # ) print('adding movers:') print('adding a RandomMover:') model.movers += RandomMover(diffusion_coef=10000) print('adding a current mover:') # # this is HYCOM currents curr_file = get_datafile(os.path.join(base_dir, 'currents.nc')) model.movers += GridCurrentMover(curr_file, num_method='Euler') print('adding a grid wind mover:') wind_file = get_datafile(os.path.join(base_dir, 'wind.nc')) #topology_file = get_datafile(os.path.join(base_dir, 'WindSpeedDirSubsetTop.dat')) #w_mover = GridWindMover(wind_file, topology_file) w_mover = GridWindMover(wind_file) w_mover.uncertain_speed_scale = 1 w_mover.uncertain_angle_scale = 0.2 # default is .4 w_mover.wind_scale = 2 model.movers += w_mover print('adding outputters') renderer = Renderer(mapfile, images_dir, image_size=(900, 600), output_timestep=timestep, draw_ontop='forecast') #set the viewport to zoom in on the map: #renderer.viewport = ((-37, -11), (-34, -8)) #alagoas renderer.viewport = ((-36, -10), (-30, 5)) model.outputters += renderer netcdf_file = os.path.join(base_dir, 'contigua.nc') scripting.remove_netcdf(netcdf_file) model.outputters += NetCDFOutput(netcdf_file, which_data='standard', surface_conc='kde') return model
def make_model(images_dir=os.path.join(base_dir, 'images')): print 'initializing the model' start_time = datetime(2012, 10, 25, 0, 1) # start_time = datetime(2015, 12, 18, 06, 01) # 1 day of data in file # 1/2 hr in seconds model = Model(start_time=start_time, duration=timedelta(hours=2), time_step=900) mapfile = get_datafile(os.path.join(base_dir, 'nyharbor.bna')) print 'adding the map' '''TODO: sort out MapFromBna's map_bounds parameter... it does nothing right now, and the spill is out of bounds''' model.map = MapFromBNA(mapfile, refloat_halflife=0.0) # 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=(1024, 768)) # renderer.viewport = ((-73.5, 40.5), (-73.1, 40.75)) # renderer.viewport = ((-122.9, 45.6), (-122.6, 46.0)) print 'adding outputters' model.outputters += renderer netcdf_file = os.path.join(base_dir, 'script_ny_plume.nc') scripting.remove_netcdf(netcdf_file) model.outputters += NetCDFOutput(netcdf_file, which_data='all') print 'adding two spills' # Break the spill into two spills, first with the larger droplets # and second with the smaller droplets. # Split the total spill volume (100 m^3) to have most # in the larger droplet spill. # Smaller droplets start at a lower depth than larger end_time = start_time + model.duration # wd = WeibullDistribution(alpha=1.8, # lambda_=.00456, # min_=.0002) # 200 micron min # # spill = subsurface_plume_spill(num_elements=10, # start_position=(-74.15, # 40.5, # 7.2), # release_time=start_time, # distribution=wd, # amount=90, # default volume_units=m^3 # units='m^3', # end_release_time=end_time, # density=600) # # model.spills += spill # wd = WeibullDistribution(alpha=1.8, # lambda_=.00456, # max_=.0002) # 200 micron max oil_name = 'ALASKA NORTH SLOPE (MIDDLE PIPELINE, 1997)' wd = UniformDistribution(low=.0002, high=.0002) spill = point_line_release_spill(num_elements=10, amount=90, units='m^3', start_position=(-74.15, 40.5, 7.2), release_time=start_time, substance = GnomeOil(oil_name,initializers=plume_initializers(distribution=wd)) #element_type=plume(distribution=wd, #substance_name='ALASKA NORTH SLOPE (MIDDLE PIPELINE, 1997)') ) model.spills += spill print 'adding a RandomMover:' model.movers += RandomMover(diffusion_coef=50000) print 'adding a RiseVelocityMover:' model.movers += RiseVelocityMover() print 'adding a RandomMover3D:' # model.movers += RandomMover3D(vertical_diffusion_coef_above_ml=5, # vertical_diffusion_coef_below_ml=.11, # mixed_layer_depth=10) # the url is broken, update and include the following four lines # url = ('http://geoport.whoi.edu/thredds/dodsC/clay/usgs/users/jcwarner/Projects/Sandy/triple_nest/00_dir_NYB05.ncml') # gc = GridCurrent.from_netCDF(url) # u_mover = PyCurrentMover(gc, default_num_method='RK2') # model.movers += u_mover # print 'adding a wind mover:' # series = np.zeros((2, ), dtype=gnome.basic_types.datetime_value_2d) # series[0] = (start_time, (30, 90)) # series[1] = (start_time + timedelta(hours=23), (30, 90)) # wind = Wind(timeseries=series, units='knot') # # default is .4 radians # w_mover = gnome.movers.WindMover(wind, uncertain_angle_scale=0) # # model.movers += w_mover print 'adding a simple mover:' # s_mover = SimpleMover(velocity=(0.0, -.3, 0.0)) # model.movers += s_mover return model
def test_eq(self): sub1 = GnomeOil(u'oil_ans_mp') sub2 = GnomeOil(u'oil_ans_mp') assert sub1 == sub2 sub3 = GnomeOil(u'oil_ans_mp', windage_range=(0.05, 0.07)) assert sub1 != sub3
def make_model(images_dir=os.path.join(base_dir, 'images2')): print('initializing the model') start_time = datetime(int(sys.argv[1]), int(sys.argv[2]), int(sys.argv[3]), int(sys.argv[4]), int(sys.argv[5])) mapfile = get_datafile(os.path.join(base_dir, './brazil-coast.bna')) gnome_map = MapFromBNA(mapfile, refloat_halflife=6) # hours # # the image output renderer # global renderer #duration = timedelta(minutes=5) #timestep = timedelta(minutes=5) duration = timedelta(minutes=5) timestep = timedelta(minutes=5) endtime = start_time + duration steps = duration.total_seconds() / timestep.total_seconds() print("Total step: %.4i " % (steps)) model = Model(start_time=start_time, duration=duration, time_step=timestep, map=gnome_map, uncertain=False, cache_enabled=False) oil_name = 'GENERIC MEDIUM CRUDE' wd = UniformDistribution(low=.0002, high=.0002) subs = GnomeOil(oil_name, initializers=plume_initializers(distribution=wd)) #print 'adding a spill' #spill = point_line_release_spill(num_elements=122, # start_position=(-35.14, # -9.40, 0.0), # release_time=start_time) #model.spills += spill #spill2 = spatial_release_spill(-35.14,-9.40, 0.0, start_time) #model.spills += spill2 #print 'load nc' #netcdf_file = os.path.join(base_dir, 'maceio.nc') #relnc = InitElemsFromFile(netcdf_file,release_time=start_time) #relnc = InitElemsFromFile(netcdf_file,index=5) #spillnc = Spill(release=relnc) #print spillnc.release.num_elements #print spillnc.release.name #print spillnc.substance #print relnc._init_data['age'] #print relnc.release_time #model.spills += spillnc #model._load_spill_data() #for sc in model.spills.items(): # sc.prepare_for_model_run() #print(relnc.num_elements) #print(relnc.num_released) # add particles - it works print('adding particles') # Persistent oil spill in contiguous zone border if int(sys.argv[6]) == 1: release = release_from_splot_data(start_time, 'contiguous.txt') print("Adding new particles") model.spills += Spill(release=release, substance=subs) # Particles from previows simulation step try: f = open('step.txt') f.close() release2 = release_from_splot_data(start_time, 'step.txt') model.spills += Spill(release=release2, substance=subs) except IOError: print('No previous step, using only contiguous.txt') #assert rel.num_elements == exp_num_elems #assert len(rel.start_position) == exp_num_elems #cumsum = np.cumsum(exp) #for ix in xrange(len(cumsum) - 1): # assert np.all(rel.start_position[cumsum[ix]] == # rel.start_position[cumsum[ix]:cumsum[ix + 1]]) #assert np.all(rel.start_position[0] == rel.start_position[:cumsum[0]]) #spnc = Spill(release=None) #spnc.release = relnc print('adding a RandomMover:') #model.movers += RandomMover(diffusion_coef=10000, uncertain_factor=2) model.movers += RandomMover(diffusion_coef=10000) print('adding a current mover:') # # this is HYCOM currents curr_file = get_datafile(os.path.join(base_dir, 'corrente15a28de09.nc')) model.movers += GridCurrentMover(curr_file, num_method='Euler') print('adding a grid wind mover:') wind_file = get_datafile(os.path.join(base_dir, 'vento15a28de09.nc')) #topology_file = get_datafile(os.path.join(base_dir, 'WindSpeedDirSubsetTop.dat')) #w_mover = GridWindMover(wind_file, topology_file) w_mover = GridWindMover(wind_file) w_mover.uncertain_speed_scale = 1 w_mover.uncertain_angle_scale = 0.2 # default is .4 w_mover.wind_scale = 2 model.movers += w_mover print('adding outputters') renderer = Renderer(mapfile, images_dir, image_size=(900, 600), output_timestep=timestep, draw_ontop='forecast') #set the viewport to zoom in on the map: #renderer.viewport = ((-37, -11), (-34, -8)) #alagoas renderer.viewport = ((-55, -34), (-30, 5)) #1/4 N alagoas model.outputters += renderer netcdf_file = os.path.join(base_dir, 'step.nc') scripting.remove_netcdf(netcdf_file) model.outputters += NetCDFOutput(netcdf_file, which_data='standard', surface_conc='kde') return model