-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSEBCS_lib.py
2951 lines (2447 loc) · 92.7 KB
/
SEBCS_lib.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
# /***************************************************************************
# SEBCS_lib.py
#
# TODO: popis
#
# -------------------
# begin :
# date :
# git sha : $Format:%H$
# copyright : (C) 2014-2023 Jakub Brom
# email : [email protected]
#
# ***************************************************************************/
# /***************************************************************************
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
# You should have received a copy of the GNU General Public License along
# with this program. If not, see <https://www.gnu.org/licenses/>.
#
# ***************************************************************************/
# Imports
import numpy as np
import math
import os
import warnings
from datetime import datetime
from scipy import ndimage
from osgeo import gdal
from osgeo import osr
# noinspection PyMethodMayBeStatic
class GeoIO:
"""
Class includes functions for reading of geotransformation features
from raster and for writing ne rasters from numpy arrays.
"""
def __init__(self):
return
def readGeo(self, rast):
"""
Reading geographical information from raster using
GDAL.
:param rast: Path to raster file in GDAL accepted format.
:type rast: str
:return: The affine transformation coefficients.
:rtype: tuple
:return: Projection information of the raster (dataset).
:rtype: str
:return: Pixel width (m) on X axis.
:rtype: float
:return: Pixel height (m) on Y axis.
:rtype: float
:return: EPSG Geodetic Parameter Set code.
:rtype: int
"""
try:
ds = gdal.Open(rast)
gtransf = ds.GetGeoTransform()
prj = ds.GetProjection()
x_size = gtransf[1]
y_size = gtransf[5] * (-1)
srs = osr.SpatialReference(wkt=prj)
if srs.IsProjected:
EPSG = int(srs.GetAttrValue("authority", 1))
else:
EPSG = None
del ds
return gtransf, prj, x_size, y_size, EPSG
except IOError:
warnings.warn("Geographical information has not been readed.", stacklevel=3)
gtransf = None
prj = None
x_size = None
y_size = None
EPSG = None
return gtransf, prj, x_size, y_size, EPSG
def arrayToRast(self, arrays, names, prj, gtransf, EPSG, out_folder,
driver_name="GTiff", out_file_name=None, multiband=False):
"""Export numpy 2D arrays to multiband or singleband raster
files. Following common raster formats are accepted for export:\n
- ENVI .hdr labeled raster format\n
- Erdas Imagine (.img) raster format\n
- Idrisi raster format (.rst)\n
- TIFF / BigTIFF / GeoTIFF (.tif) raster format\n
- PCI Geomatics Database File (.pix) raster format\n
:param arrays: Numpy array or list of arrays for export to raster.
:type arrays: numpy.ndarray, list
:param names: Name or list of names of the exported bands (in case\
of multiband raster) or particular rasters (in case of singleband\
rasters).
:type names: str, list
:param prj: Projection information of the exported raster (dataset).
:type prj: str
:param gtransf: The affine transformation coefficients.
:type gtransf: tuple
:param EPSG: EPSG Geodetic Parameter Set code.
:type EPSG: int
:param out_folder: Path to folder where the raster(s) will be created.
:type out_folder: str
:param driver_name: GDAL driver. 'GTiff' is default.
:type driver_name: str
:param out_file_name: Name of exported multiband raster.
:type out_file_name: str
:param multiband: Option of multiband raster creation.
:type multiband: bool
:return: Raster singleband or multiband file(s)
:rtype: raster
"""
# Convert arrays and names on list
if type(arrays) is not list:
arr_list = list()
arr_list.append(arrays)
arrays = arr_list
if type(names) is not list:
names_list = list()
names_list.append(names)
names = names_list
if out_file_name is None:
out_file_name = ""
multiband = False
# Drivers and suffixes
driver_list = ["ENVI", "HFA", "RST", "GTiff", "PCIDSK"] # GDAL driver for output files
out_suffixes = ["", ".img", ".rst", ".tif", ".pix"] # Suffixes of output names
# Test driver
if driver_name not in driver_list:
raise ValueError("Unknown driver. Data could not be exported.")
driver_index = driver_list.index(driver_name)
suffix = out_suffixes[driver_index]
if multiband is True and driver_name != "RST":
out_file_name, ext = os.path.splitext(out_file_name)
out_file = os.path.join(out_folder, out_file_name + suffix)
try:
driver = gdal.GetDriverByName(driver_name)
ds = driver.Create(out_file, arrays[0].shape[1], arrays[0].shape[0], len(arrays), gdal.GDT_Float32)
ds.SetProjection(prj)
ds.SetGeoTransform(gtransf)
if EPSG is not None:
outRasterSRS = osr.SpatialReference()
outRasterSRS.ImportFromEPSG(EPSG)
ds.SetProjection(outRasterSRS.ExportToWkt())
j = 1
for i in arrays:
ds.GetRasterBand(j).WriteArray(i)
ds.GetRasterBand(j).SetDescription(names[j - 1])
ds.GetRasterBand(j).SetMetadataItem("Band name", names[j - 1])
ds.GetRasterBand(j).FlushCache()
j = j + 1
del ds
except IOError:
raise Exception("Raster file {} has not been created.".format(out_file_name + suffix))
else:
for i in range(0, len(arrays)):
try:
out_file_name, ext = os.path.splitext(names[i])
out_file = os.path.join(out_folder, out_file_name + suffix)
driver = gdal.GetDriverByName(driver_name)
ds = driver.Create(out_file, arrays[i].shape[1], arrays[i].shape[0], 1, gdal.GDT_Float32)
ds.SetProjection(prj)
ds.SetGeoTransform(gtransf)
if EPSG is not None:
outRasterSRS = osr.SpatialReference()
outRasterSRS.ImportFromEPSG(EPSG)
ds.SetProjection(outRasterSRS.ExportToWkt())
ds.GetRasterBand(1).WriteArray(arrays[i])
ds.GetRasterBand(1).SetDescription(names[i])
ds.GetRasterBand(1).SetMetadataItem("Band name", names[i])
ds.GetRasterBand(1).FlushCache()
del ds
except IOError:
raise Exception("Raster file {} has not been created.".format(names[i] + suffix))
@staticmethod
def rasterToArray(layer):
"""Conversion of raster layer to numpy array.
:param layer: Path to raster layer.
:type layer: str
:return: raster file converted to numpy array
:rtype: numpy.ndarray
"""
lyr_name = os.path.split(layer)[1]
try:
if layer is not None or layer is not "":
try:
new_array = gdal.Dataset.ReadAsArray(gdal.Open(layer)).astype(
np.float32)
new_array = np.nan_to_num(new_array)
except:
new_array = None
else:
new_array = None
except IOError:
warnings.warn("Layer {lr} has not been readed. No data will be "
"used instead".format(lr=lyr_name), stacklevel=3)
new_array = None
return new_array
def lyrsExtent(self, in_lyrs_list):
"""
Check differences between size of the input layers. Function compares
rasters only on basis of number of columns and rows.
:param in_lyrs_list: List of layers (Numpy 2D arrays).
:type in_lyrs_list: list
:return: True
"""
# TODO: Solution of different spatial extent of rasters...
in_lyrs_list_true = [i for i in in_lyrs_list if
i is not None] # List of input layers without
# empty (None)
len_list = []
for i in in_lyrs_list_true:
len_list.append(len(i))
if max(len_list) != min(len_list):
raise ValueError(
"Selected layers differ in spatial extent (number of columns "
"or rows).")
return
# noinspection PyMethodMayBeStatic,PyUnusedLocal,SpellCheckingInspection,SpellCheckingInspection
class VegIndices:
"""
Calculation of vegetation indices from spectral data.
"""
def __init__(self):
return
def viNDVI(self, red, nir):
"""
Normalized Difference Vegetation Index - NDVI.
:param red: Spectral reflectance in RED region (rel.)
:type red: numpy.ndarray
:param nir: Spectral reflectance in NIR region (rel.)
:type nir: numpy.ndarray
:return: Normalized Difference Vegetation Index - NDVI (unitless)
:rtype: numpy.ndarray
"""
ignore_zero = np.seterr(all="ignore")
try:
ndvi = (nir - red) / (nir + red)
ndvi = np.where(ndvi == np.inf, 0, ndvi) # replacement inf values
# by 0
ndvi = np.where(ndvi == -np.inf, 0, ndvi) # replacement -inf
# values by 0
except ArithmeticError:
raise ArithmeticError("NDVI has not been calculated.")
return ndvi
# noinspection SpellCheckingInspection
def viSAVI(self, red, nir, L=0.5):
# noinspection SpellCheckingInspection
"""
Soil Adjusted Vegetation Index - SAVI (Huete, 1988).
:param red: Spectral reflectance in RED region (rel.)
:type red: numpy.ndarray
:param nir: Spectral reflectance in NIR region (rel.)
:type nir: numpy.ndarray
:param L: Parameter L. Default L=0.5
:type L: float
:return: Soil Adjusted Vegetation Index - SAVI (unitless)
:rtype: numpy.ndarray
\n
**References**\n
*Huete A.R. (1988): A soil-adjusted vegetation index (SAVI) Remote
Sensing of Environment 27, 47-57.*
"""
ignore_zero = np.seterr(all="ignore")
try:
savi = (1 + L) * (nir - red) / (L + nir + red)
except ArithmeticError:
raise ArithmeticError("SAVI has not been calculated.")
return savi
def viOSAVI(self, red, nir, L=0.16):
"""
Optimized Soil Adjusted Vegetation Index - OSAVI (Rondeaux et al. (
1996)).
:param red: Spectral reflectance in RED region (rel.)
:type red: numpy.ndarray
:param nir: Spectral reflectance in NIR region (rel.)
:type nir: numpy.ndarray
:param L: Parameter L. Default L=0.5
:type L: float
:return: Soil Adjusted Vegetation Index - OSAVI (unitless)
:rtype: numpy.ndarray
\n
**References**\n
*Rondeaux G., Steven M., Baret F. (1996): Optimisation of
soil-adjusted vegetation indices Remote Sensing of Environment,
55 (1996), pp. 95-107*
"""
ignore_zero = np.seterr(all="ignore")
try:
osavi = (nir - red) / (L + nir + red)
except ArithmeticError:
raise ArithmeticError("SAVI has not been calculated.")
return osavi
def viNDMI(self, nir, swir1):
"""
Normalized Vegetation Moisture Index - NDMI.
:param nir: Spectral reflectance in NIR region (rel.)
:type nir: numpy.ndarray
:param swir1: Spectral reflectance in SWIR region (approx. 1.61\
:math:`\\mu{m}` (rel.)
:type nir: numpy.ndarray
:return: Normalized Vegetation Moisture Index - NDMI (unitless)
:rtype: numpy.ndarray
"""
ignore_zero = np.seterr(all="ignore") # ignoring exceptions with dividing by zero
if swir1 is not None:
try:
ndmi = (nir - swir1) / (nir + swir1)
ndmi[ndmi == np.inf] = 0 # replacement inf values by 0
ndmi[ndmi == -np.inf] = 0 # replacement -inf values by 0
except ArithmeticError:
raise ArithmeticError("NDMI has not been calculated.")
else:
ndmi = None
return ndmi
def viMSAVI(self, red, nir):
"""
Modified Soil Adjusted Vegetation Index - MSAVI (Qi et al. 1994).
:param red: Spectral reflectance in RED region (rel.)
:type red: numpy.ndarray
:param nir: Spectral reflectance in NIR region (rel.)
:type nir: numpy.ndarray
:return: Modified Soil Adjusted Vegetation Index - SAVI (unitless)
:rtype: numpy.ndarray
\n
**References**\n
*Qi, J., Chehbouni, A., Huete, A.R., Kerr, Y.H., Sorooshian, S.,
1994. A modified soil adjusted vegetation index. Remote Sensing of
Environment 48, 119–126. https://doi.org/10.1016/0034-4257(94)90134-1*
"""
ignore_zero = np.seterr(all="ignore") # ignoring exceptions with dividing by zero
try:
msavi = 0.5 * ((2 * nir + 1) - ((2 * nir + 1) ** 2.0 - 8 * (nir - red)) ** 0.5)
msavi[msavi == np.inf] = 0 # replacement inf values by 0
msavi[msavi == -np.inf] = 0 # replacement -inf values by 0
except ArithmeticError:
raise ArithmeticError("MSAVI has not been calculated.")
return msavi
def viRDVI(self, red, nir):
"""
Renormalized Difference Vegetation Index - RDVI (Roujean and
Breon, 1995).
:param red: Spectral reflectance in RED region (rel.)
:type red: numpy.ndarray
:param nir: Spectral reflectance in NIR region (rel.)
:type nir: numpy.ndarray
:return: RDVI
:rtype: numpy.ndarray
\n
**References**\n
*Roujean, J.-L., Breon, F.-M., 1995. Estimating PAR absorbed
by vegetation from bidirectional reflectance measurements.
Remote Sensing of Environment 51, 375–384.
https://doi.org/10.1016/0034-4257(94)00114-3*
"""
ignore_zero = np.seterr(all="ignore")
try:
rdvi = (nir - red) / np.sqrt(nir + red)
rdvi = np.nan_to_num(rdvi)
except ArithmeticError:
raise ArithmeticError("RDVI has not been calculated.")
return rdvi
def fractVegCover(self, ndvi):
"""
Fractional vegetation cover layer - Fc.
:param ndvi: Normalized Difference Vegetation Index - NDVI (unitless)
:type ndvi: numpy.ndarray
:return: Fractional vegetation cover layer - Fc (unitless)
:rtype: numpy.ndarray
"""
try:
Fc = ((ndvi - 0.2) / 0.3) ** 2
except ArithmeticError:
raise ArithmeticError("Fractional cover index has not been "
"calculated.")
return Fc
def LAI(self, red, nir, method=2):
"""
Leaf Area Index (LAI) calculated according to several methods.
:param red: Spectral reflectance in RED region (rel.)
:type red: numpy.ndarray
:param nir: Spectral reflectance in NIR region (rel.)
:type nir: numpy.ndarray
:param method: Method of LAI calculation:\n
* 0: Pôças
* 1: Bastiaanssen
* 2: Jafaar (default)
* 3: Anderson
* 4: vineyard
* 5: Carrasco
* 6: Turner
* 7: Haboudane
* 8: Brom (experimental)
:type method: int
:return: Leaf Area Index (LAI) :math:`(m^2.m^{-2})`
:rtype: numpy.ndarray
\n
**References**\n
*Anderson, M., Neale, C., Li, F., Norman, J., Kustas, W., Jayanthi,
H., Chavez, J., 2004. Upscaling ground observations of vegetation
water content, canopy height, and leaf area index during SMEX02 using
aircraft and Landsat imagery. Remote Sensing of Environment 92,
447–464. https://doi.org/10.1016/j.rse.2004.03.019* \n
*Bastiaanssen, W.G.M., Menenti, M., Feddes, R.A., Holtslag, A.A.M.,
1998. A remote sensing surface energy balance algorithm for land (
SEBAL). 1. Formulation. Journal of Hydrology 212–213, 198–212.
https://doi.org/10.1016/S0022-1694(98)00253-4* \n
*Carrasco-Benavides, M., Ortega-Farías, S., Lagos, L., Kleissl, J.,
Morales-Salinas, L., Kilic, A., 2014. Parameterization of the
Satellite-Based Model (METRIC) for the Estimation of Instantaneous
Surface Energy Balance Components over a Drip-Irrigated Vineyard.
Remote Sensing 6, 11342–11371. https://doi.org/10.3390/rs61111342* \n
*Jaafar, H.H., Ahmad, F.A., 2019. Time series trends of Landsat-based
ET using automated calibration in METRIC and SEBAL: The Bekaa
Valley, Lebanon. Remote Sensing of Environment S0034425718305947.
https://doi.org/10.1016/j.rse.2018.12.033* \n
*Pôças, I., Paço, T.A., Cunha, M., Andrade, J.A., Silvestre, J.,
Sousa, A., Santos, F.L., Pereira, L.S., Allen, R.G., 2014.
Satellite-based evapotranspiration of a super-intensive olive
orchard: Application of METRIC algorithms. Biosystems Engineering
128, 69–81. https://doi.org/10.1016/j.biosystemseng.2014.06.019* \n
*Turner, D.P., Cohen, W.B., Kennedy, R.E., Fassnacht, K.S., Briggs,
J.M., 1999. Relationships between Leaf Area Index and Landsat TM
Spectral Vegetation Indices across Three Temperate Zone Sites.
Remote Sensing of Environment 70, 52–68.
https://doi.org/10.1016/S0034-4257(99)00057-7*
"""
savi = self.viSAVI(red, nir, 0.5)
ndvi = self.viNDVI(red, nir)
osavi = self.viOSAVI(red, nir)
msavi = self.viMSAVI(red, nir)
rdvi = self.viRDVI(red, nir)
# methods = {1:'Pôças', 2:'Bastiaanssen', 3:'Jafaar', 4:'Anderson',
# 5:'vineyard', 6:'Carrasco', 7:'Turner', 8:'Haboudane',
# 9:'Brom'}
if method is 0: # Pôças
LAI = np.where(savi > 0, 11.0 * savi**3, 0)
LAI = np.where(savi > 0.817, 6, LAI)
elif method is 1: # Bastiaanssen
LAI = np.where(savi > 0, np.log((0.61 - savi)/0.51)/0.91 * (-1), 0)
LAI = np.where(savi >= 0.61, 6, LAI)
elif method is 2: # Jafaar
LAI_1 = np.where(savi > 0, 11.0 * savi ** 3, 0)
LAI_1 = np.where(savi > 0.817, 6, LAI_1)
LAI_2 = np.where(savi > 0, np.log((0.61 - savi) / 0.51) / 0.91 * (
-1), 0)
LAI_2 = np.where(savi >= 0.61, 6, LAI_2)
LAI = (LAI_1 + LAI_2)/2
elif method is 3: # Anderson
LAI = (4 * osavi - 0.8) * (1 + 4.73e-6 * np.exp(15.64 * osavi))
elif method is 4: # vineyard
LAI = 4.9 * ndvi - 0.46
elif method is 5: # Carrasco
LAI = 1.2 - 3.08 * np.exp(-2013.35 * ndvi ** 6.41)
elif method is 6: # Turner
LAI = 0.5724 + 0.0989 * ndvi - 0.0114 * ndvi**2 + 0.0004 * ndvi**3
elif method is 7: # Haboudane
LAI = 0.0918 ** (6.0002 * rdvi)
elif method is 8: # Brom
LAI = 6.0/(1 + np.exp(-(8 * savi - 5)))
# Method proposed by Brom (mathematical definition only,
# not tested). Good approximation with another methods (1, 2, 3) but
# this method is very sensitive on parameters in exponent
else:
raise ArithmeticError("LAI has not been calculated.")
LAI = np.where(LAI <= 0, 0, LAI)
return LAI
def vegHeight(self, h_min, h_max, msavi):
"""
Height of effective vegetation cover (m) derived from MSAVI index
according to Gao et al. (2011).
:param h_min: Maximal height of vegetation cover (m)
:type h_max: numpy.ndarray
:param h_max: Minimal height of vegetation cover (m)
:type h_min: numpy.ndarray
:param msavi: Modified Soil Adjusted Vegetation Index (MSAVI)
:type msavi: numpy.ndarray
:return: Effective vegetation cover height (m)
:rtype: numpy.ndarray
\n
**References**\n
*Gao, Z.Q., Liu, C.S., Gao, W., Chang, N.-B., 2011. A coupled remote
sensing and the Surface Energy Balance with Topography Algorithm
(SEBTA) to estimate actual evapotranspiration over heterogeneous
terrain. Hydrol. Earth Syst. Sci. 15, 119–139.
https://doi.org/10.5194/hess-15-119-2011*
"""
try:
minmsavi = np.min(msavi[msavi != 0])
maxmsavi = np.max(msavi)
h_eff = h_min + (msavi - minmsavi) / (minmsavi - maxmsavi) * (h_min - h_max)
return h_eff
except ArithmeticError:
raise ArithmeticError("Vegetation height has not been calculated.")
def biomass_sat(self, ndvi):
"""
Calculation of amount of fresh biomass from satellite data. NDVI is used
for estimation :math:`(t.ha^{-1})`
:param ndvi: Normalized Difference Vegetation Index (NDVI).
:return: Amount of fresh biomass :math:`(t.ha^{-1})`
"""
# TODO: Velmi jednoduchý, až nereálný model. Možná by šlo použít
# model uvedený v SARCA a RWC nahradit nějakým indexem, např. NDMI
# nebo FMI (Foliar moisture index). Tohle bude složitějsí...
fresh_biomass = 50 * ndvi ** 2.5
return fresh_biomass
# noinspection PyMethodMayBeStatic
class SolarRadBalance(VegIndices):
"""
Class contains functions for calculation of solar radiation balance
and topographic features: incident radiation in dependence on surface
geometry, slope of terrain, aspect of terrain, albedo, longwave radiation
fluxes and atmospheric emissivity, shortwave radiation reflectance
and total net radiation
"""
def slopeAspect(self, DMT, x_size, y_size):
"""
Slope and aspect of terrain (DMT) in degrees.
:param DMT: Digital model of terrain (m a.s.l.)
:type DMT: numpy.ndarray
:param x_size: Size of pixel in x axis (m)
:type x_size: float
:param y_size: Size of pixel in y axis (m)
:type y_size: float
:return: Slope of the terrain :math:`(\SI{}\degree)`
:rtype: numpy.ndarray
:return: Aspect of the terrain :math:`(\SI{}\degree)`
:rtype: numpy.ndarray
"""
try:
x, y = np.gradient(DMT)
slope = np.arctan(np.sqrt((x / x_size) ** 2.0 + (y / y_size) **
2.0)) * 180 / np.pi
aspect = 270 + np.arctan(x / y) * 180 / np.pi
aspect = np.where(y > 0, aspect, aspect - 180)
# Replacing nan values to 0 and inf to value
slope = np.nan_to_num(slope)
aspect = np.nan_to_num(aspect)
del x
del y
except ArithmeticError:
raise ArithmeticError("Slope and aspect has not been calculated.")
return slope, aspect
def solarInTopo(self, Rs_in, slope, aspect, latitude, longitude,
date_acq, time_acq):
"""Calculation of incident shortwave solar radiation flux
according to the solar geometry, position (latitude
and longitude) and shape of surface (slope and orientation).
Flux of the solar energy :math:`(W.m^{-2})` is calculated on basis
of the measured global radiation using pyranometer (incomming
global radiation). Diffuse part of radiation is not separated
in calculation.
:param Rs_in: Global radiation measured by pyranometer\
:math:`(W.m^{-2})`.
:type Rs_in: float
:param slope: Slope of the terrain :math:`(\SI{}\degree)`.
:type slope: numpy.ndarray
:param aspect: Orientation of the terrain :math:`(\SI{}\degree)`.
:type aspect: numpy.ndarray
:param latitude: Mean latitude of the data in decimal degrees
:type latitude: float
:param longitude: Mean longitude of the data in decimal degrees
:type longitude: float
:param date_acq: Date of data acquisition in iso format ('YYYY-mm-dd')
:type date_acq: datetime.date
:param time_acq: Time in GMT in datetime.time format ('HH:MM:SS.SS')
:type time_acq: datetime.time
:returns: Incident shortwave radiation :math:`(W.m^{-2})` corrected\
on the terrain and solar geometry.
:rtype: numpy.ndarray
"""
# Date conversions
try:
dat = datetime.strptime(str(date_acq),
"%Y-%m-%d") # conversion of iso date to datetime.date
t = datetime.strptime(str(time_acq),
"%H:%M:%S.%f") # conversion of iso time to datetime.time
dec_t = float(t.hour) + float(t.minute) / 60.0 + float(
t.second) / 3600 # decimal time
N = dat.strftime("%j") # day of the year
except ArithmeticError:
raise ArithmeticError("Date transformation has not been done.")
# Solar radiation geometry calculation
try:
solar_time = dec_t + longitude / 360.0 * 24.0 # solar time
hs = (12.0 - float(solar_time)) * 15.0 # local solar hour angle (°)
ds = 23.45 * math.sin(360.0 * (284.0 + float(
N)) / 365.0 * math.pi / 180.0) # solar declination (°)
ds_rad = math.radians(ds) # solar declination (rad.)
L_rad = math.radians(latitude) # latitude (rad.)
hs_rad = math.radians(hs) # local solar hour angle (rad.)
sin_alpha = (math.sin(L_rad) * math.sin(ds_rad) + math.cos(L_rad)
* math.cos(ds_rad) * math.cos(
hs_rad)) # sin of solar height angle
if sin_alpha < 0.0:
sin_alpha = 0.0
slope_rad = np.radians(slope)
asp_rad = np.radians((aspect - 180) * (-1)) # aspect transformation
cosi = (np.sin(ds_rad) * (np.sin(L_rad) * np.cos(slope_rad)
- np.cos(L_rad) * np.sin(
slope_rad) * np.cos(asp_rad))
+ np.cos(ds_rad) * np.cos(hs_rad) * (np.cos(L_rad)
* np.cos(
slope_rad) + np.sin(L_rad) * np.sin(slope_rad)
* np.cos(
asp_rad)) + np.cos(ds_rad) * np.sin(slope_rad)
* np.sin(asp_rad) * np.sin(hs_rad))
except ArithmeticError:
raise ArithmeticError("Solar geometry corrections have not been "
"done.")
# Direct radiation intensity correction on DEM
try:
Is = float(
Rs_in) / sin_alpha # radiation perpendicular to solar beam angle
Rs_in_corr = Is * cosi # radiation corrected on solar and terrain geometry
except ArithmeticError:
raise ArithmeticError("Radiation intensity correction on DEM has "
"not been done.")
return Rs_in_corr
def atmEmissivity(self, e_Z, ta):
"""
Atmospheric emissivity calculated according to Idso (see
Brutsaert 1982).
:param e_Z: Atmospheric water vapour pressure (kPa)
:type e_Z: numpy.ndarray, float
:param ta: Air temperature :math:`(\SI{}\degreeCelsius)`
:type ta: numpy.ndarray, float
:return: Air emissivity (rel.)
:rtype: numpy.ndarray, float
"""
try:
emis_a = 1.24 * (e_Z * 10.0 / (ta + 273.16)) ** (1.0 / 7.0)
except ArithmeticError:
raise ArithmeticError("Air emissivity has not been calculated.")
return emis_a
def downRL(self, ta, emis_a):
"""
Funtion calculates downward flux of longwave radiation :math:`(W.m^{
-2})`
:param ta: Air temperature :math:`(\SI{}\degreeCelsius)`
:type ta: numpy.ndarray, float
:param emis_a: Air emissivity (rel.)
:type emis_a: numpy.ndarray, float
:return RL_in: Downward flux of longwave radiation :math:`(W.m^{-2})`
:rtype RL_in: numpy.ndarray, float
"""
try:
RL_in = emis_a * 5.6703 * 10.0 ** (-8.0) * (ta + 273.16) ** 4
except ArithmeticError:
raise ArithmeticError("Downward longwave radiation flux has not "
"been calculated.")
return RL_in
def outRL(self, ts, emiss):
"""
Upward flux of longwave radiation :math:`(W.m^{-2})`
:param ts: Surface temperature :math:`(\SI{}\degreeCelsius)`
:type ts: numpy.ndarray
:param emiss: Surface emissivity (rel.)
:type emiss: numpy.ndarray
:returns: Upward flux of longwave radiation :math:`(W.m^{-2})`
:rtype: numpy.ndarray
"""
try:
RL_out = emiss * 5.6703 * 10.0 ** (-8.0) * (ts + 273.16) ** 4
except ArithmeticError:
raise ArithmeticError("Upward longwave radiation flux has not "
"been calculated.")
return RL_out
def albedoBrom(self, ndvi, msavi, c_a=0.08611, c_b=0.894716, c_c=5.558657,
c_d=-0.11829, c_e=-1.9818, c_f=-4.50339, c_g=-11.4625,
c_h=7.461454, c_i=5.299396, c_j=4.76657, c_k=-2.3127,
c_l=-3.42739):
"""
Albedo (rel.) calculated according to Duffková and Brom et al. (2012)
:param ndvi: Normalized Difference Vegetation Index (-)
:type ndvi: numpy.array
:param msavi: Modified Soil Adjusted Vegetation Index (-) according\
to Gao et al. 1996.
:param c_a: constant. Default a = 0.08611
:type c_a: float
:param c_b: constant. Default a = 0.894716
:type c_b: float
:param c_c: constant. Default a = 5.558657
:type c_c: float
:param c_d: constant. Default a = -0.11829
:type c_d: float
:param c_e: constant. Default a = -1.9818
:type c_e: float
:param c_f: constant. Default a = -4.50339
:type c_f: float
:param c_g: constant. Default a = -11.4625
:type c_g: float
:param c_h: constant. Default a = 7.461454
:type c_h: float
:param c_i: constant. Default a = 5.299396
:type c_i: float
:param c_j: constant. Default a = 4.76657
:type c_j: float
:param c_k: constant. Default a = -2.3127
:type c_k: float
:param c_l: constant. Default a = -3.42739
:type c_l: float
:returns: Albedo (rel.)
:rtype: numpy.ndarray
\n
**References:**\n
*Duffková, R., Brom, J., Žížala, D., Zemek, F., Procházka, J.,
Nováková, E., Zajíček, A., Kvítek, T., 2012. Určení infiltračních
oblastí pomocí vodního stresu vegetace na základě dálkového průzkumu
Země a pozemních měření. Certifikovaná metodika. VÚMOP, v.v.i., Praha.*
"""
try:
albedo = (c_a + c_b * msavi + c_c * msavi ** 2 + c_d * ndvi + c_e
* msavi ** 3 + c_f * msavi * ndvi + c_g * msavi ** 2
* ndvi + c_h * msavi * ndvi ** 2 + c_i * msavi ** 2
* ndvi ** 2 + c_j * msavi ** 3 * ndvi + c_k * msavi ** 3
* ndvi ** 2 + c_l * msavi * ndvi ** 3)
except ArithmeticError:
raise ArithmeticError("Albedo has not been calculated.")
return albedo
def albedoLandsat(self, blue, green, red, nir, swir1, swir2, sat_type="L8"):
"""
Albedo (rel.) calculated for Landsat satellite sensors. Albedo
for Landsat 4 TM, 5 TM and Landsat 7 ETM+ is calculated
according to Tasumi et al. (2008). Albedo for Landsat 8 OLI/TIRS
is calculated according to Olmeo et al. (2017). Albedo is computed
with spectral reflectance bands on relative scale (0 to 1).\n
Note: This algorithm might be used with another data from different
devices, however a comparable spectral data (bands) should be used.
:param blue: Blue band (rel.)
:type blue: numpy.ndarray
:param green: Green band (rel.)
:type green: numpy.ndarray
:param red: Red band (rel.)
:type red: numpy.ndarray
:param nir: NIR band (rel.)
:type nir: numpy.ndarray
:param swir1: SWIR1 band on ca 1.61 :math:`\mu m` (rel.)
:type swir1: numpy.ndarray
:param swir2: SWIR2 band on ca 2.2 :math:`\mu m` (rel.)
:type swir2: numpy.ndarray
:param sat_type: Type of Landsat satellite: \n\n
- L5 - Landsat 4 TM, 5 TM or Landsat 7 ETM+\n
- L8 - Landsat 8 OLI/TIRS
:type sat_type: str
:return: Albedo (rel.)
:rtype: numpy.ndarray
\n
**References:**\n
*G.F. Olmedo, S. Ortega-Farias, D. Fonseca-Luengo,
D. de la Fuente-Saiz, F.F. Peñailillo 2018: Water: actual
evapotranspiration with energy balance models. R Package
Version 0.6 (2017)*\n
*Tasumi, M., Allen, R.G., Trezza, R., 2008. At-Surface Reflectance
and Albedo from Satellite for Operational Calculation of Land
Surface Energy Balance. Journal of Hydrologic Engineering 13, 51–63.*
https://doi.org/10.1061/(ASCE)1084-0699(2008)13:2(51).
"""
# Constants
bands = [blue, green, red, nir, swir1, swir2]
if sat_type == "L8":
wb = (0.246, 0.146, 0.191, 0.304, 0.105, 0.008) # Constants for
# L8 according to Olmeo et. al 2017: (G.F. Olmedo, S. Ortega-Farias,
# D. Fonseca-Luengo, D. de la Fuente-Saiz, F.F. Peñailillo
# Water: actual evapotranspiration with energy balance models
# R Package Version 0.6 (2017))
else:
wb = (0.254, 0.149, 0.147, 0.311, 0.103, 0.036) # Constants
# according to Tasumi et al. 2008: Tasumi, M., Allen, R.G., Trezza,
# R., 2008. At-Surface Reflectance and Albedo from Satellite
# for Operational Calculation of Land Surface Energy Balance.
# Journal of Hydrologic Engineering 13, 51–63.
# https://doi.org/10.1061/(ASCE)1084-0699(2008)13:2(51)
# Computing of broadband albedo
try:
alfa_list = []
for i in range(0, len(bands)):
alfa_band = bands[i] * wb[i]
alfa_list.append(alfa_band)
del alfa_band
albedo = np.zeros(alfa_list[0].shape)
i = 0
while i != len(alfa_list):
albedo = albedo + alfa_list[i]
i = i + 1
del alfa_list
except ArithmeticError:
raise ArithmeticError("Albedo has not been calculated.")
return albedo
def albedo(self, band_red, band_nir, sat_type="L8", band_blue=None,
band_green=None, band_sw1=None, band_sw2=None):
"""
Calculation of Albedo according to data type (satellite data type)
or data availability. Albedo can be calculated using Landsat data
or using any data including RED and NIR band. For the Landsat 8 data
Olmedo method is used, for tle Landsat 4, 5 and 7 Tasumi approach is
used. If only RED and NIR bands are available, Brom method is used.
:param band_red: Red band (rel.)
:type band_red: numpy.ndarray
:param band_nir: NIR band (rel.)
:type band_nir: numpy.ndarray
:param sat_type: Type of Landsat satellite: \n\n
- L5 - Landsat 4 TM, 5 TM or Landsat 7 ETM+\n
- L8 - Landsat 8 OLI/TIRS
:type sat_type: str
:param band_blue: Blue band (rel.)
:type band_blue: numpy.ndarray
:param band_green: Green band (rel.)
:type band_green: numpy.ndarray
:param band_sw1: SWIR1 band on ca 1.61 :math:`\mu m` (rel.)
:type band_sw1: numpy.ndarray
:param band_sw2: SWIR2 band on ca 2.2 :math:`\mu m` (rel.)
:type band_sw2: numpy.ndarray
:return: Albedo (rel.)
:rtype: numpy.ndarray