{ "cells": [ { "attachments": {}, "cell_type": "markdown", "metadata": {}, "source": [ "# The Dataset and DataArray objects used in the ECCOv4 Python package.\n", "\n", "## Objectives\n", "\n", "To introduce the two high-level data structures, `Dataset` and `DataArray`, that are used in by the `ecco_v4_py` Python package to load and store the ECCO v4 model grid parameters and state estimate variables.\n", "\n", "## Introduction\n", "\n", "The ECCO version 4 release 4 (v4r4) files are provided as NetCDF files. This tutorial shows you how to download and open these files using Python code, and takes a look at the structure of these files. The ECCO output is available as a number of **datasets** that each contain a few variables. Each dataset consists of files corresponding to a single time coordinate (monthly mean, daily mean, or snapshot). Each dataset file that represents a single time is called a **granule**.\n", "\n", "In this first tutorial we will start slowly, providing detail at every step. Later tutorials will assume knowledge of some basic operations introduced here.\n", "\n", "Let's get started.\n", "\n", "## Import external packages and modules\n", "\n", "Before using Python libraries we must import them. Usually this is done at the beginning of every Python program or interactive Juypter notebook instance but one can import a library at any point in the code. Python libraries, called **packages**, contain subroutines and/or define data structures that provide useful functionality.\n", "\n", "Before we go further, let's import some packages needed for this tutorial:" ] }, { "cell_type": "code", "execution_count": 1, "metadata": {}, "outputs": [], "source": [ "# NumPy is the fundamental package for scientific computing with Python. \n", "# It contains among other things:\n", "# a powerful N-dimensional array object\n", "# sophisticated (broadcasting) functions\n", "# tools for integrating C/C++ and Fortran code\n", "# useful linear algebra, Fourier transform, and random number capabilities\n", "# http://www.numpy.org/\n", "#\n", "# make all functions from the 'numpy' module available with the prefix 'np'\n", "import numpy as np\n", "\n", "# xarray is an open source project and Python package that aims to bring the \n", "# labeled data power of pandas to the physical sciences, by providing\n", "# N-dimensional variants of the core pandas data structures.\n", "# Our approach adopts the Common Data Model for self- describing scientific \n", "# data in widespread use in the Earth sciences: xarray.Dataset is an in-memory\n", "# representation of a netCDF file.\n", "# http://xarray.pydata.org/en/stable/\n", "#\n", "# import all function from the 'xarray' module available with the prefix 'xr'\n", "import xarray as xr\n", "\n", "# are you working in the AWS Cloud, region us-west-2?\n", "incloud_access = False" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Load the ECCO Version 4 Python package\n", "\n", "The *ecco_v4_py* is a Python package written specifically for working with ECCO NetCDF output.\n", "\n", "See the \"Getting Started\" page in the tutorial for instructions about installing the *ecco_v4_py* module on your machine." ] }, { "cell_type": "code", "execution_count": 2, "metadata": {}, "outputs": [], "source": [ "from os.path import expanduser,join,isdir\n", "\n", "## Import the ecco_v4_py library into Python\n", "## =========================================\n", "## -- If ecco_v4_py is not installed in your local Python library, \n", "## tell Python where to find it using sys.path.append.\n", "## For example, if your ecco_v4_py files are in ~/ECCOv4-py/ecco_v4_py,\n", "## you can use:\n", "# import sys\n", "# user_home_dir = expanduser('~')\n", "# ecco_v4_py_dir = join(user_home_dir,'ECCOv4-py')\n", "# if isdir(ecco_v4_py_dir):\n", "# sys.path.insert(0,ecco_v4_py_dir)\n", "\n", "import ecco_v4_py as ecco\n", "import ecco_access as ea" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "The syntax \n", "\n", "```Python\n", " import XYZ package as ABC\n", "```\n", "\n", "allows you to access all of the subroutines and/or objects in a package with perhaps a long complicated name with a shorter, easier name.\n", "\n", "Here, we import `ecco_v4_py` as `ecco` because typing `ecco` is easier than `ecco_v4_py` every time. Also, `ecco_v4_py` is actually comprised of multiple python modules and by importing just `ecco_v4_py` we can actually access all of the subroutines in those modules as well. Fancy. Furthermore, we import the `ecco_access` package using `ea` as shorthand: `import ecco_access as ea`.\n", "\n", "\n", "## Downloading and opening state estimate NetCDF files (datasets)\n", "\n", "You can access the ECCOv4r4 files through PO.DAAC, either by downloading them to your own machine, or downloading or opening them while working in the Amazon Web Services (AWS) Cloud. The [ecco_access package](https://ecco-access.readthedocs.io) helps with data access using a variety of modes; see the [ecco_access modes](https://ecco-access.readthedocs.io/ECCO_access_modes.html) tutorial for more information about each of these different modes. If you are not working in the AWS Cloud, the `download_ifspace` mode is good to use, since it will prevent download of files if they will take up more than a specified fraction of your available storage. Directories can be appended to your path using `sys.path.append`.\n", "\n", "To open ECCO v4's NetCDF files we will use the *open_mfdataset* command from the Python package [xarray](http://xarray.pydata.org/en/stable/index.html). `xarray` has the *open_dataset* routine which creates a `Dataset` object and loads the contents of the NetCDF file, including its metadata, into a data structure. The *open_mfdataset* routine does the same thing, but also concatenates multiple netCDF files with compatible dimensions and coordinates--a very handy feature!\n", "\n", "Let's download and open the monthly mean temperature/salinity files for 2010." ] }, { "cell_type": "code", "execution_count": 3, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "created download directory C:\\Users\\adelman\\Downloads\\ECCO_V4r4_PODAAC\\ECCO_L4_TEMP_SALINITY_LLC0090GRID_MONTHLY_V4R4\n", "\n", "Total number of matching granules: 12\n", "DL Progress: 100%|#########################| 12/12 [00:15<00:00, 1.29s/it]\n", "\n", "=====================================\n", "total downloaded: 208.75 Mb\n", "avg download speed: 13.48 Mb/s\n", "Time spent = 15.480218887329102 seconds\n" ] } ], "source": [ "# indicate mode of access\n", "# options are:\n", "# 'download': direct download from internet to your local machine\n", "# 'download_ifspace': like download, but only proceeds \n", "# if your machine have sufficient storage\n", "# 's3_open': access datasets in-cloud from an AWS instance\n", "# 's3_open_fsspec': use jsons generated with fsspec and \n", "# kerchunk libraries to speed up in-cloud access\n", "# 's3_get': direct download from S3 in-cloud to an AWS instance\n", "# 's3_get_ifspace': like s3_get, but only proceeds if your instance \n", "# has sufficient storage\n", "\n", "\n", "\n", "## Set top-level directory for the ECCO NetCDF files \n", "## (or json lookup files if using mode = 's3_open_fsspec')\n", "\n", "\n", "if incloud_access:\n", " access_mode = 's3_open_fsspec'\n", " download_root_dir = None\n", " jsons_root_dir = join(user_home_dir,'MZZ')\n", "else:\n", " access_mode = 'download_ifspace'\n", " download_root_dir = join(user_home_dir,'Downloads','ECCO_V4r4_PODAAC')\n", " jsons_root_dir = None\n", "\n", "\n", "\n", "ShortName = \"ECCO_L4_TEMP_SALINITY_LLC0090GRID_MONTHLY_V4R4\"\n", " \n", "# # Method 1: use ecco_podaac_access\n", "# # \n", "# # retrieve files\n", "# files_dict = ea.ecco_podaac_access(ShortName,\\\n", "# StartDate='2010-01',EndDate='2010-12',\\\n", "# mode=access_mode,\\\n", "# download_root_dir=download_root_dir,\\\n", "# jsons_root_dir=jsons_root_dir,\\\n", "# max_avail_frac=0.5)\n", "# # load file into workspace\n", "# ds = xr.open_mfdataset(files_dict[ShortName],parallel=True,\\\n", "# data_vars='minimal',coords='minimal',compat='override')\n", "\n", "# # Method 2: use ecco_podaac_to_xrdataset\n", "\n", "ds = ea.ecco_podaac_to_xrdataset(ShortName,\\\n", " StartDate='2010-01',EndDate='2010-12',\\\n", " mode=access_mode,\\\n", " download_root_dir=download_root_dir,\\\n", " jsons_root_dir=jsons_root_dir,\\\n", " max_avail_frac=0.5)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "What is *ds*? It is a `Dataset` object which is defined somewhere deep in the `xarray` package:" ] }, { "cell_type": "code", "execution_count": 4, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "xarray.core.dataset.Dataset" ] }, "execution_count": 4, "metadata": {}, "output_type": "execute_result" } ], "source": [ "type(ds)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## The Dataset object \n", "\n", "According to the xarray documentation, a [Dataset](http://xarray.pydata.org/en/stable/generated/xarray.Dataset.html) is a Python object designed as an \"in-memory representation of the data model from the NetCDF file format.\"\n", "\n", "What does that mean? NetCDF files are *self-describing* in the sense that they [include information about the data they contain](https://www.unidata.ucar.edu/software/netcdf/docs/faq.html). When `Datasets` are created by loading a NetCDF file they load all of the same data and metadata.\n", "\n", "Just as a NetCDF file can contain many variables, a `Dataset` can contain many variables. These variables are referred to as `Data Variables` in the `xarray` nomenclature.\n", "\n", "`Datasets` contain three main classes of fields:\n", "\n", "1. **Coordinates** : arrays identifying the coordinates of the data variables\n", "2. **Data Variables**: the data variable arrays and their associated coordinates\n", "3. **Attributes** : metadata describing the dataset\n", "\n", "Now that we've loaded the 2010 monthly mean files of potential temperature and salinity as the *ds* `Dataset` object, let's examine its contents. \n", "\n", "> **Note:** *You can get information about objects and their contents by typing the name of the variable and hitting **enter** in an interactive session of an IDE such as Spyder or by executing the cell of a Jupyter notebook.*\n", "\n" ] }, { "cell_type": "code", "execution_count": 5, "metadata": {}, "outputs": [ { "data": { "text/html": [ "
<xarray.Dataset> Size: 510MB\n",
"Dimensions: (i: 90, i_g: 90, j: 90, j_g: 90, k: 50, k_u: 50, k_l: 50,\n",
" k_p1: 51, tile: 13, time: 12, nv: 2, nb: 4)\n",
"Coordinates: (12/22)\n",
" * i (i) int32 360B 0 1 2 3 4 5 6 7 8 9 ... 81 82 83 84 85 86 87 88 89\n",
" * i_g (i_g) int32 360B 0 1 2 3 4 5 6 7 8 ... 81 82 83 84 85 86 87 88 89\n",
" * j (j) int32 360B 0 1 2 3 4 5 6 7 8 9 ... 81 82 83 84 85 86 87 88 89\n",
" * j_g (j_g) int32 360B 0 1 2 3 4 5 6 7 8 ... 81 82 83 84 85 86 87 88 89\n",
" * k (k) int32 200B 0 1 2 3 4 5 6 7 8 9 ... 41 42 43 44 45 46 47 48 49\n",
" * k_u (k_u) int32 200B 0 1 2 3 4 5 6 7 8 ... 41 42 43 44 45 46 47 48 49\n",
" ... ...\n",
" Zu (k_u) float32 200B dask.array<chunksize=(50,), meta=np.ndarray>\n",
" Zl (k_l) float32 200B dask.array<chunksize=(50,), meta=np.ndarray>\n",
" time_bnds (time, nv) datetime64[ns] 192B dask.array<chunksize=(1, 2), meta=np.ndarray>\n",
" XC_bnds (tile, j, i, nb) float32 2MB dask.array<chunksize=(13, 90, 90, 4), meta=np.ndarray>\n",
" YC_bnds (tile, j, i, nb) float32 2MB dask.array<chunksize=(13, 90, 90, 4), meta=np.ndarray>\n",
" Z_bnds (k, nv) float32 400B dask.array<chunksize=(50, 2), meta=np.ndarray>\n",
"Dimensions without coordinates: nv, nb\n",
"Data variables:\n",
" THETA (time, k, tile, j, i) float32 253MB dask.array<chunksize=(1, 25, 7, 45, 45), meta=np.ndarray>\n",
" SALT (time, k, tile, j, i) float32 253MB dask.array<chunksize=(1, 25, 7, 45, 45), meta=np.ndarray>\n",
"Attributes: (12/62)\n",
" acknowledgement: This research was carried out by the Jet...\n",
" author: Ian Fenty and Ou Wang\n",
" cdm_data_type: Grid\n",
" comment: Fields provided on the curvilinear lat-l...\n",
" Conventions: CF-1.8, ACDD-1.3\n",
" coordinates_comment: Note: the global 'coordinates' attribute...\n",
" ... ...\n",
" time_coverage_duration: P1M\n",
" time_coverage_end: 2010-02-01T00:00:00\n",
" time_coverage_resolution: P1M\n",
" time_coverage_start: 2010-01-01T00:00:00\n",
" title: ECCO Ocean Temperature and Salinity - Mo...\n",
" uuid: f4291248-4181-11eb-82cd-0cc47a3f446d<xarray.DataArray 'XC' (tile: 13, j: 90, i: 90)> Size: 421kB\n",
"dask.array<open_dataset-XC, shape=(13, 90, 90), dtype=float32, chunksize=(13, 90, 90), chunktype=numpy.ndarray>\n",
"Coordinates:\n",
" * i (i) int32 360B 0 1 2 3 4 5 6 7 8 9 ... 81 82 83 84 85 86 87 88 89\n",
" * j (j) int32 360B 0 1 2 3 4 5 6 7 8 9 ... 81 82 83 84 85 86 87 88 89\n",
" * tile (tile) int32 52B 0 1 2 3 4 5 6 7 8 9 10 11 12\n",
" XC (tile, j, i) float32 421kB dask.array<chunksize=(13, 90, 90), meta=np.ndarray>\n",
" YC (tile, j, i) float32 421kB dask.array<chunksize=(13, 90, 90), meta=np.ndarray>\n",
"Attributes:\n",
" long_name: longitude of tracer grid cell center\n",
" units: degrees_east\n",
" coordinate: YC XC\n",
" bounds: XC_bnds\n",
" comment: nonuniform grid spacing\n",
" coverage_content_type: coordinate\n",
" standard_name: longitude