{
"cells": [
{
"cell_type": "markdown",
"metadata": {
"tags": []
},
"source": [
"# HoloViz Visualization"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Overview\n",
"\n",
"The ability to dynamically render, pan, zoom, animate and perform other dynamic operations on data can provide many benefits, such as providing greater data fidelity within the same plot. [HoloViz](https://holoviz.org/) provides high-level tools (such as Holoviews, Datashader, Geoviews, etc.) to visualize even the very large datasets efficiently.\n",
"\n",
"This notebook explores interactively plotting using an unstructured grid dataset in the [MPAS](https://mpas-dev.github.io/) format with Holoviews, Datashader, and Geoviews."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
":::{attention}\n",
"If you are in this notebook to actually learn about and/or visualize unstructured grids, we highly recommend checking out the [UXarray Cookbook](https://projectpythia.org/unstructured-grid-viz-cookbook/README.html) that is a comprehensive showcase of workflows & techniques for visualizing Unstructured Grids using [UXarray](https://uxarray.readthedocs.io/). UXarray is a Python package that:\n",
"- Provides Xarray-styled functionality for working with unstructured grids built around the UGRID conventions\n",
"- Supports not only MPAS but also several other formats such as UGRID, SCRIP, and Exodus\n",
"- Enables significant data analysis and visualization functionality for unstructured grid research, which makes working with unstructured grids a breeze\n",
" - e.g. UXarray internally handles majority of the utility functions and data preparation steps mentioned throughout this notebook and provides user with convenient visualization and analysis functions\n",
":::"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"This notebook demonstrates:\n",
"1. Use of HoloViz tools for interactive plotting\n",
"2. Different interactivity schemes\n",
"3. Use of the MPAS format's connectivity information to render data on the native grid (hence avoiding costly Delaunay triangulation)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"The flow of the content is as follows:\n",
"\n",
"1. Package imports\n",
"2. MPAS preprocessing for visualization\n",
" - Utility functions\n",
" - Data loading\n",
" - Triangular mesh generation using MPAS's cell connectivity array from the primal mesh\n",
"3. Interactive Holoviz Plots"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Prerequisites\n",
"\n",
"| Concepts | Importance | Notes |\n",
"| --- | --- | --- |\n",
"| [Holoviews](https://holoviews.org/) | Necessary | |\n",
"| [Geoviews](https://geoviews.org/) | Useful | Not necessary for plotting but useful for adding features |\n",
"| [Matplotlib](https://matplotlib.org/) | Useful | |\n",
"| [MPAS](https://mpas-dev.github.io/) | Useful | Not necessary for interactive plotting but useful for understanding the data used |\n",
"| [Xarray](https://xarray.pydata.org/) | Useful | |\n",
"\n",
"- **Time to learn**: 60 minutes"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"---"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Imports"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"tags": []
},
"outputs": [],
"source": [
"import math as math\n",
"\n",
"import cartopy.crs as ccrs\n",
"import dask.dataframe as dd\n",
"import geocat.datafiles as gdf # Only for reading-in datasets\n",
"import geoviews.feature as gf # Only for displaying coastlines\n",
"import holoviews as hv\n",
"import numpy as np\n",
"import pandas as pd\n",
"from holoviews import opts\n",
"from holoviews.operation.datashader import rasterize as hds_rasterize\n",
"from numba import jit\n",
"from xarray import open_mfdataset\n",
"\n",
"n_workers = 1"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## MPAS Preprocessing"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"The MPAS data requires some preprocessing to get it ready for visualization such as implementation \n",
"of a few utility functions, loading the data, and creating triangular mesh out of the data to rasterize."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Utility functions"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"tags": []
},
"outputs": [],
"source": [
"def unzipMesh(x, tris, t):\n",
" \"\"\"Splits a global mesh along longitude.\n",
"\n",
" Examine the X coordinates of each triangle in 'tris'. Return an array of 'tris' where\n",
" only those triangles with legs whose length is less than 't' are returned.\n",
"\n",
" Parameters\n",
" ----------\n",
" x: numpy.ndarray\n",
" x-coordinates of each triangle in 'tris'\n",
" tris: numpy.ndarray\n",
" Triangle indices for each vertex in the MPAS file, in counter-clockwise order\n",
" t: float\n",
" Threshold value\n",
" \"\"\"\n",
" return tris[\n",
" (np.abs((x[tris[:, 0]]) - (x[tris[:, 1]])) < t)\n",
" & (np.abs((x[tris[:, 0]]) - (x[tris[:, 2]])) < t)\n",
" ]"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"tags": []
},
"outputs": [],
"source": [
"def triArea(x, y, tris):\n",
" \"\"\"Computes the signed area of a triangle.\n",
"\n",
" Parameters\n",
" ----------\n",
" x: numpy.ndarray\n",
" x-coordinates of each triangle in 'tris'\n",
" y: numpy.ndarray\n",
" y-coordinates of each triangle in 'tris'\n",
" tris: numpy.ndarray\n",
" Triangle indices for each vertex in the MPAS file\n",
" \"\"\"\n",
" return ((x[tris[:, 1]] - x[tris[:, 0]]) * (y[tris[:, 2]] - y[tris[:, 0]])) - (\n",
" (x[tris[:, 2]] - x[tris[:, 0]]) * (y[tris[:, 1]] - y[tris[:, 0]])\n",
" )"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"tags": []
},
"outputs": [],
"source": [
"def orderCCW(x, y, tris):\n",
" \"\"\"Reorder triangles as necessary so they all have counter clockwise winding order.\n",
" CCW is what Datashader and MPL require.\n",
"\n",
" Parameters\n",
" ----------\n",
" x: numpy.ndarray\n",
" x-coordinates of each triangle in 'tris'\n",
" y: numpy.ndarray\n",
" y-coordinates of each triangle in 'tris'\n",
" tris: numpy.ndarray\n",
" Triangle indices for each vertex in the MPAS file\n",
" \"\"\"\n",
" tris[triArea(x, y, tris) < 0.0, :] = tris[triArea(x, y, tris) < 0.0, ::-1]\n",
" return tris"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"tags": []
},
"outputs": [],
"source": [
"def createHVTriMesh(x, y, triangle_indices, var, n_workers=1):\n",
" \"\"\"Create a Holoviews Triangle Mesh suitable for rendering with Datashader\n",
"\n",
" This function returns a Holoviews TriMesh that is created from a list of coordinates, 'x'\n",
" and 'y', an array of triangle indices that addresses the coordinates in 'x' and 'y', and\n",
" a data variable 'var'. The data variable's values will annotate the triangle vertices\n",
"\n",
" Parameters\n",
" ----------\n",
" x: numpy.ndarray\n",
" Projected x-coordinates of each triangle in 'tris'\n",
" y: numpy.ndarray\n",
" Projected y-coordinates of each triangle in 'tris'\n",
" triangle_indices: numpy.ndarray\n",
" Triangle indices for each vertex in the MPAS file, in counter-clockwise order\n",
" var: numpy.ndarray\n",
" Data variable from which the triangle vertex values are read.\n",
" n_workers: int\n",
" Number of workers, for Dask\n",
" \"\"\"\n",
" # Declare verts array\n",
" verts = np.column_stack([x, y, var])\n",
"\n",
" # Convert to pandas\n",
" verts_df = pd.DataFrame(verts, columns=[\"x\", \"y\", \"z\"])\n",
" tris_df = pd.DataFrame(triangle_indices, columns=[\"v0\", \"v1\", \"v2\"])\n",
"\n",
" # Convert to dask\n",
" verts_ddf = dd.from_pandas(verts_df, npartitions=n_workers)\n",
" tris_ddf = dd.from_pandas(tris_df, npartitions=n_workers)\n",
"\n",
" # Declare HoloViews element\n",
" tri_nodes = hv.Nodes(verts_ddf, [\"x\", \"y\", \"index\"], [\"z\"])\n",
" trimesh = hv.TriMesh((tris_ddf, tri_nodes))\n",
" return trimesh"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"tags": []
},
"outputs": [],
"source": [
"@jit(nopython=True)\n",
"def triangulatePoly(verticesOnCell, nEdgesOnCell):\n",
" \"\"\"Triangulate MPAS dual mesh:\n",
"\n",
" Triangulate each polygon in a heterogenous mesh of n-gons by connecting\n",
" each internal polygon vertex to the first vertex. Uses the MPAS\n",
" auxilliary variables verticesOnCell, and nEdgesOnCell.\n",
"\n",
" The function is decorated with Numba's just-in-time compiler so that it is translated into\n",
" optimized machine code for better peformance\n",
"\n",
" Parameters\n",
" ----------\n",
" verticesOnCell: numpy.ndarray\n",
" Connectivity array that stores the vertex indices that surround a given cell\n",
" nEdgesOnCell: numpy.ndarray\n",
" Number of edges on a given cell.\n",
" \"\"\"\n",
"\n",
" # Calculate the number of triangles. nEdgesOnCell gives the number of vertices for each cell (polygon)\n",
" # The number of triangles per polygon is the number of vertices minus 2.\n",
" nTriangles = np.sum(nEdgesOnCell - 2)\n",
"\n",
" triangles = np.ones((nTriangles, 3), dtype=np.int64)\n",
" nCells = verticesOnCell.shape[0]\n",
" triIndex = 0\n",
" for j in range(nCells):\n",
" for i in range(nEdgesOnCell[j] - 2):\n",
" triangles[triIndex][0] = verticesOnCell[j][0]\n",
" triangles[triIndex][1] = verticesOnCell[j][i + 1]\n",
" triangles[triIndex][2] = verticesOnCell[j][i + 2]\n",
" triIndex += 1\n",
"\n",
" return triangles"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Load data and coordinates"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
":::{info}\n",
"The \"dyamond_1\" global datasets used in this example are courtesy of NCAR's Falko Judt and were produced as part of the \n",
"[DYAMOND](http://dx.doi.org/10.1186/s40645-019-0304-z) initiative. They are all from the same experiment but run at several \n",
"resolutions from 30km to 3.75km.\n",
":::"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Currently, the 30-km resolution dataset is used in this example and is available at [geocat-datafiles](https://github.com/NCAR/geocat-datafiles).\n",
"However, the other resolutions of these data are stored on NCAR's Glade data storage because of their size. Due to their size, \n",
"the higher resolution data sets are only distributed with two variables in them:\n",
"\n",
"+ relhum_200hPa: Relative humidity vertically interpolated to 200 hPa\n",
"+ vorticity_200hPa: Relative vorticity vertically interpolated to 200 hPa\n",
"\n",
"The \"relhum_200hPa\" variable is computed on the MPAS 'primal' mesh, while \"vorticity_200hPa\" is computed on the MPAS\n",
"'dual' mesh."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"tags": []
},
"outputs": [],
"source": [
"# Load data\n",
"datafiles = (\n",
" gdf.get(\n",
" \"netcdf_files/MPAS/FalkoJudt/dyamond_1/30km/diag.2016-08-20_00.00.00_subset.nc\"\n",
" ),\n",
" gdf.get(\"netcdf_files/MPAS/FalkoJudt/dyamond_1/30km/x1.655362.grid_subset.nc\"),\n",
")\n",
"\n",
"primalVarName = \"relhum_200hPa\"\n",
"dualVarName = \"vorticity_200hPa\"\n",
"central_longitude = 0.0\n",
"\n",
"ds = open_mfdataset(datafiles, decode_times=False)\n",
"primalVar = ds[primalVarName].isel(Time=0).values\n",
"dualVar = ds[dualVarName].isel(Time=0).values\n",
"\n",
"# Fetch lat and lon coordinates for the primal and dual mesh.\n",
"lonCell = ds[\"lonCell\"].values * 180.0 / math.pi\n",
"latCell = ds[\"latCell\"].values * 180.0 / math.pi\n",
"lonCell = ((lonCell - 180.0) % 360.0) - 180.0\n",
"\n",
"lonVertex = ds[\"lonVertex\"].values * 180.0 / math.pi\n",
"latVertex = ds[\"latVertex\"].values * 180.0 / math.pi\n",
"lonVertex = ((lonVertex - 180.0) % 360.0) - 180.0"
]
},
{
"cell_type": "markdown",
"metadata": {
"tags": []
},
"source": [
"### Generate triangular mesh using MPAS connectivity information"
]
},
{
"cell_type": "markdown",
"metadata": {
"tags": []
},
"source": [
"#### Primal mesh\n",
"\n",
"In this example, we use the MPAS `cellsOnVertex` auxilliary variable, which defines mesh connectivity for the MPAS grid. Specifically, this variable tells us the cell indices contained by each cell."
]
},
{
"cell_type": "markdown",
"metadata": {
"tags": []
},
"source": [
":::{important}\n",
"The benefits of this are twofold: \n",
"1. We're using the actual mesh description from the MPAS output file\n",
"2. For large grid this is *much* faster than synthesizing the connectivity information (e.g. by triangulating them with, for example, Delaunay triangulation).\n",
":::"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"So, first let's: \n",
"- Get the triangle indices (i.e. MPAS connectivity),\n",
"- Make sure it is all in counter-clockwise order,\n",
"- \"Unzip\" the mesh along the longitude (for now, assuming the central longitude from the map projection is 0.0, i.e. cutting the mesh where longitude wraps around from -180.0 to 180.0)\n",
"- Project vertices from geographic to PCS coordinates\n",
"- Create Holoviews TriMesh"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
":::{note}\n",
"Indexing in MPAS starts from 1, not zero :-(\n",
":::"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"tags": []
},
"outputs": [],
"source": [
"tris = ds.cellsOnVertex.values - 1\n",
"\n",
"tris = orderCCW(lonCell, latCell, tris)\n",
"\n",
"tris = unzipMesh(lonCell, tris, 90.0)\n",
"\n",
"projection = ccrs.Robinson(central_longitude=central_longitude)\n",
"xPCS, yPCS, _ = projection.transform_points(ccrs.PlateCarree(), lonCell, latCell).T\n",
"\n",
"trimesh = createHVTriMesh(xPCS, yPCS, tris, primalVar, n_workers=n_workers)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"#### Dual mesh\n",
"\n",
"In this example though, we use the MPAS `verticesOnCell` and `nEdgesOnCell` auxilliary variables, which defines mesh connectivity for the MPAS dual grid. A lot of details in the following code is similarv to those in the primal mesh's case except `triangulatePoly()` wheere we decompose each cell into triangles since for the dual mesh, the data are located on triangle centers, which correspond to cell (polygon) vertices."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"verticesOnCell = ds.verticesOnCell.values - 1\n",
"nEdgesOnCell = ds.nEdgesOnCell.values\n",
"\n",
"tris_dual = triangulatePoly(verticesOnCell, nEdgesOnCell)\n",
"\n",
"tris_dual = unzipMesh(lonVertex, tris_dual, 90.0)\n",
"\n",
"projection = ccrs.Robinson(central_longitude=central_longitude)\n",
"xPCS_dual, yPCS_dual, _ = projection.transform_points(\n",
" ccrs.PlateCarree(), lonVertex, latVertex\n",
").T\n",
"\n",
"trimesh_dual = createHVTriMesh(\n",
" xPCS_dual, yPCS_dual, tris_dual, dualVar, n_workers=n_workers\n",
")"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Interactive HoloViz Plots"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
":::{note} \n",
"Since the emphasis of these plots is the interactivity, we will not provide much detail on the features/arguments other than interactivity-related ones, but such details to some extent can still be found in the code comments.\n",
":::"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"HoloViz tools provide essential interactivity features such as panning, zooming, \n",
"hovering, clickable/selectable legends, etc. on a plot."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
":::{note} \n",
"The first step to achieve interactivity with HoloViz tools is to choose `bokeh` as \n",
"the backend: \n",
":::"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"hv.extension(\"bokeh\")"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Let's define keyword arguments that will be commonly used for all of the plots and their `opts` throughout. For that, the plotting arguments are `aggregator=mean` to use the average of node values for shading in the rasterization and `precompute=True` to cache the data internally; the `opts` arguments are nothing more than opting in to showing the colorbar and using a colormap called \"coolwarm\":"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"plot_kwargs = {\n",
" \"aggregator\": \"mean\",\n",
" \"precompute\": True,\n",
"}\n",
"\n",
"opts_kwargs = {\n",
" \"colorbar\": True,\n",
" \"cmap\": \"coolwarm\",\n",
"}"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Holoviews' options system: `opts`\n",
"\n",
"HoloViz packages provide high-level visualization functions that allow the customization of plot features through optional arguments. Furthermore, the HoloViews options system allows customizing a plot from title to size, legend, axes, and more. This system works by calling the `.opts()` method through a HoloViews plot object. We will set the `opts` defaults below and then customize plots throughout the notebook via `.opts()`. Keep an eye on them!"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"opts.defaults(\n",
" opts.Image(frame_width=600, data_aspect=1),\n",
")"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Pan & zoom\n",
"\n",
"Bokeh-rendered HoloViz plots come with default pan and zoom (box & wheel), tools as well as save and reset options in the very right. Just look at the following plot for those features, which uses Datashader's rasterization method to visualize the data."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"tags": []
},
"outputs": [],
"source": [
"rasterized = hds_rasterize(trimesh, **plot_kwargs)\n",
"rasterized.opts(**opts_kwargs) * gf.coastline(projection=projection)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Hover\n",
"\n",
"Use `tools=['hover']` can be used to get the plot to display data values while hovering over the plot (there are other tools that can be selected, too, but those will not be covered in this notebook). See the below plot (let's use the dual mesh data this time just for the sake of assortment of visualizations) and hover you cursor over it:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"scrolled": true
},
"outputs": [],
"source": [
"rasterized = hds_rasterize(trimesh_dual, **plot_kwargs)\n",
"rasterized.opts(tools=[\"hover\"], clim=(-4e-4, 4e-4), **opts_kwargs) * gf.coastline(\n",
" projection=projection\n",
")"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Dynamic plot"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"You can decide whether to return a dynamic plot that sends updates on widget and zoom/pan \n",
"events or whether all the data should be embedded by using the boolean `dynamic` argument. \n",
"The default value of this argument is `True`, so all the previously rendered plots were \n",
"already dynamic. "
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
":::{warning}\n",
"If you are looking at this through the Pythia Cookbook gallery webpage (i.e. this is a rendered notebook as html), you cannot experience how the \"dynamic\" option works. To do that, you have to execute the notebook live (e.g. through the Binder link we provide for the cookbook or by executing it in your local).\n",
":::"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Now let's look at a non-dynamic plot (i.e. `dynamic=False`):"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"rasterized = hds_rasterize(trimesh, **plot_kwargs, dynamic=False)\n",
"rasterized.opts(**opts_kwargs) * gf.coastline(projection=projection)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
":::{tip}\n",
"This plot does not look immediately different than the prior ones where `dynamic=True`, right? Yes, in the global view, but try zooming into the plot (again, if you are executing notebook rather than looking at the rendered one), and see how dynamic vs. non-dynamic plots look like. See the below comparison for instance:\n",
":::"
]
},
{
"attachments": {},
"cell_type": "markdown",
"metadata": {},
"source": [
"Non-Dynamic-Zoomed | Dynamic-Zoomed\n",
":-------------------------:|:-------------------------:\n",
"![non-dynamic-zoomed](images/hv-non-dynamic-zoomed.png) | ![dynamic-zoomed](images/hv-dynamic-zoomed.png)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Further interactivity considerations\n",
"\n",
"Even though we will not cover in the scope of this cookbook, you may want to have a look at the following HoloViz resources for further interactivity in your plots:\n",
"\n",
"- [Mandelbrot](https://holoviews.org/gallery/apps/bokeh/mandelbrot.html)\n",
"- [Player](https://holoviews.org/reference/apps/bokeh/player.html)\n",
"- [HoloMap](https://holoviews.org/reference/containers/bokeh/HoloMap.html)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Summary\n",
"\n",
"HoloViz technologies can be used in order to create interactive plots when Bokeh is used as the backend. Even though a really large dataset (e.g. km-scale) is not \n",
"showcased in this notebook, HoloViz packages are reasonably performant with visualization of such data, too.\n",
"\n",
"### What's next?\n",
"\n",
"The end of this notebook wraps up this cookbook as well. Thanks for reading!\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Resources and references\n",
"\n",
"- [MPAS Mesh Specification](https://mpas-dev.github.io/files/documents/MPAS-MeshSpec.pdf) for those interested"
]
}
],
"metadata": {
"kernelspec": {
"display_name": "Python 3 (ipykernel)",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.11.6"
},
"widgets": {
"application/vnd.jupyter.widget-state+json": {
"state": {},
"version_major": 2,
"version_minor": 0
}
}
},
"nbformat": 4,
"nbformat_minor": 4
}