-
Notifications
You must be signed in to change notification settings - Fork 244
/
Sentinel1.py
executable file
·1404 lines (1049 loc) · 49.7 KB
/
Sentinel1.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
# Copyright 2014 California Institute of Technology. ALL RIGHTS RESERVED.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# United States Government Sponsorship acknowledged. This software is subject to
# U.S. export control laws and regulations and has been classified as 'EAR99 NLR'
# (No [Export] License Required except when exporting to an embargoed country,
# end user, or in support of a prohibited end use). By downloading this software,
# the user agrees to comply with all applicable U.S. export laws and regulations.
# The user has the responsibility to obtain export licenses, or other export
# authority as may be required before exporting this software to any 'EAR99'
# embargoed foreign country or citizen of those countries.
#
# Author: Piyush Agram
#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
import xml.etree.ElementTree as ET
import datetime
import isceobj
from .BurstSLC import BurstSLC
from isceobj.Util import Poly1D, Poly2D
from isceobj.Planet.Planet import Planet
from isceobj.Orbit.Orbit import StateVector, Orbit
from isceobj.Planet.AstronomicalHandbook import Const
from iscesys.Component.Component import Component
from iscesys.Component.ProductManager import ProductManager
from iscesys.DateTimeUtil.DateTimeUtil import DateTimeUtil as DTUtil
import os
import glob
import numpy as np
import shelve
XML_LIST = Component.Parameter('xml',
public_name = 'xml',
default = [],
container = list,
type = str,
doc = 'List of input XML files to stitch together')
TIFF_LIST = Component.Parameter('tiff',
public_name = 'tiff',
default = [],
container = list,
type = str,
doc = 'List of input TIFF files to stitch together')
MANIFEST = Component.Parameter('manifest',
public_name = 'manifest',
default = [],
container = list,
type = str,
doc = 'Manifest file with IPF version')
SAFE_LIST = Component.Parameter('safe',
public_name = 'safe',
default = [],
container = list,
type = str,
doc = 'List of safe directories')
SWATH_NUMBER = Component.Parameter('swathNumber',
public_name = 'swath number',
default = None,
type = int,
mandatory = True,
doc = 'Swath number to process')
POLARIZATION = Component.Parameter('polarization',
public_name = 'polarization',
default = 'vv',
type = str,
mandatory = True,
doc = 'Polarization')
ORBIT_FILE = Component.Parameter('orbitFile',
public_name = 'orbit file',
default = None,
type = str,
doc = 'External orbit file with state vectors')
AUX_FILE = Component.Parameter('auxFile',
public_name = 'auxiliary file',
default = None,
type = str,
doc = 'External auxiliary file to use for antenna pattern')
ORBIT_DIR = Component.Parameter('orbitDir',
public_name = 'orbit directory',
default = None,
type = str,
doc = 'Directory to search for orbit files')
AUX_DIR = Component.Parameter('auxDir',
public_name = 'auxiliary data directory',
default = None,
type = str,
doc = 'Directory to search for auxiliary data')
OUTPUT = Component.Parameter('output',
public_name = 'output directory',
default = None,
type = str,
doc = 'Directory where bursts get unpacked')
ROI = Component.Parameter('regionOfInterest',
public_name = 'region of interest',
default = [],
container = list,
type = float,
doc = 'User defined area to crop in SNWE')
####List of facilities
PRODUCT = Component.Facility('product',
public_name='product',
module = 'isceobj.Sensor.TOPS',
factory='createTOPSSwathSLCProduct',
args = (),
mandatory = True,
doc = 'TOPS SLC Swath product populated by the reader')
class Sentinel1(Component):
"""
Sentinel-1A TOPS reader
"""
family = 's1atops'
logging = 'isce.sensor.S1A_TOPS'
parameter_list = (XML_LIST,
TIFF_LIST,
MANIFEST,
SAFE_LIST,
ORBIT_FILE,
AUX_FILE,
ORBIT_DIR,
AUX_DIR,
OUTPUT,
ROI,
SWATH_NUMBER,
POLARIZATION)
facility_list = (PRODUCT,)
def __init__(self, name=''):
super().__init__(family=self.__class__.family, name=name)
####Number of swaths
self.maxSwaths = 3
###Variables never meant to be controlled by user
self._xml_root=None
self._burstWidth = None ###Common width
self._burstLength = None ###Common length
self._numSlices = None ###Number of slides
self._parsed = False ###If products have been parsed already
self._tiffSrc = []
####Specifically used only for IPF 002.36
####Scotch tape fix
self._elevationAngleVsTau = [] ###For storing time samples
self._Geap = None ###IQ antenna pattern
self._delta_theta = None ###Elevation angle increment
return
def validateUserInputs(self):
'''
Validate inputs provided by user.
Populate tiff and xml list using SAFE folder names.
'''
import fnmatch
import zipfile
if len(self.xml) == 0:
if self.swathNumber is None:
raise Exception('Desired swath number is not provided')
if len(self.safe) == 0:
raise Exception('SAFE directory is not provided')
elif self.swathNumber not in [1,2,3]:
raise Exception('Swath number must be one out of [1,2,3]')
elif len(self.tiff) != 0:
if len(self.xml) != len(self.tiff):
raise Exception('Number of TIFF and XML files dont match')
####First find annotation file
####Dont need swath number when driving with xml and tiff file
if len(self.xml) == 0:
swathid = 's1?-iw%d'%(self.swathNumber)
polid = self.polarization
if len(self.xml) == 0:
match = None
for dirname in self.safe:
match = None
if dirname.endswith('.zip'):
pattern = os.path.join('*SAFE','annotation', swathid) + '-slc-' + polid + '*.xml'
zf = zipfile.ZipFile(dirname, 'r')
match = fnmatch.filter(zf.namelist(), pattern)
zf.close()
if (len(match) == 0):
raise Exception('No annotation xml file found in zip file: {0}'.format(dirname))
####Add /vsizip at the start to make it a zip file
self.xml.append('/vsizip/'+os.path.join(dirname, match[0]) )
else:
pattern = os.path.join('annotation',swathid)+'-slc-'+polid+'*.xml'
match = glob.glob( os.path.join(dirname, pattern))
if (len(match) == 0):
raise Exception('No annotation xml file found in {0}'.format(dirname))
self.xml.append(match[0])
if len(self.xml) == 0:
raise Exception('No annotation files found')
print('Input XML files: ', self.xml)
####Find TIFF file
if (len(self.tiff) == 0) and (len(self.safe) != 0 ):
for dirname in self.safe:
match = None
if dirname.endswith('.zip'):
pattern = os.path.join('*SAFE','measurement', swathid) + '-slc-' + polid + '*.tiff'
zf = zipfile.ZipFile(dirname, 'r')
match = fnmatch.filter(zf.namelist(), pattern)
zf.close()
if (len(match) == 0):
raise Exception('No tiff file found in zip file: {0}'.format(dirname))
####Add /vsizip at the start to make it a zip file
self.tiff.append('/vsizip/' + os.path.join(dirname, match[0]) )
else:
pattern = os.path.join('measurement', swathid) + '-slc-' + polid + '*.tiff'
match = glob.glob(os.path.join(dirname, pattern))
if len(match) == 0 :
raise Exception('No tiff file found in directory: {0}'.format(dirname))
self.tiff.append(match[0])
print('Input TIFF files: ', self.tiff)
if len(self.tiff) != 0 :
if len(self.tiff) != len(self.xml):
raise Exception('Number of XML and TIFF files dont match')
####Find manifest files
if len(self.safe) != 0:
for dirname in self.safe:
if dirname.endswith('.zip'):
pattern='*SAFE/manifest.safe'
zf = zipfile.ZipFile(dirname, 'r')
match = fnmatch.filter(zf.namelist(), pattern)
zf.close()
self.manifest.append('/vsizip/' + os.path.join(dirname, match[0]))
else:
self.manifest.append(os.path.join(dirname, 'manifest.safe'))
print('Manifest files: ', self.manifest)
####Check bbox
roi = self.regionOfInterest
if len(roi) != 0:
if len(roi) != 4:
raise Exception('4 floats in SNWE format expected for bbox/ROI')
if (roi[0] >= roi[1]) or (roi[2] >= roi[3]):
raise Exception('Error in bbox definition: SNWE expected')
return
def parse(self):
'''
Parser for S1A IW data.
This is meant to only read in the metadata and does not read any imagery.
Can be used only with the annotation xml files if needed.
'''
####Check user inputs
self.validateUserInputs()
self._numSlices = len(self.xml)
if self._numSlices > 1:
self._parseMultiSlice()
else:
self._parseOneSlice()
###Set the parsed flag to True
self._parsed = True
return
def _parseOneSlice(self):
'''
'''
if self.xml[0].startswith('/vsizip'):
import zipfile
parts = self.xml[0].split(os.path.sep)
if parts[2] == '':
parts[2] = os.path.sep
zipname = os.path.join(*(parts[2:-3]))
fname = os.path.join(*(parts[-3:]))
zf = zipfile.ZipFile(zipname, 'r')
xmlstr = zf.read(fname)
zf.close()
else:
with open(self.xml[0],'r') as fid:
xmlstr = fid.read()
self._xml_root = ET.fromstring(xmlstr)
numberBursts = self.getNumberOfBurstsFromAnnotation()
####Create empty burst SLCs
for kk in range(numberBursts):
slc = BurstSLC()
slc.configure()
slc.burstNumber = kk+1
self.product.bursts.append(slc)
self.product.numberOfBursts = numberBursts
####Populate processing software info
if len(self.manifest) != 0:
self.populateIPFVersion()
####Populate common metadata
self.populateCommonMetadata()
####Populate specific metadata
self.populateBurstSpecificMetadata()
####Populate orbit information
###Try and locate an orbit file
if self.orbitFile is None:
if self.orbitDir is not None:
self.orbitFile = s1_findOrbitFile(self.orbitDir,
self.product.bursts[0].sensingStart,
self.product.bursts[-1].sensingStop,
mission = self.product.mission)
####Read in the orbits
if self.orbitFile:
orb = self.extractPreciseOrbit()
else:
orb = self.extractOrbitFromAnnotation()
for burst in self.product.bursts:
if self.orbitFile:
burst.orbit.setOrbitSource(os.path.basename(self.orbitFile))
else:
burst.orbit.setOrbitSource('Annotation')
for sv in orb:
burst.orbit.addStateVector(sv)
####Determine pass direction using Vz
VV = burst.orbit.interpolateOrbit(burst.sensingMid, method='hermite').getVelocity()
if VV[2] >= 0:
burst.passDirection = 'ASCENDING'
else:
burst.passDirection = 'DESCENDING'
####If user provided a region of interest
if len(self.regionOfInterest) != 0:
self.crop(self.regionOfInterest)
return
def _parseMultiSlice(self):
'''
Responsible for parsing multiple slices meant to be stitched.
'''
slices = []
relTimes = []
burstWidths = []
burstLengths = []
for kk in range(self._numSlices):
###Create a new reader for one slice only
aslice = Sentinel1()
aslice.configure()
####Populate all the fields for reader
aslice.xml = [self.xml[kk]]
aslice.tiff = [self.tiff[kk]]
aslice.manifest = [self.manifest[kk]]
aslice.output = self.output
aslice.orbitFile = self.orbitFile
aslice.orbitDir = self.orbitDir
aslice.regionOfInterest = self.regionOfInterest
aslice.swathNumber = self.swathNumber
aslice.parse()
####If there are any bursts left after cropping
if aslice.product.numberOfBursts != 0:
slices.append(aslice)
relTimes.append((aslice.product.bursts[0].sensingStart - slices[0].product.bursts[0].sensingStart).total_seconds())
burstWidths.append(aslice.product.bursts[0].numberOfSamples)
burstLengths.append(aslice.product.bursts[0].numberOfLines)
####Update number of slices
self._numSlices = len(slices)
if self._numSlices == 0 :
raise Exception('There is no imagery to extract. Check region of interest and inputs.')
self.burstWidth = max(burstWidths)
self.burstLength = max(burstLengths)
if self._numSlices == 1: #If only one remains after crop
self.product = slices[0].product
self.product.numberOfBursts = len(self.product.bursts)
self._tiffSrc = (self.product.numberOfBursts) * (slices[0].tiff)
self._elevationAngleVsTau = slices[0]._elevationAngleVsTau
return
####If there are multiple slices to combine
print('Stitching {0} slices together'.format(self._numSlices))
###Sort slices by start times
indices = np.argsort(relTimes)
####Start with the first slice
firstSlice = slices[indices[0]]
####Estimate burstinterval
t0 = firstSlice.product.bursts[0].burstStartUTC
if len(firstSlice.product.bursts) > 1:
burstStartInterval = firstSlice.product.bursts[1].burstStartUTC - t0
elif len(slices) > 1:
burstStartInterval = slices[indices[1]].product.bursts[0].burstStartUTC - t0
else:
raise Exception('Atleast 2 bursts must be present in the cropped region for TOPS processing.')
self.product.processingSoftwareVersion = '+'.join(set([x.product.processingSoftwareVersion for x in slices]))
if len( self.product.processingSoftwareVersion.split('+')) != 1:
raise Exception('Trying to combine SLC products from different IPF versions {0}\n'.format(self.product.processingSoftwareVersion) +
'This is not possible as SLCs are sliced differently with different versions of the processor. \n' +
'Integer shift between bursts cannot be guaranteed\n'+
'Exiting .......')
for index in indices:
aslice = slices[index]
offset = int(np.rint((aslice.product.bursts[0].burstStartUTC - t0).total_seconds() / burstStartInterval.total_seconds()))
for kk in range(aslice.product.numberOfBursts):
#####Skip appending if burst also exists from previous scene
if (offset+kk) < len(self.product.bursts):
continue
elif (offset+kk) == len(self.product.bursts):
self.product.bursts.append(aslice.product.bursts[kk])
if len(self.tiff):
self._tiffSrc.append(aslice.tiff[0])
self._elevationAngleVsTau.append(aslice._elevationAngleVsTau[kk])
else:
print('Offset indices = ', indices)
raise Exception('There appears to be a gap between slices. Cannot stitch them successfully.')
self.product.numberOfBursts = len(self.product.bursts)
print('COMBINED VERSION: ', self.product.processingSoftwareVersion)
self.product.ascendingNodeTime = firstSlice.product.ascendingNodeTime
self.product.mission = firstSlice.product.mission
return
def getxmlattr(self, path, key):
try:
res = self._xml_root.find(path).attrib[key]
except:
raise Exception('Cannot find attribute %s at %s'%(key, path))
return res
def getxmlvalue(self, path):
try:
res = self._xml_root.find(path).text
except:
raise Exception('Tag= %s not found'%(path))
if res is None:
raise Exception('Tag = %s not found'%(path))
return res
def getxmlelement(self, path):
try:
res = self._xml_root.find(path)
except:
raise Exception('Cannot find path %s'%(path))
if res is None:
raise Exception('Cannot find path %s'%(path))
return res
def convertToDateTime(self, string):
dt = datetime.datetime.strptime(string,"%Y-%m-%dT%H:%M:%S.%f")
return dt
def getNumberOfBurstsFromAnnotation(self):
return int(self.getxmlattr('swathTiming/burstList', 'count'))
def populateCommonMetadata(self):
"""
Create metadata objects from the metadata files
"""
####Set each parameter one - by - one
mission = self.getxmlvalue('adsHeader/missionId')
swath = self.getxmlvalue('adsHeader/swath')
polarization = self.getxmlvalue('adsHeader/polarisation')
orbitnumber = int(self.getxmlvalue('adsHeader/absoluteOrbitNumber'))
frequency = float(self.getxmlvalue('generalAnnotation/productInformation/radarFrequency'))
passDirection = self.getxmlvalue('generalAnnotation/productInformation/pass')
rangeSampleRate = float(self.getxmlvalue('generalAnnotation/productInformation/rangeSamplingRate'))
rangePixelSize = Const.c/(2.0*rangeSampleRate)
azimuthPixelSize = float(self.getxmlvalue('imageAnnotation/imageInformation/azimuthPixelSpacing'))
azimuthTimeInterval = float(self.getxmlvalue('imageAnnotation/imageInformation/azimuthTimeInterval'))
lines = int(self.getxmlvalue('swathTiming/linesPerBurst'))
samples = int(self.getxmlvalue('swathTiming/samplesPerBurst'))
slantRangeTime = float(self.getxmlvalue('imageAnnotation/imageInformation/slantRangeTime'))
startingRange = float(self.getxmlvalue('imageAnnotation/imageInformation/slantRangeTime'))*Const.c/2.0
incidenceAngle = float(self.getxmlvalue('imageAnnotation/imageInformation/incidenceAngleMidSwath'))
steeringRate = np.radians(float( self.getxmlvalue('generalAnnotation/productInformation/azimuthSteeringRate')))
prf = float(self.getxmlvalue('generalAnnotation/downlinkInformationList/downlinkInformation/prf'))
terrainHeight = float(self.getxmlvalue('generalAnnotation/terrainHeightList/terrainHeight/value'))
####Sentinel is always right looking
lookSide = -1
###Read ascending node for phase calibration
ascTime = self.convertToDateTime(self.getxmlvalue('imageAnnotation/imageInformation/ascendingNodeTime'))
####Product parameters
self.product.ascendingNodeTime = ascTime
self.product.mission = mission
self.product.spacecraftName = 'Sentinel-1'
for index, burst in enumerate(self.product.bursts):
burst.numberOfSamples = samples
burst.numberOfLines = lines
burst.startingRange = startingRange
if mission == 'S1A':
burst.trackNumber = (orbitnumber-73)%175 + 1
elif mission == 'S1B':
burst.trackNumber = (orbitnumber-27)%175 + 1
else:
raise ValueError('Encountered unknown mission id {0}'.format(mission))
burst.orbitNumber = orbitnumber
burst.frameNumber = 1 #S1A doesnt appear to have a frame system
burst.polarization = polarization
burst.swathNumber = int(swath.strip()[-1])
burst.passDirection = passDirection
burst.radarWavelength = Const.c / frequency
burst.rangePixelSize = rangePixelSize
burst.azimuthTimeInterval = azimuthTimeInterval
burst.azimuthSteeringRate = steeringRate
burst.prf = prf
burst.terrainHeight = terrainHeight
burst.rangeSamplingRate = rangeSampleRate
#add these for doing bandpass filtering, Cunren Liang, 27-FEB-2018
burst.rangeWindowType = self.getxmlvalue('imageAnnotation/processingInformation/swathProcParamsList/swathProcParams/rangeProcessing/windowType')
burst.rangeWindowCoefficient = float(self.getxmlvalue('imageAnnotation/processingInformation/swathProcParamsList/swathProcParams/rangeProcessing/windowCoefficient'))
burst.rangeProcessingBandwidth = float(self.getxmlvalue('imageAnnotation/processingInformation/swathProcParamsList/swathProcParams/rangeProcessing/processingBandwidth'))
burst.azimuthWindowType = self.getxmlvalue('imageAnnotation/processingInformation/swathProcParamsList/swathProcParams/azimuthProcessing/windowType')
burst.azimuthWindowCoefficient = float(self.getxmlvalue('imageAnnotation/processingInformation/swathProcParamsList/swathProcParams/azimuthProcessing/windowCoefficient'))
burst.azimuthProcessingBandwidth = float(self.getxmlvalue('imageAnnotation/processingInformation/swathProcParamsList/swathProcParams/azimuthProcessing/processingBandwidth'))
return
def populateBurstSpecificMetadata(self):
'''
Extract burst specific metadata from the xml file.
'''
burstList = self.getxmlelement('swathTiming/burstList')
for index, burst in enumerate(burstList):
bb = self.product.bursts[index]
bb.sensingStart = self.convertToDateTime(burst.find('azimuthTime').text)
deltaT = datetime.timedelta(seconds=(bb.numberOfLines - 1)*bb.azimuthTimeInterval)
bb.sensingStop = bb.sensingStart + deltaT
bb.burstStartUTC = self.convertToDateTime(burst.find('sensingTime').text)
deltaT = datetime.timedelta(seconds=(bb.numberOfLines-1)/bb.prf)
bb.burstStopUTC = bb.burstStartUTC + deltaT
firstValidSample = [int(val) for val in burst.find('firstValidSample').text.split()]
lastValidSample = [int(val) for val in burst.find('lastValidSample').text.split()]
first=False
last=False
count=0
for ii, val in enumerate(firstValidSample):
if (val >= 0) and (not first):
first = True
bb.firstValidLine = ii
if (val < 0) and (first) and (not last):
last = True
bb.numValidLines = ii - bb.firstValidLine
lastLine = bb.firstValidLine + bb.numValidLines - 1
bb.firstValidSample = max(firstValidSample[bb.firstValidLine], firstValidSample[lastLine])
lastSample = min(lastValidSample[bb.firstValidLine], lastValidSample[lastLine])
bb.numValidSamples = lastSample - bb.firstValidSample
####Read in fm rates separately
fmrateList = self.getxmlelement('generalAnnotation/azimuthFmRateList')
fmRates = []
for index, burst in enumerate(fmrateList):
r0 = 0.5 * Const.c * float(burst.find('t0').text)
try:
c0 = float(burst.find('c0').text)
c1 = float(burst.find('c1').text)
c2 = float(burst.find('c2').text)
coeffs = [c0,c1,c2]
except AttributeError:
coeffs = [float(val) for val in burst.find('azimuthFmRatePolynomial').text.split()]
refTime = self.convertToDateTime(burst.find('azimuthTime').text)
poly = Poly1D.Poly1D()
poly.initPoly(order=len(coeffs)-1)
poly.setMean(r0)
poly.setNorm(0.5*Const.c)
poly.setCoeffs(coeffs)
fmRates.append((refTime, poly))
for index, burst in enumerate(self.product.bursts):
dd = [ np.abs((burst.sensingMid - val[0]).total_seconds()) for val in fmRates]
arg = np.argmin(dd)
burst.azimuthFMRate = fmRates[arg][1]
# print('FM rate matching: Burst %d to Poly %d'%(index, arg))
dcList = self.getxmlelement('dopplerCentroid/dcEstimateList')
dops = [ ]
for index, burst in enumerate(dcList):
r0 = 0.5 * Const.c* float(burst.find('t0').text)
refTime = self.convertToDateTime(burst.find('azimuthTime').text)
coeffs = [float(val) for val in burst.find('dataDcPolynomial').text.split()]
poly = Poly1D.Poly1D()
poly.initPoly(order=len(coeffs)-1)
poly.setMean(r0)
poly.setNorm(0.5*Const.c)
poly.setCoeffs(coeffs)
dops.append((refTime, poly))
for index, burst in enumerate(self.product.bursts):
dd = [np.abs((burst.sensingMid - val[0]).total_seconds()) for val in dops]
arg = np.argmin(dd)
burst.doppler = dops[arg][1]
# print('Doppler matching: Burst %d to Poly %d'%(index, arg))
####Specifically for IPF 002.36
if self.product.processingSoftwareVersion == '002.36':
eapList = self.getxmlelement('antennaPattern/antennaPatternList')
eaps = []
for index, burst in enumerate(eapList):
refTime = self.convertToDateTime(burst.find('azimuthTime').text)
taus = [float(val) for val in burst.find('slantRangeTime').text.split()]
angs = [float(val) for val in burst.find('elevationAngle').text.split()]
eaps.append((refTime, (taus,angs)))
for index, burst in enumerate(self.product.bursts):
dd = [np.abs((burst.sensingMid - val[0]).total_seconds()) for val in eaps]
arg = np.argmin(dd)
self._elevationAngleVsTau.append(eaps[arg][1])
else:
for index, burst in enumerate(self.product.bursts):
self._elevationAngleVsTau.append(None)
def populateIPFVersion(self):
'''
Get IPF version from the manifest file.
'''
try:
if self.manifest[0].startswith('/vsizip'):
import zipfile
parts = self.manifest[0].split(os.path.sep)
if parts[2] == '':
parts[2] = os.path.sep
zipname = os.path.join(*(parts[2:-2]))
fname = os.path.join(*(parts[-2:]))
print('MANS: ', zipname, fname)
zf = zipfile.ZipFile(zipname, 'r')
xmlstr = zf.read(fname)
else:
with open(self.manifest[0], 'r') as fid:
xmlstr = fid.read()
####Setup namespace
nsp = "{http://www.esa.int/safe/sentinel-1.0}"
root = ET.fromstring(xmlstr)
elem = root.find('.//metadataObject[@ID="processing"]')
rdict = elem.find('.//xmlData/' + nsp + 'processing/' + nsp + 'facility').attrib
self.product.processingFacility = rdict['site'] +', '+ rdict['country']
rdict = elem.find('.//xmlData/' + nsp + 'processing/' + nsp + 'facility/' + nsp + 'software').attrib
self.product.processingSystem = rdict['name']
self.product.processingSoftwareVersion = rdict['version']
print('Setting IPF version to : ', self.product.processingSoftwareVersion)
except: ###Not a critical error ... continuing
print('Could not read version number successfully from manifest file: ', self.manifest)
pass
return
def extractOrbitFromAnnotation(self):
'''
Extract orbit information from xml node.
'''
node = self._xml_root.find('generalAnnotation/orbitList')
print('Extracting orbit from annotation XML file')
frameOrbit = Orbit()
frameOrbit.configure()
for child in node:
timestamp = self.convertToDateTime(child.find('time').text)
pos = []
vel = []
posnode = child.find('position')
velnode = child.find('velocity')
for tag in ['x','y','z']:
pos.append(float(posnode.find(tag).text))
for tag in ['x','y','z']:
vel.append(float(velnode.find(tag).text))
vec = StateVector()
vec.setTime(timestamp)
vec.setPosition(pos)
vec.setVelocity(vel)
frameOrbit.addStateVector(vec)
#####Orbits provided in annotation files are not InSAR-grade
#####These also need extensions for interpolation to work
return frameOrbit
def extractPreciseOrbit(self, margin=60.0):
'''
Extract precise orbit from given Orbit file.
'''
try:
fp = open(self.orbitFile,'r')
except IOError as strerr:
print("IOError: %s" % strerr)
return
_xml_root = ET.ElementTree(file=fp).getroot()
node = _xml_root.find('Data_Block/List_of_OSVs')
print('Extracting orbit from Orbit File: ', self.orbitFile)
orb = Orbit()
orb.configure()
margin = datetime.timedelta(seconds=margin)
tstart = self.product.bursts[0].sensingStart - margin
tend = self.product.bursts[-1].sensingStop + margin
for child in node:
timestamp = self.convertToDateTime(child.find('UTC').text[4:])
if (timestamp >= tstart) and (timestamp < tend):
pos = []
vel = []
for tag in ['VX','VY','VZ']:
vel.append(float(child.find(tag).text))
for tag in ['X','Y','Z']:
pos.append(float(child.find(tag).text))
###Warn if state vector quality is not nominal
quality = child.find('Quality').text.strip()
if quality != 'NOMINAL':
print('WARNING: State Vector at time {0} tagged as {1} in orbit file {2}'.format(timestamp, quality, self.orbitFile))
vec = StateVector()
vec.setTime(timestamp)
vec.setPosition(pos)
vec.setVelocity(vel)
orb.addStateVector(vec)
fp.close()
return orb
def extractCalibrationPattern(self):
'''
Read the AUX CAL file for elevation angle antenna pattern.
'''
burst = self.product.bursts[0]
Geap_IQ = None
print("extracting aux from: " + self.auxFile)
fp = open(self.auxFile,'r')
xml_root = ET.ElementTree(file=fp).getroot()
res = xml_root.find('calibrationParamsList/calibrationParams')
paramsList = xml_root.find('calibrationParamsList')
for par in paramsList:
if (par.find('swath').text.strip() == ('IW'+str(burst.swathNumber))) and (par.find('polarisation').text == burst.polarization):
self._delta_theta = float(par.find('elevationAntennaPattern/elevationAngleIncrement').text)
Geap_IQ = [float(val) for val in par.find('elevationAntennaPattern/values').text.split()]
len(Geap_IQ)
I = np.array(Geap_IQ[0::2])
Q = np.array(Geap_IQ[1::2])
self._Geap = I[:]+Q[:]*1j # Complex vector of Elevation Antenna Pattern
return
def extractImage(self, virtual=False):
"""
Use gdal python bindings to extract image
"""
try:
from osgeo import gdal
except ImportError:
raise Exception('GDAL python bindings not found. Need this for RSAT2/ TandemX / Sentinel1A.')
if self.output is None:
raise Exception('No output directory specified')
if not self._parsed:
self.parse()
numberBursts = len(self.product.bursts)
if (numberBursts == 0):
raise Exception('NODATA: No bursts to extract')
if '002.36' in self.product.processingSoftwareVersion:
'''Range dependent correction needed.'''
if self.auxFile is None:
self.auxFile = s1_findAuxFile(self.auxDir,self.product.bursts[numberBursts//2].sensingMid,
mission = self.product.mission)
if self.auxFile is None:
print('******************************')
print('Warning: Strongly recommend using auxiliary information')
print(' when using products generated with IPF 002.36')
print('******************************')
####These get set if stitching multiple slices
####Slices can have different burst dimensions
width = self._burstWidth
length = self._burstLength
####Check if aux file corrections are needed
useAuxCorrections = False
if ('002.36' in self.product.processingSoftwareVersion) and (self.auxFile is not None):
useAuxCorrections = True
###If not specified, for single slice, use width and length from first burst
if width is None:
width = self.product.bursts[0].numberOfSamples
if length is None:
length = self.product.bursts[0].numberOfLines
os.makedirs(self.output, exist_ok=True)
prevTiff = None
for index, burst in enumerate(self.product.bursts):
####tiff for single slice
if (len(self._tiffSrc) == 0) and (len(self.tiff)==1):
tiffToRead = self.tiff[0]
else: ##tiffSrc for multi slice
tiffToRead = self._tiffSrc[index]
###To minimize reads and speed up
if tiffToRead != prevTiff:
src=None
band=None
src = gdal.Open(tiffToRead, gdal.GA_ReadOnly)
fullWidth = src.RasterXSize
fullLength = src.RasterYSize
band = src.GetRasterBand(1)
prevTiff = tiffToRead
outfile = os.path.join(self.output, 'burst_%02d'%(index+1) + '.slc')
originalWidth = burst.numberOfSamples
originalLength = burst.numberOfLines
####Use burstnumber to look into tiff file
####burstNumber still refers to original burst in slice
lineOffset = (burst.burstNumber-1) * burst.numberOfLines
###We are doing this before we extract any data because
###renderHdr also calls renderVRT and for virtual calls
###we will overwrite the VRT.
###Ideally, when we move to a single VRT interface, this
###will occur later
####Render ISCE XML
slcImage = isceobj.createSlcImage()
slcImage.setByteOrder('l')
slcImage.setFilename(outfile)
slcImage.setAccessMode('read')
slcImage.setWidth(width)
slcImage.setLength(length)
slcImage.setXmin(0)
slcImage.setXmax(width)