Skip to content

Commit a114379

Browse files
Merge branch 'v4-dev' into time_dt_as_float
2 parents 8c042d3 + 6f178dc commit a114379

File tree

6 files changed

+261
-381
lines changed

6 files changed

+261
-381
lines changed
Lines changed: 144 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,144 @@
1+
---
2+
file_format: mystnb
3+
kernelspec:
4+
name: python3
5+
---
6+
7+
# The Parcels Kernel loop
8+
9+
On this page we discuss Parcels' execution loop, and what happens under the hood when you combine multiple Kernels.
10+
11+
This is not very relevant when you only use the built-in Advection kernels, but can be important when you are writing and combining your own Kernels!
12+
13+
## Background
14+
15+
When you run a Parcels simulation (i.e. a call to `pset.execute()`), the Kernel loop is the main part of the code that is executed. This part of the code loops through time and executes the Kernels for all particle.
16+
17+
In order to make sure that the displacements of a particle in the different Kernels can be summed, all Kernels add to a _change_ in position (`particles.dlon`, `particles.dlat`, and `particles.dz`). This is important, because there are situations where movement kernels would otherwise not commute. Take the example of advecting particles by currents _and_ winds. If the particle would first be moved by the currents and then by the winds, the result could be different from first moving by the winds and then by the currents. Instead, by summing the _changes_ in position, the ordering of the Kernels has no consequence on the particle displacement.
18+
19+
## Basic implementation
20+
21+
Below is a structured overview of how the Kernel loop is implemented. Note that this is for `time` and `lon` only, but the process for `lon` is also applied to `lat` and `z`.
22+
23+
1. Initialise an extra Variable `particles.dlon=0`
24+
25+
2. Within the Kernel loop, for each particle:
26+
1. Update `particles.lon += particles.dlon`
27+
28+
2. Update `particles.time += particles.dt` (except for on the first iteration of the Kernel loop)<br>
29+
30+
3. Set variable `particles.dlon = 0`
31+
32+
4. For each Kernel in the list of Kernels:
33+
1. Execute the Kernel
34+
35+
2. Update `particles.dlon` by adding the change in longitude, if needed
36+
37+
5. If `outputdt` is a multiple of `particles.time`, write `particles.lon` and `particles.time` to zarr output file
38+
39+
Besides having commutable Kernels, the main advantage of this implementation is that, when using Field Sampling with e.g. `particles.temp = fieldset.Temp[particles.time, particles.z, particles.lat, particles.lon]`, the particle location stays the same throughout the entire Kernel loop. Additionally, this implementation ensures that the particle location is the same as the location of the sampled field in the output file.
40+
41+
## Example with currents and winds
42+
43+
Below is a simple example of some particles at the surface of the ocean. We create an idealised zonal wind flow that will "push" a particle that is already affected by the surface currents. The Kernel loop ensures that these two forces act at the same time and location.
44+
45+
```{code-cell}
46+
import matplotlib.pyplot as plt
47+
import numpy as np
48+
import xarray as xr
49+
50+
import parcels
51+
52+
# Load the CopernicusMarine data in the Agulhas region from the example_datasets
53+
example_dataset_folder = parcels.download_example_dataset(
54+
"CopernicusMarine_data_for_Argo_tutorial"
55+
)
56+
57+
ds_fields = xr.open_mfdataset(f"{example_dataset_folder}/*.nc", combine="by_coords")
58+
ds_fields.load() # load the dataset into memory
59+
60+
# Create an idealised wind field and add it to the dataset
61+
tdim, ydim, xdim = (len(ds_fields.time),len(ds_fields.latitude), len(ds_fields.longitude))
62+
ds_fields["UWind"] = xr.DataArray(
63+
data=np.ones((tdim, ydim, xdim)) * np.sin(ds_fields.latitude.values)[None, :, None],
64+
coords=[ds_fields.time, ds_fields.latitude, ds_fields.longitude])
65+
66+
ds_fields["VWind"] = xr.DataArray(
67+
data=np.zeros((tdim, ydim, xdim)),
68+
coords=[ds_fields.time, ds_fields.latitude, ds_fields.longitude])
69+
70+
fieldset = parcels.FieldSet.from_copernicusmarine(ds_fields)
71+
72+
# Set unit converters for custom wind fields
73+
fieldset.UWind.units = parcels.GeographicPolar()
74+
fieldset.VWind.units = parcels.Geographic()
75+
```
76+
77+
Now we define a wind kernel that uses a forward Euler method to apply the wind forcing. Note that we update the `particles.dlon` and `particles.dlat` variables, rather than `particles.lon` and `particles.lat` directly.
78+
79+
```{code-cell}
80+
def wind_kernel(particles, fieldset):
81+
dt_float = particles.dt / np.timedelta64(1, 's')
82+
particles.dlon += (
83+
fieldset.UWind[particles] * dt_float
84+
)
85+
particles.dlat += (
86+
fieldset.VWind[particles] * dt_float
87+
)
88+
```
89+
90+
First run a simulation where we apply kernels as `[AdvectionRK4, wind_kernel]`
91+
92+
```{code-cell}
93+
:tags: [hide-output]
94+
npart = 10
95+
z = np.repeat(ds_fields.depth[0].values, npart)
96+
lons = np.repeat(31, npart)
97+
lats = np.linspace(-32.5, -30.5, npart)
98+
99+
pset = parcels.ParticleSet(fieldset, pclass=parcels.Particle, z=z, lat=lats, lon=lons)
100+
output_file = parcels.ParticleFile(
101+
store="advection_then_wind.zarr", outputdt=np.timedelta64(6,'h')
102+
)
103+
pset.execute(
104+
[parcels.kernels.AdvectionRK4, wind_kernel],
105+
runtime=np.timedelta64(5,'D'),
106+
dt=np.timedelta64(1,'h'),
107+
output_file=output_file,
108+
)
109+
```
110+
111+
Then also run a simulation where we apply the kernels in the reverse order as `[wind_kernel, AdvectionRK4]`
112+
113+
```{code-cell}
114+
:tags: [hide-output]
115+
pset_reverse = parcels.ParticleSet(
116+
fieldset, pclass=parcels.Particle, z=z, lat=lats, lon=lons
117+
)
118+
output_file_reverse = parcels.ParticleFile(
119+
store="wind_then_advection.zarr", outputdt=np.timedelta64(6,"h")
120+
)
121+
pset_reverse.execute(
122+
[wind_kernel, parcels.kernels.AdvectionRK4],
123+
runtime=np.timedelta64(5,"D"),
124+
dt=np.timedelta64(1,"h"),
125+
output_file=output_file_reverse,
126+
)
127+
```
128+
129+
Finally, plot the trajectories to show that they are identical in the two simulations.
130+
131+
```{code-cell}
132+
# Plot the resulting particle trajectories overlapped for both cases
133+
advection_then_wind = xr.open_zarr("advection_then_wind.zarr")
134+
wind_then_advection = xr.open_zarr("wind_then_advection.zarr")
135+
plt.plot(wind_then_advection.lon.T, wind_then_advection.lat.T, "-")
136+
plt.plot(advection_then_wind.lon.T, advection_then_wind.lat.T, "--", c="k", alpha=0.7)
137+
plt.show()
138+
```
139+
140+
```{warning}
141+
It is better not to update `particles.lon` directly in a Kernel, as it can interfere with the loop above. Assigning a value to `particles.lon` in a Kernel will throw a warning.
142+
143+
Instead, update the local variable `particles.dlon`.
144+
```
Lines changed: 104 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,104 @@
1+
---
2+
file_format: mystnb
3+
kernelspec:
4+
name: python3
5+
---
6+
7+
# Working with Status Codes
8+
9+
In order to capture errors in the [Kernel loop](explanation_kernelloop.md), Parcels uses a Status Code system. There are several Status Codes, listed below.
10+
11+
```{code-cell}
12+
import parcels
13+
14+
for statuscode, val in parcels.StatusCode.__dict__.items():
15+
if statuscode.startswith("__"):
16+
continue
17+
print(f"{statuscode} = {val}")
18+
```
19+
20+
Once an error is thrown (for example, a Field Interpolation error), then the `particles.state` is updated to the corresponding status code. This gives you the flexibility to write a Kernel that checks for a status code and does something with it.
21+
22+
For example, you can write a Kernel that checks for `particles.state == parcels.StatusCode.ErrorOutOfBounds` and deletes the particle, and then append this custom Kernel to the Kernel list in `pset.execute()`.
23+
24+
```
25+
def DeleteOutOfBounds(particles, fieldset):
26+
out_of_bounds = particles.state == parcels.StatusCode.ErrorOutOfBounds
27+
particles[out_of_bounds].state = parcels.StatusCode.Delete
28+
29+
30+
def DeleteAnyError(particles, fieldset):
31+
any_error = particles.state >= 50 # This captures all Errors
32+
particles[any_error].state = parcels.StatusCode.Delete
33+
```
34+
35+
But of course, you can also write code for more sophisticated behaviour than just deleting the particle. It's up to you! Note that if you don't delete the particle, you will have to update the `particles.state = parcels.StatusCode.Evaluate` yourself. For example:
36+
37+
```
38+
def Move1DegreeWest(particles, fieldset):
39+
out_of_bounds = particles.state == parcels.StatusCode.ErrorOutOfBounds
40+
particles[out_of_bounds].dlon -= 1.0
41+
particles[out_of_bounds].state = parcels.StatusCode.Evaluate
42+
```
43+
44+
Or, if you want to make sure that particles don't escape through the water surface
45+
46+
```{code-cell}
47+
def KeepInOcean(particles, fieldset):
48+
# find particles that move through the surface
49+
through_surface = particles.state == parcels.StatusCode.ErrorThroughSurface
50+
51+
# move particles to surface
52+
particles[through_surface].dz = fieldset.W.grid.depth[0] - particles[through_surface].z
53+
54+
# change state from error to evaluate
55+
particles[through_surface].state = parcels.StatusCode.Evaluate
56+
```
57+
58+
Kernel functions such as the ones above can then be added to the list of kernels in `pset.execute()`.
59+
60+
Let's add the `KeepInOcean` Kernel to an particle simulation where particles move through the surface:
61+
62+
```{code-cell}
63+
import numpy as np
64+
from parcels._datasets.structured.generated import simple_UV_dataset
65+
66+
ds = simple_UV_dataset(dims=(1, 2, 5, 4), mesh="flat").isel(time=0)
67+
68+
dx, dy = 1.0 / len(ds.XG), 1.0 / len(ds.YG)
69+
70+
# Add W velocity that pushes through surface
71+
ds["W"] = ds["U"] - 0.1 # 0.1 m/s towards the surface
72+
73+
grid = parcels.XGrid.from_dataset(ds, mesh="flat")
74+
U = parcels.Field("U", ds["U"], grid, interp_method=parcels.interpolators.XLinear)
75+
V = parcels.Field("V", ds["V"], grid, interp_method=parcels.interpolators.XLinear)
76+
W = parcels.Field("W", ds["W"], grid, interp_method=parcels.interpolators.XLinear)
77+
UVW = parcels.VectorField("UVW", U, V, W)
78+
fieldset = parcels.FieldSet([U, V, W, UVW])
79+
```
80+
81+
If we advect particles with the `AdvectionRK2_3D` kernel, Parcels will raise a `FieldOutOfBoundSurfaceError`:
82+
83+
```{code-cell}
84+
:tags: [raises-exception]
85+
pset = parcels.ParticleSet(fieldset, parcels.Particle, z=[0.5], lat=[2], lon=[1.5])
86+
kernels = [parcels.kernels.AdvectionRK2_3D]
87+
pset.execute(kernels, runtime=np.timedelta64(1, "m"), dt=np.timedelta64(1, "s"), verbose_progress=False)
88+
```
89+
90+
When we add the `KeepInOcean` Kernel, particles will stay at the surface:
91+
92+
```{code-cell}
93+
pset = parcels.ParticleSet(fieldset, parcels.Particle, z=[0.5], lat=[2], lon=[1.5])
94+
95+
kernels = [parcels.kernels.AdvectionRK2_3D, KeepInOcean]
96+
97+
pset.execute(kernels,runtime=np.timedelta64(20, "s"), dt=np.timedelta64(1, "s"), verbose_progress=False)
98+
99+
print(f"particle z at end of run = {pset.z}")
100+
```
101+
102+
```{note}
103+
Kernels that control what to do with `particles.state` should typically be added at the _end_ of the Kernel list, because otherwise later Kernels may overwrite the `particles.state` or the `particles.dlon` variables (see [Kernel loop explanation](explanation_kernelloop.md)).
104+
```

0 commit comments

Comments
 (0)