-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbaltic_AC_forwardNN_TF_od.py
1556 lines (1318 loc) · 66.2 KB
/
baltic_AC_forwardNN_TF_od.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
# -*- coding: utf-8 -*-
import collections
import datetime
import glob
import os
import sys
import numpy as np
from scipy.optimize import curve_fit, least_squares, minimize
import tensorflow as tf
# snappy import
# sys.path.append("C:\\Users\Dagmar\.snap\snap-python")
# sys.path.append("F:\Anaconda_envs\py310_keras3\Lib\site-packages\esa_snappy")
sys.path.append("D:\olaf\miniconda3_py310\Lib\site-packages\esa_snappy")
import esa_snappy as snp
from esa_snappy import Product
from esa_snappy import ProductData
# from snappy import ProductDataUTC
# from snappy import ProductIO
from esa_snappy import ProductUtils
from esa_snappy import ProgressMonitor
from esa_snappy import FlagCoding
from esa_snappy import jpy
from esa_snappy import GPF
from esa_snappy import HashMap
#from snappy import TimeCoding #org.esa.snap.core.datamodel.TimeCoding
from esa_snappy import PixelPos #org.esa.snap.core.datamodel.PixelPos
#fetchOzone = jpy.get_type('org.esa.s3tbx.c2rcc.ancillary.AncillaryCommons.fetchOzone')
AtmosphericAuxdata = jpy.get_type('eu.esa.opt.c2rcc.ancillary.AtmosphericAuxdata')
AtmosphericAuxdataBuilder = jpy.get_type('eu.esa.opt.c2rcc.ancillary.AtmosphericAuxdataBuilder')
TimeCoding = jpy.get_type('org.esa.snap.core.datamodel.TimeCoding')
AncDownloader = jpy.get_type('eu.esa.opt.c2rcc.ancillary.AncDownloader')
AncillaryCommons = jpy.get_type('eu.esa.opt.c2rcc.ancillary.AncillaryCommons')
AncRepository = jpy.get_type('eu.esa.opt.c2rcc.ancillary.AncRepository')
File = jpy.get_type('java.io.File')
AncDataFormat = jpy.get_type('eu.esa.opt.c2rcc.ancillary.AncDataFormat')
Calendar = jpy.get_type('java.util.Calendar')
# local import
from baltic_corrections import gas_correction, glint_correction, Rayleigh_correction, diffuse_transmittance, Rmolgli_correction_Hygeos
import get_bands
from misc import default_ADF, scale_minmax
import luts_olci, luts_msi
import lut_hygeos
from auxdata_handling import setAuxData, checkAuxDataAvailablity, getGeoPositionsForS2Product, yearAndDoyAndHourUTC
# Set locale for proper time reading with datetime
# locale.setlocale(locale.LC_ALL, 'en_US.UTF_8')
# Define NNs as global variables
def read_NNs(sensor, NNversion, NNIOPversion):
global nn_forward, nn_backward, nn_backward_iop
global nnForward_IO, nnBackward_IO, nnBackwardIOP_IO
global session
# Define paths of NNs
filePath = glob.glob(os.path.join('NNs',sensor,NNversion,'forward','*.h5'))
if filePath == []:
print("Missing NN in %s format in NNs/%s/%s/forward/"%('h5',sensor,NNversion))
sys.exit(1)
else:
nnForwardFilePath = filePath[0]
filePath = glob.glob(os.path.join('NNs',sensor,NNversion,'backward','*.h5'))
if filePath == []:
print("Missing NN in %s format in NNs/%s/%s/backward/"%('h5',sensor,NNversion))
sys.exit(1)
else:
nnBackwardFilePath = filePath[0]
filePath = glob.glob(os.path.join('NNs',sensor,NNIOPversion,'backward','*.h5'))
if filePath == []:
print("Missing NN in %s format in NNs/%s/%s/backward/"%('h5',sensor,NNIOPversion))
sys.exit(1)
else:
nnBackwardIOPFilePath = filePath[0]
# Open NNs
nn_forward = open_NN(nnForwardFilePath, NNversion)
nn_backward = open_NN(nnBackwardFilePath, NNversion)
nn_backward_iop = open_NN(nnBackwardIOPFilePath, NNIOPversion)
# Define paths of .net files containing the ranges
filePath = glob.glob(os.path.join('NNs',sensor,NNversion,'forward','*.net'))
if filePath == []:
print("Missing NN in %s format in NNs/%s/%s/forward/"%('net',sensor,NNversion))
sys.exit(1)
else:
nnForwardFilePathNet = filePath[0]
filePath = glob.glob(os.path.join('NNs',sensor,NNversion,'backward','*.net'))
if filePath == []:
print("Missing NN in %s format in NNs/%s/%s/backward/"%('net',sensor,NNversion))
sys.exit(1)
else:
nnBackwardFilePathNet = filePath[0]
filePath = glob.glob(os.path.join('NNs',sensor,NNIOPversion,'backward','*.net'))
if filePath == []:
print("Missing NN in %s format in NNs/%s/%s/backward/"%('net',sensor,NNIOPversion))
sys.exit(1)
else:
nnBackwardIOPFilePathNet = filePath[0]
# Define ranges for forward NN and backward NN
nnForward_IO = read_NN_IO_fromFile(nnForwardFilePathNet)
nnBackward_IO = read_NN_IO_fromFile(nnBackwardFilePathNet)
nnBackwardIOP_IO = read_NN_IO_fromFile(nnBackwardIOPFilePathNet)
def open_NN(nnFilePath, NNversion):
global session
# Open session for tf v1.X
TF_version = tf.__version__.split('.')[0]
if TF_version == '1':
if 'session' not in globals() or (session is None):
session = tf.InteractiveSession()
else:
session = None
# Read NNs
nn_object = tf.keras.models.load_model(nnFilePath)
return nn_object
def read_NN_IO_fromFile(nnFilePath):
""" Read input range in the .net file """
file = open(nnFilePath, 'r')
lines = [line.rstrip('\n') for line in file]
file.close()
Ninput = 0
Noutput = 0
for line in lines:
if 'the net has' in line:
if 'input' in line:
Ninput = int(line.split(' ')[3])
if 'output' in line:
Noutput = int(line.split(' ')[3])
inputVariables = []
inputRange = np.zeros((Ninput, 2))
outputRange = np.zeros((Noutput, 2))
bands = [] # Either input or output bands
iIN = 0
iOUT = 0
scaling = False
for line in lines:
if line.startswith('input'):
inputVariables.append(line.split('is ')[1].split(' ')[0])
t = line.split('[')[1][:-1]
t = t.split(',')
inputRange[iIN, 0] = float(t[0])
inputRange[iIN, 1] = float(t[1])
if 'log_rw_' in line:
bands.append(int(line.split('log_rw_')[1].split(' ')[0]))
iIN += 1
if line.startswith('output'):
t = line.split('[')[1][:-1]
outputRange[iOUT, 0] = float(t.split(',')[0])
outputRange[iOUT, 1] = float(t.split(',')[1])
if 'log_rw_' in line:
bands.append(int(line.split('log_rw_')[1].split(' ')[0]))
iOUT += 1
if line.startswith('scaling'):
scaling = line.split('is ')[1].split(' ')[0].lower() == 'true'
nnIO = {
'inputVariables': inputVariables,
'inputRange': inputRange,
'outputRange': outputRange,
'bands': bands,
'scaling': scaling
}
return collections.namedtuple('NN_IO', nnIO.keys())(*nnIO.values())
def get_band_or_tiePointGrid(product, name, dtype='float32', reshape=True, subset=None):
##
# This function reads a band or tie-points, identified by its name <name>, from SNAP product <product>
# The fuction returns a numpy array of shape (height, width)
##
if subset is None:
height = product.getSceneRasterHeight()
width = product.getSceneRasterWidth()
sline, eline, scol, ecol = 0, height-1, 0, width -1
else:
sline,eline,scol,ecol = subset
height = eline - sline + 1
width = ecol - scol + 1
# var = np.zeros(width * height, dtype=dtype)
var = np.zeros(width * height)
if name in list(product.getBandNames()):
product.getBand(name).readPixels(scol, sline, width, height, var)
var = var.astype(dtype)
elif name in list(product.getTiePointGridNames()):
var.shape = (height, width)
for i,iglob in enumerate(range(sline,eline+1)):
for j,jglob in enumerate(range(scol,ecol+1)):
var[i, j] = product.getTiePointGrid(name).getPixelDouble(jglob, iglob)
var.shape = (height*width)
else:
raise Exception('{}: neither a band nor a tie point grid'.format(name))
if reshape:
var.shape = (height, width)
return var
def Level1_Reader(product, sensor, band_group='radiance', reshape=True, subset=None):
input_label = []
if sensor == 'S2MSI':
input_label = ['B1', 'B2', 'B3', 'B4', 'B5', 'B6', 'B7', 'B8', 'B8A', 'B9', 'B10', 'B11', 'B12']
elif sensor == 'OLCI':
if band_group == 'radiance':
input_label = ["Oa%02d_radiance"%(i+1) for i in range(21)]
elif band_group == 'solar_flux':
input_label = ["solar_flux_band_%d"%(i+1) for i in range(21)]
elif band_group == 'lambda0':
input_label = ["lambda0_band_%d"%(i+1) for i in range(21)]
# Initialise and read all bands contained in input_label (pixel x band)
if subset is None:
height = product.getSceneRasterHeight()
width = product.getSceneRasterWidth()
else:
sline,eline,scol,ecol = subset
height = eline - sline + 1
width = ecol - scol + 1
var = np.zeros((width * height, len(input_label)))
for i, bn in enumerate(input_label):
var[:,i] = get_band_or_tiePointGrid(product, bn, reshape=reshape, subset=subset)
return var
def get_yday(product,reshape=True, subset=None):
# Get product size
height_full = product.getSceneRasterHeight()
width_full = product.getSceneRasterWidth()
if subset is None:
height = height_full
width = width_full
else:
sline,eline,scol,ecol = subset
height = eline - sline + 1
width = ecol - scol + 1
## time handling for match-up files
if str(product.getFileLocation()).endswith('.txt') or str(product.getFileLocation()).endswith('.csv'):
if not subset is None:
print('Error: subset option not compatible with match-up file')
sys.exit(1)
yday = np.zeros((height, width))
for y in range(height):
for x in range(width):
a = product.getSceneTimeCoding().getMJD(PixelPos(x + 0.5, y + 0.5))
year, yday[y, x], hour = yearAndDoyAndHourUTC(a)
else:
## time handling for a scene
# Get yday of each row (full scene)
dstart = datetime.datetime.strptime(str(product.getStartTime()),'%d-%b-%Y %H:%M:%S.%f')
dstop = datetime.datetime.strptime(str(product.getEndTime()),'%d-%b-%Y %H:%M:%S.%f')
dstart = np.datetime64(dstart)
dstop = np.datetime64(dstop)
dpix = dstart + (dstop-dstart)/float(height_full-1.)*np.arange(height_full)
yday = [k.timetuple().tm_yday for k in dpix.astype(datetime.datetime)]
# Limit to subset
if subset:
yday = yday[sline:eline+1]
# Apply to all columns
yday = np.array(yday*width).reshape(width,height).transpose()
if not reshape:
yday = np.ravel(yday)
return yday
def radianceToReflectance_Reader(product, sensor = '', print_info=False, subset=None):
if print_info:
height = product.getSceneRasterHeight()
width = product.getSceneRasterWidth()
name = product.getName()
description = product.getDescription()
band_names = product.getBandNames()
print("Sensor: %s" % sensor)
print("Product: %s, %s" % (name, description))
print("Raster size: %d x %d pixels" % (width, height))
print("Start time: " + str(product.getStartTime()))
print("End time: " + str(product.getEndTime()))
print("Bands: %s" % (list(band_names)))
if sensor == 'OLCI':
rad = Level1_Reader(product, sensor, band_group='radiance',reshape=False, subset=subset)
solar_flux = Level1_Reader(product, sensor, band_group='solar_flux',reshape=False, subset=subset)
SZA = get_band_or_tiePointGrid(product, 'SZA', reshape=False, subset=subset)
refl = rad * np.pi / (solar_flux * np.cos(SZA.reshape(rad.shape[0],1)*np.pi/180.))
elif sensor == 'S2MSI':
refl = Level1_Reader(product, sensor,reshape=False, subset=subset)
return refl
def angle_Reader(product, sensor, subset=None):
if sensor == 'OLCI':
oaa = get_band_or_tiePointGrid(product, 'OAA', reshape=False, subset=subset)
oza = get_band_or_tiePointGrid(product, 'OZA', reshape=False, subset=subset)
saa = get_band_or_tiePointGrid(product, 'SAA', reshape=False, subset=subset)
sza = get_band_or_tiePointGrid(product, 'SZA', reshape=False, subset=subset)
elif sensor == 'S2MSI':
oaa = get_band_or_tiePointGrid(product, 'view_azimuth_mean', reshape=False, subset=subset)
oza = get_band_or_tiePointGrid(product, 'view_zenith_mean', reshape=False, subset=subset)
saa = get_band_or_tiePointGrid(product, 'sun_azimuth', reshape=False, subset=subset)
sza = get_band_or_tiePointGrid(product, 'sun_zenith', reshape=False, subset=subset)
return oaa, oza, saa, sza
def calculate_diff_azim(oaa, saa):
###
# MERIS/OLCI ground segment definition
raa = np.degrees(np.arccos(np.cos(np.radians(oaa - saa))))
###
# azimuth difference as input to the NN is defined in a range between 0° and 180°
## from c2rcc JAVA implementation
nn_raa = np.abs(180 + oaa - saa)
ID = np.array(nn_raa > 180)
if np.sum(ID) > 0:
nn_raa = 360 - nn_raa
return raa, nn_raa
def run_IdePix_processor(product, sensor):
### todo: check, if L1 flags are given as band 'quality_flags'
# (in CalValus extracts this single band representation of the flags might be missing.)
# calculate single band 'quality_flags' if necessary.
# invoke IdePix.
# define valid pixel expression.
idepixParameters = HashMap()
if product.getProductType() == 'CSV':
idepixParameters.put("computeCloudBuffer", 'false')
idepixParameters.put("computeCloudShadow", 'false')
else:
idepixParameters.put("computeCloudBuffer", 'true')
idepixParameters.put("cloudBufferWidth", '2')
idepixProducts = HashMap()
# idepixProducts.put("l1bProduct", product) # SNAP v6 ?
idepixProducts.put("sourceProduct", product)
idepix_product = None
if sensor == 'OLCI':
#idepix_product = GPF.createProduct("Idepix.Sentinel3.Olci", idepixParameters, product) # SNAP v6
idepix_product = GPF.createProduct("Idepix.Olci", idepixParameters, idepixProducts) # SNAP v7
elif sensor == 'S2MSI':
idepixParameters.put("computeCloudBufferForCloudAmbiguous", 'true')
idepix_product = GPF.createProduct("Idepix.S2", idepixParameters, idepixProducts) # SNAP v7
return idepix_product
def check_valid_pixel_expression_Idepix(product, sensor, subset=None):
valid_pixel_flag = None
if subset is None:
height = product.getSceneRasterHeight()
width = product.getSceneRasterWidth()
sline = 0
scol = 0
else:
sline,eline,scol,ecol = subset
height = eline - sline + 1
width = ecol - scol + 1
# quality_flags = np.zeros(width * height, dtype='uint32')
quality_flags = np.zeros(width * height)
product.getBand('pixel_classif_flags').readPixels(scol, sline, width, height, quality_flags)
quality_flags = quality_flags.astype(np.uint32)
if sensor == 'OLCI':
# Masks OLCI Idepix
invalid_mask = np.bitwise_and(quality_flags, 2 ** 0) == 2 ** 0
cloud_mask = np.bitwise_and(quality_flags, 2 ** 1) == 2 ** 1
cloudbuffer_mask = np.bitwise_and(quality_flags, 2 ** 4) == 2 ** 4
snowice_mask = np.bitwise_and(quality_flags, 2 ** 6) == 2 ** 6
invalid_mask = np.logical_or(np.logical_or(invalid_mask, snowice_mask), np.logical_or(cloud_mask, cloudbuffer_mask))
valid_pixel_flag = np.logical_not(invalid_mask)
if sensor == 'S2MSI':
# Masks S2MSI Idepix
invalid_mask = np.bitwise_and(quality_flags, 2 ** 0) == 2 ** 0
cloud_mask = np.bitwise_and(quality_flags, 2 ** 1) == 2 ** 1
cloudbuffer_mask = np.bitwise_and(quality_flags, 2 ** 4) == 2 ** 4
snowice_mask = np.bitwise_and(quality_flags, 2 ** 6) == 2 ** 6
invalid_mask = np.logical_or(np.logical_or(invalid_mask, snowice_mask),
np.logical_or(cloud_mask, cloudbuffer_mask))
valid_pixel_flag = np.logical_not(invalid_mask)
return valid_pixel_flag
def check_valid_pixel_expression_L1(product, sensor, subset=None):
valid_pixel_flag = None
if subset is None:
height = product.getSceneRasterHeight()
width = product.getSceneRasterWidth()
sline = 0
scol = 0
else:
sline,eline,scol,ecol = subset
height = eline - sline + 1
width = ecol - scol + 1
if sensor == 'OLCI':
# quality_flags = np.zeros(width * height, dtype='uint32')
quality_flags = np.zeros(width * height)
# match-up extractions from Calvalus do not have a 'quality_flags' band
if product.getBand('quality_flags') is None:
invalid_mask = np.zeros(width * height)
product.getBand('quality_flags.invalid').readPixels(scol, sline, width, height, invalid_mask)
invalid_mask = invalid_mask.astype(np.uint32)
land_mask = np.zeros(width * height)
product.getBand('quality_flags.land').readPixels(scol, sline, width, height, land_mask)
land_mask = land_mask.astype(np.uint32)
coastline_mask = np.zeros(width * height)
product.getBand('quality_flags.coastline').readPixels(scol, sline, width, height, coastline_mask)
coastline_mask = coastline_mask.astype(np.uint32)
inland_mask = np.zeros(width * height)
product.getBand('quality_flags.fresh_inland_water').readPixels(scol, sline, width, height, inland_mask)
inland_mask = inland_mask.astype(np.uint32)
land_mask = coastline_mask | (land_mask & ~inland_mask)
bright_mask = np.zeros(width * height)
product.getBand('quality_flags.bright').readPixels(scol, sline, width, height, bright_mask)
bright_mask = bright_mask.astype(np.uint32)
invalid_mask = np.logical_or(invalid_mask, np.logical_or(land_mask, bright_mask))
valid_pixel_flag = np.logical_not(invalid_mask)
else:
product.getBand('quality_flags').readPixels(scol, sline, width, height, quality_flags)
quality_flags = quality_flags.astype(np.uint32)
# Masks OLCI L1
## flags: 31=land 30=coastline 29=fresh_inland_water 28=tidal_region 27=bright 26=straylight_risk 25=invalid
## 24=cosmetic 23=duplicated 22=sun-glint_risk 21=dubious 20->00=saturated@Oa01->saturated@Oa21
## todo: could also include simple bright NIR test: rho_toa(865nm) < 0.2
invalid_mask = np.bitwise_and(quality_flags, 2 ** 25) == 2 ** 25
land_mask = np.bitwise_and(quality_flags, 2 ** 31) == 2 ** 31
coastline_mask = np.bitwise_and(quality_flags, 2 ** 30) == 2 ** 30
inland_mask = np.bitwise_and(quality_flags, 2 ** 29) == 2 ** 29
land_mask = coastline_mask | (land_mask & ~inland_mask)
bright_mask = np.bitwise_and(quality_flags, 2 ** 27) == 2 ** 27
invalid_mask = np.logical_or(invalid_mask , np.logical_or( land_mask , bright_mask))
valid_pixel_flag = np.logical_not(invalid_mask)
elif sensor == 'S2MSI':
#TODO: set valid pixel expression L1C S2
valid_pixel_flag = np.ones(width * height, dtype='uint32')
b8 = get_band_or_tiePointGrid(product, 'B8', reshape=False, subset=subset)
valid_pixel_flag = np.logical_and(np.array(b8 > 0), np.array(b8 < 0.1))
return valid_pixel_flag
def apply_forwardNN_TF(log_iop, sun_zenith, view_zenith, diff_azimuth, valid):
"""
Apply the forwardNN: IOP to rhow
input: numpy array log_iop, shape = (Npixels x log_iops= (log_apig, log_adet, log a_gelb, log_bpart, log_bwit)),
np.array sza, shape = (Npixels,)
np.array oza, shape = (Npixels,)
np.array raa, shape = (Npixels,); range: 0-180
returns: np.array rhow, shape = (Npixels, wavelengths)
"""
# Initialise output
nBands = len(iband_forwardNN)
rhow = np.zeros((log_iop.shape[0], nBands)) + np.NaN
# Initialise input
nInput = 3 + 5 # angle + IOPs
if 'temperature' in nnForward_IO.inputVariables:
nInput +=1
if 'salinity' in nnForward_IO.inputVariables:
nInput += 1
NN_input = np.zeros((log_iop.shape[0], nInput)) -1. # CARE -1 used by default for IOP when niop < 5
# Prepare the NN
if 'cos_' in nnForward_IO.inputVariables[0]:
NN_input[:,0] = np.cos(sun_zenith * np.pi / 180.)
NN_input[:,1] = np.cos(view_zenith * np.pi / 180.)
NN_input[:,2] = np.cos(diff_azimuth * np.pi / 180.)
else:
NN_input[:, 0] = sun_zenith
NN_input[:, 1] = view_zenith
NN_input[:, 2] = diff_azimuth
i_input = 3
if 'temperature' in nnForward_IO.inputVariables:
NN_input[:,i_input] = 15. # default temperature
i_input += 1
if 'salinity' in nnForward_IO.inputVariables:
NN_input[:,i_input] = 35. # default salinity
i_input += 1
for i in range(log_iop.shape[1]):
NN_input[:,i_input+i] = log_iop[:,i]
# Scale inputs if necessary, first constraining in the range
if nnForward_IO.scaling:
NN_input[:,i_input:] = check_and_constrain_iop(NN_input[:,i_input:], nnForward_IO)
NN_input = scale_minmax(NN_input, nnForward_IO.inputRange)
# Limit to valid pixels
NN_input = np.array(NN_input[valid, :], dtype='float32')
# Launch NN
if session is not None:
log_rhow = nn_forward(NN_input).eval(session=session)
else:
log_rhow = nn_forward(NN_input)
# Scale outputs if necessary
if nnForward_IO.scaling:
log_rhow = scale_minmax(np.array(log_rhow), nnForward_IO.outputRange, reverse=True)
# Get NN output
for i in range(nBands):
rhow[valid,i] = np.exp(log_rhow[:,i])
return rhow
def apply_backwardNN_TF(rhow, sun_zenith, view_zenith, diff_azimuth, valid, NN_IO, NNIOP=False):
"""
Apply the backwardNN: rhow to IOP
input: numpy array rhow, shape = (Npixels x rhow = (log_rw_band1, log_rw_band2_.... )),
np.array sza, shape = (Npixels,)
np.array oza, shape = (Npixels,)
np.array raa, shape = (Npixels,); range: 0-180
returns: np.array log_iop, shape = (Npixels x log_iop= (log_apig, log_adet, log a_gelb, log_bpart, log_bwit))
T, S: currently constant #TODO take ECMWF temperature at sea surface?
"""
# Initialise output
log_iop = np.zeros((rhow.shape[0], 5))
log_iop[:] = NN_IO.outputRange[:,0] # set default values, for invalid NN inversion (rhow<0)
# Initialise input
rhow_pos = np.all(rhow>0, axis=1) # limit to rhow >0
valid2 = valid & rhow_pos
nvalid = np.count_nonzero(valid2)
nInput = 3 + rhow.shape[1] # angle + log_rw
if 'temperature' in NN_IO.inputVariables:
nInput +=1
if 'salinity' in NN_IO.inputVariables:
nInput += 1
NN_input = np.zeros((nvalid, nInput), dtype='float32')
# Prepare the NN
if 'cos_' in NN_IO.inputVariables[0]:
NN_input[:,0] = np.cos(sun_zenith[valid2] * np.pi / 180.)
NN_input[:,1] = np.cos(view_zenith[valid2] * np.pi / 180.)
NN_input[:,2] = np.cos(diff_azimuth[valid2] * np.pi / 180.)
else:
NN_input[:, 0] = sun_zenith[valid2]
NN_input[:, 1] = view_zenith[valid2]
NN_input[:, 2] = diff_azimuth[valid2]
i_input = 3
if 'temperature' in NN_IO.inputVariables:
NN_input[:,i_input] = 15. # default temperature
i_input += 1
if 'salinity' in NN_IO.inputVariables:
NN_input[:,i_input] = 35. # default salinity
i_input += 1
NN_input[:,i_input:] = np.log(rhow[valid2,:])
# Scale inputs if necessary, , first constraining log_rw in the range
if NN_IO.scaling:
NN_input[:,i_input:] = check_and_constrain_rw(NN_input[:,i_input:], NN_IO)
NN_input = scale_minmax(NN_input, NN_IO.inputRange)
# Launch the NN
if NNIOP:
if session is not None:
log_iop[valid2,:] = nn_backward_iop(NN_input).eval(session=session)
else:
log_iop[valid2,:] = nn_backward_iop(NN_input)
else:
if session is not None:
log_iop[valid2,:] = nn_backward(NN_input).eval(session=session)
else:
log_iop[valid2,:] = nn_backward(NN_input)
# Scale outputs if necessary
if NN_IO.scaling:
log_iop[valid2,:] = scale_minmax(log_iop[valid2,:], NN_IO.outputRange, reverse=True)
return log_iop
def write_BalticP_AC_Product(product, baltic__product_path, sensor, spectral_dict, scalar_dict=None,
copyOriginalProduct=False, outputProductFormat="BEAM-DIMAP", addname='',
add_Idepix_Flags=False, idepixProduct=None, add_L2Flags=False, L2FlagArray=None,
add_Geometry=False, subset=None):
# Initialise the output product
File = jpy.get_type('java.io.File')
width = product.getSceneRasterWidth()
height = product.getSceneRasterHeight()
bandShape = (height, width)
if subset is None:
height_subset = height
width_subset = width
sline, eline, scol, ecol = 0, height-1, 0, width -1
else:
sline,eline,scol,ecol = subset
height_subset = eline - sline + 1
width_subset = ecol - scol + 1
bandShape_subset = (height_subset, width_subset)
dirname = os.path.dirname(baltic__product_path)
outname, ext = os.path.splitext(os.path.basename(baltic__product_path))
if outputProductFormat == "BEAM-DIMAP":
baltic__product_path = os.path.join(dirname, outname + addname +'.dim')
elif outputProductFormat == 'CSV':
baltic__product_path = os.path.join(dirname, outname + addname +'.csv')
balticPACProduct = Product('balticPAC', 'balticPAC', width, height)
balticPACProduct.setFileLocation(File(baltic__product_path))
# Copy geocoding
ProductUtils.copyGeoCoding(product, balticPACProduct)
# replacement by Tonio below does not work, geocoding is on the full image, not subset
"""# PixelSubsetRegion = jpy.get_type('org.esa.snap.core.subset.PixelSubsetRegion')
ProductSubsetDef = jpy.get_type('org.esa.snap.core.dataio.ProductSubsetDef')
# subset_region = PixelSubsetRegion(scol, sline, ecol, eline)
subset_def = ProductSubsetDef()
subset_def.setRegion(scol, sline, width, height)
product.transferGeoCodingTo(balticPACProduct, subset_def)"""
# writer = ProductIO.getProductWriter(outputProductFormat)
# writer.writeProductNodes(balticPACProduct, baltic__product_path)
# Define total number of bands (TOA)
if (sensor == 'OLCI'):
nbands = 21
elif (sensor == 'S2MSI'):
nbands = 13
for key in spectral_dict.keys():
data = spectral_dict[key].get('data')
if not data is None:
nbands_key = data.shape[-1]
if outputProductFormat == 'BEAM-DIMAP':
if sensor == 'OLCI':
bsources = [product.getBand("Oa%02d_radiance" % (i + 1)) for i in range(nbands)]
elif sensor == 'S2MSI':
bsources = [product.getBand("B%d" % (i + 1)) for i in range(8)]
bsources.append(product.getBand('B8A'))
[bsources.append(product.getBand("B%d" % (i + 9))) for i in range(4)]
sourceData = np.ndarray(bandShape,dtype='float32') + np.nan # create unique instance to avoid MemoryError
for i in range(nbands_key):
brtoa_name = key + "_" + str(i + 1)
# print(brtoa_name)
band = balticPACProduct.addBand(brtoa_name, ProductData.TYPE_FLOAT32)
if outputProductFormat == 'BEAM-DIMAP':
ProductUtils.copySpectralBandProperties(bsources[i], band)
band.ensureRasterData()
band.setNoDataValue(np.nan)
band.setNoDataValueUsed(True)
sourceData[sline:eline+1,scol:ecol+1] = data[:, i].reshape(bandShape_subset).astype('float32')
band.setRasterData(ProductData.createInstance(sourceData))
band.setSourceImage(band.getSourceImage())
# Create empty bands for scalar fields
if not scalar_dict is None:
sourceData = np.ndarray(bandShape,dtype='float32') + np.nan # create unique instance to avoid MemoryError
for key in scalar_dict.keys():
singleBand = balticPACProduct.addBand(key, ProductData.TYPE_FLOAT32)
singleBand.ensureRasterData()
singleBand.setNoDataValue(np.nan)
singleBand.setNoDataValueUsed(True)
data = scalar_dict[key].get('data')
if not data is None:
sourceData[sline:eline+1,scol:ecol+1] = data.reshape(bandShape_subset).astype('float32')
singleBand.setRasterData(ProductData.createInstance(sourceData))
singleBand.setSourceImage(singleBand.getSourceImage())
if copyOriginalProduct:
originalBands = product.getBandNames()
balticBands = balticPACProduct.getBandNames()
for bb in balticBands:
originalBands = [ob for ob in originalBands if ob != bb]
for ob in originalBands:
singleBand = balticPACProduct.addBand(ob, ProductData.TYPE_FLOAT32)
singleBand.ensureRasterData()
singleBand.setNoDataValue(np.nan)
singleBand.setNoDataValueUsed(True)
data = get_band_or_tiePointGrid(product,ob)
sourceData = data.reshape(bandShape).astype('float32')
singleBand.setRasterData(ProductData.createInstance(sourceData))
singleBand.setSourceImage(singleBand.getSourceImage())
if add_Idepix_Flags:
# flagBand = balticPACProduct.addBand('pixel_classif_flags', ProductData.TYPE_INT32)
# flagBand.ensureRasterData()
# flagBand.setDescription('Idepix flag information')
# flagBand.setNoDataValue(np.nan)
# flagBand.setNoDataValueUsed(True)
#
# data = get_band_or_tiePointGrid(idepixProduct, 'pixel_classif_flags')
# sourceData = np.array(data, dtype='int32').astype('int32')
# # flagBand.setRasterData(ProductData.createInstance(sourceData))
# for x in range(width):
# for y in range(height):
# flagBand.setPixelInt(x, y, int(sourceData[y][x]))
# flagBand.setSourceImage(flagBand.getSourceImage())
#
# idepixFlagCoding = FlagCoding('pixel_classif_flags')
# flagNames = list(idepixProduct.getAllFlagNames())
# IDflags = 'pixel_classif_flags'
# flagNames = [fn[(len(IDflags)+1):] for fn in flagNames if IDflags in fn]
# for i, fn in enumerate(flagNames):
# idepixFlagCoding.addFlag(fn, 2**i, fn)
# balticPACProduct.getFlagCodingGroup().add(idepixFlagCoding)
# flagBand.setSampleCoding(idepixFlagCoding)
ProductUtils.copyFlagBands(idepixProduct, balticPACProduct, True)
if add_L2Flags:
flagBand = balticPACProduct.addBand('baltic_L2_flags', ProductData.TYPE_INT32)
flagBand.ensureRasterData()
flagBand.setDescription('L2 flag information for the baltic+ AC')
flagBand.setNoDataValue(np.nan)
flagBand.setNoDataValueUsed(True)
sourceData = np.array(L2FlagArray, dtype='int32').reshape(bandShape)
# flagBand.setRasterData(ProductData.createInstance(sourceData))
for x in range(width):
for y in range(height):
flagBand.setPixelInt(x, y, int(sourceData[y][x]))
flagBand.setSourceImage(flagBand.getSourceImage())
L2FlagCoding = FlagCoding('baltic_L2_flags')
flagNames = ['OOR_NN_IOP', 'OOR_NN_normalisation', 'NELDER_MEAD_FAIL']
flagDescription = ['input IOPs to forwardNN out of range. at least one IOP has been constrained.',
'input rho_w to NormalisationNN out of range. at least one rho_w has been constrained.',
'Nelder-Mead Optimisation failed.']
#IDflags = 'baltic_L2_flags'
#flagNames = [fn[(len(IDflags) + 1):] for fn in flagNames if IDflags in fn]
i = 0
for fn, dscr in zip(flagNames, flagDescription):
L2FlagCoding.addFlag(fn, 2 ** i, dscr)
i += 1
balticPACProduct.getFlagCodingGroup().add(L2FlagCoding)
flagBand.setSampleCoding(L2FlagCoding)
if add_Geometry and not copyOriginalProduct:
oaa, oza, saa, sza = angle_Reader(product, sensor, subset=subset)
if sensor == 'OLCI':
geomNames = ['OAA', 'OZA', 'SAA', 'SZA']
elif sensor == 'S2MSI':
geomNames = ['view_azimuth_mean', 'view_zenith_mean', 'sun_azimuth', 'sun_zenith']
dataList = [oaa, oza, saa, sza]
sourceData = np.ndarray(bandShape,dtype='float32') + np.nan # create unique instance to avoid MemoryError
for gn, data in zip(geomNames, dataList):
singleBand = balticPACProduct.addBand(gn, ProductData.TYPE_FLOAT32)
singleBand.ensureRasterData()
singleBand.setNoDataValue(np.nan)
singleBand.setNoDataValueUsed(True)
sourceData[sline:eline+1,scol:ecol+1] = data.reshape(bandShape_subset)
singleBand.setRasterData(ProductData.createInstance(sourceData))
singleBand.setSourceImage(singleBand.getSourceImage())
if outputProductFormat == 'BEAM-DIMAP':
# Set auto grouping
autoGroupingString = ':'.join(spectral_dict.keys())
balticPACProduct.setAutoGrouping(autoGroupingString)
GPF.writeProduct(balticPACProduct, File(baltic__product_path), outputProductFormat, False, ProgressMonitor.NULL)
balticPACProduct.closeIO()
def polymer_matrix(bands_sat,bands,valid,rho_g,rho_r,sza,oza,wavelength):
"""
Compute matrices associated to the polynomial modelling of the atmosphere (POLYMER)
Care: direct matrice (forward model) is for 'bands_sat', while inverse (backward model) is limited to 'bands'
"""
# Define matrix of polynomial modelling (c0 T0 + c1 lambda^-1 + c2 rho_R)
ncoef = 3
nband = len(bands)
nband_sat = len(bands_sat)
npix = rho_g.shape[0]
Aatm = np.zeros((npix, nband_sat, ncoef), dtype='float32') # Care, defined for bands_sat
Aatm_inv = np.zeros((npix, ncoef, nband), dtype='float32') # Care, defined for only bands
# Indices of bands_corr in all bands
iband = np.searchsorted(bands_sat, bands)
# Compute T0
taum = 0.00877*((wavelength/1000.)**(-4.05))
air_mass = 1./np.cos(np.radians(sza))+1./np.cos(np.radians(oza))
rho_g0 = 0.02
factor = (1-0.5*np.exp(-rho_g/rho_g0))*air_mass
T0 = np.exp(-taum*factor[:,None])
Aatm[:,:,0] = T0
Aatm[:,:,1] = (wavelength/1000.)**-1.
Aatm[:,:,2] = rho_r
# Compute pseudo inverse: A* = ((A'.A)^(-1)).A' /!\ limited to bands
Aatm_corr = Aatm[:,iband,:]
Aatm_inv[valid] = np.linalg.pinv(Aatm_corr[valid])
return Aatm, Aatm_inv
def check_and_constrain_iop(log_iop, NN_IO):
for i, var in enumerate(['log_apig', 'log_adet', 'log_agelb', 'log_bpart', 'log_bwit']):
j = NN_IO.inputVariables.index(var)
mi = NN_IO.inputRange[j,0]
ma = NN_IO.inputRange[j,1]
log_iop[:, i][log_iop[:, i] < mi] = mi
log_iop[:, i][log_iop[:, i] > ma] = ma
return log_iop
def check_and_constrain_rw(log_rw, NN_IO):
for i, band in enumerate(NN_IO.bands):
var = 'log_rw_%d'%band
j = NN_IO.inputVariables.index(var)
mi = NN_IO.inputRange[j,0]
ma = NN_IO.inputRange[j,1]
log_rw[:, i][log_rw[:, i] < mi] = mi
log_rw[:, i][log_rw[:, i] > ma] = ma
return log_rw
def baltic_AC(scene_path='', filename='', outpath='', sensor='', platform='', subset=None, addName = '', outputSpectral=None,
outputScalar=None, correction='HYGEOS', copyOriginalProduct=False, outputProductFormat="BEAM-DIMAP",
atmosphericAuxDataPath = None, niop=5, add_Idepix_Flags=True, add_L2Flags=False, add_c2rccIOPs=False,
runAC=True, NNversion='v1_baltic+', NNIOPversion='c2rcc_20171221'):
"""
Main function to run the Baltic+ AC based on forward NN
correction: 'HYGEOS' or 'IPF' for Rayleigh+glint correction
"""
# Read the NNs
read_NNs(sensor, NNversion, NNIOPversion)
# Get sensor & NN bands
global bands_sat, bands_corr, bands_chi2, bands_forwardNN, bands_backwardNN, bands_abs
global iband_corr, iband_chi2, iband_forwardNN, iband_backwardNN, iband_backwardNNIOP, iband_abs
bands_sat, bands_corr, bands_chi2, bands_abs = get_bands.main(sensor)
nbands = len(bands_sat)
# Get band of NNs
bands_forwardNN = np.array(nnForward_IO.bands)
bands_backwardNN = np.array(nnBackward_IO.bands)
bands_backwardNNIOP = np.array(nnBackwardIOP_IO.bands)
# Check NNs bands
for NN, band_set in zip(['forward_NN','backward_NN','backward_NNIOP'], [bands_forwardNN, bands_backwardNN, bands_backwardNNIOP]):
if not set(band_set).issubset(set(bands_sat)):
print("Error: bands of %s does not match sensor band:"%NN, band_set)
sys.exit(1)
# Check bands_corr and band_chi2 are provided by forward NN. If not, take intersection
bands_AC = {
'bands_corr': bands_corr,
'bands_chi2': bands_chi2
}
for band_set, bands_value in zip(bands_AC, bands_AC.values()):
if not set(bands_value).issubset(set(bands_forwardNN)):
print("WARNING: %s is not a subset of bands_forwardNN:"%band_set)
# Searching intersection
bands_value = list(set(bands_value) & set(bands_forwardNN))
if len(bands_value) == 0:
print(" Intersection empty between %s and bands_forwardNN - Aborted"%band_set)
sys.exit(1)
else:
bands_value.sort()
bands_AC[band_set] = bands_value
print(" %s limited to "%band_set, bands_AC[band_set])
bands_corr = bands_AC['bands_corr']
bands_chi2 = bands_AC['bands_chi2']
# Identify index of bands
iband_corr = np.searchsorted(bands_sat, bands_corr)
iband_chi2 = np.searchsorted(bands_sat, bands_chi2)
iband_forwardNN = np.searchsorted(bands_sat, bands_forwardNN)
iband_backwardNN = np.searchsorted(bands_sat, bands_backwardNN)
iband_backwardNNIOP = np.searchsorted(bands_sat, bands_backwardNNIOP)
iband_abs = np.searchsorted(bands_sat, bands_abs)
# Initialising a product for Reading with snappy
product = snp.ProductIO.readProduct(os.path.join(scene_path, filename))
if sensor=='OLCI' and product.getProductType()=='CSV':
product.setProductType('OL_1_')
# Resampling S2MSI to 60m
if sensor == "S2MSI" and product.isMultiSize():
print( "Resample MSI data")
parameters = HashMap()
parameters.put('resolution', '60')
parameters.put('upsampling', 'Bicubic')
parameters.put('downsampling', 'Mean') #
parameters.put('flagDownsampling', 'FlagOr') # 'First', 'FlagAnd'
product = GPF.createProduct('S2Resampling', parameters, product)
# Get scene size
if subset is None:
height = product.getSceneRasterHeight()
width = product.getSceneRasterWidth()
else:
sline,eline,scol,ecol = subset
height = eline - sline + 1
width = ecol - scol + 1
npix = width*height
# Read L1B product and convert Radiance to reflectance
rho_toa = radianceToReflectance_Reader(product, sensor=sensor, subset=subset)
# Read geometry and compute relative azimuth angle
oaa, oza, saa, sza = angle_Reader(product, sensor, subset=subset)
raa, nn_raa = calculate_diff_azim(oaa, saa)
# Classify pixels with Level-1 flags
valid = check_valid_pixel_expression_L1(product, sensor, subset=subset)
# Check valid geometry (necessary for S2MSI)
valid[np.isnan(oza)] = False
valid[np.isnan(sza)] = False
valid[np.isnan(raa)] = False
print("%d valid pixels on %d"%(np.sum(valid), len(valid)))
# Apply Idepix
if add_Idepix_Flags:
print("Launch Idepix")
if product.getBand('quality_flags') is None: #Idepix needs a band of this name to run. L1-flags are evaluated st a different step, so values can be zero here.
band = product.addBand('quality_flags', ProductData.TYPE_INT32)
band.setNoDataValue(np.nan)
band.setNoDataValueUsed(True)
sourceData = np.zeros((product.getSceneRasterHeight(), product.getSceneRasterWidth()), dtype='uint32') # Idepix launched on full scene, not subset
band.setRasterData(ProductData.createInstance(sourceData))
idepixProduct = run_IdePix_processor(product, sensor)
validIdepix = check_valid_pixel_expression_Idepix(idepixProduct, sensor, subset=subset)
print('Idepix valid', np.sum(validIdepix))
valid = np.logical_and(valid, validIdepix)
print('total valid', np.sum(valid))
else:
idepixProduct=None
# Read wavelength (per-pixel for OLCI) and geolocation
if sensor == 'OLCI':
# Read per-pixel wavelength
wavelength = Level1_Reader(product, sensor, 'lambda0', reshape=False, subset=subset)
## if wavelength == -1: spectrum is invald!
ID = np.all(wavelength>0., axis=1)
valid = np.logical_and(ID, valid)
print('total valid 2', np.sum(valid))
# Read latitude, longitude
latitude = get_band_or_tiePointGrid(product, 'latitude', reshape=False, subset=subset)
longitude = get_band_or_tiePointGrid(product, 'longitude', reshape=False, subset=subset)
elif sensor == 'S2MSI':
# Duplicate wavelengths for all pixels
wavelength = np.tile(bands_sat,(len(sza),1)) #TODO: integrate band with S2 SRF
# Read latitude, longitude
latitude, longitude = getGeoPositionsForS2Product(product, reshape=False, subset=subset)
# Read day in the year
yday = get_yday(product, reshape=False, subset=subset)
# Read meteo data
print( "Read meteo data")