-
Notifications
You must be signed in to change notification settings - Fork 1
/
greentrack_tools.py
executable file
·2170 lines (1741 loc) · 66.8 KB
/
greentrack_tools.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 -*-
"""
GREENTRACK TOOLS
A toolbox to analyze multiple-pixel biomass indicators, generate interpolated annual
indicator curves and related statistics.
Created on Mon Nov 13 16:38:50 2023
@author: Fabio Oriani, Agroscope, [email protected]
"""
import numpy as np
import matplotlib.pyplot as plt
from scipy.interpolate import PchipInterpolator
from scipy.optimize import curve_fit
from scipy.interpolate import interp2d
import geopandas as gpd
import os
import re
import rasterio
import shapefile
#from osgeo.gdal import GetDriverByName, GetDataTypeByName
from osgeo import osr
#import geopandas
import json
import requests
from rasterio.warp import reproject, calculate_default_transform
from rasterio.io import MemoryFile
from rasterio.merge import merge
from rasterio.enums import Resampling
from rasterio.transform import from_origin
#from shapefile import Reader
#import matplotlib.path as mplp
#import time
import concurrent.futures
import threading
import zarr
import pandas as pd
from tqdm import tqdm
import multiprocessing
from functools import partial
from multiprocessing import shared_memory
print(
"""
Greentrack Copyright (C) 2024 Fabio Oriani, Agroscope, Swiss Confederation
This program comes with ABSOLUTELY NO WARRANTY under GNU General public
Licence v.3 or later.
Please cite the related publication:
F. Oriani, H. Aasen, M. K. Schneider
Different growth response of mountain rangeland habitats to annual
weather fluctuations, submitted to Alpine Botany.
"""
)
def purge(target_dir, target_pattern):
"""
PURGE remove all pattern-matching files
Parameters
----------
target_dir : str
directory where the function search RECURSIVELY for files
matching target_pattern
target_pattern : str
string searched in filenames, all filenames containing it will be
removed
Returns
-------
None.
"""
for f in os.listdir(target_dir):
if re.search(target_pattern, f):
os.remove(os.path.join(target_dir, f))
def make_grid_vec(shp_path,res,target_crs=None):
"""
MAKE_GRID_VEC
Generate x, y grid vectors for a given polygon shapefile and wanted resolution.
The grid is contained the polygon bounding box and defined in the shapefile crs.
Parameters
----------
shp_fname : str
path to the shapefile (.shp or .gpkg) of the input polygon
res : int
grid resolution compatible with the shapefile crs
target_crs: int
epsg code for the target crs for the output coordinate vectors tx and ty.
Deafult is None. If None the original crs of shp_fname is used.
Returns
-------
tx : 1d array
x coordinate vector of the grid
ty : 1d array
y coordiante vector of the grid
"""
if target_crs!=None:
shp = gpd.read_file(shp_path).to_crs("EPSG:" + str(target_crs))
else:
shp = gpd.read_file(shp_path)
# define pixel-center coordinate contained in the bounding box (+-res/2)
lef = np.min(shp.bounds.minx) + res/2
rig = np.max(shp.bounds.maxx) - res/2
tx = np.arange(lef, rig, res)
bot = np.min(shp.bounds.miny)
top = np.max(shp.bounds.maxy)
if top < bot:
res = -res
bot = bot + res/2
top = top - res/2
ty = np.arange(bot, top, res)
return tx, ty
def scene_to_array(sc,tx,ty,mask=None,no_data=0):
"""
SCENE_TO_ARRAY
Generate an numpy array (image stack) from a given Eodal SceneCollection object.
The scenes are resampled on a costant coordinate grid allowing pixel analysis.
Missing data location are marked as nans.
Parameters
----------
sc : Eodal SceneCollection
The given Scene Collection generated from Eodal
tx : Float Vector
x coordinate vector for the resample grid.
ex. tx = numpy.arange(100,150,10) # x coords from 100 to 150 with 10 resolution
ty : Float Vector
y coordinate vector for the resample grid.
mask : np.array of size [ty,tx]
if given, pixels valued False or 0 are set to no_data in the output grid.
no_data : int or nan
value for missing data in the grid
Returns
-------
im : float 4D numpy array.
Array containing the stack of all scenes.
4 dimensions: [x, y, bands, scenes]
"""
ts = sc.timestamps # time stamps for each image
bands = sc[sc.timestamps[0]].band_names # bands
im_size = [len(ty),len(tx)] # image size
im = np.empty(np.hstack([im_size,len(bands),len(ts)])) # preallocate matrix
for i, scene_iterator in enumerate(sc):
# REGRID SCENE TO BBOX AND TARGET RESOLUTION
scene = scene_iterator[1]
for idx, band_iterator in enumerate(scene):
# extract data with masked ones = 0
band = band_iterator[1]
Gv = np.copy(band.values.data)
Gv[band.values.mask==1]=0
#original grid coordinates
ny,nx = np.shape(Gv)
vx = band.coordinates['x']
vy = band.coordinates['y']
# flip vy vector to increasing values
if vy[0] > vy[-1]:
vy = np.flipud(vy)
# create interpolator
Gv_no_nans = Gv.copy()
Gv_no_nans[np.isnan(Gv)] = 0
f = interp2d(vx,vy,Gv_no_nans,kind='linear',fill_value=no_data)
# interpolate band on the target grid
Tv = f(tx,ty) #Tv = np.flipud(f(tx,ty))
# assign interpolated band [i = scene , b = band]
im[:,:,idx,i] = Tv.copy()
del Tv
# apply mask if given
if mask is not None:
im[np.logical_not(mask),:,:] = no_data
return im
def imrisc(im,qmin=1,qmax=99):
"""
IMRISC
Percentile-based 0-1 rescale for multiband images.
Useful for satellite image visualization.
Parameters
----------
im : Float Array
The image to rescale, can be multiband on the 3rd dimension
qmin : Float Scalar
Percentile to set the bottom of the value range e.g. 0.01
qmax : Float Scalar
Percentile to set the top of the value range e.g. 0.99
Returns
-------Quantile
im_out : Float Array
Rescaled image
EXAMPLE
import matplotlib.pyplot as plt
# with im being an [x,y,[r,g,b]] image
plt.figure()
plt.imshow(imrisc(im))
"""
if len(np.shape(im))==2:
band=im.copy()
band2=band[~np.isnan(band)]
vmin=np.percentile(band2,qmin)
vmax=np.percentile(band2,qmax)
band[band<vmin]=vmin
band[band>vmax]=vmax
band=(band-vmin)/(vmax-vmin)
im_out=band
else:
im_out=im.copy()
for i in range(np.shape(im)[2]):
band=im[:,:,i].copy()
band2=band[~np.isnan(band)]
vmin=np.percentile(band2,qmin)
vmax=np.percentile(band2,qmax)
band[band<vmin]=vmin
band[band>vmax]=vmax
band=(band-vmin)/(vmax-vmin)
im_out[:,:,i]=band
return im_out
def evi(blue,red,nir):
"""
EVI
Calculates the Enhanced Vegetation Index (EVI). from scipy.interpolate import interp2d
Huete et al. (2002) https://doi.org/10.1016/S0034-4257(02)00096-2
Parameters
----------
blue, red, nir : n-d numericals
blue, red, near-infrared band images or values
Returns
-------
im_out : n-d numerical
EVI image or value
"""
numerator = nir - red
denominator = nir + 6 * red - 7.5 * blue + 1
evi = 2.5 * (numerator / denominator)
# threshold values outside [-1,1] (artificial surfaces)
evi[evi > 1.0] = 1.0
evi[evi < -1.0] = -1.0
return evi
def ndvi(red,nir):
"""
NDVI
Calculates the Normalized Difference Vegetation Index (NDVI).
Rouse et al. 1974 https://ntrs.nasa.gov/citations/19740022614
Parameters
----------
red, nir : n-d numericals
blue, red, near-infrared band images or values
Returns
-------
im_out : n-d numerical
NDVI image or value
"""
ndvi = (nir - red) / (nir + red)
return ndvi
def annual_interp(time,data,time_res='doy',lb=0,rb=0,sttt=0,entt=365.25):
"""
ANNUAL CURVE INTERPOLATION
Generates the interpoalted curves for annual data. If more values are present
with the same dates (ex. pixels from the same image), the median is taken.
Parameters
----------
time : vector
any date of time vector the data
data : vector
data vector
time_res : string, optional
wanted time resolution among "doy", "week", and "month". The default is 'doy'.
lb : scalar, optional
left boundary of the interpolated curve at start time. The default is 0,
if lb = 'data' it is set to data[0]
rb : scalar, optional
right boundary of the interpolated curve at start time. The default is 0.
if rb = 'data' it is set to data[-1]
sttt : scalar, optional
starting time for the interpolation. The default is 0.
entt : scalar, optional
ending time for the interpolation. The default is 365.25.
Returns
-------
xv : vector
interpolation time
yv : vector
interpolated values
t_list : vector
time vector of the interpolated data
data : vector
interpolated data (median)
"""
t_list = np.unique(time) # data time line
# if more data are present with the same time, take the median
qm = np.array([],dtype=float)
for t in t_list:
qm = np.hstack((qm,np.nanquantile(data[time==t],0.5)))
# add start/ending 0 boundary conditions
stbt = 0 # zero time in weeks
if time_res == 'doy':
enbt = 366 # end time in doys
#sttt = 0 # start target time (beginning Mar)
#entt = 300 # end target time (end Oct)
dt = 1 # daily granularity for interp
elif time_res == 'week':
enbt = 52.17857 # end time in weeks
sttt = 9 # start target time (beginning Mar)
entt = 44 # end target time (end Oct)
dt = 1/7 # daily granularity for interp
elif time_res == 'month':
enbt = 12
sttt = 3 # start target time (beginning Mar)
entt = 10 # end target time (end Oct)
dt = 1/30 # daily granularity for interp
t_list_tmp = np.hstack([stbt,t_list,enbt])
if lb == 'data':
lb = qm[0]
if rb == 'data':
rb = qm[-1]
data_tmp = np.hstack([lb,qm,rb])
t_list_tmp,ind = np.unique(t_list_tmp, return_index=True)
data_tmp = data_tmp[ind]
# piecewise cubic hermitian interpolator
ph = PchipInterpolator(t_list_tmp,data_tmp,extrapolate=False)
# interpolation on target dates
xv = np.arange(sttt,entt+dt,dt) # daily granularity
yv = ph(xv)
return xv,yv,t_list,qm # target time weeks, target interpolated data, data time, data
def annual_plot(dates,data,dcol,dlabel,time_res = 'doy',envelope=True,lb=0,rb=0,f_range=[-1,1]):
"""
ANNUAL CURVE PLOT
Generates the interpoalted curves for annual data. If more values are present
with the same dates (ex. pixels from the same image), the median is taken.
If envelope = True, the 0.25-0.75 quantile envelope is also plotted.
The interpolated values are also given as output vectors
Parameters
----------
dates : vector
dates or time vector
data : vector
ndvi or similar values to plot
dcol : string
color string for the plotted curve
dlabel : string
legend label for the curve
time_res : string
time resolution among 'month','week', or 'doy'
envelope : boolean, optional
if = True the 0.25-0.75 quantile envelope is computed and plotted.
The default is True.
lb : scalar, optional
left boundary of the interpolated curve at start time.
The default is 0. If lb = 'data' it is set to data[0]
rb : scalar, optional
right boundary of the interpolated curve at start time.
The default is 0. If rb = 'data' it is set to data[-1]
f_range: 2-element vector
range outside which the ndvi median value is considered invalid.
Default is [-1,1], total NDVI range.
Returns
-------
d_listm : vector
time vector for the interpolated values
q2i : vector
interpolated 0.25 quantile values
qmi : vector
interpolated median values
q1i : vector
interpolated median values
"""
d_list = np.unique(dates)
plt.grid(axis='y',linestyle='--')
qm = np.array([],dtype=float)
for d in d_list:
qm = np.hstack((qm,np.nanquantile(data[dates==d],0.5)))
# filter out data with median outside given range
fil = np.logical_and(qm > f_range[0],qm < f_range[1])
d_list = d_list[fil]
qm = qm[fil]
# envelope interpolation
if envelope==True:
q1 = np.array([],dtype=float)
q2 = np.array([],dtype=float)
for d in d_list:
q1 = np.hstack((q1,np.nanquantile(data[dates==d],0.75)))
q2 = np.hstack((q2,np.nanquantile(data[dates==d],0.25)))
d_list1,q1i,*tmp = annual_interp(d_list,q1,time_res=time_res,lb=lb,rb=rb)
d_list2,q2i,*tmp = annual_interp(d_list,q2,time_res=time_res,lb=lb,rb=rb)
q2i_f = np.flip(q2i)
qi = np.hstack((q1i,q2i_f))
d = np.hstack((d_list1,np.flip(d_list1)))
d = d[~np.isnan(qi)]
qi = qi[~np.isnan(qi)]
plt.fill(d,qi,alpha=0.5,c=dcol)
# median interpolation
d_listm,qmi,*tmp = annual_interp(d_list,qm,time_res=time_res,lb=lb,rb=rb)
plt.plot(d_listm,qmi,linestyle = '--', c=dcol,markersize=15,label=dlabel)
plt.scatter(d_list,qm,c=dcol)
if envelope == True:
return d_listm, q2i, qmi, q1i # time, q.25, q.5, q.75
else:
return d_listm, qmi # time, q.5
def annual_px_stats(dates,data,plot=True):
if np.all(np.isnan(data)): # if all data is nan
return [np.nan]*8 # nan for all output stats
# INDICATOR CURVE: data median time, median data, interp median time, interp median
tm,qm,tmi,qmi = annual_px_plot(dates,data,'tab:blue', 'EVI',time_res='doy',f_range=[-0.1,1],plot=plot)
# SOG
sogm = quick_sog(tmi,qmi,th=0.05,pth=10)
# EOS
eosm = quick_eos(tmi,qmi,th=0.05,pth=10)
if np.isnan(sogm) or np.isnan(eosm): # if sason cannot be detected
return [np.nan]*8 # nan for all output stats
# LOS
if eosm-sogm > 0: # if a season is defined
losm = eosm-sogm
else:
losm = np.nan
# OTHERS STATS defined for the SOG-EOS interpolated curve portion
# area under the indicator curve from SOG to
aucm = quick_auc(tmi,qmi,sttt=sogm,entt=eosm)
# MSG: mean seasonal growth
if aucm > 0 and losm > 0:
msgm = aucm/losm
else:
msgm = np.nan
# 90th quantile of the curve
p = 0.9
q90 = quick_q(tmi, qmi, p, sttt=sogm, entt=eosm)
# standard deviation of the green portion
stdm = quick_std(tmi, qmi, sttt=sogm, entt=eosm)
# indicator growth slope fittend on growing season only (213-th DOY, 1st of Aug)
fp,C = curve_fit(gomp,
tmi[:213],
qmi[:213],
maxfev=100000,
bounds = ([0,0,0,0],[2,360,1,1]))
sl = fp[2].copy()
gom_time = np.arange(0,213)
gom_data = gomp(gom_time,*fp)
if plot==True:
plt.plot(gom_time,gom_data,'--',c='tab:purple',label="Gompertz")
plt.plot([eosm,eosm],[-0.1,0.1],'--',c='tab:brown')
plt.text(eosm+1,-0.1,s='EOS',c='tab:brown',rotation = 'vertical')
plt.plot([sogm,sogm],[-0.1,0.1],'--',c='tab:blue')
plt.text(sogm+1,-0.1,s='SOG',c='tab:blue',rotation = 'vertical')
plt.text(tmi[180],qmi[180]/2,s='AUC = ' + str(aucm)[:5],c='tab:blue')
plt.plot([sogm,eosm],[q90,q90],'--',c='tab:orange')
plt.text(sogm+10,q90+0.05,s='q90',c='tab:orange')
# graph cosmetics
plt.ylim([-0.15,1.1])
plt.xlabel('Day of the year (DOY)')
plt.ylabel('Spectral indicators [-1,1]')
plt.legend(loc='upper right',prop={'size': 11})
plt.grid(axis='y',linestyle='--',alpha=0.5)
plt.grid(axis='x',linestyle='--',alpha=0.5)
plt.tight_layout()
return sogm, eosm, losm, aucm, msgm, sl, q90, stdm
def annual_px_plot(dates,data,dcol,dlabel,time_res = 'doy',lb=0,rb=0,f_range=[-1,1],plot=True):
"""
SINGLE PIXEL ANNUAL CURVE PLOT
Generates the interpolated single-pixel or single data series curve for annual data.
If more values are present with the same dates the median is taken.
The interpolated values are also given as output vectors
Parameters
----------
dates : vector
dates or time vector
data : vector
ndvi or similar values to plot
dcol : string
color string for the plotted curve
dlabel : string
legend label for the curve
time_res : string
time resolution among 'month','week', or 'doy'
lb : scalar, optional
left boundary of the interpolated curve at start time.
The default is 0. If lb = 'data' it is set to data[0]
rb : scalar, optional
right boundary of the interpolated curve at start time.
The default is 0. If rb = 'data' it is set to data[-1]
f_range: 2-element vector
range outside which the ndvi median value is considered invalid.
Default is [-1,1], total NDVI range.
plot: boolean
wsith to generate the plot.
Returns
-------
d_listm : vector
time vector for the interpolated values
qmi : vector
interpolated median values
"""
# generate data vectors
d_list = np.unique(dates)
qm = np.array([],dtype=float)
for d in d_list:
data_tmp = data[dates==d]
if np.all(np.isnan(data_tmp)):
qm = np.hstack((qm,np.nan))
else:
qm = np.hstack((qm,np.nanquantile(data[dates==d],0.5)))
# filter out data with median outside given range
fil = np.logical_and(qm > f_range[0],qm < f_range[1])
d_list = d_list[fil]
qm = qm[fil]
# median interpolation
d_listm,qmi,*tmp = annual_interp(d_list,qm,time_res=time_res,lb=lb,rb=rb)
if plot==True:
plt.grid(axis='y',linestyle='--')
plt.plot(d_listm,qmi,linestyle = '--', c=dcol,markersize=15,label=dlabel)
plt.scatter(d_list,qm,c=dcol)
return d_list, qm, d_listm, qmi # data time, median data, interp time, interp median
def quick_eos(tmi,qmi,th=0.1,pth=5,sttt=213,entt=365):
"""
QUICK EOS (End Of Season)
Computes the season end for given interpolated annual data and an NDVI
threshold considered the end of the greening season.
Parameters
----------
tmi : vector
doy time vector
qmi : vector
interpolated data vector
th : scalar
indicator threshold below which the browning time is reached. Default is 0.1
pth : scalar
number of time steps for which ndvi_th has to be passed in order to
define the brwning time. Default is 5
sttt : scalar, optional
starting time for the interpolation. The default is 213 (half of season).
entt : scalar, optional
ending time for the interpolation. The default is 366 (end of year).
Returns
-------
EOS for the given median annual curve
"""
# extract curve portion
st_ind = np.argwhere(tmi==sttt)[0][0]
en_ind = np.argwhere(tmi==entt)[0][0]
tmi_tmp = tmi[st_ind:en_ind]
qmi_tmp = qmi[st_ind:en_ind]
# compute eos
gsw = False
n = 0
egm = np.nan
for i in range(len(tmi_tmp)):
if n==pth:
break
elif qmi_tmp[i]<th and gsw==False:
egm = tmi_tmp[i]
gsw = True
n = n+1
elif qmi_tmp[i]<th and gsw==True:
n = n+1
elif qmi_tmp[i]>=th:
egm = entt
#egm = np.nan
gsw = False
n = 0
return egm # 0.5 quantile browning time
def quick_sog(tmi,qmi,th=0.1,pth=5,sttt=0,entt=213):
"""
QUICK SOG (Start Of Greening)
Computes the season end for given interpolated annual data and an NDVI
threshold considered the end of the greening season.
Parameters
----------
tmi : vector
doy time vector
qmi : vector
interpolated data vector
th : scalar
indicator threshold below which the browning time is reached. Default is 0.1
pth : scalar
number of time steps for which ndvi_th has to be passed in order to
define the brwning time. Default is 5
sttt : scalar, optional
starting time for the interpolation. The default is 213 (half of season).
entt : scalar, optional
ending time for the interpolation. The default is 366 (end of year).
Returns
-------
SOG for the given median annual curve
"""
# extract curve portion
st_ind = np.argwhere(tmi==sttt)[0][0]
en_ind = np.argwhere(tmi==entt)[0][0]
tmi_tmp = tmi[st_ind:en_ind]
qmi_tmp = qmi[st_ind:en_ind]
# compute sog
gsw = False
n = 0
egm = np.nan
for i in range(len(tmi_tmp)):
if n==pth:
break
elif qmi_tmp[i]>th and gsw==False:
egm = tmi_tmp[i]
gsw = True
n = n+1
elif qmi_tmp[i]>th and gsw==True:
n = n+1
elif qmi_tmp[i]<=th:
egm = np.nan
gsw = False
n = 0
return egm # 0.5 quantile greening time
def quick_auc(tmi,qmi,sttt=0,entt=365):
"""
AUC
Computes the Area under the curve (AUC) for given interpolated annual curve.
Parameters
----------
tmi : vector
doy time vector
qmi : vector
interpolated data vector
sttt : scalar, optional
starting time for the interpolation. The default is 0.
entt : scalar, optional
ending time for the interpolation. The default is 365.25.
Returns
-------
qsum : scalar
AUC of the annual curve
"""
# extract curve portion
st_ind = np.argwhere(tmi==sttt)[0][0]
en_ind = np.argwhere(tmi==entt)[0][0]
qmi_tmp = qmi[st_ind:en_ind]
# auc
qmsum = np.cumsum(qmi_tmp)[-1]
return qmsum # auc
def quick_q(tmi,qmi,p,sttt=0,entt=365):
"""
QUICK QUANTILE
Computes the p-th quantile for a given interpolated annual curve.
Parameters
----------
tmi : vector
doy time vector
qmi : vector
interpolated data vector
p:
value of the quantile, defined in [0,1].
ex. q = 0.25 is the first quartile
sttt : scalar, optional
starting time for the interpolation. The default is 0.
entt : scalar, optional
ending time for the interpolation. The default is 365.25.
Returns
-------
q : scalar
p-th quantile of the annual curve
"""
# extract curve portion
st_ind = np.argwhere(tmi==sttt)[0][0]
en_ind = np.argwhere(tmi==entt)[0][0]
qmi_tmp = qmi[st_ind:en_ind]
# quantile
q = np.quantile(qmi_tmp,p)
return q
def quick_std(tmi,qmi,sttt=0,entt=365):
"""
QUICK STANDARD DEVIATION
Computes the standard deviation for a given interpolated annual curve.
Parameters
----------
tmi : vector
doy time vector
qmi : vector
interpolated data vector
sttt : scalar, optional
starting time for the interpolation. The default is 0.
entt : scalar, optional
ending time for the interpolation. The default is 365.25.
Returns
-------
stdm : scalar
stadard deviation of the selected annual curve portion
"""
# extract curve portion
st_ind = np.argwhere(tmi==sttt)[0][0]
en_ind = np.argwhere(tmi==entt)[0][0]
qmi_tmp = qmi[st_ind:en_ind]
# quantile
stdm = np.std(qmi_tmp)
return stdm
def auc(dates,data,time_res,envelope=True,sttt=0,entt=365.25):
"""
AUC
Computes the Area under the curve (AUC) for given annual data.
Data are interpolated as annual curve. If more values are present with
the same dates (ex. pixels from the same image), the median is taken.
If envelope = True, AUC is also computed for the 0.25-0.75 quantile
envelope curves.
Parameters
----------
time : vector
any date of time vector the data
data : vector
data vector
time_res : string, optional
wanted time resolution among "doy", "week", and "month". The default is 'doy'.
envelope : boolean, optional
if = True AUC of the 0.25 and 0.75 quantile envelope curves are computed.
The default is True.
sttt : scalar, optional
starting time for the interpolation. The default is 0.
entt : scalar, optional
ending time for the interpolation. The default is 365.25.
Returns
-------
q2sum : scalar
AUC of the 0.25 quantile annual curve
qmi : scalar
AUC of the median annual curve
q1i : scalar
AUC of the 0.75 quantile annual curve
"""
d_list = np.unique(dates)
#plt.grid(axis='y',linestyle='--')
if envelope==True:
q1 = np.array([],dtype=float)
q2 = np.array([],dtype=float)
for d in d_list:
q1 = np.hstack((q1,np.nanquantile(data[dates==d],0.75)))
q2 = np.hstack((q2,np.nanquantile(data[dates==d],0.25)))
d_list1,q1i,*tmp = annual_interp(d_list,q1,time_res=time_res,sttt=sttt,entt=entt)
d_list2,q2i,*tmp = annual_interp(d_list,q2,time_res=time_res,sttt=sttt,entt=entt)
q1sum = np.cumsum(q1i)[-1]
q2sum = np.cumsum(q2i)[-1]
qm = np.array([],dtype=float)
for d in d_list:
qm = np.hstack((qm,np.nanquantile(data[dates==d],0.5)))
d_listm,qmi,*tmp = annual_interp(d_list,qm,time_res=time_res,sttt=sttt,entt=entt)
qmsum = np.cumsum(qmi)[-1]
if envelope==True:
return q2sum, qmsum, q1sum # q25, qm,q75
else:
return qmsum # qm
def sog(dates,data,time_res,envelope=True,ndvi_th=0.1,pth=5,sttt=0,entt=366):
"""
SOG (Start Of Greening)
Computes the SOG for given NDVI annual data and an NDVI
threshold considered the beginning of the greening season.
Data are interpolated as annual curve. If more values are present with
the same dates (ex. pixels from the same image), the median is taken.
If envelope = True, the greening start is computed also for the 0.25-0.75
quantile envelope curves.
Parameters
----------
dates : vector
any date of time vector the data
data : vector
data vector
time_res : string, optional
wanted time resolution among "doy", "week", and "month". The default is 'doy'.
envelope : boolean, optional
if = True SOG of the 0.25 and 0.75 quantile envelope curves are computed.
The default is True.
ndvi_th : scalar
ndvi threshold below which the greening time is reached. Default is 0.1
pth : scalar
number of continuous time steps for which ndvi_th has to be passed in
order to define the greening time. Default is 5
sttt : scalar, optional
starting time for the interpolation. The default is 0.
entt : scalar, optional
ending time for the interpolation. The default is 365.25.
Returns
-------
q2sum : scalar
SOG of the 0.25 quantile annual curve
qmi : scalar
AOG of the median annual curve
q1i : scalar
SOG of the 0.75 quantile annual curve
"""
d_list = np.unique(dates)
if envelope==True:
q1 = np.array([],dtype=float)
q2 = np.array([],dtype=float)
for d in d_list:
q1 = np.hstack((q1,np.nanquantile(data[dates==d],0.75)))
q2 = np.hstack((q2,np.nanquantile(data[dates==d],0.25)))
d_list1,q1i,*tmp = annual_interp(d_list,q1,time_res=time_res,sttt=sttt,entt=entt)
d_list2,q2i,*tmp = annual_interp(d_list,q2,time_res=time_res,sttt=sttt,entt=entt)
ndvi_th = 0.1
gsw = False
n = 0
egq1 = np.nan
for i in range(len(d_list1)):
if n==5:
break
elif q1i[i]>ndvi_th and gsw==False:
egq1 = d_list1[i]
gsw = True
n = n+1
elif q1i[i]>ndvi_th and gsw==True:
n = n+1
elif q1i[i]<=ndvi_th: