def test_valid_minmax(self):
     """Check that invalid values are replaced with fallback."""
     o = OceanDrift(loglevel=20)
     from opendrift.readers.basereader import variables
     minval = variables.standard_names['x_wind']['valid_min']
     # Setting valid_min to -5, to check that replacement works
     variables.standard_names['x_wind']['valid_min'] = -5
     reader_wind = reader_netCDF_CF_generic.Reader(o.test_data_folder() +
                 '16Nov2015_NorKyst_z_surface/arome_subset_16Nov2015.nc')
     o.add_reader(reader_wind)
     o.set_config('environment:fallback:x_sea_water_velocity', 0)
     o.set_config('environment:fallback:x_wind', 2.0)
     o.set_config('environment:fallback:y_sea_water_velocity', 0)
     o.set_config('environment:fallback:land_binary_mask', 0)
     o.seed_elements(lon=4, lat=60, time=reader_wind.start_time)
     o.run(steps=1)
     variables.standard_names['x_wind']['valid_min'] = minval  # reset
     w = o.get_property('x_wind')[0][0]
     self.assertAlmostEqual(w, 2.0, 1)
Exemple #2
0
 def test_no_active_but_still_unseeded_elements(self):
     o = OceanDrift(loglevel=20)
     # deactivate elements after 3 hours
     o.set_config('drift:max_age_seconds', 3600 * 3)
     norkyst = reader_netCDF_CF_generic.Reader(
         o.test_data_folder() +
         '14Jan2016_NorKyst_z_3d/NorKyst-800m_ZDEPTHS_his_00_3Dsubset.nc')
     o.add_reader(norkyst)
     # seed two elements at 6 hour interval
     o.seed_elements(
         number=2,
         lon=4,
         lat=62,
         time=[norkyst.start_time, norkyst.start_time + timedelta(hours=6)])
     o.set_config('environment:fallback:land_binary_mask', 0)
     o.run(duration=timedelta(hours=8), outfile='test.nc')
     os.remove('test.nc')
     # Check that simulations has run until scheduled end
     self.assertEqual(o.steps_calculation, 8)
Exemple #3
0
 def test_buffer_length_stranding(self):
     o1 = OceanDrift(loglevel=30)
     norkyst = reader_netCDF_CF_generic.Reader(
         o1.test_data_folder() +
         '16Nov2015_NorKyst_z_surface/norkyst800_subset_16Nov2015.nc')
     basemap = reader_basemap_landmask.Reader(llcrnrlon=4.5,
                                              llcrnrlat=60.1,
                                              urcrnrlon=6.0,
                                              urcrnrlat=60.4,
                                              resolution='c',
                                              projection='merc')
     o1.add_reader([basemap])
     o1.fallback_values['x_sea_water_velocity'] = 0.8  # onshore drift
     o1.seed_elements(4.8,
                      60.2,
                      radius=5000,
                      number=100,
                      time=norkyst.start_time)
     o1.run(steps=100,
            time_step=900,
            time_step_output=3600,
            export_buffer_length=10)
     # Without buffer
     o2 = OceanDrift(loglevel=30)
     o2.add_reader([basemap])
     o2.fallback_values['x_sea_water_velocity'] = 0.8  # onshore drift
     o2.seed_elements(4.8,
                      60.2,
                      radius=5000,
                      number=100,
                      time=norkyst.start_time)
     o2.run(steps=100,
            time_step=900,
            time_step_output=3600,
            outfile='test_buffer_length_stranding.nc')
     self.assertIsNone(
         np.testing.assert_array_equal(o1.history['lon'].compressed(),
                                       o2.history['lon'].compressed()))
     self.assertIsNone(
         np.testing.assert_array_almost_equal(
             o1.history['status'].compressed(),
             o2.history['status'].compressed()))
     os.remove('test_buffer_length_stranding.nc')
 def test_reader_coverage(self):
     r = reader_netCDF_CF_generic.Reader(o.test_data_folder() +
         '16Nov2015_NorKyst_z_surface/norkyst800_subset_16Nov2015.nc')
     # Element outside reader domain
     self.assertEqual(len(r.covers_positions(5, 80)[0]), 0)
     x, y = r.lonlat2xy(5, 80)
     self.assertRaises(ValueError, r.check_arguments,
                       'y_sea_water_velocity', r.start_time, x, y, 0)
     # Element inside reader domain
     self.assertEqual(len(r.covers_positions(5, 60)[0]), 1)
     x, y = r.lonlat2xy(5, 60)
     var, time, x2, y2, z2, outside = \
         r.check_arguments('y_sea_water_velocity', r.start_time, x, y, 0)
     self.assertEqual(var, ['y_sea_water_velocity'])
     self.assertEqual(time, r.start_time)
     self.assertEqual(x, x2)
     self.assertEqual(y, y2)
     self.assertEqual(0, z2)
     self.assertEqual(len(outside), 0)
def test_lonlat(test_data):
    # Only used for projection
    reader_current = reader_netCDF_CF_generic.Reader(
        test_data +
        '14Jan2016_NorKyst_z_3d/NorKyst-800m_ZDEPTHS_his_00_3Dsubset.nc')

    # Simulation SRS
    p = OpenDriftSimulation.SRS()

    lon, lat = 4., 62.
    x, y = reader_current.lonlat2xy(lon, lat)

    # Single value
    u = [0.26724684, 0.2784934]
    ru, rv = reader_current.rotate_vectors(x, y, u[0], u[1],
                                           reader_current.proj, p)

    np.testing.assert_almost_equal(-0.14591436614546296, ru, decimal=3)
    np.testing.assert_almost_equal(0.3573351998976778, rv, decimal=2)

    # Profile (array of vectors)
    u = np.array([
        0.26724684, 0.26311329, 0.25992924, 0.25909173, 0.25849965, 0.24982239,
        0.25549856, 0.30730924, 0.29996288, 0.23423982, 0.23423982
    ])
    v = np.array([
        0.2784934, 0.26522627, 0.25113547, 0.2446443, 0.23454225, 0.16889542,
        0.18744907, 0.13027644, 0.09087397, 0.19704318, 0.19704318
    ])

    ru, rv = reader_current.rotate_vectors(x, y, u, v, reader_current.proj, p)

    nu = [
        -0.14591437, -0.13547045, -0.12388817, -0.11829696, -0.10930654,
        -0.05284545, -0.06749336, 0.00579645, 0.0388169, -0.08489617,
        -0.08489617
    ]
    nv = [
        0.3573352, 0.34816854, 0.33953491, 0.33613269, 0.33148788, 0.29689097,
        0.30961478, 0.33373241, 0.31101295, 0.29408664, 0.29408664
    ]
    np.testing.assert_array_almost_equal(nu, ru, decimal=3)
    np.testing.assert_array_almost_equal(nv, rv, decimal=3)
Exemple #6
0
    def test_valid_minmax_nanvalues(self):
        from opendrift.readers.basereader import variables
        # Reducing max current speed to test masking
        maxval = variables.standard_names['x_sea_water_velocity']['valid_max']
        variables.standard_names['x_sea_water_velocity']['valid_max'] = .1
        o = OceanDrift(loglevel=20)
        o.set_config('environment:fallback:land_binary_mask', 0)
        norkyst = reader_netCDF_CF_generic.Reader(
            o.test_data_folder() +
            '14Jan2016_NorKyst_z_3d/NorKyst-800m_ZDEPTHS_his_00_3Dsubset.nc')
        o.add_reader(norkyst)

        o.seed_elements(lon=4.95, lat=62, number=10, time=norkyst.start_time)
        o.run(steps=2)
        variables.standard_names['x_sea_water_velocity'][
            'valid_max'] = maxval  # reset
        u = o.get_property('x_sea_water_velocity')[0]
        self.assertAlmostEqual(u.max(), -.069,
                               3)  # Some numerical error allowed
Exemple #7
0
    def test_seed_below_reader_coverage(self):
        o = OpenOil(loglevel=20)
        reader_norkyst = reader_netCDF_CF_generic.Reader(o.test_data_folder() + '14Jan2016_NorKyst_z_3d/NorKyst-800m_ZDEPTHS_his_00_3Dsubset.nc')
        o.set_config('environment:fallback:land_binary_mask', 0)
        o.set_config('environment:fallback:x_wind', 0)
        o.set_config('environment:fallback:y_wind', 0)
        o.add_reader([reader_norkyst])
        lon = 5.0; lat = 64.0
        o.set_config('seed:droplet_diameter_min_subsea', 0.0005)
        o.set_config('seed:droplet_diameter_max_subsea', 0.005)
        o.seed_elements(lon, lat, z=-350, time=reader_norkyst.start_time,
                        density=1000)
        #o.set_config('vertical_mixing:TSprofiles', True)
        o.set_config('drift:vertical_mixing', True)

        o.set_config('vertical_mixing:timestep', 1)  # s
        o.run(steps=3, time_step=300, time_step_output=300)
        z, status = o.get_property('z')
        self.assertAlmostEqual(z[-1,0], -134.27, 1)  # After some rising
Exemple #8
0
 def test_seed_seafloor(self):
     o = OpenOil3D(loglevel=30)
     reader_norkyst = reader_netCDF_CF_generic.Reader(o.test_data_folder() + '14Jan2016_NorKyst_z_3d/NorKyst-800m_ZDEPTHS_his_00_3Dsubset.nc')
     o.fallback_values['land_binary_mask'] = 0
     o.fallback_values['x_wind'] = 0
     o.fallback_values['y_wind'] = 0
     o.fallback_values['x_sea_water_velocity'] = 0
     o.fallback_values['y_sea_water_velocity'] = 0
     o.add_reader([reader_norkyst])
     lon = 4.5; lat = 62.0
     o.seed_elements(lon, lat, z='seafloor', time=reader_norkyst.start_time,
                     density=1000)
     o.set_config('processes:turbulentmixing', True)
     o.set_config('turbulentmixing:verticalresolution', 1)  # m
     o.set_config('turbulentmixing:timestep', 1)  # s
     o.run(steps=3, time_step=300, time_step_output=300)
     #o.plot_property('z')
     z, status = o.get_property('z')
     self.assertAlmostEqual(z[0,0], -151.7, 1)  # Seeded at seafloor depth
     self.assertAlmostEqual(z[-1,0], -91.3, 1)  # After some rising
Exemple #9
0
 def test_seed_outside_coverage(self):
     """Test seeding"""
     o = OpenOil(loglevel=0)
     norkyst = reader_netCDF_CF_generic.Reader(
         o.test_data_folder() +
         '14Jan2016_NorKyst_z_3d/NorKyst-800m_ZDEPTHS_his_00_3Dsubset.nc')
     landmask = reader_global_landmask.Reader(extent=[4, 6, 60, 64])
     o.add_reader([landmask, norkyst])
     o.set_config('environment:fallback:x_wind', 0)
     o.set_config('environment:fallback:y_wind', 0)
     o.set_config('seed:oil_type', 'SNORRE B 2004')
     o.seed_elements(5,
                     63,
                     number=5,
                     time=norkyst.start_time - 24 * timedelta(hours=24))
     # Check that the oiltype is taken from config
     self.assertEqual(o.oil_name, o.get_config('seed:oil_type'))
     self.assertEqual(o.oil_name, 'SNORRE B 2004')
     with self.assertRaises(ValueError):
         o.run(steps=3, time_step=timedelta(minutes=15))
Exemple #10
0
    def test_reader_netcdf(self):
        """Check reader functionality."""

        reader1 = reader_netCDF_CF_generic.Reader(o.test_data_folder() + 
            '16Nov2015_NorKyst_z_surface/norkyst800_subset_16Nov2015.nc')
        reader2 = reader_ROMS_native.Reader(o.test_data_folder() +
            '2Feb2016_Nordic_sigma_3d/Nordic-4km_SLEVELS_avg_00_subset2Feb2016.nc')
        readers = [reader1, reader2]

        for r in readers:
            print r
            # Make four points:
            #  1) outside lower left, 2) lower left,  3) center of domain
            #  4) outside upper right
            # and assure that only 2) and 3) are marked as covered
            # Upper right is skipped, as lonlat2xy may lie slightly outside
            x = np.array([r.xmin - r.delta_x, r.xmin, (r.xmin + r.xmax)/2,
                          r.xmax + r.delta_x])
            y = np.array([r.ymin - r.delta_y, r.ymin, (r.ymin + r.ymax)/2,
                          r.ymax + r.delta_y])
            lons, lats = r.xy2lonlat(x,  y)
            covered = r.covers_positions(lons, lats, 0)
            if len(covered) != 1:
                self.assertEqual(covered.tolist(), [1, 2])
            else:
                if covered == [2]:
                    print '#'*60
                    print '#'*60
                    print 'WARNING: A point on the boundary is considered ' \
                          'outside after conversion x,y -> lon,lat -> x,y. ' \
                          'This is different from "standard", but is due to ' \
                          'rounding differences and not considered to be an ' \
                          'error. Numpy version is %s' % (np.__version__)
                    print '#'*60
                    print '#'*60
                else:
                    self.assertTrue(False)  # Should never happen!

            self.assertTrue(r.covers_time(r.start_time))
            self.assertFalse(r.covers_time(r.start_time - r.time_step))
            self.assertFalse(r.proj.is_latlong())
Exemple #11
0
    def test_vertical_profiles(self):

        norkyst3d = reader_netCDF_CF_generic.Reader(
            o.test_data_folder() +
            '14Jan2016_NorKyst_z_3d/NorKyst-800m_ZDEPTHS_his_00_3Dsubset.nc')
        lon = np.array([4.73])
        lat = np.array([62.35])
        variables = [
            'x_sea_water_velocity', 'x_sea_water_velocity',
            'sea_water_temperature'
        ]
        x, y = norkyst3d.lonlat2xy(lon, lat)
        data = norkyst3d.get_variables(variables,
                                       time=norkyst3d.start_time,
                                       x=x,
                                       y=y,
                                       z=[0, -100])
        self.assertEqual(data['z'][4], -25)
        self.assertEqual(data['z'][4], -25)
        self.assertAlmostEqual(data['sea_water_temperature'][:, 0, 0][7],
                               9.220000267028809)
Exemple #12
0
    def test_seed_below_seafloor(self):
        o = OpenOil(loglevel=20)
        reader_norkyst = reader_netCDF_CF_generic.Reader(o.test_data_folder() + '14Jan2016_NorKyst_z_3d/NorKyst-800m_ZDEPTHS_his_00_3Dsubset.nc')
        o.add_reader([reader_norkyst])
        o.set_config('environment:fallback:land_binary_mask', 0)
        o.set_config('environment:fallback:x_wind', 0)
        o.set_config('environment:fallback:y_wind', 0)
        o.set_config('environment:fallback:x_sea_water_velocity', 0)
        o.set_config('environment:fallback:y_sea_water_velocity', 0)
        lon = 4.5; lat = 62.0
        o.set_config('seed:droplet_diameter_min_subsea', 0.0005)
        o.set_config('seed:droplet_diameter_max_subsea', 0.001)
        o.seed_elements(lon, lat, z=-5000, time=reader_norkyst.start_time,
                        density=1000, oiltype='GENERIC BUNKER C')
        o.set_config('drift:vertical_mixing', True)

        o.set_config('vertical_mixing:timestep', 1)  # s
        o.run(steps=3, time_step=300, time_step_output=300)
        z, status = o.get_property('z')
        self.assertAlmostEqual(z[0,0], -147.3, 1)  # Seeded at seafloor depth
        self.assertAlmostEqual(z[-1,0], -132.5, 1)  # After some rising
Exemple #13
0
 def test_stranding_roms(self):
     o = PelagicEggDrift(loglevel=20)
     reader_arctic = reader_netCDF_CF_generic.Reader(o.test_data_folder() +
     '2Feb2016_Nordic_sigma_3d/Arctic20_1to5Feb_2016.nc')
     reader_nordic = reader_ROMS_native.Reader(o.test_data_folder() +
     '2Feb2016_Nordic_sigma_3d/Nordic-4km_SLEVELS_avg_00_subset2Feb2016.nc')
     o.add_reader(reader_arctic)
     o.add_reader(reader_nordic)
     o.set_config('environment:fallback:x_sea_water_velocity', 1)
     o.seed_elements(lon=13.0, lat=68.0, radius=20000, number=100,
                     time=[reader_arctic.start_time,
                           reader_nordic.end_time], z=-30)
     o.set_config('general:coastline_action', 'previous')
     o.set_config('drift:vertical_mixing', False)
     o.max_speed=1
     o.run(end_time=reader_nordic.end_time, time_step=3600*36)
     self.assertEqual(o.num_elements_scheduled(), 0)
     self.assertEqual(o.num_elements_active(), 100)
     self.assertEqual(o.num_elements_activated(), 100)
     self.assertEqual(o.num_elements_deactivated(), 0)
     self.assertEqual(o.num_elements_total(), 100)
Exemple #14
0
 def test_seed_outside_coverage(self):
     """Test seeding"""
     o = OpenOil3D(loglevel=0)
     norkyst = reader_netCDF_CF_generic.Reader(
         o.test_data_folder() +
         '14Jan2016_NorKyst_z_3d/NorKyst-800m_ZDEPTHS_his_00_3Dsubset.nc')
     basemap = reader_basemap_landmask.Reader(llcrnrlon=4,
                                              llcrnrlat=60,
                                              urcrnrlon=6,
                                              urcrnrlat=64,
                                              resolution='c',
                                              projection='merc')
     o.add_reader([basemap, norkyst])
     o.fallback_values['x_wind'] = 0
     o.fallback_values['y_wind'] = 0
     o.seed_elements(5,
                     63,
                     number=5,
                     time=norkyst.start_time - 24 * timedelta(hours=24))
     with self.assertRaises(ValueError):
         o.run(steps=3, time_step=timedelta(minutes=15))
Exemple #15
0
 def test_vertical_interpolation(self):
     norkyst3d = reader_netCDF_CF_generic.Reader(o.test_data_folder() +
         '14Jan2016_NorKyst_z_3d/NorKyst-800m_ZDEPTHS_his_00_3Dsubset.nc')
     lon = np.array([4.73, 4.75])
     lat = np.array([62.35, 62.30])
     z = np.array([0, -33])
     variables = ['x_sea_water_velocity', 'x_sea_water_velocity',
                  'sea_water_temperature']
     # Call get_variables_interpolated which interpolates both in 
     # space (horizontally, vertically) and then in time
     data, profiles = norkyst3d.get_variables_interpolated(
             variables, profiles=['sea_water_temperature'],
             profiles_depth = [-100, 0],
             time = norkyst3d.start_time + timedelta(seconds=900),
             lon=lon, lat=lat, z=z, block=True)
     # Check surface value
     self.assertEqual(data['sea_water_temperature'][0],
                      profiles['sea_water_temperature'][0,0])
     # Check interpolated temperature at 33 m depth
     self.assertAlmostEqual(data['sea_water_temperature'][1],
                            8.2648999309539786)
Exemple #16
0
    def test_reader_current_from_track(self):
        """Check if extrapolated currents are of expected value"""
        obslon = [3.1, 3.123456]
        obslat = [61.1, 61.132198]
        obstime = [datetime(2015, 11, 16, 0), datetime(2015, 11, 16, 6)]

        o = OceanDrift(loglevel=50)
        reader_wind = reader_netCDF_CF_generic.Reader(
            o.test_data_folder() +
            '16Nov2015_NorKyst_z_surface/arome_subset_16Nov2015.nc')

        reader_current = reader_current_from_track.Reader(
            obslon,
            obslat,
            obstime,
            wind_east=0,
            wind_north=0,
            windreader=reader_wind,
            wind_factor=0.018)
        self.assertAlmostEqual(reader_current.x_sea_water_velocity.data[0],
                               0.22070706, 8)
Exemple #17
0
 def test_buffer_length_stranding(self):
     o1 = OceanDrift(loglevel=30)
     norkyst = reader_netCDF_CF_generic.Reader(
         o1.test_data_folder() +
         '16Nov2015_NorKyst_z_surface/norkyst800_subset_16Nov2015.nc')
     landmask = reader_global_landmask.Reader(extent=[4.5, 6.0, 60.1, 60.4])
     o1.add_reader([landmask])
     o1.set_config('environment:fallback:x_sea_water_velocity',
                   0.8)  # onshore drift
     o1.seed_elements(4.8,
                      60.2,
                      radius=5000,
                      number=100,
                      time=norkyst.start_time)
     o1.run(steps=100,
            time_step=900,
            time_step_output=3600,
            export_buffer_length=10)
     # Without buffer
     o2 = OceanDrift(loglevel=30)
     o2.add_reader([landmask])
     o2.set_config('environment:fallback:x_sea_water_velocity',
                   0.8)  # onshore drift
     o2.seed_elements(4.8,
                      60.2,
                      radius=5000,
                      number=100,
                      time=norkyst.start_time)
     o2.run(steps=100,
            time_step=900,
            time_step_output=3600,
            outfile='test_buffer_length_stranding.nc')
     self.assertIsNone(
         np.testing.assert_array_equal(o1.history['lon'].compressed(),
                                       o2.history['lon'].compressed()))
     self.assertIsNone(
         np.testing.assert_array_almost_equal(
             o1.history['status'].compressed(),
             o2.history['status'].compressed()))
     os.remove('test_buffer_length_stranding.nc')
Exemple #18
0
 def test_export_step_interval(self):
     # Export to file only at end
     o1 = OceanDrift(loglevel=20)
     norkyst = reader_netCDF_CF_generic.Reader(o1.test_data_folder() +
         '16Nov2015_NorKyst_z_surface/norkyst800_subset_16Nov2015.nc')
     o1.add_reader(norkyst)
     o1.fallback_values['land_binary_mask'] = 0
     o1.seed_elements(4.25, 60.2, radius=1000, number=10,
                     time=norkyst.start_time)
     o1.run(steps=40)
     # Export to file during simulation
     o2 = OceanDrift(loglevel=20)
     o2.add_reader(norkyst)
     o2.fallback_values['land_binary_mask'] = 0
     o2.seed_elements(4.25, 60.2, radius=1000, number=10,
                     time=norkyst.start_time)
     o2.run(steps=40, export_buffer_length=6,
            outfile='export_step_interval.nc')
     self.assertIsNone(np.testing.assert_array_equal(
         o1.history['lon'].compressed(),
         o2.history['lon'].compressed()))
     # Finally check when steps is multiple of export_buffer_length
     o3 = OceanDrift(loglevel=20)
     o3.add_reader(norkyst)
     o3.fallback_values['land_binary_mask'] = 0
     o3.seed_elements(4.25, 60.2, radius=1000, number=10,
                     time=norkyst.start_time)
     o3.run(steps=42)
     # Export to file during simulation
     o4 = OceanDrift(loglevel=20)
     o4.add_reader(norkyst)
     o4.fallback_values['land_binary_mask'] = 0
     o4.seed_elements(4.25, 60.2, radius=1000, number=10,
                     time=norkyst.start_time)
     o4.run(steps=42, export_buffer_length=6,
            outfile='export_step_interval.nc')
     self.assertIsNone(np.testing.assert_array_equal(
         o3.history['lon'].compressed(),
         o4.history['lon'].compressed()))
     os.remove('export_step_interval.nc')
Exemple #19
0
    def test_openberg(self):
        """Check if weighting array is set correctly
        and if model returns expected positions"""
        o = OpenBerg(loglevel=50)

        reader_current = reader_netCDF_CF_generic.Reader(o.test_data_folder() +
                '14Jan2016_NorKyst_z_3d/NorKyst-800m_ZDEPTHS_his_00_3Dsubset.nc')

        reader_landmask = reader_global_landmask.Reader(llcrnrlon=3., llcrnrlat=60.,
                            urcrnrlon=5., urcrnrlat=63.5)

        o.add_reader([reader_current,reader_landmask])
        o.seed_elements(4.,62.,time=reader_current.start_time)
        o.run(steps=1)

        arr=[0.16072658,0.16466097,0.17384121,0.17325179,0.1715925,0.15592695]

        for indx in range(len(arr)):
            self.assertAlmostEqual(o.uw_weighting[indx],arr[indx],8)

        self.assertAlmostEqual(o.history['lon'].data[0][1],3.9921231,3)
        self.assertAlmostEqual(o.history['lat'].data[0][1],62.0108299,3)
Exemple #20
0
 def test_seed_below_seafloor(self):
     o = OpenOil3D(loglevel=0)
     reader_norkyst = reader_netCDF_CF_generic.Reader(
         o.test_data_folder() +
         '14Jan2016_NorKyst_z_3d/NorKyst-800m_ZDEPTHS_his_00_3Dsubset.nc')
     o.add_reader([reader_norkyst])
     o.fallback_values['land_binary_mask'] = 0
     lon = 4.5
     lat = 62.0
     o.seed_elements(lon,
                     lat,
                     z=-5000,
                     time=reader_norkyst.start_time,
                     density=1000)
     o.set_config('processes:turbulentmixing', True)
     o.set_config('turbulentmixing:verticalresolution', 1)  # m
     o.set_config('turbulentmixing:timestep', 1)  # s
     o.set_config('input:spill:droplet_diameter_min_subsea', 0.005)
     o.set_config('input:spill:droplet_diameter_max_subsea', 0.005)
     o.run(steps=3, time_step=300, time_step_output=300)
     z, status = o.get_property('z')
     self.assertAlmostEqual(z[0, 0], -151.2, 1)  # Seeded at seafloor depth
     self.assertAlmostEqual(z[-1, 0], -108.0, 2)  # After some rising
def test_equiv_proj(test_data):
    """ These two projections are almost equivalent """
    # Only used for projection
    reader_current = reader_netCDF_CF_generic.Reader(
        test_data +
        '14Jan2016_NorKyst_z_3d/NorKyst-800m_ZDEPTHS_his_00_3Dsubset.nc')

    # Simulation SRS
    p = pyproj.Proj(
        '+proj=stere +lat_0=90 +lat_ts=60 +lon_0=70 +x_0=0 +y_0=0 +a=6371000 +rf=298.257223563 +units=m +no_defs'
    )

    lon, lat = 4., 62.
    x, y = reader_current.lonlat2xy(lon, lat)

    # Single value
    u = [0.26724684, 0.2784934]
    ru, rv = reader_current.rotate_vectors(x, y, u[0], u[1],
                                           reader_current.proj, p)

    np.testing.assert_almost_equal(u[0], ru, decimal=3)
    np.testing.assert_almost_equal(u[1], rv, decimal=2)

    # Profile (array of vectors)
    u = np.array([
        0.26724684, 0.26311329, 0.25992924, 0.25909173, 0.25849965, 0.24982239,
        0.25549856, 0.30730924, 0.29996288, 0.23423982, 0.23423982
    ])
    v = np.array([
        0.2784934, 0.26522627, 0.25113547, 0.2446443, 0.23454225, 0.16889542,
        0.18744907, 0.13027644, 0.09087397, 0.19704318, 0.19704318
    ])

    ru, rv = reader_current.rotate_vectors(x, y, u, v, reader_current.proj, p)

    np.testing.assert_array_almost_equal(u, ru, decimal=3)
    np.testing.assert_array_almost_equal(v, rv, decimal=3)
    def test_interpolation_3dArrays(self):
        """Test interpolation."""
        reader = reader_netCDF_CF_generic.Reader(
            o.test_data_folder() +
            '14Jan2016_NorKyst_z_3d/NorKyst-800m_ZDEPTHS_his_00_3Dsubset.nc')

        # 100000 points within 50x50 pixels over sea (corner of domain)
        num_points = 1000
        np.random.seed(0)  # To get the same random numbers each time
        x = np.random.uniform(reader.xmin, reader.xmin + 800 * 50, num_points)
        y = np.random.uniform(reader.ymax - 800 * 50, reader.ymax, num_points)
        z = np.random.uniform(-200, 0, num_points)
        variables = [
            'x_sea_water_velocity', 'y_sea_water_velocity',
            'sea_water_temperature'
        ]
        # Read a block of data covering the points
        data = reader.get_variables(variables,
                                    time=reader.start_time,
                                    x=x,
                                    y=y,
                                    z=z,
                                    block=True)

        b = ReaderBlock(data, interpolation_horizontal='nearest')
        env, prof = b.interpolate(x,
                                  y,
                                  z,
                                  variables,
                                  profiles=['sea_water_temperature'],
                                  profiles_depth=[-30, 0])
        self.assertAlmostEqual(env['x_sea_water_velocity'][100], 0.075019, 3)
        self.assertAlmostEqual(prof['sea_water_temperature'][0, 11], 7.549999,
                               3)
        self.assertAlmostEqual(prof['sea_water_temperature'][-1, 11], 8.389999,
                               3)
        self.assertEqual(prof['z'][-1], b.z[-1])
    def test_repeated(self):
        """Check that block can be used for interpolation to several sets of positions"""
        reader = reader_netCDF_CF_generic.Reader(
            o.test_data_folder() +
            '14Jan2016_NorKyst_z_3d/NorKyst-800m_ZDEPTHS_his_00_3Dsubset.nc')

        # 100 points within 50x50 pixels over sea (corner of domain)
        num_points = 100
        np.random.seed(0)  # To get the same random numbers each time
        x = np.random.uniform(reader.xmin, reader.xmin + 800 * 50, num_points)
        y = np.random.uniform(reader.ymax - 800 * 50, reader.ymax, num_points)
        z = np.random.uniform(-200, 0, num_points)
        variables = [
            'x_sea_water_velocity', 'y_sea_water_velocity',
            'sea_water_temperature'
        ]
        # Read a block of data covering the points
        data = reader.get_variables(variables,
                                    time=reader.start_time,
                                    x=x,
                                    y=y,
                                    z=z,
                                    block=True)

        b = ReaderBlock(data, interpolation_horizontal='nearest')

        env, prof = b.interpolate(x, y, z, 'sea_water_temperature')
        x2 = x[20:30]
        y2 = y[20:30]
        z2 = z[20:30]
        env2, prof2 = b.interpolate(x2, y2, z2, 'sea_water_temperature')
        env3, prof3 = b.interpolate(x, y, z, 'sea_water_temperature')
        self.assertEqual(env['sea_water_temperature'][0],
                         env3['sea_water_temperature'][0])
        self.assertEqual(env['sea_water_temperature'][20],
                         env2['sea_water_temperature'][0])
def test_environment_mapping(test_data):

    # Wind from NE
    r = reader_constant.Reader({
        'wind_speed': 5,
        'wind_from_direction': 45,
        'land_binary_mask': 0
    })
    o = OceanDrift(loglevel=50)
    o.set_config('general:use_auto_landmask', False)
    o.add_reader(r)
    o.seed_elements(lon=4, lat=60, time=datetime.now())
    o.run(steps=15)
    np.testing.assert_almost_equal(o.elements.lon, 3.932, 3)
    np.testing.assert_almost_equal(o.elements.lat, 59.966, 3)
    # Wind from SW
    r = reader_constant.Reader({
        'wind_speed': 5,
        'wind_from_direction': 225,
        'land_binary_mask': 0
    })
    o = OceanDrift(loglevel=50)
    o.set_config('general:use_auto_landmask', False)
    o.add_reader(r)
    o.seed_elements(lon=4, lat=60, time=datetime.now())
    o.run(steps=15)
    np.testing.assert_almost_equal(o.elements.lon, 4.068, 3)
    np.testing.assert_almost_equal(o.elements.lat, 60.034, 3)

    # land_binary_mask mapped from sea_floor_depth_below_sea_level
    r = reader_netCDF_CF_generic.Reader(
        o.test_data_folder() +
        '14Jan2016_NorKyst_z_3d/NorKyst-800m_ZDEPTHS_his_00_3Dsubset.nc')
    assert 'land_binary_mask' not in r.derived_variables  # Disabled by default
    r.activate_environment_mapping('land_binary_mask_from_ocean_depth')
    assert 'land_binary_mask' in r.derived_variables
Exemple #25
0
 def test_vertical_mixing(self):
     # Export to file only at end
     o1 = PelagicEggDrift(loglevel=20)  # Profiles and vertical mixing
     norkyst = reader_netCDF_CF_generic.Reader(
         o1.test_data_folder() +
         '14Jan2016_NorKyst_z_3d/NorKyst-800m_ZDEPTHS_his_00_3Dsubset.nc')
     o1.add_reader([norkyst])
     o1.fallback_values['x_wind'] = 8
     o1.fallback_values['land_binary_mask'] = 0
     o1.seed_elements(4.1,
                      63.3,
                      radius=1000,
                      number=100,
                      time=norkyst.start_time)
     o1.set_config('turbulentmixing:timestep', 20.)  # seconds
     o1.set_config('turbulentmixing:verticalresolution', 1.)  # m
     o1.run(steps=20,
            time_step=300,
            time_step_output=1800,
            export_buffer_length=10,
            outfile='verticalmixing.nc')
     self.assertAlmostEqual(o1.history['z'].min(), -31.9, 1)
     self.assertAlmostEqual(o1.history['z'].max(), 0.0, 1)
     os.remove('verticalmixing.nc')
Exemple #26
0
"""
Openoil
==================================
"""

from datetime import datetime, timedelta
from opendrift.readers import reader_netCDF_CF_generic
from opendrift.models.openoil import OpenOil

o = OpenOil(loglevel=20, weathering_model='noaa')

print(o.oiltypes)  # Print available oil types

#%% Add forcing date
# Arome atmospheric model
reader_arome = reader_netCDF_CF_generic.Reader(o.test_data_folder() +
    '16Nov2015_NorKyst_z_surface/arome_subset_16Nov2015.nc')
# Norkyst ocean model
reader_norkyst = reader_netCDF_CF_generic.Reader(o.test_data_folder() +
    '16Nov2015_NorKyst_z_surface/norkyst800_subset_16Nov2015.nc')
o.add_reader([reader_norkyst, reader_arome])

#%%
# Seeding some particles
time = reader_arome.start_time
oil_type = 'GULLFAKS, EXXON'
oil_type = 'ARABIAN MEDIUM, API'
oil_type = 'ALGERIAN CONDENSATE'
o.seed_elements(lon=4.9, lat=60.1, radius=3000, number=2000,
                time=time, z=0, oil_type=oil_type)

#%%
Exemple #27
0
"""
Wind blow model
==================================
"""

from opendrift.readers import reader_netCDF_CF_generic
from opendrift.models.windblow import WindBlow

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

#%%
# Example of elements blowing with the wind, also over land

#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(
    o.test_data_folder() +
    '2Feb2016_Nordic_sigma_3d/AROME_MetCoOp_00_DEF.nc_20160202_subset')

o.add_reader([reader_arome])

#%%
# Seeding some particles
lat = 68.5
lon = 16.0  # Lofoten
o.seed_elements(lon,
                lat,
                radius=5000,
                number=1000,
                time=reader_arome.start_time)

#%%
Exemple #28
0
 def test_output_time_step(self):
     o1 = OceanDrift(loglevel=30)
     norkyst = reader_netCDF_CF_generic.Reader(
         o1.test_data_folder() +
         '16Nov2015_NorKyst_z_surface/norkyst800_subset_16Nov2015.nc')
     basemap = reader_basemap_landmask.Reader(llcrnrlon=4.5,
                                              llcrnrlat=60.0,
                                              urcrnrlon=5.2,
                                              urcrnrlat=60.5,
                                              resolution='i',
                                              projection='merc')
     o1.add_reader([basemap, norkyst])
     o1.seed_elements(4.96,
                      60.1,
                      radius=3000,
                      number=100,
                      time=norkyst.start_time)
     o1.run(duration=timedelta(hours=12),
            time_step=timedelta(minutes=30),
            time_step_output=timedelta(minutes=30),
            outfile='test_time_step30.nc')
     # Check length of time array and output array
     time = o1.get_time_array()[0]
     self.assertEqual(o1.history.shape[1], len(time))
     self.assertEqual(o1.start_time, time[0])
     self.assertEqual(o1.time, time[-1])
     # Second run, with larger output time step
     o2 = OceanDrift(loglevel=30)
     o2.add_reader([basemap, norkyst])
     o2.seed_elements(4.96,
                      60.1,
                      radius=3000,
                      number=100,
                      time=norkyst.start_time)
     o2.run(duration=timedelta(hours=12),
            time_step=timedelta(minutes=30),
            time_step_output=timedelta(minutes=60),
            outfile='test_time_step60.nc')
     self.assertEqual(o1.history.shape, (100, 25))
     self.assertEqual(o2.history.shape, (100, 13))
     # Check that start and end conditions (longitudes) are idential
     self.assertItemsEqual(o1.history['lon'][:, 24].compressed(),
                           o2.history['lon'][:, 12].compressed())
     self.assertItemsEqual(o1.history['lon'][:, 0].compressed(),
                           o2.history['lon'][:, 0].compressed())
     # Check that also run imported from file is identical
     o1i = OceanDrift(loglevel=20)
     o1i.io_import_file('test_time_step30.nc')
     o2i = OceanDrift(loglevel=20)
     o2i.io_import_file('test_time_step60.nc')
     os.remove('test_time_step30.nc')
     os.remove('test_time_step60.nc')
     self.assertItemsEqual(o2i.history['lon'][:, 12].compressed(),
                           o2.history['lon'][:, 12].compressed())
     # Check number of activated elements
     self.assertEqual(o1.num_elements_total(), o2.num_elements_total())
     self.assertEqual(o1.num_elements_total(), o1i.num_elements_total())
     self.assertEqual(o1.num_elements_total(), o2i.num_elements_total())
     # Check number of deactivated elements
     self.assertEqual(o1.num_elements_deactivated(),
                      o2.num_elements_deactivated())
     self.assertEqual(o1.num_elements_deactivated(),
                      o1i.num_elements_deactivated())
     self.assertEqual(o1.num_elements_deactivated(),
                      o2i.num_elements_deactivated())
Exemple #29
0
    def test_get_environment(self):
        o = PelagicEggDrift(loglevel=0)
        reader_nordic = reader_ROMS_native.Reader(o.test_data_folder() + '2Feb2016_Nordic_sigma_3d/Nordic-4km_SLEVELS_avg_00_subset2Feb2016.nc', name='Nordic')
        reader_arctic = reader_netCDF_CF_generic.Reader(o.test_data_folder() + '2Feb2016_Nordic_sigma_3d/Arctic20_1to5Feb_2016.nc', name='Arctic')
        ######################################################
        # Vertical interpolation is another issue to be fixed:
        reader_nordic.zlevels = reader_arctic.z
        ######################################################
        o.add_reader([reader_nordic, reader_arctic])
        # One point covered only by Nordic, two points coverd
        # by both readers, and two points covered by none of the readers
        testlon = np.array((14.0, 20.0, 20.1, 4, 5))
        testlat = np.array((70.1, 76.0, 76.1, 60, 60))
        testz = np.random.uniform(0, 0, len(testlon))
        self.assertItemsEqual([0], reader_nordic.covers_positions(
                                    testlon, testlat, testz))
        self.assertItemsEqual([0, 1, 2], reader_arctic.covers_positions(
                                    testlon, testlat, testz))
        o.seed_elements(testlon, testlat, testz, time=reader_nordic.start_time)
        o.fallback_values['land_binary_mask'] = 0
        env, env_profiles, missing = \
            o.get_environment(o.required_variables,
                              reader_nordic.start_time,
                              testlon, testlat, testz,
                              o.required_profiles)
        self.assertAlmostEqual(env['sea_water_temperature'][0], 4.338, 2)
        self.assertAlmostEqual(env['sea_water_temperature'][1], 0.6282, 3)
        self.assertAlmostEqual(env['sea_water_temperature'][4], 10.0)
        self.assertItemsEqual(missing, [False,False,False,False,False])
        self.assertAlmostEqual(env_profiles['sea_water_temperature'][0,0],
                               4.338, 2)
        self.assertAlmostEqual(env_profiles['sea_water_temperature'][0,4], 10)
        self.assertAlmostEqual(env_profiles['sea_water_temperature'][8,2], 10)
        self.assertAlmostEqual(env_profiles['sea_water_temperature'][7,2],
                               2.252265, 3)
        # Get separate data
        env2, env_profiles2, missing2 = \
            o.get_environment(['x_sea_water_velocity', 'y_sea_water_velocity',
                               'sea_water_temperature'],
                              reader_nordic.start_time,
                              testlon, testlat, testz,
                              ['sea_water_temperature'])
        self.assertTrue(env_profiles2 is not None)
        self.assertEqual(env_profiles2.keys(), ['z', 'sea_water_temperature'])
        # Get separate data, without profile
        env3, env_profiles3, missing3 = \
            o.get_environment(['x_sea_water_velocity', 'y_sea_water_velocity',
                               'sea_water_temperature'],
                              reader_nordic.start_time,
                              testlon, testlat, testz,
                              profiles=None)
        self.assertTrue(env_profiles3 is None)
        # Get separate data
        env4, env_profiles4, missing4 = \
            o.get_environment(['x_sea_water_velocity', 'y_sea_water_velocity',
                               'sea_water_temperature'],
                              reader_nordic.start_time,
                              testlon, testlat, testz,
                              ['sea_water_temperature'])

        self.assertItemsEqual(env['x_sea_water_velocity'],
                              env2['x_sea_water_velocity'])
        #print env_profiles['sea_water_temperature'], '1'*50
        #print env_profiles2['sea_water_temperature'], '2'*50
        #print env_profiles4['sea_water_temperature'], '4'*50
        # Test below should also pass, To be fixed
        #self.assertItemsEqual(env_profiles['sea_water_temperature'].ravel(),
        #                      env_profiles2['sea_water_temperature'].ravel())
        self.assertItemsEqual(env_profiles2['sea_water_temperature'].ravel(),
                              env_profiles4['sea_water_temperature'].ravel())
import numpy as np
import matplotlib.pyplot as plt
import cartopy.crs as ccrs
import cartopy.feature as cfeature
from opendrift.readers import reader_netCDF_CF_generic
from opendrift.readers import reader_ROMS_native
from opendrift.readers import reader_shape
from opendrift.models.oceandrift import OceanDrift

o = OceanDrift(loglevel=20)  # Set loglevel to 0 for debug information
o.max_speed = 3

# This example works better using hourly input from Thredds than the daily data from test folder
reader_nordic = reader_netCDF_CF_generic.Reader(
    'https://thredds.met.no/thredds/dodsC/sea/nordic4km/zdepths1h/aggregate_be'
)

#%%
# Use shapes from Cartopy for tests. These shapefiles are less acurate than those
# provided by the GSHHS dataset (available though the reader_global_landmask reader).
import cartopy.io.shapereader as shpreader
shpfilename = shpreader.natural_earth(resolution='110m',
                                      category='cultural',
                                      name='admin_0_countries')
reader_natural = reader_shape.Reader.from_shpfiles(shpfilename)
#reader_nordic = reader_ROMS_native.Reader(o.test_data_folder() +
#    '2Feb2016_Nordic_sigma_3d/Nordic-4km_SLEVELS_avg_00_subset2Feb2016.nc')

o.add_reader([reader_natural, reader_nordic])
o.set_config('general:use_auto_landmask', False)