|
| 1 | +{ |
| 2 | + "cells": [ |
| 3 | + { |
| 4 | + "attachments": {}, |
| 5 | + "cell_type": "markdown", |
| 6 | + "metadata": {}, |
| 7 | + "source": [ |
| 8 | + "# Using `parcels.interpolators`\n", |
| 9 | + "Parcels comes with a number of different interpolation methods for tracer fields, such as temperature. Here, we will look at a few common `parcels.interpolators` for structured (`X`) grids, and how to configure them in an idealised example. For more guidance on the sampling of such fields, check out the [sampling tutorial](./tutorial_sampling).\n", |
| 10 | + "\n", |
| 11 | + "We first import the relevant modules" |
| 12 | + ] |
| 13 | + }, |
| 14 | + { |
| 15 | + "cell_type": "code", |
| 16 | + "execution_count": null, |
| 17 | + "metadata": {}, |
| 18 | + "outputs": [], |
| 19 | + "source": [ |
| 20 | + "import matplotlib.pyplot as plt\n", |
| 21 | + "import numpy as np\n", |
| 22 | + "from matplotlib import cm\n", |
| 23 | + "\n", |
| 24 | + "import parcels" |
| 25 | + ] |
| 26 | + }, |
| 27 | + { |
| 28 | + "attachments": {}, |
| 29 | + "cell_type": "markdown", |
| 30 | + "metadata": {}, |
| 31 | + "source": [ |
| 32 | + "We create a small 2D structured grid, where `P` is a tracer that we want to interpolate. In each grid cell, `P` has a random value between 0.1 and 1.1. We then set `P[1,1]` to `0`, which for Parcels specifies that this is a land cell\n" |
| 33 | + ] |
| 34 | + }, |
| 35 | + { |
| 36 | + "cell_type": "code", |
| 37 | + "execution_count": null, |
| 38 | + "metadata": {}, |
| 39 | + "outputs": [], |
| 40 | + "source": [ |
| 41 | + "from parcels._datasets.structured.generated import simple_UV_dataset\n", |
| 42 | + "\n", |
| 43 | + "ds = simple_UV_dataset(dims=(1, 1, 5, 4), mesh=\"flat\").isel(time=0, depth=0)\n", |
| 44 | + "ds[\"lat\"][:] = np.linspace(0.0, 1.0, len(ds.YG))\n", |
| 45 | + "ds[\"lon\"][:] = np.linspace(0.0, 1.0, len(ds.XG))\n", |
| 46 | + "dx, dy = 1.0 / len(ds.XG), 1.0 / len(ds.YG)\n", |
| 47 | + "ds[\"P\"] = ds[\"U\"] + np.random.rand(5, 4) + 0.1\n", |
| 48 | + "ds[\"P\"][1, 1] = 0\n", |
| 49 | + "ds" |
| 50 | + ] |
| 51 | + }, |
| 52 | + { |
| 53 | + "cell_type": "markdown", |
| 54 | + "metadata": {}, |
| 55 | + "source": [ |
| 56 | + "From this dataset we create a `parcels.FieldSet`. Parcels requires an interpolation method to be set for each `parcels.Field`, which we will later adapt to see the effects of the different interpolators. A common interpolator for fields on structured grids is (tri)linear, implemented in `parcels.interpolators.XLinear`." |
| 57 | + ] |
| 58 | + }, |
| 59 | + { |
| 60 | + "cell_type": "code", |
| 61 | + "execution_count": null, |
| 62 | + "metadata": {}, |
| 63 | + "outputs": [], |
| 64 | + "source": [ |
| 65 | + "grid = parcels.XGrid.from_dataset(ds, mesh=\"flat\")\n", |
| 66 | + "U = parcels.Field(\"U\", ds[\"U\"], grid, interp_method=parcels.interpolators.XLinear)\n", |
| 67 | + "V = parcels.Field(\"V\", ds[\"V\"], grid, interp_method=parcels.interpolators.XLinear)\n", |
| 68 | + "UV = parcels.VectorField(\"UV\", U, V)\n", |
| 69 | + "P = parcels.Field(\"P\", ds[\"P\"], grid, interp_method=parcels.interpolators.XLinear)\n", |
| 70 | + "fieldset = parcels.FieldSet([U, V, UV, P])" |
| 71 | + ] |
| 72 | + }, |
| 73 | + { |
| 74 | + "attachments": {}, |
| 75 | + "cell_type": "markdown", |
| 76 | + "metadata": {}, |
| 77 | + "source": [ |
| 78 | + "We create a Particle class that can sample this field `P`." |
| 79 | + ] |
| 80 | + }, |
| 81 | + { |
| 82 | + "cell_type": "code", |
| 83 | + "execution_count": null, |
| 84 | + "metadata": {}, |
| 85 | + "outputs": [], |
| 86 | + "source": [ |
| 87 | + "SampleParticle = parcels.Particle.add_variable(\n", |
| 88 | + " parcels.Variable(\"p\", dtype=np.float32, initial=np.nan)\n", |
| 89 | + ")\n", |
| 90 | + "\n", |
| 91 | + "\n", |
| 92 | + "def SampleP(particles, fieldset):\n", |
| 93 | + " particles.p = fieldset.P[particles]" |
| 94 | + ] |
| 95 | + }, |
| 96 | + { |
| 97 | + "attachments": {}, |
| 98 | + "cell_type": "markdown", |
| 99 | + "metadata": {}, |
| 100 | + "source": [ |
| 101 | + "Now, we perform four different interpolations on `P`, which we can control by setting `fieldset.P.interp_method`. Note that this can always be done _after_ the `FieldSet` creation. We store the results of each interpolation method in an entry in the dictionary `pset`." |
| 102 | + ] |
| 103 | + }, |
| 104 | + { |
| 105 | + "cell_type": "code", |
| 106 | + "execution_count": null, |
| 107 | + "metadata": { |
| 108 | + "tags": [ |
| 109 | + "hide-output" |
| 110 | + ] |
| 111 | + }, |
| 112 | + "outputs": [], |
| 113 | + "source": [ |
| 114 | + "pset = {}\n", |
| 115 | + "from parcels.interpolators import (\n", |
| 116 | + " CGrid_Tracer,\n", |
| 117 | + " XLinear,\n", |
| 118 | + " XLinearInvdistLandTracer,\n", |
| 119 | + " XNearest,\n", |
| 120 | + ")\n", |
| 121 | + "\n", |
| 122 | + "interp_methods = [XLinear, XLinearInvdistLandTracer, XNearest, CGrid_Tracer]\n", |
| 123 | + "for p_interp in interp_methods:\n", |
| 124 | + " fieldset.P.interp_method = (\n", |
| 125 | + " p_interp # setting the interpolation method for fieldset.P\n", |
| 126 | + " )\n", |
| 127 | + "\n", |
| 128 | + " print(fieldset.P.interp_method.__name__)\n", |
| 129 | + " xv, yv = np.meshgrid(np.linspace(0, 1, 8), np.linspace(0, 1, 8))\n", |
| 130 | + " pset[p_interp.__name__] = parcels.ParticleSet(\n", |
| 131 | + " fieldset, pclass=SampleParticle, lon=xv.flatten(), lat=yv.flatten()\n", |
| 132 | + " )\n", |
| 133 | + " pset[p_interp.__name__].execute(\n", |
| 134 | + " SampleP, runtime=np.timedelta64(1, \"D\"), dt=np.timedelta64(1, \"D\")\n", |
| 135 | + " )" |
| 136 | + ] |
| 137 | + }, |
| 138 | + { |
| 139 | + "attachments": {}, |
| 140 | + "cell_type": "markdown", |
| 141 | + "metadata": {}, |
| 142 | + "source": [ |
| 143 | + "And then we can show each of the four interpolation methods, by plotting the interpolated values on the `Particles` locations (circles) on top of the `Field` values (background colors)\n" |
| 144 | + ] |
| 145 | + }, |
| 146 | + { |
| 147 | + "cell_type": "code", |
| 148 | + "execution_count": null, |
| 149 | + "metadata": {}, |
| 150 | + "outputs": [], |
| 151 | + "source": [ |
| 152 | + "fig, ax = plt.subplots(1, 4, figsize=(18, 6))\n", |
| 153 | + "for i, p in enumerate(pset.keys()):\n", |
| 154 | + " data = np.copy(fieldset.P.data[0, 0, :, :])\n", |
| 155 | + " data[1, 1] = np.nan\n", |
| 156 | + " x = np.linspace(-dx / 2, 1 + dx / 2, len(ds.XG) + 1)\n", |
| 157 | + " y = np.linspace(-dy / 2, 1 + dy / 2, len(ds.YG) + 1)\n", |
| 158 | + " if p == \"CGrid_Tracer\":\n", |
| 159 | + " for lat in fieldset.P.grid.lat:\n", |
| 160 | + " ax[i].axhline(lat, color=\"k\", linestyle=\"--\")\n", |
| 161 | + " for lon in fieldset.P.grid.lon:\n", |
| 162 | + " ax[i].axvline(lon, color=\"k\", linestyle=\"--\")\n", |
| 163 | + " pc = ax[i].pcolormesh(x, y, data, vmin=0.1, vmax=1.1)\n", |
| 164 | + " ax[i].scatter(\n", |
| 165 | + " pset[p].lon, pset[p].lat, c=pset[p].p, edgecolors=\"k\", s=50, vmin=0.1, vmax=1.1\n", |
| 166 | + " )\n", |
| 167 | + " xp, yp = np.meshgrid(fieldset.P.grid.lon, fieldset.P.grid.lat)\n", |
| 168 | + " ax[i].plot(xp, yp, \"kx\")\n", |
| 169 | + " ax[i].set_title(f\"Using interp_method='{p}'\")\n", |
| 170 | + "plt.colorbar(pc, ax=ax, orientation=\"horizontal\", shrink=0.5)\n", |
| 171 | + "plt.show()" |
| 172 | + ] |
| 173 | + }, |
| 174 | + { |
| 175 | + "attachments": {}, |
| 176 | + "cell_type": "markdown", |
| 177 | + "metadata": {}, |
| 178 | + "source": [ |
| 179 | + "The white box is here the 'land' point where the tracer is set to zero and the crosses are the locations of the grid points. As you see, the interpolated value is always equal to the field value if the particle is exactly on the grid point (circles on crosses).\n", |
| 180 | + "\n", |
| 181 | + "For `interp_method='XNearest'`, the particle values are the same for all particles in a grid cell. They are also the same for `interp_method='CGrid_Tracer'`, but the grid cells have then shifted. That is because in a C-grid, the tracer is defined on the corners of the velocity grid (black dashed lines in right-most panel).\n", |
| 182 | + "\n", |
| 183 | + "```{note}\n", |
| 184 | + "TODO: check C-grid indexing after implementation in v4\n", |
| 185 | + "```\n", |
| 186 | + "\n", |
| 187 | + "For `interp_method='XLinearInvdistLandTracer'`, we see that values are the same as `interp_method='XLinear'` for grid cells that don't border the land point. For grid cells that do border the land cell, the `XLinearInvdistLandTracer` interpolation method gives higher values, as also shown in the difference plot below.\n" |
| 188 | + ] |
| 189 | + }, |
| 190 | + { |
| 191 | + "cell_type": "code", |
| 192 | + "execution_count": null, |
| 193 | + "metadata": {}, |
| 194 | + "outputs": [], |
| 195 | + "source": [ |
| 196 | + "plt.scatter(\n", |
| 197 | + " pset[\"XLinear\"].lon,\n", |
| 198 | + " pset[\"XLinear\"].lat,\n", |
| 199 | + " c=pset[\"XLinearInvdistLandTracer\"].p - pset[\"XLinear\"].p,\n", |
| 200 | + " edgecolors=\"k\",\n", |
| 201 | + " s=50,\n", |
| 202 | + " cmap=cm.bwr,\n", |
| 203 | + " vmin=-0.05,\n", |
| 204 | + " vmax=0.05,\n", |
| 205 | + ")\n", |
| 206 | + "xp, yp = np.meshgrid(fieldset.P.grid.lon, fieldset.P.grid.lat)\n", |
| 207 | + "plt.plot(xp, yp, \"kx\")\n", |
| 208 | + "plt.colorbar()\n", |
| 209 | + "plt.title(\n", |
| 210 | + " \"Difference between 'interp_method=XLinear' \"\n", |
| 211 | + " \"and 'interp_method=XLinearInvdistLandTracer'\"\n", |
| 212 | + ")\n", |
| 213 | + "plt.show()" |
| 214 | + ] |
| 215 | + }, |
| 216 | + { |
| 217 | + "attachments": {}, |
| 218 | + "cell_type": "markdown", |
| 219 | + "metadata": {}, |
| 220 | + "source": [ |
| 221 | + "So in summary, Parcels has four different interpolation schemes for tracers on structured grids:\n", |
| 222 | + "\n", |
| 223 | + "1. `interp_method=parcels.interpolators.XLinear`: compute linear interpolation\n", |
| 224 | + "2. `interp_method=parcels.interpolators.XLinearInvdistLandTracer`: compute linear interpolation except near land (where field value is zero). In that case, inverse distance weighting interpolation is computed, weighting by squares of the distance.\n", |
| 225 | + "3. `interp_method=parcels.interpolators.XNearest`: return nearest field value\n", |
| 226 | + "4. `interp_method=parcels.interpolators.CGridTracer`: return nearest field value supposing C cells\n", |
| 227 | + "\n", |
| 228 | + "In the special case where a `parcels.Field` is constant in time and space, such as implementing constant diffusion on a spherical mesh, we can use:\n", |
| 229 | + "\n", |
| 230 | + "5. `interp_method=parcels.interpolators.XConstantField`: return single value of a Constant Field" |
| 231 | + ] |
| 232 | + }, |
| 233 | + { |
| 234 | + "cell_type": "markdown", |
| 235 | + "metadata": {}, |
| 236 | + "source": [ |
| 237 | + "```{note}\n", |
| 238 | + "TODO: link to reference API with all `parcels.interpolators`\n", |
| 239 | + "```" |
| 240 | + ] |
| 241 | + }, |
| 242 | + { |
| 243 | + "cell_type": "markdown", |
| 244 | + "metadata": {}, |
| 245 | + "source": [ |
| 246 | + "## Interpolation on unstructured grids\n", |
| 247 | + "```{note}\n", |
| 248 | + "TODO: add example on simple unstructured fieldset\n", |
| 249 | + "```\n", |
| 250 | + "- UXPiecewiseConstantFace\n", |
| 251 | + "- UXPiecewiseLinearNode" |
| 252 | + ] |
| 253 | + }, |
| 254 | + { |
| 255 | + "cell_type": "markdown", |
| 256 | + "metadata": {}, |
| 257 | + "source": [ |
| 258 | + "## Interpolation at boundaries\n", |
| 259 | + "In some cases, we need to implement specific boundary conditions, for example to prevent particles from \n", |
| 260 | + "getting \"stuck\" near land. [This guide](../examples_v3/documentation_unstuck_Agrid.ipynb) describes \n", |
| 261 | + "how to implement this in parcels using `parcels.interpolators.XFreeslip` and `parcels.interpolators.XPartialslip`." |
| 262 | + ] |
| 263 | + }, |
| 264 | + { |
| 265 | + "cell_type": "markdown", |
| 266 | + "metadata": {}, |
| 267 | + "source": [ |
| 268 | + "## Write your own interpolator\n", |
| 269 | + "The interpolators included in Parcels are designed for common interpolation schemes in Parcels simulations. If we want to add a custom interpolation method, we can write a custom function (e.g. spline) using the [interpolator API](./explanation_interpolation.md#interpolator-api)." |
| 270 | + ] |
| 271 | + } |
| 272 | + ], |
| 273 | + "metadata": { |
| 274 | + "kernelspec": { |
| 275 | + "display_name": "test-notebooks", |
| 276 | + "language": "python", |
| 277 | + "name": "python3" |
| 278 | + }, |
| 279 | + "language_info": { |
| 280 | + "codemirror_mode": { |
| 281 | + "name": "ipython", |
| 282 | + "version": 3 |
| 283 | + }, |
| 284 | + "file_extension": ".py", |
| 285 | + "mimetype": "text/x-python", |
| 286 | + "name": "python", |
| 287 | + "nbconvert_exporter": "python", |
| 288 | + "pygments_lexer": "ipython3", |
| 289 | + "version": "3.11.0" |
| 290 | + } |
| 291 | + }, |
| 292 | + "nbformat": 4, |
| 293 | + "nbformat_minor": 4 |
| 294 | +} |
0 commit comments