-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathERA_Fields_New.py
3115 lines (2750 loc) · 159 KB
/
ERA_Fields_New.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
# George Miloshevich 2021
# Importation des librairies
from pathlib import Path
from netCDF4 import Dataset
import xarray as xr
import numpy as np
import warnings
import matplotlib.pyplot as plt
import pylab as p
import sys
import os
import logging
import matplotlib.patheffects as PathEffects
from matplotlib.transforms import Bbox
from itertools import chain
import collections
from random import randrange
import pandas as pd
from scipy.signal import argrelextrema
from scipy.stats import skew, kurtosis
from scipy import integrate
from scipy.optimize import curve_fit
from sklearn.linear_model import LinearRegression
from sklearn.utils import shuffle
from sklearn.preprocessing import PolynomialFeatures
from sklearn.metrics import r2_score
from sklearn import linear_model
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import confusion_matrix
from skimage.transform import resize
path_to_parent = str(Path(__file__).resolve().parent.parent)
if not path_to_parent in sys.path:
sys.path.insert(1, path_to_parent)
try:
import general_purpose.utilities as ut
except ImportError:
import ERA.utilities as ut
logger = logging.getLogger(__name__)
logger.level = logging.INFO
global plotter
plotter = None
def _sliding_window_view_dispatcher(x, window_shape, axis=None, *,
subok=None, writeable=None):
return (x,)
from numpy.core.numeric import normalize_axis_tuple
from numpy.lib.stride_tricks import array_function_dispatch,_maybe_view_as_subclass,as_strided
# The functions below are not necessary if you are using numpy>=1.20
# To be able to use sliding_window_view, you can load from
# ef.sliding_window_view
@array_function_dispatch(_sliding_window_view_dispatcher)
def sliding_window_view(x, window_shape, axis=None, *,
subok=False, writeable=False):
"""
Create a sliding window view into the array with the given window shape.
Also known as rolling or moving window, the window slides across all
dimensions of the array and extracts subsets of the array at all window
positions.
.. versionadded:: 1.20.0
Parameters
----------
x : array_like
Array to create the sliding window view from.
window_shape : int or tuple of int
Size of window over each axis that takes part in the sliding window.
If `axis` is not present, must have same length as the number of input
array dimensions. Single integers `i` are treated as if they were the
tuple `(i,)`.
axis : int or tuple of int, optional
Axis or axes along which the sliding window is applied.
By default, the sliding window is applied to all axes and
`window_shape[i]` will refer to axis `i` of `x`.
If `axis` is given as a `tuple of int`, `window_shape[i]` will refer to
the axis `axis[i]` of `x`.
Single integers `i` are treated as if they were the tuple `(i,)`.
subok : bool, optional
If True, sub-classes will be passed-through, otherwise the returned
array will be forced to be a base-class array (default).
writeable : bool, optional
When true, allow writing to the returned view. The default is false,
as this should be used with caution: the returned view contains the
same memory location multiple times, so writing to one location will
cause others to change.
Returns
-------
view : ndarray
Sliding window view of the array. The sliding window dimensions are
inserted at the end, and the original dimensions are trimmed as
required by the size of the sliding window.
That is, ``view.shape = x_shape_trimmed + window_shape``, where
``x_shape_trimmed`` is ``x.shape`` with every entry reduced by one less
than the corresponding window size.
See Also
--------
lib.stride_tricks.as_strided: A lower-level and less safe routine for
creating arbitrary views from custom shape and strides.
broadcast_to: broadcast an array to a given shape.
Notes
-----
For many applications using a sliding window view can be convenient, but
potentially very slow. Often specialized solutions exist, for example:
- `scipy.signal.fftconvolve`
- filtering functions in `scipy.ndimage`
- moving window functions provided by
`bottleneck <https://github.com/pydata/bottleneck>`_.
As a rough estimate, a sliding window approach with an input size of `N`
and a window size of `W` will scale as `O(N*W)` where frequently a special
algorithm can achieve `O(N)`. That means that the sliding window variant
for a window size of 100 can be a 100 times slower than a more specialized
version.
Nevertheless, for small window sizes, when no custom algorithm exists, or
as a prototyping and developing tool, this function can be a good solution.
Examples
--------
>>> x = np.arange(6)
>>> x.shape
(6,)
>>> v = sliding_window_view(x, 3)
>>> v.shape
(4, 3)
>>> v
array([[0, 1, 2],
[1, 2, 3],
[2, 3, 4],
[3, 4, 5]])
This also works in more dimensions, e.g.
>>> i, j = np.ogrid[:3, :4]
>>> x = 10*i + j
>>> x.shape
(3, 4)
>>> x
array([[ 0, 1, 2, 3],
[10, 11, 12, 13],
[20, 21, 22, 23]])
>>> shape = (2,2)
>>> v = sliding_window_view(x, shape)
>>> v.shape
(2, 3, 2, 2)
>>> v
array([[[[ 0, 1],
[10, 11]],
[[ 1, 2],
[11, 12]],
[[ 2, 3],
[12, 13]]],
[[[10, 11],
[20, 21]],
[[11, 12],
[21, 22]],
[[12, 13],
[22, 23]]]])
The axis can be specified explicitly:
>>> v = sliding_window_view(x, 3, 0)
>>> v.shape
(1, 4, 3)
>>> v
array([[[ 0, 10, 20],
[ 1, 11, 21],
[ 2, 12, 22],
[ 3, 13, 23]]])
The same axis can be used several times. In that case, every use reduces
the corresponding original dimension:
>>> v = sliding_window_view(x, (2, 3), (1, 1))
>>> v.shape
(3, 1, 2, 3)
>>> v
array([[[[ 0, 1, 2],
[ 1, 2, 3]]],
[[[10, 11, 12],
[11, 12, 13]]],
[[[20, 21, 22],
[21, 22, 23]]]])
Combining with stepped slicing (`::step`), this can be used to take sliding
views which skip elements:
>>> x = np.arange(7)
>>> sliding_window_view(x, 5)[:, ::2]
array([[0, 2, 4],
[1, 3, 5],
[2, 4, 6]])
or views which move by multiple elements
>>> x = np.arange(7)
>>> sliding_window_view(x, 3)[::2, :]
array([[0, 1, 2],
[2, 3, 4],
[4, 5, 6]])
A common application of `sliding_window_view` is the calculation of running
statistics. The simplest example is the
`moving average <https://en.wikipedia.org/wiki/Moving_average>`_:
>>> x = np.arange(6)
>>> x.shape
(6,)
>>> v = sliding_window_view(x, 3)
>>> v.shape
(4, 3)
>>> v
array([[0, 1, 2],
[1, 2, 3],
[2, 3, 4],
[3, 4, 5]])
>>> moving_average = v.mean(axis=-1)
>>> moving_average
array([1., 2., 3., 4.])
Note that a sliding window approach is often **not** optimal (see Notes).
"""
window_shape = (tuple(window_shape)
if np.iterable(window_shape)
else (window_shape,))
# first convert input to array, possibly keeping subclass
x = np.array(x, copy=False, subok=subok)
window_shape_array = np.array(window_shape)
if np.any(window_shape_array < 0):
raise ValueError('`window_shape` cannot contain negative values')
if axis is None:
axis = tuple(range(x.ndim))
if len(window_shape) != len(axis):
raise ValueError(f'Since axis is `None`, must provide '
f'window_shape for all dimensions of `x`; '
f'got {len(window_shape)} window_shape elements '
f'and `x.ndim` is {x.ndim}.')
else:
axis = normalize_axis_tuple(axis, x.ndim, allow_duplicate=True)
if len(window_shape) != len(axis):
raise ValueError(f'Must provide matching length window_shape and '
f'axis; got {len(window_shape)} window_shape '
f'elements and {len(axis)} axes elements.')
out_strides = x.strides + tuple(x.strides[ax] for ax in axis)
# note: same axis can be windowed repeatedly
x_shape_trimmed = list(x.shape)
for ax, dim in zip(axis, window_shape):
if x_shape_trimmed[ax] < dim:
raise ValueError(
'window shape cannot be larger than input array shape')
x_shape_trimmed[ax] -= dim - 1
out_shape = tuple(x_shape_trimmed) + window_shape
return as_strided(x, strides=out_strides, shape=out_shape,
subok=subok, writeable=writeable)
def _broadcast_to(array, shape, subok, readonly):
shape = tuple(shape) if np.iterable(shape) else (shape,)
array = np.array(array, copy=False, subok=subok)
if not shape and array.shape:
raise ValueError('cannot broadcast a non-scalar to a scalar array')
if any(size < 0 for size in shape):
raise ValueError('all elements of broadcast shape must be non-'
'negative')
extras = []
it = np.nditer(
(array,), flags=['multi_index', 'refs_ok', 'zerosize_ok'] + extras,
op_flags=['readonly'], itershape=shape, order='C')
with it:
# never really has writebackifcopy semantics
broadcast = it.itviews[0]
result = _maybe_view_as_subclass(array, broadcast)
# In a future version this will go away
if not readonly and array.flags._writeable_no_warn:
result.flags.writeable = True
result.flags._warn_on_write = True
return result
def import_basemap():
old_proj_lib = os.environ['PROJ_LIB'] if 'PROJ_LIB' in os.environ else None
try:
os.environ['PROJ_LIB'] = '../usr/share/proj' # This one we need to import Basemap
global Basemap
from mpl_toolkits.basemap import Basemap
logger.info('Successfully imported basemap')
return True
except (ImportError, FileNotFoundError):
# revert to old proj_lib
if old_proj_lib is not None:
os.environ['PROJ_LIB'] = old_proj_lib
logger.warning('In this environment you cannot import Basemap')
return False
def import_cartopy():
try:
global cplt
try:
import general_purpose.cartopy_plots as cplt
except ImportError:
import cartopy_plots as cplt
logger.info('Successfully imported cartopy')
return True
except (ImportError, FileNotFoundError):
logger.warning('In this environment you cannot import cartopy')
return False
# set up the plotter:
def setup_plotter():
global plotter
if plotter is not None:
logger.info(f'Plotter already set to {plotter}')
return True
logger.info('Trying to import basemap')
if import_basemap():
plotter = 'basemap'
return True
logger.info('Trying to import cartopy')
if import_cartopy():
plotter = 'cartopy'
return True
logger.error('No valid plotter found')
return False
setup_plotter()
# Definition des fonctions
def significative_data(Data, Data_t_value=None, T_value=None, both=False, default_value=0): # CHANGE THIS FOR TEMPERATURE SO THAT THE OLD ROUTINE IS USED
'''
Filters `Data` depending whether `Data_t_value` exceeds a threshold `T_value`
Data that fail the filter conditions are set to `default_value`.
If `Data_t_value` or `T_value` are None, all of `Data` is considered significant
'''
return ut.significative_data(Data, Data_t_value, T_value, both=both, default_value=default_value)
def significative_data2(Data, Data_t_value, T_value, both): # CHANGE THIS FOR TEMPERATURE SO THAT THE OLD ROUTINE IS USED
'''
Does the same of significative_data, but with `default_value` to np.NaN
'''
return ut.significative_data(Data, Data_t_value, T_value, both=both, default_value=np.NaN)
# OLD VERSION
# Out_taken = np.empty((np.shape(Data)))
# Out_taken[:] = np.NaN
# Out_not_taken = np.empty((np.shape(Data)))
# Out_not_taken[:] = np.NaN
# N_points_taken = 0
# for la in range(len(Data)):
# for lo in range(len(Data[la])):
# if abs(Data_t_value[la, lo]) >= T_value:
# Out_taken[la, lo] = Data[la, lo]
# N_points_taken += 1
# else:
# Out_not_taken[la, lo] = Data[la, lo]
# if both == True:
# return Out_taken, Out_not_taken, N_points_taken
# elif both == False:
# return Out_taken, N_points_taken
def animate(i, m, Center_map, Nb_frame, Lon, Lat, T_value, data_colorbar_value, data_colorbar_t, data_colorbar_level,
data_contour_value, data_contour_t, data_contour_level, title_frame, rtime):
'''
Center_map not used
Plots at day `i` the contourf of the sigificant temperature and contour of the geopotential separating significant and non significant anomalies
'''
if plotter == 'cartopy':
raise NotImplementedError("Use cartopy_plots.animate")
fmt = '%1.0f'
temp_sign, ts_taken = significative_data(data_colorbar_value[i], data_colorbar_t[i], T_value, False)
zg_sign, zg_not, zg_taken = significative_data2(data_contour_value[i], data_contour_t[i], T_value, True)
if ts_taken != 8192 and zg_taken != 8192: #AL what is this???
print('i:', i, 'ts_taken:', ts_taken, 'zg_taken:', zg_taken)
plt.cla()
m.contourf(Lon, Lat, temp_sign, levels=data_colorbar_level, cmap=plt.cm.seismic, extend='both', latlon=True)
m.colorbar()
c_sign = m.contour(Lon, Lat, temp_sign, levels=data_colorbar_level, colors="black",linewidths=1, latlon=True, linestyles = "dotted")
m.drawcoastlines(color='black',linewidth=1)
m.drawparallels(np.arange(-80.,81.,20.),linewidth=0.5,labels=[True,False,False,False], color = "green")
m.drawmeridians(np.arange(-180.,181.,20.),linewidth=0.5,labels=[False,False,False,True],color = "green")
c_nots = m.contour(Lon, Lat, data_contour_value[i], levels=data_contour_level[:data_contour_level.shape[0]//2], colors="chocolate", linestyles = "dashed", linewidths=1, latlon=True) #negative insignificant anomalies of geopotential
v_sign = data_contour_level[int(len(data_contour_level) / 2)-1], # data_contour_level[int(len(data_contour_level) / 2)]
if len(c_nots.levels) > len(v_sign):
p.clabel(c_nots, v_sign, inline=True,fmt = fmt,fontsize=12)
c_nots = m.contour(Lon, Lat, data_contour_value[i], levels=data_contour_level[data_contour_level.shape[0]//2:], colors="tab:blue", linestyles = "dashed",linewidths=1, latlon=True) #positive insignificant anomalies of geopotential
v_sign = data_contour_level[int(len(data_contour_level) / 2)],
if len(c_nots.levels) > len(v_sign):
p.clabel(c_nots, v_sign, inline=True,fmt = fmt,fontsize=12)
c_sign = m.contour(Lon, Lat, zg_sign, levels=data_contour_level[:data_contour_level.shape[0]//2], colors="red", linestyles = "solid",linewidths=1, latlon=True) #negative significant anomalies of geopotential
c_sign = m.contour(Lon, Lat, zg_sign, levels=data_contour_level[data_contour_level.shape[0]//2:], colors="blue",linewidths=1, latlon=True) #positive significant anomalies of geopotential
plt.title(f'{title_frame}, r = {rtime}, day: {(i - Nb_frame//2)}', fontsize=20)
def PltAnomalyHist(distrib, numlevels, mycolor, myhatch, mymonths, mylinewidths, myfieldlabel, myobjct): # Plot histogram of an anomaly based on a data series
# histogram
n, bins, patches = plt.hist(distrib, 50, density=True, histtype='step', color=mycolor, hatch=myhatch,
alpha=1, label=r"{:s}: std = {:1.3f}, skew = {:1.3f}, kurt = {:1.3f}".format(
mymonths,np.std(distrib),skew(distrib),kurtosis(distrib, fisher=True)),
linewidth=mylinewidths)
# plot gaussian approximation of the anomaly
plt.plot(bins,np.exp(-bins**2/(2*np.std(distrib)**2))/(np.std(distrib)*np.sqrt(2*np.pi)),
color = mycolor,linestyle='dashed')
plt.yscale("log")
plt.xlabel(myfieldlabel + ' detrended anomaly')
plt.ylabel('Daily Probability')
plt.title('MMJAS (running mean) ' + myobjct)
def PltDistHist(myfield, convseq, mycolors, monthhatches, mymonth, mylinewidth, y, Tot_Mon1,area, start_month=5):
# Plot Distribution for each year and histograms for the anomalies
field_extract = myfield.abs_area_int[:,:]
objct = "over "+area
plt.figure(figsize=(30,5))
plt.subplot(141)
plt.plot(field_extract[y],label = 'daily')
plt.plot(np.convolve(field_extract[y], convseq, mode='valid'),label = f'{len(convseq)} d mean')
plt.title(f'Time evolution {objct} in {y = }')
plt.xlabel('Days from May 0')
plt.ylabel(myfield.label)
plt.legend(loc='best')
color_idx = np.linspace(0, 1, myfield.var.shape[0])
plt.subplot(142)
field_conv = []
for year in range(myfield.var.shape[0]):
field_conv.append(np.convolve(field_extract[year], convseq, mode='valid'))
plt.plot(field_conv[year],color=plt.cm.rainbow(color_idx[year]))
field_conv = np.array(field_conv)
plt.plot(np.convolve(field_extract[y], convseq, mode='valid'),'k-.')
plt.title(f'{len(convseq)} day running mean {objct}')
plt.xlabel('Days from May 0')
plt.ylabel(myfield.label)
plt.subplot(143)
for i in range(len(mymonth)):
temp = field_extract[:,Tot_Mon1[start_month+i]-Tot_Mon1[start_month]:Tot_Mon1[start_month+1+i]-Tot_Mon1[start_month]].reshape(myfield.var.shape[0]*(Tot_Mon1[start_month+1+i]-Tot_Mon1[start_month+i]))
PltAnomalyHist(temp, 50, mycolors[i], monthhatches[i], mymonth[i], mylinewidth[i], myfield.label, objct)
plt.legend(loc = 'best')
plt.subplot(144)
for i in range(len(mymonth)-1): # Here you have to be careful because A(t) is not defined for the september
temp = field_conv[:,Tot_Mon1[start_month+i]-Tot_Mon1[start_month]:Tot_Mon1[start_month+1+i]-Tot_Mon1[start_month]].reshape(myfield.var.shape[0]*(Tot_Mon1[start_month+1+i]-Tot_Mon1[start_month+i])) # 30 DAYS MAY NOT WORK FOR CESM
PltAnomalyHist(temp, 50, mycolors[i], monthhatches[i], mymonth[i], mylinewidth[i], myfield.label, objct)
plt.legend(loc = 'best')
def PltReturnsHist(XX_rt, YY_rt, xx_rt, yy_rt, A_max_sorted, Tot_Mon1, area, ax1, Ax, start_month=5, end_month=8):
# Plot Return times plus the histogram during the
ax1.scatter(XX_rt, YY_rt, s=4, color='royalblue', marker='x')
for i in range(len(xx_rt)):
ax1.text(xx_rt[i] + 0.02, -4.2, 'a{}={:.2f}'.format(int(xx_rt[i]), yy_rt[i]))
ax1.plot([xx_rt[i], xx_rt[i]], [-4.5, yy_rt[i]], linestyle='--', color='black', linewidth=0.5)
ax1.set_xscale('log')
ax1.set_xlabel('return time $\hat{r}$ (year)')
ax1.set_ylabel('temperature anomaly threshold $a_r$ (K)')
ax1.set_title('Temperature anomalies over '+ area, loc='left')
Days = []
years = []
for i in range(len(A_max_sorted)):
day, year = A_max_sorted[i][1] # heatwaves are already ranked by Phlippine based on 14 day temperature anomalies (Notice that she counts from June 1!)
Days.append(day+Tot_Mon1[start_month])
years.append(year)
# top 1/10 extreme events
n, bins, patches = Ax.hist(Days[:len(A_max_sorted)//10], bins = np.arange(Tot_Mon1[start_month],Tot_Mon1[end_month]-14),
density = True, facecolor='tab:brown', alpha=1, label = 'extreme $r=10$')
# top 1/4 extreme events
Ax.hist(Days[:len(A_max_sorted)//4], bins = np.arange(Tot_Mon1[start_month],Tot_Mon1[end_month]-14),
density = True, facecolor='tab:orange', alpha=0.7, label = 'extreme $r=4$')
# all extreme events
Ax.hist(Days[:len(A_max_sorted)], bins = np.arange(Tot_Mon1[start_month],Tot_Mon1[end_month]-14),
density = True, facecolor='tab:cyan', alpha=0.3, label = 'extreme $r=1$')
Ax.set_xlabel('Time, binned by {:1.4f}'.format(bins[1]-bins[0]), fontsize=13)
Ax.set_ylabel('Probability', fontsize=14)
Ax.set_ylim([0, 0.75*np.max(n)])
Ax.set_title("Events conditioned", fontsize=13)
Ax.legend(loc = 'best', fontsize=12)
def BootstrapReturnsOnly(myseries, TO, Tot_Mon1, area, ax, Ts, modified='no', write_path='./', start_month=6, end_month=9):
write_path = write_path.rstrip('/')
for T in Ts:
convseq = np.ones(T)/T
XX = []
YY = []
for j in range(10):
A = np.zeros((myseries.shape[0]//10, Tot_Mon1[end_month] - Tot_Mon1[start_month] - T+1)) # When we use convolve (running mean) there is an extra point that we can generate by displacing the window hence T-1 instead of T
for y in range(myseries.shape[0]//10):
A[y,:] = np.convolve(myseries[100*j+y,Tot_Mon1[start_month]:(Tot_Mon1[end_month])], convseq, mode='valid')
print(f"{A.shape = }")
if A.shape[1] > 30:
A_max, Ti, year_a = a_max_and_ti_postproc(A, A.shape[1])
else: # The season length is too short and we need to just take maximum
A_max = list(np.max(A,1))
Ti = list(np.argmax(A,1))
year_a = list(np.arange(myseries.shape[0]//10))
#print(Ti)
A_max_sorted = a_decrese(A_max, Ti, year_a)
#print(A_max_sorted)
#print(A_max_sorted)
XX_rt, YY_rt, xx_rt, yy_rt = return_time_fix(A_max_sorted, modified)
YY.append(np.array(YY_rt))
YY = np.array(YY)
# save results
np.save(f'{write_path}/Postproc/{TO}_{area}_XX_rt_{T}',XX_rt)
np.save(f'{write_path}/Postproc/{TO}_{area}_YY_mean_{T}',np.mean(YY,0))
np.save(f'{write_path}/Postproc/{TO}_{area}_YY_std_{T}',np.std(YY,0))
# plot
plt.fill_between(XX_rt, np.mean(YY,0)-np.std(YY,0), np.mean(YY,0)+np.std(YY,0),label=f'{T} days ({TO})')
ax.set_xscale('log')
ax.set_xlabel('return time $\hat{r}$ (year)')
ax.set_ylabel('temperature anomaly threshold $a_r$ (K)')
ax.set_title(f'Temperature anomalies over {area}', loc='left')
def BootstrapReturns(myseries,FROM, TO, Tot_Mon1,area, ax, Ts, modified='no', read_path='./', write_path='./'):
# remove extra / from paths
read_path = read_path.rstrip('/')
write_path = write_path.rstrip('/')
# Compare bootstrapped method (to be saved in "TO") to the points in "FROM"
BootstrapReturnsOnly(myseries, TO, Tot_Mon1, area, ax, Ts, modified, write_path=write_path)
for T in Ts:
ERA_XX_rt = np.load(f'{read_path}/../ERA/Postproc/{FROM}_{area}_XX_rt_{T}.npy')
ERA_YY_rt = np.load(f'{read_path}/../ERA/Postproc/{FROM}_{area}_YY_rt_{T}.npy')
plt.scatter(ERA_XX_rt, ERA_YY_rt, s=10, marker='x',label=str(T)+' days ('+FROM+')')
ax.legend(loc='best')
def func1(x, a, b, c, d):
return a * np.exp(b * x) + c * np.exp(d * x)
def func2(x, a, b, c, d):
return a * np.exp(b * x)/ b + c * np.exp(d * x)/ d
def autocorrelation(myseries, maxlag=100):
# this pads each year with padsize sample time of 0s so that when the array is permuted to be multiplied by itself we don't end up using the previous part of the year
series_pad = np.pad(myseries,((0, 0), (0, maxlag)), 'constant')
autocorr = []
for k in range(maxlag):
autocorr.append(np.sum(series_pad*np.roll(series_pad, -k))/(series_pad.shape[0]*(series_pad.shape[1]-k-maxlag)))
return autocorr
def PltAutocorrelationFit(autocorr_mean,autocorr_std,x1,x2, ax,period_label):
'''
ax is not used
'''
# Plot normalized Autocorrelation function
plt.plot(np.arange(0, len(autocorr_mean)), autocorr_mean,'b:', label=r'$\int C(t) dt$ = %5.1f d'%(integrate.cumtrapz(np.array(autocorr_mean), range(len(autocorr_mean)), initial=0)[-1]))
plt.plot(np.arange(0, len(autocorr_mean)), -autocorr_mean,'k:', label='- autocorrelation')
popt1, pcov1 = curve_fit(func1, np.array(range(x1,x2)), autocorr_mean[x1:x2], p0=(1, 1e-6, 1, 1e-6))
xaxis1 = np.arange(x1,x2)
plt.plot(xaxis1, func1(xaxis1, *popt1), 'r--', label=r'-slope$^{-1}_1$ = %5.1f ,-slope$^{-2}_2$ = %5.1f ,$\quad \tau$ = %5.1f ' %(-popt1[1]**(-1),-popt1[3]**(-1),- func2(0, *popt1)))
plt.title(period_label+r": $\Sigma_y \Sigma_t \alpha(t) \alpha(t+\tau)/N(\tau)$")
plt.yscale("log")
plt.xlabel(r"Lag $\tau$")
def PltAutocorrelationFit2(autocorr_mean,colors, linewidths, x1,x2, ax, Model):
# Plot normalized Autocorrelation function
plt.plot(np.arange(0, len(autocorr_mean)), autocorr_mean,colors[0], linewidth = linewidths[0], label=Model)
#r'$\int C(t) dt$ = %5.1f d'%(integrate.cumtrapz(np.array(autocorr_mean), range(len(autocorr_mean)), initial=0)[-1]))
#plt.plot(np.arange(0, len(autocorr_mean)), -autocorr_mean,'k:', label='- autocorrelation')
popt1, pcov1 = curve_fit(func1, np.array(range(x1,x2)), autocorr_mean[x1:x2], p0=(1, 1e-6, 1, 1e-6))
xaxis1 = np.arange(x1,x2)
plt.plot(xaxis1, func1(xaxis1, *popt1), colors[1], linewidth=linewidths[1],
label=r'A= %5.3f,$\quad$ B= %5.3f,$\quad$-slope$^{-1}_1$ = %5.1f ,$\quad$-slope$^{-2}_2$ = %5.1f ' %(popt1[0],popt1[2],-popt1[1]**(-1),-popt1[3]**(-1)))
plt.yscale("log")
plt.xlabel(r"Lag $\tau$")
def CompCompositesERA(series, myfield, T, Tot_Mon1, return_index, myfieldmean, modified='no', start_month=6, end_month=9):
# Computes composites conditioned to extremes of field of duration T based on months provided in Tot_Mon1, the return_index is the index of the return times
convseq = np.ones(T)/T
A = np.zeros((series.shape[0], Tot_Mon1[end_month] - Tot_Mon1[start_month] - T+1)) # When we use convolve (running mean) there is an extra point that we can generate by displacing the window hence 13 instead of 14
for y in range(series.shape[0]):
A[y,:]=np.convolve(series[y,Tot_Mon1[start_month]:(Tot_Mon1[end_month])], convseq, mode='valid')
print("A.shape = ",A.shape)
A_max, Ti, year_a = a_max_and_ti_postproc(A, A.shape[1])
year_a = range(series.shape[0])
A_max_sorted = a_decrese(A_max, Ti, year_a)
XX_rt, YY_rt, xx_rt, yy_rt = return_time_fix(A_max_sorted, modified)
print(xx_rt,yy_rt)
tau = np.arange(-30,30,1)
nb_events = 0
myfield.composite_mean = np.zeros((len(tau),myfield.var.shape[2],myfield.var.shape[3]))
myfield.composite_std = np.zeros((len(tau),myfield.var.shape[2],myfield.var.shape[3]))
for y in range(series.shape[0]):
if A_max[y] >= yy_rt[return_index]:
print("A_max["+str(y)+"] = ",A_max[y], "Ti["+str(y)+"] = ", Ti[y])
nb_events += 1
value = (myfield.detrended[y] - myfieldmean)[tau + (Tot_Mon1[start_month] + Ti[y]) ]
myfield.composite_mean += value # This is the raw sum
myfield.composite_std += value**2 # This is the raw square sum
print("number of events: ",nb_events)
# std and mean are computed below
myfield.composite_std = np.sqrt((myfield.composite_std - (myfield.composite_mean * myfield.composite_mean / nb_events)) / (nb_events - 1))
myfield.composite_mean /= nb_events
myfield.composite_t = (lambda a, b: np.divide(a, b, out=np.zeros(a.shape), where=b != 0))(np.sqrt(nb_events) * myfield.composite_mean, myfield.composite_std)
def CompCompositesERAThreshold(series, myfield, T, Tot_Mon1, threshold, myfieldmean, start_month=6, end_month=9):
A_max, Ti, year_a = CompExtremes(series, myfield, T, Tot_Mon1, threshold, start_month=start_month, end_month=end_month)
tau = np.arange(-30,30,1)
nb_events = 0
myfield.composite_mean = np.zeros((len(tau),myfield.var.shape[2],myfield.var.shape[3]))
myfield.composite_std = np.zeros((len(tau),myfield.var.shape[2],myfield.var.shape[3]))
for y in range(series.shape[0]):
if A_max[y] >= threshold:
print("A_max["+str(y)+"] = ",A_max[y], "Ti["+str(y)+"] = ", Ti[y])
nb_events += 1
value = (myfield.detrended[y] - myfieldmean)[tau + (Tot_Mon1[start_month] + Ti[y]) ]
myfield.composite_mean += value # This is the raw sum
myfield.composite_std += value**2 # This is the raw square sum
print("number of events: ",nb_events)
# std and mean are computed below
myfield.composite_std = np.sqrt((myfield.composite_std - (myfield.composite_mean * myfield.composite_mean / nb_events)) / (nb_events - 1))
myfield.composite_mean /= nb_events
myfield.composite_t = (lambda a, b: np.divide(a, b, out=np.zeros(a.shape), where=b != 0))(np.sqrt(nb_events) * myfield.composite_mean, myfield.composite_std)
def CompExtremes(series, myfield, T, Tot_Mon1, threshold, start_month=6, end_month=9):
'''
!!!!
myfield, threshold are not used
!!!!
The computations are performed between `start_month` (included) and `end_month` (excluded).
Month numeration is the standard one, i.e. 1 = January, 6 = June, 12 = December
'''
# Computes composites conditioned to extremes of field of duration T based on months provided in Tot_Mon1, the return_index is the index of the return times
convseq = np.ones(T)/T
A = np.zeros((series.shape[0], Tot_Mon1[end_month] - Tot_Mon1[start_month] - T+1)) # When we use convolve (running mean) there is an extra point that we can generate by displacing the window hence T - 1 instead of T
for y in range(series.shape[0]):
A[y,:]=np.convolve(series[y,Tot_Mon1[start_month]:(Tot_Mon1[end_month])], convseq, mode='valid')
print("A.shape = ",A.shape)
return a_max_and_ti_postproc(A, A.shape[1])
def CompCompositesThreshold(series, myfield, T, Tot_Mon1, threshold, start_month=6, end_month=9, observation_time=30, return_time_series=False):
'''
If `return_time_series` is true, then the time series are returned. All other computations are carried out anyways.
`time_series` is a dictionary of the time series of `myfield` aroud the heatwaves keyed with the year number
The computations are performed between `start_month` (included) and `end_month` (excluded).
Month numeration is the standard one, i.e. 1 = January, 6 = June, 12 = December
'''
A_max, Ti, year_a = CompExtremes(series, myfield, T, Tot_Mon1, threshold, start_month=start_month, end_month=end_month)
tau = np.arange(-observation_time,observation_time,1) # from observation_time days before to observation_time - 1 days after the heatwave
if return_time_series:
time_series = {}
nb_events = 0
myfield.composite_mean = np.zeros((len(tau),myfield.var.shape[2],myfield.var.shape[3])) # shape: (days, lat, lon)
myfield.composite_std = np.zeros((len(tau),myfield.var.shape[2],myfield.var.shape[3]))
# do statistics over the years
for y in range(series.shape[0]):
if A_max[y] >= threshold:
print(f'A_max[{y}] = {A_max[y]}, Ti[{y}] = {Ti[y]}')
nb_events += 1
value = (myfield.var[y])[tau + (Tot_Mon1[start_month] + Ti[y]) ] # value of the field (over the Earth) around the days when the heatwave is at its maximum
if return_time_series:
time_series[y] = value
myfield.composite_mean += value # This is the raw sum
myfield.composite_std += value**2 # This is the raw square sum
print(f'number of events: {nb_events}')
# std and mean are computed below
myfield.composite_std = np.sqrt((myfield.composite_std - (myfield.composite_mean**2 / nb_events)) / (nb_events - 1))
myfield.composite_mean /= nb_events
# t = sqrt(nb_events)*composite_mean/composite_std
myfield.composite_t = (lambda a, b: np.divide(a, b, out=np.zeros(a.shape), where=b != 0))(np.sqrt(nb_events) * myfield.composite_mean, myfield.composite_std)
if return_time_series:
return time_series
else:
return None
def CompComposites(series, myfield, T, Tot_Mon1, return_index, modified, start_month=6, end_month=9):
'''
Computes composites conditioned to extremes of field of duration T based on months provided in Tot_Mon1, the return_index is the index of the return times
The computations are performed between `start_month` (included) and `end_month` (excluded).
Month numeration is the standard one, i.e. 1 = January, 6 = June, 12 = December
'''
convseq = np.ones(T)/T
A = np.zeros((series.shape[0], Tot_Mon1[end_month] - Tot_Mon1[start_month] - T+1)) # When we use convolve (running mean) there is an extra point that we can generate by displacing the window hence 13 instead of 14
for y in range(series.shape[0]):
A[y,:]=np.convolve(series[y,Tot_Mon1[start_month]:(Tot_Mon1[end_month])], convseq, mode='valid')
print("A.shape = ",A.shape)
A_max, Ti, year_a = a_max_and_ti_postproc(A, A.shape[1])
year_a = range(series.shape[0])
A_max_sorted = a_decrese(A_max, Ti, year_a)
XX_rt, YY_rt, xx_rt, yy_rt = return_time_fix(A_max_sorted, modified)
print(xx_rt,yy_rt)
tau = np.arange(-30,30,1)
nb_events = 0
myfield.composite_mean = np.zeros((len(tau),myfield.var.shape[2],myfield.var.shape[3]))
myfield.composite_std = np.zeros((len(tau),myfield.var.shape[2],myfield.var.shape[3]))
for y in range(series.shape[0]):
if A_max[y] >= yy_rt[return_index]:
print("A_max["+str(y)+"] = ",A_max[y], "Ti["+str(y)+"] = ", Ti[y])
nb_events += 1
value = (myfield.var[y])[tau + (Tot_Mon1[start_month] + Ti[y]) ]
myfield.composite_mean += value # This is the raw sum
myfield.composite_std += value**2 # This is the raw square sum
print("number of events: ",nb_events)
# std and mean are computed below
myfield.composite_std = np.sqrt((myfield.composite_std - (myfield.composite_mean * myfield.composite_mean / nb_events)) / (nb_events - 1))
myfield.composite_mean /= nb_events
myfield.composite_t = (lambda a, b: np.divide(a, b, out=np.zeros(a.shape), where=b != 0))(np.sqrt(nb_events) * myfield.composite_mean, myfield.composite_std)
def CompCompositesBetween(series, myfield, T, Tot_Mon1, return_index, start_month=6, end_month=9):
'''
Computes composites conditioned to extremes of field of duration T based on months provided in Tot_Mon1, the return_index is the index of the return times
The computations are performed between `start_month` (included) and `end_month` (excluded).
Month numeration is the standard one, i.e. 1 = January, 6 = June, 12 = December
'''
convseq = np.ones(T)/T
A = np.zeros((series.shape[0], Tot_Mon1[end_month] - Tot_Mon1[start_month] - T+1)) # When we use convolve (running mean) there is an extra point that we can generate by displacing the window hence 13 instead of 14
for y in range(series.shape[0]):
A[y,:]=np.convolve(series[y,Tot_Mon1[start_month]:(Tot_Mon1[end_month])], convseq, mode='valid')
print("A.shape = ",A.shape)
A_max, Ti, year_a = a_max_and_ti_postproc(A, A.shape[1])
year_a = range(series.shape[0])
A_max_sorted = a_decrese(A_max, Ti, year_a)
XX_rt, YY_rt, xx_rt, yy_rt = return_time_fix(A_max_sorted)
print(xx_rt,yy_rt)
tau = np.arange(-30,30,1)
nb_events = 0
myfield.composite_mean = np.zeros((len(tau),myfield.var.shape[2],myfield.var.shape[3]))
myfield.composite_std = np.zeros((len(tau),myfield.var.shape[2],myfield.var.shape[3]))
for y in range(series.shape[0]):
if yy_rt[return_index[0]] <= A_max[y] < yy_rt[return_index[1]]:
print("A_max["+str(y)+"] = ",A_max[y], "Ti["+str(y)+"] = ", Ti[y])
nb_events += 1
value = (myfield.var[y])[tau + (Tot_Mon1[start_month] + Ti[y]) ]
myfield.composite_mean += value # This is the raw sum
myfield.composite_std += value**2 # This is the raw square sum
print("number of events: ",nb_events)
# std and mean are computed below
myfield.composite_std = np.sqrt((myfield.composite_std - (myfield.composite_mean * myfield.composite_mean / nb_events)) / (nb_events - 1))
myfield.composite_mean /= nb_events
myfield.composite_t = (lambda a, b: np.divide(a, b, out=np.zeros(a.shape), where=b != 0))(np.sqrt(nb_events) * myfield.composite_mean, myfield.composite_std)
def geo_contour(m, ax, Center_map, Lon, Lat, data_contour_value, data_contour_level, colmap1, colmap2):
'''
Plots a contour using two different colormaps for positive and negative anomalies
ax, Center_map, aren't used
'''
if plotter == 'cartopy':
return cplt.geo_contour(m, Lon, Lat, data_contour_value,
levels=data_contour_level, cmap1=colmap1, cmap2=colmap2)
c_sign = m.contour(Lon, Lat, data_contour_value,
levels=data_contour_level, cmap=colmap1,linewidths=1, linestyles="dashed",
latlon=True, vmin=data_contour_level[0], vmax=0)
subset = data_contour_value.copy()
subset[subset<0] = 0
c_sign = m.contour(Lon, Lat, subset,
levels=data_contour_level, cmap=colmap2,linewidths=1,
latlon=True, vmin=0, vmax=data_contour_level[-1])
# this is confusing
fmt = '%1.0f'
v_sign = data_contour_level[int(len(data_contour_level) / 2)-1], data_contour_level[int(len(data_contour_level) / 2)]
if len(c_sign.levels) > len(v_sign): # len(v_sign) = 2 because it is a 2-uple
p.clabel(c_sign, v_sign, inline=True,fmt=fmt,fontsize=14)
def geo_contourf(m, ax, Center_map, Lon, Lat, data_colorbar_value, data_colorbar_level, colmap, title_frame, put_colorbar=True, draw_gridlines=True):
'''
ax, Center_Map aren't used
'''
if plotter == 'cartopy':
return cplt.geo_contourf(m, Lon, Lat, data_colorbar_value,
levels=data_colorbar_level, cmap=colmap, title=title_frame, put_colorbar=put_colorbar, draw_gridlines=draw_gridlines)
plt.cla()
m.contourf(Lon, Lat, data_colorbar_value, levels=data_colorbar_level, cmap=colmap, extend='both', latlon=True)
if put_colorbar:
m.colorbar()
m.drawcoastlines(color='black',linewidth=1)
m.drawparallels(np.arange(-80.,81.,20.),linewidth=0.5,labels=[True,False,False,False], color = "green")
m.drawmeridians(np.arange(-180.,181.,20.),linewidth=0.5,labels=[False,False,False,True],color = "green")
plt.title(title_frame, fontsize=20)
def geo_contour_color(m, ax, Center_map, Lon, Lat, T_value, data_contour_value, data_contour_t, data_contour_level, colors, mylinestyles, mylinewidths):
'''
ax, Center_map not used
'''
fmt = '%1.0f'
fontsize = 12
if plotter == 'cartopy':
return cplt.geo_contour_color(m, Lon, Lat, data_contour_value, data_contour_t, T_value,
levels=data_contour_level, colors=colors, linestyles=mylinestyles,
linewidths=mylinewidths, fmt=fmt, fontsize=fontsize)
zg_sign, zg_not, zg_taken = significative_data2(data_contour_value, data_contour_t, T_value, True)
c_nots = m.contour(Lon, Lat, data_contour_value, levels=data_contour_level[:data_contour_level.shape[0]//2], colors=colors[1], linestyles = mylinestyles[1], linewidths=mylinewidths[1], latlon=True) #negative insignificant anomalies of geopotential
v_sign = data_contour_level[int(len(data_contour_level) / 2)-1], # data_contour_level[int(len(data_contour_level) / 2)]
if len(c_nots.levels) > len(v_sign):
p.clabel(c_nots, v_sign, inline=True,fmt=fmt,fontsize=fontsize)
c_nots = m.contour(Lon, Lat, data_contour_value, levels=data_contour_level[data_contour_level.shape[0]//2:], colors=colors[2], linestyles = mylinestyles[2],linewidths=mylinewidths[2], latlon=True) #positive insignificant anomalies of geopotential
v_sign = data_contour_level[int(len(data_contour_level) / 2)],
if len(c_nots.levels) > len(v_sign):
p.clabel(c_nots, v_sign, inline=True,fmt=fmt,fontsize=fontsize)
c_sign = m.contour(Lon, Lat, zg_sign, levels=data_contour_level[:data_contour_level.shape[0]//2], colors=colors[0], linestyles = mylinestyles[0],linewidths=mylinewidths[0], latlon=True) #negative significant anomalies of geopotential
c_sign = m.contour(Lon, Lat, zg_sign, levels=data_contour_level[data_contour_level.shape[0]//2:], colors=colors[3], linestyles = mylinestyles[3],linewidths=mylinewidths[3], latlon=True) #positive significant anomalies of geopotential
def PltMaxMinValue(m,Lon, Lat, data_contour_value):
if plotter == 'cartopy':
return cplt.PltMaxMinValue(m, Lon, Lat, data_contour_value)
coordsmax = np.unravel_index(np.argmin(data_contour_value, axis=None), data_contour_value.shape)
x, y = m(Lon[coordsmax[0], coordsmax[1]], Lat[coordsmax[0], coordsmax[1]])
txt = plt.text(x, y, "{:1.0f}".format(np.min(data_contour_value)), color='red')
txt.set_path_effects([PathEffects.withStroke(linewidth=2, foreground='w')])
coordsmax = np.unravel_index(np.argmax(data_contour_value, axis=None), data_contour_value.shape)
x, y = m(Lon[coordsmax[0], coordsmax[1]], Lat[coordsmax[0], coordsmax[1]])
txt = plt.text(x, y, "{:1.0f}".format(np.max(data_contour_value)), color='blue')
txt.set_path_effects([PathEffects.withStroke(linewidth=2, foreground='w')])
def anomaly_animate(m, ax, Center_map, Lon, Lat, data_colorbar_value, data_colorbar_level,
data_contour_value, data_contour_level, colmap, title_frame):
if plotter == 'cartopy':
raise NotImplementedError("Use cartopy_plots.animate")
fmt = '%1.0f'
plt.cla()
m.contourf(Lon, Lat, data_colorbar_value, levels=data_colorbar_level, cmap=colmap, extend='both', latlon=True)
m.colorbar()
c_sign = m.contour(Lon, Lat, data_contour_value, levels=data_contour_level, cmap="PuRd",linewidths=1, linestyles = "dashed", latlon=True, vmin = data_contour_level[0], vmax = 0)
subset = data_contour_value.copy()
print(subset.shape)
coordsmax = np.unravel_index(np.argmin(data_contour_value[:32,:], axis=None), data_contour_value[:32,:].shape)
x, y = m(Lon[coordsmax[0], coordsmax[1]], Lat[coordsmax[0], coordsmax[1]])
txt = plt.text(x, y, "{:1.0f}".format(np.min(data_contour_value[:32,:])), color='red')
subset[subset<0] = 0
txt.set_path_effects([PathEffects.withStroke(linewidth=2, foreground='w')])
print(subset.shape)
c_sign = m.contour(Lon, Lat, subset, levels=data_contour_level, cmap="summer",linewidths=1, latlon=True, vmin = 0, vmax = data_contour_level[-1])
v_sign = data_contour_level[int(len(data_contour_level) / 2)-1], data_contour_level[int(len(data_contour_level) / 2)]
coordsmax = np.unravel_index(np.argmax(data_contour_value[:32,:], axis=None), data_contour_value[:32,:].shape)
x, y = m(Lon[coordsmax[0], coordsmax[1]], Lat[coordsmax[0], coordsmax[1]])
txt = plt.text(x, y, "{:1.0f}".format(np.max(data_contour_value[:32,:])), color='blue')
txt.set_path_effects([PathEffects.withStroke(linewidth=2, foreground='w')])
if len(c_sign.levels) > len(v_sign):
p.clabel(c_sign, v_sign, inline=True,fmt =fmt,fontsize=14)
m.drawcoastlines(color='black',linewidth=1.5)
m.drawparallels(np.arange(-80.,81.,20.),linewidth=0.75,labels=[True,False,False,False], color = "black")
m.drawmeridians(np.arange(-180.,181.,20.),linewidth=0.75,labels=[False,False,False,True],color = "black")
plt.title(title_frame, fontsize=20)
def absolute_animate(i, m, ax, Center_map, Nb_frame, Lon, Lat, data_colorbar_value, data_colorbar_level,
data_contour_value, data_contour_level, colmap, title_frame):
if plotter == 'cartopy':
raise NotImplementedError("Use cartopy_plots.animate")
fmt = '%1.0f'
print('i:', i)
plt.cla()
coordsmax = np.unravel_index(np.argmax(data_contour_value[:Lon.shape[0]//2,:], axis=None), data_contour_value[:Lat.shape[0]//2,:].shape)
x, y = m(Lon[coordsmax[0], coordsmax[1]], Lat[coordsmax[0], coordsmax[1]])
maximum = np.max(data_contour_value[:Lat.shape[0]//2,:])
txt = plt.text(x, y, "{:1.0f}".format(maximum), color='blue')
coordsmax2 = np.unravel_index(np.argmin(data_contour_value[:Lon.shape[0]//2,:], axis=None), data_contour_value[:Lat.shape[0]//2,:].shape)
x2, y2 = m(Lon[coordsmax2[0], coordsmax2[1]], Lat[coordsmax2[0], coordsmax2[1]])
minimum = np.min(data_contour_value[:Lat.shape[0]//2,:])
txt2 = plt.text(x2, y2, "{:1.0f}".format(minimum), color='red')
c_sign_f = m.contourf(Lon, Lat, data_contour_value, levels=data_contour_level, latlon=True, cmap = "GnBu", vmin = data_contour_level[15], vmax = data_contour_level[-20])#colors="lime")
cbar=m.colorbar(location="bottom")
contf = m.contourf(Lon, Lat, data_colorbar_value, levels=data_colorbar_level, cmap=colmap, extend='both', latlon=True)
m.colorbar()
c_sign = m.contour(Lon, Lat, data_contour_value, levels=data_contour_level,linewidths=2, latlon=True, cmap = "GnBu", vmin = data_contour_level[15], vmax = data_contour_level[-20])#colors="lime")
v_sign = data_contour_level[int(len(data_contour_level) / 2)-1], data_contour_level[int(len(data_contour_level) / 2)]
txt.set_path_effects([PathEffects.withStroke(linewidth=2, foreground='w')])
txt2.set_path_effects([PathEffects.withStroke(linewidth=2, foreground='w')])
m.drawcoastlines(color='pink',linewidth=1)
m.drawparallels(np.arange(-80.,81.,20.),linewidth=0.75,labels=[True,False,False,False], color = "white")
m.drawmeridians(np.arange(-180.,181.,20.),linewidth=0.75,labels=[False,False,False,True],color = "white")
plt.title(title_frame)
def anomaly_absolute_animate(m, ax, Center_map, Lon, Lat, data_colorbar_value, data_colorbar_level,
data_contour_value, data_contour_level, colmap, title_frame):
if plotter == 'cartopy':
raise NotImplementedError("Use cartopy_plots.animate")
fmt = '%1.0f'
plt.cla()
m.contourf(Lon, Lat, data_colorbar_value, levels=data_colorbar_level, cmap=colmap, extend='both', latlon=True)
m.colorbar()
CS = m.contour(Lon, Lat, data_contour_value, levels=data_contour_level, colors='darkgreen',linewidths=2, latlon=True)
ax.clabel(CS, CS.levels, inline=True, fmt=fmt, fontsize=10)
m.drawcoastlines(color='black',linewidth=1.5)
m.drawparallels(np.arange(-80.,81.,20.),linewidth=0.75,labels=[True,False,False,False], color = "black")
m.drawmeridians(np.arange(-180.,181.,20.),linewidth=0.75,labels=[False,False,False,True],color = "black")
ax.set_title(title_frame)
def full_extent(ax, padx=0.0, pady=[]):
"""Get the full extent of an axes, including axes labels, tick labels, and
titles."""
if pady == []:
pady = padx
# For text objects, we need to draw the figure first, otherwise the extents
# are undefined.
ax.figure.canvas.draw()
items = []
if ax.get_xscale() == 'log':
items += ax.get_xticklabels()[2:-2] # weird logscale behavior
else:
items += ax.get_xticklabels()[1:-1]
if ax.get_yscale() == 'log':
items += ax.get_yticklabels()[-2:2]
else:
items += ax.get_yticklabels()[-1:1]
items += [ax, ax.title, ax.xaxis.label, ax.yaxis.label]
# items += [ax, ax.title]
bbox = Bbox.union([item.get_window_extent() for item in items])
return bbox.expanded(1.0 + padx, 1.0 + pady)
def return_time_fix(D_sorted, modified='no', specific_returns=[1, 4, 10, 40, 100, 1000]): # In this function we fix the length
'''
Computes the return time from
D_sorted: sorted dictionary with layout {anomaly: [day, year]}
specific_returns: list
list of return times that will populate x_rt and y_rt
If modified == 'no':
the return time `tau` for anomaly `a` is
`tau` = `N`/`m`
Where `N` is the total number of events in D_sorted and `m` is the number of events which have an anomaly >= `a`
If modified == 'yes':
`tau` = 1/log(1 - `m`/`N`)
For an explanation of this formula look at
T. Lestang et al. 'Computing return times or return periods with rare event algorithms'.
DOI: https://doi.org/10.1088/1742-5468/aab856
'''
m = 1 # index that counts how many extreme events are more extreme than a given one. Since the events are ordered, this is just the event counter.
Y_rt = []
X_rt = []
y_rt = []
x_rt = []
for key in D_sorted:
if modified == 'yes':
r1 = - 1/(np.log(1 - m/len(D_sorted))) # assumption of Poisson process
else:
r1 = len(D_sorted) / m # compute return time
Y_rt.append(key[0])
X_rt.append(r1)
m += 1
for r1s in [1, 4, 10, 40, 100, 1000]:
r1s_closest = min(X_rt, key=lambda x:abs(x-r1s))
x_rt.append(r1s_closest)
y_rt.append(Y_rt[X_rt.index(r1s_closest)])
return X_rt, Y_rt, x_rt, y_rt
def a_max_and_ti_postproc(A, length=None):
"""
Generates unranked set of maximal anomalies per each year and when they occur.
`A` needs to have an extra point at the beginning and end of each year to check if a maximum at the extremes is local or not.
"""
# Probably outdated comment
# In the code A is expected to be loaded from June1 - 1 to August16 + 1 to check the maxima at the boundaries
just_max_index = []
if length is None:
A_summer = A[ :, 1:-1] # allow to check maxima at the edges
length = A_summer.shape[1]
else:
A_summer = A[:, 1:length+1]
if A_summer.shape[1] < length:
warnings.warn('a_max_and_ti_postproc: adjusting length')
length = A_summer.shape[1]
#print(' verif: we look A(t) over {} index (excepted value={})'.format(len(A_summer[0]), length))
out_A_max = []
out_Ti = []
out_year_a = []
year_with_before_non_loc = [] # this way we have data about the maxima (where they belong)