/
RasterDataAdapter.java
1813 lines (1684 loc) · 70 KB
/
RasterDataAdapter.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) 2013-2022 Contributors to the Eclipse Foundation
*
* <p> See the NOTICE file distributed with this work for additional information regarding copyright
* ownership. All rights reserved. This program and the accompanying materials are made available
* under the terms of the Apache License, Version 2.0 which accompanies this distribution and is
* available at http://www.apache.org/licenses/LICENSE-2.0.txt
*/
package org.locationtech.geowave.adapter.raster.adapter;
import java.awt.Color;
import java.awt.Point;
import java.awt.Rectangle;
import java.awt.geom.AffineTransform;
import java.awt.geom.NoninvertibleTransformException;
import java.awt.image.BufferedImage;
import java.awt.image.ColorModel;
import java.awt.image.DataBuffer;
import java.awt.image.Raster;
import java.awt.image.RenderedImage;
import java.awt.image.SampleModel;
import java.awt.image.WritableRaster;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.NavigableMap;
import java.util.Set;
import java.util.TreeMap;
import javax.measure.Unit;
import javax.media.jai.Interpolation;
import javax.media.jai.InterpolationBicubic2;
import javax.media.jai.InterpolationBilinear;
import javax.media.jai.InterpolationNearest;
import javax.media.jai.PlanarImage;
import javax.media.jai.remote.SerializableState;
import javax.media.jai.remote.SerializerFactory;
import org.apache.commons.lang3.tuple.Pair;
import org.apache.commons.math.util.MathUtils;
import org.geotools.coverage.Category;
import org.geotools.coverage.CoverageFactoryFinder;
import org.geotools.coverage.GridSampleDimension;
import org.geotools.coverage.TypeMap;
import org.geotools.coverage.grid.GridCoverage2D;
import org.geotools.coverage.grid.GridCoverageFactory;
import org.geotools.coverage.grid.GridEnvelope2D;
import org.geotools.coverage.grid.GridGeometry2D;
import org.geotools.coverage.processing.Operations;
import org.geotools.coverage.util.CoverageUtilities;
import org.geotools.geometry.GeneralEnvelope;
import org.geotools.geometry.jts.GeometryClipper;
import org.geotools.geometry.jts.JTS;
import org.geotools.geometry.jts.ReferencedEnvelope;
import org.geotools.metadata.i18n.Vocabulary;
import org.geotools.metadata.i18n.VocabularyKeys;
import org.geotools.referencing.operation.projection.MapProjection;
import org.geotools.referencing.operation.transform.AffineTransform2D;
import org.geotools.renderer.lite.RendererUtilities;
import org.geotools.util.NumberRange;
import org.geotools.util.SimpleInternationalString;
import org.locationtech.geowave.adapter.raster.FitToIndexGridCoverage;
import org.locationtech.geowave.adapter.raster.RasterUtils;
import org.locationtech.geowave.adapter.raster.Resolution;
import org.locationtech.geowave.adapter.raster.adapter.merge.MultiAdapterServerMergeStrategy;
import org.locationtech.geowave.adapter.raster.adapter.merge.RasterTileMergeStrategy;
import org.locationtech.geowave.adapter.raster.adapter.merge.RasterTileRowTransform;
import org.locationtech.geowave.adapter.raster.adapter.merge.SingleAdapterServerMergeStrategy;
import org.locationtech.geowave.adapter.raster.adapter.merge.nodata.NoDataMergeStrategy;
import org.locationtech.geowave.adapter.raster.adapter.warp.WarpRIF;
import org.locationtech.geowave.adapter.raster.stats.HistogramConfig;
import org.locationtech.geowave.adapter.raster.stats.RasterBoundingBoxStatistic;
import org.locationtech.geowave.adapter.raster.stats.RasterHistogramStatistic;
import org.locationtech.geowave.adapter.raster.stats.RasterOverviewStatistic;
import org.locationtech.geowave.adapter.raster.util.SampleModelPersistenceUtils;
import org.locationtech.geowave.core.geotime.index.dimension.LatitudeDefinition;
import org.locationtech.geowave.core.geotime.index.dimension.LongitudeDefinition;
import org.locationtech.geowave.core.geotime.store.dimension.CustomCRSSpatialDimension;
import org.locationtech.geowave.core.geotime.util.GeometryUtils;
import org.locationtech.geowave.core.index.ByteArrayUtils;
import org.locationtech.geowave.core.index.CompoundIndexStrategy;
import org.locationtech.geowave.core.index.HierarchicalNumericIndexStrategy;
import org.locationtech.geowave.core.index.HierarchicalNumericIndexStrategy.SubStrategy;
import org.locationtech.geowave.core.index.IndexUtils;
import org.locationtech.geowave.core.index.StringUtils;
import org.locationtech.geowave.core.index.VarintUtils;
import org.locationtech.geowave.core.index.dimension.NumericDimensionDefinition;
import org.locationtech.geowave.core.index.numeric.BasicNumericDataset;
import org.locationtech.geowave.core.index.numeric.MultiDimensionalNumericData;
import org.locationtech.geowave.core.index.numeric.NumericRange;
import org.locationtech.geowave.core.index.persist.Persistable;
import org.locationtech.geowave.core.index.persist.PersistenceUtils;
import org.locationtech.geowave.core.store.adapter.FieldDescriptor;
import org.locationtech.geowave.core.store.adapter.FieldDescriptorBuilder;
import org.locationtech.geowave.core.store.adapter.IndexDependentDataAdapter;
import org.locationtech.geowave.core.store.adapter.InternalDataAdapter;
import org.locationtech.geowave.core.store.adapter.RowMergingDataAdapter;
import org.locationtech.geowave.core.store.api.Index;
import org.locationtech.geowave.core.store.api.RowBuilder;
import org.locationtech.geowave.core.store.api.Statistic;
import org.locationtech.geowave.core.store.api.StatisticValue;
import org.locationtech.geowave.core.store.api.VisibilityHandler;
import org.locationtech.geowave.core.store.data.field.FieldReader;
import org.locationtech.geowave.core.store.data.field.FieldWriter;
import org.locationtech.geowave.core.store.statistics.DefaultStatisticsProvider;
import org.locationtech.geowave.core.store.util.CompoundHierarchicalIndexStrategyWrapper;
import org.locationtech.geowave.core.store.util.IteratorWrapper;
import org.locationtech.geowave.core.store.util.IteratorWrapper.Converter;
import org.locationtech.geowave.mapreduce.HadoopDataAdapter;
import org.locationtech.geowave.mapreduce.HadoopWritableSerializer;
import org.locationtech.jts.geom.Geometry;
import org.locationtech.jts.geom.GeometryFactory;
import org.locationtech.jts.geom.PrecisionModel;
import org.opengis.coverage.ColorInterpretation;
import org.opengis.coverage.SampleDimension;
import org.opengis.coverage.SampleDimensionType;
import org.opengis.coverage.grid.GridCoverage;
import org.opengis.coverage.grid.GridEnvelope;
import org.opengis.geometry.Envelope;
import org.opengis.referencing.FactoryException;
import org.opengis.referencing.crs.CoordinateReferenceSystem;
import org.opengis.referencing.datum.PixelInCell;
import org.opengis.referencing.operation.TransformException;
import org.opengis.util.InternationalString;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.beust.jcommander.internal.Lists;
import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
public class RasterDataAdapter implements
IndexDependentDataAdapter<GridCoverage>,
HadoopDataAdapter<GridCoverage, GridCoverageWritable>,
RowMergingDataAdapter<GridCoverage, RasterTile<?>>,
DefaultStatisticsProvider {
// Moved static initialization to constructor (staticInit)
public static final String TILE_METADATA_PROPERTY_KEY = "TILE_METADATA";
private static boolean classInit = false;
private static Object CLASS_INIT_MUTEX = new Object();
private static final Logger LOGGER = LoggerFactory.getLogger(RasterDataAdapter.class);
protected static final String DATA_FIELD_ID = "image";
public static final int DEFAULT_TILE_SIZE = 256;
public static final boolean DEFAULT_BUILD_PYRAMID = false;
public static final boolean DEFAULT_BUILD_HISTOGRAM = true;
private static final FieldDescriptor<RasterTile> IMAGE_FIELD =
new FieldDescriptorBuilder<>(RasterTile.class).fieldName(DATA_FIELD_ID).build();
private static final FieldDescriptor<?>[] FIELDS = new FieldDescriptor[] {IMAGE_FIELD};
/** A transparent color for missing data. */
private static final Color TRANSPARENT = new Color(0, 0, 0, 0);
private String coverageName;
protected int tileSize;
private SampleModel sampleModel;
private ColorModel colorModel;
private Map<String, String> metadata;
private HistogramConfig histogramConfig;
private double[][] noDataValuesPerBand;
private double[] minsPerBand;
private double[] maxesPerBand;
private String[] namesPerBand;
private double[] backgroundValuesPerBand;
private boolean buildPyramid;
private RasterTileMergeStrategy<?> mergeStrategy;
private boolean equalizeHistogram;
private Interpolation interpolation;
public RasterDataAdapter() {}
public RasterDataAdapter(
final String coverageName,
final Map<String, String> metadata,
final GridCoverage2D originalGridCoverage) {
this(
coverageName,
metadata,
originalGridCoverage,
DEFAULT_TILE_SIZE,
DEFAULT_BUILD_PYRAMID,
DEFAULT_BUILD_HISTOGRAM,
new double[originalGridCoverage.getNumSampleDimensions()][],
new NoDataMergeStrategy());
}
public RasterDataAdapter(
final String coverageName,
final Map<String, String> metadata,
final GridCoverage2D originalGridCoverage,
final int tileSize,
final boolean buildPyramid) {
this(
coverageName,
metadata,
originalGridCoverage,
tileSize,
buildPyramid,
DEFAULT_BUILD_HISTOGRAM,
new double[originalGridCoverage.getNumSampleDimensions()][],
new NoDataMergeStrategy());
}
public RasterDataAdapter(
final String coverageName,
final Map<String, String> metadata,
final GridCoverage2D originalGridCoverage,
final int tileSize,
final boolean buildPyramid,
final boolean buildHistogram,
final double[][] noDataValuesPerBand) {
this(
coverageName,
metadata,
originalGridCoverage,
tileSize,
buildPyramid,
buildHistogram,
noDataValuesPerBand,
new NoDataMergeStrategy());
}
public RasterDataAdapter(
final String coverageName,
final Map<String, String> metadata,
final GridCoverage2D originalGridCoverage,
final int tileSize,
final boolean buildPyramid,
final boolean buildHistogram,
final double[][] noDataValuesPerBand,
final RasterTileMergeStrategy<?> mergeStrategy) {
staticInit();
final RenderedImage img = originalGridCoverage.getRenderedImage();
final SampleModel imgSampleModel = img.getSampleModel();
if ((imgSampleModel.getWidth() != tileSize) || (imgSampleModel.getHeight() != tileSize)) {
sampleModel = imgSampleModel.createCompatibleSampleModel(tileSize, tileSize);
} else {
sampleModel = imgSampleModel;
}
colorModel = img.getColorModel();
this.metadata = metadata;
this.coverageName = coverageName;
this.tileSize = tileSize;
if (buildHistogram) {
histogramConfig = new HistogramConfig(sampleModel);
} else {
histogramConfig = null;
}
if ((noDataValuesPerBand != null) && (noDataValuesPerBand.length != 0)) {
this.noDataValuesPerBand = noDataValuesPerBand;
backgroundValuesPerBand = new double[noDataValuesPerBand.length];
for (int d = 0; d < this.noDataValuesPerBand.length; d++) {
if ((noDataValuesPerBand[d] != null) && (noDataValuesPerBand[d].length > 0)) {
backgroundValuesPerBand[d] = noDataValuesPerBand[d][0];
} else {
backgroundValuesPerBand[d] = 0.0;
}
}
} else {
this.noDataValuesPerBand = new double[originalGridCoverage.getNumSampleDimensions()][];
for (int d = 0; d < this.noDataValuesPerBand.length; d++) {
this.noDataValuesPerBand[d] = originalGridCoverage.getSampleDimension(d).getNoDataValues();
}
backgroundValuesPerBand = CoverageUtilities.getBackgroundValues(originalGridCoverage);
}
this.buildPyramid = buildPyramid;
this.mergeStrategy = mergeStrategy;
}
public RasterDataAdapter(
final String coverageName,
final SampleModel sampleModel,
final ColorModel colorModel,
final Map<String, String> metadata,
final int tileSize,
final double[][] noDataValuesPerBand,
final double[] backgroundValuesPerBand,
final boolean buildPyramid) {
this(
coverageName,
sampleModel,
colorModel,
metadata,
tileSize,
noDataValuesPerBand,
backgroundValuesPerBand,
new HistogramConfig(sampleModel),
true,
Interpolation.INTERP_NEAREST,
buildPyramid,
new NoDataMergeStrategy());
}
public RasterDataAdapter(final RasterDataAdapter adapter, final String coverageName) {
this(adapter, coverageName, adapter.tileSize);
}
public RasterDataAdapter(
final RasterDataAdapter adapter,
final String coverageName,
final int tileSize) {
this(
coverageName,
adapter.getSampleModel().createCompatibleSampleModel(tileSize, tileSize),
adapter.getColorModel(),
adapter.getMetadata(),
tileSize,
adapter.getNoDataValuesPerBand(),
adapter.backgroundValuesPerBand,
adapter.histogramConfig,
adapter.equalizeHistogram,
interpolationToByte(adapter.interpolation),
adapter.buildPyramid,
adapter.mergeStrategy == null ? null : adapter.mergeStrategy);
}
public RasterDataAdapter(
final RasterDataAdapter adapter,
final String coverageName,
final RasterTileMergeStrategy<?> mergeStrategy) {
this(
coverageName,
adapter.getSampleModel(),
adapter.getColorModel(),
adapter.getMetadata(),
adapter.tileSize,
null,
null,
null,
adapter.getNoDataValuesPerBand(),
adapter.backgroundValuesPerBand,
adapter.histogramConfig,
adapter.equalizeHistogram,
interpolationToByte(adapter.interpolation),
adapter.buildPyramid,
mergeStrategy);
}
public RasterDataAdapter(
final String coverageName,
final SampleModel sampleModel,
final ColorModel colorModel,
final Map<String, String> metadata,
final int tileSize,
final double[][] noDataValuesPerBand,
final double[] backgroundValuesPerBand,
final HistogramConfig histogramConfig,
final boolean equalizeHistogram,
final int interpolationType,
final boolean buildPyramid,
final RasterTileMergeStrategy<?> mergeStrategy) {
this(
coverageName,
sampleModel,
colorModel,
metadata,
tileSize,
null,
null,
null,
noDataValuesPerBand,
backgroundValuesPerBand,
histogramConfig,
equalizeHistogram,
interpolationType,
buildPyramid,
mergeStrategy);
}
public RasterDataAdapter(
final String coverageName,
final SampleModel sampleModel,
final ColorModel colorModel,
final Map<String, String> metadata,
final int tileSize,
final double[] minsPerBand,
final double[] maxesPerBand,
final String[] namesPerBand,
final double[][] noDataValuesPerBand,
final double[] backgroundValuesPerBand,
final HistogramConfig histogramConfig,
final boolean equalizeHistogram,
final int interpolationType,
final boolean buildPyramid,
final RasterTileMergeStrategy<?> mergeStrategy) {
staticInit();
this.coverageName = coverageName;
this.tileSize = tileSize;
if ((sampleModel.getWidth() != tileSize) || (sampleModel.getHeight() != tileSize)) {
this.sampleModel = sampleModel.createCompatibleSampleModel(tileSize, tileSize);
} else {
this.sampleModel = sampleModel;
}
this.colorModel = colorModel;
this.metadata = metadata;
this.minsPerBand = minsPerBand;
this.maxesPerBand = maxesPerBand;
this.namesPerBand = namesPerBand;
this.noDataValuesPerBand = noDataValuesPerBand;
this.backgroundValuesPerBand = backgroundValuesPerBand;
// a null histogram config will result in histogram statistics not being
// accumulated
this.histogramConfig = histogramConfig;
this.buildPyramid = buildPyramid;
this.equalizeHistogram = equalizeHistogram;
interpolation = Interpolation.getInstance(interpolationType);
this.mergeStrategy = mergeStrategy;
}
@SuppressFBWarnings
private static void staticInit() {
// check outside of synchronized block to optimize performance
if (!classInit) {
synchronized (CLASS_INIT_MUTEX) {
// check again within synchonized block to ensure thread safety
if (!classInit) {
try {
GeometryUtils.initClassLoader();
SourceThresholdFixMosaicDescriptor.register(false);
WarpRIF.register(false);
MapProjection.SKIP_SANITY_CHECKS = true;
classInit = true;
} catch (final Exception e) {
LOGGER.error("Error in static init", e);
}
}
}
}
}
@Override
public Iterator<GridCoverage> convertToIndex(final Index index, final GridCoverage gridCoverage) {
final HierarchicalNumericIndexStrategy indexStrategy =
CompoundHierarchicalIndexStrategyWrapper.findHierarchicalStrategy(index.getIndexStrategy());
if (indexStrategy != null) {
final CoordinateReferenceSystem sourceCrs = gridCoverage.getCoordinateReferenceSystem();
final Envelope sampleEnvelope = gridCoverage.getEnvelope();
final ReferencedEnvelope sampleReferencedEnvelope =
new ReferencedEnvelope(
new org.locationtech.jts.geom.Envelope(
sampleEnvelope.getMinimum(0),
sampleEnvelope.getMaximum(0),
sampleEnvelope.getMinimum(1),
sampleEnvelope.getMaximum(1)),
gridCoverage.getCoordinateReferenceSystem());
ReferencedEnvelope projectedReferenceEnvelope = sampleReferencedEnvelope;
final CoordinateReferenceSystem indexCrs = GeometryUtils.getIndexCrs(index);
if (!indexCrs.equals(sourceCrs)) {
try {
projectedReferenceEnvelope = sampleReferencedEnvelope.transform(indexCrs, true);
} catch (TransformException | FactoryException e) {
LOGGER.warn("Unable to transform envelope of grid coverage to Index CRS", e);
}
}
final MultiDimensionalNumericData bounds;
if (indexCrs.equals(GeometryUtils.getDefaultCRS())) {
bounds =
IndexUtils.clampAtIndexBounds(
GeometryUtils.basicConstraintSetFromEnvelope(
projectedReferenceEnvelope).getIndexConstraints(indexStrategy),
indexStrategy);
} else {
bounds =
IndexUtils.clampAtIndexBounds(
GeometryUtils.getBoundsFromEnvelope(projectedReferenceEnvelope),
indexStrategy);
}
final GridEnvelope gridEnvelope = gridCoverage.getGridGeometry().getGridRange();
// only one set of constraints..hence reference '0' element
final double[] tileRangePerDimension = new double[bounds.getDimensionCount()];
final Double[] maxValuesPerDimension = bounds.getMaxValuesPerDimension();
final Double[] minValuesPerDimension = bounds.getMinValuesPerDimension();
for (int d = 0; d < tileRangePerDimension.length; d++) {
tileRangePerDimension[d] =
((maxValuesPerDimension[d] - minValuesPerDimension[d]) * tileSize)
/ gridEnvelope.getSpan(d);
}
final TreeMap<Double, SubStrategy> substrategyMap = new TreeMap<>();
for (final SubStrategy pyramidLevel : indexStrategy.getSubStrategies()) {
final double[] idRangePerDimension =
pyramidLevel.getIndexStrategy().getHighestPrecisionIdRangePerDimension();
// to create a pyramid, ingest into each substrategy that is
// lower resolution than the sample set in at least one
// dimension and the one substrategy that is at least the same
// resolution or higher resolution to retain the original
// resolution as well as possible
double maxSubstrategyResToSampleSetRes = -Double.MAX_VALUE;
for (int d = 0; d < tileRangePerDimension.length; d++) {
final double substrategyResToSampleSetRes =
idRangePerDimension[d] / tileRangePerDimension[d];
maxSubstrategyResToSampleSetRes =
Math.max(maxSubstrategyResToSampleSetRes, substrategyResToSampleSetRes);
}
substrategyMap.put(maxSubstrategyResToSampleSetRes, pyramidLevel);
}
// all entries will be greater than 1 (lower resolution pyramid
// levels)
// also try to find the one entry that is closest to 1.0 without
// going over (this will be the full resolution level)
// add an epsilon to try to catch any roundoff error
final double fullRes = 1.0 + MathUtils.EPSILON;
final Entry<Double, SubStrategy> fullResEntry = substrategyMap.floorEntry(fullRes);
final List<SubStrategy> pyramidLevels = new ArrayList<>();
if (fullResEntry != null) {
pyramidLevels.add(fullResEntry.getValue());
}
if (buildPyramid) {
final NavigableMap<Double, SubStrategy> map = substrategyMap.tailMap(fullRes, false);
pyramidLevels.addAll(map.values());
}
if (pyramidLevels.isEmpty()) {
// this case shouldn't occur theoretically, but just in case,
// make sure the substrategy closest to 1.0 is used
final Entry<Double, SubStrategy> bestEntry = substrategyMap.higherEntry(1.0);
pyramidLevels.add(bestEntry.getValue());
}
return new IteratorWrapper<>(
pyramidLevels.iterator(),
new MosaicPerPyramidLevelBuilder(
bounds,
gridCoverage,
tileSize,
backgroundValuesPerBand,
RasterUtils.getFootprint(projectedReferenceEnvelope, gridCoverage),
interpolation,
projectedReferenceEnvelope.getCoordinateReferenceSystem()));
}
LOGGER.warn(
"Strategy is not an instance of HierarchicalNumericIndexStrategy : "
+ index.getIndexStrategy().getClass().getName());
return Collections.<GridCoverage>emptyIterator();
}
private static class MosaicPerPyramidLevelBuilder implements
Converter<SubStrategy, GridCoverage> {
private final MultiDimensionalNumericData originalBounds;
private final GridCoverage originalData;
private final int tileSize;
private final double[] backgroundValuesPerBand;
private final Geometry footprint;
private final Interpolation defaultInterpolation;
private final CoordinateReferenceSystem crs;
public MosaicPerPyramidLevelBuilder(
final MultiDimensionalNumericData originalBounds,
final GridCoverage originalData,
final int tileSize,
final double[] backgroundValuesPerBand,
final Geometry footprint,
final Interpolation defaultInterpolation,
final CoordinateReferenceSystem crs) {
this.originalBounds = originalBounds;
this.originalData = originalData;
this.tileSize = tileSize;
this.backgroundValuesPerBand = backgroundValuesPerBand;
this.footprint = footprint;
this.defaultInterpolation = defaultInterpolation;
this.crs = crs;
}
@Override
public Iterator<GridCoverage> convert(final SubStrategy pyramidLevel) {
// get all pairs of partition/sort keys for insertionIds that
// represent the original bounds at this pyramid level
final Iterator<Pair<byte[], byte[]>> insertionIds =
pyramidLevel.getIndexStrategy().getInsertionIds(
originalBounds).getPartitionKeys().stream().flatMap(
partition -> partition.getSortKeys().stream().map(
sortKey -> Pair.of(partition.getPartitionKey(), sortKey))).iterator();
return new Iterator<GridCoverage>() {
@Override
public boolean hasNext() {
return insertionIds.hasNext();
}
@Override
public GridCoverage next() {
Pair<byte[], byte[]> insertionId = insertionIds.next();
if (insertionId == null) {
return null;
}
final MultiDimensionalNumericData rangePerDimension =
pyramidLevel.getIndexStrategy().getRangeForId(
insertionId.getLeft(),
insertionId.getRight());
final NumericDimensionDefinition[] dimensions =
pyramidLevel.getIndexStrategy().getOrderedDimensionDefinitions();
int longitudeIndex = 0, latitudeIndex = 1;
final double[] minDP = new double[2];
final double[] maxDP = new double[2];
for (int d = 0; d < dimensions.length; d++) {
if (dimensions[d] instanceof LatitudeDefinition) {
latitudeIndex = d;
minDP[1] = originalBounds.getMinValuesPerDimension()[d];
maxDP[1] = originalBounds.getMaxValuesPerDimension()[d];
} else if (dimensions[d] instanceof LongitudeDefinition) {
longitudeIndex = d;
minDP[0] = originalBounds.getMinValuesPerDimension()[d];
maxDP[0] = originalBounds.getMaxValuesPerDimension()[d];
} else if (dimensions[d] instanceof CustomCRSSpatialDimension) {
minDP[d] = originalBounds.getMinValuesPerDimension()[d];
maxDP[d] = originalBounds.getMaxValuesPerDimension()[d];
}
}
final Envelope originalEnvelope = new GeneralEnvelope(minDP, maxDP);
final Double[] minsPerDimension = rangePerDimension.getMinValuesPerDimension();
final Double[] maxesPerDimension = rangePerDimension.getMaxValuesPerDimension();
final ReferencedEnvelope mapExtent =
new ReferencedEnvelope(
minsPerDimension[longitudeIndex],
maxesPerDimension[longitudeIndex],
minsPerDimension[latitudeIndex],
maxesPerDimension[latitudeIndex],
crs);
final AffineTransform worldToScreenTransform =
RendererUtilities.worldToScreenTransform(
mapExtent,
new Rectangle(tileSize, tileSize));
GridGeometry2D insertionIdGeometry;
try {
final AffineTransform2D gridToCRS =
new AffineTransform2D(worldToScreenTransform.createInverse());
insertionIdGeometry =
new GridGeometry2D(
new GridEnvelope2D(new Rectangle(tileSize, tileSize)),
PixelInCell.CELL_CORNER,
gridToCRS,
crs,
null);
final double[] tileRes =
pyramidLevel.getIndexStrategy().getHighestPrecisionIdRangePerDimension();
final double[] pixelRes = new double[tileRes.length];
for (int d = 0; d < tileRes.length; d++) {
pixelRes[d] = tileRes[d] / tileSize;
}
Geometry footprintWithinTileWorldGeom = null;
Geometry footprintWithinTileScreenGeom = null;
try {
// using fixed precision for geometry factory will
// round screen geometry values to the nearest
// pixel, which seems to be the most appropriate
// behavior
final Geometry wholeFootprintScreenGeom =
new GeometryFactory(new PrecisionModel(PrecisionModel.FIXED)).createGeometry(
JTS.transform(footprint, new AffineTransform2D(worldToScreenTransform)));
final org.locationtech.jts.geom.Envelope fullTileEnvelope =
new org.locationtech.jts.geom.Envelope(0, tileSize, 0, tileSize);
final GeometryClipper tileClipper = new GeometryClipper(fullTileEnvelope);
footprintWithinTileScreenGeom = tileClipper.clip(wholeFootprintScreenGeom, true);
if (footprintWithinTileScreenGeom == null) {
// for some reason the original image
// footprint
// falls outside this insertion ID
LOGGER.warn(
"Original footprint geometry ("
+ originalData.getGridGeometry()
+ ") falls outside the insertion bounds ("
+ insertionIdGeometry
+ ")");
return null;
}
footprintWithinTileWorldGeom =
JTS.transform(
// change the precision model back
// to JTS
// default from fixed precision
new GeometryFactory().createGeometry(footprintWithinTileScreenGeom),
gridToCRS);
if (footprintWithinTileScreenGeom.covers(
new GeometryFactory().toGeometry(fullTileEnvelope))) {
// if the screen geometry fully covers the
// tile,
// don't bother carrying it forward
footprintWithinTileScreenGeom = null;
}
} catch (final TransformException e) {
LOGGER.warn("Unable to calculate geometry of footprint for tile", e);
}
Interpolation tileInterpolation = defaultInterpolation;
final int dataType = originalData.getRenderedImage().getSampleModel().getDataType();
// TODO a JAI bug "workaround" in GeoTools does not
// work, this is a workaround for the GeoTools bug
// see https://jira.codehaus.org/browse/GEOT-3585,
// and
// line 666-698 of
// org.geotools.coverage.processing.operation.Resampler2D
// (gt-coverage-12.1)
if ((dataType == DataBuffer.TYPE_FLOAT) || (dataType == DataBuffer.TYPE_DOUBLE)) {
final Envelope tileEnvelope = insertionIdGeometry.getEnvelope();
final ReferencedEnvelope tileReferencedEnvelope =
new ReferencedEnvelope(
new org.locationtech.jts.geom.Envelope(
tileEnvelope.getMinimum(0),
tileEnvelope.getMaximum(0),
tileEnvelope.getMinimum(1),
tileEnvelope.getMaximum(1)),
crs);
final Geometry tileJTSGeometry =
new GeometryFactory().toGeometry(tileReferencedEnvelope);
if (!footprint.contains(tileJTSGeometry)) {
tileInterpolation = Interpolation.getInstance(Interpolation.INTERP_NEAREST);
}
}
GridCoverage resampledCoverage =
(GridCoverage) RasterUtils.getCoverageOperations().resample(
originalData,
crs,
insertionIdGeometry,
tileInterpolation,
backgroundValuesPerBand);
// NOTE: for now this is commented out, but
// beware the
// resample operation under certain conditions,
// this requires more investigation rather than
// adding a
// hacky fix
// sometimes the resample results in an image that
// is
// not tileSize in width and height although the
// insertionIdGeometry is telling it to resample to
// tileSize
// in these cases, check and perform a rescale to
// finalize the grid coverage to guarantee it is the
// correct tileSize
final GridEnvelope e = resampledCoverage.getGridGeometry().getGridRange();
boolean resize = false;
for (int d = 0; d < e.getDimension(); d++) {
if (e.getSpan(d) != tileSize) {
resize = true;
break;
}
}
if (resize) {
resampledCoverage =
Operations.DEFAULT.scale(
resampledCoverage,
(double) tileSize / (double) e.getSpan(0),
(double) tileSize / (double) e.getSpan(1),
-resampledCoverage.getRenderedImage().getMinX(),
-resampledCoverage.getRenderedImage().getMinY());
}
if ((resampledCoverage.getRenderedImage().getWidth() != tileSize)
|| (resampledCoverage.getRenderedImage().getHeight() != tileSize)
|| (resampledCoverage.getRenderedImage().getMinX() != 0)
|| (resampledCoverage.getRenderedImage().getMinY() != 0)) {
resampledCoverage =
Operations.DEFAULT.scale(
resampledCoverage,
1,
1,
-resampledCoverage.getRenderedImage().getMinX(),
-resampledCoverage.getRenderedImage().getMinY());
}
if (pyramidLevel.getIndexStrategy() instanceof CompoundIndexStrategy) {
// this is exclusive on the end, and the tier is set
// so just get the id based on the lowest half of
// the multidimensional data
final Double[] centroids = rangePerDimension.getCentroidPerDimension();
final Double[] mins = rangePerDimension.getMinValuesPerDimension();
final NumericRange[] ranges = new NumericRange[centroids.length];
for (int d = 0; d < centroids.length; d++) {
ranges[d] = new NumericRange(mins[d], centroids[d]);
}
insertionId =
pyramidLevel.getIndexStrategy().getInsertionIds(
new BasicNumericDataset(ranges)).getFirstPartitionAndSortKeyPair();
// this is intended to allow the partitioning
// algorithm to use a consistent multi-dimensional
// dataset (so if hashing is done on the
// multi-dimensional data, it will be a consistent
// hash for each tile and merge strategies will work
// correctly)
}
return new FitToIndexGridCoverage(
resampledCoverage,
insertionId.getLeft(),
insertionId.getRight(),
new Resolution(pixelRes),
originalEnvelope,
footprintWithinTileWorldGeom,
footprintWithinTileScreenGeom,
getProperties(originalData));
} catch (IllegalArgumentException | NoninvertibleTransformException e) {
LOGGER.warn("Unable to calculate transformation for grid coordinates on write", e);
}
return null;
}
@Override
public void remove() {
insertionIds.remove();
}
};
}
}
@Override
public String getTypeName() {
return getCoverageName();
}
@Override
public byte[] getDataId(final GridCoverage entry) {
return new byte[0];
}
@Override
public InternalDataAdapter<GridCoverage> asInternalAdapter(final short internalAdapterId) {
return new InternalRasterDataAdapter(this, internalAdapterId);
}
@Override
public InternalDataAdapter<GridCoverage> asInternalAdapter(
final short internalAdapterId,
final VisibilityHandler visibilityHandler) {
return new InternalRasterDataAdapter(this, internalAdapterId, visibilityHandler);
}
public GridCoverage getCoverageFromRasterTile(
final RasterTile rasterTile,
final byte[] partitionKey,
final byte[] sortKey,
final Index index) {
final MultiDimensionalNumericData indexRange =
index.getIndexStrategy().getRangeForId(partitionKey, sortKey);
final NumericDimensionDefinition[] orderedDimensions =
index.getIndexStrategy().getOrderedDimensionDefinitions();
final Double[] minsPerDimension = indexRange.getMinValuesPerDimension();
final Double[] maxesPerDimension = indexRange.getMaxValuesPerDimension();
Double minX = null;
Double maxX = null;
Double minY = null;
Double maxY = null;
boolean wgs84 = true;
for (int d = 0; d < orderedDimensions.length; d++) {
if (orderedDimensions[d] instanceof LongitudeDefinition) {
minX = minsPerDimension[d];
maxX = maxesPerDimension[d];
} else if (orderedDimensions[d] instanceof LatitudeDefinition) {
minY = minsPerDimension[d];
maxY = maxesPerDimension[d];
} else if (orderedDimensions[d] instanceof CustomCRSSpatialDimension) {
wgs84 = false;
}
}
if (wgs84 && ((minX == null) || (minY == null) || (maxX == null) || (maxY == null))) {
return null;
}
final CoordinateReferenceSystem indexCrs = GeometryUtils.getIndexCrs(index);
final ReferencedEnvelope mapExtent =
new ReferencedEnvelope(
minsPerDimension[0],
maxesPerDimension[0],
minsPerDimension[1],
maxesPerDimension[1],
indexCrs);
try {
return prepareCoverage(rasterTile, tileSize, mapExtent);
} catch (final IOException e) {
LOGGER.warn("Unable to build grid coverage from adapter encoded data", e);
}
return null;
}
/**
* This method is responsible for creating a coverage from the supplied {@link RenderedImage}.
*
* @param image
* @return
* @throws IOException
*/
private GridCoverage2D prepareCoverage(
final RasterTile rasterTile,
final int tileSize,
final ReferencedEnvelope mapExtent) throws IOException {
final DataBuffer dataBuffer = rasterTile.getDataBuffer();
final Persistable tileMetadata = rasterTile.getMetadata();
final SampleModel sm = sampleModel.createCompatibleSampleModel(tileSize, tileSize);
final boolean alphaPremultiplied = colorModel.isAlphaPremultiplied();
final WritableRaster raster = Raster.createWritableRaster(sm, dataBuffer, null);
final int numBands = sm.getNumBands();
final BufferedImage image = new BufferedImage(colorModel, raster, alphaPremultiplied, null);
// creating bands
final ColorModel cm = image.getColorModel();
final GridSampleDimension[] bands = new GridSampleDimension[numBands];
final Set<String> bandNames = new HashSet<>();
// setting bands names.
for (int i = 0; i < numBands; i++) {
ColorInterpretation colorInterpretation = null;
String bandName = null;
if (cm != null) {
// === color interpretation
colorInterpretation = TypeMap.getColorInterpretation(cm, i);
if (colorInterpretation == null) {
throw new IOException("Unrecognized sample dimension type");
}
bandName = colorInterpretation.name();
if ((colorInterpretation == ColorInterpretation.UNDEFINED)
|| bandNames.contains(bandName)) {
// make sure we create no duplicate band names
bandName = "Band" + (i + 1);
}
} else { // no color model
bandName = "Band" + (i + 1);
colorInterpretation = ColorInterpretation.UNDEFINED;
}
// sample dimension type
final SampleDimensionType st = TypeMap.getSampleDimensionType(sm, i);
if (st == null) {
LOGGER.error("Could not get sample dimension type, getSampleDimensionType returned null");
throw new IOException(
"Could not get sample dimension type, getSampleDimensionType returned null");
}
// set some no data values, as well as Min and Max values
double noData;
double min = -Double.MAX_VALUE, max = Double.MAX_VALUE;
if (st.compareTo(SampleDimensionType.REAL_32BITS) == 0) {
noData = Float.NaN;
} else if (st.compareTo(SampleDimensionType.REAL_64BITS) == 0) {
noData = Double.NaN;
} else if (st.compareTo(SampleDimensionType.SIGNED_16BITS) == 0) {
noData = Short.MIN_VALUE;
min = Short.MIN_VALUE;
max = Short.MAX_VALUE;
} else if (st.compareTo(SampleDimensionType.SIGNED_32BITS) == 0) {
noData = Integer.MIN_VALUE;
min = Integer.MIN_VALUE;
max = Integer.MAX_VALUE;
} else if (st.compareTo(SampleDimensionType.SIGNED_8BITS) == 0) {
noData = -128;
min = -128;
max = 127;
} else {
// unsigned
noData = 0;
min = 0;
// compute max
if (st.compareTo(SampleDimensionType.UNSIGNED_1BIT) == 0) {
max = 1;
} else if (st.compareTo(SampleDimensionType.UNSIGNED_2BITS) == 0) {
max = 3;
} else if (st.compareTo(SampleDimensionType.UNSIGNED_4BITS) == 0) {
max = 7;
} else if (st.compareTo(SampleDimensionType.UNSIGNED_8BITS) == 0) {
max = 255;
} else if (st.compareTo(SampleDimensionType.UNSIGNED_16BITS) == 0) {
max = 65535;
} else if (st.compareTo(SampleDimensionType.UNSIGNED_32BITS) == 0) {
max = Math.pow(2, 32) - 1;
}
}
if ((noDataValuesPerBand != null)
&& (noDataValuesPerBand[i] != null)
&& (noDataValuesPerBand[i].length > 0)) {
// just take the first value, even if there are multiple
noData = noDataValuesPerBand[i][0];
}
if ((minsPerBand != null) && (minsPerBand.length > i)) {
min = minsPerBand[i];
}