/
Sentinel1RemoveThermalNoiseOp.java
1528 lines (1283 loc) · 65.4 KB
/
Sentinel1RemoveThermalNoiseOp.java
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
/*
* Copyright (C) 2014 by Array Systems Computing Inc. http://www.array.ca
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the Free
* Software Foundation; either version 3 of the License, or (at your option)
* any later version.
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, see http://www.gnu.org/licenses/
*/
package org.esa.s1tbx.calibration.gpf;
import com.bc.ceres.core.ProgressMonitor;
import org.esa.s1tbx.calibration.gpf.calibrators.Sentinel1Calibrator;
import org.esa.s1tbx.commons.Sentinel1Utils;
import org.esa.snap.core.datamodel.Band;
import org.esa.snap.core.datamodel.MetadataElement;
import org.esa.snap.core.datamodel.Product;
import org.esa.snap.core.datamodel.ProductData;
import org.esa.snap.core.datamodel.VirtualBand;
import org.esa.snap.core.gpf.Operator;
import org.esa.snap.core.gpf.OperatorException;
import org.esa.snap.core.gpf.OperatorSpi;
import org.esa.snap.core.gpf.Tile;
import org.esa.snap.core.gpf.annotations.OperatorMetadata;
import org.esa.snap.core.gpf.annotations.Parameter;
import org.esa.snap.core.gpf.annotations.SourceProduct;
import org.esa.snap.core.gpf.annotations.TargetProduct;
import org.esa.snap.core.util.ProductUtils;
import org.esa.snap.core.util.SystemUtils;
import org.esa.snap.engine_utilities.datamodel.AbstractMetadata;
import org.esa.snap.engine_utilities.datamodel.Unit;
import org.esa.snap.engine_utilities.eo.Constants;
import org.esa.snap.engine_utilities.gpf.InputProductValidator;
import org.esa.snap.engine_utilities.gpf.OperatorUtils;
import org.esa.snap.engine_utilities.gpf.TileIndex;
import org.esa.snap.engine_utilities.util.Maths;
import java.awt.Rectangle;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
/**
* Apply thermal noise correction to Sentinel-1 Level-1 products.
*/
@OperatorMetadata(alias = "ThermalNoiseRemoval",
category = "Radar/Radiometric",
authors = "Cecilia Wong, Jun Lu, Luis Veci",
copyright = "Copyright (C) 2014 by Array Systems Computing Inc.",
version = "1.0",
description = "Removes thermal noise from products")
public final class Sentinel1RemoveThermalNoiseOp extends Operator {
@SourceProduct
private Product sourceProduct;
@TargetProduct
private Product targetProduct;
@Parameter(description = "The list of polarisations", label = "Polarisations")
private String[] selectedPolarisations;
@Parameter(description = "Remove thermal noise", defaultValue = "true", label = "Remove Thermal Noise")
private Boolean removeThermalNoise = true;
@Parameter(description = "Re-introduce thermal noise", defaultValue = "false", label = "Re-Introduce Thermal Noise")
private Boolean reIntroduceThermalNoise = false;
private MetadataElement absRoot = null;
private MetadataElement origMetadataRoot = null;
private boolean absoluteCalibrationPerformed = false;
private boolean isComplex = false;
private boolean inputSigmaBand = false;
private boolean inputBetaBand = false;
private boolean inputGammaBand = false;
private boolean inputDNBand = false;
private boolean isTOPSARSLC = false;
private String productType = null;
private int numOfSubSwath = 1;
private ThermalNoiseInfo[] noise = null;
private Sentinel1Calibrator.CalibrationInfo[] calibration = null;
private List<String> selectedPolList = null;
private final HashMap<String, String[]> targetBandNameToSourceBandName = new HashMap<>(2);
// For after IPF 2.9.0 ...
private double version = 0.0f;
private boolean isTOPS = false;
private boolean isGRD = false;
public static float trgFloorValue = 0.01234567890000f;
private static final String PRODUCT_SUFFIX = "_NR";
private static class TimeMaps {
private final HashMap<String, Double> t0Map = new HashMap<>();
private final HashMap<String, Double> deltaTsMap = new HashMap<>();
private final HashMap<String, double[]> swathStartEndTimesMap = new HashMap<>();
}
/**
* Default constructor. The graph processing framework
* requires that an operator has a default constructor.
*/
public Sentinel1RemoveThermalNoiseOp() {
}
/**
* Initializes this operator and sets the one and only target product.
* <p>The target product can be either defined by a field of type {@link Product} annotated with the
* {@link TargetProduct TargetProduct} annotation or
* by calling {@link #setTargetProduct} method.</p>
* <p>The framework calls this method after it has created this operator.
* Any client code that must be performed before computation of tile data
* should be placed here.</p>
*
* @throws OperatorException If an error occurs during operator initialisation.
* @see #getTargetProduct()
*/
@Override
public void initialize() throws OperatorException {
try {
final InputProductValidator validator = new InputProductValidator(sourceProduct);
validator.checkIfSentinel1Product();
validator.checkAcquisitionMode(new String[] {"IW","EW","SM"});
validator.checkProductType(new String[] {"SLC","GRD"});
absRoot = AbstractMetadata.getAbstractedMetadata(sourceProduct);
origMetadataRoot = AbstractMetadata.getOriginalProductMetadata(sourceProduct);
getIPFVersion();
getProductType();
getAcquisitionMode();
getThermalNoiseCorrectionFlag();
setSelectedPolarisations();
if (version < 2.9 || !isTOPS) { // SM SLC/GRD do not have noise azimuth vectors
noise = getThermalNoiseVectors(origMetadataRoot, selectedPolList, numOfSubSwath);
}
getSampleType();
getCalibrationFlag();
if (absoluteCalibrationPerformed) {
getCalibrationVectors();
}
createTargetProduct();
updateTargetProductMetadata();
} catch (Throwable e) {
OperatorUtils.catchOperatorException(getId(), e);
}
}
/**
* Get product type from abstracted metadata.
*/
private void getProductType() {
productType = absRoot.getAttributeString(AbstractMetadata.PRODUCT_TYPE);
String mode = absRoot.getAttributeString(AbstractMetadata.ACQUISITION_MODE);
isTOPSARSLC = productType.contains("SLC") && (mode.contains("IW") || mode.contains("EW"));
final MetadataElement annotationElem = origMetadataRoot.getElement("annotation");
final MetadataElement[] annotationDataSetListElem = annotationElem.getElements();
final String imageName = annotationDataSetListElem[0].getName();
isTOPS = mode.contains("IW") || mode.contains("EW");
isGRD = productType.contains("GRD");
}
/**
* Get acquisition mode from abstracted metadata.
*/
private void getAcquisitionMode() {
final String acquisitionMode = absRoot.getAttributeString(AbstractMetadata.ACQUISITION_MODE);
if (productType.equals("SLC")) {
if (acquisitionMode.equals("IW")) {
numOfSubSwath = 3;
} else if (acquisitionMode.equals("EW")) {
numOfSubSwath = 5;
}
}
}
/**
* Get thermal noise correction flag from the original product metadata.
*/
private void getThermalNoiseCorrectionFlag() {
final MetadataElement annotationElem = origMetadataRoot.getElement("annotation");
final MetadataElement[] annotationDataSetListElem = annotationElem.getElements();
final MetadataElement productElem = annotationDataSetListElem[0].getElement("product");
final MetadataElement imageAnnotationElem = productElem.getElement("imageAnnotation");
final MetadataElement processingInformationElem = imageAnnotationElem.getElement("processingInformation");
Boolean thermalNoiseCorrectionPerformed = Boolean.parseBoolean(
processingInformationElem.getAttribute("thermalNoiseCorrectionPerformed").getData().getElemString());
if (removeThermalNoise && thermalNoiseCorrectionPerformed) {
throw new OperatorException("Thermal noise correction has already been performed for the product");
}
if (reIntroduceThermalNoise && !thermalNoiseCorrectionPerformed) {
throw new OperatorException("Thermal noise correction has never been performed for the product");
}
}
/**
* Get thermal noise vectors from the original product metadata.
*/
public static ThermalNoiseInfo[] getThermalNoiseVectors(final MetadataElement origMetadataRoot,
final List<String> selectedPolList,
final int numOfSubSwath) throws IOException {
final ThermalNoiseInfo[] noise = new ThermalNoiseInfo[numOfSubSwath * selectedPolList.size()];
if(origMetadataRoot == null) {
throw new IOException("Unable to find original product metadata");
}
final MetadataElement noiseElem = origMetadataRoot.getElement("noise");
if(noiseElem == null) {
throw new IOException("Unable to find noise element in original product metadata");
}
final MetadataElement[] noiseDataSetListElem = noiseElem.getElements();
int dataSetIndex = 0;
for (MetadataElement dataSetListElem : noiseDataSetListElem) {
final MetadataElement noiElem = dataSetListElem.getElement("noise");
final MetadataElement adsHeaderElem = noiElem.getElement("adsHeader");
final String pol = adsHeaderElem.getAttributeString("polarisation");
if (!selectedPolList.contains(pol)) {
continue;
}
MetadataElement noiseVectorListElem = noiElem.getElement("noiseVectorList");
// Called by S1CalibrationTPGAction
if (noiseVectorListElem == null) {
noiseVectorListElem = noiElem.getElement("noiseRangeVectorList");
}
final String subSwath = adsHeaderElem.getAttributeString("swath");
noise[dataSetIndex] = new ThermalNoiseInfo(pol, subSwath,
Sentinel1Utils.getTime(adsHeaderElem, "startTime").getMJD(),
Sentinel1Utils.getTime(adsHeaderElem, "stopTime").getMJD(),
Sentinel1Calibrator.getNumOfLines(origMetadataRoot, pol, subSwath),
Integer.parseInt(noiseVectorListElem.getAttributeString("count")),
Sentinel1Utils.getNoiseVector(noiseVectorListElem));
dataSetIndex++;
}
return noise;
}
private void getSampleType() {
final String sampleType = absRoot.getAttributeString(AbstractMetadata.SAMPLE_TYPE);
if (sampleType.equals("COMPLEX")) {
isComplex = true;
}
}
/**
* Get absolute calibration flag from the abstracted metadata.
*/
private void getCalibrationFlag() {
absoluteCalibrationPerformed =
absRoot.getAttribute(AbstractMetadata.abs_calibration_flag).getData().getElemBoolean();
if (absoluteCalibrationPerformed) {
if (isComplex) {
// Currently the calibrated complex product can only be sigma0, this should be changed later if
// complex beta0 and gamma0 are available
inputSigmaBand = true;
} else {
final String[] sourceBandNames = sourceProduct.getBandNames();
for (String bandName : sourceBandNames) {
if (bandName.contains("Sigma0")) {
inputSigmaBand = true;
} else if (bandName.contains("Gamma0")) {
inputGammaBand = true;
} else if (bandName.contains("Beta0")) {
inputBetaBand = true;
} else if (bandName.contains("DN")) {
inputDNBand = true;
}
}
if (!inputSigmaBand && !inputGammaBand && !inputBetaBand && !inputDNBand) {
throw new OperatorException("For calibrated product, Sigma0 or Gamma0 or Beta0 or DN band is expected");
}
}
}
}
/**
* Get calibration vectors from the original product metadata.
*/
private void getCalibrationVectors() throws IOException {
calibration = Sentinel1Calibrator.getCalibrationVectors(
sourceProduct,
selectedPolList,
inputSigmaBand,
inputBetaBand,
inputGammaBand,
inputDNBand);
}
/**
* Set user selected polarisations.
*/
private void setSelectedPolarisations() {
String[] selectedPols = selectedPolarisations;
if (selectedPols == null || selectedPols.length == 0) {
selectedPols = Sentinel1Utils.getProductPolarizations(absRoot);
}
selectedPolList = Arrays.asList(selectedPols);
}
/**
* Create a target product for output.
*/
private void createTargetProduct() {
targetProduct = new Product(sourceProduct.getName() + PRODUCT_SUFFIX,
sourceProduct.getProductType(),
sourceProduct.getSceneRasterWidth(),
sourceProduct.getSceneRasterHeight());
addSelectedBands();
ProductUtils.copyProductNodes(sourceProduct, targetProduct);
}
/**
* Add user selected bands to target product.
*/
private void addSelectedBands() {
final Band[] sourceBands = sourceProduct.getBands();
for (int i = 0; i < sourceBands.length; i++) {
final Band srcBand = sourceBands[i];
if (srcBand instanceof VirtualBand) {
continue;
}
final String unit = srcBand.getUnit();
if (unit == null) {
throw new OperatorException("band " + srcBand.getName() + " requires a unit");
}
if (!unit.contains(Unit.REAL) && !unit.contains(Unit.AMPLITUDE) && !unit.contains(Unit.INTENSITY)) {
continue;
}
String[] srcBandNames;
if (unit.contains(Unit.REAL)) { // SLC
if (i + 1 >= sourceBands.length) {
throw new OperatorException("Real and imaginary bands are not in pairs");
}
final String nextUnit = sourceBands[i + 1].getUnit();
if (nextUnit == null || !nextUnit.contains(Unit.IMAGINARY)) {
throw new OperatorException("Real and imaginary bands are not in pairs");
}
srcBandNames = new String[2];
srcBandNames[0] = srcBand.getName();
srcBandNames[1] = sourceBands[i + 1].getName();
++i;
} else { // GRD
srcBandNames = new String[1];
srcBandNames[0] = srcBand.getName();
}
final String pol = srcBandNames[0].substring(srcBandNames[0].lastIndexOf("_") + 1);
if (!selectedPolList.contains(pol)) {
continue;
}
final String targetBandName = createTargetBandName(srcBandNames[0]);
if (targetProduct.getBand(targetBandName) == null) {
targetBandNameToSourceBandName.put(targetBandName, srcBandNames);
final Band targetBand = new Band(
targetBandName,
ProductData.TYPE_FLOAT32,
srcBand.getRasterWidth(),
srcBand.getRasterHeight());
targetBand.setUnit(Unit.INTENSITY);
targetBand.setDescription(srcBand.getDescription());
targetBand.setNoDataValue(srcBand.getNoDataValue());
targetBand.setNoDataValueUsed(true);
targetProduct.addBand(targetBand);
}
}
}
/**
* Create target band name for given source bane name.
*
* @param sourceBandName Source band name string.
* @return Target band name string.
*/
private String createTargetBandName(final String sourceBandName) {
final String pol = sourceBandName.substring(sourceBandName.indexOf('_'));
if (absoluteCalibrationPerformed) {
if (isComplex) {
return "Sigma0" + pol;
} else {
return sourceBandName;
}
}
return "Intensity" + pol;
}
/**
* Update target product metadata.
*/
private void updateTargetProductMetadata() {
final MetadataElement abs = AbstractMetadata.getAbstractedMetadata(targetProduct);
final String[] targetBandNames = targetProduct.getBandNames();
Sentinel1Utils.updateBandNames(abs, selectedPolList, targetBandNames);
final MetadataElement origMetadataRoot = AbstractMetadata.getOriginalProductMetadata(targetProduct);
final MetadataElement annotationElem = origMetadataRoot.getElement("annotation");
final MetadataElement[] annotationDataSetListElem = annotationElem.getElements();
for (MetadataElement elem : annotationDataSetListElem) {
final MetadataElement productElem = elem.getElement("product");
final MetadataElement imageAnnotationElem = productElem.getElement("imageAnnotation");
final MetadataElement processingInformationElem = imageAnnotationElem.getElement("processingInformation");
if (removeThermalNoise) {
processingInformationElem.getAttribute("thermalNoiseCorrectionPerformed").getData().setElems("true");
}
if (reIntroduceThermalNoise) {
processingInformationElem.getAttribute("thermalNoiseCorrectionPerformed").getData().setElems("false");
}
}
}
private double[][] populateNoiseAzimuthBlock(
final int x0, final int y0, final int w, final int h, final String targetBandName) {
if (version >= 2.9) {
final TimeMaps timeMaps = new TimeMaps();
if (isGRD) {
return buildNoiseLUTForTOPSGRD(x0, y0, w, h, targetBandName, timeMaps);
} else if (isTOPSARSLC) {
return buildNoiseLUTForTOPSSLC(x0, y0, w, h, targetBandName, timeMaps);
}
}
return null;
}
/**
* Called by the framework in order to compute a tile for the given target band.
* <p>The default implementation throws a runtime exception with the message "not implemented".</p>
*
* @param targetBand The target band.
* @param targetTile The current tile associated with the target band to be computed.
* @param pm A progress monitor which should be used to determine computation cancelation requests.
* @throws OperatorException If an error occurs during computation of the target raster.
*/
@Override
public void computeTile(Band targetBand, Tile targetTile, ProgressMonitor pm) throws OperatorException {
final Rectangle targetTileRectangle = targetTile.getRectangle();
final int x0 = targetTileRectangle.x;
final int y0 = targetTileRectangle.y;
final int w = targetTileRectangle.width;
final int h = targetTileRectangle.height;
//System.out.println("x0 = " + x0 + ", y0 = " + y0 + ", w = " + w + ", h = " + h + ", target band = " + targetBand.getName());
try {
final String targetBandName = targetBand.getName();
double[][] noiseBlock = null;
if (version >= 2.9) {
noiseBlock = populateNoiseAzimuthBlock(x0, y0, w, h, targetBandName);
}
Tile sourceRaster1 = null;
ProductData srcData1 = null;
ProductData srcData2 = null;
Band sourceBand1 = null;
final String[] srcBandNames = targetBandNameToSourceBandName.get(targetBandName);
if (srcBandNames.length == 1) {
sourceBand1 = sourceProduct.getBand(srcBandNames[0]);
sourceRaster1 = getSourceTile(sourceBand1, targetTileRectangle);
srcData1 = sourceRaster1.getDataBuffer();
} else {
sourceBand1 = sourceProduct.getBand(srcBandNames[0]);
final Band sourceBand2 = sourceProduct.getBand(srcBandNames[1]);
sourceRaster1 = getSourceTile(sourceBand1, targetTileRectangle);
final Tile sourceRaster2 = getSourceTile(sourceBand2, targetTileRectangle);
srcData1 = sourceRaster1.getDataBuffer();
srcData2 = sourceRaster2.getDataBuffer();
}
final double srcNoDataValue = sourceBand1.getNoDataValue();
final Unit.UnitType bandUnit = Unit.getUnitType(sourceBand1);
final ProductData trgData = targetTile.getDataBuffer();
final TileIndex srcIndex = new TileIndex(sourceRaster1);
final TileIndex tgtIndex = new TileIndex(targetTile);
final int maxY = y0 + h;
final int maxX = x0 + w;
final boolean complexData = bandUnit == Unit.UnitType.REAL || bandUnit == Unit.UnitType.IMAGINARY;
String key = "";
if (version >= 2.9 && isTOPS) {
if (complexData) { // SLC
key = targetBandName.substring(10).toLowerCase();
} else { // GRD
key = getBandPol(targetBandName);
}
}
Sentinel1Calibrator.CalibrationInfo calInfo = null;
Sentinel1Calibrator.CALTYPE calType = null;
if (absoluteCalibrationPerformed) {
calInfo = getCalInfo(targetBandName);
calType = Sentinel1Calibrator.getCalibrationType(targetBandName);
}
double dn, dn2, i, q;
int srcIdx, tgtIdx;
for (int y = y0; y < maxY; ++y) {
srcIndex.calculateStride(y);
tgtIndex.calculateStride(y);
double[] lut = new double[w];
if (absoluteCalibrationPerformed) {
final int calVecIdx = calInfo.getCalibrationVectorIndex(y);
final Sentinel1Utils.CalibrationVector vec0 = calInfo.getCalibrationVector(calVecIdx);
final Sentinel1Utils.CalibrationVector vec1 = calInfo.getCalibrationVector(calVecIdx + 1);
final float[] vec0LUT = Sentinel1Calibrator.getVector(calType, vec0);
final float[] vec1LUT = Sentinel1Calibrator.getVector(calType, vec1);
final Sentinel1Utils.CalibrationVector calVec = calInfo.calibrationVectorList[calVecIdx];
final int pixelIdx0 = calVec.getPixelIndex(x0);
if (version < 2.9) {
final ThermalNoiseInfo noiseInfo = getNoiseInfo(targetBandName);
computeTileScaledNoiseLUT(y, x0, w, noiseInfo, calInfo, vec0.timeMJD, vec1.timeMJD,
vec0LUT, vec1LUT, vec0.pixels, pixelIdx0, lut);
} else {
computeTileScaledNoiseLUT(y, x0, y0, w, noiseBlock, calInfo, vec0.timeMJD, vec1.timeMJD,
vec0LUT, vec1LUT, vec0.pixels, pixelIdx0, lut);
}
} else {
if (version < 2.9) {
final ThermalNoiseInfo noiseInfo = getNoiseInfo(targetBandName);
computeTileNoiseLUT(y, x0, w, noiseInfo, lut);
} else {
computeTileNoiseLUT(y - y0, x0, w, noiseBlock, lut);
}
}
for (int x = x0; x < maxX; ++x) {
final int xx = x - x0;
srcIdx = srcIndex.getIndex(x);
tgtIdx = tgtIndex.getIndex(x);
if (bandUnit == Unit.UnitType.AMPLITUDE) {
dn = srcData1.getElemDoubleAt(srcIdx);
dn2 = dn * dn;
} else if (complexData) {
i = srcData1.getElemDoubleAt(srcIdx);
q = srcData2.getElemDoubleAt(srcIdx);
dn2 = i * i + q * q;
} else if (bandUnit == Unit.UnitType.INTENSITY) {
dn2 = srcData1.getElemDoubleAt(srcIdx);
} else {
throw new OperatorException("Unhandled unit");
}
if(dn2 == srcNoDataValue) {
trgData.setElemDoubleAt(tgtIdx, srcNoDataValue);
continue;
}
double value = dn2 - lut[xx];
if(value < 0) {
//value = dn2; // small intensity value; if too small, calibration will make it nodatavalue
// Eq-1 in Section 6 of MPC-0392 DI-MPC-TN Issue 1.1 2017,Nov.28 "Thermal Denoising of Products Generated by the S-1 IPF"
value = (dn2 == 0.0?trgFloorValue:dn2);
}
trgData.setElemDoubleAt(tgtIdx, value);
}
}
} catch (Throwable e) {
throw new OperatorException(e.getMessage());
}
}
/**
* Get thermal noise information for given target band.
*
* @param targetBandName Target band name.
* @return The ThermalNoiseInfo object.
*/
private ThermalNoiseInfo getNoiseInfo(final String targetBandName) throws OperatorException {
for (ThermalNoiseInfo noiseInfo : noise) {
if (isTOPSARSLC) {
if (targetBandName.contains(noiseInfo.polarization) && targetBandName.contains(noiseInfo.subSwath)) {
return noiseInfo;
}
} else {
if (targetBandName.contains(noiseInfo.polarization)) {
return noiseInfo;
}
}
}
throw new OperatorException("NoiseInfo not found for "+targetBandName);
}
/**
* Get calibration information for given target band.
*
* @param targetBandName Target band name.
* @return The CalibrationInfo object.
*/
private Sentinel1Calibrator.CalibrationInfo getCalInfo(final String targetBandName) {
for (Sentinel1Calibrator.CalibrationInfo cal : calibration) {
final String pol = cal.polarization;
final String ss = cal.subSwath;
if (isTOPSARSLC) {
if (targetBandName.contains(pol) && targetBandName.contains(ss)) {
return cal;
}
} else {
if (targetBandName.contains(pol)) {
return cal;
}
}
}
return null;
}
/**
* Compute scaled noise LUTs for the given range line.
*
* @param y Index of the given range line.
* @param x0 X coordinate of the upper left corner pixel of the given tile.
* @param w Tile width.
* @param noiseInfo Object of ThermalNoiseInfo class.
* @param calInfo Object of CalibrationInfo class.
* @param lut The scaled noise LUT.
*/
private void computeTileScaledNoiseLUT(final int y, final int x0, final int w,
final ThermalNoiseInfo noiseInfo,
final Sentinel1Calibrator.CalibrationInfo calInfo,
final double azT0, final double azT1,
final float[] vec0LUT, final float[] vec1LUT,
final int[] vec0Pixels, final int pixelIdx0,
final double[] lut) {
final double[] noiseLut = new double[w];
computeTileNoiseLUT(y, x0, w, noiseInfo, noiseLut);
final double[] calLut = new double[w];
computeTileCalibrationLUTs(y, x0, w, calInfo, azT0, azT1,
vec0LUT, vec1LUT, vec0Pixels, pixelIdx0, calLut);
if (removeThermalNoise) {
for (int i = 0; i < w; i++) {
lut[i] = noiseLut[i] / (calLut[i]*calLut[i]);
}
} else { // reIntroduceThermalNoise
for (int i = 0; i < w; i++) {
lut[i] = -noiseLut[i] / (calLut[i]*calLut[i]);
}
}
}
private void computeTileScaledNoiseLUT(final int y, final int x0, final int y0, final int w,
final double[][] noiseBlock,
final Sentinel1Calibrator.CalibrationInfo calInfo,
final double azT0, final double azT1,
final float[] vec0LUT, final float[] vec1LUT,
final int[] vec0Pixels, final int pixelIdx0,
final double[] lut) {
final double[] calLut = new double[w];
computeTileCalibrationLUTs(y, x0, w, calInfo, azT0, azT1,
vec0LUT, vec1LUT, vec0Pixels, pixelIdx0, calLut);
final int yy = y - y0;
if (removeThermalNoise) {
for (int i = 0; i < w; i++) {
lut[i] = noiseBlock[yy][i] / (calLut[i]*calLut[i]);
}
} else { // reIntroduceThermalNoise
for (int i = 0; i < w; i++) {
lut[i] = -noiseBlock[yy][i] / (calLut[i]*calLut[i]);
}
}
}
/**
* Compute calibration LUTs for the given range line.
*
* @param y Index of the given range line.
* @param x0 X coordinate of the upper left corner pixel of the given tile.
* @param w Tile width.
* @param calInfo Object of CalibrationInfo class.
* @param lut LUT for calibration.
*/
private static void computeTileCalibrationLUTs(final int y, final int x0, final int w,
final Sentinel1Calibrator.CalibrationInfo calInfo,
final double azT0, final double azT1,
final float[] vec0LUT, final float[] vec1LUT,
final int[] vec0Pixels, int pixelIdx0,
final double[] lut) {
final double azTime = calInfo.firstLineTime + y * calInfo.lineTimeInterval;
double muX, muY = (azTime - azT0) / (azT1 - azT0);
int pixelIdx = pixelIdx0;
final int maxX = x0 + w;
for (int x = x0; x < maxX; x++) {
if (x > vec0Pixels[pixelIdx + 1]) {
pixelIdx++;
}
muX = (double) (x - vec0Pixels[pixelIdx]) / (double) (vec0Pixels[pixelIdx + 1] - vec0Pixels[pixelIdx]);
lut[x - x0] = Maths.interpolationBiLinear(
vec0LUT[pixelIdx], vec0LUT[pixelIdx + 1], vec1LUT[pixelIdx], vec1LUT[pixelIdx + 1], muX, muY);
}
}
/**
* Compute noise LUTs for the given range line.
*
* @param y Index of the given range line.
* @param x0 X coordinate of the upper left corner pixel of the given tile.
* @param w Tile width.
* @param noiseInfo Object of ThermalNoiseInfo class.
* @param lut The noise LUT.
*/
private static void computeTileNoiseLUT(final int y, final int x0, final int w,
final ThermalNoiseInfo noiseInfo, final double[] lut) {
try {
final int noiseVecIdx = getNoiseVectorIndex(y, noiseInfo);
final Sentinel1Utils.NoiseVector noiseVector0 = noiseInfo.noiseVectorList[noiseVecIdx];
final Sentinel1Utils.NoiseVector noiseVector1 = noiseInfo.noiseVectorList[noiseVecIdx + 1];
final double azTime = noiseInfo.firstLineTime + y * noiseInfo.lineTimeInterval;
final double azT0 = noiseVector0.timeMJD;
final double azT1 = noiseVector1.timeMJD;
final double muY = (azTime - azT0) / (azT1 - azT0);
int pixelIdx0 = getPixelIndex(x0, noiseVector0);
int pixelIdx1 = getPixelIndex(x0, noiseVector1);
final int maxLength0 = noiseVector0.pixels.length - 2;
final int maxLength1 = noiseVector1.pixels.length - 2;
final int maxX = x0 + w;
for (int x = x0; x < maxX; x++) {
if (x > noiseVector0.pixels[pixelIdx0 + 1] && pixelIdx0 < maxLength0) {
pixelIdx0++;
}
final int x00 = noiseVector0.pixels[pixelIdx0];
final int x01 = noiseVector0.pixels[pixelIdx0 + 1];
final double muX0 = (double) (x - x00) / (double) (x01 - x00);
final double noise0 = Maths.interpolationLinear(
noiseVector0.noiseLUT[pixelIdx0], noiseVector0.noiseLUT[pixelIdx0 + 1], muX0);
if (x > noiseVector1.pixels[pixelIdx1 + 1] && pixelIdx1 < maxLength1) {
pixelIdx1++;
}
final int x10 = noiseVector1.pixels[pixelIdx1];
final int x11 = noiseVector1.pixels[pixelIdx1 + 1];
final double muX1 = (double) (x - x10) / (double) (x11 - x10);
final double noise1 = Maths.interpolationLinear(
noiseVector1.noiseLUT[pixelIdx1], noiseVector1.noiseLUT[pixelIdx1 + 1], muX1);
lut[x - x0] = Maths.interpolationLinear(noise0, noise1, muY);
}
} catch (Throwable e) {
OperatorUtils.catchOperatorException("computeTileNoiseLUT", e);
}
}
private static void computeTileNoiseLUT(final int yy, final int x0, final int w,
final double[][] noiseBlock, final double[] lut) {
try {
final int maxX = x0 + w;
for (int x = x0; x < maxX; x++) {
final int xx = x - x0;
lut[xx] = noiseBlock[yy][xx];
}
} catch (Throwable e) {
OperatorUtils.catchOperatorException("computeTileNoiseLUT", e);
}
}
/**
* Get index of the noise vector in the list for a given line.
*
* @param y Line coordinate.
* @param noiseInfo Object of ThermalNoiseInfo class.
* @return The noise vector index.
*/
private static int getNoiseVectorIndex(final int y, final ThermalNoiseInfo noiseInfo) {
for (int i = 1; i < noiseInfo.count; i++) {
if (y < noiseInfo.noiseVectorList[i].line) {
return i - 1;
}
}
return noiseInfo.count - 2;
}
/**
* Get pixel index in a given noise vector for a given pixel.
*
* @param x Pixel coordinate.
* @param noiseVector Noise vector.
* @return The pixel index.
*/
private static int getPixelIndex(final int x, final Sentinel1Utils.NoiseVector noiseVector) {
for (int i = 0; i < noiseVector.pixels.length; i++) {
if (x < noiseVector.pixels[i]) {
return i - 1;
}
}
return noiseVector.pixels.length - 2;
}
private void getIPFVersion() {
final String procSysId = absRoot.getAttributeString(AbstractMetadata.ProcessingSystemIdentifier);
version = Double.valueOf(procSysId.substring(procSysId.lastIndexOf(" ")));
//System.out.println("Sentinel1RemoveThermalNoiseOp: IPF version = " + version);
}
private double[][] buildNoiseLUTForTOPSSLC(
final int x0, final int y0, final int w, final int h, final String targetBandName, final TimeMaps timeMaps) {
final String targetBandPol = getBandPol(targetBandName).toLowerCase();
final String targetBandSwath = getBandSwath(targetBandName).toLowerCase();
final MetadataElement noiseElem = origMetadataRoot.getElement("noise");
final MetadataElement[] noiseDataSetListElem = noiseElem.getElements();
Sentinel1Utils.NoiseAzimuthVector[] noiseAzimuthVectors = null;
Sentinel1Utils.NoiseVector[] noiseRangeVectors = null;
for (MetadataElement dataSetListElem : noiseDataSetListElem) {
final String imageName = dataSetListElem.getName();
if (!imageName.toLowerCase().contains(targetBandPol) || !imageName.toLowerCase().contains(targetBandSwath)){
continue;
}
getT0andDeltaTS(imageName, timeMaps);
final MetadataElement noiElem = dataSetListElem.getElement("noise");
MetadataElement noiseAzimuthVectorListElem = noiElem.getElement("noiseAzimuthVectorList");
noiseAzimuthVectors = Sentinel1Utils.getAzimuthNoiseVector(noiseAzimuthVectorListElem);
MetadataElement noiseRangeVectorListElem = noiElem.getElement("noiseRangeVectorList");
noiseRangeVectors = Sentinel1Utils.getNoiseVector(noiseRangeVectorListElem);
}
final MetadataElement annotationElem = origMetadataRoot.getElement("annotation");
final MetadataElement[] annotationDataSetListElem = annotationElem.getElements();
final HashMap<String, Sentinel1Utils.NoiseVector> burstToRangeVectorMap = new HashMap<>();
int linesPerBurst = 0;
for (MetadataElement elem : annotationDataSetListElem) {
final String imageName = elem.getName();
if (!imageName.toLowerCase().contains(targetBandPol) || !imageName.toLowerCase().contains(targetBandSwath)){
continue;
}
final MetadataElement productElem = elem.getElement("product");
final MetadataElement swathTimingElem = productElem.getElement("swathTiming");
linesPerBurst = swathTimingElem.getAttributeInt("linesPerBurst");
//final int samplesPerBurst = swathTimingElem.getAttributeInt("samplesPerBurst");
final MetadataElement burstListElem = swathTimingElem.getElement("burstList");
final MetadataElement[] burstListArray = burstListElem.getElements();
for (int i = 0; i < burstListArray.length; i++) {
final int burstCenterLine = i*linesPerBurst + linesPerBurst/2;
burstToRangeVectorMap.put("burst_" + i, getBurstRangeVector(burstCenterLine, noiseRangeVectors));
}
}
// create noise matrix for the tile
double[][] noiseMatrix = new double[h][w];
populateNoiseMatrixForTOPSSLC(
noiseAzimuthVectors[0], burstToRangeVectorMap, linesPerBurst, x0, y0, w, h, noiseMatrix);
return noiseMatrix;
}
private Sentinel1Utils.NoiseVector getBurstRangeVector(
final int burstCenterLine, final Sentinel1Utils.NoiseVector[] noiseRangeVectors) {
int closest = 0;
for (int j = 1; j < noiseRangeVectors.length; j++) {
if (Math.abs(burstCenterLine - noiseRangeVectors[j].line) <
Math.abs(burstCenterLine - noiseRangeVectors[closest].line)) {
closest = j;
}
}
return noiseRangeVectors[closest];
}
private void populateNoiseMatrixForTOPSSLC(final Sentinel1Utils.NoiseAzimuthVector noiseAzimuthVector,
final HashMap<String, Sentinel1Utils.NoiseVector> burstToRangeVectorMap,
final int linesPerBurst,
final int x0, final int y0, final int w, final int h,
final double[][] noiseMatrix) {
final int xMax = x0 + w - 1;
final int yMax = y0 + h - 1;
final double[] interpolatedAzimuthVector = new double[h];
interpolNoiseAzimuthVector(noiseAzimuthVector, y0, yMax, interpolatedAzimuthVector);
int currentNoiseVectorLine = Integer.MAX_VALUE;
double[] interpolatedRangeVector = new double[w];
for (int y = y0; y <= yMax; ++y) {
final int yy = y - y0;
final int burstIdx = y / linesPerBurst;
final Sentinel1Utils.NoiseVector noiseRangeVector = burstToRangeVectorMap.get("burst_" + burstIdx);
if (noiseRangeVector.line != currentNoiseVectorLine) {
currentNoiseVectorLine = noiseRangeVector.line;
interpolNoiseRangeVector(noiseRangeVector, x0, xMax, interpolatedRangeVector);
}
for (int x = x0; x <= xMax; ++x) {
final int xx = x - x0;
noiseMatrix[yy][xx] = interpolatedAzimuthVector[yy] * interpolatedRangeVector[xx];
}
}
}
private double[][] buildNoiseLUTForTOPSGRD(
final int x0, final int y0, final int w, final int h, final String targetBandName, final TimeMaps timeMaps) {
final int xMax = x0 + w - 1;
final int yMax = y0 + h - 1;
final String targetBandPol = getBandPol(targetBandName);
final MetadataElement noiseElem = origMetadataRoot.getElement("noise");
final MetadataElement[] noiseDataSetListElem = noiseElem.getElements();
// loop through s1a-iw-grd-hh-..., s1a-iw-grd-hv-... (TOPS (IW and EW) GRD products)
for (MetadataElement dataSetListElem : noiseDataSetListElem) {
// imageName is s1a-iw-grd-hh-... or s1a-ew1-slc-hh-...
final MetadataElement noiElem = dataSetListElem.getElement("noise");
final MetadataElement adsHeaderElem = noiElem.getElement("adsHeader");
final String pol = adsHeaderElem.getAttributeString("polarisation");
if (!pol.equals(targetBandPol)) {
continue;
}
final String imageName = dataSetListElem.getName();
// get the noise azimuth vectors
MetadataElement noiseAzimuthVectorListElem = noiElem.getElement("noiseAzimuthVectorList");