-
Notifications
You must be signed in to change notification settings - Fork 48
/
grid.py
3013 lines (2696 loc) · 108 KB
/
grid.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# -*- coding: utf-8 -*-
"""
Class to load and manipulate RegularGrid and UnRegularGrid
"""
from datetime import datetime
import logging
from cv2 import filter2D
from matplotlib.path import Path as BasePath
from netCDF4 import Dataset
from numba import njit, prange, types as numba_types
from numpy import (
arange,
array,
ceil,
concatenate,
cos,
deg2rad,
empty,
errstate,
exp,
float_,
floor,
histogram2d,
int_,
interp,
isnan,
linspace,
ma,
mean as np_mean,
meshgrid,
nan,
nanmean,
ones,
percentile,
pi,
radians,
round_,
sin,
sinc,
sqrt,
where,
zeros,
)
from pint import UnitRegistry
from scipy.interpolate import RectBivariateSpline, interp1d
from scipy.ndimage import gaussian_filter
from scipy.signal import welch
from scipy.spatial import cKDTree
from scipy.special import j1
from .. import VAR_DESCR
from ..data import get_demo_path
from ..eddy_feature import Amplitude, Contours
from ..generic import (
bbox_indice_regular,
coordinates_to_local,
distance,
interp2d_geo,
local_to_coordinates,
nearest_grd_indice,
uniform_resample,
)
from ..observations.observation import EddiesObservations
from ..poly import (
create_vertice,
fit_circle,
get_pixel_in_regular,
poly_area,
poly_contain_poly,
visvalingam,
winding_number_poly,
)
logger = logging.getLogger("pet")
def raw_resample(datas, fixed_size):
nb_value = datas.shape[0]
if nb_value == 1:
raise Exception()
return interp(
arange(fixed_size), arange(nb_value) * (fixed_size - 1) / (nb_value - 1), datas
)
@property
def mean_coordinates(self):
# last coordinates == first
return self.vertices[1:].mean(axis=0)
@property
def lon(self):
return self.vertices[:, 0]
@property
def lat(self):
return self.vertices[:, 1]
BasePath.mean_coordinates = mean_coordinates
BasePath.lon = lon
BasePath.lat = lat
@njit(cache=True)
def uniform_resample_stack(vertices, num_fac=2, fixed_size=None):
x_val, y_val = vertices[:, 0], vertices[:, 1]
x_new, y_new = uniform_resample(x_val, y_val, num_fac, fixed_size)
data = empty((x_new.shape[0], 2), dtype=vertices.dtype)
data[:, 0] = x_new
data[:, 1] = y_new
return data
@njit(cache=True)
def value_on_regular_contour(x_g, y_g, z_g, m_g, vertices, num_fac=2, fixed_size=None):
x_val, y_val = vertices[:, 0], vertices[:, 1]
x_new, y_new = uniform_resample(x_val, y_val, num_fac, fixed_size)
return interp2d_geo(x_g, y_g, z_g, m_g, x_new[1:], y_new[1:])
@njit(cache=True)
def mean_on_regular_contour(
x_g, y_g, z_g, m_g, vertices, num_fac=2, fixed_size=-1, nan_remove=False
):
x_val, y_val = vertices[:, 0], vertices[:, 1]
x_new, y_new = uniform_resample(x_val, y_val, num_fac, fixed_size)
values = interp2d_geo(x_g, y_g, z_g, m_g, x_new[1:], y_new[1:])
if nan_remove:
return nanmean(values)
else:
return values.mean()
def fit_circle_path(self, method="fit"):
if not hasattr(self, "_circle_params"):
self._circle_params = dict()
if method not in self._circle_params.keys():
if method == "fit":
self._circle_params["fit"] = _fit_circle_path(self.vertices)
if method == "equal_area":
self._circle_params["equal_area"] = _circle_from_equal_area(self.vertices)
return self._circle_params[method]
@njit(cache=True, fastmath=True)
def _circle_from_equal_area(vertice):
lons, lats = vertice[:, 0], vertice[:, 1]
# last coordinates == first
lon0, lat0 = lons[1:].mean(), lats[1:].mean()
c_x, c_y = coordinates_to_local(lons, lats, lon0, lat0)
# Sometimes, edge is only a dot of few coordinates
d_lon = lons.max() - lons.min()
d_lat = lats.max() - lats.min()
if d_lon < 1e-7 and d_lat < 1e-7:
# logger.warning('An edge is only define in one position')
# logger.debug('%d coordinates %s,%s', len(lons),lons,
# lats)
return 0, -90, nan, nan
return lon0, lat0, (poly_area(c_x, c_y) / pi) ** 0.5, nan
@njit(cache=True, fastmath=True)
def _fit_circle_path(vertice):
lons, lats = vertice[:, 0], vertice[:, 1]
# last coordinates == first
lon0, lat0 = lons[1:].mean(), lats[1:].mean()
c_x, c_y = coordinates_to_local(lons, lats, lon0, lat0)
# Some time, edge is only a dot of few coordinates
d_lon = lons.max() - lons.min()
d_lat = lats.max() - lats.min()
if d_lon < 1e-7 and d_lat < 1e-7:
# logger.warning('An edge is only define in one position')
# logger.debug('%d coordinates %s,%s', len(lons),lons,
# lats)
return 0, -90, nan, nan
centlon, centlat, eddy_radius, err = fit_circle(c_x, c_y)
centlon, centlat = local_to_coordinates(centlon, centlat, lon0, lat0)
centlon = (centlon - lon0 + 180) % 360 + lon0 - 180
return centlon, centlat, eddy_radius, err
@njit(cache=True, fastmath=True)
def _get_pixel_in_unregular(vertices, x_c, y_c, x_start, x_stop, y_start, y_stop):
nb_x, nb_y = x_stop - x_start, y_stop - y_start
wn = empty((nb_x, nb_y), dtype=numba_types.bool_)
for i in range(nb_x):
for j in range(nb_y):
x_pt = x_c[i + x_start, j + y_start]
y_pt = y_c[i + x_start, j + y_start]
wn[i, j] = winding_number_poly(x_pt, y_pt, vertices)
i_x, i_y = where(wn)
i_x += x_start
i_y += y_start
return i_x, i_y
BasePath.fit_circle = fit_circle_path
def pixels_in(self, grid):
if not hasattr(self, "_slice"):
self._slice = grid.bbox_indice(self.vertices)
if not hasattr(self, "_pixels_in"):
self._pixels_in = grid.get_pixels_in(self)
return self._pixels_in
@property
def bbox_slice(self):
if not hasattr(self, "_slice"):
raise Exception("No pixels_in call before!")
return self._slice
@property
def pixels_index(self):
if not hasattr(self, "_slice"):
raise Exception("No pixels_in call before!")
return self._pixels_in
@property
def nb_pixel(self):
if not hasattr(self, "_pixels_in"):
raise Exception("No pixels_in call before!")
return self._pixels_in[0].shape[0]
BasePath.pixels_in = pixels_in
BasePath.pixels_index = pixels_index
BasePath.bbox_slice = bbox_slice
BasePath.nb_pixel = nb_pixel
class GridDataset(object):
"""
Class for basic tools on NetCDF Grid
"""
__slots__ = (
"x_c",
"y_c",
"x_bounds",
"y_bounds",
"centered",
"x_dim",
"y_dim",
"coordinates",
"filename",
"dimensions",
"indexs",
"variables_description",
"global_attrs",
"vars",
"contours",
"nan_mask",
)
GRAVITY = 9.807
EARTH_RADIUS = 6370997.0
# EARTH_RADIUS = 6378136.3
# indice margin (if put to 0, raise warning that i don't understand)
N = 1
def __init__(
self,
filename,
x_name,
y_name,
centered=None,
indexs=None,
unset=False,
nan_masking=False,
):
"""
:param str filename: Filename to load
:param str x_name: Name of longitude coordinates
:param str y_name: Name of latitude coordinates
:param bool,None centered: Allow to know how coordinates could be used with pixel
:param dict indexs: A dictionary that sets indexes to use for non-coordinate dimensions
:param bool unset: Set to True to create an empty grid object without file
:param bool nan_masking: Set to True to replace data.mask with isnan method result
"""
self.dimensions = None
self.variables_description = None
self.global_attrs = None
self.x_c = None
self.y_c = None
self.x_bounds = None
self.y_bounds = None
self.x_dim = None
self.y_dim = None
self.nan_mask = nan_masking
self.centered = centered
self.contours = None
self.filename = filename
self.coordinates = x_name, y_name
self.vars = dict()
self.indexs = dict() if indexs is None else indexs
if centered is None:
logger.warning(
"We assume pixel position of grid is centered for %s", filename
)
if not unset:
self.populate()
def populate(self):
if self.dimensions is None:
self.load_general_features()
self.load()
def clean(self):
self.dimensions = None
self.variables_description = None
self.global_attrs = None
self.x_c = None
self.y_c = None
self.x_bounds = None
self.y_bounds = None
self.x_dim = None
self.y_dim = None
self.contours = None
self.vars = dict()
@property
def is_centered(self):
"""Give True if pixel is described with its center's position or
a corner
:return: True if centered
:rtype: bool
"""
if self.centered is None:
return True
else:
return self.centered
def load_general_features(self):
"""Load attrs to be stored in object"""
logger.debug(
"Load general feature from %(filename)s", dict(filename=self.filename)
)
with Dataset(self.filename) as h:
# Load generals
self.dimensions = {i: len(v) for i, v in h.dimensions.items()}
self.variables_description = dict()
for i, v in h.variables.items():
args = (i, v.datatype)
kwargs = dict(dimensions=v.dimensions, zlib=True)
if hasattr(v, "_FillValue"):
kwargs["fill_value"] = (v._FillValue,)
attrs = dict()
for attr in v.ncattrs():
if attr in kwargs.keys():
continue
if attr == "_FillValue":
continue
attrs[attr] = getattr(v, attr)
self.variables_description[i] = dict(
args=args, kwargs=kwargs, attrs=attrs, infos=dict()
)
self.global_attrs = {attr: getattr(h, attr) for attr in h.ncattrs()}
def write(self, filename):
"""Write dataset output with same format as input
:param str filename: filename used to save the grid
"""
with Dataset(filename, "w") as h_out:
for dimension, size in self.dimensions.items():
test = False
for varname, variable in self.variables_description.items():
if (
varname not in self.coordinates
and varname not in self.vars.keys()
):
continue
if dimension in variable["kwargs"]["dimensions"]:
test = True
break
if test:
h_out.createDimension(dimension, size)
for varname, variable in self.variables_description.items():
if varname not in self.coordinates and varname not in self.vars.keys():
continue
var = h_out.createVariable(*variable["args"], **variable["kwargs"])
for key, value in variable["attrs"].items():
setattr(var, key, value)
infos = self.variables_description[varname]["infos"]
if infos.get("transpose", False):
var[:] = self.vars[varname].T
else:
var[:] = self.vars[varname]
for attr, value in self.global_attrs.items():
setattr(h_out, attr, value)
def load(self):
"""
Load variable (data).
Get coordinates and setup coordinates function
"""
x_name, y_name = self.coordinates
with Dataset(self.filename) as h:
self.x_dim = h.variables[x_name].dimensions
self.y_dim = h.variables[y_name].dimensions
sl_x = [self.indexs.get(dim, slice(None)) for dim in self.x_dim]
sl_y = [self.indexs.get(dim, slice(None)) for dim in self.y_dim]
self.vars[x_name] = h.variables[x_name][sl_x]
self.vars[y_name] = h.variables[y_name][sl_y]
self.setup_coordinates()
@staticmethod
def get_mask(a):
if len(a.mask.shape):
m = a.mask
else:
m = ones(a.shape, dtype="bool") if a.mask else zeros(a.shape, dtype="bool")
return m
@staticmethod
def c_to_bounds(c):
"""
Centered coordinates to bounds coordinates
:param array c: centered coordinates to translate
:return: bounds coordinates
"""
bounds = concatenate((c, (2 * c[-1] - c[-2],)))
d = bounds[1:] - bounds[:-1]
bounds[:-1] -= d / 2
bounds[-1] -= d[-1] / 2
return bounds
def setup_coordinates(self):
x_name, y_name = self.coordinates
if self.is_centered:
# logger.info("Grid center")
self.x_c = array(self.vars[x_name].astype("float64"))
self.y_c = array(self.vars[y_name].astype("float64"))
self.x_bounds = concatenate((self.x_c, (2 * self.x_c[-1] - self.x_c[-2],)))
self.y_bounds = concatenate((self.y_c, (2 * self.y_c[-1] - self.y_c[-2],)))
d_x = self.x_bounds[1:] - self.x_bounds[:-1]
d_y = self.y_bounds[1:] - self.y_bounds[:-1]
self.x_bounds[:-1] -= d_x / 2
self.x_bounds[-1] -= d_x[-1] / 2
self.y_bounds[:-1] -= d_y / 2
self.y_bounds[-1] -= d_y[-1] / 2
else:
self.x_bounds = array(self.vars[x_name].astype("float64"))
self.y_bounds = array(self.vars[y_name].astype("float64"))
if len(self.x_dim) == 1:
self.x_c = self.x_bounds.copy()
dx2 = (self.x_bounds[1:] - self.x_bounds[:-1]) / 2
self.x_c[:-1] += dx2
self.x_c[-1] += dx2[-1]
self.y_c = self.y_bounds.copy()
dy2 = (self.y_bounds[1:] - self.y_bounds[:-1]) / 2
self.y_c[:-1] += dy2
self.y_c[-1] += dy2[-1]
else:
raise Exception("not write")
def is_circular(self):
"""Check grid circularity"""
return False
def units(self, varname):
"""Get unit from variable"""
stored_units = self.variables_description[varname]["attrs"].get("units", None)
if stored_units is not None:
return stored_units
with Dataset(self.filename) as h:
var = h.variables[varname]
if hasattr(var, "units"):
return var.units
@property
def variables(self):
return self.variables_description.keys()
def copy(self, grid_in, grid_out):
"""
Duplicate the variable from grid_in in grid_out
:param grid_in:
:param grid_out:
"""
h_dict = self.variables_description[grid_in]
self.variables_description[grid_out] = dict(
infos=h_dict["infos"].copy(),
attrs=h_dict["attrs"].copy(),
args=tuple((grid_out, *h_dict["args"][1:])),
kwargs=h_dict["kwargs"].copy(),
)
self.vars[grid_out] = self.grid(grid_in).copy()
def add_grid(self, varname, grid):
"""
Add a grid in handler
:param str varname: name of the future grid
:param array grid: grid array
"""
self.vars[varname] = grid
def grid(self, varname, indexs=None):
"""Give the grid required
:param str varname: Variable to get
:param dict,None indexs: If defined dict must have dimensions name as key
:return: array asked, reduced by the indexes
:rtype: array
.. minigallery:: py_eddy_tracker.GridDataset.grid
"""
if indexs is None:
indexs = dict()
if varname not in self.vars:
coordinates_dims = list(self.x_dim)
coordinates_dims.extend(list(self.y_dim))
logger.debug(
"Load %(varname)s from %(filename)s",
dict(varname=varname, filename=self.filename),
)
with Dataset(self.filename) as h:
dims = h.variables[varname].dimensions
sl = [
indexs.get(
dim,
self.indexs.get(
dim, slice(None) if dim in coordinates_dims else 0
),
)
for dim in dims
]
self.vars[varname] = h.variables[varname][sl]
if len(self.x_dim) == 1:
i_x = where(array(dims) == self.x_dim)[0][0]
i_y = where(array(dims) == self.y_dim)[0][0]
if i_x > i_y:
self.variables_description[varname]["infos"]["transpose"] = True
self.vars[varname] = self.vars[varname].T
if self.nan_mask:
self.vars[varname] = ma.array(
self.vars[varname],
mask=isnan(self.vars[varname]),
)
if not hasattr(self.vars[varname], "mask"):
self.vars[varname] = ma.array(
self.vars[varname],
mask=zeros(self.vars[varname].shape, dtype="bool"),
)
return self.vars[varname]
def grid_tiles(self, varname, slice_x, slice_y):
"""Give the grid tiles required, without buffer system"""
coordinates_dims = list(self.x_dim)
coordinates_dims.extend(list(self.y_dim))
logger.debug(
"Extract %(varname)s from %(filename)s with slice(x:%(slice_x)s,y:%(slice_y)s)",
dict(
varname=varname,
filename=self.filename,
slice_y=slice_y,
slice_x=slice_x,
),
)
with Dataset(self.filename) as h:
dims = h.variables[varname].dimensions
sl = [
(slice_x if dim in list(self.x_dim) else slice_y)
if dim in coordinates_dims
else 0
for dim in dims
]
data = h.variables[varname][sl]
if len(self.x_dim) == 1:
i_x = where(array(dims) == self.x_dim)[0][0]
i_y = where(array(dims) == self.y_dim)[0][0]
if i_x > i_y:
data = data.T
if not hasattr(data, "mask"):
data = ma.array(data, mask=zeros(data.shape, dtype="bool"))
return data
def high_filter(self, grid_name, w_cut, **kwargs):
"""Return the high-pass filtered grid, by substracting to the initial grid the low-pass filtered grid (default: order=1)
:param grid_name: the name of the grid
:param int, w_cut: the half-power wavelength cutoff (km)
"""
result = self._low_filter(grid_name, w_cut, **kwargs)
self.vars[grid_name] -= result
def low_filter(self, grid_name, w_cut, **kwargs):
"""Return the low-pass filtered grid (default: order=1)
:param grid_name: the name of the grid
:param int, w_cut: the half-power wavelength cutoff (km)
"""
result = self._low_filter(grid_name, w_cut, **kwargs)
self.vars[grid_name] -= self.vars[grid_name] - result
@property
def bounds(self):
"""Give bounds"""
return (
self.x_bounds.min(),
self.x_bounds.max(),
self.y_bounds.min(),
self.y_bounds.max(),
)
def eddy_identification(
self,
grid_height,
uname,
vname,
date,
step=0.005,
shape_error=55,
presampling_multiplier=10,
sampling=50,
sampling_method="visvalingam",
pixel_limit=None,
precision=None,
force_height_unit=None,
force_speed_unit=None,
**kwargs,
):
"""
Compute eddy identification on the specified grid
:param str grid_height: Grid name of Sea Surface Height
:param str uname: Grid name of u speed component
:param str vname: Grid name of v speed component
:param datetime.datetime date: Date to be stored in object to date data
:param float,int step: Height between two layers in m
:param float,int shape_error: Maximal error allowed for outermost contour in %
:param int presampling_multiplier:
Evenly oversample the initial number of points in the contour by nb_pts x presampling_multiplier to fit circles
:param int sampling: Number of points to store contours and speed profile
:param str sampling_method: Method to resample the stored contours, 'uniform' or 'visvalingam'
:param (int,int),None pixel_limit:
Min and max number of pixels inside the inner and the outermost contour to be considered as an eddy
:param float,None precision: Truncate values at the defined precision in m
:param str force_height_unit: Unit used for height unit
:param str force_speed_unit: Unit used for speed unit
:param dict kwargs: Arguments given to amplitude (mle, nb_step_min, nb_step_to_be_mle).
Look at :py:meth:`py_eddy_tracker.eddy_feature.Amplitude`
The amplitude threshold is given by `step*nb_step_min`
:return: Return a list of 2 elements: Anticyclones and Cyclones
:rtype: py_eddy_tracker.observations.observation.EddiesObservations
.. minigallery:: py_eddy_tracker.GridDataset.eddy_identification
"""
if not isinstance(date, datetime):
raise Exception("Date argument must be a datetime object")
# The inf limit must be in pixel and sup limit in surface
if pixel_limit is None:
pixel_limit = (4, 1000)
# Compute an interpolator for eke
self.init_speed_coef(uname, vname)
# Get unit of h grid
h_units = (
self.units(grid_height) if force_height_unit is None else force_height_unit
)
units = UnitRegistry()
in_h_unit = units.parse_expression(h_units)
if in_h_unit is not None:
factor, _ = in_h_unit.to("m").to_tuple()
logger.info(
"We will apply on step a factor to be coherent with grid : %f",
1 / factor,
)
step /= factor
if precision is not None:
precision /= factor
# Get ssh grid
data = self.grid(grid_height).astype("f8")
# In case of a reduced mask
if len(data.mask.shape) == 0 and not data.mask:
data.mask = zeros(data.shape, dtype="bool")
# we remove noisy data
if precision is not None:
data = (data / precision).round() * precision
# Compute levels for ssh
z_min, z_max = data.min(), data.max()
d_z = z_max - z_min
data_tmp = data[~data.mask]
epsilon = 0.001 # in %
z_min_p, z_max_p = (
percentile(data_tmp, epsilon),
percentile(data_tmp, 100 - epsilon),
)
d_zp = z_max_p - z_min_p
if d_z / d_zp > 2:
logger.warning(
"Maybe some extrema are present zmin %f (m) and zmax %f (m) will be replace by %f and %f",
z_min,
z_max,
z_min_p,
z_max_p,
)
z_min, z_max = z_min_p, z_max_p
logger.debug("Levels from %f to %f", z_min, z_max)
levels = arange(z_min - z_min % step, z_max - z_max % step + 2 * step, step)
# Get x and y values
x, y = self.x_c, self.y_c
# Compute ssh contour
self.contours = Contours(x, y, data, levels, wrap_x=self.is_circular())
out_sampling = dict(fixed_size=sampling)
resample = visvalingam if sampling_method == "visvalingam" else uniform_resample
track_extra_variables = [
"height_max_speed_contour",
"height_external_contour",
"height_inner_contour",
"lon_max",
"lat_max",
]
array_variables = [
"contour_lon_e",
"contour_lat_e",
"contour_lon_s",
"contour_lat_s",
"uavg_profile",
]
# Complete cyclonic and anticylonic research:
a_and_c = list()
for anticyclonic_search in [True, False]:
eddies = list()
iterator = 1 if anticyclonic_search else -1
# Loop over each collection
for coll_ind, coll in enumerate(self.contours.iter(step=iterator)):
corrected_coll_index = coll_ind
if iterator == -1:
corrected_coll_index = -coll_ind - 1
contour_paths = coll.get_paths()
nb_paths = len(contour_paths)
if nb_paths == 0:
continue
cvalues = self.contours.cvalues[corrected_coll_index]
logger.debug(
"doing collection %s, contour value %.4f, %d paths",
corrected_coll_index,
cvalues,
nb_paths,
)
# Loop over individual c_s contours (i.e., every eddy in field)
for contour in contour_paths:
if contour.used:
continue
# FIXME : center could be outside the contour due to the fit
# FIXME : warning : the fit is made on raw sampling
_, _, _, aerr = contour.fit_circle()
# Filter for shape
if aerr < 0 or aerr > shape_error or isnan(aerr):
contour.reject = 1
continue
# Find all pixels in the contour
i_x_in, i_y_in = contour.pixels_in(self)
# Check if pixels in contour are masked
if has_masked_value(data.mask, i_x_in, i_y_in):
if contour.reject == 0:
contour.reject = 2
continue
# Test of the rotating sense: cyclone or anticyclone
if has_value(
data.data, i_x_in, i_y_in, cvalues, below=anticyclonic_search
):
continue
# Test the number of pixels within the outermost contour
# FIXME : Maybe limit max must be replaced with a maximum of surface
if (
contour.nb_pixel < pixel_limit[0]
or contour.nb_pixel > pixel_limit[1]
):
contour.reject = 3
continue
# Here the considered contour passed shape_error test, masked_pixels test,
# values strictly above (AEs) or below (CEs) the contour, number_pixels test)
# Compute amplitude
reset_centroid, amp = self.get_amplitude(
contour,
cvalues,
data,
anticyclonic_search=anticyclonic_search,
level=self.contours.levels[corrected_coll_index],
interval=step,
**kwargs,
)
# If we have a valid amplitude
if (not amp.within_amplitude_limits()) or (amp.amplitude == 0):
contour.reject = 4
continue
if reset_centroid:
if self.is_circular():
centi = self.normalize_x_indice(reset_centroid[0])
else:
centi = reset_centroid[0]
centj = reset_centroid[1]
# FIXME : To move in regular and unregular grid
if len(x.shape) == 1:
centlon_e = x[centi]
centlat_e = y[centj]
else:
centlon_e = x[centi, centj]
centlat_e = y[centi, centj]
# centlat_e and centlon_e must be indexes of maximum, we will loose some inner contour if it's not
(
max_average_speed,
speed_contour,
inner_contour,
speed_array,
i_max_speed,
i_inner,
) = self.get_uavg(
self.contours,
centlon_e,
centlat_e,
contour,
anticyclonic_search,
corrected_coll_index,
pixel_min=pixel_limit[0],
)
# FIXME : Instantiate new EddyObservation object (high cost, need to be reviewed)
obs = EddiesObservations(
size=1,
track_extra_variables=track_extra_variables,
track_array_variables=sampling,
array_variables=array_variables,
)
obs.height_max_speed_contour[:] = self.contours.cvalues[i_max_speed]
obs.height_external_contour[:] = cvalues
obs.height_inner_contour[:] = self.contours.cvalues[i_inner]
array_size = speed_array.shape[0]
obs.nb_contour_selected[:] = array_size
if speed_array.shape[0] == 1:
obs.uavg_profile[:] = speed_array[0]
else:
obs.uavg_profile[:] = raw_resample(speed_array, sampling)
obs.amplitude[:] = amp.amplitude
obs.speed_average[:] = max_average_speed
obs.num_point_e[:] = contour.lon.shape[0]
obs.num_point_s[:] = speed_contour.lon.shape[0]
# Evenly resample contours with nb_pts = nb_pts_original x presampling_multiplier
xy_i = uniform_resample(
inner_contour.lon,
inner_contour.lat,
num_fac=presampling_multiplier,
)
xy_e = uniform_resample(
contour.lon,
contour.lat,
num_fac=presampling_multiplier,
)
xy_s = uniform_resample(
speed_contour.lon,
speed_contour.lat,
num_fac=presampling_multiplier,
)
# First, get position of max SSH based on best fit circle with resampled innermost contour
centlon_i, centlat_i, _, _ = _fit_circle_path(create_vertice(*xy_i))
obs.lon_max[:] = centlon_i
obs.lat_max[:] = centlat_i
# Second, get speed-based radius, shape error, eddy center, area based on resampled contour of max uavg
centlon_s, centlat_s, eddy_radius_s, aerr_s = _fit_circle_path(
create_vertice(*xy_s)
)
obs.radius_s[:] = eddy_radius_s
obs.shape_error_s[:] = aerr_s
obs.speed_area[:] = poly_area(
*coordinates_to_local(*xy_s, lon0=centlon_s, lat0=centlat_s)
)
obs.lon[:] = centlon_s
obs.lat[:] = centlat_s
# Third, compute effective radius, shape error, area from resampled effective contour
_, _, eddy_radius_e, aerr_e = _fit_circle_path(
create_vertice(*xy_e)
)
obs.radius_e[:] = eddy_radius_e
obs.shape_error_e[:] = aerr_e
obs.effective_area[:] = poly_area(
*coordinates_to_local(*xy_e, lon0=centlon_s, lat0=centlat_s)
)
# Finally, resample contours with output parameters
xy_e_f = resample(*xy_e, **out_sampling)
xy_s_f = resample(*xy_s, **out_sampling)
obs.contour_lon_s[:], obs.contour_lat_s[:] = xy_s_f
obs.contour_lon_e[:], obs.contour_lat_e[:] = xy_e_f
if aerr > 99.9 or aerr_s > 99.9:
logger.warning(
"Strange shape at this step! shape_error : %f, %f",
aerr,
aerr_s,
)
eddies.append(obs)
# To reserve definitively the area
data.mask[i_x_in, i_y_in] = True
if len(eddies) == 0:
eddies = EddiesObservations(
track_extra_variables=track_extra_variables,
track_array_variables=sampling,
array_variables=array_variables,
)
else:
eddies = EddiesObservations.concatenate(eddies)
eddies.sign_type = 1 if anticyclonic_search else -1
eddies.time[:] = (date - datetime(1950, 1, 1)).total_seconds() / 86400.0
# normalization longitude between 0 - 360, because storage have an offset on 180
eddies.lon_max[:] %= 360
eddies.lon[:] %= 360
ref = eddies.lon - 180
eddies.contour_lon_e[:] = ((eddies.contour_lon_e.T - ref) % 360 + ref).T
eddies.contour_lon_s[:] = ((eddies.contour_lon_s.T - ref) % 360 + ref).T
a_and_c.append(eddies)
if in_h_unit is not None:
for name in [
"amplitude",
"height_max_speed_contour",
"height_external_contour",
"height_inner_contour",
]:
out_unit = units.parse_expression(VAR_DESCR[name]["nc_attr"]["units"])
factor, _ = in_h_unit.to(out_unit).to_tuple()
a_and_c[0].obs[name] *= factor
a_and_c[1].obs[name] *= factor
u_units = self.units(uname) if force_speed_unit is None else force_speed_unit
in_u_units = units.parse_expression(u_units)
if in_u_units is not None:
for name in ["speed_average", "uavg_profile"]:
out_unit = units.parse_expression(VAR_DESCR[name]["nc_attr"]["units"])
factor, _ = in_u_units.to(out_unit).to_tuple()
a_and_c[0].obs[name] *= factor
a_and_c[1].obs[name] *= factor
return a_and_c
def get_uavg(
self,
all_contours,
centlon_e,
centlat_e,
original_contour,
anticyclonic_search,
level_start,
pixel_min=3,
):
"""
Compute geostrophic speed around successive contours
Returns the average
"""
# Init max speed to search maximum
max_average_speed = self.speed_coef_mean(original_contour)
speed_array = [max_average_speed]
eddy_contours = [original_contour]