forked from AntSimi/py-eddy-tracker
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathnetwork.py
More file actions
2271 lines (1957 loc) · 79 KB
/
network.py
File metadata and controls
2271 lines (1957 loc) · 79 KB
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 create network of observations
"""
from glob import glob
import logging
import time
import netCDF4
from numba import njit, types as nb_types
from numba.typed import List
from numpy import (
arange,
array,
bincount,
bool_,
concatenate,
empty,
nan,
ones,
percentile,
uint16,
uint32,
unique,
where,
zeros,
)
import zarr
from ..dataset.grid import GridCollection
from ..generic import build_index, wrap_longitude
from ..poly import bbox_intersection, vertice_overlap
from .groups import GroupEddiesObservations, get_missing_indices, particle_candidate
from .observation import EddiesObservations
from .tracking import TrackEddiesObservations, track_loess_filter, track_median_filter
logger = logging.getLogger("pet")
class Singleton(type):
_instances = {}
def __call__(cls, *args, **kwargs):
if cls not in cls._instances:
cls._instances[cls] = super().__call__(*args, **kwargs)
return cls._instances[cls]
class Buffer(metaclass=Singleton):
__slots__ = (
"buffersize",
"contour_name",
"xname",
"yname",
"memory",
)
DATA = dict()
FLIST = list()
def __init__(self, buffersize, intern=False, memory=False):
self.buffersize = buffersize
self.contour_name = EddiesObservations.intern(intern, public_label=True)
self.xname, self.yname = EddiesObservations.intern(intern)
self.memory = memory
def load_contour(self, filename):
if isinstance(filename, EddiesObservations):
return filename[self.xname], filename[self.yname]
if filename not in self.DATA:
if len(self.FLIST) > self.buffersize:
self.DATA.pop(self.FLIST.pop(0))
if self.memory:
# Only if netcdf
with open(filename, "rb") as h:
e = EddiesObservations.load_file(h, include_vars=self.contour_name)
else:
e = EddiesObservations.load_file(
filename, include_vars=self.contour_name
)
self.FLIST.append(filename)
self.DATA[filename] = e[self.xname], e[self.yname]
return self.DATA[filename]
@njit(cache=True)
def fix_next_previous_obs(next_obs, previous_obs, flag_virtual):
"""When an observation is virtual, we have to fix the previous and next obs
:param np.array(int) next_obs : index of next observation from network
:param np.array(int previous_obs: index of previous observation from network
:param np.array(bool) flag_virtual: if observation is virtual or not
"""
for i_o in range(next_obs.size):
if not flag_virtual[i_o]:
continue
# if there are several consecutive virtuals, some values are written multiple times.
# but it should not be slow
next_obs[i_o - 1] = i_o
next_obs[i_o] = i_o + 1
previous_obs[i_o] = i_o - 1
previous_obs[i_o + 1] = i_o
class NetworkObservations(GroupEddiesObservations):
__slots__ = ("_index_network", "_index_segment_track", "_segment_track_array")
NOGROUP = 0
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.reset_index()
def __repr__(self):
m_event, s_event = (
self.merging_event(only_index=True, triplet=True)[0],
self.splitting_event(only_index=True, triplet=True)[0],
)
period = (self.period[1] - self.period[0]) / 365.25
nb_by_network = self.network_size()
nb_trash = 0 if self.ref_index != 0 else nb_by_network[0]
big = 50_000
infos = [
f"Atlas with {self.nb_network} networks ({self.nb_network / period:0.0f} networks/year),"
f" {self.nb_segment} segments ({self.nb_segment / period:0.0f} segments/year), {len(self)} observations ({len(self) / period:0.0f} observations/year)",
f" {m_event.size} merging ({m_event.size / period:0.0f} merging/year), {s_event.size} splitting ({s_event.size / period:0.0f} splitting/year)",
f" with {(nb_by_network > big).sum()} network with more than {big} obs and the biggest have {nb_by_network.max()} observations ({nb_by_network[nb_by_network> big].sum()} observations cumulate)",
f" {nb_trash} observations in trash",
]
return "\n".join(infos)
def reset_index(self):
self._index_network = None
self._index_segment_track = None
self._segment_track_array = None
def find_segments_relative(self, obs, stopped=None, order=1):
"""
Find all relative segments from obs linked with merging/splitting events at a specific order.
:param int obs: index of observation after the event
:param int stopped: index of observation before the event
:param int order: order of relatives accepted
:return: all relative segments
:rtype: EddiesObservations
"""
# extraction of network where the event is
network_id = self.tracks[obs]
nw = self.network(network_id)
# indice of observation in new subnetwork
i_obs = where(nw.segment == self.segment[obs])[0][0]
if stopped is None:
return nw.relatives(i_obs, order=order)
else:
i_stopped = where(nw.segment == self.segment[stopped])[0][0]
return nw.relatives([i_obs, i_stopped], order=order)
def get_missing_indices(self, dt):
"""Find indices where observations are missing.
As network have all untracked observation in tracknumber `self.NOGROUP`,
we don't compute them
:param int,float dt: theorical delta time between 2 observations
"""
return get_missing_indices(
self.time, self.track, dt=dt, flag_untrack=True, indice_untrack=self.NOGROUP
)
def fix_next_previous_obs(self):
"""Function used after 'insert_virtual', to correct next_obs and
previous obs.
"""
fix_next_previous_obs(self.next_obs, self.previous_obs, self.virtual)
@property
def index_network(self):
if self._index_network is None:
self._index_network = build_index(self.track)
return self._index_network
@property
def index_segment_track(self):
if self._index_segment_track is None:
self._index_segment_track = build_index(self.segment_track_array)
return self._index_segment_track
def segment_size(self):
return self.index_segment_track[1] - self.index_segment_track[0]
@property
def ref_segment_track_index(self):
return self.index_segment_track[2]
@property
def ref_index(self):
return self.index_network[2]
def network_segment_size(self, id_networks=None):
"""Get number of segment by network
:return array:
"""
i0, i1, ref = build_index(self.track[self.index_segment_track[0]])
if id_networks is None:
return i1 - i0
else:
i = id_networks - ref
return i1[i] - i0[i]
def network_size(self, id_networks=None):
"""
Return size for specified network
:param list,array, None id_networks: ids to identify network
"""
if id_networks is None:
return self.index_network[1] - self.index_network[0]
else:
i = id_networks - self.index_network[2]
return self.index_network[1][i] - self.index_network[0][i]
def unique_segment_to_id(self, id_unique):
"""Return id network and id segment for a unique id
:param array id_unique:
"""
i = self.index_segment_track[0][id_unique] - self.ref_segment_track_index
return self.track[i], self.segment[i]
def segment_slice(self, id_network, id_segment):
"""
Return slice for one segment
:param int id_network: id to identify network
:param int id_segment: id to identify segment
"""
raise Exception("need to be implemented")
def network_slice(self, id_network):
"""
Return slice for one network
:param int id_network: id to identify network
"""
i = id_network - self.index_network[2]
i_start, i_stop = self.index_network[0][i], self.index_network[1][i]
return slice(i_start, i_stop)
@property
def elements(self):
elements = super().elements
elements.extend(
[
"track",
"segment",
"next_obs",
"previous_obs",
"next_cost",
"previous_cost",
]
)
return list(set(elements))
def astype(self, cls):
new = cls.new_like(self, self.shape)
for k in new.fields:
if k in self.fields:
new[k][:] = self[k][:]
new.sign_type = self.sign_type
return new
def longer_than(self, nb_day_min=-1, nb_day_max=-1):
"""
Select network on time duration
:param int nb_day_min: Minimal number of days covered by one network, if negative -> not used
:param int nb_day_max: Maximal number of days covered by one network, if negative -> not used
"""
if nb_day_max < 0:
nb_day_max = 1000000000000
mask = zeros(self.shape, dtype="bool")
t = self.time
for i, _, _ in self.iter_on(self.track):
nb = i.stop - i.start
if nb == 0:
continue
if nb_day_min <= (ptp(t[i]) + 1) <= nb_day_max:
mask[i] = True
return self.extract_with_mask(mask)
@classmethod
def from_split_network(cls, group_dataset, indexs, **kwargs):
"""
Build a NetworkObservations object with Group dataset and indices
:param TrackEddiesObservations group_dataset: Group dataset
:param indexs: result from split_network
:return: NetworkObservations
"""
index_order = indexs.argsort(order=("group", "track", "time"))
network = cls.new_like(group_dataset, len(group_dataset), **kwargs)
network.sign_type = group_dataset.sign_type
for field in group_dataset.elements:
if field not in network.elements:
continue
network[field][:] = group_dataset[field][index_order]
network.segment[:] = indexs["track"][index_order]
# n & p must be re-indexed
n, p = indexs["next_obs"][index_order], indexs["previous_obs"][index_order]
# we add 2 for -1 index return index -1
translate = -ones(index_order.max() + 2, dtype="i4")
translate[index_order] = arange(index_order.shape[0])
network.next_obs[:] = translate[n]
network.previous_obs[:] = translate[p]
network.next_cost[:] = indexs["next_cost"][index_order]
network.previous_cost[:] = indexs["previous_cost"][index_order]
return network
def infos(self, label=""):
return f"{len(self)} obs {unique(self.segment).shape[0]} segments"
def correct_close_events(self, nb_days_max=20):
"""
Transform event where
segment A splits from segment B, then x days after segment B merges with A
to
segment A splits from segment B then x days after segment A merges with B (B will be longer)
These events have to last less than `nb_days_max` to be changed.
------------------- A
/ /
B --------------------
to
--A--
/ \
B -----------------------------------
:param float nb_days_max: maximum time to search for splitting-merging event
"""
_time = self.time
# segment used to correct and track changes
segment = self.segment_track_array.copy()
# final segment used to copy into self.segment
segment_copy = self.segment
segments_connexion = dict()
previous_obs, next_obs = self.previous_obs, self.next_obs
# record for every segment the slice, index of next obs & index of previous obs
for i, seg, _ in self.iter_on(segment):
if i.start == i.stop:
continue
i_p, i_n = previous_obs[i.start], next_obs[i.stop - 1]
segments_connexion[seg] = [i, i_p, i_n]
for seg in sorted(segments_connexion.keys()):
seg_slice, _, i_seg_n = segments_connexion[seg]
# the segment ID has to be corrected, because we may have changed it since
seg_corrected = segment[seg_slice.stop - 1]
# we keep the real segment number
seg_corrected_copy = segment_copy[seg_slice.stop - 1]
if i_seg_n == -1:
continue
# if segment is split
n_seg = segment[i_seg_n]
seg2_slice, i2_seg_p, _ = segments_connexion[n_seg]
if i2_seg_p == -1:
continue
p2_seg = segment[i2_seg_p]
# if it merges on the first in a certain time
if (p2_seg == seg_corrected) and (
_time[i_seg_n] - _time[i2_seg_p] < nb_days_max
):
my_slice = slice(i_seg_n, seg2_slice.stop)
# correct the factice segment
segment[my_slice] = seg_corrected
# correct the good segment
segment_copy[my_slice] = seg_corrected_copy
previous_obs[i_seg_n] = seg_slice.stop - 1
segments_connexion[seg_corrected][0] = my_slice
return self.sort()
def sort(self, order=("track", "segment", "time")):
"""
Sort observations
:param tuple order: order or sorting. Given to :func:`numpy.argsort`
"""
index_order = self.obs.argsort(order=order, kind="mergesort")
self.reset_index()
for field in self.fields:
self[field][:] = self[field][index_order]
nb_obs = len(self)
# we add 1 for -1 index return index -1
translate = -ones(nb_obs + 1, dtype="i4")
translate[index_order] = arange(nb_obs)
# next & previous must be re-indexed
self.next_obs[:] = translate[self.next_obs]
self.previous_obs[:] = translate[self.previous_obs]
return index_order, translate
def obs_relative_order(self, i_obs):
self.only_one_network()
return self.segment_relative_order(self.segment[i_obs])
def find_link(self, i_observations, forward=True, backward=False):
"""
Find all observations where obs `i_observation` could be
in future or past.
If forward=True, search all observations where water
from obs "i_observation" could go
If backward=True, search all observation
where water from obs `i_observation` could come from
:param int,iterable(int) i_observation:
indices of observation. Can be
int, or iterable of int.
:param bool forward, backward:
if forward, search observations after obs.
else mode==backward search before obs
"""
i_obs = (
[i_observations]
if not hasattr(i_observations, "__iter__")
else i_observations
)
segment = self.segment_track_array
previous_obs, next_obs = self.previous_obs, self.next_obs
segments_connexion = dict()
for i_slice, seg, _ in self.iter_on(segment):
if i_slice.start == i_slice.stop:
continue
i_p, i_n = previous_obs[i_slice.start], next_obs[i_slice.stop - 1]
p_seg, n_seg = segment[i_p], segment[i_n]
# dumping slice into dict
if seg not in segments_connexion:
segments_connexion[seg] = [i_slice, [], []]
else:
segments_connexion[seg][0] = i_slice
if i_p != -1:
if p_seg not in segments_connexion:
segments_connexion[p_seg] = [None, [], []]
# backward
segments_connexion[seg][2].append((i_slice.start, i_p, p_seg))
# forward
segments_connexion[p_seg][1].append((i_p, i_slice.start, seg))
if i_n != -1:
if n_seg not in segments_connexion:
segments_connexion[n_seg] = [None, [], []]
# forward
segments_connexion[seg][1].append((i_slice.stop - 1, i_n, n_seg))
# backward
segments_connexion[n_seg][2].append((i_n, i_slice.stop - 1, seg))
mask = zeros(segment.size, dtype=bool)
def func_forward(seg, indice):
seg_slice, _forward, _ = segments_connexion[seg]
mask[indice : seg_slice.stop] = True
for i_begin, i_end, seg2 in _forward:
if i_begin < indice:
continue
if not mask[i_end]:
func_forward(seg2, i_end)
def func_backward(seg, indice):
seg_slice, _, _backward = segments_connexion[seg]
mask[seg_slice.start : indice + 1] = True
for i_begin, i_end, seg2 in _backward:
if i_begin > indice:
continue
if not mask[i_end]:
func_backward(seg2, i_end)
for indice in i_obs:
if forward:
func_forward(segment[indice], indice)
if backward:
func_backward(segment[indice], indice)
return self.extract_with_mask(mask)
def connexions(self, multi_network=False):
"""Create dictionnary for each segment, gives the segments in interaction with
:param bool multi_network: use segment_track_array instead of segment, defaults to False
:return dict: Return dict of set, for each seg id we get set of segment which have event with him
"""
if multi_network:
segment = self.segment_track_array
else:
self.only_one_network()
segment = self.segment
segments_connexion = dict()
def add_seg(s1, s2):
if s1 not in segments_connexion:
segments_connexion[s1] = set()
if s2 not in segments_connexion:
segments_connexion[s2] = set()
segments_connexion[s1].add(s2), segments_connexion[s2].add(s1)
# Get index for each segment
i0, i1, _ = self.index_segment_track
i1 = i1 - 1
# Check if segment merge
i_next = self.next_obs[i1]
m_n = i_next != -1
# Check if segment come from splitting
i_previous = self.previous_obs[i0]
m_p = i_previous != -1
# For each split
for s1, s2 in zip(segment[i_previous[m_p]], segment[i0[m_p]]):
add_seg(s1, s2)
# For each merge
for s1, s2 in zip(segment[i_next[m_n]], segment[i1[m_n]]):
add_seg(s1, s2)
return segments_connexion
@classmethod
def __close_segment(cls, father, shift, connexions, distance):
i_father = father - shift
if distance[i_father] == -1:
distance[i_father] = 0
d_target = distance[i_father] + 1
for son in connexions.get(father, list()):
i_son = son - shift
d_son = distance[i_son]
if d_son == -1 or d_son > d_target:
distance[i_son] = d_target
else:
continue
cls.__close_segment(son, shift, connexions, distance)
def segment_relative_order(self, seg_origine):
"""
Compute the relative order of each segment to the chosen segment
"""
self.only_one_network()
i_s, i_e, i_ref = build_index(self.segment)
segment_connexions = self.connexions()
relative_tr = -ones(i_s.shape, dtype="i4")
self.__close_segment(seg_origine, i_ref, segment_connexions, relative_tr)
d = -ones(self.shape)
for i0, i1, v in zip(i_s, i_e, relative_tr):
if i0 == i1:
continue
d[i0:i1] = v
return d
def relatives(self, obs, order=2):
"""
Extract the segments at a certain order from multiple observations.
:param iterable,int obs:
indices of observation for relatives computation. Can be one observation (int)
or collection of observations (iterable(int))
:param int order: order of relatives wanted. 0 means only observations in obs, 1 means direct relatives, ...
:return: all segments' relatives
:rtype: EddiesObservations
"""
segment = self.segment_track_array
previous_obs, next_obs = self.previous_obs, self.next_obs
segments_connexion = dict()
for i_slice, seg, _ in self.iter_on(segment):
if i_slice.start == i_slice.stop:
continue
i_p, i_n = previous_obs[i_slice.start], next_obs[i_slice.stop - 1]
p_seg, n_seg = segment[i_p], segment[i_n]
# dumping slice into dict
if seg not in segments_connexion:
segments_connexion[seg] = [i_slice, []]
else:
segments_connexion[seg][0] = i_slice
if i_p != -1:
if p_seg not in segments_connexion:
segments_connexion[p_seg] = [None, []]
# backward
segments_connexion[seg][1].append(p_seg)
segments_connexion[p_seg][1].append(seg)
if i_n != -1:
if n_seg not in segments_connexion:
segments_connexion[n_seg] = [None, []]
# forward
segments_connexion[seg][1].append(n_seg)
segments_connexion[n_seg][1].append(seg)
i_obs = [obs] if not hasattr(obs, "__iter__") else obs
distance = zeros(segment.size, dtype=uint16) - 1
def loop(seg, dist=1):
i_slice, links = segments_connexion[seg]
d = distance[i_slice.start]
if dist < d and dist <= order:
distance[i_slice] = dist
for _seg in links:
loop(_seg, dist + 1)
for indice in i_obs:
loop(segment[indice], 0)
return self.extract_with_mask(distance <= order)
# keep old names, for backward compatibility
relative = relatives
def close_network(self, other, nb_obs_min=10, **kwargs):
"""
Get close network from another atlas.
:param self other: Atlas to compare
:param int nb_obs_min: Minimal number of overlap for one trajectory
:param dict kwargs: keyword arguments for match function
:return: return other atlas reduced to common tracks with self
.. warning::
It could be a costly operation for huge dataset
"""
p0, p1 = self.period
indexs = list()
for i_self, i_other, t0, t1 in self.align_on(other, bins=range(p0, p1 + 2)):
i, j, s = self.match(other, i_self=i_self, i_other=i_other, **kwargs)
indexs.append(other.re_reference_index(j, i_other))
indexs = concatenate(indexs)
tr, nb = unique(other.track[indexs], return_counts=True)
m = zeros(other.track.shape, dtype=bool)
for i in tr[nb >= nb_obs_min]:
m[other.network_slice(i)] = True
return other.extract_with_mask(m)
def normalize_longitude(self):
"""Normalize all longitudes
Normalize longitude field and in the same range :
- longitude_max
- contour_lon_e (how to do if in raw)
- contour_lon_s (how to do if in raw)
"""
i_start, i_stop, _ = self.index_network
lon0 = (self.lon[i_start] - 180).repeat(i_stop - i_start)
logger.debug("Normalize longitude")
self.lon[:] = (self.lon - lon0) % 360 + lon0
if "lon_max" in self.fields:
logger.debug("Normalize longitude_max")
self.lon_max[:] = (self.lon_max - self.lon + 180) % 360 + self.lon - 180
if not self.raw_data:
if "contour_lon_e" in self.fields:
logger.debug("Normalize effective contour longitude")
self.contour_lon_e[:] = (
(self.contour_lon_e.T - self.lon + 180) % 360 + self.lon - 180
).T
if "contour_lon_s" in self.fields:
logger.debug("Normalize speed contour longitude")
self.contour_lon_s[:] = (
(self.contour_lon_s.T - self.lon + 180) % 360 + self.lon - 180
).T
def numbering_segment(self, start=0):
"""
New numbering of segment
"""
for i, _, _ in self.iter_on("track"):
new_numbering(self.segment[i], start)
def numbering_network(self, start=1):
"""
New numbering of network
"""
new_numbering(self.track, start)
def only_one_network(self):
"""
Raise a warning or error?
if there are more than one network
"""
_, i_start, _ = self.index_network
if i_start.size > 1:
raise Exception("Several networks")
def position_filter(self, median_half_window, loess_half_window):
self.median_filter(median_half_window, "time", "lon").loess_filter(
loess_half_window, "time", "lon"
)
self.median_filter(median_half_window, "time", "lat").loess_filter(
loess_half_window, "time", "lat"
)
def loess_filter(self, half_window, xfield, yfield, inplace=True):
result = track_loess_filter(
half_window, self.obs[xfield], self.obs[yfield], self.segment_track_array
)
if inplace:
self.obs[yfield] = result
return self
return result
def median_filter(self, half_window, xfield, yfield, inplace=True):
result = track_median_filter(
half_window, self[xfield], self[yfield], self.segment_track_array
)
if inplace:
self[yfield][:] = result
return self
return result
def display_timeline(
self,
ax,
event=True,
field=None,
method=None,
factor=1,
colors_mode="roll",
**kwargs,
):
"""
Plot the timeline of a network.
Must be called on only one network.
:param matplotlib.axes.Axes ax: matplotlib axe used to draw
:param bool event: if True, draw the splitting and merging events
:param str,array field: yaxis values, if None, segments are used
:param str method: if None, mean values are used
:param float factor: to multiply field
:param str colors_mode:
color of lines. "roll" means looping through colors,
"y" means color adapt the y values (for matching color plots)
:return: plot mappable
"""
self.only_one_network()
j = 0
line_kw = dict(
ls="-",
marker="+",
markersize=6,
zorder=1,
lw=3,
)
line_kw.update(kwargs)
mappables = dict(lines=list())
if event:
mappables.update(
self.event_timeline(
ax,
field=field,
method=method,
factor=factor,
colors_mode=colors_mode,
)
)
if field is not None:
field = self.parse_varname(field)
for i, b0, b1 in self.iter_on("segment"):
x = self.time[i]
if x.shape[0] == 0:
continue
if field is None:
y = b0 * ones(x.shape)
else:
if method == "all":
y = field[i] * factor
else:
y = field[i].mean() * ones(x.shape) * factor
if colors_mode == "roll":
_color = self.get_color(j)
elif colors_mode == "y":
_color = self.get_color(b0 - 1)
else:
raise NotImplementedError(f"colors_mode '{colors_mode}' not defined")
line = ax.plot(x, y, **line_kw, color=_color)[0]
mappables["lines"].append(line)
j += 1
return mappables
def event_timeline(self, ax, field=None, method=None, factor=1, colors_mode="roll"):
"""Mark events in plot"""
j = 0
events = dict(splitting=[], merging=[])
# TODO : fill mappables dict
y_seg = dict()
_time = self.time
if field is not None and method != "all":
for i, b0, _ in self.iter_on("segment"):
y = self.parse_varname(field)[i]
if y.shape[0] != 0:
y_seg[b0] = y.mean() * factor
mappables = dict()
for i, b0, b1 in self.iter_on("segment"):
x = _time[i]
if x.shape[0] == 0:
continue
if colors_mode == "roll":
_color = self.get_color(j)
elif colors_mode == "y":
_color = self.get_color(b0 - 1)
else:
raise NotImplementedError(f"colors_mode '{colors_mode}' not defined")
event_kw = dict(color=_color, ls="-", zorder=1)
i_n, i_p = (
self.next_obs[i.stop - 1],
self.previous_obs[i.start],
)
if field is None:
y0 = b0
else:
if method == "all":
y0 = self.parse_varname(field)[i.stop - 1] * factor
else:
y0 = y_seg[b0]
if i_n != -1:
seg_next = self.segment[i_n]
y1 = (
seg_next
if field is None
else (
self.parse_varname(field)[i_n] * factor
if method == "all"
else y_seg[seg_next]
)
)
ax.plot((x[-1], _time[i_n]), (y0, y1), **event_kw)[0]
events["merging"].append((x[-1], y0))
if i_p != -1:
seg_previous = self.segment[i_p]
if field is not None and method == "all":
y0 = self[field][i.start] * factor
y1 = (
seg_previous
if field is None
else (
self.parse_varname(field)[i_p] * factor
if method == "all"
else y_seg[seg_previous]
)
)
ax.plot((x[0], _time[i_p]), (y0, y1), **event_kw)[0]
events["splitting"].append((x[0], y0))
j += 1
kwargs = dict(color="k", zorder=-1, linestyle=" ")
if len(events["splitting"]) > 0:
X, Y = list(zip(*events["splitting"]))
ref = ax.plot(
X, Y, marker="*", markersize=12, label="splitting events", **kwargs
)[0]
mappables.setdefault("events", []).append(ref)
if len(events["merging"]) > 0:
X, Y = list(zip(*events["merging"]))
ref = ax.plot(
X, Y, marker="H", markersize=10, label="merging events", **kwargs
)[0]
mappables.setdefault("events", []).append(ref)
return mappables
def mean_by_segment(self, y, **kw):
kw["dtype"] = y.dtype
return self.map_segment(lambda x: x.mean(), y, **kw)
def map_segment(self, method, y, same=True, **kw):
if same:
out = empty(y.shape, **kw)
else:
out = list()
for i, _, _ in self.iter_on(self.segment_track_array):
res = method(y[i])
if same:
out[i] = res
else:
if isinstance(i, slice):
if i.start == i.stop:
continue
elif len(i) == 0:
continue
out.append(res)
if not same:
out = array(out)
return out
def map_network(self, method, y, same=True, return_dict=False, **kw):
"""
Transform data `y` with method `method` for each track.
:param Callable method: method to apply on each track
:param np.array y: data where to apply method
:param bool same: if True, return an array with the same size than y. Else, return a list with the edited tracks
:param bool return_dict: if None, mean values are used
:param float kw: to multiply field
:return: array or dict of result from method for each network
"""
if same and return_dict:
raise NotImplementedError(
"both conditions 'same' and 'return_dict' should no be true"
)
if same:
out = empty(y.shape, **kw)
elif return_dict:
out = dict()
else:
out = list()
for i, b0, b1 in self.iter_on(self.track):
res = method(y[i])
if same:
out[i] = res
elif return_dict:
out[b0] = res
else:
if isinstance(i, slice):
if i.start == i.stop:
continue
elif len(i) == 0:
continue
out.append(res)
if not same and not return_dict:
out = array(out)
return out
def scatter_timeline(
self,
ax,
name,
factor=1,
event=True,
yfield=None,
yfactor=1,
method=None,
**kwargs,
):
"""
Must be called on only one network
"""
self.only_one_network()