-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsm_pp_local_coupling_diagnostics.py
3250 lines (2342 loc) · 178 KB
/
sm_pp_local_coupling_diagnostics.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
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Thu Apr 12 10:54:12 2018
@author: julian.giles
"""
# Este script calcula los indices de heterogeneidad para comparar los eventos
# de precipitación por la tarde con las condiciones precedentes de humedad del suelo
# Version 2 : improved efficiency
# Version 3 : fixed proper control non-event definition (no morning prec)
# Version 4 : Completely redone code. Calculation is fragmented in more stages for easier bug solving.
# Version 5 : New approach for calculating faster non event metrics
# Version 6 : Fixed bug, v5 was not taking into account the season selection and was calculating all year.
# Now all year is calculated and saved, season selection is for delta calculations and posterior plotting
# Version 7 : Updated code to use xarray and cartopy
# Version 8 : Implemented box size election
# Version 9 : Implemented dynamic regime classification (welty et al 2018, 2020) using VIMFC
# Version 10: Implemented degrading of resolution for delta calculation (from original grid to NxN pixels grid) (esto influye a partir del calculo de los deltas)
# Version 11: Added combination of datasets (GLEAM+CMORPH+ERA5). Added delta_period for selection of sub-period before delta calculation.
# Added alternative Ys calculation. Added SM anomaly parameters.
# Version 12: Modified code for new timestep selection (new juli_functions option).
# Now timesteps represent values in the current hour (t - t+1) instead of previous hour (t-1 - t)
# Added new SM anomaly calculation option (with respect to the climatology for that day of the year)
# Added new SM anomaly calculation option (with respect to the seasonal expectation: average 21-day rolling mean for that day of the year, without considering event year)
# Version 13: Missing feature added: now events with morning P>pre_mor_max in adjacent tiles are also filtered out.
# Improvements to speed with wrapping of xr.apply_ufunc and new event detection method
# Version 14: Missing feature added: now non-events with morning P>pre_mor_max in adjacent tiles are also filtered out.
# Version 15: minor bug fixed: SM anomalies calculated only from morning values (instead of daily averages). Forced SM from UNC to be fixed to the mean annual wave.
# Version 16: bug fixed: improved way to select timezone bands (some hours from the day after the event were being left out)
# Version 17: added condition to test whether the SM increases after the afternoon P event (useful for mixed SM and P datasets)
# Queda por retocar:
# falta agregar un if que si se cargan los datos de una corrida anterior se pase directamente a los graficos (o al calculo de deltas)
# si me voy a otra region que no sea Sudamerica, cuidado con la seleccion de bandas horarias (actualmente a las horas de manana/tarde se les resta el huso horario, que podria ser negativo en otra region)
# CUIDADO CON LOS MULTIPLICADORES DE LAS UNIDADES DE PRECIPITACION (por ej ERA5 está en m/h no en mm/h)
# Guardar con pickle no es forward compatible, cambiar (ys_event_types)
##########################
#
# CUIDADO AL CARGAR DATOS YA CALCULADOS QUE LOS DELTAS NO ESTAN IDENTIFICADOS SEGUN ESTACION, FALTA MEJORAR ESTO
#
##########################
# ------------- PAQUETES --------------
# Con esto que está primero se soluciona el eror del device grafico. Al final no grafica nada pero se puede salvar el plot
import matplotlib
# Force matplotlib to not use any Xwindows backend.
#matplotlib.use('Agg')
import matplotlib.pyplot as plt
import cartopy
import cartopy.crs as ccrs
import cartopy.feature
from cartopy.mpl.ticker import LongitudeFormatter, LatitudeFormatter
import numpy as np
from numpy import ma
import pandas as pd
import xarray as xr
from datetime import datetime
import matplotlib.colors as mcolors
import os
from matplotlib import gridspec
import scipy.stats
from scipy import signal
import gc
import juli_functions
import plotly.offline as py
import plotly.graph_objs as go
import plotly.tools as tls
#import comet as cm
from skimage.feature import peak_local_max
import itertools
import math
import timeit
from scipy import stats
import collections
import warnings
#ignore by message
warnings.filterwarnings("ignore", message="Default reduction dimension will be changed to the grouped dimension")
warnings.filterwarnings("ignore", message="More than 20 figures have been opened")
warnings.filterwarnings("ignore", message="Setting the 'color' property will override the edgecolor or facecolor properties.")
warnings.filterwarnings("ignore", category=FutureWarning)
# ---------- PARÁMETROS ----------
#lista de variables que quiero ver (si quiero EF ponerlo al final de la lista, dsps de lhf y shf)
var_list = ['pre','lhf','shf','lwr','swr','t2m','slp','u900','v900','uv900conv','u10m', 'v10m', 'uv10mconv', 'qu2d', 'qv2d', 'vimfc2d',
'EF', 'EF_v2', 'q900', 'zi', 'evapot', 'swa', 'w900', 'w500', 'q2m', 'cloudbot', 'lowcc', 'totcc', 'qu900', 'qv900', 'quv900conv',
'precwtr']
var_list = ['pre', 'sm1', 'vimfc2d', 'evapot', 'orog', 'lsmask'] # la orografia tiene que ir ultima
chunksize = 1000 # tamaño de los chunks para dask
start_date = '1983-01-01'
end_date = '2012-12-31'
models = {
'RCA4': "RCA4 "+start_date[0:4]+"-"+end_date[0:4],
'RCA4CLIM': "RCA4CLIM "+start_date[0:4]+"-"+end_date[0:4],
# 'LMDZ': "LMDZ "+start_date[0:4]+"-"+end_date[0:4],
# 'TRMM-3B42': "TRMM-3B42 V7 1998-2012",
# 'CMORPH': "CMORPH V1.0 1998-2012",
# 'JRA-55': "JRA-55 "+start_date[0:4]+"-"+end_date[0:4],
'ERA5': "ERA5 "+start_date[0:4]+"-"+end_date[0:4],
'GLEAM': "GLEAM "+start_date[0:4]+"-"+end_date[0:4],
'GLDASNOAH': "GLDASNOAH "+start_date[0:4]+"-"+end_date[0:4],
'ESACCI': "ESA-CCI "+start_date[0:4]+"-"+end_date[0:4],
}
latlims=(-57,13.5) # custom lat limits for loading the data (default is -50.3, 13.5)
load_raw = True # cargar todos los datos originales crudos?
reload = False #reload previously calculated climatologies?
trih = False # force datasets into 3h steps (poner en True para los mapas trihorarios)
seasons = [''] # estaciones que quiero calcular (en este script se calcula en ppio para todo y despues se elige una muestra para los delta)
months = 'JFMAMJJASOND' # string de meses
seas_warm = [1,2,3,10,11,12] # En que meses quiero la estacion a considerar (incluidos)
seas_cold = [4,5,6,7,8,9]
homepath = '/home/julian.giles/datos/'
data_path = '/datosfreyja/d1/GDATA/'
temp_path = '/home/julian.giles/datos/temp/heterog_sm_pp/run5_v17/'
images_path = '/home/julian.giles/datos/CTL/Images/heterogeneity_sm_pre_taylor_guillod/run5_v17/'
font_size = 20 # font size for all elements
proj = ccrs.PlateCarree(central_longitude=0.0) # Proyeccion cyl eq
mult_hd = juli_functions.unit_multipliers()
interpolated= 'no' # yes or no all datasets interpolated to the RCA grid
lonfix = {'yes': {'LMDZ':0, 'TRMM-3B42':0},
'no': {'LMDZ':-360, 'TRMM-3B42':-360}}
latfix = {'yes':1, 'no':-1}
units_labels=juli_functions.units_labels()
regions = juli_functions.regions()
arrow_scale={'vimfc2d':4000,
'quv900conv':1,
'uv900conv':100,
'uv850conv':100,
'uv10mconv':100}
arrow_scale_anoms={'vimfc2d':1000,
'quv900conv':0.3,
'uv900conv':50,
'uv850conv':50,
'uv10mconv':25}
arrow_spacing = 6
# diccionario con los nombres de los archivos:
files = juli_functions.files_dict()
# para las etiquetas de los subplots
numbering = ['(a)', '(b)', '(c)', '(d)', '(e)', '(f)', '(g)', '(h)', '(i)', '(j)', '(k)', '(l)', '(m)', '(n)', '(o)', '(p)', '(q)', '(r)', '(s)']
# PRINT SELECTED OPTIONS
print('Script started. Computing datasets '+str([mod for mod in models.keys()])+'\n variables: '+str(var_list)+'\n from '+start_date+' to '+end_date+'\n Reloading previous calculations? '+str(reload)+'\n Forcing 3h data conversion? '+str(trih))
# ----------- PASAR RCA4 A TRIHORARIO -------------
#aux_counter = 0
#for model in ['RCA4', 'RCA4CLIM']:
# for var in ['pre','t2m', 'evapot']:
# if not ('3h' in files[model][var]):
# aux = xr.open_dataset(homepath+files[model][var], chunks={'time':1000})
# var_temp = dict(aux.data_vars)
# if var == 'pre' or var== 'evapot':
# aux_2 = aux.sel(time=slice(start_date, end_date)).resample(time='3H', closed= 'right', label= 'right').sum() #[[str(var_name) for var_name in set(var_temp.keys())][0]][1:,:,:,:]\
# aux_2.to_netcdf(homepath+files[model][var][:-3]+'_3hsum.nc')
# if var == 't2m':
# aux_2 = aux.sel(time=slice(start_date, end_date)).resample(time='3H', closed= 'right', label= 'right').last(skipna=False) #[[str(var_name) for var_name in set(var_temp.keys())][0]][1:,:,:,:]\
# aux_2.to_netcdf(homepath+files[model][var][:-3]+'_3h.nc')
# del(aux); del(aux_2)
# aux_counter = aux_counter +1
#
#if aux_counter != 0:
# #exit the program early
# from sys import exit
# exit('3h file computed, reset script with new file')
# ---------- TOMA DE DATOS -----------
lon = dict()
lat = dict()
lonproj = dict()
latproj = dict()
if load_raw:
data_xr, data, lon, lat, lonproj, latproj = juli_functions.load_datasets(models, var_list, start_date, end_date, data_path, homepath,
files, chunksize, seas_warm, seas_cold, latfix, lonfix,
forward_timestep=True,
interpolated='no', latlims=latlims, triRCA= trih)
# ------------- CAMBIAR FUENTE ------------------
matplotlib.rcParams.update({'font.size':font_size}) #Change font size for all elements
#%% ---------- PARÁMETROS ----------
pre_multipliers = 1#/1000 # para acomodar las unidades de precipitación. Ej: ERA5 viene en m/h, entonces hay q dividir los umbrales por mil para q sean las mismas unidades
if 'ERA5' in models: pre_multipliers = 1/1000
if 'GLDASNOAH' in models: pre_multipliers = 1/(3*60*60)
if 'CMORPH' in models: pre_multipliers = 1
ys_calculation_type = 'min' # 'min' for comparison against min P point, 'mean' for comparison against sorrounding mean
delta_period = ('1983-01-01', '2012-12-31') # (start_date, end_date) Período sobre el cual calcular los deltas (puedo tener todo el proceso de eventos hecho para un periodo mas largo y dsps elegir sub periodo para los delta finales)
load_deltas = False # load previously calculated deltas?
seas = set([10,11,12,1,2,3]) # set([12,1,2])# set([4,5,6,7,8,9]) # set([1,2,3,10,11,12]) # En que meses quiero la estacion a considerar (incluidos)
seas_name = 'ONDJFM' # Para los títulos
# test for increase in SM after afternoon P event?
test_increase_sm = False
# rangos horarios, recordar que ahora los timesteps indican el inicio del intervalo (forward_timestep=True)
rango_sm = (6,11) # Rango de horas para SM (en la mañana)
rango_pre_mor = (6,11) # Rango de horas para pre (en la mañana) Tener en cuenta que es el acumulado
rango_pre_aft = (12,23) # Rango de horas para pre (en la tarde)
if 'RCA4' in models or 'RCA4CLIM' in models: rango_sm = (6,8); rango_pre_mor = (6,8); rango_pre_aft = (9,20)
pre_mor_max = 1*pre_multipliers # Máxima prec en la mañana en mm
pre_aft_min = 4*pre_multipliers # Mínima prec en la tarde en mm
delta_orog_lim = 180 # Máximo cambio en orografía admitido dentro de la caja 3x3 en metros (para 0.25 seria 180, para 0.5 seria 360)
box_size = (3,3) # Dimensiones (horizontal,vertical) de la caja de los eventos (en puntos de grilla)
if 'RCA4' in models: delta_orog_lim = 360
box_size2 = (int((box_size[0]-1)/2), int((box_size[1]-1)/2)) # para uso en el calculo
bootslength = 1000 # Cantidad de valores del bootstrapping
min_events = 25 # minimo de eventos que tiene que haber para plotear el resultado (solo aplica a los graficos)
degrade = True # degradar la reticula para agrupar eventos?
degrade_n = 6 # numero de puntos de reticula a agrupar (degrade_n x degrade_n)
if 'RCA4' in models: degrade_n = 3
if degrade_n >0: degrade =True
n_rollmean = 31 # nro de dias de referencia para tomar la anomalia (si es centrada tiene que ser impar)
sm_roll_mean_center = True # si tomar la anomalia de SM respecto a la rolling mean centrada (True) o para atras (False), para quitar los bias estacionales
seas_expect_smanom = False # la anomalia de SM es respecto a la seasonal expectation (Petrova, tomado de Taylor): roll mean centrada de 21 dias y promediada en los años menos en el año del evento
if seas_expect_smanom: sm_roll_mean_center = True
dayofyear_smanom = False # si hacer la anomalia de SM respecto a la climatología para ese dia del año. Si False, entonces hacer la rolling mean
previous_day_sm = False # calcula usando la SM promedio del dia previo en lugar de por la mañana (usa datos diarios de SM)
#%% --------- CONSTRUYO EL DATASET MEZCLA DE GLEAM+CMORPH+ERA5 ----------
if 'GLEAM' in models.keys():
data['GLEAM+CMORPH+ERA5'] = dict()
for var in var_list:
data['GLEAM+CMORPH+ERA5'][var] = dict()
data['GLEAM+CMORPH+ERA5']['pre'][''] = data['CMORPH']['pre']['']
data['GLEAM+CMORPH+ERA5']['sm1'][''] = data['GLEAM']['sm1'][''][:,:,1:-1].transpose('time', 'lat', 'lon')
data['GLEAM+CMORPH+ERA5']['evapot'][''] = data['GLEAM']['evapot'][''][:,:,1:-1].transpose('time', 'lat', 'lon')
for var in ['vimfc2d', 'orog', 'lsmask']:
data['GLEAM+CMORPH+ERA5'][var][''] = data['ERA5'][var][''][:,1:-2,:-1].rename({'longitude':'lon', 'latitude':'lat'})
lat['GLEAM+CMORPH+ERA5'] = data['GLEAM+CMORPH+ERA5'][var]['']['lat']
lon['GLEAM+CMORPH+ERA5'] = data['GLEAM+CMORPH+ERA5'][var]['']['lon']
lonproj['GLEAM+CMORPH+ERA5'], latproj['GLEAM+CMORPH+ERA5'] = np.meshgrid(lon['GLEAM+CMORPH+ERA5'], lat['GLEAM+CMORPH+ERA5'])
data['GLEAM+CMORPH+ERA5']['pre'][''].coords['lon'] = data['GLEAM+CMORPH+ERA5']['pre']['']['lon']-0.125
data['GLEAM+CMORPH+ERA5']['pre'][''].coords['lat'] = data['GLEAM+CMORPH+ERA5']['pre']['']['lat']-0.125
data['GLEAM+CMORPH+ERA5']['sm1'][''].coords['lon'] = data['GLEAM+CMORPH+ERA5']['sm1']['']['lon']-0.125
data['GLEAM+CMORPH+ERA5']['sm1'][''].coords['lat'] = data['GLEAM+CMORPH+ERA5']['sm1']['']['lat']-0.125
data['GLEAM+CMORPH+ERA5']['evapot'][''].coords['lon'] = data['GLEAM+CMORPH+ERA5']['evapot']['']['lon']-0.125
data['GLEAM+CMORPH+ERA5']['evapot'][''].coords['lat'] = data['GLEAM+CMORPH+ERA5']['evapot']['']['lat']-0.125
models = {'GLEAM+CMORPH+ERA5': "GLEAM+CMORPH+ERA5 "+start_date[0:4]+"-"+end_date[0:4]}
if 'GLDASNOAH' in models.keys():
if 'CMORPH' in models.keys():
# creo diccionario
data['GLDASNOAH+CMORPH+ERA5'] = dict()
for var in var_list:
data['GLDASNOAH+CMORPH+ERA5'][var] = dict()
# Muevo las lon/lat para que coincidan
data['CMORPH']['pre'][''].coords['lon'] = data['CMORPH']['pre']['']['lon']-0.125
data['CMORPH']['pre'][''].coords['lat'] = data['CMORPH']['pre']['']['lat']-0.125
data['GLDASNOAH']['sm1'][''].coords['lat'] = data['GLDASNOAH']['sm1']['']['lat']-0.125
# asigno variables
data['GLDASNOAH+CMORPH+ERA5']['pre'][''] = data['CMORPH']['pre']['']
data['GLDASNOAH+CMORPH+ERA5']['sm1'][''] = data['GLDASNOAH']['sm1'][''].where(data['CMORPH']['pre'][''][0]+1) # el where es porque la reticula de CMORPH es la mas chica
#data['GLDASNOAH+CMORPH+ERA5']['evapot'][''] = data['GLDASNOAH']['evapot']['']
for var in ['vimfc2d', 'orog', 'lsmask']:
data['GLDASNOAH+CMORPH+ERA5'][var][''] = data['ERA5'][var][''].rename({'longitude':'lon', 'latitude':'lat'}).where(data['CMORPH']['pre'][''][0]+1)
lat['GLDASNOAH+CMORPH+ERA5'] = data['GLDASNOAH+CMORPH+ERA5'][var]['']['lat']
lon['GLDASNOAH+CMORPH+ERA5'] = data['GLDASNOAH+CMORPH+ERA5'][var]['']['lon']
lonproj['GLDASNOAH+CMORPH+ERA5'], latproj['GLDASNOAH+CMORPH+ERA5'] = np.meshgrid(lon['GLDASNOAH+CMORPH+ERA5'], lat['GLDASNOAH+CMORPH+ERA5'])
models = {'GLDASNOAH+CMORPH+ERA5': "GLDASNOAH+CMORPH+ERA5 "+start_date[0:4]+"-"+end_date[0:4]}
else:
# creo diccionario
data['GLDASNOAH+ERA5'] = dict()
for var in var_list:
data['GLDASNOAH+ERA5'][var] = dict()
# Muevo las lon/lat para que coincidan
data['GLDASNOAH']['sm1'][''].coords['lat'] = data['GLDASNOAH']['sm1']['']['lat']-0.125
data['GLDASNOAH']['pre'][''].coords['lat'] = data['GLDASNOAH']['pre']['']['lat']-0.125
# asigno variables
data['GLDASNOAH+ERA5']['pre'][''] = data['GLDASNOAH']['pre']['']
data['GLDASNOAH+ERA5']['sm1'][''] = data['GLDASNOAH']['sm1']['']
#data['GLDASNOAH+CMORPH+ERA5']['evapot'][''] = data['GLDASNOAH']['evapot']['']
for var in ['vimfc2d', 'orog', 'lsmask']:
data['GLDASNOAH+ERA5'][var][''] = data['ERA5'][var][''].rename({'longitude':'lon', 'latitude':'lat'}).where(data['GLDASNOAH']['pre'][''][0]+1) # el where es porque la reticula de CMORPH es la mas chica
lat['GLDASNOAH+ERA5'] = data['GLDASNOAH+ERA5'][var]['']['lat']
lon['GLDASNOAH+ERA5'] = data['GLDASNOAH+ERA5'][var]['']['lon']
lonproj['GLDASNOAH+ERA5'], latproj['GLDASNOAH+ERA5'] = np.meshgrid(lon['GLDASNOAH+ERA5'], lat['GLDASNOAH+ERA5'])
models = {'GLDASNOAH+ERA5': "GLDASNOAH+ERA5 "+start_date[0:4]+"-"+end_date[0:4]}
#%% --------- FILTRO LOS PUNTOS CON OROGRAFIA EMPINADA --------
print('######### Filtrando puntos de orografía empinada y enmascarando oceanos ##############')
mask = dict()
for model in models.keys():
print('.... '+model+' ......')
init_time = timeit.time.time()
lat_name = [coord for coord in set(data[model]['orog'][''].coords.keys()) if "lat" in coord][0]
lon_name = [coord for coord in set(data[model]['orog'][''].coords.keys()) if "lon" in coord][0]
orog_shifted = xr.concat([data[model]['orog'][''][0].shift({lat_name:ii, lon_name:jj})*mult_hd['orog'][model][0] for ii,jj in list(itertools.product(range(-box_size2[0],box_size2[0]+1), repeat=2))], dim='shifted').compute()
orog_shifted_max = orog_shifted.max(dim='shifted')
orog_shifted_min = orog_shifted.min(dim='shifted')
mask[model] = ( ((orog_shifted_max - orog_shifted_min)<delta_orog_lim).values * (data[model]['lsmask'][''][0] >0) ).compute()
print(str(round((timeit.time.time()-init_time)/60,2))+' min')
#orog_ocean_mask = np.rollaxis(np.dstack([mask]*sm_RCA_CTL_daily_rm.shape[0]), axis=2)
#%% ------- ###### Cargar datos ya calculados #########
data_mor = dict() #datos diarios de mañana
data_aft = dict() #datos diarios de tarde
data_day = dict() #datos diarios de vimfc2d
ys_e = dict()
yt_e = dict()
yh_e = dict()
ys_event_types = dict()
ys_c = dict()
yt_c = dict()
yh_c = dict()
delta_e_ys = dict()
delta_e_yt = dict()
delta_e_yh = dict()
delta_ys = dict()
delta_yt = dict()
delta_yh = dict()
delta_e_ys_dynreg = dict()
delta_e_yt_dynreg = dict()
delta_e_yh_dynreg = dict()
delta_ys_dynreg = dict()
delta_yt_dynreg = dict()
delta_yh_dynreg = dict()
if degrade:
delta_e_ys_dg = dict()
delta_e_yt_dg = dict()
delta_e_yh_dg = dict()
delta_ys_dg = dict()
delta_yt_dg = dict()
delta_yh_dg = dict()
delta_e_ys_dg_dynreg = dict()
delta_e_yt_dg_dynreg = dict()
delta_e_yh_dg_dynreg = dict()
delta_ys_dg_dynreg = dict()
delta_yt_dg_dynreg = dict()
delta_yh_dg_dynreg = dict()
for model in models.keys():
if reload:
print('cargando datos ya calculados')
try:
timename='time'
if model=='JRA-55': timename='initial_time0_hours'
data_mor[model] = dict() #datos diarios de mañana
data_aft[model] = dict() #datos diarios de tarde
data_day[model] = dict()
data_mor[model]['pre'] = xr.open_dataarray(temp_path+'/pre_mor_'+model+'.nc')
data_aft[model]['pre'] = xr.open_dataarray(temp_path+'/pre_aft_'+model+'.nc')
data_mor[model]['sm1'] = xr.open_dataarray(temp_path+'/sm1_mor_'+model+'.nc')
data_day[model]['vimfc2d'] = xr.open_dataarray(temp_path+'/vimfc2d_day_'+model+'.nc')
ys_e[model] = xr.open_dataarray(temp_path+'/ys_e_'+model+'.nc', chunks={timename:-1})
yt_e[model] = xr.open_dataarray(temp_path+'/yt_e_'+model+'.nc', chunks={timename:-1})
yh_e[model] = xr.open_dataarray(temp_path+'/yh_e_'+model+'.nc', chunks={timename:-1})
ys_event_types[model] = np.load(temp_path+'/ys_event_types_'+model+'.nc.npy', allow_pickle=True)
ys_c[model] = xr.open_dataarray(temp_path+'/ys_c_'+model+'.nc', chunks={timename:-1})
yt_c[model] = xr.open_dataarray(temp_path+'/yt_c_'+model+'.nc', chunks={timename:-1})
yh_c[model] = xr.open_dataarray(temp_path+'/yh_c_'+model+'.nc', chunks={timename:-1})
if load_deltas:
if degrade:
delta_e_ys_dg[model] = xr.open_dataarray(temp_path+'/delta_e_ys_'+model+'_'+delta_period[0]+'-'+delta_period[1]+'_dg'+str(degrade_n)+'.nc')
delta_e_yt_dg[model] = xr.open_dataarray(temp_path+'/delta_e_yt_'+model+'_'+delta_period[0]+'-'+delta_period[1]+'_dg'+str(degrade_n)+'.nc')
delta_e_yh_dg[model] = xr.open_dataarray(temp_path+'/delta_e_yh_'+model+'_'+delta_period[0]+'-'+delta_period[1]+'_dg'+str(degrade_n)+'.nc')
delta_ys_dg[model] = xr.open_dataarray(temp_path+'/delta_ys_'+model+'_'+delta_period[0]+'-'+delta_period[1]+'_dg'+str(degrade_n)+'.nc')
delta_yt_dg[model] = xr.open_dataarray(temp_path+'/delta_yt_'+model+'_'+delta_period[0]+'-'+delta_period[1]+'_dg'+str(degrade_n)+'.nc')
delta_yh_dg[model] = xr.open_dataarray(temp_path+'/delta_yh_'+model+'_'+delta_period[0]+'-'+delta_period[1]+'_dg'+str(degrade_n)+'.nc')
delta_e_ys_dg_dynreg[model] = dict()
delta_e_yt_dg_dynreg[model] = dict()
delta_e_yh_dg_dynreg[model] = dict()
delta_ys_dg_dynreg[model] = dict()
delta_yt_dg_dynreg[model] = dict()
delta_yh_dg_dynreg[model] = dict()
for dr in ['low', 'mid', 'high']:
delta_e_ys_dg_dynreg[model][dr] = xr.open_dataarray(temp_path+'/delta_e_ys_dynreg_'+model+'_'+delta_period[0]+'-'+delta_period[1]+'_dg'+str(degrade_n)+'_'+dr+'.nc')
delta_e_yt_dg_dynreg[model][dr] = xr.open_dataarray(temp_path+'/delta_e_yt_dynreg_'+model+'_'+delta_period[0]+'-'+delta_period[1]+'_dg'+str(degrade_n)+'_'+dr+'.nc')
delta_e_yh_dg_dynreg[model][dr] = xr.open_dataarray(temp_path+'/delta_e_yh_dynreg_'+model+'_'+delta_period[0]+'-'+delta_period[1]+'_dg'+str(degrade_n)+'_'+dr+'.nc')
delta_ys_dg_dynreg[model][dr] = xr.open_dataarray(temp_path+'/delta_ys_dynreg_'+model+'_'+delta_period[0]+'-'+delta_period[1]+'_dg'+str(degrade_n)+'_'+dr+'.nc')
delta_yt_dg_dynreg[model][dr] = xr.open_dataarray(temp_path+'/delta_yt_dynreg_'+model+'_'+delta_period[0]+'-'+delta_period[1]+'_dg'+str(degrade_n)+'_'+dr+'.nc')
delta_yh_dg_dynreg[model][dr] = xr.open_dataarray(temp_path+'/delta_yh_dynreg_'+model+'_'+delta_period[0]+'-'+delta_period[1]+'_dg'+str(degrade_n)+'_'+dr+'.nc')
else:
delta_e_ys[model] = xr.open_dataarray(temp_path+'/delta_e_ys_'+model+'_'+delta_period[0]+'-'+delta_period[1]+'.nc')
delta_e_yt[model] = xr.open_dataarray(temp_path+'/delta_e_yt_'+model+'_'+delta_period[0]+'-'+delta_period[1]+'.nc')
delta_e_yh[model] = xr.open_dataarray(temp_path+'/delta_e_yh_'+model+'_'+delta_period[0]+'-'+delta_period[1]+'.nc')
delta_ys[model] = xr.open_dataarray(temp_path+'/delta_ys_'+model+'_'+delta_period[0]+'-'+delta_period[1]+'.nc')
delta_yt[model] = xr.open_dataarray(temp_path+'/delta_yt_'+model+'_'+delta_period[0]+'-'+delta_period[1]+'.nc')
delta_yh[model] = xr.open_dataarray(temp_path+'/delta_yh_'+model+'_'+delta_period[0]+'-'+delta_period[1]+'.nc')
delta_e_ys_dynreg[model] = dict()
delta_e_yt_dynreg[model] = dict()
delta_e_yh_dynreg[model] = dict()
delta_ys_dynreg[model] = dict()
delta_yt_dynreg[model] = dict()
delta_yh_dynreg[model] = dict()
for dr in ['low', 'mid', 'high']:
delta_e_ys_dynreg[model][dr] = xr.open_dataarray(temp_path+'/delta_e_ys_dynreg_'+model+'_'+delta_period[0]+'-'+delta_period[1]+'_'+dr+'.nc')
delta_e_yt_dynreg[model][dr] = xr.open_dataarray(temp_path+'/delta_e_yt_dynreg_'+model+'_'+delta_period[0]+'-'+delta_period[1]+'_'+dr+'.nc')
delta_e_yh_dynreg[model][dr] = xr.open_dataarray(temp_path+'/delta_e_yh_dynreg_'+model+'_'+delta_period[0]+'-'+delta_period[1]+'_'+dr+'.nc')
delta_ys_dynreg[model][dr] = xr.open_dataarray(temp_path+'/delta_ys_dynreg_'+model+'_'+delta_period[0]+'-'+delta_period[1]+'_'+dr+'.nc')
delta_yt_dynreg[model][dr] = xr.open_dataarray(temp_path+'/delta_yt_dynreg_'+model+'_'+delta_period[0]+'-'+delta_period[1]+'_'+dr+'.nc')
delta_yh_dynreg[model][dr] = xr.open_dataarray(temp_path+'/delta_yh_dynreg_'+model+'_'+delta_period[0]+'-'+delta_period[1]+'_'+dr+'.nc')
except:
print('algo salio mal cargando los datos ya calculados')
#%% ------- CALCULOS -----------
data_mor = dict() #datos diarios de mañana
data_aft = dict() #datos diarios de tarde
sm_daily = dict()
sm_daily_rm = dict()
sm_daily_doy = dict()
data_day = dict() #datos diarios para vimfc2d
# defino funciones para seleccionar mañana y tarde
def pre_morning(hour):
return (hour >= rango_pre_mor[0]) & (hour <= rango_pre_mor[1])
def pre_afternoon(hour):
return (hour >= rango_pre_aft[0]) & (hour <= rango_pre_aft[1])
def sm_morning(hour):
return (hour >= rango_sm[0]) & (hour <= rango_sm[1])
# ESTO SOLO PARA CASOS DONDE LOS DATASET DE P Y SM SON DE DISTINTA FUENTE Y QUIERO CHEQUEAR QUE COINCIDE LA P CON UN AUMENTO DE SM
def sm_afternoon(hour):
return (hour >= rango_pre_aft[1]-3) & (hour <= rango_pre_aft[1])
sm_daily_aft = dict()
sm_increase = dict()
print('########## CALCULANDO ##############')
for model in models.keys():
print('..... '+model+' ....')
data_mor[model] = dict()
data_aft[model] = dict()
data_day[model] = dict()
timename='time'
if model=='JRA-55': timename='initial_time0_hours'
lon_name = [coord for coord in set(data[model][var_list[0]][''].coords.keys()) if "lon" in coord][0]
# LIMITES DE LAS TIMEZONES #########################################
timezones = [5,4,3,2] # A MEJORAR: SE PODRIA AGREGAR EL NEGATIVO DENTRO DE ESTA VARIABLE (son franjas -3, -4, etc)
zonelimits = np.array([float(lon[model][0]), -67.5-0.24, -52.5-0.24, -37.5-0.24, float(lon[model][-1])])
pre_mor = dict() #diccionario temporal para guardar calculos por franjas horarias
pre_aft = dict()
sm_mor = dict()
vimfc2d_day = dict()
sm_aft = dict()
# creo datos diarios sumando/promediando las horas de interés para cada caso
print('calculando por franjas horarias')
init_time = timeit.time.time()
for nn,zone in enumerate(timezones):
print(str(nn+1)+'/'+str(len(timezones)))
# muevo el tiempo de vimfc2d a LST , hago las cuentas y los vuelvo a sus tiempos originales
data[model]['pre'][''].coords[timename] = data[model]['pre'][''][timename] - zone*3600000000000
data[model]['sm1'][''].coords[timename] = data[model]['sm1'][''][timename] - zone*3600000000000
pre_mor[zone] = data[model]['pre'][''].loc[{timename:slice(start_date, end_date)}].loc[{timename:pre_morning(data[model]['pre'][''].loc[{timename:slice(start_date, end_date)}][timename+'.hour']), lon_name:slice(zonelimits[nn],zonelimits[nn+1])}].resample({timename:'D'}).sum().compute()
pre_aft[zone] = data[model]['pre'][''].loc[{timename:slice(start_date, end_date)}].loc[{timename:pre_afternoon(data[model]['pre'][''].loc[{timename:slice(start_date, end_date)}][timename+'.hour']), lon_name:slice(zonelimits[nn],zonelimits[nn+1])}].resample({timename:'D'}).sum().compute()
if 'GLEAM' not in model:
sm_mor[zone] = data[model]['sm1'][''].loc[{timename:slice(start_date, end_date)}].loc[{timename:sm_morning(data[model]['sm1'][''].loc[{timename:slice(start_date, end_date)}][timename+'.hour']), lon_name:slice(zonelimits[nn],zonelimits[nn+1])}].resample({timename:'D'}).mean().compute()
if test_increase_sm:
sm_aft[zone] = data[model]['sm1'][''].loc[{timename:slice(start_date, end_date)}].loc[{timename:sm_afternoon(data[model]['sm1'][''].loc[{timename:slice(start_date, end_date)}][timename+'.hour']), lon_name:slice(zonelimits[nn],zonelimits[nn+1])}].resample({timename:'D'}).mean().compute()
data[model]['pre'][''].coords[timename] = data[model]['pre'][''][timename] + zone*3600000000000
data[model]['sm1'][''].coords[timename] = data[model]['sm1'][''][timename] + zone*3600000000000
# muevo el tiempo de vimfc2d a LST , hago la cuenta y lo vuelvo a su tiempo original
data[model]['vimfc2d'][''].coords[timename] = data[model]['vimfc2d'][''][timename] - zone*3600000000000
vimfc2d_day[zone] = data[model]['vimfc2d'][''].loc[{timename: slice(start_date,end_date), lon_name:slice(zonelimits[nn],zonelimits[nn+1])}].resample({timename:'D'}).mean().compute()*mult_hd['vimfc2d'][model][0]
data[model]['vimfc2d'][''].coords[timename] = data[model]['vimfc2d'][''][timename] + zone*3600000000000
print(str(round((timeit.time.time()-init_time)/60,2))+' min')
# calculo la rolling mean de SM
print('calculando rolling mean diario de SM')
init_time = timeit.time.time()
if 'GLEAM' in model:
sm_daily[model] = data[model]['sm1']['']
if dayofyear_smanom:
sm_daily_doy[model] = sm_daily[model].groupby(timename+'.dayofyear').mean(dim=timename, skipna=True).compute()
else:
sm_daily_rm[model] = sm_daily[model].rolling({timename:n_rollmean}, center=sm_roll_mean_center, min_periods=15).mean().compute()
else:
# muevo el tiempo de sm1 a LST (aprox)
# data[model]['sm1'][''].coords[timename] = data[model]['sm1'][''][timename] - 4*3600000000000
# sm_daily[model] = data[model]['sm1'][''].resample({timename:'D'}).mean().compute()
# data[model]['sm1'][''].coords[timename] = data[model]['sm1'][''][timename] + 4*3600000000000
sm_daily[model] = xr.concat([sm_mor[i] for i in timezones], dim=lon_name)
if test_increase_sm:
sm_daily_aft[model] = xr.concat([sm_aft[i] for i in timezones], dim=lon_name)
if len(sm_daily_aft[model]) < len(sm_daily[model]): sm_daily_aft[model] = xr.concat([sm_daily_aft[model], sm_daily[model][-(len(sm_daily[model]) - len(sm_daily_aft[model])):]], dim='time')
sm_increase[model] = sm_daily_aft[model] > sm_daily[model]
if dayofyear_smanom:
sm_daily_doy[model] = sm_daily[model].groupby(timename+'.dayofyear').mean(dim=timename, skipna=True)
elif seas_expect_smanom:
aux = sm_daily[model].rolling({timename:n_rollmean}, center=sm_roll_mean_center, min_periods=15).mean()
sm_daily_rm[model] = aux.groupby(timename+'.dayofyear').mean(dim=timename, skipna=True) - (aux/((int(end_date[0:4])-int(start_date[0:4]))+1)).groupby(timename+'.dayofyear')
else:
sm_daily_rm[model] = sm_daily[model].rolling({timename:n_rollmean}, center=sm_roll_mean_center, min_periods=15).mean()
print(str(round((timeit.time.time()-init_time)/60,2))+' min')
#junto los resultados por timezones en un solo array
print('concatenando y guardando arrays')
if not os.path.exists(temp_path):
os.makedirs(temp_path)
data_mor[model]['pre'] = xr.concat([pre_mor[i] for i in timezones], dim=lon_name)
data_mor[model]['pre'].to_netcdf(temp_path+'/pre_mor_'+model+'.nc')
data_mor[model]['pre'] = xr.open_dataarray(temp_path+'/pre_mor_'+model+'.nc')
data_aft[model]['pre'] = xr.concat([pre_aft[i] for i in timezones], dim=lon_name)
data_aft[model]['pre'].to_netcdf(temp_path+'/pre_aft_'+model+'.nc')
data_aft[model]['pre'] = xr.open_dataarray(temp_path+'/pre_aft_'+model+'.nc')
if 'GLEAM' in model or previous_day_sm:
if dayofyear_smanom:
data_mor[model]['sm1'] = (sm_daily[model].groupby(timename+'.dayofyear')-sm_daily_doy[model]).roll(time=1, roll_coords=False)
else:
data_mor[model]['sm1'] = (sm_daily[model] - sm_daily_rm[model]).roll(time=1, roll_coords=False)
data_mor[model]['sm1'].to_netcdf(temp_path+'/sm1_mor_'+model+'.nc')
data_mor[model]['sm1'] = xr.open_dataarray(temp_path+'/sm1_mor_'+model+'.nc')
else:
if dayofyear_smanom:
#data_mor[model]['sm1'] = xr.concat([sm_mor[i] for i in timezones], dim=lon_name).groupby(timename+'.dayofyear') - sm_daily_doy[model]
data_mor[model]['sm1'] = (sm_daily[model].groupby(timename+'.dayofyear') - sm_daily_doy[model]).round(7) #round is added to removes imprecise residuals in CLIM
else:
# data_mor[model]['sm1'] = xr.concat([sm_mor[i] for i in timezones], dim=lon_name) - sm_daily_rm[model]
data_mor[model]['sm1'] = (sm_daily[model] - sm_daily_rm[model]).round(7) #round is added to removes imprecise residuals in CLIM
data_mor[model]['sm1'].to_netcdf(temp_path+'/sm1_mor_'+model+'.nc')
data_mor[model]['sm1'] = xr.open_dataarray(temp_path+'/sm1_mor_'+model+'.nc')
data_day[model]['vimfc2d'] = xr.concat([vimfc2d_day[i] for i in timezones], dim=lon_name)
data_day[model]['vimfc2d'].to_netcdf(temp_path+'/vimfc2d_day_'+model+'.nc')
data_day[model]['vimfc2d'] = xr.open_dataarray(temp_path+'/vimfc2d_day_'+model+'.nc')
if test_increase_sm:
sm_increase[model].to_netcdf(temp_path+'/sm_increase_'+model+'.nc')
sm_increase[model] = xr.open_dataarray(temp_path+'/sm_increase_'+model+'.nc')
#%% ---------- IDENTIFICO LOS EVENTOS Y CALCULO LAS METRICAS ------------------
ys_e = dict()
yt_e = dict()
yh_e = dict()
ys_event_types = dict()
pre_cond_event = dict()
print('Identifying event days')
for model in models.keys():
print('..... '+model+' ....')
print('Processing conditions')
init_time = timeit.time.time()
timename='time'
if model=='JRA-55': timename='initial_time0_hours'
lat_name = [coord for coord in set(data[model][var_list[0]][''].coords.keys()) if "lat" in coord][0]
lon_name = [coord for coord in set(data[model][var_list[0]][''].coords.keys()) if "lon" in coord][0]
# condicion de que el máximo esté en el pixel central
iteration = list(itertools.product(range(-box_size2[0],box_size2[0]+1), repeat=2))
iteration.remove((0,0))
pre_cond1 = math.prod([data_aft[model]['pre'].shift({lat_name:ii, lon_name:jj})<data_aft[model]['pre'] for ii,jj in iteration])
# condicion de no precip por la mañana en ningun punto de la caja (<pre_mor_max)
pre_cond11 = math.prod([data_mor[model]['pre'].shift({lat_name:ii, lon_name:jj})<pre_mor_max for ii,jj in list(itertools.product(range(-box_size2[0],box_size2[0]+1), repeat=2))])
# condicion de no precip por la mañana y precip por la tarde mayor a cierto umbral
pre_cond2 = (data_mor[model]['pre'] < pre_mor_max)*(data_aft[model]['pre'] > pre_aft_min)
# junto las condiciones
pre_cond_event[model] = (pre_cond1 * pre_cond11 * pre_cond2)
if test_increase_sm:
pre_cond_event[model] = pre_cond1 * pre_cond11 * pre_cond2 * sm_increase[model]
print(str(round((timeit.time.time()-init_time)/60,2))+' min')
# Calculo Ys_e: métrica de preferencia espacial e Yh_e: métrica de heterogeneidad
# (está contemplado que si hay dos mínimos de prec en un dia evento, la resta Ys_e es entre el
# punto del maximo (central) y la media de los valores en las posiciones de los minimos)
print('Computing Ys_e & Yh_e')
init_time = timeit.time.time()
if ys_calculation_type == 'min':
def calculo_ys_yh(sm_array, pre_cond_event, pre_aft):
ys_e = np.empty(sm_array.shape); ys_e.fill(np.nan)
yh_e = np.empty(sm_array.shape); yh_e.fill(np.nan)
ys_event_types = np.empty(sm_array.shape, dtype=object)
for i,j in zip(np.where(mask[model]==True)[0], np.where(mask[model]==True)[1]):
if pre_cond_event[i,j]:
min_pos = np.where(pre_aft[(i-box_size2[0]):(i+box_size2[0]+1), (j-box_size2[1]):(j+box_size2[1]+1)] == pre_aft[(i-box_size2[0]):(i+box_size2[0]+1), (j-box_size2[1]):(j+box_size2[1]+1)].min())
ys_e[i, j] = float(sm_array[i,j] - np.mean([sm_array[i-box_size2[0]+ii, j-box_size2[1]+jj] for ii,jj in list(zip(min_pos[0], min_pos[1]))]))
ys_event_types[i,j] = (set(zip(min_pos[0],min_pos[1])))
yh_e[i,j] = float(np.std(sm_array[(i-box_size2[0]):(i+box_size2[0]+1), (j-box_size2[1]):(j+box_size2[1]+1)]))
return ys_e, yh_e, ys_event_types
elif ys_calculation_type == 'mean':
def calculo_ys_yh(sm_array, pre_cond_event, pre_aft):
ys_e = np.empty(sm_array.shape); ys_e.fill(np.nan)
yh_e = np.empty(sm_array.shape); yh_e.fill(np.nan)
ys_event_types = np.empty(sm_array.shape, dtype=object)
for i,j in zip(np.where(mask[model]==True)[0], np.where(mask[model]==True)[1]):
if pre_cond_event[i,j]:
ys_e[i, j] = float(sm_array[i,j] - np.mean(sm_array[(i-box_size2[0]):(i+box_size2[0]+1), (j-box_size2[1]):(j+box_size2[1]+1)][np.where(sm_array[(i-box_size2[0]):(i+box_size2[0]+1), (j-box_size2[1]):(j+box_size2[1]+1)]!=sm_array[i, j])]))
ys_event_types[i,j] = np.nan
yh_e[i,j] = float(np.std(sm_array[(i-box_size2[0]):(i+box_size2[0]+1), (j-box_size2[1]):(j+box_size2[1]+1)]))
return ys_e, yh_e, ys_event_types
else:
print('Calculation type for Ys not recognized, aborting...')
from sys import exit
exit()
def wrap():
ys_e[model], yh_e[model], aux_events = xr.apply_ufunc(calculo_ys_yh, data_mor[model]['sm1'], pre_cond_event[model], data_aft[model]['pre'],
input_core_dims=[[lat_name, lon_name], [lat_name, lon_name], [lat_name, lon_name]],
output_core_dims=[[lat_name, lon_name], [lat_name, lon_name], [lat_name, lon_name]],
vectorize=True, dask='parallelized',
dask_gufunc_kwargs={'allow_rechunk':True})
ds_out = ys_e[model].to_dataset(name='ys_e')
ds_out['yh_e'] = yh_e[model]
ds_out['aux_events'] = aux_events
return ds_out
ds_out = wrap().compute()
ys_e[model] = ds_out['ys_e']
yh_e[model] = ds_out['yh_e']
aux_events = ds_out['aux_events']
def reduce_set_events(point):
try:
return set.union(*np.asarray(point[point != np.array(None)]))
except:
return {}
ys_event_types[model] = xr.apply_ufunc(reduce_set_events, aux_events, input_core_dims=[[timename]], output_core_dims=[[]], vectorize=True, dask='parallelized',
dask_gufunc_kwargs={'allow_rechunk':True})
print(str(round((timeit.time.time()-init_time)/60,2))+' min')
# Calculo Yt_e: métrica de preferencia temporal
print('Computing Yt_e')
init_time = timeit.time.time()
yt_e_condition_mask = (pre_cond_event[model]==1)*mask[model]
yt_e[model] = data_mor[model]['sm1'].where(yt_e_condition_mask)
print(str(round((timeit.time.time()-init_time)/60,2))+' min')
# Guardo los resultados:
print('Saving arrays in temp')
ys_e[model].to_netcdf(temp_path+'/ys_e_'+model+'.nc')
yt_e[model].to_netcdf(temp_path+'/yt_e_'+model+'.nc')
yh_e[model].to_netcdf(temp_path+'/yh_e_'+model+'.nc')
np.save(temp_path+'/ys_event_types_'+model+'.nc', ys_event_types[model])
print('reloading results')
ys_e[model] = xr.open_dataarray(temp_path+'/ys_e_'+model+'.nc', chunks={timename:-1})
yt_e[model] = xr.open_dataarray(temp_path+'/yt_e_'+model+'.nc', chunks={timename:-1})
yh_e[model] = xr.open_dataarray(temp_path+'/yh_e_'+model+'.nc', chunks={timename:-1})
ys_event_types[model] = np.load(temp_path+'/ys_event_types_'+model+'.nc.npy', allow_pickle=True) # el pickle no es forward compatible, cambiar
#%% ---------- IDENTIFICO LOS NO EVENTOS Y CALCULO LAS METRICAS ------------------
# Creo los arrays vacios para guardar los datos
event_type = [(0,1), (0,2), (1,2), (2,2), (2,1), (2,0), (1,0), (0,0)] # tipo de evento segun la posicion del minimo
ys_c = dict()
yt_c = dict()
yh_c = dict()
print('Identifying non event days')
for model in models.keys():
print('..... '+model+' ....')
timename='time'
if model=='JRA-55': timename='initial_time0_hours'
lat_name = [coord for coord in set(data[model][var_list[0]][''].coords.keys()) if "lat" in coord][0]
lon_name = [coord for coord in set(data[model][var_list[0]][''].coords.keys()) if "lon" in coord][0]
# condición de no evento: no tiene que haber evento ni precipitacion por la mañana
pre_cond3 = data_mor[model]['pre'] < pre_mor_max
pre_cond_nonevent = (~(pre_cond_event[model]==True))*pre_cond3
# Calculo Ys_e: métrica de preferencia espacial e Yh_e: métrica de heterogeneidad
# (está contemplado que si hay dos mínimos de prec en un dia evento, la resta Ys_e es entre el
# punto del maximo (central) y la media de los valores en las posiciones de los minimos)
print('Computing Ys_c, Yh_c & Yt_c')
if ys_calculation_type == 'min':
def calculo_no_events(data_mor, pre_cond_nonevent):
event_type = [(0,1), (0,2), (1,2), (2,2), (2,1), (2,0), (1,0), (0,0)] # tipo de evento segun la posicion del minimo
ys_c = np.empty((len(event_type),
pre_cond_nonevent.shape[0],
pre_cond_nonevent.shape[1])); ys_c.fill(np.nan)
yt_c = np.empty(pre_cond_nonevent.shape); yt_c.fill(np.nan)
yh_c = np.empty(pre_cond_nonevent.shape); yh_c.fill(np.nan)
for i,j in zip(np.where(mask[model]==True)[0], np.where(mask[model]==True)[1]):
ev_number=0
if pre_cond_nonevent[(i-box_size2[0]):(i+box_size2[0]+1), (j-box_size2[1]):(j+box_size2[1]+1)].all() and i>box_size2[0]-1 and j>box_size2[1]-1 and i<mask[model].shape[0]-(box_size2[0]-1) and j<mask[model].shape[1]-(box_size2[1]-1):
for ev_type in ys_event_types[model][i,j]:
ys_c[ev_number,i,j] = np.asarray(data_mor[i,j] - data_mor[i-box_size2[0]+ev_type[0], j-box_size2[1]+ev_type[1]])
ev_number = ev_number+1
yh_c[i,j] = np.asarray(np.std(data_mor[(i-box_size2[0]):(i+box_size2[0]+1), (j-box_size2[1]):(j+box_size2[1]+1)]) )
yt_c[i,j] = np.asarray(data_mor[i,j])
return ys_c, yh_c, yt_c
elif ys_calculation_type == 'mean':
def calculo_no_events(data_mor, pre_cond_nonevent):
ys_c = np.empty((1,
pre_cond_nonevent.shape[0],
pre_cond_nonevent.shape[1])); ys_c.fill(np.nan)
yt_c = np.empty(pre_cond_nonevent.shape); yt_c.fill(np.nan)
yh_c = np.empty(pre_cond_nonevent.shape); yh_c.fill(np.nan)
for i,j in zip(np.where(mask[model]==True)[0], np.where(mask[model]==True)[1]):
if pre_cond_nonevent[(i-box_size2[0]):(i+box_size2[0]+1), (j-box_size2[1]):(j+box_size2[1]+1)].all() and i>box_size2[0]-1 and j>box_size2[1]-1 and i<mask[model].shape[0]-(box_size2[0]-1) and j<mask[model].shape[1]-(box_size2[1]-1):
ys_c[0,i,j] = np.asarray(data_mor[i,j] - np.mean(data_mor[(i-box_size2[0]):(i+box_size2[0]+1), (j-box_size2[1]):(j+box_size2[1]+1)][np.where(data_mor[(i-box_size2[0]):(i+box_size2[0]+1), (j-box_size2[1]):(j+box_size2[1]+1)]!=data_mor[i, j])]))
yh_c[i,j] = np.asarray(np.std(data_mor[(i-box_size2[0]):(i+box_size2[0]+1), (j-box_size2[1]):(j+box_size2[1]+1)]) )
yt_c[i,j] = np.asarray(data_mor[i,j])
return ys_c, yh_c, yt_c
else:
print('Calculation type for Ys not recognized, aborting...')
from sys import exit
exit()
def wrap():
ys_c[model], yh_c[model], yt_c[model] = xr.apply_ufunc(calculo_no_events, data_mor[model]['sm1'], pre_cond_nonevent,
input_core_dims=[[lat_name, lon_name], [lat_name, lon_name]],
output_core_dims=[['evtypes',lat_name, lon_name], [lat_name, lon_name], [lat_name, lon_name]],
vectorize=True, dask='parallelized', dask_gufunc_kwargs={'allow_rechunk':True})
ds_out = ys_c[model].to_dataset(name='ys_c')
ds_out['yh_c'] = yh_c[model]
ds_out['yt_c'] = yt_c[model]
return ds_out
init_time = timeit.time.time()
ds_out = wrap().compute()
ys_c[model] = ds_out['ys_c']
yt_c[model] = ds_out['yt_c']
yh_c[model] = ds_out['yh_c']
print(str(round((timeit.time.time()-init_time)/60,2))+' min')
# Guardo los resultados:
print('Saving arrays in temp')
ys_c[model].to_netcdf(temp_path+'/ys_c_'+model+'.nc')
yt_c[model].to_netcdf(temp_path+'/yt_c_'+model+'.nc')
yh_c[model].to_netcdf(temp_path+'/yh_c_'+model+'.nc')
print('reloading results')
ys_c[model] = xr.open_dataarray(temp_path+'/ys_c_'+model+'.nc', chunks={timename:-1})
yt_c[model] = xr.open_dataarray(temp_path+'/yt_c_'+model+'.nc', chunks={timename:-1})
yh_c[model] = xr.open_dataarray(temp_path+'/yh_c_'+model+'.nc', chunks={timename:-1})
#%% -------------------- RECORTO LA ESTACIÓN DESEADA --------
ys_e_cut = dict()
yt_e_cut = dict()
yh_e_cut = dict()
ys_c_cut = dict()
yt_c_cut = dict()
yh_c_cut = dict()
data_day_cut = dict()
for model in models.keys():
timename='time'
if model=='JRA-55': timename='initial_time0_hours'
daily_time_months = np.asarray(ys_e[model][timename+'.month'])
if seas_name == 'Yearly':
ys_e_cut[model] = ys_e[model].loc[{timename:slice(delta_period[0], delta_period[1])}]
yt_e_cut[model] = yt_e[model].loc[{timename:slice(delta_period[0], delta_period[1])}]
yh_e_cut[model] = yh_e[model].loc[{timename:slice(delta_period[0], delta_period[1])}]
ys_c_cut[model] = ys_c[model].loc[{timename:slice(delta_period[0], delta_period[1])}]
yt_c_cut[model] = yt_c[model].loc[{timename:slice(delta_period[0], delta_period[1])}]
yh_c_cut[model] = yh_c[model].loc[{timename:slice(delta_period[0], delta_period[1])}]
data_day_cut[model] = dict()
data_day_cut[model]['vimfc2d'] = data_day[model]['vimfc2d'].loc[{timename:slice(delta_period[0], delta_period[1])}]
else:
def season_sel(month):
return np.asarray([m in seas for m in month])
ys_e_cut[model] = ys_e[model][season_sel(daily_time_months)].loc[{timename:slice(delta_period[0], delta_period[1])}]
yt_e_cut[model] = yt_e[model][season_sel(daily_time_months)].loc[{timename:slice(delta_period[0], delta_period[1])}]
yh_e_cut[model] = yh_e[model][season_sel(daily_time_months)].loc[{timename:slice(delta_period[0], delta_period[1])}]
ys_c_cut[model] = ys_c[model][season_sel(daily_time_months)].loc[{timename:slice(delta_period[0], delta_period[1])}]
yt_c_cut[model] = yt_c[model][season_sel(daily_time_months)].loc[{timename:slice(delta_period[0], delta_period[1])}]
yh_c_cut[model] = yh_c[model][season_sel(daily_time_months)].loc[{timename:slice(delta_period[0], delta_period[1])}]
daily_time_months2 = np.asarray(data_day[model]['vimfc2d'][timename+'.month'])
data_day_cut[model] = dict()
data_day_cut[model]['vimfc2d'] = data_day[model]['vimfc2d'][season_sel(daily_time_months2)].loc[{timename:slice(delta_period[0], delta_period[1])}]
#%% -------------------- CALCULO LOS DELTAS --------
print('Calculando delta_e y delta_c')
print('... sin separar los regimenes dinamicos ...')
delta_e_ys = dict()
delta_e_yt = dict()
delta_e_yh = dict()
delta_ys = dict()
delta_yt = dict()
delta_yh = dict()
if degrade:
ys_e_cut_dg = dict()
yt_e_cut_dg = dict()
yh_e_cut_dg = dict()
ys_c_cut_dg = dict()
yt_c_cut_dg = dict()
yh_c_cut_dg = dict()
delta_e_ys_dg = dict()
delta_e_yt_dg = dict()
delta_e_yh_dg = dict()
delta_ys_dg = dict()
delta_yt_dg = dict()
delta_yh_dg = dict()
for model in models.keys():
print('..... '+model+' ....')
timename='time'
if model=='JRA-55': timename='initial_time0_hours'
lat_name = [coord for coord in set(data[model][var_list[0]][''].coords.keys()) if "lat" in coord][0]
lon_name = [coord for coord in set(data[model][var_list[0]][''].coords.keys()) if "lon" in coord][0]
def bootstrap_resample(X, n=None):
""" Bootstrap resample an array_like
Parameters
----------
X : array_like
data to resample
n : int, optional
length of resampled array, equal to len(X) if n==None
Results
-------
returns X_resamples
"""