Commit 44b86435 authored by Fabian Wachsmann's avatar Fabian Wachsmann
Browse files

Merge branch 'setup-for-ci' into 'master'

Setup for ci

See merge request !75
parents 2c4a1ae1 c7dfd64f
Pipeline #19409 passed with stages
in 28 minutes and 28 seconds
......@@ -425,7 +425,7 @@
"cell_type": "markdown",
"metadata": {},
"source": [
"The data base is loaded into an underlying `panda`s dataframe which we can access with `col.df`. `col.df.head()` displays the first rows of the table:"
"The data base is loaded into an underlying `panda`s dataframe which we can access with `esm_col.df`. `esm_col.df.head()` displays the first rows of the table:"
]
},
{
......@@ -639,12 +639,14 @@
"source": [
"### How to load more columns\n",
"\n",
"If you work remotely away from the data, you can use the **opendap_url**'s to access the subset of interest for all files published at DKRZ. The opendap_url is an *additional* column that can also be loaded.\n",
"Intake allows to load only a subset of the columns that is inside the **intake-esm** catalog. Since the memory usage of **intake-esm** is high, the default columns are only a subset from all possible columns. Sometimes, other columns are of interest:\n",
"\n",
"If you work remotely away from the data, you can use the **opendap_url**'s to access the subset of interest for all files published at DKRZ. The *opendap_url* is an *additional* column that can also be loaded.\n",
"\n",
"We can define 3 different column name types for the usage of intake catalogs:\n",
"\n",
"1. **Default** attributes which are loaded from the main catalog and which can be seen via `_entries[CATNAME]._open_args`.\n",
"2. **Overall** attributes or **template** attributes which should be defined for **ALL** catalogs at DKRZ (exceptions excluded). At DKRZ, we use the newly defined **Cataloonie** scheme template which can be found via `dkrz_catalog.metadata[\"parameters\"][\"cataloonie_columns\"]`\n",
"2. **Overall** attributes or **template** attributes which should be defined for **ALL** catalogs at DKRZ (exceptions excluded). At DKRZ, we use the newly defined **Cataloonie** scheme template which can be found via `dkrz_catalog.metadata[\"parameters\"][\"cataloonie_columns\"]`. With these template attributes, there may be redundancy in the columns. They exist to simplify merging catalogs across projects.\n",
"3. **Additional** attributes which are not necessary to identify a single asset but helpful for users. You can find these via\n",
"\n",
"`dkrz_catalog.metadata[\"parameters\"][\"additional_PROJECT_columns\"]`\n",
......@@ -670,13 +672,6 @@
"```"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"There is a lot of redundancy in the columns. That is because they exist to be conform to other kind of standards. This will simplify merging catalogs across projects."
]
},
{
"cell_type": "markdown",
"metadata": {},
......@@ -711,6 +706,14 @@
"esm_col=dkrz_catalog.dkrz_cmip6_disk(csv_kwargs=dict(usecols=cols))"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"- ⭐ The customization of catalog columns allows highest flexibility for intake users. \n",
"- ⭐ In theory, we could add many more columns with additional information because ot all have to be loaded from the data base."
]
},
{
"cell_type": "markdown",
"metadata": {},
......@@ -750,7 +753,7 @@
"query = dict(\n",
" variable_id=\"tas\",\n",
" table_id=\"Amon\",\n",
" source_id=\"MPI-ESM1-2-HR\",\n",
" source_id=\"MPI-ESM1-2-LR\",\n",
" experiment_id=\"historical\")\n",
"cat = esm_col.search(**query)\n",
"cat"
......@@ -846,13 +849,31 @@
"- The `time_range` column was used to **concat** data along the `time` dimension\n",
"- The `member_id` column was used to generate a new dimension\n",
"\n",
"The underlying `dask` package will only load the data into memory if needed."
"The underlying `dask` package will only load the data into memory if needed. Note that attributes which disagree from file to file, e.g. *tracking_id*, are excluded from the dataset."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"How **intake-esm** should open and aggregate the assets is configured in the *aggregation_control* part of the description:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"print(esm_col.esmcol_data[\"aggregation_control\"][\"aggregations\"])"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Columns can be defined for appending or creating new dimensions. The *options* are keyword arguments for xarray.\n",
"\n",
"They **keys** of the dictionary are made with column values defined in the *aggregation_control* of the **intake-esm** catalog. These will determine the **key_template**. The corresponding commands are:"
]
},
......@@ -906,7 +927,25 @@
"cell_type": "markdown",
"metadata": {},
"source": [
"#### Pangeo's data store\n",
"### Troubleshooting\n",
"\n",
"The variables are collected in **one** dataset. This requires that **the dimensions and coordinates must be the same over all files**. Otherwise, xarray cannot merge these together.\n",
"\n",
"For CMIP6, most of the variables collected in one **table_id** should be on the same dimensions and coordinates. Unfortunately, there are exceptions.: \n",
"\n",
"- a few variables are requested for *time slices* only. \n",
"- sometimes models use different dimension names from file to file\n",
"\n",
"Using the [preprocessing](https://tutorials.dkrz.de/tutorial_intake-4-preprocessing-derived-vars.html#use-preprocessing-when-opening-assets-and-creating-datasets) keyword argument can help to rename dimensions before merging.\n",
"\n",
"For Intake providers: the more information on the dimensions and coordinates provided already in the catalog, the better the aggregation control."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Pangeo's data store\n",
"\n",
"Let's have a look into Pangeo's ESM Collection as well. This is accessible via cloud from everywhere - you only need internet to load data. We use the same `query` as in the example before."
]
......
%% Cell type:markdown id: tags:
# Intake I - find, browse and access `intake-esm` collections
%% Cell type:markdown id: tags:
```{admonition} Overview
:class: dropdown
![Level](https://img.shields.io/badge/Level-Introductory-green.svg)
🎯 **objectives**: Learn how to use `intake` to find, browse and access `intake-esm` ESM-collections
⌛ **time_estimation**: "30min"
☑️ **requirements**: `intake_esm.__version__ >= 2021.8.17`, at least 10GB memory.
© **contributors**: k204210
⚖ **license**:
```
%% Cell type:markdown id: tags:
```{admonition} Agenda
:class: tip
In this part, you learn
1. [Motivation of intake-esm](#motivation)
1. [Features of intake and intake-esm](#features)
1. [Browse through catalogs](#browse)
1. [Data access via intake-esm](#dataaccess)
```
%% Cell type:markdown id: tags:
<a class="anchor" id="motivation"></a>
We follow here the guidance presented by `intake-esm` on its [repository](https://intake-esm.readthedocs.io/en/latest/user-guide/cmip6-tutorial.html).
## Motivation of intake-esm
> Simulations of the Earth’s climate and weather generate huge amounts of data. These data are often persisted on different storages in a variety of formats (netCDF, zarr, etc...). Finding, investigating, loading these data assets into compute-ready data containers costs time and effort. The data user needs to know what data sets are available, the attributes describing each data set, before loading a specific data set and analyzing it.
> `Intake-esm` addresses these issues by providing necessary functionality for **searching, discovering, data access and data loading**.
%% Cell type:markdown id: tags:
For intake users, many data preparation tasks **are no longer necessary**. They do not need to know:
- 🌍 where data is saved
- 🪧 how data is saved
- 📤 how data should be loaded
but still can search, discover, access and load data of a project.
%% Cell type:markdown id: tags:
<a class="anchor" id="features"></a>
## Features of intake and intake-esm
Intake is a generic **cataloging system** for listing data sources. As a plugin, `intake-esm` is built on top of `intake`, `pandas`, and `xarray` and configures `intake` such that it is able to also **load and process** ESM data.
- display catalogs as clearly structured tables 📄 inside jupyter notebooks for easy investigation
- browse 🔍 through the catalog and select your data without
- being next to the data (e.g. logged in on dkrz's luv)
- knowing the project's data reference syntax i.e. the storage tree hierarchy and path and file name templates
- open climate data in an analysis ready dictionary of `xarray` datasets 🎁
%% Cell type:markdown id: tags:
All required information for searching, accessing and loading the catalog's data is configured within the catalogs:
- 🌍 where data is saved
* users can browse data without knowing the data storage platform including e.g. the root path of the project and the directory syntax
* data of different platforms (cloud or disk) can be combined in one catalog
* on mid term, intake catalogs can be **a single point of access**
- 🪧 how data is saved
* users can work with a *xarray* dataset representation of the data no matter whether it is saved in **grb, netcdf or zarr** format.
* catalogs can contain more information an therefore more search facets than obvious from names and pathes of the data.
- 📤 how data should be loaded
* users work with an **aggregated** *xarray* dataset representation which merges files/assets perfectly fitted to the project's data model design.
* with *xarray* and the underlying *dask* library, data which are **larger than the RAM** can be loaded
%% Cell type:markdown id: tags:
In this tutorial, we load a CMIP6 catalog which contains all data from the pool on DKRZ's mistral disk storage.
CMIP6 is the 6th phase of the Coupled Model Intercomparison Project and builds the data base used in the IPCC AR6.
The CMIP6 catalog contains all data that is published or replicated at the ESGF node at DKRZ.
%% Cell type:markdown id: tags:
<a class="anchor" id="terminology"></a>
## Terminology: **Catalog**, **Catalog file** and **Collection**
We align our wording with `intake`'s [*glossary*](https://intake.readthedocs.io/en/latest/glossary.html) which is still evolving. The names overlap with other definitions, making it difficult to keep track. Here we try to give an overview of the hierarchy of catalog terms:
- a **top level catalog file** 📋 is the **main** catalog of an institution which will be opened first. It contains other project [*catalogs*](#catalog) 📖 📖 📖. Such catalogs can be assigned an [*intake driver*](#intakedriver) which is used to open and load the catalog within the top level catalog file. Technically, a catalog file 📋 is <a class="anchor" id="catalogfile"></a>
- is a `.yaml` file
- can be opened with `open_catalog`, e.g.:
```python
intake.open_catalog(["https://dkrz.de/s/intake"])
```
- **intake driver**s also named **plugin**s are specified for [*catalogs*](#catalog) becaues they load specific data sets. <a class="anchor" id="intakedriver"></a>
%% Cell type:markdown id: tags:
- a **catalog** 📖 (or collection) is defined by two parts: <a class="anchor" id="catalog"></a>
- a **description** of a group of data sets. It describes how to *load* **assets** of the data set(s) with the specified [driver](#intakedriver). This group forms an entity. E.g., all CMIP6 data sets can be collected in a catalog. <a class="anchor" id="description"></a>
- an **asset** is most often a file. <a class="anchor" id="asset"></a>
- a **collection** of all [assets](#asset) of the data set(s). <a class="anchor" id="collection"></a>
- the collection can be included in the catalog or separately saved in a **data base** 🗂. In the latter case, the catalog references the data base, e.g.:
```json
"catalog_file": "/mnt/lustre02/work/ik1017/Catalogs/dkrz_cmip6_disk.csv.gz"
```
```{note}
The term *collection* is often used synonymically for [catalog](#catalog).
```
%% Cell type:markdown id: tags:
- a *intake-esm* catalog 📖 is a `.json` file and can be opened with intake-esm's function `intake.open_esm_datastore()`, e.g:
```python
intake.open_esm_datastore("https://gitlab.dkrz.de/data-infrastructure-services/intake-esm/-/raw/master/esm-collections/cloud-access/dkrz_cmip6_disk.json")
```
%% Cell type:code id: tags:
``` python
#note that intake_esm is imported with `import intake` as a plugin
import intake
```
%% Cell type:markdown id: tags:
<a class="anchor" id="browse"></a>
## Open and browse through catalogs
We begin with using only *intake* functions for catalogs. Afterwards, we continue with concrete *intake-esm* utilites.
intake **opens** catalog-files in `yaml` format. These contain information about additonal sources: other catalogs/collections which will be loaded with specific *plugins*/*drivers*. The command is `open_catalog`.
<mark> You only need to remember one URL as the *single point of access* for DKRZ's intake catalogs: The DKRZ top level catalog can be accessed via dkrz.de/s/intake . Intake will only follow this *redirect* if a specific parser is activated. This can be done by providing the url in a list.</mark>
%% Cell type:code id: tags:
``` python
#dkrz_catalog=intake.open_catalog(["https://dkrz.de/s/intake"])
#
#only for the web page we need to take the original link:
dkrz_catalog=intake.open_catalog(["https://gitlab.dkrz.de/data-infrastructure-services/intake-esm/-/raw/master/esm-collections/cloud-access/dkrz_catalog.yaml"])
```
%% Cell type:markdown id: tags:
```{note}
Right now, two versions of the top level catalog file exist: One for accessing the catalog via [cloud](https://gitlab.dkrz.de/data-infrastructure-services/intake-esm/-/raw/master/esm-collections/cloud_access/dkrz_catalog.yaml), one for via [disk](https://gitlab.dkrz.de/data-infrastructure-services/intake-esm/-/raw/master/esm-collections/disk_access/dkrz_catalog.yaml). They however contain **the same content**.
```
%% Cell type:markdown id: tags:
We can look into the catalog with `print` and `list`
%% Cell type:markdown id: tags:
Over the time, many collections have been created. `dkrz_catalog` is a **main** catalog prepared to keep an overview of all other collections. `list` shows all sub **project catalogs** which are available at DKRZ.
%% Cell type:code id: tags:
``` python
list(dkrz_catalog)
```
%% Cell type:markdown id: tags:
All these catalogs are **intake-esm** catalogs. You can find this information via the `_entries` attribute. The line `plugin: ['esm_datastore']
` refers to **intake-esm**'s function `open_esm_datastore()`.
%% Cell type:code id: tags:
``` python
print(dkrz_catalog._entries)
```
%% Cell type:markdown id: tags:
The DKRZ ESM-Collections follow a name template:
`dkrz_${project}_${store}[_${auxiliary_catalog}]`
where
- **project** can be one of the *model intercomparison project*, e.g. `cmip6`, `cmip5`, `cordex`, `era5` or `mpi-ge`.
- **store** is the data store and can be one of:
- `disk`: DKRZ holds a lot of data on a consortial disk space on the file system of the High Performance Computer (HPC) where it is accessible for every HPC user. Working next to the data on the file system will be the fastest way possible.
- `cloud`: A small subset is transferred into DKRZ's cloud in order to test the performance. swift is DKRZ's cloud storage.
- `archive`: A lot of data exists in the band archive of DKRZ. Before it can be accessed, it has to be retrieved. Therefore, catalogs for `hsm` are limited in functionality but still convenient for data browsing.
- **auxiliary_catalog** can be *grid*
%% Cell type:markdown id: tags:
**Why that convention?**:
- **dkrz**: Assume you work with internation collections. Than it may become important that you know from where the data comes, e.g. if only pathes on a local file system are given as the locations of the data.
- **project**: Project's data standards differ from each other so that different catalog attributes are required to identify a single asset in a project data base.
- **store**: Intake-esm cannot load data from all stores. Before data from the archive can be accessed, it has to be retrieved. Therefore, the opening function is not working for catalog merged for all stores.
%% Cell type:markdown id: tags:
**Best practice for naming catalogs**:
- Use small letters for all values
- Do **NOT** use `_` as a separator in values
- Do not repeat values of other attributes ("dkrz_dkrz-dyamond")
%% Cell type:markdown id: tags:
We could directly start to work with **two intake catalog** at the same time.
Let's have a look into a master catalog of [Pangeo](https://pangeo.io/):
%% Cell type:code id: tags:
``` python
pangeo=intake.open_catalog("https://raw.githubusercontent.com/pangeo-data/pangeo-datastore/master/intake-catalogs/master.yaml")
```
%% Cell type:code id: tags:
``` python
pangeo
```
%% Cell type:code id: tags:
``` python
list(pangeo)
```
%% Cell type:markdown id: tags:
While DKRZ's master catalog has one sublevel, Pangeo's is a nested one. We can access another `yaml` catalog which is also a **parent** catalog by simply:
%% Cell type:code id: tags:
``` python
pangeo.climate
```
%% Cell type:markdown id: tags:
Pangeo's ESM collections are one level deeper in the catalog tree:
%% Cell type:code id: tags:
``` python
list(pangeo.climate)
```
%% Cell type:markdown id: tags:
### The `intake-esm` catalogs
We now look into a catalog which is opened by the plugin `intake-esm`.
> An ESM (Earth System Model) collection file is a `JSON` file that conforms to the ESM Collection Specification. When provided a link/path to an esm collection file, intake-esm establishes a link to a database (`CSV` file) that contains data assets locations and associated metadata (i.e., which experiment, model, the come from).
Since the data base of the CMIP6 ESM Collection is about 100MB in compressed format, it takes up to a minute to load the catalog.
%% Cell type:markdown id: tags:
```{note}
The project catalogs contain only valid and current project data. They are constantly updated.
If your work is based on a catalog and a subset of the data from it, be sure to save that subset so you can later compare your database to the most current catalog.
```
%% Cell type:code id: tags:
``` python
esm_col=dkrz_catalog.dkrz_cmip6_disk
print(esm_col)
```
%% Cell type:markdown id: tags:
`intake-esm` gives us an overview over the content of the ESM collection. The ESM collection is a data base described by specific attributes which are technically columns. Each project data standard is the basis for the columns and used to parse information given by the path and file names.
The pure display of `esm_col` shows us the number of unique values in each column. Since each `uri` refers to one file, we can conclude that the DKRZ-CMIP6 ESM Collection contains **6.1 Mio Files** in 2022.
%% Cell type:markdown id: tags:
The data base is loaded into an underlying `panda`s dataframe which we can access with `col.df`. `col.df.head()` displays the first rows of the table:
The data base is loaded into an underlying `panda`s dataframe which we can access with `esm_col.df`. `esm_col.df.head()` displays the first rows of the table:
%% Cell type:code id: tags:
``` python
esm_col.df.head()
```
%% Cell type:markdown id: tags:
We can find out details about `esm_col` with the object's attributes. `esm_col.esmcol_data` contains all information given in the `JSON` file. We can also focus on some specific attributes.
%% Cell type:code id: tags:
``` python
#esm_col.esmcol_data
```
%% Cell type:code id: tags:
``` python
print("What is this catalog about? \n" + esm_col.esmcol_data["description"])
#
print("The link to the data base: "+ esm_col.esmcol_data["catalog_file"])
```
%% Cell type:markdown id: tags:
Advanced: To find out how many datasets are available, we can use pandas functions (drop columns that are irrelevant for a dataset, drop the duplicates, keep one):
%% Cell type:code id: tags:
``` python
cat = esm_col.df.drop(['uri','time_range'],1).drop_duplicates(keep="first")
print(len(cat))
```
%% Cell type:markdown id: tags:
### Browse through the data of the ESM collection
%% Cell type:markdown id: tags:
You will browse the collection technically by setting values the **column names** of the underlying table. Per default, the catalog was loaded with all cmip6 attributes/columns that define the CMIP6 data standard:
%% Cell type:code id: tags:
``` python
esm_col.df.columns
```
%% Cell type:markdown id: tags:
These are configured in the top level catalog so you <mark> do not need to open the catalog to see the columns </mark>
%% Cell type:code id: tags:
``` python
dkrz_catalog._entries["dkrz_cmip6_disk"]._open_args
```
%% Cell type:markdown id: tags:
Most of the time, we want to set more than one attribute for a search. Therefore, we define a query `dict`ionary and use the `search` function of the `esm_col` object. In the following case, we look for temperature at surface in monthly resolution for 3 different experiments:
%% Cell type:code id: tags:
``` python
query = dict(
variable_id="tas",
table_id="Amon",
experiment_id=["piControl", "historical", "ssp370"])
# piControl = pre-industrial control, simulation to represent a stable climate from 1850 for >100 years.
# historical = historical Simulation, 1850-2014
# ssp370 = Shared Socioeconomic Pathways (SSPs) are scenarios of projected socioeconomic global changes. Simulation covers 2015-2100
cat = esm_col.search(**query)
```
%% Cell type:code id: tags:
``` python
cat
```
%% Cell type:markdown id: tags:
We could also use *Wildcards*. For example, in order to find out which ESMs of the institution *MPI-M* have produced data for our subset:
%% Cell type:code id: tags:
``` python
cat.search(source_id="MPI-ES*")
```
%% Cell type:markdown id: tags:
We can find out which models have submitted data for at least one of them by:
%% Cell type:code id: tags:
``` python
cat.unique(["source_id"])
```
%% Cell type:markdown id: tags:
If we instead look for the models that have submitted data for ALL experiments, we use the `require_all_on` keyword argument:
%% Cell type:code id: tags:
``` python
cat = esm_col.search(require_all_on=["source_id"], **query)
cat.unique(["source_id"])
```
%% Cell type:markdown id: tags:
Note that only the combination of a `variable_id` and a `table_id` is unique in CMIP6. If you search for `tas` in all tables, you will find many entries more:
%% Cell type:code id: tags:
``` python
query = dict(
variable_id="tas",
# table_id="Amon",
experiment_id=["piControl", "historical", "ssp370"])
cat = esm_col.search(**query)
cat.unique(["table_id"])
```
%% Cell type:markdown id: tags:
Be careful when you search for specific time slices. Each frequency is connected with a individual name template for the filename. If the data is yearly, you have YYYY-YYYY whereas you have YYYYMM-YYYYMM for monthly data.
%% Cell type:markdown id: tags:
### How to load more columns
If you work remotely away from the data, you can use the **opendap_url**'s to access the subset of interest for all files published at DKRZ. The opendap_url is an *additional* column that can also be loaded.
Intake allows to load only a subset of the columns that is inside the **intake-esm** catalog. Since the memory usage of **intake-esm** is high, the default columns are only a subset from all possible columns. Sometimes, other columns are of interest:
If you work remotely away from the data, you can use the **opendap_url**'s to access the subset of interest for all files published at DKRZ. The *opendap_url* is an *additional* column that can also be loaded.
We can define 3 different column name types for the usage of intake catalogs:
1. **Default** attributes which are loaded from the main catalog and which can be seen via `_entries[CATNAME]._open_args`.
2. **Overall** attributes or **template** attributes which should be defined for **ALL** catalogs at DKRZ (exceptions excluded). At DKRZ, we use the newly defined **Cataloonie** scheme template which can be found via `dkrz_catalog.metadata["parameters"]["cataloonie_columns"]`
2. **Overall** attributes or **template** attributes which should be defined for **ALL** catalogs at DKRZ (exceptions excluded). At DKRZ, we use the newly defined **Cataloonie** scheme template which can be found via `dkrz_catalog.metadata["parameters"]["cataloonie_columns"]`. With these template attributes, there may be redundancy in the columns. They exist to simplify merging catalogs across projects.
3. **Additional** attributes which are not necessary to identify a single asset but helpful for users. You can find these via
`dkrz_catalog.metadata["parameters"]["additional_PROJECT_columns"]`
So, for CMIP6 there are:
%% Cell type:code id: tags:
``` python
dkrz_catalog.metadata["parameters"]["additional_cmip6_columns"]
```
%% Cell type:markdown id: tags:
```{tip}
You may find *variable_id*s in the catalog which are not obvious or abbrevations for a clear variable name. In that cases you would need additional information like a *long_name* of the variable. For CMIP6, we provided the catalog with this `long_name` so you could add it as a column.
```
%% Cell type:markdown id: tags:
There is a lot of redundancy in the columns. That is because they exist to be conform to other kind of standards. This will simplify merging catalogs across projects.
%% Cell type:markdown id: tags:
So, this is the instruction how to open the catalog with additional columns:
1. create a combination of all your required columns:
%% Cell type:code id: tags:
``` python
cols=dkrz_catalog._entries["dkrz_cmip6_disk"]._open_args["csv_kwargs"]["usecols"]+["opendap_url"]
```
%% Cell type:markdown id: tags:
2. open the **dkrz_cmip6_disk** catalog with the `csv_kwargs` keyword argument in this way:
%% Cell type:code id: tags:
``` python
esm_col=dkrz_catalog.dkrz_cmip6_disk(csv_kwargs=dict(usecols=cols))
```
%% Cell type:markdown id: tags:
- ⭐ The customization of catalog columns allows highest flexibility for intake users.
- ⭐ In theory, we could add many more columns with additional information because ot all have to be loaded from the data base.
%% Cell type:markdown id: tags:
```{warning}
The number of columns determines the required memory.
```
%% Cell type:markdown id: tags:
```{tip}
If you work from remote and also want to access the data remotely, load the *opendap_url* column.
```
%% Cell type:markdown id: tags:
<a class="anchor" id="dataaccess"></a>
## Access and load data of the ESM collection
With the power of `xarray`, `intake` can load your subset into a `dict`ionary of datasets. We therefore focus on the data of `MPI-ESM1-2-LR`:
%% Cell type:code id: tags:
``` python
#case insensitive?
query = dict(
variable_id="tas",
table_id="Amon",
source_id="MPI-ESM1-2-HR",
source_id="MPI-ESM1-2-LR",
experiment_id="historical")
cat = esm_col.search(**query)
cat
```
%% Cell type:markdown id: tags:
You can find out which column intake uses to access the data via the following keyword:
%% Cell type:code id: tags:
``` python
print(cat.path_column_name)
```
%% Cell type:markdown id: tags:
As we are working with the *_disk* catalog, **uri** contains *pathes* to the files on filesystem. If you are working from remote, you would have
- to change the catalog's attribute `path_column_name` to *opendap_url*.
- to reassign the `format` column from *netcdf* to *opendap*
as follows:
%% Cell type:code id: tags:
``` python
#cat.path_column_name="opendap_url"
#newdf=cat.df.copy()
#newdf.loc[:,"format"]="opendap"
#cat.df=newdf
```
%% Cell type:markdown id: tags:
**Intake-ESM** natively supports the following data formats or access formats (since opendap is not really a file format):
- netcdf
- opendap
- zarr
You can also open **grb** data but right now only by specifying xarray's attribute *engine* in the *open* function which is defined in the following. I.e., it does not make a difference if you specify **grb** as format.
You can find an example in the *era5* notebook.
%% Cell type:markdown id: tags:
The function to open data is `to_dataset_dict`.
We recommend to set a keyword argument `cdf_kwargs` for the chunk size of the variable's data array. Otherwise, `xarray` may choose too large chunks. Most often, your data contains a time dimension so that you could set `cdf_kwargs={"chunks":{"time":1}}`.
If your collection contains **zarr** formatted data, you need to add another keyword argument `zarr_kwargs`. <mark> The trick is: You can just specify both. Intake knows from the `format` column which *kwargs* should be taken.
%% Cell type:code id: tags:
``` python
xr_dict = cat.to_dataset_dict(cdf_kwargs=dict(chunks=dict(time=1)),
zarr_kwargs=dict(consolidated=True,
decode_times=True,
use_cftime=True)
)
xr_dict
```
%% Cell type:markdown id: tags:
`Intake` was able to aggregate many files into only one dataset:
- The `time_range` column was used to **concat** data along the `time` dimension
- The `member_id` column was used to generate a new dimension
The underlying `dask` package will only load the data into memory if needed.
The underlying `dask` package will only load the data into memory if needed. Note that attributes which disagree from file to file, e.g. *tracking_id*, are excluded from the dataset.
%% Cell type:markdown id: tags:
How **intake-esm** should open and aggregate the assets is configured in the *aggregation_control* part of the description:
%% Cell type:code id: tags:
``` python
print(esm_col.esmcol_data["aggregation_control"]["aggregations"])
```
%% Cell type:markdown id: tags:
Columns can be defined for appending or creating new dimensions. The *options* are keyword arguments for xarray.
They **keys** of the dictionary are made with column values defined in the *aggregation_control* of the **intake-esm** catalog. These will determine the **key_template**. The corresponding commands are:
%% Cell type:code id: tags:
``` python
print(cat.esmcol_data["aggregation_control"]["groupby_attrs"])
#
print(cat.key_template)
```
%% Cell type:markdown id: tags:
You can work with these keys **directly** on the **intake-esm** catalog which will give you an overview over all columns (too long for the web page):
%% Cell type:code id: tags:
``` python
#cat["CMIP.MPI-ESM1-2-HR.historical.Amon.gn"]
```
%% Cell type:markdown id: tags:
If we are only interested in the **first** dataset of the dictionary, we can *pop it out*:
%% Cell type:code id: tags:
``` python
xr_dset = xr_dict.popitem()[1]
xr_dset
```
%% Cell type:markdown id: tags:
#### Pangeo's data store
### Troubleshooting
The variables are collected in **one** dataset. This requires that **the dimensions and coordinates must be the same over all files**. Otherwise, xarray cannot merge these together.
For CMIP6, most of the variables collected in one **table_id** should be on the same dimensions and coordinates. Unfortunately, there are exceptions.:
- a few variables are requested for *time slices* only.
- sometimes models use different dimension names from file to file
Using the [preprocessing](https://tutorials.dkrz.de/tutorial_intake-4-preprocessing-derived-vars.html#use-preprocessing-when-opening-assets-and-creating-datasets) keyword argument can help to rename dimensions before merging.
For Intake providers: the more information on the dimensions and coordinates provided already in the catalog, the better the aggregation control.
%% Cell type:markdown id: tags:
### Pangeo's data store
Let's have a look into Pangeo's ESM Collection as well. This is accessible via cloud from everywhere - you only need internet to load data. We use the same `query` as in the example before.
%% Cell type:code id: tags:
``` python
pangeo_cmip6=pangeo.climate.cmip6_gcs
cat = pangeo_cmip6.search(**query)
cat
```
%% Cell type:markdown id: tags:
There are differences between the collections because
- Pangeo provides files in *consolidated*, `zarr` formatted datasets which correspond to `zstore` entries in the catalog instead of `path`s or `opendap_url`s.
- The `zarr` datasets are already aggregated over time so there is no need for a `time_range` column
If we now open the data with `intake`, we have to specify keyword arguments as follows:
%% Cell type:code id: tags:
``` python
dset_dict = cat.to_dataset_dict(
zarr_kwargs={"consolidated": True, "decode_times": True, "use_cftime": True}
)
```
%% Cell type:code id: tags:
``` python
dset_dict
```
%% Cell type:markdown id: tags:
`dset_dict` and `xr_dict` are the same. You succesfully did the intake tutorial!
%% Cell type:markdown id: tags:
### Making a quick plot
The following line exemplifies the ease of the intake's data processing library chain. On the web page, the interactivity will not work as all plots would have to be loaded which is not feasible.
For more examples, check out the **use cases** on that web page.
%% Cell type:code id: tags:
``` python
import hvplot.xarray
xr_dset["tas"].hvplot.quadmesh(width=600)
```
%% Cell type:markdown id: tags:
```{seealso}
This tutorial is part of a series on `intake`:
* [Part 1: Introduction](https://data-infrastructure-services.gitlab-pages.dkrz.de/tutorials-and-use-cases/tutorial_intake-1-introduction.html)
* [Part 2: Modifying and subsetting catalogs](https://data-infrastructure-services.gitlab-pages.dkrz.de/tutorials-and-use-cases/tutorial_intake-2-subset-catalogs.html)
* [Part 3: Merging catalogs](https://data-infrastructure-services.gitlab-pages.dkrz.de/tutorials-and-use-cases/tutorial_intake-3-merge-catalogs.html)
* [Part 4: Use preprocessing and create derived variables](https://data-infrastructure-services.gitlab-pages.dkrz.de/tutorials-and-use-cases/tutorial_intake-4-preprocessing-derived-variables.html)
* [Part 5: How to create an intake catalog](https://data-infrastructure-services.gitlab-pages.dkrz.de/tutorials-and-use-cases/tutorial_intake-5-create-esm-collection.html)
- You can also do another [CMIP6 tutorial](https://intake-esm.readthedocs.io/en/latest/user-guide/cmip6-tutorial.html) from the official intake page.
```
%% Cell type:markdown id: tags:
%% Cell type:code id: tags:
``` python
```
......
......@@ -63,16 +63,6 @@
"esm_dkrz=dkrz_cdp.dkrz_cmip6_disk"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"#levante uri to mistral uri:\n",
"esm_dkrz.df[\"uri\"]=esm_dkrz.df[\"uri\"].str.replace(\"lustre/\",\"lustre02/\")"
]
},
{
"cell_type": "markdown",
"metadata": {},
......
%% Cell type:markdown id: tags:
# Intake IV - preprocessing and derived variables
%% Cell type:markdown id: tags:
```{admonition} Overview
:class: dropdown
![Level](https://img.shields.io/badge/Level-expert-red.svg)
🎯 **objectives**: Learn how to integrate `intake-esm` in your workflow
⌛ **time_estimation**: "30min"
☑️ **requirements**:
- intake I
© **contributors**: k204210
⚖ **license**:
```
%% Cell type:markdown id: tags:
```{admonition} Agenda
:class: tip
Based on DKRZ's CMIP6 catalog, you learn in this part how to
1. [add a **preprocessing** to `to_dataset_dict()`](#preprocess)
1. [create a derived variable registry](#derived)
```
%% Cell type:code id: tags:
``` python
import intake
#dkrz_catalog=intake.open_catalog(["https://dkrz.de/s/intake"])
#only for generating the web page we need to take the original link:
dkrz_cdp=intake.open_catalog(["https://gitlab.dkrz.de/data-infrastructure-services/intake-esm/-/raw/master/esm-collections/cloud-access/dkrz_catalog.yaml"])
esm_dkrz=dkrz_cdp.dkrz_cmip6_disk
```
%% Cell type:code id: tags:
``` python
#levante uri to mistral uri:
esm_dkrz.df["uri"]=esm_dkrz.df["uri"].str.replace("lustre/","lustre02/")
```
%% Cell type:markdown id: tags:
<a class="anchor" id="preprocessing"></a>
## Use Preprocessing when opening assets and creating datasets
When calling intake-esm's `to_dataset_dict` function, we can pass an argument **preprocess**. Its value should be a function which is applied to all assets before they are opened.
```{note}
For CMIP6, a [preprocessing package](https://github.com/jbusecke/cmip6_preprocessing) has been developped for homogenizing and preparing datasets of different ESMs for a grand analysis featuring
- renaming and setting of coordinates
- adjusting grid values to fit into a common range (0-360 for lon)
```
E.g., if you would like to set some specific variables as coordinates, you can define a [function](https://github.com/jbusecke/cmip6_preprocessing/blob/209041a965984c2dc283dd98188def1dea4c17b3/cmip6_preprocessing/preprocessing.py#L239) which
- receives an xarray dataset as an argument
- returns a new xarray dataset
%% Cell type:code id: tags:
``` python
def correct_coordinates(ds) :
"""converts wrongly assigned data_vars to coordinates"""
ds = ds.copy()
for co in [
"x",
"y",
"lon",
"lat",
"lev",
"bnds",
"lev_bounds",
"lon_bounds",
"lat_bounds",
"time_bounds",
"lat_verticies",
"lon_verticies",
]:
if co in ds.variables:
ds = ds.set_coords(co)
return ds
```
%% Cell type:markdown id: tags:
Now, when you open the dataset dictionary, you provide it for *preprocess*:
%% Cell type:code id: tags:
``` python
cat=esm_dkrz.search(variable_id="tas",
table_id="Amon",
source_id="MPI-ESM1-2-HR",
member_id="r1i1p1f1",
experiment_id="ssp370"
)
test_dsets=cat.to_dataset_dict(
zarr_kwargs={"consolidated":True},
cdf_kwargs={"chunks":{"time":1}},
preprocess=correct_coordinates
)
```
%% Cell type:markdown id: tags:
<a class="anchor" id="derived"></a>
## Derived variables
Most of the following is taken from the [intake-esm tutorial](https://intake-esm.readthedocs.io/en/latest/how-to/define-and-use-derived-variable-registry.html).
> A “derived variable” in this case is a variable that doesn’t itself exist in an intake-esm catalog, but can be computed (i.e., “derived”) from variables that do exist in the catalog. Currently, the derived variable implementation requires variables on the same grid, etc.; i.e., it assumes that all variables involved can be merged within the same dataset. [...] Derived variables could include more sophsticated diagnostic output like aggregations of terms in a tracer budget or gradients in a particular field.
The registry of the derived variables can be connected to the catalog. When users open
%% Cell type:code id: tags:
``` python
import intake
import intake_esm
```
%% Cell type:code id: tags:
``` python
from intake_esm import DerivedVariableRegistry
```
%% Cell type:markdown id: tags:
```{seealso}
This tutorial is part of a series on `intake`:
* [Part 1: Introduction](https://data-infrastructure-services.gitlab-pages.dkrz.de/tutorials-and-use-cases/tutorial_intake-1-introduction.html)
* [Part 2: Modifying and subsetting catalogs](https://data-infrastructure-services.gitlab-pages.dkrz.de/tutorials-and-use-cases/tutorial_intake-2-subset-catalogs.html)
* [Part 3: Merging catalogs](https://data-infrastructure-services.gitlab-pages.dkrz.de/tutorials-and-use-cases/tutorial_intake-3-merge-catalogs.html)
* [Part 4: Use preprocessing and create derived variables](https://data-infrastructure-services.gitlab-pages.dkrz.de/tutorials-and-use-cases/tutorial_intake-4-preprocessing-derived-variables.html)
* [Part 5: How to create an intake catalog](https://data-infrastructure-services.gitlab-pages.dkrz.de/tutorials-and-use-cases/tutorial_intake-5-create-esm-collection.html)
- You can also do another [CMIP6 tutorial](https://intake-esm.readthedocs.io/en/latest/user-guide/cmip6-tutorial.html) from the official intake page.
```
%% Cell type:code id: tags:
``` python
```
......
......@@ -170,8 +170,10 @@
"outputs": [],
"source": [
"# Path to master catalog on the DKRZ server\n",
"col_url = \"https://dkrz.de/s/intake\"\n",
"parent_col=intake.open_catalog([col_url])\n",
"#dkrz_catalog=intake.open_catalog([\"https://dkrz.de/s/intake\"])\n",
"#\n",
"#only for the web page we need to take the original link:\n",
"parent_col=intake.open_catalog([\"https://gitlab.dkrz.de/data-infrastructure-services/intake-esm/-/raw/master/esm-collections/cloud-access/dkrz_catalog.yaml\"])\n",
"list(parent_col)\n",
"\n",
"# Open the catalog with the intake package and name it \"col\" as short for \"collection\"\n",
......
%% Cell type:markdown id: tags:
# Advanced *Summer Days* calculation with `xarray` using CMIP6 data
We will show here how to count the annual summer days for a particular geolocation of your choice using the results of a climate model, in particular, we can chose one of the historical or one of the shared socioeconomic pathway (ssp) experiments of the Coupled Model Intercomparison Project [CMIP6](https://pcmdi.llnl.gov/CMIP6/).
Thanks to the data and computer scientists Marco Kulüke, Fabian Wachsmann, Regina Kwee-Hinzmann, Caroline Arnold, Felix Stiehler, Maria Moreno, and Stephan Kindermann at DKRZ for their contribution to this notebook.
%% Cell type:markdown id: tags:
In this use case you will learn the following:
- How to access a dataset from the DKRZ CMIP6 model data archive
- How to count the annual number of summer days for a particular geolocation using this model dataset
- How to visualize the results
You will use:
- [Intake](https://github.com/intake/intake) for finding the data in the catalog of the DKRZ archive
- [Xarray](http://xarray.pydata.org/en/stable/) for loading and processing the data
- [hvPlot](https://hvplot.holoviz.org/index.html) for visualizing the data in the Jupyter notebook and save the plots in your local computer
%% Cell type:markdown id: tags:
## 0. Load Packages
%% Cell type:code id: tags:
``` python
import numpy as np # fundamental package for scientific computing
import pandas as pd # data analysis and manipulation tool
import xarray as xr # handling labelled multi-dimensional arrays
import intake # to find data in a catalog, this notebook explains how it works
from ipywidgets import widgets # to use widgets in the Jupyer Notebook
from geopy.geocoders import Nominatim # Python client for several popular geocoding web services
import folium # visualization tool for maps
import hvplot.pandas # visualization tool for interactive plots
```
%% Cell type:markdown id: tags:
## 1. Which dataset do we need? -> Choose Shared Socioeconomic Pathway, Place, and Year
<a id='selection'></a>
%% Cell type:code id: tags:
``` python
# Produce the widget where we can select what experiment we are interested on
#experiments = {'historical':range(1850, 2015), 'ssp126':range(2015, 2101),
# 'ssp245':range(2015, 2101), 'ssp370':range(2015, 2101), 'ssp585':range(2015, 2101)}
#experiment_box = widgets.Dropdown(options=experiments, description="Select experiment: ", disabled=False,)
#display(experiment_box)
```
%% Cell type:code id: tags:
``` python
# Produce the widget where we can select what geolocation and year are interested on
#print("Feel free to change the default values.")
#place_box = widgets.Text(description="Enter place:", value="Hamburg")
#display(place_box)
#x = experiment_box.value
#year_box = widgets.Dropdown(options=x, description="Select year: ", disabled=False,)
#display(year_box)
```
%% Cell type:code id: tags:
``` python
pb="Hamburg"
yb=2021
eb="ssp370"
%store -r
```
%% Cell type:markdown id: tags:
### 1.1 Find Coordinates of chosen Place
If ambiguous, the most likely coordinates will be chosen, e.g. "Hamburg" results in "Hamburg, 20095, Deutschland", (53.55 North, 10.00 East)
%% Cell type:code id: tags:
``` python
# We use the module Nominatim gives us the geographical coordinates of the place we selected above
geolocator = Nominatim(user_agent="any_agent")
location = geolocator.geocode(pb)
print(location.address)
print((location.latitude, location.longitude))
```
%% Cell type:markdown id: tags:
### 1.2 Show Place on a Map
%% Cell type:code id: tags:
``` python
# We use the folium package to plot our selected geolocation in a map
m = folium.Map(location=[location.latitude, location.longitude])
tooltip = location.latitude, location.longitude
folium.Marker([location.latitude, location.longitude], tooltip=tooltip).add_to(m)
display(m)
```
%% Cell type:markdown id: tags:
We have defined the place and time. Now, we can search for the climate model dataset.
%% Cell type:markdown id: tags:
## 2. Intake Catalog
### 2.1 Load the Intake Catalog
%% Cell type:code id: tags:
``` python
# Path to master catalog on the DKRZ server
col_url = "https://dkrz.de/s/intake"
parent_col=intake.open_catalog([col_url])
#dkrz_catalog=intake.open_catalog(["https://dkrz.de/s/intake"])
#
#only for the web page we need to take the original link:
parent_col=intake.open_catalog(["https://gitlab.dkrz.de/data-infrastructure-services/intake-esm/-/raw/master/esm-collections/cloud-access/dkrz_catalog.yaml"])
list(parent_col)
# Open the catalog with the intake package and name it "col" as short for "collection"
col=parent_col["dkrz_cmip6_disk"]
```
%% Cell type:markdown id: tags:
### 2.2 Browse the Intake Catalog
In this example we chose the Max-Planck Earth System Model in High Resolution Mode ("MPI-ESM1-2-HR") and the maximum temperature near surface ("tasmax") as variable. We also choose an experiment. CMIP6 comprises several kind of experiments. Each experiment has various simulation members. you can find more information in the [CMIP6 Model and Experiment Documentation](https://pcmdi.llnl.gov/CMIP6/Guide/dataUsers.html#5-model-and-experiment-documentation).
%% Cell type:code id: tags:
``` python
# Store the name of the model we chose in a variable named "climate_model"
climate_model = "MPI-ESM1-2-HR" # here we choose Max-Plack Institute's Earth Sytem Model in high resolution
# This is how we tell intake what data we want
query = dict(
source_id = climate_model, # the model
variable_id = "tasmax", # temperature at surface, maximum
table_id = "day", # daily maximum
experiment_id = eb, # what we selected in the drop down menu,e.g. SSP2.4-5 2015-2100
member_id = "r10i1p1f1", # "r" realization, "i" initialization, "p" physics, "f" forcing
)
# Intake looks for the query we just defined in the catalog of the CMIP6 data pool at DKRZ
col.df["uri"]=col.df["uri"].str.replace("lustre/","lustre02/")
cat = col.search(**query)
del col
# Show query results
cat.df
```
%% Cell type:markdown id: tags:
### 2.3 Create Dictionary and get Data into one Object
%% Cell type:code id: tags:
``` python
# cdf_kwargs are given to xarray.open_dataset
# cftime is like datetime but extends to all four digit years and many calendar types
dset_dict = cat.to_dataset_dict(cdf_kwargs={"chunks": {"time": -1}, "use_cftime": True})
```
%% Cell type:code id: tags:
``` python
# get all data into one object
for key, value in dset_dict.items():
model = key.split(".")[2] # extract model name from key
tasmax_xr = value["tasmax"].squeeze() # extract variable from dataset
```
%% Cell type:code id: tags:
``` python
tasmax_xr
```
%% Cell type:markdown id: tags:
## 3. Select Year and Look at (Meta) Data
%% Cell type:code id: tags:
``` python
tasmax_year_xr = tasmax_xr.sel(time=str(yb))
# Let's have a look at the xarray data array
tasmax_year_xr
```
%% Cell type:markdown id: tags:
We see not only the numbers, but also information about it, such as long name, units, and the data history. This information is called metadata.
%% Cell type:markdown id: tags:
## 4. Compare Model Grid Cell with chosen Location
%% Cell type:code id: tags:
``` python
# Find nearest model coordinate by finding the index of the nearest grid point
abslat = np.abs(tasmax_year_xr["lat"] - location.latitude)
abslon = np.abs(tasmax_year_xr["lon"] - location.longitude)
c = np.maximum(abslon, abslat)
([xloc], [yloc]) = np.where(c == np.min(c)) # xloc and yloc are the indices of the neares model grid point
```
%% Cell type:code id: tags:
``` python
# Draw map again
m = folium.Map(location=[location.latitude, location.longitude], zoom_start=8)
tooltip = location.latitude, location.longitude
folium.Marker(
[location.latitude, location.longitude],
tooltip=tooltip,
popup="Location selected by You",
).add_to(m)
#
tooltip = float(tasmax_year_xr["lat"][yloc].values), float(tasmax_year_xr["lon"][xloc].values)
folium.Marker(
[tasmax_year_xr["lat"][yloc], tasmax_year_xr["lon"][xloc]],
tooltip=tooltip,
popup="Model Grid Cell Center",
).add_to(m)
# Define coordinates of model grid cell (just for visualization)
rect_lat1_model = (tasmax_year_xr["lat"][yloc - 1] + tasmax_year_xr["lat"][yloc]) / 2
rect_lon1_model = (tasmax_year_xr["lon"][xloc - 1] + tasmax_year_xr["lon"][xloc]) / 2
rect_lat2_model = (tasmax_year_xr["lat"][yloc + 1] + tasmax_year_xr["lat"][yloc]) / 2
rect_lon2_model = (tasmax_year_xr["lon"][xloc + 1] + tasmax_year_xr["lon"][xloc]) / 2
# Draw model grid cell
folium.Rectangle(
bounds=[[rect_lat1_model, rect_lon1_model], [rect_lat2_model, rect_lon2_model]],
color="#ff7800",
fill=True,
fill_color="#ffff00",
fill_opacity=0.2,
).add_to(m)
m
```
%% Cell type:markdown id: tags:
Climate models have a finite resolution. Hence, models do not provide the data of a particular point, but the mean over a model grid cell. Take this in mind when comparing model data with observed data (e.g. weather stations).
Now, we will visualize the daily maximum temperature time series of the model grid cell.
%% Cell type:markdown id: tags:
## 5. Draw Temperature Time Series and Count Summer days
%% Cell type:markdown id: tags:
The definition of a summer day varies from region to region. According to the [German Weather Service](https://www.dwd.de/EN/ourservices/germanclimateatlas/explanations/elements/_functions/faqkarussel/sommertage.html), "a summer day is a day on which the maximum air temperature is at least 25.0 °C". Depending on the place you selected, you might want to apply a different threshold to calculate the summer days index.
%% Cell type:code id: tags:
``` python
tasmax_year_place_xr = tasmax_year_xr[:, yloc, xloc] - 273.15 # Convert Kelvin to °C
tasmax_year_place_df = pd.DataFrame(index = tasmax_year_place_xr['time'].values,
columns = ['Temperature', 'Summer Day Threshold']) # create the dataframe
tasmax_year_place_df.loc[:, 'Model Temperature'] = tasmax_year_place_xr.values # insert model data into the dataframe
tasmax_year_place_df.loc[:, 'Summer Day Threshold'] = 25 # insert the threshold into the dataframe
# Plot data and define title and legend
tasmax_year_place_df.hvplot.line(y=['Model Temperature', 'Summer Day Threshold'],
value_label='Temperature in °C', legend='bottom',
title='Daily maximum Temperature near Surface for '+pb,
height=500, width=620)
```
%% Cell type:markdown id: tags:
As we can see, the maximum daily temperature is highly variable over the year. As we are using the mean temperature in a model grid cell, the amount of summer days might we different that what you would expect at a single location.
%% Cell type:code id: tags:
``` python
# Summer days index calculation
no_summer_days_model = tasmax_year_place_xr[tasmax_year_place_xr > 25].size # count the number of summer days
# Print results in a sentence
print("According to the German Weather Service definition, in the " +eb +" experiment the "
+climate_model +" model shows " +str(no_summer_days_model) +" summer days for " + pb
+ " in " + str(yb) +".")
```
%% Cell type:markdown id: tags:
[Try another location and year](#selection)
......
......@@ -93,8 +93,10 @@
"outputs": [],
"source": [
"# Path to master catalog on the DKRZ server\n",
"col_url = \"https://dkrz.de/s/intake\"\n",
"parent_col=intake.open_catalog([col_url])\n",
"#dkrz_catalog=intake.open_catalog([\"https://dkrz.de/s/intake\"])\n",
"#\n",
"#only for the web page we need to take the original link:\n",
"parent_col=intake.open_catalog([\"https://gitlab.dkrz.de/data-infrastructure-services/intake-esm/-/raw/master/esm-collections/cloud-access/dkrz_catalog.yaml\"])\n",
"list(parent_col)\n",
"\n",
"# Open the catalog with the intake package and name it \"col\" as short for \"collection\"\n",
......
%% Cell type:markdown id: tags:
# Calculate Number of Frost Days
%% Cell type:markdown id: tags:
This notebook computes the annual number of frost days for a given year, by using the daily minimum temperature (`tasmin`). The number of frost days index is the annual count of days where `tasmin` < 0 °C.
%% Cell type:markdown id: tags:
This Jupyter notebook is meant to run in the Jupyterhub server of the German Climate Computing Center [DKRZ](https://www.dkrz.de/) which is an [ESGF](https://esgf.llnl.gov/) repository that hosts 4 petabytes of CMIP6 data. Please, choose the Python 3 unstable kernel on the Kernel tab above, it contains all the common geoscience packages. See more information on how to run Jupyter notebooks at DKRZ [here](https://www.dkrz.de/up/systems/mistral/programming/jupyter-notebook). Find there how to run this Jupyter notebook in the DKRZ server out of the Jupyterhub, which will entail that you create the environment accounting for the required package dependencies. Running this Jupyter notebook in your premise, which is also known as [client-side](https://en.wikipedia.org/wiki/Client-side) computing, will also require that you install the necessary packages on you own but it will anyway fail because you will not have direct access to the data pool. Direct access to the data pool is one of the main benefits of the [server-side](https://en.wikipedia.org/wiki/Server-side) data-near computing we demonstrate in this use case.
%% Cell type:markdown id: tags:
In this use case you will learn the following:
- How to access a dataset from the DKRZ CMIP6 model data archive
- How to count the annual number of frost days globally for a specified year
- How to visualize the results
You will use:
- [Intake](https://github.com/intake/intake) for finding the data in the catalog of the DKRZ archive
- [Xarray](http://xarray.pydata.org/en/stable/) for loading and processing the data
- [Cartopy](https://pypi.org/project/Cartopy/) for visualizing the data in the Jupyter notebook and save the plots in your local computer
%% Cell type:markdown id: tags:
## 0. Import Packages
%% Cell type:code id: tags:
``` python
import intake # to find data in a catalog, this notebook explains how it works
import xarray as xr # handling labelled multi-dimensional arrays
# plotting libraries
import matplotlib.pyplot as plt
import cartopy.crs as ccrs
from cartopy.util import add_cyclic_point
```
%% Cell type:markdown id: tags:
## 1. Select the Year for Frost Days Calculation
%% Cell type:code id: tags:
``` python
year = "2100"
```
%% Cell type:markdown id: tags:
## 2. Intake Catalog
Similar to the shopping catalog at your favorite online bookstore, the intake catalog contains information (e.g. model, variables, and time range) about each dataset (the title, author, and number of pages of the book, for instance) that you can access before loading the data. It means that thanks to the catalog, you can find where is the book just by using some keywords and you do not need to hold it in your hand to know the number of pages, for instance.
### 2.1. Load the Intake Catalog and Orientate
We load the catalog descriptor with the intake package. The catalog is updated daily. The catalog descriptor is created by the DKRZ developers that manage the catalog, you do not need to care so much about it, knowing where it is and loading it is enough:
%% Cell type:code id: tags:
``` python
# Path to master catalog on the DKRZ server
col_url = "https://dkrz.de/s/intake"
parent_col=intake.open_catalog([col_url])
#dkrz_catalog=intake.open_catalog(["https://dkrz.de/s/intake"])
#
#only for the web page we need to take the original link:
parent_col=intake.open_catalog(["https://gitlab.dkrz.de/data-infrastructure-services/intake-esm/-/raw/master/esm-collections/cloud-access/dkrz_catalog.yaml"])
list(parent_col)
# Open the catalog with the intake package and name it "col" as short for "collection"
col=parent_col["dkrz_cmip6_disk"]
```
%% Cell type:markdown id: tags:
Let's see what is inside the intake catalog. The underlying data base is given as a pandas dataframe which we can access with `col.df`. Hence, `col.df.head()` shows us the first rows of the table of the catalog.
%% Cell type:code id: tags:
``` python
col.df.head()
```
%% Cell type:markdown id: tags:
This catalog contains all datasets of the CMIP6 archive at DKRZ. Before searching for the needed data file we will have a closer look at the cataloge.
%% Cell type:markdown id: tags:
100 climate models `source_id` are part of the catalog.
%% Cell type:code id: tags:
``` python
col.unique(["source_id"])
```
%% Cell type:markdown id: tags:
The catalog offers 1162 variables.
%% Cell type:code id: tags:
``` python
#col.unique(["variable_id"])
```
%% Cell type:markdown id: tags:
You can create a subset of the catalog with pandas operations. Here we select all CMIP activities (`col.df["activity_id"] == "CMIP"`)
%% Cell type:code id: tags:
``` python
col.df[col.df["activity_id"] == "CMIP"]
```
%% Cell type:markdown id: tags:
### 2.2. Browse the Intake Catalog
The most elegant way for creating subsets is a query with a dictionary. In our case we design the search dictionary as follows: We chose the Max-Planck Earth System Model in Low Resolution Mode ("MPI-ESM1-2-LR") and the minimm temperature near surface (`tasmin`) as variable. We also choose an experiment. CMIP6 comprises several kind of experiments. Each experiment has various simulation members. you can find more information in the CMIP6 Model and Experiment Documentation.
%% Cell type:code id: tags:
``` python
# This is how we tell intake what data we want
query = dict(
source_id = "MPI-ESM1-2-LR", # here we choose Max-Plack Institute's Earth Sytem Model in high resolution
variable_id = "tasmin", # temperature at surface, minimum
table_id = "day", # daily frequency
experiment_id = "ssp585", # what we selected in the drop down menu,e.g. SSP2.4-5 2015-2100
member_id = "r10i1p1f1", # "r" realization, "i" initialization, "p" physics, "f" forcing
)
# Intake looks for the query we just defined in the catalog of the CMIP6 data pool at DKRZ
col.df["uri"]=col.df["uri"].str.replace("lustre/","lustre02/")
cat = col.search(**query)
del col # Make space for other python objects
# Show query results
cat.df
```
%% Cell type:markdown id: tags:
The result of the query are like the list of results you get when you search for articles in the internet by writing keywords in your search engine (Duck duck go, Ecosia, Google,...). Thanks to the intake package, we did not need to know the path of each dataset, just selecting some keywords (the model name, the variable,...) was enough to obtain the results. If advance users are still interested in the location of the data inside the DKRZ archive, intake also provides the path and the OpenDAP URL (see the last columns above).
Now we will find which file in the dataset contains our selected year so in the next section we can just load that specific file and not the whole dataset.
%% Cell type:markdown id: tags:
### 2.3. Find the Dataset
%% Cell type:code id: tags:
``` python
# Create a copy of cat.df, thus further modifications do not affect it
query_result_df = cat.df.copy() # new dataframe to play with
# Each dataset contains many files, extract the initial and final year of each file
query_result_df["start_year"] = query_result_df["time_range"].str[0:4].astype(int) # add column with start year
query_result_df["end_year"] = query_result_df["time_range"].str[9:13].astype(int) # add column with end year
# Delete the time range column
query_result_df.drop(columns=["time_range"], inplace = True) # "inplace = False" will drop the column in the view but not in the actual dataframe
query_result_df.iloc[0:3]
# Select the file that contains the year we selected in the drop down menu above, e.g. 2015
selected_file = query_result_df[(int(year) >= query_result_df["start_year"]) & (
int(year) <= query_result_df["end_year"])]
# Path of the file that contains the selected year
selected_path = selected_file["uri"].values[0]
# Show the path of the file that contains the selected year
selected_path
```
%% Cell type:markdown id: tags:
## 3. Load the Model Data
%% Cell type:code id: tags:
``` python
ds = xr.open_dataset(selected_path)
# Open variable "tasmin" over the whole time range
ds_tasmin = ds["tasmin"]
```
%% Cell type:markdown id: tags:
Look at data
%% Cell type:code id: tags:
``` python
ds_tasmin
```
%% Cell type:markdown id: tags:
Select year
%% Cell type:code id: tags:
``` python
ds_tasmin_year = ds_tasmin.sel(time=year)
```
%% Cell type:markdown id: tags:
Count the number of frost days
%% Cell type:code id: tags:
``` python
ds_tasmin_year_count = ds_tasmin_year.where(ds_tasmin_year < 273.15).count(dim='time')
```
%% Cell type:markdown id: tags:
Before plotting, a cyclic point has to be added, otherwise there will be a gap at the prime meridian.
%% Cell type:code id: tags:
``` python
lon = ds_tasmin_year_count.lon
lat = ds_tasmin_year_count.lat
#ds_tasmin_year_count, lon = add_cyclic_point(ds_tasmin_year_count, lon)
```
%% Cell type:markdown id: tags:
## 4. Plot data with `cartopy`
%% Cell type:code id: tags:
``` python
fig = plt.figure(figsize=(10, 5))
ax = fig.add_subplot(1, 1, 1, projection=ccrs.Mollweide())
plt.contourf(lon, lat, ds_tasmin_year_count, 60,
transform=ccrs.PlateCarree(),
cmap='Blues')
ax.coastlines()
ax.set_global()
# Add a color bar
plt.colorbar(ax=ax)
plt.title('Number of Frost Days in Year ' +year)
plt.show()
```
%% Cell type:code id: tags:
``` python
```
......
......@@ -91,12 +91,14 @@
"source": [
"import intake\n",
"# Path to master catalog on the DKRZ server\n",
"col_url = \"https://dkrz.de/s/intake\"\n",
"dkrz_catalog=intake.open_catalog([col_url])\n",
"#dkrz_catalog=intake.open_catalog([\"https://dkrz.de/s/intake\"])\n",
"#\n",
"#only for the web page we need to take the original link:\n",
"dkrz_catalog=intake.open_catalog([\"https://gitlab.dkrz.de/data-infrastructure-services/intake-esm/-/raw/master/esm-collections/cloud-access/dkrz_catalog.yaml\"])\n",
"list(dkrz_catalog)\n",
"\n",
"# Open the catalog with the intake package and name it \"col\" as short for \"collection\"\n",
"cols=dkrz_catalog.metadata[\"parameters\"][\"cmip6_columns\"][\"default\"]+[\"opendap_url\"]\n",
"cols=dkrz_catalog._entries[\"dkrz_cmip6_disk\"]._open_args[\"csv_kwargs\"][\"usecols\"]+[\"opendap_url\"]\n",
"col=dkrz_catalog.dkrz_cmip6_disk(csv_kwargs=dict(usecols=cols))"
]
},
......
%% Cell type:markdown id: tags:
# Climate Extremes Indices with CDOs according to the ETCCDI standard
%% Cell type:markdown id: tags:
A **climate index** is a calculated measure for the state and/or variations of the climate system. In the field of meteorology, many definitions for different types of climate indices exist. For example, the German Weather Service defines a **Klimakenntag**: If a climatological parameter exceeds a specific threshold at one day, the day is considered as a specific klimakenntag.
The expert team ETCCDI has defined a core set of descriptive indices of extremes (Climate Extremes Indices, CEI) in order to