<jupyter_start><jupyter_text>Building an Intake-esm catalog from CESM2 History FilesAs mentioned in a couple of ESDS posts ([intake-esm and Dask](https://ncar.github.io/esds/posts/intake_esm_dask/), [debugging intake-esm](https://ncar.github.io/esds/posts/intake_cmip6_debug/)), [intake-esm](https://intake-esm.readthedocs.io/en/latest/) can be a helpful tool to work with when dealing with model data, especially CESM. One of the requirements for using intake-esm is having a catalog which is comprised of two pieces:* A table of the relevant metadata (ex. file path, variable, stream, etc.)* A json describing the dataset, including how to aggregate the variablesTypically, these pieces are constructed "manually" using information within the file path, on a very ad-hoc basis. Also, these catalogs are typically only created for "larger", community datasets, not neccessarily used within smaller model runs/daily workflows. A new package (currently a prototype), called [ecgtools](https://ecgtools.readthedocs.io/en/latest/) works to solve the issues of generating these intake-esm catalogs. Ecgtools stands for Earth System Model (ESM) Catalog Generation tools. The current catalog generation tools supported are:* CMIP6 models* CESM "history" files* CESM "timeseries" filesThis package has not officially been release yet on [pypi](https://pypi.org/) or [conda-forge](https://conda-forge.org/), but this release will likely happen soon. This post will give an overview of using [ecgtools](https://ecgtools.readthedocs.io/en/latest/) for parsing CESM history file model output, and reading in the data using [intake-esm](https://intake-esm.readthedocs.io/en/latest/). In this example, we use model output using the default component-set (compset) detailed in the [CESM Quickstart Guide](https://escomp.github.io/CESM/versions/cesm2.1/html/). What's a "history" file?A history file is the default output from CESM, where each file is a single time "slice" with every variable from the component of interest. These types of files can be difficult to work with, since often times one is interested in a time series of a single variable. Building a catalog can be helpful in accessing your data, querying for certain variables, and potentially creating timeseries files later down the road.Let's get started! Downloading the beta version of ecgtoolsIn order to access this in its current state, you will need to clone the repository from github. On the machine with the data you are planning on creating a catalog for, run the following:```git clone https://github.com/NCAR/ecgtools.git```This will create a clone of the repository on your machine. After you clone the respository, run```pip install -e ecgtools```This will install the package into the python environment you currently activated (for more on dealing with conda environments, check out the [faq page](https://ncar.github.io/esds/faq/conda-environments)You will also want to install intake-esm, which you can install using `conda-forge````conda install -c conda-forge intake-esm``` ImportsThe only parts of ecgtools we need are the `Builder` object and the `parse_cesm_history` parser from the CESM parsers! We import `glob` to take a look at the files we are parsing.<jupyter_code>import glob

from ecgtools import Builder
from ecgtools.parsers.cesm import parse_cesm_history<jupyter_output><empty_output><jupyter_text>Understanding the Directory StructureThe first step to setting up the `Builder` object is determining where your files are stored. As mentioned previously, we have a sample dataset of CESM2 model output, which is stored in `/glade/work/mgrover/cesm_test_data/`Taking a look at that directory, we see that there is a single case `b.e20.B1850.f19_g17.test`<jupyter_code>glob.glob('/glade/work/mgrover/cesm_test_data/*')<jupyter_output><empty_output><jupyter_text>Once we go into that directory, we see all the different components, including the atmosphere (atm), ocean (ocn), and land (lnd)!<jupyter_code>glob.glob('/glade/work/mgrover/cesm_test_data/b.e20.B1850.f19_g17.test/*')<jupyter_output><empty_output><jupyter_text>If we go one step further, we notice that within each component, is a `hist` directory which contains the model output<jupyter_code>glob.glob('/glade/work/mgrover/cesm_test_data/b.e20.B1850.f19_g17.test/atm/*/*.nc')[0:3]<jupyter_output><empty_output><jupyter_text>If we take a look at the `ocn` component though, we notice that there are a few timeseries files in there...<jupyter_code>glob.glob('/glade/work/mgrover/cesm_test_data/b.e20.B1850.f19_g17.test/ocn/*/*.nc')[0:3]<jupyter_output><empty_output><jupyter_text>When we setup our catalog builder, we will need to specify not including the timeseries (tseries) and restart (rest) directories!Now that we understand the directory structure, let's make the catalog.  Build the catalog!Let's start by inspecting the builder object<jupyter_code>Builder?<jupyter_output><empty_output><jupyter_text>Info    Note that as of 21 June, 2021, the parsing_func parameter is now used in the .build() method!<jupyter_code>b = Builder(
    # Directory with the output
    "/glade/work/mgrover/cesm_test_data/b.e20.B1850.f19_g17.test/",
    # Depth of 1 since we are sending it to the case output directory
    depth=1,
    # Exclude the timeseries and restart directories
    exclude_patterns=["*/tseries/*", "*/rest/*"],
    # Number of jobs to execute - should be equal to # threads you are using
    njobs=5,
)<jupyter_output><empty_output><jupyter_text>Double check the object is set up...<jupyter_code>b<jupyter_output><empty_output><jupyter_text>We are good to go! Let's build the catalog by calling `.build()` on the object, passing in the `parse_cesm_history` parser! By default, it will use the `LokyBackend` which is described in the [Joblib documentation](https://joblib.readthedocs.io/en/latest/parallel.html).<jupyter_code>b = b.build(parse_cesm_history)<jupyter_output>[Parallel(n_jobs=5)]: Using backend LokyBackend with 5 concurrent workers.
[Parallel(n_jobs=5)]: Done   6 out of  12 | elapsed:    0.2s remaining:    0.2s
[Parallel(n_jobs=5)]: Done   9 out of  12 | elapsed:    0.2s remaining:    0.1s
[Parallel(n_jobs=5)]: Done  12 out of  12 | elapsed:    0.2s remaining:    0.0s
[Parallel(n_jobs=5)]: Done  12 out of  12 | elapsed:    0.2s finished
[Parallel(n_jobs=5)]: Using backend LokyBackend with 5 concurrent workers.
[Parallel(n_jobs=5)]: Done   8 tasks      | elapsed:    1.6s
[Parallel(n_jobs=5)]: Done  62 tasks      | elapsed:    4.5s
[Parallel(n_jobs=5)]: Done 152 tasks      | elapsed:   11.4s
[Parallel(n_jobs=5)]: Done 264 out of 264 | elapsed:   15.1s finished
/glade/work/mgrover/git_repos/ecgtools/ecgtools/builder.py:180: UserWarning: Unable to parse 5 assets/files. A list of these assets can be found in `.invalid_assets` attribute.
  parsing_func, parsing_func_kwargs<jupyter_text>Inspect the Catalog Now that the catalog is built, we can inspect the dataframe which is used to create the catalog by calling `.df` on the builder object<jupyter_code>b.df<jupyter_output><empty_output><jupyter_text>The resultant dataframe includes the:* Component* Stream* Case* Date* Frequency* Variables* PathWe can also check to see which files ***were not*** parsed by calling `.invalid_assets`<jupyter_code>b.invalid_assets
b.invalid_assets.INVALID_ASSET.values[0]
b.df<jupyter_output><empty_output><jupyter_text>It appears that one of the invalid assets is a `pop.hv` stream, which is a time-invariant dataset we would not neccessarily be interested in looking at. If there is a file you think ***should*** be included in the resultant catalog but isn't, be sure to add it to the `_STREAMS_DICT` used in the [parsing tool](https://github.com/NCAR/ecgtools/blob/main/ecgtools/parsers/cesm.py)!   Save the Catalog<jupyter_code>b.save(
    # File path - could save as .csv (uncompressed csv) or .csv.gz (compressed csv)
    "/glade/work/mgrover/cesm-hist-test.csv",
    # Column name including filepath
    path_column_name='path',
    # Column name including variables
    variable_column_name='variables',
    # Data file format - could be netcdf or zarr (in this case, netcdf)
    data_format="netcdf",
    # Which attributes to groupby when reading in variables using intake-esm
    groupby_attrs=["component", "stream", "case"],
    # Aggregations which are fed into xarray when reading in data using intake
    aggregations=[
        {
            "type": "join_existing",
            "attribute_name": "date",
            "options": {"dim": "time", "coords": "minimal", "compat": "override"},
        }
    ],
)<jupyter_output>Saved catalog location: /glade/work/mgrover/cesm-hist-test.json and /glade/work/mgrover/cesm-hist-test.csv<jupyter_text>Using the Catalog You'll notice the resultant filepaths are output when calling `.save` - which you could use within your intake-esm `open_esm_datastore` function. Additional Imports<jupyter_code># Import ast which helps with parsing the list of variables
import ast

# Import intake-esm
import intake<jupyter_output><empty_output><jupyter_text>Use the catalog to read in data<jupyter_code>col = intake.open_esm_datastore(
    "/glade/work/mgrover/cesm-hist-test.json",
    csv_kwargs={"converters": {"variables": ast.literal_eval}},
    sep="/",
)
col
cat = col.search(
    variables='TEMP',
)
cat
dsets = cat.to_dataset_dict(cdf_kwargs={'use_cftime': True, 'chunks': {'time': 10}})
dsets<jupyter_output><empty_output><jupyter_text>Let's plot a quick figure from the dataset!<jupyter_code>dsets['ocn/pop.h/b.e20.B1850.f19_g17.test'].TEMP.isel(time=0, z_t=0).plot();<jupyter_output><empty_output>
{'fraction_non_alphanumeric': 0.09955315390210953, 'fraction_numerical': 0.01558765457757456, 'mean_word_length': 5.018761726078799, 'pattern_counts': {'":': 8, '<': 59, '<?xml version=': 0, '>': 59, 'https://': 13, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 1, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '15', 'dir': 'jupyter-structured-clean-dedup', 'id': '67184', 'license': 'Apache-2.0', 'n_tokens_mistral': 3158, 'n_tokens_neox': 2989, 'n_words': 1039, 'path': 'posts/2021/ecgtools-history-files-example.ipynb', 'repo_name': 'jukent/esds', 'size': '9623'}