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)
        so.seed_elements(lon=lon, lat=lat, radius=radius, time=start_time)
        so.plot(buffer=.5, fast=True)
        del so
Beispiel #2
0
class TestLeeway(unittest.TestCase):
    """Tests for Leeway module."""

    def test_leewayprop(self):
        """Check that Leeway properties are properly read."""
        self.objectType = 85  # MED-WASTE-7
        self.lee = Leeway(loglevel=20)
        objectType = self.objectType
        self.assertEqual(self.lee.leewayprop[objectType]
                         ['Description'],
                         '>>Medical waste, syringes, small')
        self.assertEqual(self.lee.leewayprop[objectType]['DWSLOPE'], 1.79)

    def test_leewayrun(self):
        """Test the expected Leeway left/right split."""
        self.lee = Leeway(loglevel=30)
        self.objectType = 50  # FISHING-VESSEL-1
        self.reader_basemap = reader_basemap_landmask.Reader(
            llcrnrlon=3, llcrnrlat=59.8, projection='merc',
            urcrnrlon=6, urcrnrlat=60.5, resolution='i')
        self.lee.add_reader([self.reader_basemap])
        self.lee.seed_elements(lon=4.5, lat=60, number=100,
                               objectType=self.objectType,
                               time=datetime(2015, 1, 1))
        self.lee.fallback_values['x_wind'] = 0
        self.lee.fallback_values['y_wind'] = 10
        self.lee.fallback_values['x_sea_water_velocity'] = 0
        self.lee.fallback_values['y_sea_water_velocity'] = 0
        # Check that 7 out of 100 elements strand towards coast
        self.lee.run(steps=24, time_step=3600)
        self.assertEqual(self.lee.num_elements_scheduled(), 0)
        self.assertEqual(self.lee.num_elements_active(), 97)
        self.assertEqual(self.lee.num_elements_deactivated(), 3)  # stranded
        self.lee.export_ascii('leeway_ascii.txt')
        os.remove('leeway_ascii.txt')
Beispiel #3
0
    def test_lazy_reader_leeway_compare(self):

        o1 = Leeway(loglevel=0)
        #o1.set_config('environment:fallback:land_binary_mask', 0)
        o1.required_variables = [r for r in o1.required_variables
                                 if r != 'land_binary_mask']
        o1.add_readers_from_list(reader_list, lazy=False)
        time = o1.readers['roms native'].start_time
        o1.seed_elements(lat=67.85, lon=14, time=time)
        o1.run(steps=5)

        o2 = Leeway(loglevel=20)
        #o2.set_config('environment:fallback:land_binary_mask', 0)
        o2.required_variables = [r for r in o1.required_variables
                                 if r != 'land_binary_mask']
        o2.add_readers_from_list(reader_list, lazy=True)
        o2.seed_elements(lat=67.85, lon=14, time=time)
        o2.run(steps=5)

        # Some differences in wind and current components
        # due to different coordinate system
        for var in o1.history.dtype.names:
            if var in ['x_wind', 'y_wind', 'x_sea_water_velocity',
                       'y_sea_water_velocity']:
                tolerance = 1
            else:
                tolerance = 5
            self.assertIsNone(np.testing.assert_array_almost_equal(
                o1.history[var], o2.history[var], tolerance))
Beispiel #4
0
    def get(self):

        parser = reqparse.RequestParser()
        parser.add_argument('latitude', type=float, help='Latitude of the object')
        parser.add_argument('longitude', type=float, help='Longitude of object')
        args = parser.parse_args(strict=True)
        if args['latitude'] is not None and args['longitude'] is not None:
            if abs(args['latitude']) > 90 :
                abort(404, message="latitude is out of range of -90 <= latitude <= 90")
            
            if abs(args['longitude']) > 180:
                abort(404, message='longitude is out of range of -180 <= longitude <= 180')
            
            latitude = args['latitude']
            longitude = args['longitude']
            lw = Leeway()  # 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(lw.test_data_folder() + 
                '16Nov2015_NorKyst_z_surface/arome_subset_16Nov2015.nc')

            reader_norkyst = reader_netCDF_CF_generic.Reader('http://tds.hycom.org/thredds/dodsC/GLBu0.08/expt_91.2/uv3z')

            # Landmask (Basemap)
            reader_basemap = reader_basemap_landmask.Reader(
                                llcrnrlon=longitude-2, llcrnrlat=latitude-2,
                                urcrnrlon=longitude+2, urcrnrlat=latitude+2, resolution='h',
                                projection='merc')
            
            #lw.add_reader([reader_norkyst, reader_arome, reader_basemap])
            # Adding readers succesively, and specifying which variables they 
            # shall provide. This way, order of adding readers does not matter,
            # except for small rounding differences due to different projection
            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.add_reader(reader_basemap,
                        variables=['land_binary_mask'])

            # Seed leeway elements at defined position and time
            objType = 26  # 26 = Life-raft, no ballast
            lw.seed_elements(longitude, latitude, radius=100, number=30,
                            time=reader_arome.start_time, objectType=objType)

            lw.set_projection('+proj=merc')

            lw.run(steps=60*4, time_step=900)
            
            lp = lw.plot(show=False)
            img = StringIO.StringIO()
            lp[1].savefig(img,format='png')
            img.seek(0)
            response=make_response(img.buf)
            response.headers['Content-Type'] = 'image/png'
            return response
        else:
            abort(404, message="Requires latitude and longitude but none were given.")
Beispiel #5
0
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'
Beispiel #6
0
 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.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)
Beispiel #7
0
 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.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 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)
Beispiel #9
0
 def test_leeway_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=14,
                     lat=67.85,
                     number=100,
                     radius=1000,
                     time=datetime.now())
     o.run(steps=15)
     print o
     self.assertEqual(o.steps_calculation, 15)
Beispiel #10
0
    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)
Beispiel #11
0
class TestLeeway(unittest.TestCase):
    """Tests for Leeway module."""
    def test_leewayprop(self):
        """Check that Leeway properties are properly read."""
        self.objectType = 85  # MED-WASTE-7
        self.lee = Leeway(loglevel=20)
        objectType = self.objectType
        self.assertEqual(self.lee.leewayprop[objectType]['Description'],
                         '>>Medical waste, syringes, small')
        self.assertEqual(self.lee.leewayprop[objectType]['DWSLOPE'], 1.79)

    def test_leeway_config_object(self):
        """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
        self.assertEqual(l.leewayprop[objType]['Description'],
                         'Surf board with person')
        self.assertEqual(l.leewayprop[objType]['OBJKEY'],
                         'PERSON-POWERED-VESSEL-2')

    def test_leewayrun(self):
        """Test the expected Leeway left/right split."""
        self.lee = Leeway(loglevel=30)
        self.objectType = 50  # FISHING-VESSEL-1
        self.reader_landmask = reader_global_landmask.Reader(llcrnrlon=3,
                                                             llcrnrlat=59.8,
                                                             urcrnrlon=6,
                                                             urcrnrlat=60.5)
        self.lee.add_reader([self.reader_landmask])
        self.lee.seed_elements(lon=4.5,
                               lat=60,
                               number=100,
                               objectType=self.objectType,
                               time=datetime(2015, 1, 1))
        self.lee.fallback_values['x_wind'] = 0
        self.lee.fallback_values['y_wind'] = 10
        self.lee.fallback_values['x_sea_water_velocity'] = 0
        self.lee.fallback_values['y_sea_water_velocity'] = 0
        # Check that 7 out of 100 elements strand towards coast
        self.lee.run(steps=24, time_step=3600)
        self.assertEqual(self.lee.num_elements_scheduled(), 0)
        self.assertEqual(self.lee.num_elements_active(), 96)
        self.assertEqual(self.lee.num_elements_deactivated(), 4)  # stranded
        self.lee.export_ascii('leeway_ascii.txt')
        os.remove('leeway_ascii.txt')
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)
Beispiel #13
0
    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)
Beispiel #14
0
    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
Beispiel #15
0
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.fallback_values['x_wind'] = 0
    lee.fallback_values['y_wind'] = 10
    lee.fallback_values['x_sea_water_velocity'] = 0
    lee.fallback_values['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() == 96
    assert lee.num_elements_deactivated() == 4  # stranded
    lee.export_ascii(tmpdir + '/leeway_ascii.txt')
Beispiel #16
0
    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
Beispiel #17
0
class TestArray(unittest.TestCase):
    """Tests for Leeway module."""
    def setUp(self):
        self.objectType = 50  # FISHING-VESSEL-1
        self.lee = Leeway(loglevel=20)
        #print self.lee.leewayprop.values()[0]

        #self.lee = WindBlow(loglevel=0)
        self.reader_basemap = reader_basemap_landmask.Reader(llcrnrlon=3,
                                                             llcrnrlat=59,
                                                             projection='merc',
                                                             urcrnrlon=6,
                                                             urcrnrlat=61,
                                                             resolution='i')
        self.lee.add_reader([self.reader_basemap])
        self.lee.fallback_values['x_wind'] = 0
        self.lee.fallback_values['y_wind'] = 10
        self.lee.fallback_values['x_sea_water_velocity'] = 0
        self.lee.fallback_values['y_sea_water_velocity'] = 0

    def test_leewayprop(self):
        """Check that Leeway properties are properly read."""
        objectType = self.objectType
        self.assertEqual(self.lee.leewayprop[objectType]['Description'],
                         ' Fishing vessel, general (mean values)\n')
        self.assertEqual(self.lee.leewayprop[objectType]['DWSLOPE'], 2.47)

    def test_leewayrun(self):
        """Test the expected Leeway left/right split."""
        self.lee.seed_elements(lon=4.5,
                               lat=60,
                               number=100,
                               objectType=self.objectType,
                               time=datetime(2015, 1, 1))
        # Check that 7 out of 100 elements strand towards coast
        self.lee.run(steps=24, time_step=3600)
        self.assertEqual(self.lee.num_elements_scheduled(), 0)
        self.assertEqual(self.lee.num_elements_active(), 97)
        self.assertEqual(self.lee.num_elements_deactivated(), 3)  # stranded
Beispiel #18
0
class TestArray(unittest.TestCase):
    """Tests for Leeway module."""

    def setUp(self):
        self.objectType = 50  # FISHING-VESSEL-1
        self.lee = Leeway(loglevel=20)
        #print self.lee.leewayprop.values()[0]

        #self.lee = WindBlow(loglevel=0)
        self.reader_basemap = reader_basemap_landmask.Reader(
            llcrnrlon=3, llcrnrlat=59, projection='merc',
            urcrnrlon=6, urcrnrlat=61, resolution='i')
        self.lee.add_reader([self.reader_basemap])
        self.lee.fallback_values['x_wind'] = 0
        self.lee.fallback_values['y_wind'] = 10
        self.lee.fallback_values['x_sea_water_velocity'] = 0
        self.lee.fallback_values['y_sea_water_velocity'] = 0

    def test_leewayprop(self):
        """Check that Leeway properties are properly read."""
        objectType = self.objectType
        self.assertEqual(self.lee.leewayprop[objectType]
                         ['Description'],
                         ' Fishing vessel, general (mean values)\n')
        self.assertEqual(self.lee.leewayprop[objectType]['DWSLOPE'], 2.47)

    def test_leewayrun(self):
        """Test the expected Leeway left/right split."""
        self.lee.seed_elements(lon=4.5, lat=60, number=100,
                               objectType=self.objectType,
                               time=datetime(2015, 1, 1))
        # Check that 7 out of 100 elements strand towards coast
        self.lee.run(steps=24, time_step=3600)
        self.assertEqual(self.lee.num_elements_scheduled(), 0)
        self.assertEqual(self.lee.num_elements_active(), 97)
        self.assertEqual(self.lee.num_elements_deactivated(), 3)  # stranded
Beispiel #19
0
    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)
Beispiel #20
0
                    continue  # Only surface seeding for Leeway
                o = Leeway()
                args = {'objectType': 32}

            o.add_readers_from_list(readers, timeout=5)
            print(o)

            #lons=[-0.8, 0.4]; lats=[59.9, 59.95] # NorKyst border
            #lons=[4.8, 5.1]; lats=[59.9, 59.95] # Western Norway coast
            #lons=[13.11, 13.13]; lats=[67.81, 67.80] # Lofoten
            #lons=[19.37, 19.33]; lats=[70.32, 70.34] # Troms
            lons=[3.8, 3.82]; lats=[59.6, 59.61] # North Sea

            o.seed_elements(lon=lons, lat=lats,
                            time=[datetime.now() - timedelta(hours=3),
                                  datetime.now()],
                            number=1000, radius = [0, 1000],
                            cone=True, **args)

            print(o)
            o.run(duration=timedelta(hours=24), time_step=timestep,
                  time_step_output=1800, outfile='halo_test.nc')

            print(o)
            o.animation()
            if case == 'oil':
                o.plot()
                o.plot_oil_budget()
                o.plot_property('water_fraction')
                o.animation_profile()
Beispiel #21
0
    '16Nov2015_NorKyst_z_surface/norkyst800_subset_16Nov2015.nc')

lw.add_reader([reader_norkyst, reader_arome])
lw.fallback_values['x_sea_water_velocity'] = 0
lw.fallback_values['y_sea_water_velocity'] = 0
lw.fallback_values['x_wind'] = 0
lw.fallback_values['y_wind'] = 0

# 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)

# Print and plot results
print(lw)
lw.plot()
lw.animation()
Beispiel #22
0
    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)
    '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(lw.test_data_folder() + 
    '16Nov2015_NorKyst_z_surface/norkyst800_subset_16Nov2015.nc')

# Landmask (Basemap)
reader_basemap = reader_basemap_landmask.Reader(llcrnrlon=2.5, llcrnrlat=59.3,
                    urcrnrlon=5.8, urcrnrlat=62.5, resolution='i')

lw.add_reader([reader_norkyst, reader_arome, reader_basemap])

# 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)]
#time = reader_arome.start_time

objType = 26  # 26 = Life-raft, no ballast
lw.seed_elements(lon, lat, radius=[1000, 10000], number=5000,
                 time=time, objectType=objType)

# Running model (until end of driver data)
lw.run(steps=66*4, time_step=900)

# Print and plot results
print lw
lw.plot()
lw.animation()
Beispiel #24
0
Vietnam
==================================
"""

from datetime import datetime, timedelta
from opendrift.models.leeway import Leeway

o = Leeway(loglevel=20)  # Set loglevel to 0 for debug information

# Adding readers for global Thredds datasets:
# - Ocean forecast from global Hycom
# - Weather forecast from NOAA/NCEP
o.add_readers_from_list([
    'https://tds.hycom.org/thredds/dodsC/GLBy0.08/latest',
    'https://pae-paha.pacioos.hawaii.edu/thredds/dodsC/ncep_global/NCEP_Global_Atmospheric_Model_best.ncd'])

# Seed some particles
objType = 26  # 26 = Life-raft, no ballast
o.seed_elements(lon=107.8, lat=10.0, radius=1000, number=1000,
                objectType=objType, time=datetime.now())

# Run model
o.run(duration=timedelta(days=3),
      time_step=timedelta(hours=1),
      time_step_output=timedelta(hours=3))

# Print and plot results
print(o)
o.plot(fast=True)
o.animation(fast=True)
Beispiel #25
0
    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 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=20)
            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=2000,
                            radius=radius,
                            time=start_time,
                            objectType=ln + 1)
        if self.model.get() == 'OpenOil':
            o = OpenOil(loglevel=20)
            o.seed_elements(lon=lon,
                            lat=lat,
                            number=2000,
                            radius=radius,
                            time=start_time,
                            cone=cone,
                            oiltype=self.oljetype.get())

        print 'Making Basemap...'
        lons = o.elements_scheduled.lon
        lats = o.elements_scheduled.lat
        bufferlat = 2
        basemap = reader_basemap_landmask.Reader(
            llcrnrlon=lons.min() - bufferlat,
            llcrnrlat=lats.min() - bufferlat,
            urcrnrlon=lons.max() + bufferlat,
            urcrnrlat=lats.max() + bufferlat,
            resolution='h',
            projection='merc',
            minimise_whitespace=True)
        o.add_reader([basemap, self.current, self.wind])

        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

        tk.Button(self.master, text='Animation',
                  command=o.animation).grid(row=7,
                                            column=2,
                                            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=3,
                                                      sticky=tk.W,
                                                      pady=4)

        o.plot()
Beispiel #27
0
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)
Beispiel #28
0
"""

from datetime import datetime, timedelta
from opendrift.models.leeway import Leeway

o = Leeway()

#%%
# Adding a CMEMS reader as a JSON string, and NCEP winds from thredds URL.
# For CMEMS, username or password must be stored in a .netrc file under
# machine name "cmems", or provided explicitly instead of *null*
o.add_readers_from_list([
    '{"reader": "reader_cmems", "dataset": "global-analysis-forecast-phy-001-024-hourly-t-u-v-ssh", "cmems_user": null, "cmems_password": null}',
    'https://pae-paha.pacioos.hawaii.edu/thredds/dodsC/ncep_global/NCEP_Global_Atmospheric_Model_best.ncd'
])

o.seed_elements(time=datetime.utcnow(),
                lon=123,
                lat=-16.1,
                number=1000,
                radius=1000)

o.run(duration=timedelta(hours=72))

print(o)

o.animation(fast=False,
            skip=1,
            scale=10,
            background=['x_sea_water_velocity', 'y_sea_water_velocity'])
Beispiel #29
0
    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)
Beispiel #30
0
time = datetime.now()
duration = timedelta(days=3)
bufferlat = duration.total_seconds()/111000 
bufferlon = bufferlat*np.cos(lat*np.pi/180)

# Fetching current data from CMEMS
cmems_file = 'opendrift_cmems_download.nc'
if os.path.exists(cmems_file):
    # Reuising downloaded file, if existing. Delete it to force update.
    cmems = reader_netCDF_CF_generic.Reader(cmems_file)
else:
    cmems = reader_cmems.Reader(username=username, password=password,
                                motu=motu_client,
                                lon_min = lon - bufferlon,
                                lon_max = lon + bufferlon,
                                lat_min = lat - bufferlat,
                                lat_max = lat + bufferlat,
                                time_start = time,
                                time_end = time + duration)

# Fetching wind data from NCEP
reader_ncep = reader_netCDF_CF_generic.Reader('http://oos.soest.hawaii.edu/thredds/dodsC/hioos/model/atm/ncep_global/NCEP_Global_Atmospheric_Model_best.ncd')

o = Leeway()
o.add_reader([cmems, reader_ncep])
o.seed_elements(lon=lon, lat=lat, number=5000, time=time)
o.run(duration=duration, outfile='cmems.nc',
      time_step=600, time_step_output=3600)
o.animation()
Beispiel #31
0
    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)
Beispiel #32
0
# Landmask (Basemap)
reader_basemap = reader_basemap_landmask.Reader(
                    llcrnrlon=5.5, llcrnrlat=61.05,
                    urcrnrlon=6.65, urcrnrlat=61.21, resolution='f',
                    projection='merc')

reader_norkyst.interpolation = 'linearND'  # Slower, but extrapolates to coast
reader_arome.interpolation = 'linearND'
o.add_reader([reader_basemap, reader_norkyst, reader_arome])

# Seed elements at defined position and time
lat = 61.117594; lon = 6.55
time = None
#time = [reader_arome.start_time,
#        reader_arome.start_time + timedelta(hours=5)]
time = reader_arome.start_time
objType = 1  # 1: Person-in-water (PIW), unknown state (mean values)
o.seed_elements(lon, lat, radius=50, number=5000, time=time, objectType=objType)

print o

# Running model (until end of driver data)
o.run(steps=66*12, time_step=300)
#stop

# Print and plot results
print o
o.plot()
o.animation()
Beispiel #33
0
                    continue  # Only surface seeding for Leeway
                o = Leeway()
                args = {'objectType': 32}

            #o.add_readers_from_list(readers, timeout=5)
            o.add_halo_readers()
            print o

            #lons=[-0.8, 0.4]; lats=[59.9, 59.95] # NorKyst border
            #lons=[4.8, 5.1]; lats=[59.9, 59.95] # Western Norway coast
            #lons=[13.11, 13.13]; lats=[67.81, 67.80] # Lofoten
            #lons=[19.37, 19.33]; lats=[70.32, 70.34] # Troms
            lons=[3.8, 3.82]; lats=[59.6, 59.61] # North Sea

            o.seed_elements(lon=lons, lat=lats,
                            time=[datetime.now() - timedelta(hours=3),
                                  datetime.now()],
                            number=1000, radius = [0, 1000], cone=True, **args)

            print o
            o.run(duration=timedelta(hours=24), time_step=timestep,
                  time_step_output=1800, outfile='halo_test.nc')

            print o
            o.animation()
            if case == 'oil':
                o.plot()
                o.plot_oil_budget()
                o.plot_property('water_fraction')
                o.animation_profile()
Beispiel #34
0
#lw.add_reader([reader_norkyst, reader_arome, reader_basemap])
# Adding readers succesively, and specifying which variables they 
# shall provide. This way, order of adding readers does not matter,
# except for small rounding differences due to different projection
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.add_reader(reader_basemap,
              variables=['land_binary_mask'])

# Seeding some particles
lon = 4.5; lat = 60.0; # Outside Bergen

# Seed leeway elements at defined position and time
objType = 26  # 26 = Life-raft, no ballast
lw.seed_elements(lon, lat, radius=1000, number=3000,
                 time=reader_arome.start_time, objectType=objType)

lw.set_projection('+proj=merc')

# Running model (until end of driver data)
lw.run(steps=60*4, time_step=900)

# Print and plot results
print lw
lw.animation()
#lw.animation(filename='leeway.gif')
lw.plot()
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)

#%%
# Animation with current as background.
# Note that drift is also depending on wind, which is not shown.
lw.animation(background=['x_sea_water_velocity', 'y_sea_water_velocity'],
             skip=5,  # show every 5th vector
             cmap=cmocean.cm.speed, vmin=0, vmax=.8, bgalpha=.7, land_color='#666666', fast=True)
Beispiel #36
0
reader_basemap = reader_basemap_landmask.Reader(llcrnrlon=5.5,
                                                llcrnrlat=61.05,
                                                urcrnrlon=6.65,
                                                urcrnrlat=61.21,
                                                resolution='f',
                                                projection='merc')

o.add_reader([reader_basemap, reader_norkyst, reader_arome])

# Seed elements
lat = 61.117594
lon = 6.55
#time = [reader_arome.start_time,
#        reader_arome.start_time + timedelta(hours=5)]
time = reader_arome.start_time
objType = 1  # 1: Person-in-water (PIW), unknown state (mean values)
o.seed_elements(lon,
                lat,
                radius=50,
                number=5000,
                time=time,
                objectType=objType)

# Running model for 66 hours
o.run(steps=66 * 12, time_step=300)

# Print and plot results
print o
o.plot()
o.animation()
Beispiel #37
0
    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=20)
            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=2000,
                            radius=radius, time=start_time,
                            objectType=ln + 1)
        if self.model.get() == 'OpenOil':
            o = OpenOil(loglevel=20)
            o.seed_elements(lon=lon, lat=lat, number=2000, radius=radius,
                            time=start_time, cone=cone,
                            oiltype=self.oljetype.get())

        print 'Making Basemap...'
        lons = o.elements_scheduled.lon
        lats = o.elements_scheduled.lat
        bufferlat = 2
        basemap = reader_basemap_landmask.Reader(
            llcrnrlon=lons.min() - bufferlat,
            llcrnrlat=lats.min() - bufferlat,
            urcrnrlon=lons.max() + bufferlat,
            urcrnrlat=lats.max() + bufferlat,
            resolution='h', projection='merc',
            minimise_whitespace=True)
        o.add_reader([basemap, self.current, self.wind])

        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

        tk.Button(self.master, text='Animation',
                  command=o.animation).grid(row=7, column=2,
                                            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=3,
                                                      sticky=tk.W, pady=4)

        o.plot()
Beispiel #38
0
# Adding readers succesively, and specifying which variables they 
# shall provide. This way, order of adding readers does not matter,
# except for small rounding differences due to different projection
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.add_reader(reader_basemap,
              variables=['land_binary_mask'])
lw.fallback_values['x_sea_water_velocity'] = 0
lw.fallback_values['y_sea_water_velocity'] = 0

# Seeding some particles
lon = 4.5; lat = 60.0; # Outside Bergen

# Seed leeway elements at defined position and time
objType = 26  # 26 = Life-raft, no ballast
lw.seed_elements(lon, lat, radius=1000, number=3000,
                 time=reader_arome.start_time, objectType=objType)

lw.set_projection('+proj=merc')

# Running model (until end of driver data)
lw.run(steps=60*4, time_step=900)

# Print and plot results
print(lw)
lw.animation()
#lw.animation(filename='leeway.gif')
lw.plot()
Beispiel #39
0
    o.test_data_folder() +
    '16Nov2015_NorKyst_z_surface/arome_subset_16Nov2015.nc')
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
#time = [reader_arome.start_time,
#        reader_arome.start_time + timedelta(hours=5)]
time = reader_arome.start_time
object_type = 1  # 1: Person-in-water (PIW), unknown state (mean values)
o.seed_elements(lon=6.55,
                lat=61.117594,
                radius=50,
                number=5000,
                time=time,
                object_type=object_type)

#%%
# Running model for 12 hours, using small time step due to high resolution coastline
o.run(duration=timedelta(hours=12), time_step=300, time_step_output=3600)

#%%
# Print and plot results
print(o)
o.animation()

#%%
# .. image:: /gallery/animations/example_fjord_0.gif