Skip to content

Commit

Permalink
Merge pull request #1435 from knutfrode/dev
Browse files Browse the repository at this point in the history
Made new example illustrating mapping of variables for CMEMS currents…
  • Loading branch information
knutfrode authored Oct 31, 2024
2 parents 21c107b + 379c453 commit 71b903a
Show file tree
Hide file tree
Showing 5 changed files with 82 additions and 65 deletions.
1 change: 1 addition & 0 deletions environment.yml
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ dependencies:
- xarray
- dask
- cfgrib
- cf_xarray
- pygrib
- xhistogram
- requests
Expand Down
20 changes: 8 additions & 12 deletions examples/example_long_cmems.py
Original file line number Diff line number Diff line change
@@ -1,21 +1,20 @@
#!/usr/bin/env python
"""
CMEMS
=============
This example runs an OceanDrift simulation
with current data from CMEMS
To run this example, you need a CMEMS account created at
https://marine.copernicus.eu
with username and password stored as environment variables ``COPERNICUSMARINE_SERVICE_USERNAME`` and ``COPERNICUSMARINE_SERVICE_PASSWORD``
Copernicus Marine Client (CMEMS)
================================
This example runs an OceanDrift simulation with current data from CMEMS.
To run this example, you need a CMEMS account created at https://marine.copernicus.eu
with username and password stored as environment variables
``COPERNICUSMARINE_SERVICE_USERNAME`` and ``COPERNICUSMARINE_SERVICE_PASSWORD``
or in a ``.netrc`` file with contents::
machine copernicusmarine login <your username> password <your password>
This file must be stored in your home folder (and unreadable by others) or in the main OpenDrift folder
Alternatively, an Xarray dataset can be created explicitly with the copernicusmarine client, and provided to reader_netCDF_CF_generic:
https://opendrift.github.io/gallery/example_long_cmems_new.html
https://opendrift.github.io/gallery/example_long_cmems_currents.html
"""

from datetime import datetime, timedelta
Expand All @@ -36,6 +35,3 @@

o.animation(fast=True, clabel='Ocean current [m/s]',
background=['x_sea_water_velocity', 'y_sea_water_velocity'])

#%%
# .. image:: /gallery/animations/example_cmems_0.gif
64 changes: 64 additions & 0 deletions examples/example_long_cmems_currents.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
#!/usr/bin/env python
"""
CMEMS current components
========================
The global CMEMS/copernicus ocean model contains several different surface current fields.
OpenDrift will by default use the variables with "standard_name" attribute equal to what is requested from a module, typically "x_sea_water_velocity"/"y_sea_water_velocity" for currents.
Note that "east/north" counterparts will also be detected, and eventual rotation will be performed automatically.
This example illustrates how a "standard_name_mapping" can be added to the generic netCDF reader to chose alternative variables.
The example also illustrates the alternative (experimental) mechanism of summing two readers.
"""

from datetime import datetime, timedelta
import cf_xarray
import copernicusmarine
from opendrift.models.oceandrift import OceanDrift
from opendrift.readers.reader_netCDF_CF_generic import Reader

#%%
# Get an Xarray dataset from copernicusmarine client
ds = copernicusmarine.open_dataset(dataset_id='cmems_mod_glo_phy_anfc_merged-uv_PT1H-i')
print(ds) # Default Xarray output
print(ds.cf) # Output from cf-xarray

#%%
# Create an OpenDrift reader from this dataset
reader_default = Reader(ds, name='CMEMS default')

#%%
# Mapping other variables to required standard_name's
reader_tides_only = Reader(ds, standard_name_mapping={
'utide': 'x_sea_water_velocity',
'vtide': 'y_sea_water_velocity',
}, name='Tides only')
reader_stokes = Reader(ds, standard_name_mapping={
'vsdx': 'x_sea_water_velocity',
'vsdy': 'y_sea_water_velocity',
}, name='Stokes only')
reader_total = Reader(ds, standard_name_mapping={
'utotal': 'x_sea_water_velocity',
'vtotal': 'y_sea_water_velocity',
}, name='Total current')

#%%
# Run and compare simulations using the different current components
cases = {'Eulerian current': reader_default,
'Tides only': reader_tides_only,
'Stokes drift only': reader_stokes,
'Total current': reader_total,
'SUM: Eulerian + Tides': reader_default + reader_tides_only, # Experimental feature
'SUM: Eulerian + Stokes': reader_default + reader_stokes, # Experimental feature
}

simulations = []
for cname, reader in cases.items():
o = OceanDrift()
o.add_reader(reader, variables=['x_sea_water_velocity', 'y_sea_water_velocity'])
o.seed_elements(lon=4.8, lat=60, time=datetime(2024, 10, 31, 6))
o.run(duration=timedelta(hours=12))
simulations.append(o)

simulations[0].plot(filename='cmems_comparison.png', buffer=.05,
compare=simulations[1:], legend=list(cases))
45 changes: 0 additions & 45 deletions examples/example_long_cmems_new.py

This file was deleted.

17 changes: 9 additions & 8 deletions opendrift/readers/reader_copernicusmarine.py
Original file line number Diff line number Diff line change
Expand Up @@ -32,12 +32,13 @@ def __init__(self, dataset_id, username=None, password=None, cache_dir=None):
if username is not None and password is not None:
logger.info(f'Using CMEMS password for user {username} from provided variables')

if cache_dir is None:
cache_dir = os.getenv('COPERNICUSMARINE_CACHE_DIRECTORY')
if cache_dir == '': # Set env variable COPERNICUSMARINE_CACHE_DIRECTORY to "" to disable cahcing
no_metadata_cache=True
else:
no_metadata_cache=False
# no_metadata_cache will be disabled from version 2.0
#if cache_dir is None:
# cache_dir = os.getenv('COPERNICUSMARINE_CACHE_DIRECTORY')
#if cache_dir == '': # Set env variable COPERNICUSMARINE_CACHE_DIRECTORY to "" to disable cahcing
# no_metadata_cache=True
#else:
# no_metadata_cache=False
if username is None:
username = os.getenv('COPERNICUSMARINE_SERVICE_USERNAME')
password = os.getenv('COPERNICUSMARINE_SERVICE_PASSWORD')
Expand Down Expand Up @@ -68,8 +69,8 @@ def __init__(self, dataset_id, username=None, password=None, cache_dir=None):
if username is None:
raise ValueError('To use CMEMS datasets, provide username and password, or store these in .netrc file in home folder or main opendrift folder with machine name "copernicusmarine". Alternatively, creadentials can be stored as environment variables COPERNICUSMARINE_SERVICE_USERNAME and COPERNICUSMARINE_SERVICE_PASSWORD.')

ds = copernicusmarine.open_dataset(dataset_id=dataset_id, username=username, password=password,
no_metadata_cache=no_metadata_cache)
ds = copernicusmarine.open_dataset(dataset_id=dataset_id, username=username, password=password)

ds['name'] = str(dataset_id)

# Run constructor of parent Reader class
Expand Down

0 comments on commit 71b903a

Please sign in to comment.