Skip to content

Commit 7c28d80

Browse files
committed
escape hatches and a exercise
1 parent 68dbf32 commit 7c28d80

File tree

1 file changed

+72
-0
lines changed

1 file changed

+72
-0
lines changed

intermediate/hierarchical_computation.ipynb

Lines changed: 72 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -235,6 +235,78 @@
235235
"\n",
236236
"tree.map_over_datasets(demean)"
237237
]
238+
},
239+
{
240+
"cell_type": "markdown",
241+
"id": "21",
242+
"metadata": {},
243+
"source": [
244+
"## Escape hatches\n",
245+
"\n",
246+
"For some more complex operations, it might make sense to work on {py:class}`xarray.Dataset` or {py:class}`xarray.DataArray` objects and reassemble the tree afterwards.\n",
247+
"\n",
248+
"Let's look at a new dataset:"
249+
]
250+
},
251+
{
252+
"cell_type": "code",
253+
"execution_count": null,
254+
"id": "22",
255+
"metadata": {},
256+
"outputs": [],
257+
"source": [
258+
"precipitation = xr.tutorial.open_datatree(\"precipitation.nc4\").load()\n",
259+
"precipitation"
260+
]
261+
},
262+
{
263+
"cell_type": "markdown",
264+
"id": "23",
265+
"metadata": {},
266+
"source": [
267+
"Suppose we wanted to interpolate the observed precipitation to the modelled precipitation. We could use `map_over_datasets` for this, but we can also have a bit more control:"
268+
]
269+
},
270+
{
271+
"cell_type": "code",
272+
"execution_count": null,
273+
"id": "24",
274+
"metadata": {},
275+
"outputs": [],
276+
"source": [
277+
"interpolated = xr.DataTree.from_dict(\n",
278+
" {\n",
279+
" \"/\": precipitation.ds,\n",
280+
" \"/observed\": precipitation[\"/observed\"].ds.interp(\n",
281+
" lat=precipitation[\"/reanalysis/lat\"],\n",
282+
" lon=precipitation[\"/reanalysis/lon\"],\n",
283+
" ),\n",
284+
" \"/reanalysis\": precipitation[\"/reanalysis\"],\n",
285+
" }\n",
286+
")\n",
287+
"interpolated"
288+
]
289+
},
290+
{
291+
"cell_type": "markdown",
292+
"id": "25",
293+
"metadata": {},
294+
"source": [
295+
"::::{admonition} Exercise\n",
296+
":class: tip\n",
297+
"Compute the difference between total observed and modelled precipitation, and plot the result.\n",
298+
"\n",
299+
":::{admonition} Solution\n",
300+
":class: dropdown\n",
301+
"\n",
302+
"```python\n",
303+
"total = precipitation.sum(dim=[\"lon\", \"lat\"])\n",
304+
"difference = total[\"/observed/precipitation\"] - total[\"/reanalysis/precipitation\"]\n",
305+
"difference.plot()\n",
306+
"```\n",
307+
":::\n",
308+
"::::\n"
309+
]
238310
}
239311
],
240312
"metadata": {

0 commit comments

Comments
 (0)