class TestModels(unittest.TestCase): """Tests for OpenDrift models""" def test_seed(self): """Test seeding""" self.o = OpenOil() self.fake_eddy = reader_ArtificialOceanEddy.Reader(2, 62) self.fake_eddy.start_time = datetime(2015, 1, 1) self.o.add_reader([self.fake_eddy]) self.o.seed_elements(lon=4, lat=60, number=100, time=self.fake_eddy.start_time) self.assertEqual(len(self.o.elements), 0) self.assertEqual(len(self.o.elements_deactivated), 0) self.assertEqual(len(self.o.elements_scheduled), 100) def test_windblow(self): o = WindBlow(loglevel=0) reader_arome = reader_netCDF_CF_generic.Reader( o.test_data_folder() + '2Feb2016_Nordic_sigma_3d/AROME_MetCoOp_00_DEF.nc_20160202_subset') o.add_reader([reader_arome]) lat = 67.711251 lon = 13.556971 # Lofoten o.seed_elements(lon, lat, radius=5000, number=1000, time=reader_arome.start_time) o.run(steps=48 * 4, time_step=900) self.assertAlmostEqual(o.elements.lon.max(), 17.54, 2)
def test_seed(self): """Test seeding""" self.o = OpenOil() self.fake_eddy = reader_ArtificialOceanEddy.Reader(2, 62) self.fake_eddy.start_time = datetime(2015, 1, 1) self.o.add_reader([self.fake_eddy]) self.o.seed_elements(lon=4, lat=60, number=100, time=self.fake_eddy.start_time) self.assertEqual(len(self.o.elements), 0) self.assertEqual(len(self.o.elements_deactivated), 0) self.assertEqual(len(self.o.elements_scheduled), 100)
def test_openoil_today(self): o = OpenOil(loglevel=0) o.add_readers_from_file(o.test_data_folder() + '../../opendrift/scripts/data_sources.txt') o.seed_elements(lon=14, lat=67.85, number=100, radius=1000, time=datetime.now()) o.run(steps=15) print(o) self.assertEqual(o.steps_calculation, 15)
def test_openoil_global_one_month_ago(self): o = OpenOil(loglevel=0) o.add_readers_from_file(o.test_data_folder() + '../../opendrift/scripts/data_sources.txt') o.seed_elements(lon=50, lat=29, number=100, radius=1000, time=datetime.now() - timedelta(days=30)) o.run(steps=15) print(o) self.assertEqual(o.steps_calculation, 15)
def set_model(self, model): if model == 'OpenOil': self.categoryLabel['text'] = 'Oil type' self.oljetype.set('') self.categorydrop['menu'].delete(0, 'end') self.o = OpenOil() for cat in self.o.oiltypes: self.categorydrop['menu'].add_command(label=cat, command=tk._setit( self.oljetype, cat)) self.oljetype.set(self.o.oiltypes[0]) if model == 'Leeway': self.categoryLabel['text'] = 'Object type' self.oljetype.set('') self.categorydrop['menu'].delete(0, 'end') self.o = Leeway() self.leewaycategories = [ self.o.leewayprop[c]['Description'].strip().replace('>', '') for c in self.o.leewayprop ] for cat in self.leewaycategories: self.categorydrop['menu'].add_command(label=cat, command=tk._setit( self.oljetype, cat)) self.oljetype.set(self.leewaycategories[0])
def test_constant_reader(self): o = OpenOil(loglevel=0) cw = reader_constant.Reader({'x_wind':5, 'y_wind': 6}) cc = reader_constant.Reader({'x_sea_water_velocity':0, 'y_sea_water_velocity': .2}) cs = reader_constant.Reader({'sea_water_temperature': 278}) r = reader_netCDF_CF_generic.Reader(o.test_data_folder() + '16Nov2015_NorKyst_z_surface/norkyst800_subset_16Nov2015.nc') o.add_reader([cw, cc, r]) # TODO: should check why adding constant reader with # sea_water_temperature gives Deprecated warning #o.add_reader([cw, cc, cs, r]) o.seed_elements(lon=4, lat=60, time=r.start_time, number=5) o.run(steps=3)
def test_get_openoil_list(test_data): oils = Path(test_data) / 'generated' / 'oil_list_full.txt' with open(oils, 'r') as fd: oils = [o.strip() for o in fd.readlines()] o = OpenOil() assert set(o.oiltypes) >= set(oils)
def test_get_openoil_list_norway(test_data): oils = Path(test_data) / 'generated' / 'oil_list_norway.txt' with open(oils, 'r') as fd: oils = [o.strip() for o in fd.readlines()] o = OpenOil(location='NORWAY') print(set(oils) - set(o.oiltypes)) assert set(o.oiltypes) >= set(oils)
class TestModels(unittest.TestCase): """Tests for OpenDrift models""" def test_seed(self): """Test seeding""" self.o = OpenOil() self.fake_eddy = reader_ArtificialOceanEddy.Reader(2, 62) self.fake_eddy.start_time = datetime(2015, 1, 1) self.o.add_reader([self.fake_eddy]) self.o.seed_elements(lon=4, lat=60, number=100, time=self.fake_eddy.start_time) self.assertEqual(len(self.o.elements), 0) self.assertEqual(len(self.o.elements_deactivated), 0) self.assertEqual(len(self.o.elements_scheduled), 100) def test_windblow(self): o = WindBlow(loglevel=0) reader_arome = reader_netCDF_CF_generic.Reader(o.test_data_folder() + '2Feb2016_Nordic_sigma_3d/AROME_MetCoOp_00_DEF.nc_20160202_subset') o.add_reader([reader_arome]) lat = 67.711251; lon = 13.556971 # Lofoten o.seed_elements(lon, lat, radius=5000, number=1000, time=reader_arome.start_time) o.run(steps=48*4, time_step=900) self.assertAlmostEqual(o.elements.lon.max(), 17.54, 2)
def test_seed_polygon(self): o = OpenOil(loglevel=0) number = 10 lonvec = np.array([2, 3, 3, 2]) latvec = np.array([60, 60, 61, 61]) time=datetime(2015, 1, 1, 12, 5, 17) o.set_config('seed:oil_type', 'HEIDRUN') o.seed_within_polygon(lonvec, latvec, number=number, time=time, wind_drift_factor=.09) self.assertEqual(o.num_elements_scheduled(), number) self.assertEqual(o.elements_scheduled_time[0], time) self.assertAlmostEqual(o.elements_scheduled.wind_drift_factor, .09) # Check that oil type is taken fom config self.assertEqual(o.oil_name, 'HEIDRUN')
def test_seed_below_seafloor_deactivating(self): o = OpenOil(loglevel=50) reader_norkyst = reader_netCDF_CF_generic.Reader( o.test_data_folder() + '14Jan2016_NorKyst_z_3d/NorKyst-800m_ZDEPTHS_his_00_3Dsubset.nc') o.add_reader([reader_norkyst]) o.set_config('environment:fallback:land_binary_mask', 0) o.set_config('environment:fallback:x_wind', 0) o.set_config('environment:fallback:y_wind', 0) o.set_config('environment:fallback:x_sea_water_velocity', 0) o.set_config('environment:fallback:y_sea_water_velocity', 0) lon = 4.5 lat = 62.0 o.set_config('seed:droplet_diameter_min_subsea', 0.0005) o.set_config('seed:droplet_diameter_max_subsea', 0.001) o.seed_elements(lon, lat, z=[-5000, -100], time=reader_norkyst.start_time, density=1000, number=2, oil_type='AASGARD A 2003') o.set_config('general:seafloor_action', 'deactivate') # This time we deactivate o.set_config('drift:vertical_mixing', True) o.set_config('vertical_mixing:timestep', 1) # s o.run(steps=3, time_step=300, time_step_output=300) z, status = o.get_property('z') self.assertEqual(o.num_elements_total(), 2) self.assertEqual(o.num_elements_active(), 1) self.assertEqual(o.num_elements_deactivated(), 1) self.assertAlmostEqual(z[0, 1], -100, 1) # Seeded at seafloor depth self.assertAlmostEqual(z[-1, 1], -81.4, 1) # After some rising
#!/usr/bin/env python """ Cone seeding ===================== """ from datetime import datetime, timedelta from opendrift.readers import reader_netCDF_CF_generic from opendrift.models.openoil import OpenOil o = OpenOil(loglevel=20) # Set loglevel to 0 for debug information #%% # Using live data from Thredds o.add_readers_from_list( ['https://thredds.met.no/thredds/dodsC/sea/norkyst800m/1h/aggregate_be']) #%% # Seed elements along cone, e.g. ship track with # increasing uncertainty in position latstart = 68.988911 lonstart = 16.040701 latend = 69.991446 lonend = 17.760061 time = [datetime.utcnow(), datetime.utcnow() + timedelta(hours=12)] o.seed_cone(lon=[lonstart, lonend], lat=[latstart, latend], oiltype='EKOFISK', radius=[100, 800], number=10000,
#!/usr/bin/env python from datetime import datetime from opendrift.readers import reader_netCDF_CF_generic from opendrift.models.openoil import OpenOil o = OpenOil(loglevel=0) # Set loglevel to 0 for debug information # Arome reader_arome = reader_netCDF_CF_generic.Reader( o.test_data_folder() + '16Nov2015_NorKyst_z_surface/arome_subset_16Nov2015.nc') # Norkyst reader_norkyst = reader_netCDF_CF_generic.Reader( o.test_data_folder() + '16Nov2015_NorKyst_z_surface/norkyst800_subset_16Nov2015.nc') o.add_reader([reader_norkyst, reader_arome]) o.set_config('processes:evaporation', False) ############################################################ # Seed oil particles within contour detected from satellite ############################################################ o.seed_from_gml( o.test_data_folder() + 'radarsat_oil_satellite_observation/RS2_20151116_002619_0127_SCNB_HH_SGF_433012_9730_12182143_Oil.gml', num_elements=2000) ############################################################ # Additional continous point release, lasting 24 hours
def test_seed_below_reader_coverage(self): o = OpenOil(loglevel=20) reader_norkyst = reader_netCDF_CF_generic.Reader( o.test_data_folder() + '14Jan2016_NorKyst_z_3d/NorKyst-800m_ZDEPTHS_his_00_3Dsubset.nc') o.set_config('environment:fallback:land_binary_mask', 0) o.set_config('environment:fallback:x_wind', 0) o.set_config('environment:fallback:y_wind', 0) o.add_reader([reader_norkyst]) lon = 5.0 lat = 64.0 o.set_config('seed:droplet_diameter_min_subsea', 0.0005) o.set_config('seed:droplet_diameter_max_subsea', 0.005) o.seed_elements(lon, lat, z=-350, time=reader_norkyst.start_time, density=1000, oil_type='AASGARD A 2003') #o.set_config('vertical_mixing:TSprofiles', True) o.set_config('drift:vertical_mixing', True) o.set_config('vertical_mixing:timestep', 1) # s o.run(steps=3, time_step=300, time_step_output=300) z, status = o.get_property('z') self.assertAlmostEqual(z[-1, 0], -134.0, 1) # After some rising
#!/usr/bin/env python """ Cone seeding ============= """ from datetime import timedelta from opendrift.readers import reader_netCDF_CF_generic from opendrift.models.openoil import OpenOil o = OpenOil(loglevel=20) # Set loglevel to 0 for debug information # Arome reader_arome = reader_netCDF_CF_generic.Reader(o.test_data_folder() + '16Nov2015_NorKyst_z_surface/arome_subset_16Nov2015.nc') # Norkyst reader_norkyst = reader_netCDF_CF_generic.Reader(o.test_data_folder() + '16Nov2015_NorKyst_z_surface/norkyst800_subset_16Nov2015.nc') o.add_reader([reader_norkyst, reader_arome]) #%% # Seed elements along cone, e.g. ship track with # increasing uncertainty in position time = [reader_arome.start_time, reader_arome.start_time + timedelta(hours=30)] #time = reader_arome.start_time #%% # Seed oil elements at defined position and time
def __init__(self): # Available models self.available_models = opendrift.get_model_names() tk.Tk.__init__(self) ################## # Layout frames ################## self.n = ttk.Notebook(self.master) self.n.grid() self.seed = ttk.Frame(self.n) self.config = ttk.Frame(self.n) self.n.add(self.seed, text='Seeding') self.n.add(self.config, text='Config') # Top self.top = tk.Frame(self.seed, relief=tk.FLAT, pady=25, padx=25) self.top.grid(row=0, column=1, rowspan=1) # Config self.con = tk.Label(self.config, text="\n\nConfiguration\n\n") self.con.grid(row=0, column=1, rowspan=1) # Time start and end self.start_t = tk.Frame(self.seed, relief=tk.FLAT) self.start_t.grid(row=20, column=0, rowspan=1) self.end_t = tk.Frame(self.seed, relief=tk.FLAT) self.end_t.grid(row=30, column=0, rowspan=1) self.start = tk.Frame(self.seed, bg='lightgray', bd=2, relief=tk.SUNKEN, pady=5, padx=5) self.start.grid(row=20, column=1, rowspan=1) self.end = tk.Frame(self.seed, bg='gray', bd=2, relief=tk.SUNKEN, padx=5, pady=5) self.end.grid(row=30, column=1) self.coastline = tk.Frame(self.seed, bd=2, relief=tk.FLAT, padx=5, pady=0) self.coastline.grid(row=40, column=1) self.duration = tk.Frame(self.seed, bd=2, relief=tk.FLAT, padx=5, pady=5) self.duration.grid(row=50, column=1) self.output = tk.Frame(self.seed, bd=2, relief=tk.FLAT, padx=5, pady=0) self.output.grid(row=70, column=0, columnspan=7, sticky='nsew') self.results = tk.Frame(self.seed, bd=2, relief=tk.FLAT, padx=5, pady=0) self.results.grid(row=60, column=7, columnspan=1, sticky='ew') ########################## self.title('OpenDrift') self.o = OpenOil(weathering_model='noaa', location='NORWAY') try: img = ImageTk.PhotoImage(Image.open(self.o.test_data_folder() + '../../docs/opendrift_logo.png')) panel = tk.Label(self.seed, image=img) panel.image = img panel.grid(row=0, column=0) except: pass # Could not display logo ####################################################### tk.Label(self.top, text='Simulation type').grid(row=0, column=0) self.model = tk.StringVar() models = opendrift.get_model_names() self.model.set(models[0]) self.modeldrop = tk.OptionMenu(self.top, self.model, *(models), command=self.set_model) self.modeldrop.grid(row=0, column=1) help_button = tk.Button(self.top, text='Help', command=self.show_help) help_button.grid(row=0, column=2, padx=50) ########## # Release ########## startlabel = tk.Label(self.start_t, text="\n\nStart release\n\n") startlabel.grid(row=0, column=0) tk.Label(self.start, text='Longitude').grid(row=0, column=1) tk.Label(self.start, text='Latitude').grid(row=0, column=0) tk.Label(self.start, text='Radius [m]').grid(row=0, column=2) self.latvar = tk.StringVar() self.lonvar = tk.StringVar() self.radiusvar = tk.StringVar() self.lat = tk.Entry(self.start, textvariable=self.latvar, width=6, justify=tk.RIGHT) self.lon = tk.Entry(self.start, textvariable=self.lonvar, width=6, justify=tk.RIGHT) self.radius = tk.Entry(self.start, width=6, textvariable=self.radiusvar, justify=tk.RIGHT) self.lon.grid(row=10, column=1) self.lon.insert(0, '4.5') self.lat.grid(row=10, column=0) self.lat.insert(0, '60.0') self.radius.grid(row=10, column=2) self.radius.insert(0, '1000') self.lonvar.trace('w', self.copy_position) self.latvar.trace('w', self.copy_position) self.radiusvar.trace('w', self.copy_position) ########## # Time ########## now = datetime.utcnow() tk.Label(self.start, text='Day').grid(row=20, column=0) tk.Label(self.start, text='Month').grid(row=20, column=1) tk.Label(self.start, text='Year').grid(row=20, column=2) tk.Label(self.start, text='Hour').grid(row=20, column=3) tk.Label(self.start, text='Minutes [UTC]').grid(row=20, column=4) self.datevar = tk.StringVar() self.dates = range(1, 32) self.datevar.set(now.day) self.date = tk.OptionMenu(self.start, self.datevar, *self.dates) self.date.grid(row=30, column=0) self.monthvar = tk.StringVar() self.months = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'] self.monthvar.set(self.months[now.month-1]) self.month = tk.OptionMenu(self.start, self.monthvar, *self.months) self.month.grid(row=30, column=1) self.yearvar = tk.StringVar() self.years = range(2015, now.year+2) self.yearvar.set(now.year) self.year = tk.OptionMenu(self.start, self.yearvar, *self.years) self.year.grid(row=30, column=2) self.hourvar = tk.StringVar() self.hours = range(0, 24) self.hourvar.set(now.hour) self.hour = tk.OptionMenu(self.start, self.hourvar, *self.hours) self.hour.grid(row=30, column=3) self.minutevar = tk.StringVar() self.minutes = range(0, 60, 5) self.minutevar.set(now.minute) self.minute = tk.OptionMenu(self.start, self.minutevar, *self.minutes) self.minute.grid(row=30, column=4) self.datevar.trace('w', self.copy_position) self.monthvar.trace('w', self.copy_position) self.yearvar.trace('w', self.copy_position) self.hourvar.trace('w', self.copy_position) self.minutevar.trace('w', self.copy_position) ############### # Release End ############### endlabel = tk.Label(self.end_t, text="\n\nEnd release\n\n") endlabel.grid(row=0, column=0) tk.Label(self.end, text='Longitude', bg='gray').grid(row=0, column=1) tk.Label(self.end, text='Latitude', bg='gray').grid(row=0, column=0) tk.Label(self.end, text='Radius [m]', bg='gray').grid(row=0, column=2) self.elat = tk.Entry(self.end, width=6, justify=tk.RIGHT) self.elon = tk.Entry(self.end, width=6, justify=tk.RIGHT) self.eradius = tk.Entry(self.end, width=6, justify=tk.RIGHT) self.elon.grid(row=10, column=1) self.elon.insert(0, '4.5') self.elat.grid(row=10, column=0) self.elat.insert(0, '60.0') self.eradius.grid(row=10, column=2) self.eradius.insert(0, '1000') ########## # Time ########## now = datetime.utcnow() tk.Label(self.end, text='Day', bg='gray').grid(row=20, column=0) tk.Label(self.end, text='Month', bg='gray').grid(row=20, column=1) tk.Label(self.end, text='Year', bg='gray').grid(row=20, column=2) tk.Label(self.end, text='Hour', bg='gray').grid(row=20, column=3) tk.Label(self.end, text='Minutes [UTC]', bg='gray').grid(row=20, column=4) self.edatevar = tk.StringVar() self.edates = range(1, 32) self.edatevar.set(now.day) self.edate = tk.OptionMenu(self.end, self.edatevar, *self.edates) self.edate.grid(row=30, column=0) self.emonthvar = tk.StringVar() self.emonthvar.set(self.months[now.month-1]) self.emonth = tk.OptionMenu(self.end, self.emonthvar, *self.months) self.emonth.grid(row=30, column=1) self.eyearvar = tk.StringVar() self.eyears = range(2015, now.year+2) self.eyearvar.set(now.year) self.eyear = tk.OptionMenu(self.end, self.eyearvar, *self.eyears) self.eyear.grid(row=30, column=2) self.ehourvar = tk.StringVar() self.ehours = range(0, 24) self.ehourvar.set(now.hour) self.ehour = tk.OptionMenu(self.end, self.ehourvar, *self.ehours) self.ehour.grid(row=30, column=3) self.eminutevar = tk.StringVar() self.eminutes = range(0, 60, 5) self.eminutevar.set(now.minute) self.eminute = tk.OptionMenu(self.end, self.eminutevar, *self.eminutes) self.eminute.grid(row=30, column=4) self.eyear.config(bg='gray') self.emonth.config(bg='gray') self.edate.config(bg='gray') self.ehour.config(bg='gray') self.eminute.config(bg='gray') # Check seeding check_seed = tk.Button(self.end_t, text='Check seeding', command=self.check_seeding) check_seed.grid(row=10, column=0, padx=0) ####################### # Simulation duration ####################### #tk.Label(self.coastline, text='Coastline resolution ').grid( # row=40, column=1) #self.mapresvar = tk.StringVar() #self.mapres = tk.OptionMenu(self.coastline, self.mapresvar, # *['full', 'high']) #self.mapres.grid(row=40, column=2) #self.mapresvar.set('high') tk.Label(self.duration, text='Run simulation ').grid(row=50, column=0) self.durationhours = tk.Entry(self.duration, width=3, justify=tk.RIGHT) self.durationhours.grid(row=50, column=1) self.durationhours.insert(0, 12) tk.Label(self.duration, text=' hours ').grid(row=50, column=2) self.directionvar = tk.StringVar() self.directionvar.set('forwards') self.direction = tk.OptionMenu(self.duration, self.directionvar, 'forwards', 'backwards') self.direction.grid(row=50, column=3) tk.Label(self.duration, text=' in time ').grid(row=50, column=4) ############## # Output box ############## self.text = tk.Text(self.output, wrap="word", height=18) self.text.grid(row=60, columnspan=6, sticky='nsw') self.text.tag_configure("stderr", foreground="#b22222") sys.stdout = TextRedirector(self.text, "stdout") sys.stderr = TextRedirector(self.text, "stderr") s = tk.Scrollbar(self) s.grid(row=60, column=6, sticky='ns') s.config(command=self.text.yview) self.text.config(yscrollcommand=s.set) # Diana self.dianadir = '/vol/vvfelles/opendrift/output/' if os.path.exists(self.dianadir): self.has_diana = True print('Diana is available!') self.outputdir = '/vol/vvfelles/opendrift/output_native/' startbutton = 'PEIS PAO' else: self.has_diana = False startbutton = 'START' ############## # Initialise ############## #o = OpenOil() self.set_model(self.available_models[0]) ########## # RUN ########## tk.Button(self.seed, text=startbutton, bg='green', command=self.run_opendrift).grid(row=80, column=1, sticky=tk.W, pady=4)
#!/usr/bin/env python from datetime import datetime, timedelta import numpy as np #from opendrift.models.oceandrift import OceanDrift from opendrift.models.openoil import OpenOil #o = OceanDrift(loglevel=50) o = OpenOil(loglevel=50) o.set_config('processes:diffusion', False) # We do not care about landmask or current for this seeding demonstration, # so we simple specify fallback_values instead of adding any readers o.fallback_values['land_binary_mask'] = 0 o.fallback_values['x_sea_water_velocity'] = 0 o.fallback_values['y_sea_water_velocity'] = 0 time=datetime(2016, 1, 20, 12, 30, 0) print '\n' + '='*70 print 'Seeding a single element at a point:' print 'o.seed_elements(lon=4, lat=60, time=time)' print '='*70 o.seed_elements(lon=4, lat=60, time=time) o.run(steps=1) o.plot(buffer=1) print '\n' + '='*70
#!/usr/bin/env python """ Generic example =============== """ from datetime import datetime, timedelta from opendrift.readers import reader_netCDF_CF_generic from opendrift.models.openoil import OpenOil o = OpenOil(loglevel=0) # Set loglevel to 0 for debug information # Arome atmospheric model reader_arome = reader_netCDF_CF_generic.Reader(o.test_data_folder() + '16Nov2015_NorKyst_z_surface/arome_subset_16Nov2015.nc') # Norkyst ocean model reader_norkyst = reader_netCDF_CF_generic.Reader(o.test_data_folder() + '16Nov2015_NorKyst_z_surface/norkyst800_subset_16Nov2015.nc') # Uncomment to use live data from thredds #reader_arome = reader_netCDF_CF_generic.Reader('http://thredds.met.no/thredds/dodsC/meps25files/meps_det_extracted_2_5km_latest.nc') #reader_norkyst = reader_netCDF_CF_generic.Reader('http://thredds.met.no/thredds/dodsC/sea/norkyst800m/1h/aggregate_be') o.add_reader([reader_norkyst, reader_arome]) #%% # Seeding some particles #time = datetime(2015, 9, 22, 6, 0, 0) time = [reader_arome.start_time, reader_arome.start_time + timedelta(hours=30)] #time = reader_arome.start_time
#!/usr/bin/env python from datetime import timedelta from opendrift.readers import reader_basemap_landmask from opendrift.readers import reader_netCDF_CF_generic from opendrift.models.openoil import OpenOil o = OpenOil(loglevel=20) # Set loglevel to 0 for debug information # Arome reader_arome = reader_netCDF_CF_generic.Reader(o.test_data_folder() + '16Nov2015_NorKyst_z_surface/arome_subset_16Nov2015.nc') #reader_arome = reader_netCDF_CF_generic.Reader('http://thredds.met.no/thredds/dodsC/arome25/arome_metcoop_default2_5km_latest.nc') # Norkyst reader_norkyst = reader_netCDF_CF_generic.Reader(o.test_data_folder() + '16Nov2015_NorKyst_z_surface/norkyst800_subset_16Nov2015.nc') #reader_norkyst = reader_netCDF_CF_generic.Reader('http://thredds.met.no/thredds/dodsC/sea/norkyst800m/1h/aggregate_be') # Landmask (Basemap) reader_basemap = reader_basemap_landmask.Reader(llcrnrlon=3, llcrnrlat=59.5, urcrnrlon=7, urcrnrlat=62, resolution='h', projection='merc') o.add_reader([reader_basemap, reader_norkyst, reader_arome]) # Seeding some particles lon = 4.2; lat = 60.0; # Outside Bergen time = [reader_arome.start_time, reader_arome.start_time + timedelta(hours=30)]
#!/usr/bin/env python from datetime import timedelta from opendrift.readers import reader_basemap_landmask from opendrift.readers import reader_netCDF_CF_generic from opendrift.models.openoil import OpenOil o = OpenOil(loglevel=0) # Set loglevel to 0 for debug information # Using live data from Thredds reader_arome = reader_netCDF_CF_generic.Reader('http://thredds.met.no/thredds/dodsC/meps25files/meps_det_extracted_2_5km_latest.nc') reader_norkyst = reader_netCDF_CF_generic.Reader('http://thredds.met.no/thredds/dodsC/sea/norkyst800m/1h/aggregate_be') o.add_reader([reader_norkyst, reader_arome]) # Seed elements along cone, e.g. ship track with # increasing uncertainty in position latstart = 68.988911 lonstart = 16.040701 #latstart = 69.477754 #lonstart = 16.441702 latend = 69.991446 lonend = 17.760061 lon = [lonstart, lonend]; lat = [latstart, latend]; # Outside Tromso time = [reader_arome.start_time, reader_arome.start_time + timedelta(hours=30)] o.seed_elements(lon, lat, radius=[100, 500], number=10000, time=time, cone=True)
#!/usr/bin/env python from datetime import timedelta from opendrift.readers import reader_basemap_landmask from opendrift.readers import reader_netCDF_CF_generic from opendrift.models.openoil import OpenOil o = OpenOil(loglevel=0) # Set loglevel to 0 for debug information # Arome #reader_arome = reader_netCDF_CF_generic.Reader('http://thredds.met.no/thredds/dodsC/arome25/arome_metcoop_default2_5km_latest.nc') reader_arome = reader_netCDF_CF_generic.Reader(o.test_data_folder() + '16Nov2015_NorKyst_z_surface/arome_subset_16Nov2015.nc') # Norkyst #reader_norkyst = reader_netCDF_CF_generic.Reader('http://thredds.met.no/thredds/dodsC/sea/norkyst800m/1h/aggregate_be') reader_norkyst = reader_netCDF_CF_generic.Reader(o.test_data_folder() + '16Nov2015_NorKyst_z_surface/norkyst800_subset_16Nov2015.nc') # Landmask (Basemap) reader_basemap = reader_basemap_landmask.Reader(llcrnrlon=2, llcrnrlat=59, urcrnrlon=6, urcrnrlat=62, resolution='i', projection='merc') o.add_reader([reader_basemap, reader_norkyst, reader_arome]) # Seeding some particles lon = [3.6, 5.1]; lat = [61., 59.6]; # Outside Bergen # Seed elements along cone, e.g. ship track with
#!/usr/bin/env python from datetime import datetime, timedelta from opendrift.readers import reader_basemap_landmask from opendrift.readers import reader_netCDF_CF_generic from opendrift.models.openoil import OpenOil o = OpenOil(loglevel=0) # Set loglevel to 0 for debug information # HYCOM #reader_hycom = reader_netCDF_CF_generic.Reader('http://tds.hycom.org/thredds/dodsC/GLBu0.08/expt_19.1/2010/3hrly') #print reader_hycom reader_globcurrent = reader_netCDF_CF_generic.Reader('http://tds0.ifremer.fr/thredds/dodsC/CLS-L4-CUREUL_HS-ALT_SUM-V02.0_FULL_TIME_SERIE') # Landmask (Basemap) reader_basemap = reader_basemap_landmask.Reader(llcrnrlon=100, llcrnrlat=5, urcrnrlon=120, urcrnrlat=15, resolution='h') # OceanWind try: reader_oceanwind = reader_netCDF_CF_generic.Reader( 'http://www.ncdc.noaa.gov/thredds/dodsC/oceanwinds6hr') print reader_oceanwind o.add_reader([reader_globcurrent, reader_oceanwind, reader_basemap]) except: o.add_reader([reader_globcurrent, reader_basemap]) # Seed some particles
class TestModels(unittest.TestCase): """Tests for OpenDrift models""" def test_seed(self): """Test seeding""" self.o = OpenOil() self.fake_eddy = reader_ArtificialOceanEddy.Reader(2, 62) self.fake_eddy.start_time = datetime(2015, 1, 1) self.o.add_reader([self.fake_eddy]) self.o.seed_elements(lon=4, lat=60, number=100, time=self.fake_eddy.start_time) self.assertEqual(len(self.o.elements), 0) self.assertEqual(len(self.o.elements_deactivated), 0) self.assertEqual(len(self.o.elements_scheduled), 100) def test_windblow(self): o = WindBlow(loglevel=30) reader_arome = reader_netCDF_CF_generic.Reader(o.test_data_folder() + '2Feb2016_Nordic_sigma_3d/AROME_MetCoOp_00_DEF.nc_20160202_subset') o.add_reader([reader_arome]) lat = 67.711251; lon = 13.556971 # Lofoten o.seed_elements(lon, lat, radius=5000, number=1000, time=reader_arome.start_time) o.run(steps=24, time_step=3600) self.assertAlmostEqual(o.elements.lon.max(), 16.167, 2) def test_shipdrift(self): """Sintef case study""" s = ShipDrift(loglevel=50) c = reader_constant.Reader({ 'sea_surface_wave_significant_height': 5, 'sea_surface_wave_mean_period_from_variance_spectral_density_second_frequency_moment': 11, 'x_wind': 14.14213562, 'y_wind': -14.14213562, 'x_sea_water_velocity': 0.05656854249, 'y_sea_water_velocity': -0.05656854249}) s.fallback_values['land_binary_mask'] = 0 s.add_reader(c) s.seed_elements(lon=2, lat=60, time=datetime.now(), number=1, length=80, beam=14, height=25, draft=5) s.run(time_step=600, duration=timedelta(hours=4)) self.assertAlmostEqual(s.elements.lon, 2.25267706) self.assertAlmostEqual(s.elements.lat, 59.87694775) def test_shipdrift_backwards(self): """Case above, reversed""" s = ShipDrift(loglevel=50) c = reader_constant.Reader({ 'sea_surface_wave_significant_height': 5, 'sea_surface_wave_mean_period_from_variance_spectral_density_second_frequency_moment': 11, 'x_wind': 14.14213562, 'y_wind': -14.14213562, 'x_sea_water_velocity': 0.05656854249, 'y_sea_water_velocity': -0.05656854249}) s.fallback_values['land_binary_mask'] = 0 s.add_reader(c) s.seed_elements(lon=2.25267706, lat=59.87694775, time=datetime.now(), number=1, length=80, beam=14, height=25, draft=5) s.run(time_step=-600, duration=timedelta(hours=4)) self.assertAlmostEqual(s.elements.lon, 2.0, 3) self.assertAlmostEqual(s.elements.lat, 60, 3)
#!/usr/bin/env python from datetime import timedelta from opendrift.readers import reader_basemap_landmask from opendrift.readers import reader_netCDF_CF_generic from opendrift.models.openoil import OpenOil o = OpenOil(loglevel=20) # Set loglevel to 0 for debug information # Arome reader_arome = reader_netCDF_CF_generic.Reader(o.test_data_folder() + '16Nov2015_NorKyst_z_surface/arome_subset_16Nov2015.nc') # Norkyst reader_norkyst = reader_netCDF_CF_generic.Reader(o.test_data_folder() + '16Nov2015_NorKyst_z_surface/norkyst800_subset_16Nov2015.nc') # Landmask (Basemap) reader_basemap = reader_basemap_landmask.Reader(llcrnrlon=3, llcrnrlat=59.5, urcrnrlon=7, urcrnrlat=62, resolution='h', projection='merc') o.add_reader([reader_basemap, reader_norkyst, reader_arome]) # Seeding some particles lon = 4.3; lat = 60.0; # Outside Bergen time = [reader_arome.start_time, reader_arome.start_time + timedelta(hours=30)] # Seed oil elements at defined position and time
#!/usr/bin/env python from datetime import datetime, timedelta from opendrift.readers import reader_netCDF_CF_generic from opendrift.models.openoil import OpenOil o = OpenOil(loglevel=0) o.max_speed = 1 # Nordc4 reader_arctic = reader_netCDF_CF_generic.Reader(o.test_data_folder() + '2Feb2016_Nordic_sigma_3d/Arctic20_1to5Feb_2016.nc') reader_arctic.interpolation = 'linearND' #o.add_reader([reader_basemap, reader_arctic]) #o.add_reader([reader_arctic, reader_basemap]) o.add_reader([reader_arctic]) # Seeding some particles lon = 26.4; lat = 77.3; # Spitzbergen #time = datetime(2015, 9, 22, 6, 0, 0) #time = [reader_nordic4.start_time, # reader_nordic4.start_time + timedelta(hours=30)] time = reader_arctic.start_time # Seed oil elements at defined position and time o.seed_elements(lon, lat, radius=7000, number=3000, time=time) o.fallback_values['y_wind'] = 4 # Adding some northwards wind print o
def test_oilbudget(self): for windspeed in [3, 8]: for dispersion in [True, False]: o = OpenOil(loglevel=30, weathering_model='noaa') o.set_config('environment:fallback:x_wind', windspeed) o.set_config('environment:fallback:y_wind', 0) o.set_config('environment:fallback:x_sea_water_velocity', 0) o.set_config('environment:fallback:y_sea_water_velocity', 0) o.set_config('environment:fallback:land_binary_mask', 0) o.set_config('seed:oil_type', 'SIRTICA') o.set_config('processes:dispersion', dispersion) seed_hours = 3 m3_per_hour = 200 o.set_config('seed:m3_per_hour', m3_per_hour) o.seed_elements( lon=0, lat=60, number=100, #m3_per_hour=m3_per_hour, time=[ datetime.now(), datetime.now() + timedelta(hours=seed_hours) ]) o.run(duration=timedelta(hours=4)) b = o.get_oil_budget() density = o.get_property('density')[0][0, 0] volume = b['mass_total'] / density self.assertAlmostEqual(volume[-1], seed_hours * m3_per_hour, 2) if dispersion is True: disp = 'dispersion' else: disp = 'nodispersion' filename = 'oilbudget_%s_%s.png' % (windspeed, disp) o.plot_oil_budget(filename=filename) os.remove(filename)
def __init__(self): tk.Tk.__init__(self) self.title('OpenDrift') o = OpenOil() try: img = ImageTk.PhotoImage(Image.open(o.test_data_folder() + '../../docs/opendrift_logo.png')) panel = tk.Label(self.master, image=img) panel.image = img panel.grid(row=0, column=0) except: pass # Could not display logo self.top = tk.Frame(self.master, relief=tk.FLAT, pady=25, padx=25) self.top.grid(row=0, column=1, rowspan=1) tk.Label(self.top, text='Simulation type').grid(row=0, column=0) self.model = tk.StringVar() models = ['OpenOil', 'Leeway'] self.model.set(models[0]) self.modeldrop = tk.OptionMenu(self.top, self.model, *(models), command=self.set_model) self.modeldrop.grid(row=0, column=1) self.categoryLabel = tk.Label(self.master, text='Oil type') self.categoryLabel.grid(row=1, column=0) oljetyper = o.oiltypes self.oljetype = tk.StringVar() self.oljetype.set(oljetyper[0]) self.categorydrop = tk.OptionMenu(self.master, self.oljetype, *oljetyper) self.categorydrop.grid(row=1, column=1) ########## # Release ########## self.start_t = tk.Frame(self.master, relief=tk.FLAT) self.start_t.grid(row=2, column=0, rowspan=1) startlabel = tk.Label(self.start_t, text="\n\nStart release\n\n") startlabel.grid(row=0, column=0) self.start = tk.Frame(self.master, bg='lightgray', bd=2, relief=tk.SUNKEN, pady=5, padx=5) self.start.grid(row=2, column=1, rowspan=1) tk.Label(self.start, text='Longitude').grid(row=0, column=0) tk.Label(self.start, text='Latitude').grid(row=0, column=1) tk.Label(self.start, text='Radius [m]').grid(row=0, column=2) self.lon = tk.Entry(self.start, width=6, justify=tk.RIGHT) self.lat = tk.Entry(self.start, width=6, justify=tk.RIGHT) self.radius = tk.Entry(self.start, width=6, justify=tk.RIGHT) self.lon.grid(row=1, column=0) self.lon.insert(0, '4.5') self.lat.grid(row=1, column=1) self.lat.insert(0, '60.0') self.radius.grid(row=1, column=2) self.radius.insert(0, '5000') ########## # Time ########## now = datetime.now() tk.Label(self.start, text='Day').grid(row=2, column=0) tk.Label(self.start, text='Month').grid(row=2, column=1) tk.Label(self.start, text='Year').grid(row=2, column=2) tk.Label(self.start, text='Hour').grid(row=2, column=3) tk.Label(self.start, text='Minutes [UTC]').grid(row=2, column=4) self.datevar = tk.StringVar() self.dates = range(1, 32) self.datevar.set(now.day) self.date = tk.OptionMenu(self.start, self.datevar, *self.dates) self.date.grid(row=3, column=0) self.monthvar = tk.StringVar() self.months = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'] self.monthvar.set(self.months[now.month-1]) self.month = tk.OptionMenu(self.start, self.monthvar, *self.months) self.month.grid(row=3, column=1) self.yearvar = tk.StringVar() self.years = range(2015, 2017) self.yearvar.set(now.year) self.year = tk.OptionMenu(self.start, self.yearvar, *self.years) self.year.grid(row=3, column=2) self.hourvar = tk.StringVar() self.hours = range(0, 24) self.hourvar.set(now.hour) self.hour = tk.OptionMenu(self.start, self.hourvar, *self.hours) self.hour.grid(row=3, column=3) self.minutevar = tk.StringVar() self.minutes = range(0, 60, 5) self.minutevar.set(now.minute) self.minute = tk.OptionMenu(self.start, self.minutevar, *self.minutes) self.minute.grid(row=3, column=4) ############### # Release End ############### self.end_t = tk.Frame(self.master, relief=tk.FLAT) endlabel = tk.Label(self.end_t, text="\n\nEnd release\n\n") endlabel.grid(row=0, column=0) self.end_t.grid(row=3, column=0, rowspan=1) self.end = tk.Frame(self.master, bg='gray', bd=2, relief=tk.SUNKEN, padx=5, pady=5) self.end.grid(row=3, column=1) tk.Label(self.end, text='Longitude').grid(row=0, column=0) tk.Label(self.end, text='Latitude').grid(row=0, column=1) tk.Label(self.end, text='Radius [m]').grid(row=0, column=2) self.elon = tk.Entry(self.end, width=6, justify=tk.RIGHT) self.elat = tk.Entry(self.end, width=6, justify=tk.RIGHT) self.eradius = tk.Entry(self.end, width=6, justify=tk.RIGHT) self.elon.grid(row=1, column=0) self.elon.insert(0, '4.5') self.elat.grid(row=1, column=1) self.elat.insert(0, '60.0') self.eradius.grid(row=1, column=2) self.eradius.insert(0, '0') ########## # Time ########## now = datetime.now() tk.Label(self.end, text='Day').grid(row=2, column=0) tk.Label(self.end, text='Month').grid(row=2, column=1) tk.Label(self.end, text='Year').grid(row=2, column=2) tk.Label(self.end, text='Hour').grid(row=2, column=3) tk.Label(self.end, text='Minutes [UTC]').grid(row=2, column=4) self.edatevar = tk.StringVar() self.edates = range(1, 32) self.edatevar.set(now.day) self.edate = tk.OptionMenu(self.end, self.edatevar, *self.edates) self.edate.grid(row=3, column=0) self.emonthvar = tk.StringVar() self.emonthvar.set(self.months[now.month-1]) self.emonth = tk.OptionMenu(self.end, self.emonthvar, *self.months) self.emonth.grid(row=3, column=1) self.eyearvar = tk.StringVar() self.eyears = range(2015, 2017) self.eyearvar.set(now.year) self.eyear = tk.OptionMenu(self.end, self.eyearvar, *self.eyears) self.eyear.grid(row=3, column=2) self.ehourvar = tk.StringVar() self.ehours = range(0, 24) self.ehourvar.set(now.hour) self.ehour = tk.OptionMenu(self.end, self.ehourvar, *self.ehours) self.ehour.grid(row=3, column=3) self.eminutevar = tk.StringVar() self.eminutes = range(0, 60, 5) self.eminutevar.set(now.minute) self.eminute = tk.OptionMenu(self.end, self.eminutevar, *self.eminutes) self.eminute.grid(row=3, column=4) ####################### # Simulation duration ####################### self.duration = tk.Frame(self.master, bd=2, relief=tk.FLAT, padx=5, pady=15) self.duration.grid(row=4, column=1) tk.Label(self.duration, text='Run simulation ').grid(row=4, column=0) self.durationhours = tk.Entry(self.duration, width=3, justify=tk.RIGHT) self.durationhours.grid(row=4, column=1) self.durationhours.insert(0, 50) tk.Label(self.duration, text=' hours ').grid(row=4, column=2) self.directionvar = tk.StringVar() self.directionvar.set('forwards') self.direction = tk.OptionMenu(self.duration, self.directionvar, 'forwards', 'backwards') self.direction.grid(row=4, column=3) tk.Label(self.duration, text=' in time ').grid(row=4, column=4) ############## # Output box ############## self.text = tk.Text(self, wrap="word") self.text.grid(row=5, columnspan=5, sticky='nsew') self.text.tag_configure("stderr", foreground="#b22222") sys.stdout = TextRedirector(self.text, "stdout") sys.stderr = TextRedirector(self.text, "stderr") s = tk.Scrollbar(self) s.grid(row=5, column=5, sticky='ns') s.config(command=self.text.yview) self.text.config(yscrollcommand=s.set) ############## # Driver data ############## o = OpenOil() self.current = reader_netCDF_CF_generic.Reader('http://thredds.met.no/thredds/dodsC/sea/norkyst800m/1h/aggregate_be') # o.test_data_folder() + # '16Nov2015_NorKyst_z_surface/norkyst800_subset_16Nov2015.nc') self.wind = reader_netCDF_CF_generic.Reader('http://thredds.met.no/thredds/dodsC/arome25/arome_metcoop_default2_5km_latest.nc') #self.wind = reader_netCDF_CF_generic.Reader(o.test_data_folder() + # '16Nov2015_NorKyst_z_surface/arome_subset_16Nov2015.nc') print '#'*41 print 'Current data coverage:' print str(self.current.start_time) + ' - ' + \ str(self.current.end_time) print '#'*41 print 'Wind data coverage:' print str(self.wind.start_time) + ' - ' + \ str(self.wind.end_time) print '#'*41 self.start_time = self.current.start_time ########## # RUN ########## tk.Button(self.master, text='PEIS PAO', bg='green', command=self.run_opendrift).grid(row=7, column=1, sticky=tk.W, pady=4)
#!/usr/bin/env python from opendrift.readers import reader_basemap_landmask from opendrift.readers import reader_netCDF_CF_generic from opendrift.models.openoil import OpenOil o = OpenOil(loglevel=0) # Set loglevel to 0 for debug information # Arome reader_arome = reader_netCDF_CF_generic.Reader( o.test_data_folder() + '16Nov2015_NorKyst_z_surface/arome_subset_16Nov2015.nc') # Norkyst reader_norkyst = reader_netCDF_CF_generic.Reader( o.test_data_folder() + '16Nov2015_NorKyst_z_surface/norkyst800_subset_16Nov2015.nc') # Landmask (Basemap) reader_basemap = reader_basemap_landmask.Reader(llcrnrlon=3.5, llcrnrlat=60.4, urcrnrlon=7, urcrnrlat=61.8, resolution='h', projection='merc') o.add_reader([reader_basemap, reader_norkyst, reader_arome]) ############################################################ # Seed oil particles within contour detected from satellite ############################################################
#!/usr/bin/env python from datetime import datetime from opendrift.models.openoil import OpenOil try: import gdal except: raise ValueError('Please install GDAL (www.gdal.org) with Python' ' support to run this example') o = OpenOil(loglevel=0) # Set loglevel to 0 for debug information o.max_speed = .5 # To minimise plotting boundaries ##################################################### # Seed oil particles within contours from shapefile ##################################################### o.seed_from_shapefile(o.test_data_folder() + 'shapefile_spawning_areas/Torsk.shp', number=2000, layername=None, featurenum=[2, 4], time=datetime.now()) o.fallback_values['x_wind'] = -4 # Constant wind drift o.fallback_values['y_wind'] = 8 o.set_config('drift:wind_uncertainty', 4) # Adding some diffusion # Running model o.run(steps=50, time_step=3600) # Print and plot results
def set_model(self, model): if model == 'OpenOil': self.o = OpenOil(weathering_model='noaa', location='NORWAY') elif model == 'Leeway': self.o = Leeway() elif model == 'ShipDrift': self.o = ShipDrift() elif model == 'OpenBerg': self.o = OpenBerg() for con in self.config.winfo_children(): con.destroy() self.con = tk.Label(self.config, text="\n\nConfiguration\n\n") self.con.grid(row=0, column=1, rowspan=1) for i, cs in enumerate(self.o._config_hashstrings()): tk.Label(self.config, text=cs).grid(row=i, column=1, rowspan=1) try: self.results.destroy() except: pass try: # Removing depth input boxes self.depthlabel.destroy() self.depth.destroy() self.seafloor.destroy() self.amount.destroy() self.amountlabel.destroy() except: pass print('Setting model: ' + model) print(self.o.list_configspec()) sc = self.o.get_seed_config() print(sc) self.seed_input = {} self.seed_input_var = {} self.seed_input_label = {} self.seed_frame = tk.Frame(self.seed, bd=2, relief=tk.FLAT, padx=5, pady=0) self.seed_frame.grid(row=60, columnspan=8, sticky='nsew') # FIND for num, i in enumerate(sc): if i in ['ocean_only', 'jibeProbability']: continue # workaround, should be avoided in future self.seed_input_label[i] = tk.Label(self.seed_frame, text=i + '\t') self.seed_input_label[i].grid(row=num, column=0) self.seed_input_var[i] = tk.StringVar() if type(sc[i]['options']) is list: self.seed_input[i] = ttk.Combobox( self.seed_frame, width=50, textvariable=self.seed_input_var[i], values=sc[i]['options']) self.seed_input_var[i].set(sc[i]['default']) else: self.seed_input[i] = tk.Entry( self.seed_frame, textvariable=self.seed_input_var[i], width=6, justify=tk.RIGHT) self.seed_input[i].insert(0, sc[i]['default']) self.seed_input[i].grid(row=num, column=1) if model == 'OpenOil': # User may be able to chose release depth self.depthlabel = tk.Label(self.duration, text='Spill depth [m]') self.depthlabel.grid(row=60, column=0) self.depthvar = tk.StringVar() self.depth = tk.Entry(self.duration, textvariable=self.depthvar, width=6, justify=tk.RIGHT) self.depth.grid(row=60, column=2) self.depth.insert(0, '0') self.seafloorvar = tk.IntVar() self.seafloor = tk.Checkbutton(self.duration, variable=self.seafloorvar, text='seafloor', command=self.seafloorbutton) self.seafloor.grid(row=60, column=3) self.amountvar = tk.StringVar() self.amount = tk.Entry(self.duration, textvariable=self.amountvar, width=6, justify=tk.RIGHT) self.amount.grid(row=60, column=4) self.amount.insert(0, '100') self.amountlabel = tk.Label(self.duration, text='m3 (per hour)') self.amountlabel.grid(row=60, column=5)
#!/usr/bin/env python from opendrift.readers import reader_basemap_landmask from opendrift.readers import reader_netCDF_CF_generic from opendrift.models.openoil import OpenOil o = OpenOil(loglevel=0) # Set loglevel to 0 for debug information # Arome reader_arome = reader_netCDF_CF_generic.Reader(o.test_data_folder() + '16Nov2015_NorKyst_z_surface/arome_subset_16Nov2015.nc') # Norkyst reader_norkyst = reader_netCDF_CF_generic.Reader(o.test_data_folder() + '16Nov2015_NorKyst_z_surface/norkyst800_subset_16Nov2015.nc') # Landmask (Basemap) reader_basemap = reader_basemap_landmask.Reader(llcrnrlon=3.5, llcrnrlat=60.4, urcrnrlon=7, urcrnrlat=61.8, resolution='h', projection='merc') o.add_reader([reader_basemap, reader_norkyst, reader_arome]) ############################################################ # Seed oil particles within contour detected from satellite ############################################################ o.seed_from_gml(o.test_data_folder() + 'radarsat_oil_satellite_observation/RS2_20151116_002619_0127_SCNB_HH_SGF_433012_9730_12182143_Oil.gml', num_elements=2000) # Adjusting some configuration o.set_config('processes:dispersion', True)
def run_opendrift(self): sys.stdout.write('running OpenDrift') try: self.budgetbutton.destroy() except Exception as e: print(e) pass month = np.int(self.months.index(self.monthvar.get()) + 1) start_time = datetime(np.int(self.yearvar.get()), month, np.int(self.datevar.get()), np.int(self.hourvar.get()), np.int(self.minutevar.get())) emonth = np.int(self.months.index(self.emonthvar.get()) + 1) end_time = datetime(np.int(self.eyearvar.get()), emonth, np.int(self.edatevar.get()), np.int(self.ehourvar.get()), np.int(self.eminutevar.get())) sys.stdout.flush() lon = np.float(self.lon.get()) lat = np.float(self.lat.get()) radius = np.float(self.radius.get()) elon = np.float(self.elon.get()) elat = np.float(self.elat.get()) eradius = np.float(self.eradius.get()) if lon != elon or lat != elat or start_time != end_time: lon = [lon, elon] lat = [lat, elat] radius = [radius, eradius] start_time = [start_time, end_time] cone = True else: cone = False if self.model.get() == 'Leeway': self.o = Leeway(loglevel=0) #for ln, lc in enumerate(self.leewaycategories): # if self.oljetype.get() == lc.strip().replace('>', ''): # print('Leeway object category: ' + lc) # break #extra_seed_args = {'objectType': ln + 1} elif self.model.get() == 'OpenOil': self.o = OpenOil(weathering_model='noaa', loglevel=0) #extra_seed_args = {'oiltype': self.oljetype.get()} elif self.model.get() == 'ShipDrift': self.o = ShipDrift(loglevel=0) extra_seed_args = {} for se in self.seed_input: if se == 'ocean_only': continue # To be fixed/removed val = self.seed_input[se].get() try: extra_seed_args[se] = np.float(val) except: extra_seed_args[se] = val self.o.set_config('seed:' + se, val) if 'object_type' in extra_seed_args: extra_seed_args['objectType'] = extra_seed_args['object_type'] del extra_seed_args['object_type'] self.o.add_readers_from_file(self.o.test_data_folder() + '../../opendrift/scripts/data_sources.txt') extra_seed_args = {} if self.model.get() == 'OpenOil': if self.seafloorvar.get() == 1: z = 'seafloor' else: z = -np.abs(np.float(self.depthvar.get())) # ensure negative z extra_seed_args['z'] = z extra_seed_args['m3_per_hour'] = np.float(self.amountvar.get()) self.o.seed_elements(lon=lon, lat=lat, number=5000, radius=radius, time=start_time, cone=cone, **extra_seed_args) #time_step = o.get_config('general:time_step_minutes')*60 time_step = 900 # 15 minutes time_step_output = timedelta(minutes=30) duration = int(self.durationhours.get())*3600/time_step if self.directionvar.get() == 'backwards': time_step = -time_step if self.has_diana is True: extra_args = {'outfile': self.outputdir + '/opendrift_' + self.model.get() + self.o.start_time.strftime('_%Y%m%d_%H%M.nc')} else: extra_args = {} #mapres = self.mapresvar.get()[0] self.simulationname = 'opendrift_' + self.model.get() + \ self.o.start_time.strftime('_%Y%m%d_%H%M') # Starting simulation run self.o.run(steps=duration, time_step=time_step, time_step_output=time_step_output, **extra_args) print(self.o) self.results.destroy() self.results = tk.Frame(self.seed, bd=2, relief=tk.FLAT, padx=5, pady=0) self.results.grid(row=70, column=3, columnspan=1, sticky='ew') tk.Button(self.results, text='Show animation', command=lambda: self.handle_result( 'showanimation')).grid(row=10, column=1) tk.Button(self.results, text='Save animation', command=lambda: self.handle_result( 'saveanimation')).grid(row=20, column=1) tk.Button(self.results, text='Show plot', command=lambda: self.handle_result( 'showplot')).grid(row=30, column=1) tk.Button(self.results, text='Save plot', command=lambda: self.handle_result( 'saveplot')).grid(row=40, column=1) if self.model.get() == 'OpenOil': tk.Button(self.results, text='Save oil budget', command=lambda: self.handle_result( 'saveoilbudget')).grid(row=50, column=1) tk.Button(self.results, text='Show oil budget', command=lambda: self.handle_result( 'showoilbudget')).grid(row=60, column=1) if self.has_diana is True: diana_filename = self.dianadir + self.simulationname + '.nc' self.o.write_netcdf_density_map(diana_filename) tk.Button(self.results, text='Show in Diana', command=lambda: os.system('diana &') ).grid(row=80, column=1)
#!/usr/bin/env python from datetime import datetime, timedelta from opendrift.readers import reader_basemap_landmask from opendrift.readers import reader_netCDF_CF_generic from opendrift.models.openoil import OpenOil print '#'*30 print 'NOTE: this example depends on availability of data from two Thredds servers: tds.hycom.org and www.ncdc.noaa.gov. May sometimes be slow or hanging.' print '#'*30 o = OpenOil(loglevel=0) # Set loglevel to 0 for debug information reader_hycom = reader_netCDF_CF_generic.Reader('http://tds.hycom.org/thredds/dodsC/GLBu0.08/expt_19.1/2010/3hrly') #print reader_hycom0 #reader_globcurrent = reader_netCDF_CF_generic.Reader('http://tds0.ifremer.fr/thredds/dodsC/CLS-L4-CUREUL_HS-ALT_SUM-V01.0_FULL_TIME_SERIE') # Total reader_oceanwind = reader_netCDF_CF_generic.Reader('http://www.ncdc.noaa.gov/thredds/dodsC/oceanwinds6hr') #print reader_oceanwind # Landmask (Basemap) reader_basemap = reader_basemap_landmask.Reader( llcrnrlon=-94, llcrnrlat=20, urcrnrlon=-80, urcrnrlat=32, resolution='i') # Add readers o.add_reader([reader_basemap, reader_hycom, reader_oceanwind]) #o.add_reader([reader_basemap, reader_globcurrent, reader_oceanwind]) # Seed some particles
def test_seed_outside_coverage(self): """Test seeding""" o = OpenOil(loglevel=0) norkyst = reader_netCDF_CF_generic.Reader( o.test_data_folder() + '14Jan2016_NorKyst_z_3d/NorKyst-800m_ZDEPTHS_his_00_3Dsubset.nc') landmask = reader_global_landmask.Reader(extent=[4, 6, 60, 64]) o.add_reader([landmask, norkyst]) o.set_config('environment:fallback:x_wind', 0) o.set_config('environment:fallback:y_wind', 0) o.set_config('seed:oil_type', 'SNORRE B 2004') o.seed_elements(5, 63, number=5, time=norkyst.start_time - 24 * timedelta(hours=24)) # Check that the oiltype is taken from config self.assertEqual(o.oil_name, o.get_config('seed:oil_type')) self.assertEqual(o.oil_name, 'SNORRE B 2004') with self.assertRaises(ValueError): o.run(steps=3, time_step=timedelta(minutes=15))
def test_biodegradation(self): o = OpenOil(loglevel=50, weathering_model='noaa') o.seed_elements(lon=4.8, lat=60, number=100, time=datetime.now(), oiltype='SIRTICA') o.set_config('processes:dispersion', True) o.set_config('processes:evaporation', True) o.set_config('processes:emulsification', True) o.set_config('processes:biodegradation', True) o.set_config('environment:fallback:land_binary_mask', 0) o.set_config('environment:fallback:x_wind', 0) o.set_config('environment:fallback:y_wind', 0) o.set_config('environment:fallback:x_sea_water_velocity', 0) o.set_config('environment:fallback:y_sea_water_velocity', 0) o.set_config('environment:fallback:sea_water_temperature', 30) o.run(duration=timedelta(days=1), time_step=1800) initial_mass = o.get_property('mass_oil')[0][0, 0] biodegraded30 = o.elements.mass_biodegraded factor = 0.127 #(1-e^(-1)) self.assertAlmostEqual(biodegraded30[-1] / initial_mass, factor, 3)
def test_seed_below_seafloor(self): o = OpenOil(loglevel=20) reader_norkyst = reader_netCDF_CF_generic.Reader( o.test_data_folder() + '14Jan2016_NorKyst_z_3d/NorKyst-800m_ZDEPTHS_his_00_3Dsubset.nc') o.add_reader([reader_norkyst]) o.set_config('environment:fallback:land_binary_mask', 0) o.set_config('environment:fallback:x_wind', 0) o.set_config('environment:fallback:y_wind', 0) o.set_config('environment:fallback:x_sea_water_velocity', 0) o.set_config('environment:fallback:y_sea_water_velocity', 0) lon = 4.5 lat = 62.0 o.set_config('seed:droplet_diameter_min_subsea', 0.0005) o.set_config('seed:droplet_diameter_max_subsea', 0.001) o.seed_elements(lon, lat, z=-5000, time=reader_norkyst.start_time, density=1000, oil_type='GENERIC BUNKER C') o.set_config('drift:vertical_mixing', True) o.set_config('vertical_mixing:timestep', 1) # s o.run(steps=3, time_step=300, time_step_output=300) z, status = o.get_property('z') self.assertAlmostEqual(z[0, 0], -147.3, 1) # Seeded at seafloor depth self.assertAlmostEqual(z[-1, 0], -132.45, 1) # After some rising
def test_droplet_distribution(self): # TODO: Should also add Li2017 here for droplet_distribution in ['Johansen et al. (2015)']: o = OpenOil(loglevel=50, weathering_model='noaa') if 'SKRUGARD' in o.oiltypes: oiltype = 'SKRUGARD' else: oiltype = 'SKRUGARD 2012' o.set_config('wave_entrainment:droplet_size_distribution', droplet_distribution) o.seed_elements(lon=4.8, lat=60, number=100, time=datetime.now(), oiltype=oiltype) o.set_config('environment:fallback:land_binary_mask', 0) o.set_config('environment:fallback:x_wind', 8) o.set_config('environment:fallback:y_wind', 0) o.set_config('environment:fallback:x_sea_water_velocity', 0) o.set_config('environment:fallback:y_sea_water_velocity', .3) o.run(duration=timedelta(hours=1), time_step=1800) d = o.elements.diameter # Suspicious, Sintef-param should give larer droplets if droplet_distribution == 'Johansen et al. (2015)': #self.assertAlmostEqual(d.mean(), 0.000072158) self.assertAlmostEqual(d.mean(), 0.000653, 2)
def test_oil_mixed_to_seafloor(self): o = OpenOil(loglevel=30) norkyst = reader_netCDF_CF_generic.Reader( o.test_data_folder() + '14Jan2016_NorKyst_z_3d/NorKyst-800m_ZDEPTHS_his_00_3Dsubset.nc') o.add_reader(norkyst) o.set_config('processes:evaporation', False) o.set_config('environment:fallback:x_wind', 25) o.set_config('environment:fallback:y_wind', 0) o.set_config('environment:fallback:land_binary_mask', 0) o.set_config('environment:fallback:ocean_vertical_diffusivity', 0.9) o.seed_elements(lon=5.38, lat=62.77, time=norkyst.start_time, number=100, radius=5000) o.run(end_time=norkyst.end_time) self.assertEqual(o.num_elements_active(), 100)
def test_oils(self): o = OpenOil(loglevel=50, weathering_model='noaa') assert len(o.oiltypes) >= 1478 for oiltype in o.oiltypes[12:14]: if oiltype == 'JP-8': continue o = OpenOil(loglevel=50, weathering_model='noaa') o.set_config('environment:fallback:x_wind', 7) o.set_config('environment:fallback:y_wind', 0) o.set_config('environment:fallback:x_sea_water_velocity', .7) o.set_config('environment:fallback:y_sea_water_velocity', 0) o.set_config('environment:fallback:land_binary_mask', 0) o.seed_elements(4.7, 60.0, radius=3000, number=3, z=0, time=datetime.now(), oiltype=oiltype) o.set_config('processes:evaporation', True) o.set_config('processes:emulsification', True) o.set_config('drift:vertical_mixing', False) o.set_config('drift:wind_uncertainty', 0) o.set_config('drift:current_uncertainty', 0) o.run(steps=3) initial_mass = o.get_property('mass_oil')[0][0, 0] self.assertEqual(o.elements.mass_evaporated.min(), o.elements.mass_evaporated.max()) self.assertTrue(o.elements.mass_evaporated.min() > 0) self.assertTrue( o.elements.mass_evaporated.max() / initial_mass <= 1) print(oiltype, o.elements.mass_evaporated.min())
class TestModels(unittest.TestCase): """Tests for OpenDrift models""" def test_seed(self): """Test seeding""" self.o = OpenOil() self.fake_eddy = reader_ArtificialOceanEddy.Reader(2, 62) self.fake_eddy.start_time = datetime(2015, 1, 1) self.o.add_reader([self.fake_eddy]) self.o.seed_elements(lon=4, lat=60, number=100, time=self.fake_eddy.start_time) self.assertEqual(len(self.o.elements), 0) self.assertEqual(len(self.o.elements_deactivated), 0) self.assertEqual(len(self.o.elements_scheduled), 100) def test_windblow(self): o = WindBlow(loglevel=0) reader_arome = reader_netCDF_CF_generic.Reader( o.test_data_folder() + '2Feb2016_Nordic_sigma_3d/AROME_MetCoOp_00_DEF.nc_20160202_subset') o.add_reader([reader_arome]) lat = 67.711251 lon = 13.556971 # Lofoten o.seed_elements(lon, lat, radius=5000, number=1000, time=reader_arome.start_time) o.run(steps=24, time_step=3600) self.assertAlmostEqual(o.elements.lon.max(), 16.167, 2) def test_shipdrift(self): """Sintef case study""" s = ShipDrift(loglevel=50) s.set_config('drift:current_uncertainty', 0) s.set_config('drift:wind_uncertainty', 0) c = reader_constant.Reader({ 'sea_surface_wave_significant_height': 5, 'sea_surface_wave_mean_period_from_variance_spectral_density_second_frequency_moment': 11, 'x_wind': 14.14213562, 'y_wind': -14.14213562, 'x_sea_water_velocity': 0.05656854249, 'y_sea_water_velocity': -0.05656854249 }) s.fallback_values['land_binary_mask'] = 0 s.add_reader(c) s.seed_elements(lon=2, lat=60, time=datetime.now(), number=1, length=80, beam=14, height=25, draft=5) s.run(time_step=600, duration=timedelta(hours=4)) self.assertIsNone( np.testing.assert_array_almost_equal(s.elements.lon, 2.25267706)) self.assertIsNone( np.testing.assert_array_almost_equal(s.elements.lat, 59.87694775)) def test_shipdrift_backwards(self): """Case above, reversed""" s = ShipDrift(loglevel=50) c = reader_constant.Reader({ 'sea_surface_wave_significant_height': 5, 'sea_surface_wave_mean_period_from_variance_spectral_density_second_frequency_moment': 11, 'x_wind': 14.14213562, 'y_wind': -14.14213562, 'x_sea_water_velocity': 0.05656854249, 'y_sea_water_velocity': -0.05656854249 }) s.fallback_values['land_binary_mask'] = 0 s.add_reader(c) s.seed_elements(lon=2.25267706, lat=59.87694775, time=datetime.now(), number=1, length=80, beam=14, height=25, draft=5) s.run(time_step=-600, duration=timedelta(hours=4)) self.assertIsNone( np.testing.assert_array_almost_equal(s.elements.lon, 2.0, 3)) self.assertIsNone( np.testing.assert_array_almost_equal(s.elements.lat, 60, 3)) def test_wind_drift_shear(self): """Testing PlastDrift model, with wind-induced current shear""" o = PlastDrift(loglevel=30) o.fallback_values['x_wind'] = 10 o.fallback_values['y_wind'] = 0 o.fallback_values['land_binary_mask'] = 0 o.seed_elements(lat=60, lon=5, time=datetime.now(), number=3, z=np.array([0, -0.05, -.1])) o.run(duration=timedelta(hours=10)) self.assertIsNone( np.testing.assert_array_almost_equal( o.elements.lon, [5.013484, 5.03395595, 5.01149002])) self.assertAlmostEqual(o.elements.lat[0], o.elements.lat[2]) def test_openberg(self): """Check if weighting array is set correctly and if model returns expected positions""" o = OpenBerg(loglevel=50) reader_current = reader_netCDF_CF_generic.Reader( o.test_data_folder() + '14Jan2016_NorKyst_z_3d/NorKyst-800m_ZDEPTHS_his_00_3Dsubset.nc') reader_basemap = reader_basemap_landmask.Reader(llcrnrlon=3., llcrnrlat=60., urcrnrlon=5., urcrnrlat=63.5, resolution='c', projection='gall') # reader_basemap = reader_basemap_landmask.Reader(llcrnrlon=-1.5, llcrnrlat=59, urcrnrlon=7, urcrnrlat=64, resolution='c') o.add_reader([reader_current, reader_basemap]) o.seed_elements(4., 62., time=reader_current.start_time) o.run(steps=1) arr = [ 0.16072658, 0.16466097, 0.17384121, 0.17325179, 0.1715925, 0.15592695 ] for indx in range(len(arr)): self.assertAlmostEqual(o.uw_weighting[indx], arr[indx], 8) self.assertAlmostEqual(o.history['lon'].data[0][1], 3.9921231, 3) self.assertAlmostEqual(o.history['lat'].data[0][1], 62.0108299, 3)
#!/usr/bin/env python from datetime import datetime from opendrift.readers import reader_netCDF_CF_generic from opendrift.models.openoil import OpenOil o = OpenOil(loglevel=0) # Set loglevel to 0 for debug information # Arome reader_arome = reader_netCDF_CF_generic.Reader(o.test_data_folder() + '16Nov2015_NorKyst_z_surface/arome_subset_16Nov2015.nc') # Norkyst reader_norkyst = reader_netCDF_CF_generic.Reader(o.test_data_folder() + '16Nov2015_NorKyst_z_surface/norkyst800_subset_16Nov2015.nc') o.add_reader([reader_norkyst, reader_arome]) o.set_config('processes:evaporation', False) ############################################################ # Seed oil particles within contour detected from satellite ############################################################ o.seed_from_gml(o.test_data_folder() + 'radarsat_oil_satellite_observation/RS2_20151116_002619_0127_SCNB_HH_SGF_433012_9730_12182143_Oil.gml', num_elements=2000) ############################################################ # Additional continous point release, lasting 24 hours ############################################################ o.seed_elements(3.8, 60.9, radius=0, number=1000, time=[datetime(2015,11,16,8), datetime(2015,11,17,8)]) ############################################################ # Additional cone release (e.g. from moving ship)
#!/usr/bin/env python from datetime import datetime, timedelta from opendrift.readers import reader_basemap_landmask from opendrift.readers import reader_netCDF_CF_generic from opendrift.models.openoil import OpenOil o = OpenOil(loglevel=0) # Set loglevel to 0 for debug information # Arome #reader_arome = reader_netCDF_CF_generic.Reader('http://thredds.met.no/thredds/dodsC/arome25/arome_metcoop_default2_5km_latest.nc') reader_arome = reader_netCDF_CF_generic.Reader(o.test_data_folder() + '16Nov2015_NorKyst_z_surface/arome_subset_16Nov2015.nc') # Norkyst #reader_norkyst = reader_netCDF_CF_generic.Reader('http://thredds.met.no/thredds/dodsC/sea/norkyst800m/1h/aggregate_be') reader_norkyst = reader_netCDF_CF_generic.Reader(o.test_data_folder() + '16Nov2015_NorKyst_z_surface/norkyst800_subset_16Nov2015.nc') # Landmask (Basemap) reader_basemap = reader_basemap_landmask.Reader( llcrnrlon=4, llcrnrlat=59.8, urcrnrlon=6, urcrnrlat=61, resolution='h', projection='merc') o.add_reader([reader_basemap, reader_norkyst, reader_arome]) # Seeding some particles lon = 4.6; lat = 60.0; # Outside Bergen #lon = 6.73; lat = 62.78; # Outside Trondheim time = None
def test_dispersion(self): for oil in ['SMORBUKK KONDENSAT', 'SKRUGARD']: for windspeed in [3, 8]: if oil == 'SKRUGARD' and windspeed == 3: continue o = OpenOil(loglevel=20, weathering_model='noaa') oilname = oil if oil not in o.oiltypes: if oilname == 'SKRUGARD': oilname = 'SKRUGARD 2012' elif oilname == 'SMORBUKK KONDENSAT': oilname = 'SMORBUKK KONDENSAT 2003' o.seed_elements(lon=4.8, lat=60, number=100, time=datetime.now(), oiltype=oilname) o.set_config('processes:dispersion', True) o.set_config('vertical_mixing:timestep', 10) o.set_config('environment:fallback:land_binary_mask', 0) o.set_config('environment:fallback:x_wind', windspeed) o.set_config('environment:fallback:y_wind', 0) o.set_config('environment:fallback:x_sea_water_velocity', 0) o.set_config('environment:fallback:y_sea_water_velocity', .3) o.run(duration=timedelta(hours=3), time_step=900) b = o.get_oil_budget() actual_dispersed = b['mass_dispersed'] / b['mass_total'] actual_submerged = b['mass_submerged'] / b['mass_total'] actual_evaporated = b['mass_evaporated'] / b['mass_total'] print('Dispersion fraction %f for ' '%s and wind speed %f' % (actual_dispersed[-1], oil, windspeed)) if oil == 'SMORBUKK KONDENSAT' and windspeed == 3: fraction_dispersed = 0 fraction_submerged = 0 fraction_evaporated = 0.526 meanlon = 4.81742 elif oil == 'SMORBUKK KONDENSAT' and windspeed == 8: fraction_dispersed = 0.086 fraction_submerged = 0.372 fraction_evaporated = 0.479 meanlon = 4.811 elif oil == 'SKRUGARD' and windspeed == 8: fraction_dispersed = 0.139 fraction_submerged = 0.367 fraction_evaporated = 0.180 meanlon = 4.824 else: fraction_dispersed = -1 # not defined self.assertAlmostEqual(actual_dispersed[-1], fraction_dispersed, 2) self.assertAlmostEqual(actual_submerged[-1], fraction_submerged, 2) self.assertAlmostEqual(actual_evaporated[-1], fraction_evaporated, 2) self.assertAlmostEqual(np.mean(o.elements.lon), meanlon, 3)
#!/usr/bin/env python """ Openoil ================================== """ from datetime import datetime, timedelta from opendrift.readers import reader_netCDF_CF_generic from opendrift.models.openoil import OpenOil o = OpenOil(loglevel=20, weathering_model='noaa') print(o.oiltypes) # Print available oil types #%% Add forcing date # Arome atmospheric model reader_arome = reader_netCDF_CF_generic.Reader(o.test_data_folder() + '16Nov2015_NorKyst_z_surface/arome_subset_16Nov2015.nc') # Norkyst ocean model reader_norkyst = reader_netCDF_CF_generic.Reader(o.test_data_folder() + '16Nov2015_NorKyst_z_surface/norkyst800_subset_16Nov2015.nc') o.add_reader([reader_norkyst, reader_arome]) #%% # Seeding some particles time = reader_arome.start_time oil_type = 'GULLFAKS, EXXON' oil_type = 'ARABIAN MEDIUM, API' oil_type = 'ALGERIAN CONDENSATE' o.seed_elements(lon=4.9, lat=60.1, radius=3000, number=2000, time=time, z=0, oil_type=oil_type)
def test_no_dispersion(self): o = OpenOil(loglevel=50, weathering_model='noaa') o.seed_elements(lon=4.8, lat=60, number=100, time=datetime.now(), oiltype='SIRTICA') o.set_config('processes:dispersion', False) o.set_config('environment:fallback:land_binary_mask', 0) o.set_config('environment:fallback:x_wind', 8) o.set_config('environment:fallback:y_wind', 8) o.set_config('environment:fallback:x_sea_water_velocity', 0) o.set_config('environment:fallback:y_sea_water_velocity', .3) o.run(duration=timedelta(hours=2), time_step=1800) b = o.get_oil_budget() actual_dispersed = b['mass_dispersed'] / b['mass_total'] self.assertAlmostEqual(actual_dispersed[-1], 0) self.assertIsNone( np.testing.assert_array_almost_equal(o.elements.lon[0:3], [4.797, 4.802, 4.826], 3))