-
Notifications
You must be signed in to change notification settings - Fork 6
/
ProcessGraphDeserializer.py
2264 lines (1926 loc) · 101 KB
/
ProcessGraphDeserializer.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
# TODO: rename this module to something in snake case? It doesn't even implement a ProcessGraphDeserializer class.
# pylint: disable=unused-argument
import calendar
import copy
import datetime
import logging
import math
import re
import tempfile
import time
import warnings
from pathlib import Path
from typing import Any, Callable, Dict, Iterable, List, Tuple, Union, Sequence
import geopandas as gpd
import numpy as np
import openeo.udf
import openeo_processes
import pandas as pd
import pyproj
import requests
import shapely.geometry
import shapely.ops
from dateutil.relativedelta import relativedelta
from openeo.capabilities import ComparableVersion
from openeo.internal.process_graph_visitor import ProcessGraphVisitException, ProcessGraphVisitor
from openeo.metadata import CollectionMetadata, MetadataException
from openeo.util import deep_get, load_json, rfc3339, str_truncate
from shapely.geometry import GeometryCollection, MultiPolygon, mapping, shape
from openeo_driver import dry_run
from openeo_driver.backend import (
UserDefinedProcessMetadata,
LoadParameters,
Processing,
OpenEoBackendImplementation,
)
from openeo_driver.datacube import (
DriverDataCube,
DriverVectorCube,
DriverMlModel,
SupportsRunUdf,
)
from openeo_driver.datastructs import SarBackscatterArgs, ResolutionMergeArgs
from openeo_driver.delayed_vector import DelayedVector
from openeo_driver.dry_run import DryRunDataTracer, SourceConstraint, DryRunDataCube
from openeo_driver.errors import (
ProcessParameterRequiredException,
ProcessParameterInvalidException,
FeatureUnsupportedException,
OpenEOApiException,
ProcessGraphInvalidException,
ProcessUnsupportedException,
CollectionNotFoundException,
)
from openeo_driver.processes import ProcessRegistry, ProcessSpec, DEFAULT_NAMESPACE, ProcessArgs
from openeo_driver.save_result import (
JSONResult,
SaveResult,
AggregatePolygonResult,
NullResult,
to_save_result,
AggregatePolygonSpatialResult,
MlModelResult,
)
from openeo_driver.specs import SPECS_ROOT, read_spec
from openeo_driver.util.date_math import month_shift
from openeo_driver.util.geometry import geojson_to_geometry, geojson_to_multipolygon, spatial_extent_union
from openeo_driver.util.utm import auto_utm_epsg_for_geometry
from openeo_driver.utils import EvalEnv, smart_bool
_log = logging.getLogger(__name__)
# Set up process registries (version dependent)
# Process registry based on 1.x version of openeo-processes, to be used with api_version 1.0 an 1.1
process_registry_100 = ProcessRegistry(spec_root=SPECS_ROOT / "openeo-processes/1.x", argument_names=["args", "env"])
# Process registry based on 2.x version of openeo-processes, to be used starting with api_version 1.2
process_registry_2xx = ProcessRegistry(spec_root=SPECS_ROOT / "openeo-processes/2.x", argument_names=["args", "env"])
def _add_standard_processes(process_registry: ProcessRegistry, process_ids: List[str]):
"""
Add standard processes as implemented by the openeo-processes-python project.
"""
def wrap(process: Callable):
"""Adapter to connect the kwargs style of openeo-processes-python with args/EvalEnv"""
def wrapped(args: dict, env: EvalEnv):
return process(**args)
return wrapped
for pid in set(process_ids):
if openeo_processes.has_process(pid):
proc = openeo_processes.get_process(pid)
wrapped = wrap(proc)
spec = process_registry.load_predefined_spec(pid)
process_registry.add_process(name=pid, function=wrapped, spec=spec)
elif pid in _openeo_processes_extra:
proc = _openeo_processes_extra[pid]
wrapped = wrap(proc)
spec = process_registry.load_predefined_spec(pid)
process_registry.add_process(name=pid, function=wrapped, spec=spec)
else:
# TODO: this warning is triggered before logging is set up usually
_log.warning("Adding process {p!r} without implementation".format(p=pid))
process_registry.add_spec_by_name(pid)
_OPENEO_PROCESSES_PYTHON_WHITELIST = [
'array_apply', 'array_contains', 'array_element', 'array_filter', 'array_find', 'array_labels',
'count', 'first', 'last', 'order', 'rearrange', 'sort',
'between', 'eq', 'gt', 'gte', 'is_nan', 'is_nodata', 'is_valid', 'lt', 'lte', 'neq',
'all', 'and', 'any', 'not', 'or', 'xor',
'absolute', 'add', 'clip', 'divide', 'extrema', 'int', 'max', 'mean',
'median', 'min', 'mod', 'multiply', 'power', 'product', 'quantiles', 'sd', 'sgn', 'sqrt',
'subtract', 'sum', 'variance', 'e', 'pi', 'exp', 'ln', 'log',
'ceil', 'floor', 'int', 'round',
'arccos', 'arcosh', 'arcsin', 'arctan', 'arctan2', 'arsinh', 'artanh', 'cos', 'cosh', 'sin', 'sinh', 'tan', 'tanh',
'all', 'any', 'count', 'first', 'last', 'max', 'mean', 'median', 'min', 'product', 'sd', 'sum', 'variance'
]
_openeo_processes_extra = {
"pi": lambda: math.pi,
"e": lambda: math.e,
}
_add_standard_processes(process_registry_100, _OPENEO_PROCESSES_PYTHON_WHITELIST)
_add_standard_processes(process_registry_2xx, _OPENEO_PROCESSES_PYTHON_WHITELIST)
# Type hint alias for a "process function":
# a Python function that implements some openEO process (as used in `apply_process`)
ProcessFunction = Callable[[dict, EvalEnv], Any]
def process(f: ProcessFunction) -> ProcessFunction:
"""
Decorator for registering a process function in the process registries.
To be used as shortcut for all simple cases of
@process_registry_100.add_function
@process_registry_2xx.add_function
def foo(args, env):
...
"""
process_registry_100.add_function(f)
process_registry_2xx.add_function(f)
return f
def simple_function(f: Callable) -> Callable:
"""
Decorator for registering a process function in the process registries.
To be used as shortcut for all simple cases of
@process_registry_100.add_simple_function
@process_registry_2xx.add_simple_function
def foo(args, env):
...
"""
process_registry_100.add_simple_function(f)
process_registry_2xx.add_simple_function(f)
return f
def non_standard_process(spec: ProcessSpec) -> Callable[[ProcessFunction], ProcessFunction]:
"""Decorator for registering non-standard process functions"""
def decorator(f: ProcessFunction) -> ProcessFunction:
process_registry_100.add_function(f=f, spec=spec.to_dict_100())
process_registry_2xx.add_function(f=f, spec=spec.to_dict_100())
return f
return decorator
def custom_process(f: ProcessFunction):
"""Decorator for custom processes (e.g. in custom_processes.py)."""
process_registry_100.add_hidden(f)
process_registry_2xx.add_hidden(f)
return f
def custom_process_from_process_graph(
process_spec: Union[dict, Path],
process_registries: Sequence[ProcessRegistry] = (process_registry_100, process_registry_2xx),
namespace: str = DEFAULT_NAMESPACE,
):
"""
Register a custom process from a process spec containing a "process_graph" definition
:param process_spec: process spec dict or path to a JSON file,
containing keys like "id", "process_graph", "parameter"
:param process_registries: process registries to register to
"""
# TODO: option to hide process graph for (public) listing
if isinstance(process_spec, Path):
process_spec = load_json(process_spec)
process_id = process_spec["id"]
process_function = _process_function_from_process_graph(process_spec)
for process_registry in process_registries:
process_registry.add_function(process_function, name=process_id, spec=process_spec, namespace=namespace)
def _process_function_from_process_graph(process_spec: dict) -> ProcessFunction:
"""
Build a process function (to be used in `apply_process`) from a given process spec with process graph
:param process_spec: process spec dict, containing keys like "id", "process_graph", "parameter"
:return: process function
"""
process_id = process_spec["id"]
process_graph = process_spec["process_graph"]
parameters = process_spec.get("parameters")
def process_function(args: dict, env: EvalEnv):
return _evaluate_process_graph_process(
process_id=process_id, process_graph=process_graph, parameters=parameters,
args=args, env=env
)
return process_function
def _register_fallback_implementations_by_process_graph(process_registry: ProcessRegistry):
"""
Register process functions for (yet undefined) processes that have
a process graph based fallback implementation in their spec
"""
for name in process_registry.list_predefined_specs():
spec = process_registry.load_predefined_spec(name)
if "process_graph" in spec and not process_registry.contains(name):
_log.info(f"Registering fallback implementation of {name!r} by process graph ({process_registry})")
custom_process_from_process_graph(process_spec=spec, process_registries=[process_registry])
# Some (env) string constants to simplify code navigation
ENV_SOURCE_CONSTRAINTS = "source_constraints"
ENV_DRY_RUN_TRACER = "dry_run_tracer"
ENV_SAVE_RESULT= "save_result"
class SimpleProcessing(Processing):
"""
Simple graph processing: just implement basic math/logic operators
(based on openeo-processes-python implementation)
"""
# For lazy loading of (global) process registry
_registry_cache = {}
def get_process_registry(self, api_version: Union[str, ComparableVersion]) -> ProcessRegistry:
# Lazy load registry.
api_version = ComparableVersion(api_version)
if api_version.at_least("1.2.0"):
spec = "openeo-processes/2.x"
elif api_version.at_least("1.0.0"):
spec = "openeo-processes/1.x"
else:
raise OpenEOApiException(message=f"No process support for openEO version {api_version}")
if spec not in self._registry_cache:
registry = ProcessRegistry(spec_root=SPECS_ROOT / spec, argument_names=["args", "env"])
_add_standard_processes(registry, _OPENEO_PROCESSES_PYTHON_WHITELIST)
self._registry_cache[spec] = registry
return self._registry_cache[spec]
def get_basic_env(self, api_version=None) -> EvalEnv:
return EvalEnv(
{
"backend_implementation": OpenEoBackendImplementation(processing=self),
"version": api_version or "1.0.0", # TODO: get better default api version from somewhere?
"node_caching": False,
}
)
def evaluate(self, process_graph: dict, env: EvalEnv = None):
return evaluate(process_graph=process_graph, env=env or self.get_basic_env(), do_dry_run=False)
class ConcreteProcessing(Processing):
"""
Concrete process graph processing: (most) processes have concrete Python implementation
(manipulating `DriverDataCube` instances)
"""
def get_process_registry(self, api_version: Union[str, ComparableVersion]) -> ProcessRegistry:
if ComparableVersion(api_version).at_least("1.2.0"):
return process_registry_2xx
elif ComparableVersion(api_version).at_least("1.0.0"):
return process_registry_100
else:
raise OpenEOApiException(message=f"No process support for openEO version {api_version}")
def evaluate(self, process_graph: dict, env: EvalEnv = None):
return evaluate(process_graph=process_graph, env=env)
def validate(self, process_graph: dict, env: EvalEnv = None) -> List[dict]:
dry_run_tracer = DryRunDataTracer()
env = env.push({ENV_DRY_RUN_TRACER: dry_run_tracer})
try:
top_level_node = ProcessGraphVisitor.dereference_from_node_arguments(process_graph)
result_node = process_graph[top_level_node]
except ProcessGraphVisitException as e:
return [{"code": "ProcessGraphInvalid", "message": str(e)}]
try:
result = convert_node(result_node, env=env)
except OpenEOApiException as e:
return [{"code": e.code, "message": str(e)}]
except Exception as e:
return [{"code": "Internal", "message": str(e)}]
errors = []
# TODO: check other resources for errors, warnings?
source_constraints = dry_run_tracer.get_source_constraints()
errors.extend(self.extra_validation(
process_graph=process_graph,
env=env,
result=result,
source_constraints=source_constraints
))
return errors
def extra_validation(
self, process_graph: dict, env: EvalEnv, result, source_constraints: List[SourceConstraint]
) -> Iterable[dict]:
"""
Extra process graph validation
:return: List (or generator) of validation error dicts (having at least a "code" and "message" field)
"""
return []
def evaluate(
process_graph: dict,
env: EvalEnv,
do_dry_run: Union[bool, DryRunDataTracer] = True
) -> Union[DriverDataCube, Any]:
"""
Converts the json representation of a (part of a) process graph into the corresponding Python data cube.
Warning: this function could manipulate the given process graph dict in-place (see `convert_node`).
"""
if "version" not in env:
_log.warning("No version in `evaluate()` env. Blindly assuming 1.0.0.")
env = env.push({"version": "1.0.0"})
top_level_node = ProcessGraphVisitor.dereference_from_node_arguments(process_graph)
result_node = process_graph[top_level_node]
if ENV_SAVE_RESULT not in env:
env = env.push({ENV_SAVE_RESULT: []})
if do_dry_run:
dry_run_tracer = do_dry_run if isinstance(do_dry_run, DryRunDataTracer) else DryRunDataTracer()
_log.info("Doing dry run")
convert_node(result_node, env=env.push({
ENV_DRY_RUN_TRACER: dry_run_tracer,
ENV_SAVE_RESULT: [], # otherwise dry run and real run append to the same mutable result list
"node_caching": False
}))
# TODO: work with a dedicated DryRunEvalEnv?
source_constraints = dry_run_tracer.get_source_constraints()
_log.info("Dry run extracted these source constraints: {s}".format(s=source_constraints))
env = env.push({ENV_SOURCE_CONSTRAINTS: source_constraints})
result = convert_node(result_node, env=env)
if len(env[ENV_SAVE_RESULT]) > 0:
if len(env[ENV_SAVE_RESULT]) == 1:
return env[ENV_SAVE_RESULT][0]
else:
# unpack to remain consistent with previous behaviour of returning results
return env[ENV_SAVE_RESULT]
else:
return result
def convert_node(processGraph: Union[dict, list], env: EvalEnv = None):
"""
Warning: this function could manipulate the given process graph dict in-place,
e.g. by adding a "result_cache" key (see lower).
"""
if isinstance(processGraph, dict):
if 'process_id' in processGraph:
process_id = processGraph['process_id']
caching_flag = smart_bool(env.get("node_caching", True)) and process_id != "load_collection"
cached = None
if caching_flag and "result_cache" in processGraph:
cached = processGraph["result_cache"]
process_result = apply_process(process_id=process_id, args=processGraph.get('arguments', {}),
namespace=processGraph.get("namespace", None), env=env)
if caching_flag:
if cached is not None:
comparison = cached == process_result
#numpy arrays have a custom eq that requires this weird check
if isinstance(comparison,bool) and comparison:
_log.info(f"Reusing an already evaluated subgraph for process {process_id}")
return cached
# TODO: this manipulates the process graph, while we often assume it's immutable.
# Adding complex data structures could also interfere with attempts to (re)encode the process graph as JSON again.
processGraph["result_cache"] = process_result
return process_result
elif 'node' in processGraph:
return convert_node(processGraph['node'], env=env)
elif 'callback' in processGraph or 'process_graph' in processGraph:
# a "process_graph" object is a new process graph, don't evaluate it in the parent graph
return processGraph
elif 'from_parameter' in processGraph:
try:
parameters = env.collect_parameters()
return parameters[processGraph['from_parameter']]
except KeyError:
raise ProcessParameterRequiredException(process="n/a", parameter=processGraph['from_parameter'])
else:
# TODO: Don't apply `convert_node` for some special cases (e.g. geojson objects)?
return {k:convert_node(v, env=env) for k,v in processGraph.items()}
elif isinstance(processGraph, list):
return [convert_node(x, env=env) for x in processGraph]
return processGraph
def _as_process_args(args: Union[dict, ProcessArgs], process_id: str = "n/a") -> ProcessArgs:
"""Adapter for legacy style args"""
if not isinstance(args, ProcessArgs):
args = ProcessArgs(args, process_id=process_id)
elif process_id not in {args.process_id, "n/a"}:
_log.warning(f"Inconsistent {process_id=} in extract_arg(): expected {args.process_id=}")
return args
def extract_arg(args: ProcessArgs, name: str, process_id="n/a"):
# TODO: eliminate this function, use `ProcessArgs.get_required()` directly
return _as_process_args(args, process_id=process_id).get_required(name=name)
def _align_extent(extent,collection_id,env):
metadata = None
try:
metadata = env.backend_implementation.catalog.get_collection_metadata(collection_id)
except CollectionNotFoundException:
pass
# TODO #275 eliminate this VITO specific handling?
if metadata is None or metadata.get("_vito") is None or not metadata.get("_vito").get("data_source", {}).get("realign", False):
return extent
x = metadata.get('cube:dimensions', {}).get('x', {})
y = metadata.get('cube:dimensions', {}).get('y', {})
if ("step" in x
and "step" in y
and x.get('reference_system', '') == 4326
and extent.get('crs','') == "EPSG:4326"
and "extent" in x and "extent" in y
):
def align(v, dimension, rounding):
range = dimension.get('extent', [])
if v < range[0]:
v = range[0]
elif v > range[1]:
v = range[1]
else:
index = rounding((v - range[0]) / dimension['step'])
v = range[0] + index * dimension['step']
return v
new_extent = {
'west': align(extent['west'], x, math.floor),
'east': align(extent['east'], x, math.ceil),
'south': align(extent['south'], y, math.floor),
'north': align(extent['north'], y, math.ceil),
'crs': extent['crs']
}
_log.info(f"Realigned input extent {extent} into {new_extent}")
return new_extent
else:
return extent
def _extract_load_parameters(env: EvalEnv, source_id: tuple) -> LoadParameters:
"""
This is a side effect method that also removes source constraints from the list, which needs to happen in the right order!!
Args:
env:
source_id:
Returns:
"""
source_constraints: List[SourceConstraint] = env[ENV_SOURCE_CONSTRAINTS]
global_extent = None
process_types = set()
filtered_constraints = [c for c in source_constraints if c[0] == source_id]
for collection_id, constraint in source_constraints:
extent = None
if "spatial_extent" in constraint:
extent = constraint["spatial_extent"]
if "weak_spatial_extent" in constraint:
extent = constraint["weak_spatial_extent"]
if extent is not None:
if "resample" not in constraint:
# Ensure that the extent that the user provided is aligned with the collection's native grid.
extent = _align_extent(extent, collection_id[1][0], env)
global_extent = spatial_extent_union(global_extent, extent) if global_extent else extent
for _, constraint in filtered_constraints:
if "process_type" in constraint:
process_types |= set(constraint["process_type"])
_, constraints = filtered_constraints.pop(0)
source_constraints.remove((source_id,constraints))
params = LoadParameters()
params.temporal_extent = constraints.get("temporal_extent", ["1970-01-01", "2070-01-01"])
labels_args = constraints.get("filter_labels", {})
if("dimension" in labels_args and labels_args["dimension"] == "t"):
params.filter_temporal_labels = labels_args.get("condition")
params.spatial_extent = constraints.get("spatial_extent", {})
params.global_extent = global_extent
params.bands = constraints.get("bands", None)
params.properties = constraints.get("properties", {})
params.aggregate_spatial_geometries = constraints.get("aggregate_spatial", {}).get("geometries")
if params.aggregate_spatial_geometries is None:
params.aggregate_spatial_geometries = constraints.get("filter_spatial", {}).get("geometries")
params.sar_backscatter = constraints.get("sar_backscatter", None)
params.process_types = process_types
params.custom_mask = constraints.get("custom_cloud_mask", {})
params.data_mask = env.get("data_mask", None)
if params.data_mask:
_log.debug(f"extracted data_mask {params.data_mask}")
params.target_crs = constraints.get("resample", {}).get("target_crs",None)
params.target_resolution = constraints.get("resample", {}).get("resolution", None)
params.resample_method = constraints.get("resample", {}).get("method", "near")
params.pixel_buffer = constraints.get("pixel_buffer", {}).get("buffer_size", None)
return params
@process
def load_collection(args: dict, env: EvalEnv) -> DriverDataCube:
collection_id = extract_arg(args, 'id')
# Sanitized arguments
arguments = {}
if args.get("temporal_extent"):
arguments["temporal_extent"] = _extract_temporal_extent(
args, field="temporal_extent", process_id="load_collection"
)
if args.get("spatial_extent"):
arguments["spatial_extent"] = _extract_bbox_extent(
args, field="spatial_extent", process_id="load_collection", handle_geojson=True
)
# TODO when spatial_extent is geojson: additional mask_polygon operation? https://github.com/Open-EO/openeo-python-driver/issues/49
if args.get("bands"):
arguments["bands"] = extract_arg(args, "bands", process_id="load_collection")
if args.get("properties"):
arguments["properties"] = extract_arg(args, 'properties', process_id="load_collection")
if args.get("featureflags"):
arguments["featureflags"] = extract_arg(args, 'featureflags', process_id="load_collection")
metadata = env.backend_implementation.catalog.get_collection_metadata(collection_id)
dry_run_tracer: DryRunDataTracer = env.get(ENV_DRY_RUN_TRACER)
if dry_run_tracer:
return dry_run_tracer.load_collection(collection_id=collection_id, arguments=arguments, metadata=metadata)
else:
# Extract basic source constraints.
# TODO #275: eliminate this VITO specific handling?
properties = {**CollectionMetadata(metadata).get("_vito", "properties", default={}),
**arguments.get("properties", {})}
source_id = dry_run.DataSource.load_collection(collection_id=collection_id,
properties=properties).get_source_id()
load_params = _extract_load_parameters(env, source_id=source_id)
# Override with explicit arguments
load_params.update(arguments)
return env.backend_implementation.catalog.load_collection(collection_id, load_params=load_params, env=env)
@non_standard_process(
ProcessSpec(id='load_disk_data', description="Loads arbitrary from disk. This process is deprecated, considering using load_uploaded_files or load_stac.")
.param(name='format', description="the file format, e.g. 'GTiff'", schema={"type": "string"}, required=True)
.param(name='glob_pattern', description="a glob pattern that matches the files to load from disk",
schema={"type": "string"}, required=True)
.param(name='options', description="options specific to the file format", schema={"type": "object"})
.returns(description="the data as a data cube", schema={})
)
def load_disk_data(args: Dict, env: EvalEnv) -> DriverDataCube:
"""
Deprecated, use load_uploaded_files or load_stac
"""
kwargs = dict(
glob_pattern=extract_arg(args, 'glob_pattern'),
format=extract_arg(args, 'format'),
options=args.get('options', {}),
)
dry_run_tracer: DryRunDataTracer = env.get(ENV_DRY_RUN_TRACER)
if dry_run_tracer:
return dry_run_tracer.load_disk_data(**kwargs)
else:
source_id = dry_run.DataSource.load_disk_data(**kwargs).get_source_id()
load_params = _extract_load_parameters(env, source_id=source_id)
return env.backend_implementation.load_disk_data(**kwargs, load_params=load_params, env=env)
def _check_geometry_path_assumption(path: str, process: str, parameter: str):
if isinstance(path, str) and path.lstrip().startswith("{"):
raise ProcessParameterInvalidException(
parameter=parameter,
process=process,
reason=f"provided a string (to be handled as path/URL), but it looks like (Geo)JSON encoded data: {str_truncate(path, width=32)!r}.",
)
@non_standard_process(
ProcessSpec(id='vector_buffer', description="Add a buffer around a geometry.")
.param(name='geometries', description="Input geometry (GeoJSON object) to add buffer to.",
schema={"type": "object", "subtype": "geojson"})
.param(name='distance', description="The size of the buffer. Can be negative to subtract the buffer",
schema={"type": "number"}, required=True)
.returns(description="Output geometry (GeoJSON object) with the added or subtracted buffer",
schema={"type": "object", "subtype": "geojson"})
)
def vector_buffer(args: Dict, env: EvalEnv) -> dict:
if("geometry" in args):
#old style, not official
geometry = extract_arg(args, 'geometry')
else:
geometry = extract_arg(args, 'geometries')
distance = extract_arg(args, 'distance')
#unit argument is not official spec
unit = args.get("unit","meter")
input_crs = output_crs = 'epsg:4326'
buffer_resolution = 3
# TODO #114 EP-3981 convert `geometry` to vector cube and move buffer logic to there
if isinstance(geometry,DriverVectorCube):
geoms = geometry.get_geometries()
input_crs = geometry.get_crs()
elif isinstance(geometry, str):
_check_geometry_path_assumption(
path=geometry, process="vector_buffer", parameter="geometry"
)
# TODO: assumption here that `geometry` is a path/url
geoms = list(DelayedVector(geometry).geometries)
elif isinstance(geometry, dict) and "type" in geometry:
geometry_type = geometry["type"]
if geometry_type == "FeatureCollection":
geoms = [shape(feat["geometry"]) for feat in geometry["features"]]
elif geometry_type == "GeometryCollection":
geoms = [shape(geom) for geom in geometry["geometries"]]
elif geometry_type in {"Polygon", "MultiPolygon", "Point", "MultiPoint", "LineString"}:
geoms = [shape(geometry)]
elif geometry_type == "Feature":
geoms = [shape(geometry["geometry"])]
else:
raise ProcessParameterInvalidException(
parameter="geometry", process="vector_buffer", reason=f"Invalid geometry type {geometry_type}."
)
if "crs" in geometry:
_log.warning("Handling GeoJSON dict with (non-standard) crs field")
try:
crs_name = geometry["crs"]["properties"]["name"]
input_crs = pyproj.crs.CRS.from_string(crs_name)
except Exception:
_log.error(f"Failed to parse input geometry CRS {crs_name!r}", exc_info=True)
raise ProcessParameterInvalidException(
parameter="geometry", process="vector_buffer", reason=f"Failed to parse input geometry CRS."
)
else:
raise ProcessParameterInvalidException(
parameter="geometry", process="vector_buffer", reason="The input geometry cannot be parsed"
)
geoms = gpd.GeoSeries(geoms, crs=input_crs)
unit_scaling = {"meter": 1, "kilometer": 1000}
if unit not in unit_scaling:
raise ProcessParameterInvalidException(
parameter="unit", process="vector_buffer",
reason=f"Invalid unit {unit!r}. Should be one of {list(unit_scaling.keys())}."
)
distance = distance * unit_scaling[unit]
epsg_utmzone = auto_utm_epsg_for_geometry(geoms.geometry[0])
#TODO in the official spec, we have to throw an exception rather than reproject implicitly
poly_buff_latlon = geoms.to_crs(epsg_utmzone).buffer(distance, resolution=buffer_resolution).to_crs(output_crs)
empty_result_indices = np.where(poly_buff_latlon.is_empty)[0]
if empty_result_indices.size > 0:
raise ProcessParameterInvalidException(
parameter="geometry", process="vector_buffer",
reason=f"Buffering with distance {distance} {unit} resulted in empty geometries "
f"at position(s) {empty_result_indices}"
)
return mapping(poly_buff_latlon[0]) if len(poly_buff_latlon) == 1 else mapping(poly_buff_latlon)
@process
def apply_neighborhood(args: ProcessArgs, env: EvalEnv) -> DriverDataCube:
data_cube = args.get_required("data", expected_type=DriverDataCube)
process = args.get_deep("process", "process_graph", expected_type=dict)
size = args.get_required("size")
overlap = args.get_optional("overlap")
context = args.get_optional("context", default=None)
return data_cube.apply_neighborhood(process=process, size=size, overlap=overlap, env=env, context=context)
@process
def apply_dimension(args: ProcessArgs, env: EvalEnv) -> DriverDataCube:
data_cube = args.get_required("data", expected_type=(DriverDataCube, DriverVectorCube))
process = args.get_deep("process", "process_graph", expected_type=dict)
dimension = args.get_required(
"dimension", expected_type=str, validator=ProcessArgs.validator_one_of(data_cube.get_dimension_names())
)
target_dimension = args.get_optional("target_dimension", default=None, expected_type=str)
context = args.get_optional("context", default=None)
cube = data_cube.apply_dimension(
process=process, dimension=dimension, target_dimension=target_dimension, context=context, env=env
)
if target_dimension is not None and target_dimension not in cube.metadata.dimension_names():
cube = cube.rename_dimension(dimension, target_dimension)
return cube
@process
def save_result(args: Dict, env: EvalEnv) -> SaveResult: # TODO: return type no longer holds
data = extract_arg(args, 'data')
format = extract_arg(args, 'format')
options = args.get('options', {})
if isinstance(data, SaveResult):
# TODO: Is this an expected code path? `save_result` should be terminal node in a graph
# so chaining `save_result` calls should not be valid
# https://github.com/Open-EO/openeo-geopyspark-driver/issues/295
data = data.with_format(format, options)
if ENV_SAVE_RESULT in env:
env[ENV_SAVE_RESULT].append(data)
return data
else:
result = to_save_result(data, format=format, options=options)
if ENV_SAVE_RESULT in env:
env[ENV_SAVE_RESULT].append(result)
return data
else:
return result
@process_registry_100.add_function(spec=read_spec("openeo-processes/experimental/save_ml_model.json"))
@process_registry_2xx.add_function(spec=read_spec("openeo-processes/experimental/save_ml_model.json"))
def save_ml_model(args: dict, env: EvalEnv) -> MlModelResult:
data: DriverMlModel = extract_arg(args, "data", process_id="save_ml_model")
if not isinstance(data, DriverMlModel):
raise ProcessParameterInvalidException(
parameter="data", process="save_ml_model", reason=f"Invalid data type {type(data)!r} expected raster-cube."
)
options = args.get("options", {})
return MlModelResult(ml_model=data, options=options)
@process_registry_100.add_function(spec=read_spec("openeo-processes/experimental/load_ml_model.json"))
@process_registry_2xx.add_function(spec=read_spec("openeo-processes/experimental/load_ml_model.json"))
def load_ml_model(args: dict, env: EvalEnv) -> DriverMlModel:
if env.get(ENV_DRY_RUN_TRACER):
return DriverMlModel()
job_id = extract_arg(args, "id")
return env.backend_implementation.load_ml_model(job_id)
@process
def apply(args: ProcessArgs, env: EvalEnv) -> DriverDataCube:
"""
Applies a unary process (a local operation) to each value of the specified or all dimensions in the data cube.
"""
data_cube = args.get_required("data", expected_type=DriverDataCube)
apply_pg = args.get_deep("process", "process_graph", expected_type=dict)
context = args.get_optional("context", default=None)
return data_cube.apply(process=apply_pg, context=context, env=env)
@process
def reduce_dimension(args: ProcessArgs, env: EvalEnv) -> DriverDataCube:
data_cube: DriverDataCube = args.get_required("data", expected_type=DriverDataCube)
reduce_pg = args.get_deep("reducer", "process_graph", expected_type=dict)
dimension = args.get_required(
"dimension", expected_type=str, validator=ProcessArgs.validator_one_of(data_cube.get_dimension_names())
)
context = args.get_optional("context", default=None)
return data_cube.reduce_dimension(reducer=reduce_pg, dimension=dimension, context=context, env=env)
@process_registry_100.add_function(
spec=read_spec("openeo-processes/experimental/chunk_polygon.json"), name="chunk_polygon"
)
def chunk_polygon(args: ProcessArgs, env: EvalEnv) -> DriverDataCube:
# TODO #229 deprecate this process and promote the "apply_polygon" name.
# See https://github.com/Open-EO/openeo-processes/issues/287, https://github.com/Open-EO/openeo-processes/pull/298
data_cube = args.get_required("data", expected_type=DriverDataCube)
reduce_pg = args.get_deep("process", "process_graph", expected_type=dict)
chunks = args.get_required("chunks")
mask_value = args.get_optional("mask_value", expected_type=(int, float), default=None)
context = args.get_optional("context", default=None)
# Chunks parameter check.
# TODO #114 EP-3981 normalize first to vector cube and simplify logic
if isinstance(chunks, DelayedVector):
polygons = list(chunks.geometries)
for p in polygons:
if not isinstance(p, shapely.geometry.Polygon):
reason = "{m!s} is not a polygon.".format(m=p)
raise ProcessParameterInvalidException(parameter='chunks', process='chunk_polygon', reason=reason)
polygon = MultiPolygon(polygons)
elif isinstance(chunks, shapely.geometry.base.BaseGeometry):
polygon = MultiPolygon(chunks)
elif isinstance(chunks, dict):
polygon = geojson_to_multipolygon(chunks)
if isinstance(polygon, shapely.geometry.Polygon):
polygon = MultiPolygon([polygon])
elif isinstance(chunks, str):
# Delayed vector is not supported yet.
reason = "Polygon of type string is not yet supported."
raise ProcessParameterInvalidException(parameter='chunks', process='chunk_polygon', reason=reason)
else:
reason = "Polygon type is not supported."
raise ProcessParameterInvalidException(parameter='chunks', process='chunk_polygon', reason=reason)
if polygon.area == 0:
reason = "Polygon {m!s} has an area of {a!r}".format(m=polygon, a=polygon.area)
raise ProcessParameterInvalidException(parameter='chunks', process='chunk_polygon', reason=reason)
return data_cube.chunk_polygon(reducer=reduce_pg, chunks=polygon, mask_value=mask_value, context=context, env=env)
@process_registry_100.add_function(spec=read_spec("openeo-processes/2.x/proposals/apply_polygon.json"))
@process_registry_2xx.add_function(spec=read_spec("openeo-processes/2.x/proposals/apply_polygon.json"))
def apply_polygon(args: ProcessArgs, env: EvalEnv) -> DriverDataCube:
data_cube = args.get_required("data", expected_type=DriverDataCube)
process = args.get_deep("process", "process_graph", expected_type=dict)
polygons = args.get_required("polygons")
mask_value = args.get_optional("mask_value", expected_type=(int, float), default=None)
context = args.get_optional("context", default=None)
# TODO #114 EP-3981 normalize first to vector cube and simplify logic
# TODO: this logic (copied from original chunk_polygon implementation) coerces the input polygons
# to a single MultiPolygon of pure (non-multi) polygons, which is conceptually wrong.
# Instead it should normalize to a feature collection or vector cube.
if isinstance(polygons, DelayedVector):
polygons = list(polygons.geometries)
for p in polygons:
if not isinstance(p, shapely.geometry.Polygon):
reason = "{m!s} is not a polygon.".format(m=p)
raise ProcessParameterInvalidException(parameter="polygons", process="apply_polygon", reason=reason)
polygon = MultiPolygon(polygons)
elif isinstance(polygons, shapely.geometry.base.BaseGeometry):
polygon = MultiPolygon(polygons)
elif isinstance(polygons, dict):
polygon = geojson_to_multipolygon(polygons)
if isinstance(polygon, shapely.geometry.Polygon):
polygon = MultiPolygon([polygon])
elif isinstance(polygons, str):
# Delayed vector is not supported yet.
reason = "Polygon of type string is not yet supported."
raise ProcessParameterInvalidException(parameter="polygons", process="apply_polygon", reason=reason)
else:
reason = "Polygon type is not supported."
raise ProcessParameterInvalidException(parameter="polygons", process="apply_polygon", reason=reason)
if polygon.area == 0:
reason = "Polygon {m!s} has an area of {a!r}".format(m=polygon, a=polygon.area)
raise ProcessParameterInvalidException(parameter="polygons", process="apply_polygon", reason=reason)
return data_cube.apply_polygon(polygons=polygon, process=process, mask_value=mask_value, context=context, env=env)
@process_registry_100.add_function(spec=read_spec("openeo-processes/experimental/fit_class_random_forest.json"))
@process_registry_2xx.add_function(spec=read_spec("openeo-processes/experimental/fit_class_random_forest.json"))
def fit_class_random_forest(args: dict, env: EvalEnv) -> DriverMlModel:
# Keep it simple for dry run
if env.get(ENV_DRY_RUN_TRACER):
return DriverMlModel()
predictors = extract_arg(args, 'predictors')
if not isinstance(predictors, (AggregatePolygonSpatialResult, DriverVectorCube)):
# TODO #114 EP-3981 drop AggregatePolygonSpatialResult support.
raise ProcessParameterInvalidException(
parameter="predictors",
process="fit_class_random_forest",
reason=f"should be non-temporal vector-cube, but got {type(predictors)}.",
)
target = extract_arg(args, "target")
if isinstance(target, DriverVectorCube):
pass
elif isinstance(target, dict) and target.get("type") == "FeatureCollection":
# TODO: convert to vector cube, e.g.:
# target = env.backend_implementation.vector_cube_cls.from_geojson(target)
pass
else:
raise ProcessParameterInvalidException(
parameter="target",
process="fit_class_random_forest",
reason=f"expected feature collection or vector-cube value, but got {type(target)}.",
)
# TODO: get defaults from process spec?
# TODO: do parameter checks automatically based on process spec?
num_trees = args.get("num_trees", 100)
if not isinstance(num_trees, int) or num_trees < 0:
raise ProcessParameterInvalidException(
parameter="num_trees", process="fit_class_random_forest",
reason="should be an integer larger than 0."
)
max_variables = args.get("max_variables") or args.get('mtry')
seed = args.get("seed")
if not (seed is None or isinstance(seed, int)):
raise ProcessParameterInvalidException(
parameter="seed", process="fit_class_random_forest", reason="should be an integer"
)
return predictors.fit_class_random_forest(
target=target, num_trees=num_trees, max_variables=max_variables, seed=seed,
)
@process_registry_100.add_function(spec=read_spec("openeo-processes/experimental/predict_random_forest.json"))
@process_registry_2xx.add_function(spec=read_spec("openeo-processes/experimental/predict_random_forest.json"))
def predict_random_forest(args: dict, env: EvalEnv):
raise NotImplementedError
@process_registry_100.add_function(spec=read_spec("openeo-processes/experimental/predict_catboost.json"))
@process_registry_2xx.add_function(spec=read_spec("openeo-processes/experimental/predict_catboost.json"))
def predict_catboost(args: dict, env: EvalEnv):
raise NotImplementedError
@process_registry_100.add_function(spec=read_spec("openeo-processes/experimental/predict_probabilities.json"))
@process_registry_2xx.add_function(spec=read_spec("openeo-processes/experimental/predict_probabilities.json"))
def predict_probabilities(args: dict, env: EvalEnv):
raise NotImplementedError
@process
def add_dimension(args: ProcessArgs, env: EvalEnv) -> DriverDataCube:
data_cube = args.get_required("data", expected_type=DriverDataCube)
return data_cube.add_dimension(
name=args.get_required("name", expected_type=str),
label=args.get_required("label", expected_type=str),
type=args.get_optional("type", default="other", expected_type=str),
)
@process
def drop_dimension(args: dict, env: EvalEnv) -> DriverDataCube:
data_cube = extract_arg(args, 'data')
if not isinstance(data_cube, DriverDataCube):
raise ProcessParameterInvalidException(
parameter="data", process="drop_dimension",
reason=f"Invalid data type {type(data_cube)!r} expected raster-cube."
)
return data_cube.drop_dimension(name=extract_arg(args, 'name'))
@process
def dimension_labels(args: dict, env: EvalEnv) -> DriverDataCube:
data_cube = extract_arg(args, 'data')
if not isinstance(data_cube, DriverDataCube):
raise ProcessParameterInvalidException(
parameter="data", process="dimension_labels",
reason=f"Invalid data type {type(data_cube)!r} expected raster-cube."
)
return data_cube.dimension_labels(dimension=extract_arg(args, 'dimension'))
@process
def rename_dimension(args: dict, env: EvalEnv) -> DriverDataCube:
data_cube = extract_arg(args, 'data')
if not isinstance(data_cube, DriverDataCube):
raise ProcessParameterInvalidException(
parameter="data", process="rename_dimension",
reason=f"Invalid data type {type(data_cube)!r} expected raster-cube."
)
return data_cube.rename_dimension(source=extract_arg(args, 'source'),target=extract_arg(args, 'target'))
@process