Streaming data from NASA's Earth Surface Minteral Dust Source Investigation (EMIT)¶
This is a proof of concept notebook to demonstrate how earthaccess can facilitate the use of cloud hosted data from NASA using xarray and holoviews. For a formal tutorial on EMIT please visit the official repository where things are explained in detail. EMIT Science Tutorial
Prerequisites
- NASA EDL credentials
- Openscapes Conda environment installed
- For direct access this notebook should run in AWS
IMPORTANT: This notebook should run out of AWS but is not recommended as streaming HDF5 data is slow out of region
from pprint import pprint
import earthaccess
import xarray as xr
print(f"using earthaccess version {earthaccess.__version__}")
auth = earthaccess.login()
--------------------------------------------------------------------------- TypeError Traceback (most recent call last) Cell In[1], line 3 1 from pprint import pprint ----> 3 import earthaccess 4 import xarray as xr 6 print(f"using earthaccess version {earthaccess.__version__}") File ~/checkouts/readthedocs.org/user_builds/earthaccess/checkouts/1298/earthaccess/__init__.py:5 2 import threading 3 from typing import Optional ----> 5 from .api import ( 6 auth_environ, 7 collection_query, 8 download, 9 get_edl_token, 10 get_fsspec_https_session, 11 get_requests_https_session, 12 get_s3_credentials, 13 get_s3_filesystem, 14 get_s3fs_session, 15 granule_query, 16 login, 17 open, # noqa: A004 18 search_data, 19 search_datasets, 20 search_services, 21 status, 22 ) 23 from .auth import Auth 24 from .search import DataCollection, DataCollections, DataGranule, DataGranules File ~/checkouts/readthedocs.org/user_builds/earthaccess/checkouts/1298/earthaccess/api.py:20 18 from .auth import Auth 19 from .results import DataCollection, DataGranule, Results ---> 20 from .search import CollectionQuery, DataCollections, DataGranules, GranuleQuery 21 from .store import Store 22 from .system import PROD, System File ~/checkouts/readthedocs.org/user_builds/earthaccess/checkouts/1298/earthaccess/search.py:27 23 type FloatLike = str | SupportsFloat 24 type PointLike = tuple[FloatLike, FloatLike] ---> 27 class DataCollections(CollectionQuery): 28 """Query CMR for collection metadata. 29 30 ???+ Info (...) 33 the response has to be in umm_json to use the result classes. 34 """ 36 _fields: list[str] | None = None File ~/checkouts/readthedocs.org/user_builds/earthaccess/checkouts/1298/earthaccess/search.py:84, in DataCollections() 79 raise RuntimeError(ex.response.text) from ex 81 return int(response.headers["CMR-Hits"]) 83 @override ---> 84 def get(self, limit: int = 2000) -> Results[DataCollection]: 85 """Get all the collections (datasets) that match with our current parameters 86 up to some limit, even if spanning multiple pages. 87 (...) 101 RuntimeError: The CMR query failed. 102 """ 103 return Results( 104 [ 105 DataCollection(collection, self._fields) (...) 108 query=self, 109 ) TypeError: type 'Results' is not subscriptable
Searching for the dataset with .search_datasets()¶
Note: See our API docs for details
results = earthaccess.search_datasets(short_name="EMITL2ARFL", cloud_hosted=True)
# Let's print our datasets
for dataset in results:
pprint(dataset.summary())
--------------------------------------------------------------------------- NameError Traceback (most recent call last) Cell In[2], line 1 ----> 1 results = earthaccess.search_datasets(short_name="EMITL2ARFL", cloud_hosted=True) 3 # Let's print our datasets 4 for dataset in results: NameError: name 'earthaccess' is not defined
Searching for the data with .search_data() over Ecuador¶
# ~Ecuador = -82.05,-3.17,-76.94,-0.52
granules = earthaccess.search_data(
short_name="EMITL2ARFL",
bounding_box=(-82.05, -3.17, -76.94, -0.52),
count=10,
)
print(len(granules))
--------------------------------------------------------------------------- NameError Traceback (most recent call last) Cell In[3], line 2 1 # ~Ecuador = -82.05,-3.17,-76.94,-0.52 ----> 2 granules = earthaccess.search_data( 3 short_name="EMITL2ARFL", 4 bounding_box=(-82.05, -3.17, -76.94, -0.52), 5 count=10, 6 ) 7 print(len(granules)) NameError: name 'earthaccess' is not defined
earthaccess can print a preview of the data using the metadata from CMR¶
Note: there is a bug in earthaccess where the reported size of the granules are always 0, fix is coming next week
granules[7]
--------------------------------------------------------------------------- NameError Traceback (most recent call last) Cell In[4], line 1 ----> 1 granules[7] NameError: name 'granules' is not defined
Streaming data from S3 with fsspec¶
Opening the data with earthaccess.open() and accessing the NetCDF as if it was local
If we run this code in AWS(us-west-2), earthaccess can use direct S3 links. If we run it out of AWS, earthaccess can only use HTTPS links. Direct S3 access for NASA data is only allowed in region.
# open() accepts a list of results or a list of links
file_handlers = earthaccess.open(granules)
file_handlers
--------------------------------------------------------------------------- NameError Traceback (most recent call last) Cell In[5], line 2 1 # open() accepts a list of results or a list of links ----> 2 file_handlers = earthaccess.open(granules) 3 file_handlers NameError: name 'earthaccess' is not defined
%%time
# we can use any file from the array
file_p = file_handlers[4]
refl = xr.open_dataset(file_p)
wvl = xr.open_dataset(file_p, group="sensor_band_parameters")
loc = xr.open_dataset(file_p, group="location")
ds = xr.merge([refl, loc])
ds = ds.assign_coords(
{
"downtrack": (["downtrack"], refl.downtrack.data),
"crosstrack": (["crosstrack"], refl.crosstrack.data),
**wvl.variables,
},
)
ds
CPU times: user 10 μs, sys: 0 ns, total: 10 μs Wall time: 13.4 μs
--------------------------------------------------------------------------- NameError Traceback (most recent call last) Cell In[6], line 1 ----> 1 get_ipython().run_cell_magic('time', '', '\n# we can use any file from the array\nfile_p = file_handlers[4]\n\nrefl = xr.open_dataset(file_p)\nwvl = xr.open_dataset(file_p, group="sensor_band_parameters")\nloc = xr.open_dataset(file_p, group="location")\nds = xr.merge([refl, loc])\nds = ds.assign_coords(\n {\n "downtrack": (["downtrack"], refl.downtrack.data),\n "crosstrack": (["crosstrack"], refl.crosstrack.data),\n **wvl.variables,\n },\n)\n\nds\n') File ~/checkouts/readthedocs.org/user_builds/earthaccess/envs/1298/lib/python3.12/site-packages/IPython/core/interactiveshell.py:2565, in InteractiveShell.run_cell_magic(self, magic_name, line, cell) 2563 with self.builtin_trap: 2564 args = (magic_arg_s, cell) -> 2565 result = fn(*args, **kwargs) 2567 # The code below prevents the output from being displayed 2568 # when using magics with decorator @output_can_be_silenced 2569 # when the last Python token in the expression is a ';'. 2570 if getattr(fn, magic.MAGIC_OUTPUT_CAN_BE_SILENCED, False): File ~/checkouts/readthedocs.org/user_builds/earthaccess/envs/1298/lib/python3.12/site-packages/IPython/core/magics/execution.py:1470, in ExecutionMagics.time(self, line, cell, local_ns) 1468 if interrupt_occured: 1469 if exit_on_interrupt and captured_exception: -> 1470 raise captured_exception 1471 return 1472 return out File ~/checkouts/readthedocs.org/user_builds/earthaccess/envs/1298/lib/python3.12/site-packages/IPython/core/magics/execution.py:1434, in ExecutionMagics.time(self, line, cell, local_ns) 1432 st = clock2() 1433 try: -> 1434 exec(code, glob, local_ns) 1435 out = None 1436 # multi-line %%time case File <timed exec>:2 NameError: name 'file_handlers' is not defined
Plotting non orthorectified data¶
Use the following code to plot the Panel widget when you run this code on AWS us-west-2
import holoviews as hv
import hvplot.xarray
import numpy as np
import panel as pn
pn.extension()
# Find band nearest to value of 850 nm (NIR)
b850 = np.nanargmin(abs(ds["wavelengths"].values - 850))
ref_unc = ds["reflectance_uncertainty"]
image = ref_unc.sel(bands=b850).hvplot("crosstrack", "downtrack", cmap="viridis")
stream = hv.streams.Tap(source=image, x=255, y=484)
def wavelengths_histogram(x, y):
histo = ref_unc.sel(crosstrack=x, downtrack=y, method="nearest").hvplot(
x="wavelengths", color="green"
)
return histo
tap_dmap = hv.DynamicMap(wavelengths_histogram, streams=[stream])
pn.Column(image, tap_dmap)