-
Notifications
You must be signed in to change notification settings - Fork 5
/
geopysparkdatacube.py
2614 lines (2284 loc) · 129 KB
/
geopysparkdatacube.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
import collections
import collections.abc
import json
import logging
import math
import os
import pathlib
import subprocess
import tempfile
from datetime import datetime, date
from functools import partial
from typing import Dict, List, Union, Tuple, Iterable, Callable, Optional
import geopyspark as gps
import numpy as np
import pandas as pd
import geopandas as gpd
import pyproj
import pytz
import xarray as xr
from geopyspark import TiledRasterLayer, Pyramid, Tile, SpaceTimeKey, SpatialKey, Metadata
from geopyspark.geotrellis import Extent, ResampleMethod
from geopyspark.geotrellis.constants import CellType
from pandas import Series
from pyproj import CRS
from shapely.geometry import mapping, Point, Polygon, MultiPolygon, GeometryCollection, box
from shapely.geometry.base import BaseGeometry, BaseMultipartGeometry
from openeo.internal.process_graph_visitor import ProcessGraphVisitor
from openeo.metadata import Band
from openeo.udf import UdfData
from openeo.udf.xarraydatacube import XarrayDataCube, XarrayIO
from openeo.util import dict_no_none, str_truncate
from openeo_driver.datacube import DriverDataCube, DriverVectorCube
from openeo_driver.datastructs import ResolutionMergeArgs
from openeo_driver.datastructs import SarBackscatterArgs
from openeo_driver.delayed_vector import DelayedVector
from openeo_driver.errors import FeatureUnsupportedException, OpenEOApiException, \
ProcessParameterInvalidException
from openeo_driver.ProcessGraphDeserializer import convert_node, _period_to_intervals
from openeo_driver.save_result import AggregatePolygonResult
from openeo_driver.utils import EvalEnv, smart_bool
from openeogeotrellis.config import get_backend_config
from openeogeotrellis.configparams import ConfigParams
from openeogeotrellis.geopysparkcubemetadata import GeopysparkCubeMetadata
from openeogeotrellis.ml.geopysparkmlmodel import GeopysparkMlModel
from openeogeotrellis.processgraphvisiting import GeotrellisTileProcessGraphVisitor, SingleNodeUDFProcessGraphVisitor
from openeogeotrellis.ml.aggregatespatialvectorcube import AggregateSpatialVectorCube
from openeogeotrellis.utils import (
to_projected_polygons,
log_memory,
ensure_executor_logging,
get_jvm,
temp_csv_dir,
reproject_cellsize,
normalize_temporal_extent,
)
from openeogeotrellis.udf import run_udf_code
from openeogeotrellis._version import __version__ as softwareversion
from openeogeotrellis.vectorcube import AggregateSpatialResultCSV
_log = logging.getLogger(__name__)
SpatialExtent = collections.namedtuple("SpatialExtent", ["top", "bottom", "right", "left", "height", "width"])
def callsite(func):
def try_str(f):
try:
if(isinstance(f,DriverDataCube)):
if( f.metadata.has_band_dimension()):
return ",".join(f.metadata.band_names)
else:
return 'datacube'
if (isinstance(f, DriverVectorCube)):
return 'vectorcube'
if (isinstance(f, dict)):
return str_truncate(", ".join(f.keys()), width=40)
return str_truncate(str(f),width=32)
except Exception as e:
return repr(e)
def run(*args, **kwargs):
name = func.__name__
arg_str = ','.join(map(try_str,args))
kwargs_str = ','.join(map(try_str, kwargs.values()))
full = ", ".join([name,arg_str,kwargs_str])
gps.get_spark_context().setLocalProperty("callSite.short",full)
try:
return func(*args, **kwargs)
finally:
gps.get_spark_context().setLocalProperty("callSite.short", None)
return run
class GeopysparkDataCube(DriverDataCube):
metadata: GeopysparkCubeMetadata = None
def __init__(
self, pyramid: Pyramid,
metadata: GeopysparkCubeMetadata = None
):
super().__init__(metadata=metadata or GeopysparkCubeMetadata({}))
self.pyramid = pyramid
def _is_spatial(self):
return self.get_max_level().layer_type == gps.LayerType.SPATIAL
def apply_to_levels(self, func, metadata: GeopysparkCubeMetadata = None) -> 'GeopysparkDataCube':
"""
Applies a function to each level of the pyramid. The argument provided to the function is of type TiledRasterLayer
:param func:
:return:
"""
pyramid = Pyramid({k: func(l) for k, l in self.pyramid.levels.items()})
return GeopysparkDataCube(pyramid=pyramid, metadata=metadata or self.metadata)
@staticmethod
def _convert_celltype(layer: TiledRasterLayer, cell_type: CellType):
tiled_raster_layer = TiledRasterLayer(layer.layer_type, layer.srdd.convertDataType(cell_type))
tiled_raster_layer = GeopysparkDataCube._transform_metadata(tiled_raster_layer, cellType=cell_type)
return tiled_raster_layer
def _create_tilelayer(self,contextrdd, layer_type, zoom_level):
jvm = get_jvm()
spatial_tiled_raster_layer = jvm.geopyspark.geotrellis.SpatialTiledRasterLayer
temporal_tiled_raster_layer = jvm.geopyspark.geotrellis.TemporalTiledRasterLayer
if layer_type == gps.LayerType.SPATIAL:
srdd = spatial_tiled_raster_layer.apply(jvm.scala.Option.apply(zoom_level),contextrdd)
else:
srdd = temporal_tiled_raster_layer.apply(jvm.scala.Option.apply(zoom_level),contextrdd)
return gps.TiledRasterLayer(layer_type, srdd)
def _apply_to_levels_geotrellis_rdd(self, func, metadata: GeopysparkCubeMetadata = None, target_type = None):
"""
Applies a function to each level of the pyramid. The argument provided to the function is the Geotrellis ContextRDD.
:param func:
:return:
"""
pyramid = Pyramid({
k: self._create_tilelayer(func(l.srdd.rdd(), k), l.layer_type if target_type==None else target_type , k)
for k, l in self.pyramid.levels.items()
})
return GeopysparkDataCube(pyramid=pyramid, metadata=metadata or self.metadata)
def _data_source_type(self):
return self.metadata.get("_vito", "data_source", "type", default="Accumulo")
# TODO: deprecated
def date_range_filter(
self, start_date: Union[str, datetime, date], end_date: Union[str, datetime, date]
) -> 'GeopysparkDataCube':
return self.apply_to_levels(lambda rdd: rdd.filter_by_times([pd.to_datetime(start_date),pd.to_datetime(end_date)]))
@callsite
def filter_temporal(self, start: str, end: str) -> 'GeopysparkDataCube':
# TODO: is this necessary? Temporal range is handled already at load_collection time
start, end = normalize_temporal_extent((start, end))
return self.apply_to_levels(
lambda rdd: rdd.filter_by_times([pd.to_datetime(start), pd.to_datetime(end)]),
metadata=self.metadata.filter_temporal(start, end)
)
@callsite
def filter_bbox(self, west, east, north, south, crs=None, base=None, height=None) -> 'GeopysparkDataCube':
return self.filter_spatial(geometries=box(west,south,east,north),geometry_crs=crs,mask=False)
@callsite
def filter_spatial(
self, geometries: Union[Polygon, MultiPolygon, DriverVectorCube], geometry_crs="EPSG:4326", mask=True
) -> "GeopysparkDataCube":
# TODO: support more geometry types but geopyspark.geotrellis.layer.TiledRasterLayer.mask doesn't seem to work
# with e.g. GeometryCollection
max_level = self.get_max_level()
layer_crs = max_level.layer_metadata.crs
if isinstance(geometries, DriverVectorCube):
geometry_crs = geometries.get_crs()
geometries = geometries.to_multipolygon()
reprojected_polygon = self.__reproject_polygon(polygon=geometries, srs=geometry_crs, dest_srs=layer_crs)
if mask:
masked = self.mask_polygon(reprojected_polygon,srs=layer_crs)
else:
masked = self
xmin, ymin, xmax, ymax = reprojected_polygon.bounds
crop_extent = get_jvm().geotrellis.vector.Extent(xmin, ymin, xmax, ymax)
crop = gps.get_spark_context()._jvm.org.openeo.geotrellis.OpenEOProcesses().crop_metadata
return masked._apply_to_levels_geotrellis_rdd(
lambda rdd, level: crop(rdd,crop_extent),
metadata=self.metadata.filter_bbox(west=xmin, south=ymin, east=xmax, north=ymax, crs=layer_crs)
)
@callsite
def filter_bands(self, bands) -> 'GeopysparkDataCube':
band_indices = [self.metadata.get_band_index(b) for b in bands]
_log.info("filter_bands({b!r}) -> indices {i!r}".format(b=bands, i=band_indices))
return self.apply_to_levels(lambda rdd: rdd.bands(band_indices), metadata=self.metadata.filter_bands(bands))
@callsite
def filter_labels(self, condition: dict, dimension: str, context: Optional[dict] = None,
env: EvalEnv = None) -> 'DriverDataCube':
#TODO this is provided by FileLayerProvider, but also need this here
return self
@callsite
def rename_dimension(self, source: str, target: str) -> 'GeopysparkDataCube':
return GeopysparkDataCube(pyramid=self.pyramid, metadata=self.metadata.rename_dimension(source, target))
@callsite
def apply(self, process: dict, *, context: Optional[dict] = None, env: EvalEnv) -> "GeopysparkDataCube":
from openeogeotrellis.backend import GeoPySparkBackendImplementation
if isinstance(process, dict):
datatype = self.get_max_level().layer_metadata.cell_type
process = GeoPySparkBackendImplementation.accept_process_graph(process, default_input_parameter="data",
default_input_datatype=datatype)
if isinstance(process, GeotrellisTileProcessGraphVisitor):
#apply should leave metadata intact, so can do a simple call?
# Note: It's not obvious from its name, but `reduce_bands` not only supports reduce operations,
# also `apply` style local unary mapping operations.
return self._apply_bands_dimension(process,context = context)
if isinstance(process, SingleNodeUDFProcessGraphVisitor):
udf, udf_context = self._extract_udf_code_and_context(process=process, context=context, env=env)
runtime = process.udf_args.get("runtime", "Python")
return self.apply_tiles(udf_code=udf, context=udf_context, runtime=runtime)
else:
raise FeatureUnsupportedException(f"Unsupported: apply with {process}")
def _extract_udf_code_and_context(
self,
process: SingleNodeUDFProcessGraphVisitor,
context: dict,
env: Optional[EvalEnv] = None,
) -> Tuple[str, dict]:
"""Extract UDF code and UDF context from given visitor and parent's context"""
udf = process.udf_args.get("udf")
if not isinstance(udf, str):
raise ValueError(f"The 'run_udf' process requires at least a 'udf' string argument, but got: {udf!r}.")
udf_context = process.udf_args.get("context", {})
# Resolve "from_parameter" references
udf_context = convert_node(udf_context, env=(env or EvalEnv()).push_parameters({"context": context}))
return udf, udf_context
@callsite
def apply_dimension(
self,
process: Union[dict, GeotrellisTileProcessGraphVisitor],
*,
dimension: str,
target_dimension: Optional[str] = None,
context: Optional[dict] = None,
env: EvalEnv,
) -> "DriverDataCube":
from openeogeotrellis.backend import GeoPySparkBackendImplementation
apply_bands = self.metadata.has_band_dimension() and dimension == self.metadata.band_dimension.name
datatype = "float32" if apply_bands else self.get_max_level().layer_metadata.cell_type
if isinstance(process, dict):
process = GeoPySparkBackendImplementation.accept_process_graph(process,default_input_parameter="data",default_input_datatype=datatype)
if isinstance(process, GeotrellisTileProcessGraphVisitor):
if self.metadata.has_temporal_dimension() and dimension == self.metadata.temporal_dimension.name:
context = convert_node(context, env=env)
pysc = gps.get_spark_context()
if self.metadata.has_band_dimension() and target_dimension == self.metadata.band_dimension.name:
#reduce the time dimension into the bands dimension
result_collection = self._apply_to_levels_geotrellis_rdd(
lambda rdd, level: pysc._jvm.org.openeo.geotrellis.OpenEOProcesses().applyTimeDimensionTargetBands(rdd,
process.builder,
context if isinstance(
context,
dict) else {}), target_type=gps.LayerType.SPATIAL)
result_collection.metadata = result_collection.metadata.reduce_dimension(dimension)
return result_collection
else:
return self._apply_to_levels_geotrellis_rdd(
lambda rdd, level: pysc._jvm.org.openeo.geotrellis.OpenEOProcesses().applyTimeDimension(rdd,process.builder,context if isinstance(context,dict) else {}))
elif apply_bands:
return self._apply_bands_dimension(process)
else:
raise FeatureUnsupportedException(f"apply_dimension along dimension {dimension} is not supported. These dimensions are available: " + str(self.metadata.dimension_names()))
if isinstance(process, SingleNodeUDFProcessGraphVisitor):
udf, udf_context = self._extract_udf_code_and_context(process=process, context=context, env=env)
runtime = process.udf_args.get("runtime", "Python")
return self._run_udf_dimension(udf=udf, udf_context=udf_context, dimension=dimension, runtime=runtime)
raise FeatureUnsupportedException(f"Unsupported: apply_dimension with {process}")
@callsite
def reduce_bands(self, pgVisitor: GeotrellisTileProcessGraphVisitor) -> 'GeopysparkDataCube':
"""
TODO Define in super class? API is not yet ready for client side...
:param pgVisitor:
:return:
"""
result = self._apply_bands_dimension(pgVisitor)
if result.metadata.has_band_dimension():
result.metadata = result.metadata.reduce_dimension(result.metadata.band_dimension.name)
return result
def _apply_bands_dimension(self, pgVisitor: GeotrellisTileProcessGraphVisitor, context=None) -> 'GeopysparkDataCube':
"""
Apply a process graph to every tile, with tile.bands (List[Tile]) as process input.
"""
# All processing is done with float32 as cell type.
float_datacube = self.apply_to_levels(lambda layer: layer.convert_data_type("float32"))
# Apply process to every tile, with tile.bands (List[Tile]) as process input.
# This is done for the entire pyramid.
pysc = gps.get_spark_context()
if isinstance(context, GeopysparkMlModel):
context = context.get_java_object()
if context is None:
context = {}
elif not isinstance(context, dict):
context = {"context": context}
if self.metadata.has_band_dimension():
context["array_labels"] = self.metadata.band_names
else:
_log.warning(f"Applying callback to the bands, but no band labels available on this datacube.")
result_cube: GeopysparkDataCube = float_datacube._apply_to_levels_geotrellis_rdd(
lambda rdd, level:
pysc._jvm.org.openeo.geotrellis.OpenEOProcesses().mapBands(
rdd, pgVisitor.builder, context
)
)
# Convert/Restrict cell type after processing.
target_cell_type = pgVisitor.builder.getOutputCellType().name()
return result_cube.apply_to_levels(lambda layer: self._convert_celltype(layer, target_cell_type))
def _normalize_temporal_reducer(self, dimension: str, reducer: str) -> str:
if dimension != self.metadata.temporal_dimension.name:
raise FeatureUnsupportedException('Reduce on dimension {d!r} not supported'.format(d=dimension))
if reducer.upper() in ["MIN", "MAX", "SUM", "MEAN", "VARIANCE", "MEDIAN", "FIRST", "LAST", "PRODUCT"]:
reducer = reducer.lower().capitalize()
elif reducer.upper() == "SD":
reducer = "StandardDeviation"
else:
raise FeatureUnsupportedException('Reducer {r!r} not supported'.format(r=reducer))
return reducer
@callsite
def add_dimension(self, name: str, label: str, type: str = None):
return GeopysparkDataCube(
pyramid=self.pyramid,
metadata=self.metadata.add_dimension(name=name, label=label, type=type)
)
@callsite
def drop_dimension(self, name: str):
if name not in self.metadata.dimension_names():
raise OpenEOApiException(status_code=400, code="DimensionNotAvailable", message=
"""Dimension with name '{}' does not exist""".format(name))
if self.metadata.has_temporal_dimension() and self.metadata.temporal_dimension.name == name:
return self.apply_to_levels(lambda l:l.to_spatial_layer(),metadata=self.metadata.drop_dimension(name=name))
elif self.metadata.has_band_dimension() and self.metadata.band_dimension.name == name:
if not len(self.metadata.bands) == 1:
raise OpenEOApiException(status_code=400, code="DimensionLabelCountMismatch", message=
"""Band dimension can only be dropped if there is only 1 band left in the datacube""")
else:
return GeopysparkDataCube(
pyramid=self.pyramid,
metadata=self.metadata.drop_dimension(name=name)
)
else:
raise OpenEOApiException(status_code=400, code="DimensionNotAvailable", message=
"""'drop_dimension' is only supported for dimension types 'bands' and 'temporal'.""")
@callsite
def dimension_labels(self, dimension: str):
if dimension not in self.metadata.dimension_names():
raise OpenEOApiException(status_code=400, code="DimensionNotAvailable", message=
"""Dimension with name '{}' does not exist""".format(dimension))
if self.metadata.has_temporal_dimension() and self.metadata.temporal_dimension.name == dimension:
return sorted(set(map(lambda k: k.instant, self.pyramid.levels[self.pyramid.max_zoom].collect_keys())))
elif self.metadata.has_band_dimension() and self.metadata.band_dimension.name == dimension:
return self.metadata.band_names
else:
raise OpenEOApiException(status_code=400, code="DimensionNotAvailable", message=
"""'dimension_labels' is only supported for dimension types 'bands' and 'temporal'.""")
@callsite
def rename_labels(self, dimension: str, target: list, source: list=None) -> 'GeopysparkDataCube':
""" Renames the labels of the specified dimension in the data cube from source to target.
:param dimension: Dimension name
:param target: The new names for the labels.
:param source: The names of the labels as they are currently in the data cube.
:return: An GeopysparkDataCube instance
"""
return GeopysparkDataCube(
pyramid=self.pyramid,
metadata=self.metadata.rename_labels(dimension,target,source)
)
@classmethod
def _mapTransform(cls, layoutDefinition, spatialKey) -> SpatialExtent:
ex = layoutDefinition.extent
x_range = ex.xmax - ex.xmin
xinc = x_range / layoutDefinition.tileLayout.layoutCols
yrange = ex.ymax - ex.ymin
yinc = yrange / layoutDefinition.tileLayout.layoutRows
return SpatialExtent(
top=ex.ymax - yinc * spatialKey.row,
bottom=ex.ymax - yinc * (spatialKey.row + 1),
right=ex.xmin + xinc * (spatialKey.col + 1),
left=ex.xmin + xinc * spatialKey.col,
height=layoutDefinition.tileLayout.tileCols,
width=layoutDefinition.tileLayout.tileRows
)
@classmethod
def _numpy_to_xarraydatacube(
cls,
bands_numpy: np.ndarray, extent: SpatialExtent,
band_coordinates: List[str],
time_coordinates: pd.DatetimeIndex = None
) -> XarrayDataCube:
"""
Converts a numpy array representing a tile to an XarrayDataCube by adding coordinates and dimension labels.
:param bands_numpy:
The numpy array with shape = (a,b,c,d).
With,
a: time (#dates) (if exists)
b: bands (#bands) (if exists)
c: y-axis (#cells)
d: x-axis (#cells)
E.g. (5,2,256,256) has tiles of 256x256 cells, each with 2 bands for 5 given dates.
:param extent:
The SpatialExtent of the tile in order to calculate the coordinates for the x and y dimensions.
If None then the resulting xarray will have no x,y coordinates.
E.g. SpatialExtent(bottom: 140, top: 145, left: 60, right: 65, height: 256, width: 256)
:param band_coordinates: A list of band names to act as coordinates for the band dimension (if exists).
:param time_coordinates: A list of dates to act as coordinates for the time dimension (if exists).
:return: An XarrayDatacube containing the given numpy array with the correct labels and coordinates.
"""
coords = {}
dims = ('bands','y', 'x')
# time coordinates if exists
if len(bands_numpy.shape) == 4:
#we have a temporal dimension
coords = {'t':time_coordinates}
dims = ('t' ,'bands','y', 'x')
# Set the band names as xarray coordinates if exists.
if band_coordinates:
# TODO: also use the band dimension name (`band_dimension.name`) instead of hardcoded "bands"?
coords['bands'] = band_coordinates
# Make sure the numpy array has the right shape.
band_count = bands_numpy.shape[dims.index('bands')]
if band_count != len(band_coordinates):
raise OpenEOApiException(
status_code=400,
message="""In run_udf, the data has {b} bands, while the 'bands' dimension has {len_dim} labels.
These labels were set on the dimension: {labels}. Please investigate if dimensions and labels are correct. The mismatch occured for {extent} and {time}.""".format(
b=band_count, len_dim=len(band_coordinates), labels=str(band_coordinates), extent = str(extent), time = time_coordinates
),
)
# Set the X and Y coordinates.
# this is tricky because if apply_neighborhood is used, then extent is the area without overlap
# in addition the coordinates are computed to cell center.
#
# VERY IMPORTANT NOTE: building x,y coordinates assumes that extent and bands_numpy is compatible
# as if it is concatenating an image:
# * spatial dimension order is [y,x] <- row-column order
# * origin is upper left corner
#
# NOTE.2.: for optimization reasons the y coordinate is computed decreasing instead of flipping the datacube (expensive)
# NOTE.3.: if extent is None, no coordinates will be generated (UDF's dominantly don't use x&y)
if extent is not None:
gridx = (extent.right - extent.left) / extent.width
gridy = (extent.top - extent.bottom) / extent.height
xdelta = gridx * 0.5 * (bands_numpy.shape[-1] - extent.width)
ydelta = gridy * 0.5 * (bands_numpy.shape[-2] - extent.height)
xmin = extent.left - xdelta
xmax = extent.right + xdelta
ymin = extent.bottom - ydelta
ymax = extent.top + ydelta
coords["x"] = np.linspace(xmin + 0.5 * gridx, xmax - 0.5 * gridx, bands_numpy.shape[-1], dtype=np.float32)
coords["y"] = np.linspace(ymax - 0.5 * gridy, ymin + 0.5 * gridy, bands_numpy.shape[-2], dtype=np.float32)
the_array = xr.DataArray(bands_numpy, coords=coords,dims=dims,name="openEODataChunk")
return XarrayDataCube(the_array)
@callsite
def apply_tiles_spatiotemporal(self, udf_code: str, udf_context: Optional[dict] = None, runtime: str = "Python", overlap_x: int = 0, overlap_y: int = 0) -> "GeopysparkDataCube":
"""
Group tiles by SpatialKey, then apply a Python function to every group of tiles.
:param udf_code: A string containing a Python function that handles groups of tiles, each labeled by date.
:return: The original data cube with its tiles transformed by the function.
"""
# Early compile to detect syntax errors
_log.info(f"[apply_tiles_spatiotemporal] Setting up for running UDF {str_truncate(udf_code, width=1000)!r}")
_ = compile(source=udf_code, filename='UDF.py', mode='exec')
if runtime == "Python-Jep":
band_names = []
if self.metadata.has_band_dimension():
band_names = self.metadata.band_dimension.band_names
new_bands: Optional[str] = None
def rdd_function(rdd, _zoom):
nonlocal new_bands # TODO: Get rid of nonlocal usage
jvm = gps.get_spark_context()._jvm
udf = jvm.org.openeo.geotrellis.udf.Udf
tup = udf.runUserCodeSpatioTemporalWithBands(udf_code, rdd, band_names, udf_context, overlap_x, overlap_y)
if new_bands:
assert new_bands == list(tup._2())
new_bands = list(tup._2())
return tup._1()
float_cube = self.apply_to_levels(lambda layer: self._convert_celltype(layer, "float32"))
ret = float_cube._apply_to_levels_geotrellis_rdd(rdd_function, self.metadata, gps.LayerType.SPACETIME)
if new_bands:
self.metadata.band_dimension.bands = [Band(b) for b in new_bands]
return ret
@ensure_executor_logging
def tile_function(metadata:Metadata,
openeo_metadata: GeopysparkCubeMetadata,
tiles: Tuple[gps.SpatialKey, List[Tuple[SpaceTimeKey, Tile]]]
) -> 'List[Tuple[gps.SpatialKey, List[Tuple[SpaceTimeKey, Tile]]]]':
tile_list = list(tiles[1])
# Sort by instant
tile_list.sort(key=lambda tup: tup[0].instant)
dates = map(lambda t: t[0].instant, tile_list)
arrays = map(lambda t: t[1].cells, tile_list)
multidim_array = np.array(list(arrays))
extent = GeopysparkDataCube._mapTransform(metadata.layout_definition, tile_list[0][0])
datacube: XarrayDataCube = GeopysparkDataCube._numpy_to_xarraydatacube(
multidim_array,
extent=extent,
band_coordinates=openeo_metadata.band_dimension.band_names if openeo_metadata.has_band_dimension() else None,
time_coordinates=pd.DatetimeIndex(dates)
)
data = UdfData(proj={"EPSG": CRS.from_user_input(metadata.crs).to_epsg()}, datacube_list=[datacube], user_context=udf_context)
_log.debug(f"[apply_tiles_spatiotemporal] running UDF {str_truncate(udf_code, width=1000)!r} on {datacube!r} with context {udf_context}")
result_data = run_udf_code(code=udf_code, data=data)
cubes = result_data.get_datacube_list()
if len(cubes) != 1:
raise ValueError(f"The provided UDF should return one datacube, but got: {result_data}")
result_array: xr.DataArray = cubes[0].array
_log.debug(f"[apply_tiles_spatiotemporal] UDF resulted in {result_array}!r")
if 't' in result_array.dims:
result_array = result_array.transpose(*('t' ,'bands','y', 'x'))
return [(SpaceTimeKey(col=tiles[0].col, row=tiles[0].row, instant=pd.Timestamp(timestamp)),
Tile(array_slice.values, CellType.FLOAT32, tile_list[0][1].no_data_value))
for timestamp, array_slice in result_array.groupby('t')]
else:
result_array = result_array.transpose(*( 'bands', 'y', 'x'))
return [(SpaceTimeKey(col=tiles[0].col, row=tiles[0].row, instant=datetime.fromisoformat('2020-01-01T00:00:00')),
Tile(result_array.values, CellType.FLOAT32, tile_list[0][1].no_data_value))]
def rdd_function(openeo_metadata: GeopysparkCubeMetadata, rdd: TiledRasterLayer) -> TiledRasterLayer:
converted = rdd.convert_data_type(CellType.FLOAT32)
float_rdd = converted.to_numpy_rdd()
def to_spatial_key(tile: Tuple[SpaceTimeKey, Tile]):
key: SpatialKey = gps.SpatialKey(tile[0].col, tile[0].row)
value: Tuple[SpaceTimeKey, Tile] = (tile[0], tile[1])
return (key, value)
b = rdd.layer_metadata.bounds
rows = b.maxKey.row - b.minKey.row + 1
partitions = (b.maxKey.col - b.minKey.col + 1) * (rows)
def partitionByKey(spatialkey):
"""
Try having one partition per timeseries to bring memory to a minimum
"""
try:
return rows * (spatialkey.col-b.minKey.col) + (spatialkey.row-b.minKey.row)
except Exception as e:
import pyspark
hashPartitioner = pyspark.rdd.portable_hash
return hashPartitioner(tuple)
# Group all tiles by SpatialKey. Save the SpaceTimeKey in the value with the Tile.
spatially_grouped = float_rdd.map(lambda tile: to_spatial_key(tile)).groupByKey(numPartitions=partitions,partitionFunc=partitionByKey)
# Apply the tile_function to all tiles with the same spatial key.
numpy_rdd = spatially_grouped.flatMap(
log_memory(partial(tile_function, rdd.layer_metadata, openeo_metadata))
)
# Convert the result back to a TiledRasterLayer.
metadata = GeopysparkDataCube._transform_metadata(rdd.layer_metadata, cellType=CellType.FLOAT32)
_log.info(f"apply_neighborhood created datacube {metadata}")
return gps.TiledRasterLayer.from_numpy_rdd(gps.LayerType.SPACETIME, numpy_rdd, metadata)
return self.apply_to_levels(partial(rdd_function, self.metadata))
@callsite
def chunk_polygon(
self,
reducer: Union[ProcessGraphVisitor, Dict],
# TODO: it's wrong to use MultiPolygon as a collection of polygons. MultiPolygons should be handled as single, atomic "features"
# also see https://github.com/Open-EO/openeo-python-driver/issues/288
chunks: MultiPolygon,
mask_value: float,
env: EvalEnv,
context: Optional[dict] = None,
) -> "GeopysparkDataCube":
# TODO: rename this to `apply_polygon`
from openeogeotrellis.backend import GeoPySparkBackendImplementation
if isinstance(reducer, dict):
reducer = GeoPySparkBackendImplementation.accept_process_graph(reducer)
if isinstance(chunks, Polygon):
chunks = [chunks]
elif isinstance(chunks, MultiPolygon):
chunks: List[Polygon] = chunks.geoms
else:
raise ValueError(f"Invalid type for `chunks`: {type(chunks)}")
jvm = get_jvm()
result_collection = None
if isinstance(reducer, SingleNodeUDFProcessGraphVisitor):
udf, udf_context = self._extract_udf_code_and_context(process=reducer, context=context, env=env)
# Polygons should use the same projection as the rdd.
# TODO Usage of GeometryCollection should be avoided. It's abused here like a FeatureCollection,
# but a GeometryCollections is conceptually just single "feature".
# What you want here is proper support for FeatureCollections or at least a list of individual geometries.
# also see https://github.com/Open-EO/openeo-python-driver/issues/71, https://github.com/Open-EO/openeo-python-driver/issues/288
reprojected_polygons: jvm.org.openeo.geotrellis.ProjectedPolygons \
= to_projected_polygons(jvm, GeometryCollection(chunks))
band_names = self.metadata.band_dimension.band_names
def rdd_function(rdd, _zoom):
return jvm.org.openeo.geotrellis.udf.Udf.runChunkPolygonUserCode(
udf, rdd, reprojected_polygons, band_names, udf_context, mask_value
)
# All JEP implementation work with float cell types.
float_cube = self.apply_to_levels(lambda layer: self._convert_celltype(layer, "float32"))
result_collection = float_cube._apply_to_levels_geotrellis_rdd(
rdd_function, self.metadata, gps.LayerType.SPACETIME
)
else:
# Use OpenEOProcessScriptBuilder.
raise NotImplementedError()
return result_collection
@callsite
def reduce_dimension(
self,
reducer: Union[ProcessGraphVisitor, Dict],
*,
dimension: str,
context: Optional[dict] = None,
env: EvalEnv,
binary=False,
) -> "GeopysparkDataCube":
from openeogeotrellis.backend import GeoPySparkBackendImplementation
if isinstance(reducer, dict):
datatype = self.get_max_level().layer_metadata.cell_type
reducer = GeoPySparkBackendImplementation.accept_process_graph(reducer, default_input_parameter="data",
default_input_datatype=datatype)
if isinstance(reducer, SingleNodeUDFProcessGraphVisitor):
udf, udf_context = self._extract_udf_code_and_context(process=reducer, context=context, env=env)
runtime = reducer.udf_args.get("runtime", "Python")
result_collection = self._run_udf_dimension(udf=udf, udf_context=udf_context, dimension=dimension, runtime=runtime)
elif self.metadata.has_band_dimension() and dimension == self.metadata.band_dimension.name:
result_collection = self._apply_bands_dimension(reducer, context)
elif self.metadata.has_temporal_dimension() and dimension == self.metadata.temporal_dimension.name:
pysc = gps.get_spark_context()
result_collection = self._apply_to_levels_geotrellis_rdd(
lambda rdd, level: pysc._jvm.org.openeo.geotrellis.OpenEOProcesses().applyTimeDimension(
rdd, reducer.builder, context if isinstance(context, dict) else {}
)
)
else:
raise FeatureUnsupportedException(
"Unsupported combination of reducer %s and dimension %s." % (reducer, dimension))
if result_collection is not None:
result_collection.metadata = result_collection.metadata.reduce_dimension(dimension)
if self.metadata.has_temporal_dimension() and dimension == self.metadata.temporal_dimension.name and self.pyramid.layer_type != gps.LayerType.SPATIAL:
result_collection = result_collection.apply_to_levels(lambda rdd: rdd.to_spatial_layer() if rdd.layer_type != gps.LayerType.SPATIAL else rdd)
return result_collection
def _run_udf_dimension(self, udf: str, udf_context: dict, dimension: str, runtime: str = "Python"):
if not isinstance(udf, str):
raise ValueError("The 'run_udf' process requires at least a 'udf' string argument, but got: '%s'." % udf)
if self.metadata.has_temporal_dimension() and dimension == self.metadata.temporal_dimension.name:
# EP-2760 a special case of reduce where only a single udf based callback is provided. The more generic case is not yet supported.
return self.apply_tiles_spatiotemporal(udf_code=udf, udf_context=udf_context, runtime=runtime)
elif self.metadata.has_band_dimension() and dimension == self.metadata.band_dimension.name:
return self.apply_tiles(udf_code=udf, context=udf_context, runtime=runtime)
else:
raise FeatureUnsupportedException(f"reduce_dimension with UDF along dimension {dimension} is not supported")
@callsite
def apply_tiles(self, udf_code: str, context={}, runtime="python", overlap_x: int = 0, overlap_y: int = 0) -> 'GeopysparkDataCube':
"""Apply a function to the given set of bands in this image collection."""
#TODO apply .bands(bands)
# Early compile to detect syntax errors
_log.info(f"[apply_tiles] setting up for running UDF {str_truncate(udf_code, width=1000)!r}")
_ = compile(source=udf_code, filename='UDF.py', mode='exec')
if runtime == 'Python-Jep':
band_names = self.metadata.band_dimension.band_names
new_bands: Optional[str] = None
def rdd_function(rdd, _zoom):
nonlocal new_bands # TODO: Get rid of nonlocal usage
jvm = gps.get_spark_context()._jvm
udf = jvm.org.openeo.geotrellis.udf.Udf
tup = udf.runUserCodeWithBands(udf_code, rdd, band_names, context, overlap_x, overlap_y)
if new_bands:
assert new_bands == list(tup._2())
new_bands = list(tup._2())
return tup._1()
# All JEP implementation work with the float datatype.
float_cube = self.apply_to_levels(lambda layer: self._convert_celltype(layer, "float32"))
ret = float_cube._apply_to_levels_geotrellis_rdd(rdd_function, self.metadata, gps.LayerType.SPACETIME)
if new_bands:
self.metadata.band_dimension.bands = [Band(b) for b in new_bands]
return ret
else:
def rdd_function(openeo_metadata: GeopysparkCubeMetadata, rdd: TiledRasterLayer):
"""
Apply a user defined function to every tile in a TiledRasterLayer
and return the transformed TiledRasterLayer.
"""
@ensure_executor_logging
def tile_function(metadata: Metadata,
openeo_metadata: GeopysparkCubeMetadata,
geotrellis_tile: Tuple[SpaceTimeKey, Tile]
) -> 'Tuple[SpaceTimeKey, Tile]':
"""
Apply a user defined function to a geopyspark.geotrellis.Tile and return the transformed tile.
"""
# Setup the UDF input data.
key = geotrellis_tile[0]
extent = GeopysparkDataCube._mapTransform(metadata.layout_definition, key)
datacube: XarrayDataCube = GeopysparkDataCube._numpy_to_xarraydatacube(
geotrellis_tile[1].cells,
extent=extent,
band_coordinates=openeo_metadata.band_dimension.band_names if openeo_metadata.has_band_dimension() else None,
)
data = UdfData(proj={"EPSG": CRS.from_user_input(metadata.crs).to_epsg()}, datacube_list=[datacube], user_context=context)
# Run UDF.
_log.debug(f"[apply_tiles] running UDF {str_truncate(udf_code, width=1000)!r} on {data}!r")
result_data = run_udf_code(code=udf_code, data=data)
_log.debug(f"[apply_tiles] UDF resulted in {result_data}!r")
# Handle the resulting xarray datacube.
cubes: List[XarrayDataCube] = result_data.get_datacube_list()
if len(cubes) != 1:
raise ValueError("The provided UDF should return one datacube, but got: " + str(cubes))
result_array: xr.DataArray = cubes[0].array
_log.info(f"apply_tiles tilefunction result dims: {result_array.dims}")
result_tile = Tile(result_array.values,
geotrellis_tile[1].cell_type,
geotrellis_tile[1].no_data_value)
return (key, result_tile)
# Convert TiledRasterLayer to PySpark RDD to access the Scala RDD cell values in Python.
numpy_rdd = rdd.convert_data_type(CellType.FLOAT32).to_numpy_rdd()
# Apply the UDF to every tile in the RDD.
# Note rdd_metadata variable:
# if rdd.layer_metadata is passed directly in lambda function it will try to serialize the entire rdd!
rdd_metadata = rdd.layer_metadata
numpy_rdd = numpy_rdd.map(
log_memory(partial(tile_function, rdd_metadata, openeo_metadata)),
preservesPartitioning=True
)
# Return the result back as a TiledRasterLayer.
metadata = GeopysparkDataCube._transform_metadata(rdd.layer_metadata, cellType=CellType.FLOAT32)
return gps.TiledRasterLayer.from_numpy_rdd(rdd.layer_type, numpy_rdd, metadata)
# Apply the UDF to every tile for every zoom level of the pyramid.
return self.apply_to_levels(partial(rdd_function, self.metadata))
def aggregate_time(self, temporal_window, aggregationfunction) -> Series :
#group keys
#reduce
pass
@callsite
def aggregate_temporal(
self, intervals: List, labels: List, reducer, dimension: str = None, context: Optional[dict] = None, reduce = True
) -> "GeopysparkDataCube":
"""Computes a temporal aggregation based on an array of date and/or time intervals.
Calendar hierarchies such as year, month, week etc. must be transformed into specific intervals by the clients. For each interval, all data along the dimension will be passed through the reducer. The computed values will be projected to the labels, so the number of labels and the number of intervals need to be equal.
If the dimension is not set, the data cube is expected to only have one temporal dimension.
:param intervals: Left-closed temporal intervals, which are allowed to overlap. Each temporal interval in the array has exactly two elements:
The first element is the start of the temporal interval. The specified instance in time is included in the interval.
The second element is the end of the temporal interval. The specified instance in time is excluded from the interval.
:param labels: Labels for the intervals. The number of labels and the number of groups need to be equal.
:param reducer: A reducer to be applied on all values along the specified dimension. The reducer must be a callable process (or a set processes) that accepts an array and computes a single return value of the same type as the input values, for example median.
:param dimension: The temporal dimension for aggregation. All data along the dimension will be passed through the specified reducer. If the dimension is not set, the data cube is expected to only have one temporal dimension.
:return: A data cube containing a result for each time window
"""
reformat_date = lambda d : pd.to_datetime(d).strftime('%Y-%m-%dT%H:%M:%SZ')
date_list = []
for interval in intervals:
if isinstance(interval,str):
date_list.append(interval)
else:
for date in interval:
date_list.append(date)
intervals_iso = [ reformat_date(date) for date in date_list ]
if(labels is not None):
labels_iso = list(map(lambda l:pd.to_datetime(l).strftime('%Y-%m-%dT%H:%M:%SZ'), labels))
else:
labels_iso = [ reformat_date(i[0]) for i in intervals]
pysc = gps.get_spark_context()
from openeogeotrellis.backend import GeoPySparkBackendImplementation
if isinstance(reducer, dict):
datatype = self.get_max_level().layer_metadata.cell_type
reducer = GeoPySparkBackendImplementation.accept_process_graph(reducer, default_input_parameter="data",
default_input_datatype=datatype)
if isinstance(reducer, str):
#deprecated codepath: only single process reduces
pysc = gps.get_spark_context()
mapped_keys = self._apply_to_levels_geotrellis_rdd(
lambda rdd,level: pysc._jvm.org.openeo.geotrellis.OpenEOProcesses().mapInstantToInterval(rdd,intervals_iso,labels_iso))
reducer = self._normalize_temporal_reducer(dimension, reducer)
return mapped_keys.apply_to_levels(lambda rdd: rdd.aggregate_by_cell(reducer))
elif isinstance(reducer, GeotrellisTileProcessGraphVisitor):
def aggregate(rdd,level):
pr = pysc._jvm.org.openeo.geotrellis.OpenEOProcesses()
band_names = []
if self.metadata.has_band_dimension():
band_names = self.metadata.band_names
else:
band_names = ["band_unnamed"]
wrapped = pr.wrapCube(rdd)
wrapped.openEOMetadata().setBandNames(band_names)
return pr.aggregateTemporal(wrapped, intervals_iso, labels_iso, reducer.builder, context if isinstance(context, dict) else {}, reduce)
return self._apply_to_levels_geotrellis_rdd(aggregate)
else:
raise FeatureUnsupportedException("Unsupported type of reducer in aggregate_temporal: " + str(reducer))
@classmethod
def _transform_metadata(cls, layer_or_metadata, cellType = None):
layer = None
if hasattr(layer_or_metadata,'layer_metadata'):
layer=layer_or_metadata
metadata=layer_or_metadata.layer_metadata
else:
metadata=layer_or_metadata
output_metadata_dict = metadata.to_dict()
if cellType != None:
output_metadata_dict['cellType'] = CellType.FLOAT32
metadata= Metadata.from_dict(output_metadata_dict)
if layer is not None:
layer.layer_metadata = metadata
return layer
else:
return metadata
def _aggregate_over_time_numpy(self, reducer: Callable[[Iterable[Tile]], Tile]) -> 'GeopysparkDataCube':
"""
Aggregate over time.
:param reducer: a function that reduces n Tiles to a single Tile
:return:
"""
def aggregate_temporally(layer):
grouped_numpy_rdd = layer.to_spatial_layer().convert_data_type(CellType.FLOAT32).to_numpy_rdd().groupByKey()
composite = grouped_numpy_rdd.mapValues(reducer)
metadata = GeopysparkDataCube._transform_metadata(layer.layer_metadata, cellType=CellType.FLOAT32)
return TiledRasterLayer.from_numpy_rdd(gps.LayerType.SPATIAL, composite, metadata)
return self.apply_to_levels(aggregate_temporally)
@classmethod
def __reproject_polygon(cls, polygon: Union[Polygon, MultiPolygon], srs, dest_srs):
from shapely.ops import transform
from pyproj import Transformer
return transform(Transformer.from_crs(srs, dest_srs, always_xy=True).transform, polygon) # apply projection
@callsite
def merge_cubes(self, other: 'GeopysparkDataCube', overlaps_resolver:str=None):
#we may need to align datacubes automatically?
#other_pyramid_levels = {k: l.tile_to_layout(layout=self.pyramid.levels[k]) for k, l in other.pyramid.levels.items()}
pysc = gps.get_spark_context()
leftBandNames = []
rightBandNames = []
if self.metadata.has_band_dimension():
leftBandNames = self.metadata.band_names
else:
leftBandNames = [ "left_band_unnamed"]
if other.metadata.has_band_dimension():
rightBandNames = other.metadata.band_names
else:
rightBandNames = [ "right_band_unnamed"]
if other.pyramid.levels.keys() != self.pyramid.levels.keys():
raise OpenEOApiException(message="Trying to merge two cubes with different levels, perhaps you had to use 'resample_cube_spatial'? Levels of this cube: " + str(self.pyramid.levels.keys()) +
" are merged with %s" % str(other.pyramid.levels.keys()))
if overlaps_resolver is None:
# TODO: checking for overlap should also consider spatial extent and temporal extent, not only bands #479
intersection = [value for value in leftBandNames if value in rightBandNames]
if len(intersection) > 0:
# Spec: https://github.com/Open-EO/openeo-processes/blob/0dd3ab0d81f67506547136532af39b5c9a16771e/merge_cubes.json#L83-L87
raise OpenEOApiException(
status_code=400,
code="OverlapResolverMissing",
message=f"merge_cubes: Overlapping data cubes, but no overlap resolver has been specified."
+ f" Either set an overlaps_resolver or rename the bands."
+ f" Left names: {leftBandNames}, right names: {rightBandNames}.",
)
# TODO properly combine bbox in metadata?
pr = pysc._jvm.org.openeo.geotrellis.OpenEOProcesses()
if self._is_spatial() and other._is_spatial():
def merge(rdd,other,level):
left = pr.wrapCube(rdd)
left.openEOMetadata().setBandNames(leftBandNames)
right = pr.wrapCube(other.pyramid.levels[level].srdd.rdd())
right.openEOMetadata().setBandNames(rightBandNames)
return pr.mergeSpatialCubes(
left,
right,
overlaps_resolver
)
merged_data = self._apply_to_levels_geotrellis_rdd(
lambda rdd, level:merge(rdd,other,level)
)
elif self._is_spatial():
merged_data = self._apply_to_levels_geotrellis_rdd(
lambda rdd, level:
pr.mergeCubes_SpaceTime_Spatial(
other.pyramid.levels[level].srdd.rdd(),
rdd,
overlaps_resolver,
True # swapOperands
),
target_type=gps.LayerType.SPACETIME
)
elif other._is_spatial():
merged_data = self._apply_to_levels_geotrellis_rdd(
lambda rdd, level:
pr.mergeCubes_SpaceTime_Spatial(
rdd,
other.pyramid.levels[level].srdd.rdd(),
overlaps_resolver,
False # swapOperands
),