|
27 | 27 | ===========================================================================
|
28 | 28 |
|
29 | 29 | """
|
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 |
31 | 31 | from .. import VAR_DESCR_inv
|
32 | 32 | import logging
|
33 | 33 | from datetime import datetime, timedelta
|
@@ -242,6 +242,14 @@ def loess_filter(self, half_window, xfield, yfield, inplace=True):
|
242 | 242 | if inplace:
|
243 | 243 | self.obs[yfield] = result
|
244 | 244 |
|
| 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 | + |
245 | 253 | def __extract_with_mask(
|
246 | 254 | self, mask, full_path=False, remove_incomplete=False, compress_id=False
|
247 | 255 | ):
|
@@ -350,3 +358,39 @@ def track_loess_filter(half_window, x, y, track):
|
350 | 358 | dx = x[i_next] - x[i]
|
351 | 359 | y_new[i] = y_sum / w_sum
|
352 | 360 | 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