def test_leeway_config_object(): """Check that correct object type is fetched from config""" l = Leeway(loglevel=20) l.set_config('seed:object_type', 'Surf board with person') l.seed_elements(lon=4.5, lat=60, number=100, time=datetime(2015, 1, 1)) objType = l.elements_scheduled.objectType assert l.leewayprop[objType]['Description'] == 'Surf board with person' assert l.leewayprop[objType]['OBJKEY'] == 'PERSON-POWERED-VESSEL-2'
def test_leeway_global_today(self): o = Leeway(loglevel=0) o.add_readers_from_file(o.test_data_folder() + '../../opendrift/scripts/data_sources.txt') o.set_config('general:basemap_resolution', 'i') o.seed_elements(lon=50, lat=29, number=100, radius=1000, time=datetime.now()) o.run(steps=15) print o self.assertEqual(o.steps_calculation, 15)
def test_constant_and_lazy_reader_leeway(self): cw = reader_constant.Reader({'x_wind':5, 'y_wind': 6}) cc = reader_constant.Reader({'x_sea_water_velocity':0, 'y_sea_water_velocity': .2}) o = Leeway(loglevel=20) o.add_reader([cw, cc]) o.add_readers_from_list(reader_list) o.set_config('environment:fallback:x_sea_water_velocity', 0.0) o.set_config('environment:fallback:y_sea_water_velocity', 0.1) time = datetime(2016,2,2,12) o.seed_elements(lat=67.85, lon=14, time=time) o.run(steps=2) self.assertAlmostEqual(o.elements.lat[0], 67.8548, 3)
def test_leeway_global_one_month_ago(self): o = Leeway(loglevel=0) o.add_readers_from_file(o.test_data_folder() + '../../opendrift/scripts/data_sources.txt') o.set_config('general:basemap_resolution', 'i') o.seed_elements(lon=50, lat=29, number=100, radius=1000, time=datetime.now() - timedelta(days=30)) o.run(steps=15) o.export_ascii('leeway_ascii.txt') os.remove('leeway_ascii.txt') print o self.assertEqual(o.steps_calculation, 15)
def check_seeding(self): print('#' * 50) print('Hang on, plot is comming in a few seconds...') mapres = self.mapresvar.get()[0] if mapres == 'f': print( '...actually more like 30 seconds for full resolution coastline....' ) if self.has_diana is True: print('Du far ta deg ein liten trall mens du ventar.') print('#' * 50) 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 so = Leeway(loglevel=50) so.seed_elements(lon=lon, lat=lat, number=5000, radius=radius, time=start_time) so.set_config('general:basemap_resolution', mapres) so.plot(buffer=.5) del so
def test_constant_and_lazy_reader_leeway(self): cw = reader_constant.Reader({'x_wind': 5, 'y_wind': 6}) cc = reader_constant.Reader({ 'x_sea_water_velocity': 0, 'y_sea_water_velocity': .2 }) o = Leeway(loglevel=20) o.set_config('general:basemap_resolution', 'c') o.add_reader([cw, cc]) o.add_readers_from_list(reader_list) o.fallback_values['x_sea_water_velocity'] = 0.0 o.fallback_values['y_sea_water_velocity'] = 0.1 time = datetime(2016, 2, 2, 12) o.seed_elements(lat=67.85, lon=14, time=time) o.run(steps=2) self.assertAlmostEqual(o.elements.lat[0], 67.8548, 3)
def check_seeding(self): print '#'*50 print 'Hang on, plot is comming in a few seconds...' mapres = self.mapresvar.get()[0] if mapres == 'f': print '...actually more like 30 seconds for full resolution coastline....' if self.has_diana is True: print 'Du far ta deg ein liten trall mens du ventar.' print '#'*50 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 so = Leeway(loglevel=50) so.seed_elements(lon=lon, lat=lat, number=5000, radius=radius, time=start_time) so.set_config('general:basemap_resolution', mapres) so.plot(buffer=.5) del so
def check_seeding(self): print('#' * 50) print('Hang on, plot is comming in a few seconds...') print('#' * 50) 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 so = Leeway(loglevel=50) for k, v in self.GUI_config.items(): try: so.set_config(k, v) except: pass so.seed_cone(lon=lon, lat=lat, radius=radius, time=start_time) so.plot(buffer=.5, fast=True) del so
def test_simulation_back_extent(): # backward leeb = Leeway() objectType = 50 # FISHING-VESSEL-1 leeb.seed_elements(lon=4, lat=60, number=100, objectType=objectType, time=datetime(2015, 1, 1)) leeb.set_config('environment:fallback:x_wind', 1.5) leeb.set_config('environment:fallback:y_wind', 10) leeb.set_config('environment:fallback:x_sea_water_velocity', 1.5) # maximum speed in automatic landmask leeb.set_config('environment:fallback:y_sea_water_velocity', 0) with pytest.raises(ValueError) as ex: leeb.run(duration=timedelta(days=-1), time_step=3600, time_step_output=10*3600) assert 'Time step must be negative if duration is negative.' in str(ex.value)
def test_leewayrun(tmpdir): """Test the expected Leeway left/right split.""" lee = Leeway(loglevel=30) objectType = 50 # FISHING-VESSEL-1 reader_landmask = reader_global_landmask.Reader(extent=[3, 59.8, 6, 60.5]) lee.add_reader([reader_landmask]) lee.seed_elements(lon=4.5, lat=60, number=100, objectType=objectType, time=datetime(2015, 1, 1)) lee.set_config('environment:fallback:x_wind', 0) lee.set_config('environment:fallback:y_wind', 10) lee.set_config('environment:fallback:x_sea_water_velocity', 0) lee.set_config('environment:fallback:y_sea_water_velocity', 0) # Check that 7 out of 100 elements strand towards coast lee.run(steps=24, time_step=3600) assert lee.num_elements_scheduled() == 0 assert lee.num_elements_active() == 92 assert lee.num_elements_deactivated() == 8 # stranded lee.export_ascii(tmpdir + '/leeway_ascii.txt')
def test_leewayrun(tmpdir, test_data): """Test the expected Leeway left/right split.""" lee = Leeway(loglevel=20) object_type = 50 # FISHING-VESSEL-1 reader_landmask = reader_global_landmask.Reader(extent=[ 3, 59.8, 6, 60.5 ]) lee.add_reader([reader_landmask]) lee.seed_cone(lon=[4.5, 4.7], lat=[60.1, 60], number=100, object_type=object_type, time=[datetime(2015, 1, 1, 0), datetime(2015, 1, 1, 6)]) lee.set_config('environment:fallback:x_wind', 0) lee.set_config('environment:fallback:y_wind', 10) lee.set_config('environment:fallback:x_sea_water_velocity', 0) lee.set_config('environment:fallback:y_sea_water_velocity', 0) # Check that 10 out of 100 elements strand towards coast lee.run(steps=24, time_step=3600) assert lee.num_elements_scheduled() == 0 assert lee.num_elements_active() == 88 assert lee.num_elements_deactivated() == 12 # stranded asciif = tmpdir + '/leeway_ascii.txt' lee.export_ascii(asciif) asciitarget = test_data + "/generated/test_leewayrun_export_ascii.txt" import filecmp assert filecmp.cmp(asciif, asciitarget)
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': o = Leeway(loglevel=0) for ln, lc in enumerate(self.leewaycategories): if self.oljetype.get() == lc.strip().replace('>', ''): print 'Leeway object category: ' + lc break o.seed_elements(lon=lon, lat=lat, number=5000, radius=radius, time=start_time, objectType=ln + 1) if self.model.get() == 'OpenOil': o = OpenOil3D(weathering_model='noaa', loglevel=0) o.seed_elements(lon=lon, lat=lat, number=5000, radius=radius, time=start_time, cone=cone, oiltype=self.oljetype.get()) o.add_readers_from_file(o.test_data_folder() + '../../opendrift/scripts/data_sources.txt') o.set_config('general:basemap_resolution', 'h') time_step = 1800 # Half hour 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() + o.start_time.strftime( '_%Y%m%d_%H%M.nc')} else: extra_args = {} mapres = self.mapresvar.get()[0] o.set_config('general:basemap_resolution', mapres) o.run(steps=duration, time_step=time_step, time_step_output=time_step, **extra_args) print o if self.has_diana is True: diana_filename = self.dianadir + '/opendrift_' + \ self.model.get() + o.start_time.strftime( '_%Y%m%d_%H%M.nc') o.write_netcdf_density_map(diana_filename) tk.Button(self.master, text='Show in Diana', command=lambda: os.system('diana &') ).grid(row=8, column=2, sticky=tk.W, pady=4) tk.Button(self.master, text='Animation', command=o.animation).grid(row=8, column=3, sticky=tk.W, pady=4) if self.model.get() == 'OpenOil': self.budgetbutton = tk.Button(self.master, text='Oil Budget', command=o.plot_oil_budget) self.budgetbutton.grid(row=8, column=4, sticky=tk.W, pady=4)
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': o = Leeway(loglevel=0) for ln, lc in enumerate(self.leewaycategories): if self.oljetype.get() == lc.strip().replace('>', ''): print 'Leeway object category: ' + lc break o.seed_elements(lon=lon, lat=lat, number=5000, radius=radius, time=start_time, objectType=ln + 1) if self.model.get() == 'OpenOil': o = OpenOil3D(weathering_model='noaa', loglevel=0) o.seed_elements(lon=lon, lat=lat, number=5000, radius=radius, time=start_time, cone=cone, oiltype=self.oljetype.get()) readers = [ # Note that order (priority) is important! '/lustre/storeA/project/copernicus/sea/romsnorkyst/zdepths1h/*fc*.nc', 'http://thredds.met.no/thredds/dodsC/sea/norkyst800m/1h/aggregate_be', '/lustre/storeA/project/copernicus/sea/romsnordic/zdepths1h/roms_nordic4_ZDEPTHS_hr.fc.*.nc', 'http://thredds.met.no/thredds/dodsC/sea/nordic4km/zdepths1h/aggregate_be', '/lustre/storeA/project/metproduction/products/meps/symlinks/thredds/meps_det_pp_2_5km_latest.nc', 'http://thredds.met.no/thredds/dodsC/meps25files/meps_det_pp_2_5km_latest.nc', '/lustre/storeA/project/metproduction/products/arome2_5_arctic/thredds/arome_arctic_pp_2_5km_latest.nc', 'http://thredds.met.no/thredds/dodsC/aromearcticlatest/arome_arctic_pp_2_5km_latest.nc', '/lustre/storeA/project/copernicus/sea/mywavewam4/*fc*.nc', 'http://thredds.met.no/thredds/dodsC/sea/mywavewam4/mywavewam4_be', 'http://tds.hycom.org/thredds/dodsC/GLBu0.08/expt_91.2/uv3z', 'http://oos.soest.hawaii.edu/thredds/dodsC/hioos/model/atm/ncep_global/NCEP_Global_Atmospheric_Model_best.ncd'] o.add_readers_from_list(readers) o.set_config('general:basemap_resolution', 'h') time_step = 1800 # Half hour 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() + o.start_time.strftime( '_%Y%m%d_%H%M.nc')} else: extra_args = {} mapres = self.mapresvar.get()[0] o.set_config('general:basemap_resolution', mapres) o.run(steps=duration, time_step=time_step, time_step_output=time_step, **extra_args) print o if self.has_diana is True: diana_filename = self.dianadir + '/opendrift_' + \ self.model.get() + o.start_time.strftime( '_%Y%m%d_%H%M.nc') o.write_netcdf_density_map(diana_filename) tk.Button(self.master, text='Show in Diana', command=lambda: os.system('diana &') ).grid(row=8, column=2, sticky=tk.W, pady=4) tk.Button(self.master, text='Animation', command=o.animation).grid(row=8, column=3, sticky=tk.W, pady=4) if self.model.get() == 'OpenOil': self.budgetbutton = tk.Button(self.master, text='Oil Budget', command=o.plot_oil_budget) self.budgetbutton.grid(row=8, column=4, sticky=tk.W, pady=4)
from opendrift.readers import reader_netCDF_CF_generic from opendrift.models.leeway import Leeway lw = Leeway(loglevel=0) # Set loglevel to 0 for debug information # Arome reader_arome = reader_netCDF_CF_generic.Reader(lw.test_data_folder() + '16Nov2015_NorKyst_z_surface/arome_subset_16Nov2015.nc') # Norkyst reader_norkyst = reader_netCDF_CF_generic.Reader(lw.test_data_folder() + '16Nov2015_NorKyst_z_surface/norkyst800_subset_16Nov2015.nc') lw.add_reader([reader_norkyst, reader_arome]) # Intermediate map resolution is sufficient for large scale lw.set_config('general:basemap_resolution', 'i') # Seed elements along cone, e.g. ship track with # increasing uncertainty in position lon = [3.6, 5.1]; lat = [61., 59.6]; time = [reader_arome.start_time, reader_arome.start_time + timedelta(hours=30)] objType = 26 # 26 = Life-raft, no ballast lw.seed_elements(lon, lat, radius=[1000, 10000], number=5000, time=time, objectType=objType) # Running model lw.run(steps=66*4, time_step=900) print lw
lw = Leeway(loglevel=0) # Set loglevel to 0 for debug information # Arome reader_arome = reader_netCDF_CF_generic.Reader( lw.test_data_folder() + '16Nov2015_NorKyst_z_surface/arome_subset_16Nov2015.nc') # Norkyst reader_norkyst = reader_netCDF_CF_generic.Reader( lw.test_data_folder() + '16Nov2015_NorKyst_z_surface/norkyst800_subset_16Nov2015.nc') lw.add_reader([reader_norkyst, reader_arome]) # Intermediate map resolution is sufficient for large scale lw.set_config('general:basemap_resolution', 'i') # Seed elements along cone, e.g. ship track with # increasing uncertainty in position lon = [3.6, 5.1] lat = [61., 59.6] time = [reader_arome.start_time, reader_arome.start_time + timedelta(hours=30)] objType = 26 # 26 = Life-raft, no ballast lw.seed_elements(lon, lat, radius=[1000, 10000], number=5000, time=time, objectType=objType)
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': o = Leeway(loglevel=0) for ln, lc in enumerate(self.leewaycategories): if self.oljetype.get() == lc.strip().replace('>', ''): print 'Leeway object category: ' + lc break o.seed_elements(lon=lon, lat=lat, number=5000, radius=radius, time=start_time, objectType=ln + 1) if self.model.get() == 'OpenOil': o = OpenOil3D(weathering_model='noaa', loglevel=0) o.seed_elements(lon=lon, lat=lat, number=5000, radius=radius, time=start_time, cone=cone, oiltype=self.oljetype.get()) readers = [ # Note that order (priority) is important! '/lustre/storeA/project/copernicus/sea/romsnorkyst/zdepths1h/*fc*.nc', 'http://thredds.met.no/thredds/dodsC/sea/norkyst800m/1h/aggregate_be', '/lustre/storeA/project/copernicus/sea/romsnordic/zdepths1h/roms_nordic4_ZDEPTHS_hr.fc.*.nc', 'http://thredds.met.no/thredds/dodsC/sea/nordic4km/zdepths1h/aggregate_be', '/lustre/storeA/project/metproduction/products/meps/symlinks/thredds/meps_det_pp_2_5km_latest.nc', 'http://thredds.met.no/thredds/dodsC/meps25files/meps_det_pp_2_5km_latest.nc', '/lustre/storeA/project/metproduction/products/arome2_5_arctic/thredds/arome_arctic_pp_2_5km_latest.nc', 'http://thredds.met.no/thredds/dodsC/aromearcticlatest/arome_arctic_pp_2_5km_latest.nc', '/lustre/storeA/project/copernicus/sea/mywavewam4/*fc*.nc', 'http://thredds.met.no/thredds/dodsC/sea/mywavewam4/mywavewam4_be', 'http://tds.hycom.org/thredds/dodsC/GLBu0.08/expt_91.2/uv3z', 'http://oos.soest.hawaii.edu/thredds/dodsC/hioos/model/atm/ncep_global/NCEP_Global_Atmospheric_Model_best.ncd' ] o.add_readers_from_list(readers) o.set_config('general:basemap_resolution', 'h') time_step = 1800 # Half hour 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() + o.start_time.strftime('_%Y%m%d_%H%M.nc') } else: extra_args = {} mapres = self.mapresvar.get()[0] o.set_config('general:basemap_resolution', mapres) o.run(steps=duration, time_step=time_step, time_step_output=time_step, **extra_args) print o if self.has_diana is True: diana_filename = self.dianadir + '/opendrift_' + \ self.model.get() + o.start_time.strftime( '_%Y%m%d_%H%M.nc') o.write_netcdf_density_map(diana_filename) tk.Button(self.seed, text='Show in Diana', command=lambda: os.system('diana &')).grid(row=8, column=2, sticky=tk.W, pady=4) tk.Button(self.seed, text='Animation', command=o.animation).grid(row=8, column=3, sticky=tk.W, pady=4) if self.model.get() == 'OpenOil': self.budgetbutton = tk.Button(self.seed, text='Oil Budget', command=o.plot_oil_budget) self.budgetbutton.grid(row=8, column=4, sticky=tk.W, pady=4)
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': o = Leeway(loglevel=0) for ln, lc in enumerate(self.leewaycategories): if self.oljetype.get() == lc.strip().replace('>', ''): print('Leeway object category: ' + lc) break o.seed_elements(lon=lon, lat=lat, number=5000, radius=radius, time=start_time, objectType=ln + 1) if self.model.get() == 'OpenOil': o = OpenOil3D(weathering_model='noaa', loglevel=0) o.seed_elements(lon=lon, lat=lat, number=5000, radius=radius, time=start_time, cone=cone, oiltype=self.oljetype.get()) o.add_readers_from_file(o.test_data_folder() + '../../opendrift/scripts/data_sources.txt') o.set_config('general:basemap_resolution', 'h') time_step = 1800 # Half hour 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() + o.start_time.strftime('_%Y%m%d_%H%M.nc') } else: extra_args = {} mapres = self.mapresvar.get()[0] o.set_config('general:basemap_resolution', mapres) o.run(steps=duration, time_step=time_step, time_step_output=time_step, **extra_args) print(o) if self.has_diana is True: diana_filename = self.dianadir + '/opendrift_' + \ self.model.get() + o.start_time.strftime( '_%Y%m%d_%H%M.nc') o.write_netcdf_density_map(diana_filename) tk.Button(self.master, text='Show in Diana', command=lambda: os.system('diana &')).grid(row=8, column=2, sticky=tk.W, pady=4) tk.Button(self.master, text='Animation', command=o.animation).grid(row=8, column=3, sticky=tk.W, pady=4) if self.model.get() == 'OpenOil': self.budgetbutton = tk.Button(self.master, text='Oil Budget', command=o.plot_oil_budget) self.budgetbutton.grid(row=8, column=4, sticky=tk.W, pady=4)
def test_simulation_matches_forw_backward(): """ Check if simulation extent matches for both forward and backward modeling. """ # forward leef = Leeway() objectType = 50 # FISHING-VESSEL-1 leef.seed_elements(lon=4.5, lat=60, number=100, objectType=objectType, time=datetime(2015, 1, 1)) leef.set_config('environment:fallback:x_wind', -1.5) leef.set_config('environment:fallback:y_wind', -10) leef.set_config('environment:fallback:x_sea_water_velocity', -1.5) # maximum speed in automatic landmask leef.set_config('environment:fallback:y_sea_water_velocity', 0) leef.run(steps=2, time_step=10*3600, time_step_output=10*3600) # backward leeb = Leeway() objectType = 50 # FISHING-VESSEL-1 leeb.seed_elements(lon=4.5, lat=60, number=100, objectType=objectType, time=datetime(2015, 1, 1)) leeb.set_config('environment:fallback:x_wind', 1.5) leeb.set_config('environment:fallback:y_wind', 10) leeb.set_config('environment:fallback:x_sea_water_velocity', 1.5) # maximum speed in automatic landmask leeb.set_config('environment:fallback:y_sea_water_velocity', 0) leeb.run(steps=2, time_step=-10*3600, time_step_output=-10*3600) maskf = leef.readers['global_landmask'] maskb = leeb.readers['global_landmask'] assert maskf.xmin == maskb.xmin assert maskf.ymin == maskb.ymin assert maskf.xmax == maskb.xmax assert maskf.ymax == maskb.ymax assert leef.num_elements_scheduled() == leeb.num_elements_scheduled() assert leef.num_elements_active() == leeb.num_elements_active() assert leef.num_elements_deactivated() == leeb.num_elements_deactivated() flon, flat = leef.get_lonlats() flon = flon[:,-1] flat = flat[:,-1] blon, blat = leeb.get_lonlats() blon = blon[:,-1] blat = blat[:,-1] np.testing.assert_array_almost_equal(np.sort(flon), np.sort(blon)) np.testing.assert_array_almost_equal(np.sort(flat), np.sort(blat), decimal = 5)
#reader_arome = reader_netCDF_CF_generic.Reader('https://thredds.met.no/thredds/dodsC/mepslatest/meps_lagged_6_h_latest_2_5km_latest.nc') reader_arome = reader_netCDF_CF_generic.Reader(lw.test_data_folder() + '16Nov2015_NorKyst_z_surface/arome_subset_16Nov2015.nc') # Ocean model for current #reader_norkyst = reader_netCDF_CF_generic.Reader('https://thredds.met.no/thredds/dodsC/mepslatest/meps_lagged_6_h_latest_2_5km_latest.nc') reader_norkyst = reader_netCDF_CF_generic.Reader(lw.test_data_folder() + '16Nov2015_NorKyst_z_surface/norkyst800_subset_16Nov2015.nc') #%% # Adding readers successively, and specifying which variables they # shall provide. This way, order of adding readers does not matter lw.add_reader(reader_norkyst, variables=['x_sea_water_velocity', 'y_sea_water_velocity']) lw.add_reader(reader_arome, variables=['x_wind', 'y_wind']) lw.set_config('environment:fallback:x_sea_water_velocity', 0) lw.set_config('environment:fallback:y_sea_water_velocity', 0) #%% # Seed leeway elements at defined position and time object_type = 26 # 26 = Life-raft, no ballast lw.seed_elements(lon=4.5, lat=59.6, radius=100, number=1000, time=reader_arome.start_time, object_type=object_type) #%% # Running model lw.run(duration=timedelta(hours=48), time_step=900, time_step_output=3600) #%% # Print and plot results print(lw)
def run_opendrift(self): sys.stdout.write('running OpenDrift') 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())) if start_time > self.current.end_time: sys.stdout.write('Start time after end of current data!') start_time = self.current.start_time 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': o = Leeway(loglevel=0) for ln, lc in enumerate(self.leewaycategories): if self.oljetype.get() == lc.strip().replace('>', ''): print 'Leeway object category: ' + lc break o.seed_elements(lon=lon, lat=lat, number=5000, radius=radius, time=start_time, objectType=ln + 1) if self.model.get() == 'OpenOil': o = OpenOil3D(weathering_model='noaa', loglevel=0) o.seed_elements(lon=lon, lat=lat, number=5000, radius=radius, time=start_time, cone=cone, oiltype=self.oljetype.get()) o.add_reader([self.current, self.wind, self.waves]) o.set_config('general:basemap_resolution', 'h') time_step = 1800 # Half hour duration = int(self.durationhours.get()) * 3600 / time_step if self.directionvar.get() == 'backwards': time_step = -time_step o.run(steps=duration, time_step=time_step) print o if self.has_diana is True: diana_filename = self.dianadir + '/opendrift_' + \ self.model.get() + o.start_time.strftime( '_%Y%m%d_%H%M.nc') tk.Button(self.master, text='Save to Diana', command=o.write_netcdf_density_map(diana_filename)).grid( row=7, column=2, sticky=tk.W, pady=4) tk.Button(self.master, text='Animation', command=o.animation).grid(row=7, column=3, sticky=tk.W, pady=4) if self.model.get() == 'OpenOil': tk.Button(self.master, text='Oil Budget', command=o.plot_oil_budget).grid(row=7, column=4, sticky=tk.W, pady=4)
def test_config_suggestion(self): o = Leeway(loglevel=20) try: o.set_config('seed:object_type', 'person') except Exception as e: self.assertTrue('Did you mean' in str(e))
class OpenDriftGUI(tk.Tk): def __init__(self): tk.Tk.__init__(self) self.title('OpenDrift') o = OpenOil3D(weathering_model='noaa', location='NORWAY') 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) help_button = tk.Button(self.top, text='Help', command=self.show_help) help_button.grid(row=0, column=2, padx=50) 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 = ttk.Combobox(self.master, width=50, textvariable=self.oljetype, values=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=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=1, column=1) self.lon.insert(0, '4.5') self.lat.grid(row=1, column=0) self.lat.insert(0, '60.0') self.radius.grid(row=1, 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=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, now.year + 1) 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) 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 ############### 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', 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=1, column=1) self.elon.insert(0, '4.5') self.elat.grid(row=1, column=0) self.elat.insert(0, '60.0') self.eradius.grid(row=1, column=2) self.eradius.insert(0, '1000') ########## # Time ########## now = datetime.utcnow() tk.Label(self.end, text='Day', bg='gray').grid(row=2, column=0) tk.Label(self.end, text='Month', bg='gray').grid(row=2, column=1) tk.Label(self.end, text='Year', bg='gray').grid(row=2, column=2) tk.Label(self.end, text='Hour', bg='gray').grid(row=2, column=3) tk.Label(self.end, text='Minutes [UTC]', bg='gray').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, now.year + 1) 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) 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=1, column=0, padx=0) ####################### # Simulation duration ####################### self.coastline = tk.Frame(self.master, bd=2, relief=tk.FLAT, padx=5, pady=0) self.coastline.grid(row=4, column=1) tk.Label(self.coastline, text='Coastline resolution ').grid(row=4, column=1) self.mapresvar = tk.StringVar() self.mapres = tk.OptionMenu(self.coastline, self.mapresvar, *['full', 'high']) self.mapres.grid(row=4, column=2) self.mapresvar.set('high') self.duration = tk.Frame(self.master, bd=2, relief=tk.FLAT, padx=5, pady=5) self.duration.grid(row=5, column=1) tk.Label(self.duration, text='Run simulation ').grid(row=5, column=0) self.durationhours = tk.Entry(self.duration, width=3, justify=tk.RIGHT) self.durationhours.grid(row=5, column=1) self.durationhours.insert(0, 12) tk.Label(self.duration, text=' hours ').grid(row=5, column=2) self.directionvar = tk.StringVar() self.directionvar.set('forwards') self.direction = tk.OptionMenu(self.duration, self.directionvar, 'forwards', 'backwards') self.direction.grid(row=5, column=3) tk.Label(self.duration, text=' in time ').grid(row=5, column=4) ############## # Output box ############## self.text = tk.Text(self, wrap="word", height=18) self.text.grid(row=6, columnspan=8, 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=6, column=8, 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/' else: self.has_diana = False ############## # Initialise ############## o = OpenOil3D() ########## # RUN ########## tk.Button(self.master, text='PEIS PAO', bg='green', command=self.run_opendrift).grid(row=8, column=1, sticky=tk.W, pady=4) def copy_position(self, a, b, c): self.elat.delete(0, tk.END) self.elat.insert(0, self.lat.get()) self.elon.delete(0, tk.END) self.elon.insert(0, self.lon.get()) self.eradius.delete(0, tk.END) self.eradius.insert(0, self.radius.get()) self.edatevar.set(self.datevar.get()) self.emonthvar.set(self.monthvar.get()) self.eyearvar.set(self.yearvar.get()) self.ehourvar.set(self.hourvar.get()) self.eminutevar.set(self.minutevar.get()) def set_model(self, model): if model == 'OpenOil': self.categoryLabel['text'] = 'Oil type' self.oljetype.set('') self.o = OpenOil3D(weathering_model='noaa', location='NORWAY') self.categorydrop['values'] = self.o.oiltypes self.oljetype.set(self.o.oiltypes[0]) if model == 'Leeway': self.categoryLabel['text'] = 'Object type' self.oljetype.set('') self.o = Leeway() self.leewaycategories = [ self.o.leewayprop[c]['Description'].strip().replace('>', '') for c in self.o.leewayprop ] self.categorydrop['values'] = self.leewaycategories self.oljetype.set(self.leewaycategories[0]) def show_help(self): help_url = 'https://github.com/OpenDrift/opendrift/wiki/Graphical-User-Interface' print('Opening help website:\n' + help_url) import webbrowser webbrowser.open(help_url) def check_seeding(self): print('#' * 50) print('Hang on, plot is comming in a few seconds...') mapres = self.mapresvar.get()[0] if mapres == 'f': print( '...actually more like 30 seconds for full resolution coastline....' ) if self.has_diana is True: print('Du far ta deg ein liten trall mens du ventar.') print('#' * 50) 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 so = Leeway(loglevel=50) so.seed_elements(lon=lon, lat=lat, number=5000, radius=radius, time=start_time) so.set_config('general:basemap_resolution', mapres) so.plot(buffer=.5) del so def save_animation(self): mp4_filename = os.path.expanduser("~") + \ '/opendrift_' + self.model.get() + \ self.o.start_time.strftime('_%Y%m%d_%H%M.mp4') self.o.animation(filename=mp4_filename) print('Animation saved to:') print(mp4_filename) 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 self.o.seed_elements(lon=lon, lat=lat, number=5000, radius=radius, time=start_time, objectType=ln + 1) if self.model.get() == 'OpenOil': self.o = OpenOil3D(weathering_model='noaa', loglevel=0) self.o.seed_elements(lon=lon, lat=lat, number=5000, radius=radius, time=start_time, cone=cone, oiltype=self.oljetype.get()) self.o.add_readers_from_file( self.o.test_data_folder() + '../../opendrift/scripts/data_sources.txt') self.o.set_config('general:basemap_resolution', 'h') time_step = self.o.get_config('general:time_step_minutes') * 60 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.o.set_config('general:basemap_resolution', mapres) self.o.run(steps=duration, time_step=time_step, time_step_output=3600, **extra_args) print(self.o) if self.has_diana is True: diana_filename = self.dianadir + '/opendrift_' + \ self.model.get() + self.o.start_time.strftime( '_%Y%m%d_%H%M.nc') self.o.write_netcdf_density_map(diana_filename) tk.Button(self.master, text='Show in Diana', command=lambda: os.system('diana &')).grid(row=8, column=2, sticky=tk.W, pady=4) #tk.Button(self.master, text='Save animation', # command=self.save_animation).grid( # row=8, column=3, sticky=tk.W, pady=4) tk.Button(self.master, text='Animation', command=self.o.animation).grid(row=8, column=3, sticky=tk.W, pady=4) if self.model.get() == 'OpenOil': self.budgetbutton = tk.Button(self.master, text='Oil Budget', command=self.o.plot_oil_budget) self.budgetbutton.grid(row=8, column=4, sticky=tk.W, pady=4)