-
Notifications
You must be signed in to change notification settings - Fork 12
/
s1_annotation.py
1258 lines (1016 loc) · 44.5 KB
/
s1_annotation.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
'''
A module to load annotation files for Sentinel-1 IW SLC SAFE data
To be used for the class "Sentinel1BurstSlc"
'''
from __future__ import annotations
from dataclasses import dataclass
import datetime
import os
import warnings
import zipfile
from types import SimpleNamespace
import lxml.etree as ET
import numpy as np
from isce3.core import speed_of_light
from packaging import version
from scipy.interpolate import InterpolatedUnivariateSpline, interp1d
# Minimum IPF version from which the S1 product's Noise Annotation
# Data Set (NADS) includes azimuth noise vector annotation
min_ipf_version_az_noise_vector = version.parse('2.90')
# Minimum IPF version from which the RFI information gets available
# source: "Sentinel-1: Using the RFI annotations", reference no: MPC-0540,
# URL: (https://sentinel.esa.int/documents/247904/1653442/
# DI-MPC-OTH-0540-1-0-RFI-Tech-Note.pdf)
RFI_INFO_AVAILABLE_FROM = version.Version('3.40')
# Dictionary of the fields in RFI information, and their data type castor
dict_datatype_rfi = {
"swath": str,
"azimuthTime": lambda T: datetime.datetime.strptime(T, '%Y-%m-%dT%H:%M:%S.%f'),
"inBandOutBandPowerRatio": float,
"percentageAffectedLines": float,
"avgPercentageAffectedSamples": float,
"maxPercentageAffectedSamples": float,
"numSubBlocks": int,
"subBlockSize": int,
"maxPercentageAffectedBW": float,
"percentageBlocksPersistentRfi": float,
"maxPercentageBWAffectedPersistentRfi": float
}
def element_to_dict(elem_in: ET, dict_tree: dict = None):
'''
Recursively parse the element tree,
return the results as SimpleNameSpace
Parameters
----------
elem_in: ElementTree
Input element tree object
dict_tree: dict
Dictionary to be populated
Returns
-------
dict_tree: dict
A populated dictionary by `elem_in`
'''
if dict_tree is None:
dict_tree = {}
key_elem = elem_in.tag
child_elem = list(elem_in.iterchildren())
if len(child_elem) == 0:
# Reached the tree end
text_elem = elem_in.text
if key_elem in dict_datatype_rfi:
elem_datatype = dict_datatype_rfi[key_elem]
else:
warnings.warn(f'Data type for element {key_elem} is not defined. '
f'Casting the value "{text_elem}" as string.')
elem_datatype = str
dict_tree[key_elem] = elem_datatype(text_elem)
else:
dict_tree[key_elem] = {}
for et_child in child_elem:
element_to_dict(et_child, dict_tree[key_elem])
return dict_tree
@dataclass
class AnnotationBase:
'''
A virtual base class of the inheriting annotation class i.e. Product, Calibration, and Noise.
Not intended for standalone use.
'''
xml_et: ET
@classmethod
def _parse_scalar(cls, path_field: str, str_type: str):
'''A class method that parse the scalar value in AnnotationBase.xml_et
Parameters
----------
path_field : str
Field in the xml_et to parse
str_type : str
Specify how the texts in the field will be parsed.
accepted values:
{'datetime', 'scalar_int', 'scalar_float', 'vector_int', 'vector_float', 'str'}
Returns
-------
val_out: {datetime.datetime, int, float, np.array, str}
Parsed data in the annotation
Datatype of vel_out follows str_type.
val_out becomes np.array when str_type is vector*
'''
elem_field = cls.xml_et.find(path_field)
if str_type == 'datetime':
val_out = datetime.datetime.strptime(elem_field.text, '%Y-%m-%dT%H:%M:%S.%f')
elif str_type == 'scalar_int':
val_out = int(elem_field.text)
elif str_type == 'scalar_float':
val_out = float(elem_field.text)
elif str_type == 'vector_int':
val_out = np.array([int(strin) for strin in elem_field.text.split()])
elif str_type == 'vector_float':
val_out = np.array([float(strin) for strin in elem_field.text.split()])
elif str_type == 'str':
val_out = elem_field.text
else:
raise ValueError(f'Unsupported type the element: "{str_type}"')
return val_out
@classmethod
def _parse_vectorlist(cls, name_vector_list: str, name_vector: str, str_type: str):
'''A class method that parse the list of the values from xml_et in the class
Parameters
----------
name_vector_list : str
List Field in the xml_et to parse
name_vector : str
Name of the field in each elements of the VectorList
(e.g. 'noiseLut' in 'noiseVectorList')
str_type : str
Specify how the texts in the field will be parsed
accepted values:
{'datetime', 'scalar_int', 'scalar_float', 'vector_int', 'vector_float', 'str'}
Returns
-------
val_out: list
Parsed data in the annotation
'''
element_to_parse = cls.xml_et.find(name_vector_list)
num_element = len(element_to_parse)
list_out = [None]*num_element
if str_type == 'datetime':
for i,elem in enumerate(element_to_parse):
str_elem = elem.find(name_vector).text
list_out[i] = datetime.datetime.strptime(str_elem, '%Y-%m-%dT%H:%M:%S.%f')
list_out = np.array(list_out)
elif str_type == 'scalar_int':
for i,elem in enumerate(element_to_parse):
str_elem = elem.find(name_vector).text
list_out[i] = int(str_elem)
elif str_type == 'scalar_float':
for i,elem in enumerate(element_to_parse):
str_elem = elem.find(name_vector).text
list_out[i] = float(str_elem)
elif str_type == 'vector_int':
for i,elem in enumerate(element_to_parse):
str_elem = elem.find(name_vector).text
list_out[i] = np.array([int(strin) for strin in str_elem.split()])
elif str_type == 'vector_float':
for i,elem in enumerate(element_to_parse):
str_elem = elem.find(name_vector).text
list_out[i] = np.array([float(strin) for strin in str_elem.split()])
elif str_type == 'str':
list_out = element_to_parse[0].find(name_vector).text
else:
raise ValueError(f'Cannot recognize the type of the element: {str_type}')
return list_out
@dataclass
class CalibrationAnnotation(AnnotationBase):
'''Reader for Calibration Annotation Data Set (CADS)'''
basename_annotation: str
list_azimuth_time: np.ndarray
list_line: list
list_pixel: None
list_sigma_nought: list
list_beta_nought : list
list_gamma: list
list_dn: list
@classmethod
def from_et(cls, et_in: ET, path_annotation: str):
'''
Extracts the list of calibration informaton from etree from
the Calibration Annotation Data Set (CADS).
Parameters:
-----------
et_in: ET
ElementTree From CADS .xml file
Returns:
--------
cls: CalibrationAnnotation
Instance of CalibrationAnnotation initialized by the input parameter
'''
cls.xml_et = et_in
cls.basename_annotation = \
os.path.basename(path_annotation)
cls.list_azimuth_time = \
cls._parse_vectorlist('calibrationVectorList',
'azimuthTime',
'datetime')
cls.list_line = \
cls._parse_vectorlist('calibrationVectorList',
'line',
'scalar_int')
cls.list_pixel = \
cls._parse_vectorlist('calibrationVectorList',
'pixel',
'vector_int')
cls.list_sigma_nought = \
cls._parse_vectorlist('calibrationVectorList',
'sigmaNought',
'vector_float')
cls.list_beta_nought = \
cls._parse_vectorlist('calibrationVectorList',
'betaNought',
'vector_float')
cls.list_gamma = \
cls._parse_vectorlist('calibrationVectorList',
'gamma',
'vector_float')
cls.list_dn = \
cls._parse_vectorlist('calibrationVectorList',
'dn',
'vector_float')
return cls
@dataclass
class NoiseAnnotation(AnnotationBase):
'''
Reader for Noise Annotation Data Set (NADS) for IW SLC
Based on ESA documentation: "Thermal Denoising of Products Generated by the S-1 IPF"
'''
basename_annotation: str
rg_list_azimuth_time: np.ndarray
rg_list_line: list
rg_list_pixel: list
rg_list_noise_range_lut: list
az_first_azimuth_line: int
az_first_range_sample: int
az_last_azimuth_line: int
az_last_range_sample: int
az_line: np.ndarray
az_noise_azimuth_lut: np.ndarray
@classmethod
def from_et(cls,et_in: ET, ipf_version: version.Version, path_annotation: str):
'''
Extracts list of noise information from etree
Parameter
----------
et_in : xml.etree.ElementTree
Parsed NADS annotation .xml
Return
-------
cls: NoiseAnnotation
Parsed NADS from et_in
'''
cls.xml_et = et_in
cls.basename_annotation = os.path.basename(path_annotation)
if ipf_version < min_ipf_version_az_noise_vector: # legacy SAFE data
cls.rg_list_azimuth_time = \
cls._parse_vectorlist('noiseVectorList',
'azimuthTime',
'datetime')
cls.rg_list_line = \
cls._parse_vectorlist('noiseVectorList',
'line',
'scalar_int')
cls.rg_list_pixel = \
cls._parse_vectorlist('noiseVectorList',
'pixel',
'vector_int')
cls.rg_list_noise_range_lut = \
cls._parse_vectorlist('noiseVectorList',
'noiseLut',
'vector_float')
cls.az_first_azimuth_line = None
cls.az_first_range_sample = None
cls.az_last_azimuth_line = None
cls.az_last_range_sample = None
cls.az_line = None
cls.az_noise_azimuth_lut = None
else:
cls.rg_list_azimuth_time = \
cls._parse_vectorlist('noiseRangeVectorList',
'azimuthTime',
'datetime')
cls.rg_list_line = \
cls._parse_vectorlist('noiseRangeVectorList',
'line',
'scalar_int')
cls.rg_list_pixel = \
cls._parse_vectorlist('noiseRangeVectorList',
'pixel',
'vector_int')
cls.rg_list_noise_range_lut = \
cls._parse_vectorlist('noiseRangeVectorList',
'noiseRangeLut',
'vector_float')
cls.az_first_azimuth_line = \
cls._parse_vectorlist('noiseAzimuthVectorList',
'firstAzimuthLine',
'scalar_int')[0]
cls.az_first_range_sample = \
cls._parse_vectorlist('noiseAzimuthVectorList',
'firstRangeSample',
'scalar_int')[0]
cls.az_last_azimuth_line = \
cls._parse_vectorlist('noiseAzimuthVectorList',
'lastAzimuthLine',
'scalar_int')[0]
cls.az_last_range_sample = \
cls._parse_vectorlist('noiseAzimuthVectorList',
'lastRangeSample',
'scalar_int')[0]
cls.az_line = \
cls._parse_vectorlist('noiseAzimuthVectorList',
'line',
'vector_int')[0]
cls.az_noise_azimuth_lut = \
cls._parse_vectorlist('noiseAzimuthVectorList',
'noiseAzimuthLut',
'vector_float')[0]
return cls
@dataclass
class ProductAnnotation(AnnotationBase):
'''
Reader for L1 Product annotation for IW SLC
For Elevation Antenna Pattern (EAP) correction
'''
image_information_slant_range_time: float
# Attributes to be used when determining what AUX_CAL to load
instrument_cfg_id: int
# elevation_angle:
antenna_pattern_azimuth_time: list
antenna_pattern_slant_range_time: list
antenna_pattern_elevation_angle: list
antenna_pattern_elevation_pattern: list
antenna_pattern_incidence_angle: list
ascending_node_time: datetime.datetime
number_of_samples: int
range_sampling_rate: float
slant_range_time: float
@classmethod
def from_et(cls, et_in: ET):
'''
Extracts list of product information from etree from
L1 annotation data set (LADS) Parameter
----------
et_in : xml.etree.ElementTree
Parsed LADS annotation .xml
Return
-------
cls: ProductAnnotation
Parsed LADS from et_in
'''
cls.xml_et = et_in
cls.antenna_pattern_azimuth_time = \
cls._parse_vectorlist('antennaPattern/antennaPatternList',
'azimuthTime',
'datetime')
cls.antenna_pattern_slant_range_time = \
cls._parse_vectorlist('antennaPattern/antennaPatternList',
'slantRangeTime',
'vector_float')
cls.antenna_pattern_elevation_angle = \
cls._parse_vectorlist('antennaPattern/antennaPatternList',
'elevationAngle',
'vector_float')
cls.antenna_pattern_elevation_pattern = \
cls._parse_vectorlist('antennaPattern/antennaPatternList',
'elevationPattern',
'vector_float')
cls.antenna_pattern_incidence_angle = \
cls._parse_vectorlist('antennaPattern/antennaPatternList',
'incidenceAngle',
'vector_float')
cls.image_information_slant_range_time = \
cls._parse_scalar('imageAnnotation/imageInformation/slantRangeTime',
'scalar_float')
cls.ascending_node_time = \
cls._parse_scalar('imageAnnotation/imageInformation/ascendingNodeTime',
'datetime')
cls.number_of_samples = \
cls._parse_scalar('imageAnnotation/imageInformation/numberOfSamples',
'scalar_int')
cls.number_of_samples = \
cls._parse_scalar('imageAnnotation/imageInformation/numberOfSamples',
'scalar_int')
cls.range_sampling_rate = \
cls._parse_scalar('generalAnnotation/productInformation/rangeSamplingRate',
'scalar_float')
cls.slant_range_time = \
cls._parse_scalar('imageAnnotation/imageInformation/slantRangeTime',
'scalar_float')
cls.inst_config_id = \
cls._parse_scalar('generalAnnotation/downlinkInformationList/downlinkInformation/'
'downlinkValues/instrumentConfigId',
'scalar_int')
return cls
@dataclass
class AuxCal(AnnotationBase):
'''AUX_CAL information for EAP correction'''
beam_nominal_near_range: float
beam_nominal_far_range: float
elevation_angle_increment: float
elevation_antenna_pattern: np.ndarray
azimuth_angle_increment: float
azimuth_antenna_pattern: np.ndarray
azimuth_antenna_element_pattern_increment: float
azimuth_antenna_element_pattern: float
absolute_calibration_constant: float
noise_calibration_factor: float
@classmethod
def load_from_zip_file(cls, path_aux_cal_zip: str, pol: str, str_swath: str):
'''
A class method that extracts list of information AUX_CAL from the input ET.
Parameters
---------
path_aux_cal_zip : str
Path to the AUX_CAL .zip file
pol: str {'vv','vh','hh','hv'}
Polarization of interest
str_swath: {'iw1','iw2','iw3'}
IW subswath of interest
Returns
-------
cls: AuxCal class populated by et_in in the parameter
'''
if not path_aux_cal_zip.endswith('.zip'):
raise ValueError('Only AUX_CAL files in .zip format are accepted.')
if os.path.exists(path_aux_cal_zip):
str_safe_aux_cal = os.path.basename(path_aux_cal_zip).replace('.zip','')
# detect the platform from path_aux_cal_zip
str_platform = str_safe_aux_cal.split('_')[0]
else:
raise ValueError(f'Cannot find AUX_CAL .zip file: {path_aux_cal_zip}')
with zipfile.ZipFile(path_aux_cal_zip, 'r') as zipfile_aux_cal:
filepath_xml = f'{str_safe_aux_cal}/data/{str_platform.lower()}-aux-cal.xml'
# check if the input file has the aux_cal .xml file to load
list_files_in_zip = [zf.filename for zf in zipfile_aux_cal.filelist]
if filepath_xml not in list_files_in_zip:
raise ValueError(f'Cannot find {filepath_xml} in '
f'zip file {path_aux_cal_zip}.\n'
'Make sure if the legit AUX_CAL .zip file is provided.')
with zipfile_aux_cal.open(filepath_xml,'r') as f_aux_cal:
et_in = ET.parse(f_aux_cal)
calibration_params_list = et_in.find('calibrationParamsList')
for calibration_params in calibration_params_list:
swath_xml = calibration_params.find('swath').text
polarisation_xml = calibration_params.find('polarisation').text
if polarisation_xml == pol.upper() and swath_xml==str_swath.upper():
cls.beam_nominal_near_range = \
float(calibration_params.
find('elevationAntennaPattern/beamNominalNearRange').text)
cls.beam_nominal_far_range = \
float(calibration_params.
find('elevationAntennaPattern/beamNominalFarRange').text)
cls.elevation_angle_increment = \
float(calibration_params.
find('elevationAntennaPattern/elevationAngleIncrement').text)
n_val = \
int(calibration_params.
find('elevationAntennaPattern/values').attrib['count'])
arr_eap_val = \
np.array([float(token_val) for \
token_val in calibration_params.
find('elevationAntennaPattern/values').text.split()])
if n_val == len(arr_eap_val):
# Provided in real numbers: In case of AUX_CAL for old IPFs.
cls.elevation_antenna_pattern = arr_eap_val
elif n_val*2 == len(arr_eap_val):
# Provided in complex numbers: In case of recent IPFs e.g. 3.10
cls.elevation_antenna_pattern = arr_eap_val[0::2] + arr_eap_val[1::2] * 1.0j
else:
raise ValueError('The number of values does not match. '
f'n_val={n_val}, '
f'#len(elevationAntennaPattern/values)={len(arr_eap_val)}')
cls.azimuth_angle_increment = \
float(calibration_params.
find('azimuthAntennaPattern/azimuthAngleIncrement').text)
cls.azimuth_antenna_pattern = \
np.array([float(token_val) for \
token_val in calibration_params.
find('azimuthAntennaPattern/values').text.split()])
cls.azimuth_antenna_element_pattern_increment = \
float(calibration_params.
find('azimuthAntennaElementPattern/azimuthAngleIncrement').text)
cls.azimuth_antenna_element_pattern = \
np.array([float(token_val) for \
token_val in calibration_params.
find('azimuthAntennaElementPattern/values').text.split()])
cls.absolute_calibration_constant = \
float(calibration_params.find('absoluteCalibrationConstant').text)
cls.noise_calibration_factor = \
float(calibration_params.find('noiseCalibrationFactor').text)
return cls
@dataclass
class SwathRfiInfo:
'''
Burst RFI information in a swath
Reference documentation: "Sentinel-1: Using the RFI annotations" by
G.Hajduch et al.
url = "https://sentinel.esa.int/documents/247904/1653442/
DI-MPC-OTH-0540-1-0-RFI-Tech-Note.pdf/
4b4fa95d-039f-5c78-fb90-06d307b3c13a?t=1644988601315"
'''
# RFI info in the product annotation
rfi_mitigation_performed: str
rfi_mitigation_domain: str
# RFI info in the RFI annotation
rfi_burst_report_list: list
azimuth_time_list: list
@classmethod
def from_et(cls,
et_rfi: ET,
et_product: ET,
ipf_version: version.Version):
'''Load RFI information from etree
Parameters
----------
et_rfi: ET
XML ElementTree from RFI annotation
et_product: ET
XML ElementTree from product annotation
ipf_version: version.Version
IPF version of the input sentinel-1 data
Returns
-------
cls: SwathRfiInfo
dataclass populated by this function
'''
if ipf_version < RFI_INFO_AVAILABLE_FROM:
# RFI related processing is not in place
# return an empty dataclass
return None
# Attempt to locate the RFI information from the input annotations
header_lads = et_product.find('imageAnnotation/processingInformation')
if header_lads is None:
raise ValueError('Cannot locate the element in the product '
'anotation where RFI mitigation info is located.')
header_rfi = et_rfi.find('rfiBurstReportList')
if header_rfi is None:
raise ValueError('Cannot locate `rfiBurstReportList` '
'in the RFI annotation')
# Start to load RFI information
cls.rfi_mitigation_performed =\
header_lads.find('rfiMitigationPerformed').text
cls.rfi_mitigation_domain =\
header_lads.find('rfiMitigationDomain').text
num_burst_rfi_report = len(header_rfi)
cls.rfi_burst_report_list = [None] * num_burst_rfi_report
cls.azimuth_time_list = [None] * num_burst_rfi_report
for i_burst, elem_burst in enumerate(header_rfi):
cls.rfi_burst_report_list[i_burst] =\
element_to_dict(elem_burst)['rfiBurstReport']
cls.azimuth_time_list[i_burst] =\
cls.rfi_burst_report_list[i_burst]['azimuthTime']
return cls
@classmethod
def extract_by_aztime(cls, aztime_start: datetime.datetime):
'''
Extract the burst RFI report that is within the azimuth time of a burst
Parameters
----------
aztime_start: datetime.datetime
Starting azimuth time of a burst
Returns
-------
rfi_info: SimpleNamespace
A SimpleNamespace that contains the burst RFI report as a dictionary,
along with the RFI related information from the product annotation
'''
# find the corresponding burst
index_burst =\
closest_block_to_azimuth_time(np.array(cls.azimuth_time_list),
aztime_start)
burst_report_out = cls.rfi_burst_report_list[index_burst]
rfi_info = SimpleNamespace()
rfi_info.rfi_mitigation_performed = cls.rfi_mitigation_performed
rfi_info.rfi_mitigation_domain = cls.rfi_mitigation_domain
rfi_info.rfi_burst_report = burst_report_out
return rfi_info
@dataclass
class SwathMiscMetadata:
'''
Miscellaneous metadata
'''
azimuth_looks: int
slant_range_looks: int
aztime_vec: np.ndarray
inc_angle_list: list
# Processing data from manifest
slc_post_processing: dict
def extract_by_aztime(self, aztime_start: datetime.datetime):
'''
Extract the miscellaneous metadata for a burst that
corresponds to `aztime_start`
Parameters
----------
aztime_start: datetime.datetime
Starting azimuth time of a burst
Returns
-------
burst_misc_metadata: SimpleNamespace
A SimpleNamespace that contains the misc. metadata
'''
index_burst =\
closest_block_to_azimuth_time(self.aztime_vec,
aztime_start)
inc_angle_burst = self.inc_angle_list[index_burst]
burst_misc_metadata = SimpleNamespace()
# Metadata names to be populated into OPERA products as
# the source data's processing information
keys_misc_metadata = ['stop', 'country', 'organisation', 'site']
for key_metadata in keys_misc_metadata:
if not key_metadata in self.slc_post_processing:
self.slc_post_processing[key_metadata] =\
'Not available in sentinel-1 manifest.safe'
burst_misc_metadata.processing_info_dict = self.slc_post_processing
burst_misc_metadata.azimuth_looks = self.azimuth_looks
burst_misc_metadata.slant_range_looks = self.slant_range_looks
burst_misc_metadata.inc_angle_near_range = inc_angle_burst[0]
burst_misc_metadata.inc_angle_far_range = inc_angle_burst[-1]
return burst_misc_metadata
def closest_block_to_azimuth_time(vector_azimuth_time: np.ndarray,
azimuth_time_burst: datetime.datetime) -> int:
'''
Find the id of the closest data block in annotation.
To be used when populating BurstNoise, BurstCalibration, and BurstEAP.
Parameters
----------
vector_azimuth_time : np.ndarray
numpy array azimuth time whose data type is datetime.datetime
azimuth_time_burst: datetime.datetime
Azimuth time of the burst
Returns
-------
_: int
Index of vector_azimuth_time that is the closest to azimuth_burst_time
'''
return np.argmin(np.abs(vector_azimuth_time - azimuth_time_burst))
@dataclass
class BurstNoise:
'''Noise correction information for Sentinel-1 burst'''
basename_nads: str
range_azimuth_time: datetime.datetime
range_line: float
range_pixel: np.ndarray
range_lut: np.ndarray
azimuth_first_azimuth_line: int
azimuth_first_range_sample: int
azimuth_last_azimuth_line: int
azimuth_last_range_sample: int
azimuth_line: np.ndarray
azimuth_lut: np.ndarray
line_from: int
line_to: int
@classmethod
def from_noise_annotation(cls, noise_annotation: NoiseAnnotation,
azimuth_time: datetime.datetime,
line_from: int,
line_to: int,
ipf_version: version.Version):
'''
Extracts the noise correction information for
individual burst from NoiseAnnotation
Parameters
----------
noise_annotation: NoiseAnnotation
Subswath-wide noise annotation information
azimuth_time : datetime.datetime
Azimuth time of the burst
line_from: int
First line of the burst in the subswath
line_to: int
Last line of the burst in the subswath
ipf_version: float
IPF version of the SAFE data
Returns
-------
cls: BurstNoise
Instance of BurstNoise initialized by the input parameters
'''
basename_nads = noise_annotation.basename_annotation
id_closest = closest_block_to_azimuth_time(noise_annotation.rg_list_azimuth_time,
azimuth_time)
range_azimuth_time = noise_annotation.rg_list_azimuth_time[id_closest]
range_line = noise_annotation.rg_list_line[id_closest]
range_pixel = noise_annotation.rg_list_pixel[id_closest]
range_lut = noise_annotation.rg_list_noise_range_lut[id_closest]
azimuth_first_azimuth_line = noise_annotation.az_first_azimuth_line
azimuth_first_range_sample = noise_annotation.az_first_range_sample
azimuth_last_azimuth_line = noise_annotation.az_last_azimuth_line
azimuth_last_range_sample = noise_annotation.az_last_range_sample
if ipf_version >= min_ipf_version_az_noise_vector:
# Azimuth noise LUT exists - crop to the extent of the burst
id_top = np.argmin(np.abs(noise_annotation.az_line-line_from))
id_bottom = np.argmin(np.abs(noise_annotation.az_line-line_to))
# put some margin when possible
if id_top > 0:
id_top -= 1
if id_bottom < len(noise_annotation.az_line)-1:
id_bottom += 1
azimuth_line = noise_annotation.az_line[id_top:id_bottom + 1]
azimuth_lut = noise_annotation.az_noise_azimuth_lut[id_top:id_bottom + 1]
else:
azimuth_line = None
azimuth_lut = None
return cls(basename_nads, range_azimuth_time, range_line, range_pixel, range_lut,
azimuth_first_azimuth_line, azimuth_first_range_sample,
azimuth_last_azimuth_line, azimuth_last_range_sample,
azimuth_line, azimuth_lut,
line_from, line_to)
def compute_thermal_noise_lut(self, shape_lut):
'''
Calculate thermal noise LUT whose shape is `shape_lut`
Parameter:
----------
shape_lut: tuple or list
Shape of the output LUT
Returns
-------
arr_lut_total: np.ndarray
2d array containing thermal noise correction look up table values
'''
nrows, ncols = shape_lut
# Interpolate the range noise vector
rg_lut_interp_obj = InterpolatedUnivariateSpline(self.range_pixel,
self.range_lut,
k=1)
if self.azimuth_last_range_sample is not None:
vec_rg = np.arange(self.azimuth_last_range_sample + 1)
else:
vec_rg = np.arange(ncols)
rg_lut_interpolated = rg_lut_interp_obj(vec_rg)
# Interpolate the azimuth noise vector
if (self.azimuth_line is None) or (self.azimuth_lut is None):
az_lut_interpolated = np.ones(nrows)
else: # IPF >= 2.90
az_lut_interp_obj = InterpolatedUnivariateSpline(self.azimuth_line,
self.azimuth_lut,
k=1)
vec_az = np.arange(self.line_from, self.line_to + 1)
az_lut_interpolated = az_lut_interp_obj(vec_az)
arr_lut_total = np.matmul(az_lut_interpolated[..., np.newaxis],
rg_lut_interpolated[np.newaxis, ...])
return arr_lut_total
@dataclass
class BurstCalibration:
'''Calibration information for Sentinel-1 IW SLC burst
'''
basename_cads: str
azimuth_time: datetime.datetime = None
line: float = None
pixel: np.ndarray = None
sigma_naught: np.ndarray = None
beta_naught: np.ndarray = None
gamma: np.ndarray = None
dn: np.ndarray = None
@classmethod
def from_calibration_annotation(cls, calibration_annotation: CalibrationAnnotation,
azimuth_time: datetime.datetime):
'''
A class method that extracts the calibration info for the burst
Parameters
----------
calibration_annotation: CalibrationAnnotation
A subswath-wide calibraion information from CADS file
azimuth_time: datetime.datetime
Azimuth time of the burst
Returns
-------
cls: BurstCalibration
Radiometric correction information for the burst
'''
basename_cads = calibration_annotation.basename_annotation
id_closest = closest_block_to_azimuth_time(calibration_annotation.list_azimuth_time,
azimuth_time)
azimuth_time = calibration_annotation.list_azimuth_time[id_closest]
line = calibration_annotation.list_line[id_closest]
pixel = calibration_annotation.list_pixel[id_closest]
sigma_naught = calibration_annotation.list_sigma_nought[id_closest]
gamma = calibration_annotation.list_gamma[id_closest]
dn = calibration_annotation.list_dn[id_closest]
# Check if all values in the list of beta_naught LUTs are the same
matrix_beta_naught = np.array(calibration_annotation.list_beta_nought)
if matrix_beta_naught.min() == matrix_beta_naught.max():
beta_naught = np.min(matrix_beta_naught)
else:
# TODO Switch to LUT-based method when there is significant changes in the array
beta_naught = np.mean(matrix_beta_naught)
return cls(basename_cads, azimuth_time, line, pixel,
sigma_naught, beta_naught, gamma, dn)
@dataclass
class BurstEAP:
'''EAP correction information for Sentinel-1 IW SLC burst
'''
# from LADS
freq_sampling: float # range sampling rate
eta_start: datetime.datetime
tau_0: float # imageInformation/slantRangeTime
tau_sub: np.ndarray # antennaPattern/slantRangeTime
theta_sub: np.ndarray # antennaPattern/elevationAngle
azimuth_time: datetime.datetime
ascending_node_time: datetime.datetime
# from AUX_CAL
gain_eap: np.ndarray # elevationAntennaPattern
delta_theta:float # elavationAngleIncrement
@classmethod
def from_product_annotation_and_aux_cal(cls, product_annotation: ProductAnnotation,
aux_cal: AuxCal, azimuth_time: datetime.datetime):
'''
A class method that extracts the EAP correction info for the IW SLC burst
Parameters
----------
product_annotation: ProductAnnotation
A swath-wide product annotation class
aux_cal: AuxCal
AUX_CAL information that corresponds to the sensing time
azimuth_time: datetime.datetime
Azimuth time of the burst
Returns
-------
cls: BurstEAP
A burst-wide information for EAP correction
'''
id_closest = closest_block_to_azimuth_time(product_annotation.antenna_pattern_azimuth_time,