|
| 1 | +""" |
| 2 | +Time advection |
| 3 | +============== |
| 4 | +
|
| 5 | +Example which use CMEMS surface current with a Runge-Kutta 4 algorithm to advect particles. |
| 6 | +""" |
| 7 | +# sphinx_gallery_thumbnail_number = 2 |
| 8 | +import re |
| 9 | +from datetime import datetime, timedelta |
| 10 | + |
| 11 | +from matplotlib import pyplot as plt |
| 12 | +from matplotlib.animation import FuncAnimation |
| 13 | +from numpy import arange, isnan, meshgrid, ones |
| 14 | + |
| 15 | +import py_eddy_tracker.gui |
| 16 | +from py_eddy_tracker import start_logger |
| 17 | +from py_eddy_tracker.data import get_path |
| 18 | +from py_eddy_tracker.dataset.grid import GridCollection |
| 19 | + |
| 20 | +start_logger().setLevel("ERROR") |
| 21 | + |
| 22 | + |
| 23 | +# %% |
| 24 | +class VideoAnimation(FuncAnimation): |
| 25 | + def _repr_html_(self, *args, **kwargs): |
| 26 | + """To get video in html and have a player""" |
| 27 | + content = self.to_html5_video() |
| 28 | + return re.sub( |
| 29 | + r'width="[0-9]*"\sheight="[0-9]*"', 'width="100%" height="100%"', content |
| 30 | + ) |
| 31 | + |
| 32 | + def save(self, *args, **kwargs): |
| 33 | + if args[0].endswith("gif"): |
| 34 | + # In this case gif is use to create thumbnail which are not use but consume same time than video |
| 35 | + # So we create an empty file, to save time |
| 36 | + with open(args[0], "w") as _: |
| 37 | + pass |
| 38 | + return |
| 39 | + return super().save(*args, **kwargs) |
| 40 | + |
| 41 | + |
| 42 | +# %% |
| 43 | +# Data |
| 44 | +# ---- |
| 45 | +# Load Input time grid ADT |
| 46 | +c = GridCollection.from_netcdf_cube( |
| 47 | + get_path("dt_med_allsat_phy_l4_2005T2.nc"), |
| 48 | + "longitude", |
| 49 | + "latitude", |
| 50 | + "time", |
| 51 | + # To create U/V variable |
| 52 | + heigth="adt", |
| 53 | +) |
| 54 | + |
| 55 | +# %% |
| 56 | +# Anim |
| 57 | +# ---- |
| 58 | +# Particles setup |
| 59 | +step_p = 1 / 8 |
| 60 | +x, y = meshgrid(arange(13, 36, step_p), arange(28, 40, step_p)) |
| 61 | +x, y = x.reshape(-1), y.reshape(-1) |
| 62 | +# Remove all original position that we can't advect at first place |
| 63 | +t0 = 20181 |
| 64 | +m = ~isnan(c[t0].interp("u", x, y)) |
| 65 | +x0, y0 = x[m], y[m] |
| 66 | +x, y = x0.copy(), y0.copy() |
| 67 | + |
| 68 | + |
| 69 | +# %% |
| 70 | +# Function |
| 71 | +def anim_ax(**kw): |
| 72 | + fig = plt.figure(figsize=(10, 5), dpi=55) |
| 73 | + axes = fig.add_axes([0, 0, 1, 1], projection="full_axes") |
| 74 | + axes.set_xlim(19, 30), axes.set_ylim(31, 36.5), axes.grid() |
| 75 | + line = axes.plot([], [], "k", **kw)[0] |
| 76 | + return fig, axes.text(21, 32.1, ""), line |
| 77 | + |
| 78 | + |
| 79 | +def update(_): |
| 80 | + tt, xt, yt = f.__next__() |
| 81 | + mappable.set_data(xt, yt) |
| 82 | + d = timedelta(tt / 86400.0) + datetime(1950, 1, 1) |
| 83 | + txt.set_text(f"{d:%Y/%m/%d-%H}") |
| 84 | + |
| 85 | + |
| 86 | +# %% |
| 87 | +f = c.filament(x, y, "u", "v", t_init=t0, nb_step=2, time_step=21600, filament_size=3) |
| 88 | +fig, txt, mappable = anim_ax(lw=0.5) |
| 89 | +ani = VideoAnimation(fig, update, frames=arange(160), interval=100) |
| 90 | + |
| 91 | + |
| 92 | +# %% |
| 93 | +# Particules stat |
| 94 | +# --------------- |
| 95 | +# Time_step settings |
| 96 | +# ^^^^^^^^^^^^^^^^^^ |
| 97 | +# Dummy experiment to test advection precision, we run particles 50 days forward and backward with different time step |
| 98 | +# and we measure distance between new positions and original positions. |
| 99 | +fig = plt.figure() |
| 100 | +ax = fig.add_subplot(111) |
| 101 | +kw = dict( |
| 102 | + bins=arange(0, 50, 0.002), |
| 103 | + cumulative=True, |
| 104 | + weights=ones(x0.shape) / x0.shape[0] * 100.0, |
| 105 | + histtype="step", |
| 106 | +) |
| 107 | +kw_p = dict(u_name="u", v_name="v", nb_step=1) |
| 108 | +for time_step in (10800, 21600, 43200, 86400): |
| 109 | + x, y = x0.copy(), y0.copy() |
| 110 | + nb = int(30 * 86400 / time_step) |
| 111 | + # Go forward |
| 112 | + p = c.advect(x, y, time_step=time_step, t_init=20181.5, **kw_p) |
| 113 | + for i in range(nb): |
| 114 | + t_, _, _ = p.__next__() |
| 115 | + # Go backward |
| 116 | + p = c.advect(x, y, time_step=time_step, backward=True, t_init=t_ / 86400.0, **kw_p) |
| 117 | + for i in range(nb): |
| 118 | + t_, _, _ = p.__next__() |
| 119 | + d = ((x - x0) ** 2 + (y - y0) ** 2) ** 0.5 |
| 120 | + ax.hist(d, **kw, label=f"{86400. / time_step:.0f} time step by day") |
| 121 | +ax.set_xlim(0, 0.25), ax.set_ylim(0, 100), ax.legend(loc="lower right"), ax.grid() |
| 122 | +ax.set_title("Distance after 50 days forward and 50 days backward") |
| 123 | +ax.set_xlabel("Distance between original position and final position (in degrees)") |
| 124 | +_ = ax.set_ylabel("Percent of particles with distance lesser than") |
| 125 | + |
| 126 | +# %% |
| 127 | +# Time duration |
| 128 | +# ^^^^^^^^^^^^^ |
| 129 | +# We keep same time_step but change time duration |
| 130 | +fig = plt.figure() |
| 131 | +ax = fig.add_subplot(111) |
| 132 | +time_step = 10800 |
| 133 | +for duration in (10, 40, 80): |
| 134 | + x, y = x0.copy(), y0.copy() |
| 135 | + nb = int(duration * 86400 / time_step) |
| 136 | + # Go forward |
| 137 | + p = c.advect(x, y, time_step=time_step, t_init=20181.5, **kw_p) |
| 138 | + for i in range(nb): |
| 139 | + t_, _, _ = p.__next__() |
| 140 | + # Go backward |
| 141 | + p = c.advect(x, y, time_step=time_step, backward=True, t_init=t_ / 86400.0, **kw_p) |
| 142 | + for i in range(nb): |
| 143 | + t_, _, _ = p.__next__() |
| 144 | + d = ((x - x0) ** 2 + (y - y0) ** 2) ** 0.5 |
| 145 | + ax.hist(d, **kw, label=f"Time duration {duration} days") |
| 146 | +ax.set_xlim(0, 0.25), ax.set_ylim(0, 100), ax.legend(loc="lower right"), ax.grid() |
| 147 | +ax.set_title( |
| 148 | + "Distance after N days forward and N days backward\nwith a time step of 1/8 days" |
| 149 | +) |
| 150 | +ax.set_xlabel("Distance between original position and final position (in degrees)") |
| 151 | +_ = ax.set_ylabel("Percent of particles with distance lesser than ") |
0 commit comments