Skip to content

Commit 3236a7b

Browse files
committed
Add median filter
1 parent 49b3acd commit 3236a7b

File tree

1 file changed

+45
-1
lines changed

1 file changed

+45
-1
lines changed

src/py_eddy_tracker/observations/tracking.py

Lines changed: 45 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -27,7 +27,7 @@
2727
===========================================================================
2828
2929
"""
30-
from numpy import empty, arange, where, unique, interp, ones, bool_, zeros, array
30+
from numpy import empty, arange, where, unique, interp, ones, bool_, zeros, array, median
3131
from .. import VAR_DESCR_inv
3232
import logging
3333
from datetime import datetime, timedelta
@@ -242,6 +242,14 @@ def loess_filter(self, half_window, xfield, yfield, inplace=True):
242242
if inplace:
243243
self.obs[yfield] = result
244244

245+
def median_filter(self, half_window, xfield, yfield, inplace=True):
246+
track = self.obs["track"]
247+
x = self.obs[xfield]
248+
y = self.obs[yfield]
249+
result = track_median_filter(half_window, x, y, track)
250+
if inplace:
251+
self.obs[yfield] = result
252+
245253
def __extract_with_mask(
246254
self, mask, full_path=False, remove_incomplete=False, compress_id=False
247255
):
@@ -350,3 +358,39 @@ def track_loess_filter(half_window, x, y, track):
350358
dx = x[i_next] - x[i]
351359
y_new[i] = y_sum / w_sum
352360
return y_new
361+
362+
363+
@njit(cache=True)
364+
def track_median_filter(half_window, x, y, track):
365+
"""
366+
Apply a loess filter on y field
367+
Args:
368+
window: parameter of smoother
369+
x: must be growing for each track but could be irregular
370+
y: field to smooth
371+
track: field which allow to separate path
372+
373+
Returns:
374+
375+
"""
376+
nb = y.shape[0]
377+
last = nb - 1
378+
y_new = empty(y.shape, dtype=y.dtype)
379+
for i in range(nb):
380+
cur_track = track[i]
381+
i_previous = i
382+
i_next = i
383+
dx = 0
384+
while dx <= half_window and i_previous != 0 and cur_track == track[i_previous]:
385+
i_previous -= 1
386+
dx = x[i] - x[i_previous]
387+
if dx > half_window or cur_track != track[i_previous]:
388+
i_previous += 1
389+
dx = 0
390+
while dx <= half_window and i_next != last and cur_track == track[i_next]:
391+
i_next += 1
392+
dx = x[i_next] - x[i]
393+
if dx > half_window or cur_track != track[i_next]:
394+
i_next -= 1
395+
y_new[i] = median(y[i_previous:i_next + 1])
396+
return y_new

0 commit comments

Comments
 (0)