forked from Open-EO/openeo_odc_driver
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathopeneo_odc_driver.py
2004 lines (1867 loc) · 120 KB
/
openeo_odc_driver.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
# coding=utf-8
# Author: Claus Michele - Eurac Research - michele (dot) claus (at) eurac (dot) edu
# Date: 21/10/2022
def warn(*args, **kwargs):
pass
import warnings
warnings.warn = warn
# Import necessary libraries
# System
import os
from os.path import exists
import sys
from time import time
from datetime import datetime
import json
import uuid
import pickle
import logging
import traceback
from glob import glob
# Math & Science
import math
import numpy as np
import scipy
from scipy.interpolate import griddata
from scipy.spatial import Delaunay
from scipy.interpolate import LinearNDInterpolator, NearestNDInterpolator
from scipy.optimize import curve_fit
import random
# Image processing
import cv2
# Geography
from pyproj import Proj, transform, Transformer, CRS
import geopandas as gpd
from shapely.geometry import Point
from shapely.geometry.polygon import Polygon
from shapely.geometry.multipolygon import MultiPolygon
from shapely.geometry.multipoint import MultiPoint
from osgeo import gdal
# Machine Learning
from sklearn import tree, model_selection
from sklearn.metrics import accuracy_score
from sklearn import metrics
from sklearn.ensemble import RandomForestClassifier, RandomForestRegressor
# Datacubes and databases
import datacube
import xarray as xr
import rioxarray
import pandas as pd
# Parallel Computing
import dask
from dask.distributed import Scheduler, Worker, Client, LocalCluster
from dask import delayed
from joblib import Parallel
from joblib import delayed as joblibDelayed
# openEO
from openeo_pg_parser.translate import translate_process_graph
# openeo_odc_driver
from openEO_error_messages import *
from odc_wrapper import Odc
from config import *
# SAR2Cube
try:
from sar2cube_utils import *
except:
pass
def init_logging():
logging.basicConfig(
level=logging.INFO,
format="%(asctime)s [%(levelname)s] %(message)s",
handlers=[
logging.FileHandler("odc_openeo_engine.log"),
logging.StreamHandler(sys.stdout)
]
)
init_logging()
logger = logging.getLogger("odc_openeo_engine_logger")
logging.getLogger('rasterio').setLevel(logging.INFO)
logging.getLogger('datacube').setLevel(logging.INFO)
logging.getLogger('dask.distributed').setLevel(logging.INFO)
class OpenEO():
def __init__(self,jsonProcessGraph):
self.jsonProcessGraph = jsonProcessGraph
try:
self.jobId = jsonProcessGraph['id']
except:
self.jobId = "None"
self.data = None
self.listExecutedIds = []
self.partialResults = {}
self.crs = None
self.bands = None
self.graph = translate_process_graph(jsonProcessGraph,process_defs=OPENEO_PROCESSES).sort(by='result')
self.outFormat = None
self.returnFile = True
self.mimeType = None
self.run_udf_number = 0
self.i = 0
if self.jobId == "None":
self.tmpFolderPath = TMP_FOLDER_PATH + str(uuid.uuid4())
else:
self.tmpFolderPath = TMP_FOLDER_PATH + self.jobId # If it is a batch job, there will be a field with it's id
self.sar2cubeCollection = False
self.fitCurveFunctionString = ""
try:
os.mkdir(self.tmpFolderPath)
except:
pass
self.start = time()
logger.info("[*] Init of dask cluster")
try:
with LocalCluster(n_workers=32, threads_per_worker=1, processes=True,memory_limit='30GB') as cluster:
with Client(cluster) as client:
client.run(init_logging)
dask.config.set({"distributed.comm.timeouts.tcp": "50s"})
for i in range(0,len(self.graph)+1):
if not self.process_node(i):
logger.info('[*] Processing finished!')
logger.info('[*] Total elapsed time: {}'.format(time() - self.start))
break
except Exception as e:
raise e
def process_node(self,i):
node = self.graph[i]
processName = node.process_id
logger.info("Process id: {} Process name: {}".format(node.id,processName))
try:
start_time_proc = time()
if processName == 'load_collection':
defaultTimeStart = '1970-01-01'
defaultTimeEnd = str(datetime.now()).split(' ')[0] # Today is the default date for timeEnd, to include all the dates if not specified
timeStart = defaultTimeStart
timeEnd = defaultTimeEnd
collection = None
south = None
north = None
east = None
west = None
bands = None # List of bands
resolutions = None # Tuple
outputCrs = None
crs = None
resamplingMethod = None
polygon = None
if 'bands' in node.arguments:
bands = node.arguments['bands']
if bands == []: bands = None
collection = node.arguments['id'] # The datacube we have to load
if collection is None:
raise Exception('[!] You must provide a collection name!')
self.sar2cubeCollection = ('SAR2Cube' in collection) # Return True if it's a SAR2Cube collection
if node.arguments['temporal_extent'] is not None:
timeStart = node.arguments['temporal_extent'][0]
timeEnd = node.arguments['temporal_extent'][1]
# If there is a bounding-box or a polygon we set the variables, otherwise we pass the defaults
if 'spatial_extent' in node.arguments and node.arguments['spatial_extent'] is not None:
if 'south' in node.arguments['spatial_extent'] and \
'north' in node.arguments['spatial_extent'] and \
'east' in node.arguments['spatial_extent'] and \
'west' in node.arguments['spatial_extent']:
south = node.arguments['spatial_extent']['south'] #lowLat
north = node.arguments['spatial_extent']['north'] #highLat
east = node.arguments['spatial_extent']['east'] #lowLon
west = node.arguments['spatial_extent']['west'] #highLon
elif 'coordinates' in node.arguments['spatial_extent']:
# Pass coordinates to odc and process them there
polygon = node.arguments['spatial_extent']['coordinates']
if 'crs' in node.arguments['spatial_extent'] and node.arguments['spatial_extent']['crs'] is not None:
crs = node.arguments['spatial_extent']['crs']
for n in self.graph: # Let's look for resample_spatial nodes
parentID = 0
if n.content['process_id'] == 'resample_spatial':
for n_0 in n.dependencies: # Check if the (or one of the) resample_spatial process is related to this load_collection
parentID = n_0.id
continue
if parentID == node.id: # The found resample_spatial comes right after the current load_collection, let's apply the resampling to the query
if 'resolution' in n.arguments:
res = n.arguments['resolution']
if isinstance(res,float) or isinstance(res,int):
resolutions = (res,res)
elif len(res) == 2:
resolutions = (res[0],res[1])
else:
logger.info('error')
if 'projection' in n.arguments:
if n.arguments['projection'] is not None:
projection = n.arguments['projection']
if isinstance(projection,int): # Check if it's an EPSG code and append 'epsg:' to it, without ODC returns an error
## TODO: make other projections available
projection = 'epsg:' + str(projection)
else:
logger.info('This type of reprojection is not yet implemented')
outputCrs = projection
if 'method' in n.arguments:
resamplingMethod = n.arguments['method']
odc = Odc(collections=collection,timeStart=timeStart,timeEnd=timeEnd,bands=bands,south=south,north=north,west=west,east=east,resolutions=resolutions,outputCrs=outputCrs,polygon=polygon,resamplingMethod=resamplingMethod,crs=crs)
if len(odc.data) == 0:
raise Exception("load_collection returned an empty dataset, please check the requested bands, spatial and temporal extent.")
self.partialResults[node.id] = odc.data.to_array()
self.crs = odc.data.crs # We store the data CRS separately, because it's a metadata we may lose it in the processing
logger.info(self.partialResults[node.id]) # The loaded data, stored in a dictionary with the id of the node that has generated it
if processName == 'resample_spatial':
source = node.arguments['data']['from_node']
self.partialResults[node.id] = self.partialResults[source]
# The following code block handles the fit_curve and predict_curve processes, where we need to convert a process graph into a callable python function
if node.parent_process is not None:
if (node.parent_process.process_id=='fit_curve' or node.parent_process.process_id=='predict_curve'):
if processName in ['pi']:
if processName == 'pi':
self.partialResults[node.id] = "np.pi"
if processName in ['array_element']:
self.partialResults[node.id] = 'a' + str(node.arguments['index'])
if processName in ['multiply','divide','subtract','add','sin','cos']:
x = None
y = None
source = None
if 'x' in node.arguments and node.arguments['x'] is not None:
if isinstance(node.arguments['x'],float) or isinstance(node.arguments['x'],int): # We have to distinguish when the input data is a number or a datacube from a previous process
x = str(node.arguments['x'])
else:
if 'from_node' in node.arguments['x']:
source = node.arguments['x']['from_node']
elif 'from_parameter' in node.arguments['x']:
x = 'x'
if source is not None:
x = self.partialResults[source]
source = None
if 'y' in node.arguments and node.arguments['y'] is not None:
if isinstance(node.arguments['y'],float) or isinstance(node.arguments['y'],int):
y = str(node.arguments['y'])
else:
if 'from_node' in node.arguments['y']:
source = node.arguments['y']['from_node']
elif 'from_parameter' in node.arguments['y']:
y = 'x'
if source is not None:
y = self.partialResults[source]
if processName == 'multiply':
if x is None or y is None:
raise Exception(MultiplicandMissing)
else:
self.partialResults[node.id] = "(" + x + "*" + y + ")"
elif processName == 'divide':
if y==0:
raise Exception(DivisionByZero)
else:
self.partialResults[node.id] = "(" + x + "/" + y + ")"
elif processName == 'subtract':
self.partialResults[node.id] = "(" + x + "-" + y + ")"
elif processName == 'add':
self.partialResults[node.id] = "(" + x + "+" + y + ")"
elif processName == 'sin':
self.partialResults[node.id] = "np.sin(" + x + ")"
elif processName == 'cos':
self.partialResults[node.id] = "np.cos(" + x + ")"
return 1
if processName == 'run_udf':
from openeo_r_udf import udf_lib
logging.getLogger('rpy2').setLevel(logging.ERROR)
parent = node.parent_process # I need to read the parent reducer process to see along which dimension take the mean
if 'from_node' in node.arguments['data']:
source = node.arguments['data']['from_node']
elif 'from_parameter' in node.arguments['data']:
source = node.parent_process.arguments['data']['from_node']
else:
logger.info('ERROR')
udf_dim = None
if parent.dimension in ['t','temporal','DATE','time']:
udf_dim = 'time'
elif parent.dimension in ['bands']:
udf_dim = 'variable'
spatial_ref_dim = 'spatial_ref'
if spatial_ref_dim in self.partialResults[source].coords:
self.crs = self.partialResults[source]['spatial_ref'].item(0)
self.partialResults[source] = self.partialResults[source].drop(spatial_ref_dim)
input_data = self.partialResults[source]
if 'time' in input_data.dims:
input_data['time'] = input_data['time'].astype('str')
# Parallelization config
if 'chunk_size' in node.arguments['context']:
chunk_size = node.arguments['context']['chunk_size']
else:
chunk_size = 512
if 'num_jobs' in node.arguments['context']:
num_jobs = node.arguments['context']['num_jobs']
else:
num_jobs = 8
if 'vectorized' in node.arguments['context']:
vectorized = int(node.arguments['context']['vectorized'])
else:
vectorized = False
logger.info('Chunk size: {} Number of workers: {}'.format(chunk_size,num_jobs))
# Define callback function
if vectorized:
logger.info("Run R UDF without joblib")
self.partialResults[node.id] = udf_lib.execute_udf(process=parent.process_id,
udf_path=node.arguments['udf'],
data=input_data,
dimension=udf_dim,
context=node.arguments['context']
)
else:
logger.info("Run R UDF with joblib")
def compute_udf(i,data,run_udf_number):
# logging.getLogger('rpy2').setLevel(logging.ERROR)
result = udf_lib.execute_udf(parent.process_id, node.arguments['udf'], data, dimension = udf_dim, context = node.arguments['context'])
result.to_netcdf(self.tmpFolderPath + '/udf_' + str(run_udf_number) + '_' + str(i) + '.nc')
result = None
return
# # Run UDF executor in parallel
input_data_chunked = udf_lib.chunk_cube(input_data, size=chunk_size)
results = Parallel(n_jobs=num_jobs)(joblibDelayed(compute_udf)(i,data,self.run_udf_number) for i,data in enumerate(input_data_chunked))
self.partialResults[node.id] = xr.open_mfdataset(self.tmpFolderPath + '/udf_' + str(self.run_udf_number) + '_*.nc', combine="nested").to_array()
self.run_udf_number = self.run_udf_number + 1
if processName == 'resample_cube_spatial':
target = node.arguments['target']['from_node']
source = node.arguments['data']['from_node']
method = node.arguments['method']
if method is None:
method = 'nearest'
if method == 'near':
method = 'nearest'
try:
import odc.algo
self.partialResults[node.id] = odc.algo._warp.xr_reproject(self.partialResults[source].compute(),self.partialResults[target].geobox,resampling=method).compute()
except Exception as e:
logger.info(e)
try:
self.partialResults[node.id] = self.partialResults[source].rio.reproject_match(self.partialResults[target],resampling=method)
except Exception as e:
raise Exception("ODC Error in process: ",processName,'\n Full Python log:\n',str(e))
if processName == 'resample_cube_temporal':
target = node.arguments['target']['from_node']
source = node.arguments['data']['from_node']
def nearest(items, pivot):
return min(items, key=lambda x: abs(x - pivot))
def resample_temporal(sourceCube,targetCube):
# Find in sourceCube the closest dates to tergetCube
newTime = []
for i,targetTime in enumerate(targetCube.time):
nearT = nearest(sourceCube.time.values,targetTime.values)
if i==0:
tmp = sourceCube.loc[dict(time=nearT)]
else:
tmp = xr.concat([tmp,sourceCube.loc[dict(time=nearT)]], dim='time')
if 'time' in tmp.dims:
tmp['time'] = targetCube.time
else:
tmp = tmp.expand_dims('time')
tmp['time'] = targetCube.time.values
return tmp
self.partialResults[node.id] = resample_temporal(self.partialResults[source],self.partialResults[target])
if processName in ['multiply','divide','subtract','add','lt','lte','gt','gte','eq','neq','log','ln']:
x = None
y = None
source = None
if 'x' in node.arguments and node.arguments['x'] is not None:
if isinstance(node.arguments['x'],float) or isinstance(node.arguments['x'],int): # We have to distinguish when the input data is a number or a datacube from a previous process
x = node.arguments['x']
else:
if 'from_node' in node.arguments['x']:
source = node.arguments['x']['from_node']
elif 'from_parameter' in node.arguments['x']:
if node.parent_process.process_id == 'merge_cubes':
source = node.parent_process.arguments['cube1']['from_node']
else:
source = node.parent_process.arguments['data']['from_node']
if source is not None:
x = self.partialResults[source]
if 'y' in node.arguments and node.arguments['y'] is not None:
if isinstance(node.arguments['y'],float) or isinstance(node.arguments['y'],int):
y = node.arguments['y']
else:
if 'from_node' in node.arguments['y']:
source = node.arguments['y']['from_node']
elif 'from_parameter' in node.arguments['y']:
if node.parent_process.process_id == 'merge_cubes':
source = node.parent_process.arguments['cube2']['from_node']
else:
source = node.parent_process.arguments['data']['from_node']
if source is not None:
y = self.partialResults[source]
if processName == 'multiply':
if x is None or y is None:
raise Exception(MultiplicandMissing)
else:
try:
result = (x * y)
if isinstance(result,int):
result = float(result)
if isinstance(result,float):
pass
else:
result = result.astype(np.float32)
self.partialResults[node.id] = result
except:
if hasattr(x,'chunks'):
x = x.compute()
if hasattr(y,'chunks'):
y = y.compute()
try:
self.partialResults[node.id] = (x * y).astype(np.float32).chunk()
except Exception as e:
raise e
elif processName == 'divide':
if (isinstance(y,int) or isinstance(y,float)) and y==0:
raise Exception(DivisionByZero)
else:
try:
result = (x / y)
if isinstance(result,int):
result = float(result)
if isinstance(result,float):
pass
else:
result = result.astype(np.float32)
self.partialResults[node.id] = result
except:
if hasattr(x,'chunks'):
x = x.compute()
if hasattr(y,'chunks'):
y = y.compute()
try:
self.partialResults[node.id] = (x / y).astype(np.float32).chunk()
except Exception as e:
raise e
elif processName == 'subtract':
try:
result = (x - y)
if isinstance(result,int):
result = float(result)
if isinstance(result,float):
pass
else:
result = result.astype(np.float32)
self.partialResults[node.id] = result
except:
if hasattr(x,'chunks'):
x = x.compute()
if hasattr(y,'chunks'):
y = y.compute()
try:
self.partialResults[node.id] = (x - y).astype(np.float32).chunk()
except Exception as e:
raise e
elif processName == 'add':
try:
result = (x + y)
if isinstance(result,int):
result = float(result)
if isinstance(result,float):
pass
else:
result = result.astype(np.float32)
self.partialResults[node.id] = result
except:
if hasattr(x,'chunks'):
x = x.compute()
if hasattr(y,'chunks'):
y = y.compute()
try:
self.partialResults[node.id] = (x + y).astype(np.float32).chunk()
except Exception as e:
raise e
elif processName == 'lt':
self.partialResults[node.id] = x < y
elif processName == 'lte':
self.partialResults[node.id] = x <= y
elif processName == 'gt':
self.partialResults[node.id] = x > y
elif processName == 'gte':
self.partialResults[node.id] = x >= y
elif processName == 'eq':
self.partialResults[node.id] = x == y
elif processName == 'neq':
self.partialResults[node.id] = x != y
elif processName == 'log':
base = float(node.arguments['base'])
self.partialResults[node.id] = np.log(x)/np.log(base)
elif processName == 'ln':
if isinstance(x,float) or isinstance(x,int):
self.partialResults[node.id] = np.ln(x)
else:
self.partialResults[node.id] = np.ln(x)
if processName == 'not':
if isinstance(node.arguments['x'],float) or isinstance(node.arguments['x'],int): # We have to distinguish when the input data is a number or a datacube from a previous process
x = node.arguments['x']
else:
if 'from_node' in node.arguments['x']:
source = node.arguments['x']['from_node']
elif 'from_parameter' in node.arguments['x']:
source = node.parent_process.arguments['data']['from_node']
x = self.partialResults[source]
self.partialResults[node.id] = np.logical_not(x)
if processName == 'sum':
parent = node.parent_process # I need to read the parent reducer process to see along which dimension take the sum
if parent.content['process_id'] == 'aggregate_spatial_window':
source = node.arguments['data']['from_node']
xDim, yDim = parent.content['arguments']['size']
boundary = parent.content['arguments']['boundary']
self.partialResults[node.id] = self.partialResults[source].coarsen(x=xDim,y=yDim,boundary = boundary).sum()
elif parent.content['process_id'] in ['aggregate_temporal_period','aggregate_spatial']:
self.partialResults[node.id] = 'sum' # Don't do anything, apply the sum later after aggregation
else:
x = 0
for i,d in enumerate(node.arguments['data']):
if isinstance(d,float) or isinstance(d,int): # We have to distinguish when the input data is a number or a datacube from a previous process
x = d
else:
if 'from_node' in d:
source = d['from_node']
elif 'from_parameter' in d:
source = node.parent_process.arguments['data']['from_node']
x = self.partialResults[source]
if i==0: self.partialResults[node.id] = x
else: self.partialResults[node.id] += x
if processName == 'product':
parent = node.parent_process # I need to read the parent reducer process to see along which dimension take the product
if parent.content['process_id'] == 'aggregate_spatial_window':
source = node.arguments['data']['from_node']
xDim, yDim = parent.content['arguments']['size']
boundary = parent.content['arguments']['boundary']
self.partialResults[node.id] = self.partialResults[source].coarsen(x=xDim,y=yDim,boundary = boundary).prod()
elif parent.content['process_id'] in ['aggregate_temporal_period','aggregate_spatial']:
self.partialResults[node.id] = 'product' # Don't do anything, apply the prod later after aggregation
else:
x = 0
for i,d in enumerate(node.arguments['data']):
if isinstance(d,float) or isinstance(d,int): # We have to distinguish when the input data is a number or a datacube from a previous process
x = d
else:
if 'from_node' in d:
source = d['from_node']
elif 'from_parameter' in d:
source = node.parent_process.arguments['data']['from_node']
x = self.partialResults[source]
if i==0: self.partialResults[node.id] = x
else: self.partialResults[node.id] *= x
if processName == 'sqrt':
x = node.arguments['x']
if isinstance(x,float) or isinstance(x,int): # We have to distinguish when the input data is a number or a datacube from a previous process
self.partialResults[node.id] = np.sqrt(x)
else:
if 'from_node' in node.arguments['x']:
source = node.arguments['x']['from_node']
elif 'from_parameter' in node.arguments['x']:
source = node.parent_process.arguments['data']['from_node']
self.partialResults[node.id] = np.sqrt(self.partialResults[source])
if processName == 'and':
x = node.arguments['x']['from_node']
y = node.arguments['y']['from_node']
self.partialResults[node.id] = np.bitwise_and(self.partialResults[x],self.partialResults[y])
if processName == 'or':
x = node.arguments['x']['from_node']
y = node.arguments['y']['from_node']
self.partialResults[node.id] = np.bitwise_or(self.partialResults[x],self.partialResults[y])
if processName == 'array_element':
if 'from_node' in node.arguments['data']:
source = node.arguments['data']['from_node']
elif 'from_parameter' in node.arguments['data']:
source = node.parent_process.arguments['data']['from_node']
else:
logger.info('ERROR')
noLabel = 1
if 'label' in node.arguments:
if node.arguments['label'] is not None:
bandLabel = node.arguments['label']
noLabel = 0
self.partialResults[node.id] = self.partialResults[source].loc[dict(variable=bandLabel)].drop('variable')
if 'index' in node.arguments and noLabel:
index = node.arguments['index']
self.partialResults[node.id] = self.partialResults[source][index]
if 'variable' in self.partialResults[node.id].coords:
self.partialResults[node.id] = self.partialResults[node.id].drop('variable')
if processName == 'normalized_difference':
def normalized_difference(x,y):
return (x-y)/(x+y)
xSource = (node.arguments['x']['from_node'])
ySource = (node.arguments['y']['from_node'])
self.partialResults[node.id] = normalized_difference(self.partialResults[xSource],self.partialResults[ySource])
if processName == 'reduce_dimension':
source = node.arguments['reducer']['from_node']
self.partialResults[node.id] = self.partialResults[source]
if processName == 'aggregate_spatial_window':
source = node.arguments['reducer']['from_node']
self.partialResults[node.id] = self.partialResults[source]
if processName == 'aggregate_spatial':
source = node.arguments['data']['from_node']
geometries = node.arguments['geometries']
try:
for feature in geometries['features']:
if 'properties' not in feature:
feature['properties'] = {}
elif feature['properties'] is None:
feature['properties'] = {}
except Exception as e:
print(e)
pass
try:
gdf = gpd.GeoDataFrame.from_features(geometries['features'])
## Currently I suppose the input geometries are in EPSG:4326 and the collection is projected in UTM
gdf = gdf.set_crs(4326)
except Exception as e:
print(e)
try:
coords = geometries['coordinates']
polygon = Polygon([tuple(c) for c in coords[0]])
gdf = gpd.GeoDataFrame(index=[0], crs='epsg:4326', geometry=[polygon])
except Exception as e:
raise(e)
gdf_utm = gdf.to_crs(int(self.partialResults[source].spatial_ref))
target_dimension = 'result'
if 'target_dimension' in node.arguments:
target_dimension = node.arguments['target_dimension']
## First clip the data and keep only the data within the polygons
crop = self.partialResults[source].rio.clip(gdf_utm.geometry, drop=True)
reducer = self.partialResults[node.arguments['reducer']['from_node']]
tmp = None
## Loop over the geometries in the FeatureCollection and apply the reducer
for i in range(len(gdf_utm)):
if reducer == 'mean':
geom_crop = crop.rio.clip(gdf_utm.loc[[i]].geometry).mean(dim=['x','y'])
elif reducer == 'min':
geom_crop = crop.rio.clip(gdf_utm.loc[[i]].geometry).min(dim=['x','y'])
elif reducer == 'max':
geom_crop = crop.rio.clip(gdf_utm.loc[[i]].geometry).max(dim=['x','y'])
elif reducer == 'median':
geom_crop = crop.rio.clip(gdf_utm.loc[[i]].geometry).median(dim=['x','y'])
elif reducer == 'product':
geom_crop = crop.rio.clip(gdf_utm.loc[[i]].geometry).prod(dim=['x','y'])
elif reducer == 'sum':
geom_crop = crop.rio.clip(gdf_utm.loc[[i]].geometry).sum(dim=['x','y'])
elif reducer == 'sd':
geom_crop = crop.rio.clip(gdf_utm.loc[[i]].geometry).std(dim=['x','y'])
elif reducer == 'variance':
geom_crop = crop.rio.clip(gdf_utm.loc[[i]].geometry).std(dim=['x','y'])**2
geom_crop[target_dimension] = i
if tmp is not None:
tmp = xr.concat([tmp,geom_crop],dim=target_dimension)
else:
tmp = geom_crop
self.partialResults[node.id] = tmp
if processName == 'filter_spatial':
source = node.arguments['data']['from_node']
try:
gdf = gpd.GeoDataFrame.from_features(node.arguments['geometries']['features'])
## Currently I suppose the input geometries are in EPSG:4326 and the collection is projected in UTM
gdf = gdf.set_crs(4326)
except:
try:
coords = node.arguments['geometries']['coordinates']
print(coords)
polygon = Polygon([tuple(c) for c in coords[0]])
gdf = gpd.GeoDataFrame(index=[0], crs='epsg:4326', geometry=[polygon])
except Exception as e:
raise(e)
gdf_utm = gdf.to_crs(int(self.partialResults[source].spatial_ref))
## Clip the data and keep only the data within the polygons
self.partialResults[node.id] = self.partialResults[source].rio.clip(gdf_utm.geometry, drop=True)
if processName == 'max':
parent = node.parent_process # I need to read the parent reducer process to see along which dimension take the max
if 'from_node' in node.arguments['data']:
source = node.arguments['data']['from_node']
elif 'from_parameter' in node.arguments['data']:
source = node.parent_process.arguments['data']['from_node']
else:
logger.info('ERROR')
if parent.content['process_id'] == 'aggregate_spatial_window':
xDim, yDim = parent.content['arguments']['size']
boundary = parent.content['arguments']['boundary']
self.partialResults[node.id] = self.partialResults[source].coarsen(x=xDim,y=yDim,boundary = boundary).max()
elif parent.content['process_id'] in ['aggregate_temporal_period','aggregate_spatial']:
self.partialResults[node.id] = 'max' # Don't do anything, apply the max later after aggregation
else:
dim = parent.dimension
if dim in ['t','temporal','DATE'] and 'time' in self.partialResults[source].dims:
self.partialResults[node.id] = self.partialResults[source].max('time')
elif dim in ['bands'] and 'variable' in self.partialResults[source].dims:
self.partialResults[node.id] = self.partialResults[source].max('variable')
elif dim in ['x'] and 'x' in self.partialResults[source].dims:
self.partialResults[node.id] = self.partialResults[source].max('x')
elif dim in ['y'] and 'y' in self.partialResults[source].dims:
self.partialResults[node.id] = self.partialResults[source].max('y')
else:
self.partialResults[node.id] = self.partialResults[source]
logger.info('[!] Dimension {} not available in the current data.'.format(dim))
if processName == 'min':
parent = node.parent_process # I need to read the parent reducer process to see along which dimension take the min
if 'from_node' in node.arguments['data']:
source = node.arguments['data']['from_node']
elif 'from_parameter' in node.arguments['data']:
source = node.parent_process.arguments['data']['from_node']
else:
logger.info('ERROR')
if parent.content['process_id'] == 'aggregate_spatial_window':
xDim, yDim = parent.content['arguments']['size']
boundary = parent.content['arguments']['boundary']
self.partialResults[node.id] = self.partialResults[source].coarsen(x=xDim,y=yDim,boundary = boundary).min()
elif parent.content['process_id'] in ['aggregate_temporal_period','aggregate_spatial']:
self.partialResults[node.id] = 'min' # Don't do anything, apply the min later after aggregation
else:
dim = parent.dimension
if dim in ['t','temporal','DATE'] and 'time' in self.partialResults[source].dims:
self.partialResults[node.id] = self.partialResults[source].min('time')
elif dim in ['bands'] and 'variable' in self.partialResults[source].dims:
self.partialResults[node.id] = self.partialResults[source].min('variable')
elif dim in ['x'] and 'x' in self.partialResults[source].dims:
self.partialResults[node.id] = self.partialResults[source].min('x')
elif dim in ['y'] and 'y' in self.partialResults[source].dims:
self.partialResults[node.id] = self.partialResults[source].min('y')
else:
self.partialResults[node.id] = self.partialResults[source]
logger.info('[!] Dimension {} not available in the current data.'.format(dim))
if processName == 'mean':
parent = node.parent_process # I need to read the parent reducer process to see along which dimension take the mean
if 'from_node' in node.arguments['data']:
source = node.arguments['data']['from_node']
elif 'from_parameter' in node.arguments['data']:
source = node.parent_process.arguments['data']['from_node']
else:
logger.info('ERROR')
self.partialResults[source] = self.partialResults[source].astype(np.float32)
if parent.content['process_id'] == 'aggregate_spatial_window':
xDim, yDim = parent.content['arguments']['size']
boundary = parent.content['arguments']['boundary']
self.partialResults[node.id] = self.partialResults[source].coarsen(x=xDim,y=yDim,boundary = boundary).mean()
elif parent.content['process_id'] in ['aggregate_temporal_period','aggregate_spatial']:
self.partialResults[node.id] = 'mean' # Don't do anything, apply the mean later after aggregation
else:
dim = parent.dimension
if dim in ['t','temporal','DATE'] and 'time' in self.partialResults[source].dims:
self.partialResults[node.id] = self.partialResults[source].mean('time')
elif dim in ['bands'] and 'variable' in self.partialResults[source].dims:
self.partialResults[node.id] = self.partialResults[source].mean('variable')
elif dim in ['x'] and 'x' in self.partialResults[source].dims:
self.partialResults[node.id] = self.partialResults[source].mean('x')
elif dim in ['y'] and 'y' in self.partialResults[source].dims:
self.partialResults[node.id] = self.partialResults[source].mean('y')
else:
self.partialResults[node.id] = self.partialResults[source]
logger.info('[!] Dimension {} not available in the current data.'.format(dim))
if processName == 'median':
parent = node.parent_process # I need to read the parent reducer process to see along which dimension take the median
if 'from_node' in node.arguments['data']:
source = node.arguments['data']['from_node']
elif 'from_parameter' in node.arguments['data']:
source = node.parent_process.arguments['data']['from_node']
else:
logger.info('ERROR')
self.partialResults[source] = self.partialResults[source].astype(np.float32)
if parent.content['process_id'] == 'aggregate_spatial_window':
xDim, yDim = parent.content['arguments']['size']
boundary = parent.content['arguments']['boundary']
self.partialResults[node.id] = self.partialResults[source].coarsen(x=xDim,y=yDim,boundary = boundary).median()
elif parent.content['process_id'] in ['aggregate_temporal_period','aggregate_spatial']:
self.partialResults[node.id] = 'median' # Don't do anything, apply the median later after aggregation
else:
dim = parent.dimension
if dim in ['t','temporal','DATE'] and 'time' in self.partialResults[source].dims:
self.partialResults[node.id] = self.partialResults[source].median('time')
elif dim in ['bands'] and 'variable' in self.partialResults[source].dims:
self.partialResults[node.id] = self.partialResults[source].median('variable')
elif dim in ['x'] and 'x' in self.partialResults[source].dims:
self.partialResults[node.id] = self.partialResults[source].median('x')
elif dim in ['y'] and 'y' in self.partialResults[source].dims:
self.partialResults[node.id] = self.partialResults[source].median('y')
else:
self.partialResults[node.id] = self.partialResults[source]
logger.info('[!] Dimension {} not available in the current data.'.format(dim))
if processName == 'sd':
parent = node.parent_process # I need to read the parent reducer process to see along which dimension take the std
if 'from_node' in node.arguments['data']:
source = node.arguments['data']['from_node']
elif 'from_parameter' in node.arguments['data']:
source = node.parent_process.arguments['data']['from_node']
else:
logger.info('ERROR')
if parent.content['process_id'] == 'aggregate_spatial_window':
xDim, yDim = parent.content['arguments']['size']
boundary = parent.content['arguments']['boundary']
self.partialResults[node.id] = self.partialResults[source].coarsen(x=xDim,y=yDim,boundary = boundary).std()
elif parent.content['process_id'] in ['aggregate_temporal_period','aggregate_spatial']:
self.partialResults[node.id] = 'sd' # Don't do anything, apply the std later after aggregation
else:
dim = parent.dimension
if dim in ['t','temporal','DATE'] and 'time' in self.partialResults[source].dims:
self.partialResults[node.id] = self.partialResults[source].std('time')
elif dim in ['bands'] and 'variable' in self.partialResults[source].dims:
self.partialResults[node.id] = self.partialResults[source].std('variable')
elif dim in ['x'] and 'x' in self.partialResults[source].dims:
self.partialResults[node.id] = self.partialResults[source].std('x')
elif dim in ['y'] and 'y' in self.partialResults[source].dims:
self.partialResults[node.id] = self.partialResults[source].std('y')
else:
self.partialResults[node.id] = self.partialResults[source]
logger.info('[!] Dimension {} not available in the current data.'.format(dim))
if processName == 'quantiles':
parent = node.parent_process # I need to read the parent reducer process to see along which dimension take the quantiles
if parent.process_id != 'apply_dimension':
raise Exception(f'The quantiles process must be used inside an apply_dimension process and not in {parent.process_id}')
if 'from_node' in node.arguments['data']:
source = node.arguments['data']['from_node']
elif 'from_parameter' in node.arguments['data']:
source = node.parent_process.arguments['data']['from_node']
else:
logger.info('ERROR')
if 'dimension' in parent.arguments and parent.arguments['dimension'] is not None:
dim = parent.arguments['dimension']
else:
raise Exception(DimensionNotAvailable)
target_dimension = None
if 'target_dimension' in parent.arguments and parent.arguments['target_dimension'] is not None:
target_dimension = parent.arguments['target_dimension']
p = None
q = None
if 'probabilities' in node.arguments and node.arguments['probabilities']!=[]:
p = node.arguments['probabilities']
if 'q' in node.arguments:
q = node.arguments['q']
if q is not None and p is not None:
raise Exception(QuantilesParameterConflict)
if q is None and p is None:
raise Exception(QuantilesParameterMissing)
if q is not None:
p = list(np.arange(0, 1, 1./q))[1:]
if dim in ['t','temporal','DATE','time'] and 'time' in self.partialResults[source].dims:
dim = 'time'
elif dim in ['bands'] and 'variable' in self.partialResults[source].dims:
dim = 'variable'
elif dim in ['x'] and 'x' in self.partialResults[source].dims:
dim = 'x'
elif dim in ['y'] and 'y' in self.partialResults[source].dims:
dim = 'y'
else:
raise Exception(DimensionNotAvailable)
self.partialResults[node.id] = self.partialResults[source].chunk(dict(time=-1)).quantile(np.array(p), dim=dim, skipna=True)
if target_dimension is not None:
self.partialResults[node.id] = self.partialResults[node.id].rename({'quantile':target_dimension})
else:
self.partialResults[node.id] = self.partialResults[node.id].rename({'quantile':dim})
if processName == 'aggregate_temporal_period':
source = node.arguments['data']['from_node']
reducer = self.partialResults[node.arguments['reducer']['from_node']]
#{'context': '', 'period': 'day', 'reducer': {'from_node': '1_2'}, 'data': {'from_node': '1_0'}, 'dimension': ''}
period = node.arguments['period']
# hour: Hour of the day
# day: Day of the year
# week: Week of the year
# dekad: Ten day periods, counted per year with three periods per month (day 1 - 10, 11 - 20 and 21 - end of month). The third dekad of the month can range from 8 to 11 days. For example, the fourth dekad is Feb, 1 - Feb, 10 each year.
# month: Month of the year
# season: Three month periods of the calendar seasons (December - February, March - May, June - August, September - November).
# tropical-season: Six month periods of the tropical seasons (November - April, May - October).
# year: Proleptic years
# decade: Ten year periods (0-to-9 decade), from a year ending in a 0 to the next year ending in a 9.
# decade-ad: Ten year periods (1-to-0 decade) better aligned with the anno Domini (AD) calendar era, from a year ending in a 1 to the next year ending in a 0.
periodsNotSupported = ['dekad','tropical-season','decade','decade-ad']
#periodDict = {'hour':'time.hour','day':'time.dayofyear','week':'t.week','month':'time.month','season':'time.season','year':'year.time'}
periodDict = {'hour':'1H','day':'1D','week':'1W','month':'1M','season':'QS','year':'1Y'}
if period in periodsNotSupported:
raise Exception("The selected period " + period + " is not currently supported. Please use one of: " + list(periodDict.keys()))
xarrayPeriod = str(periodDict[period])
supportedReducers = ['sum','product','min','max','median','mean','sd']
try:
if reducer == 'sum':
self.partialResults[node.id] = self.partialResults[source].resample(time=xarrayPeriod).sum()
elif reducer == 'product':
self.partialResults[node.id] = self.partialResults[source].resample(time=xarrayPeriod).prod()
elif reducer == 'min':
self.partialResults[node.id] = self.partialResults[source].resample(time=xarrayPeriod).min()
elif reducer == 'max':
self.partialResults[node.id] = self.partialResults[source].resample(time=xarrayPeriod).max()
elif reducer == 'median':
self.partialResults[node.id] = self.partialResults[source].resample(time=xarrayPeriod).median()
elif reducer == 'mean':
self.partialResults[node.id] = self.partialResults[source].resample(time=xarrayPeriod).mean()
elif reducer == 'sd':
self.partialResults[node.id] = self.partialResults[source].resample(time=xarrayPeriod).std()
else:
raise Exception("The selected reducer is not supported. Please use one of: " + supportedReducers)
except Exception as e:
logger.info(e)
if reducer == 'sum':
self.partialResults[node.id] = self.partialResults[source].resample(t=xarrayPeriod).sum()
elif reducer == 'product':
self.partialResults[node.id] = self.partialResults[source].resample(t=xarrayPeriod).prod()
elif reducer == 'min':
self.partialResults[node.id] = self.partialResults[source].resample(t=xarrayPeriod).min()
elif reducer == 'max':
self.partialResults[node.id] = self.partialResults[source].resample(t=xarrayPeriod).max()
elif reducer == 'median':
self.partialResults[node.id] = self.partialResults[source].resample(t=xarrayPeriod).median()
elif reducer == 'mean':
self.partialResults[node.id] = self.partialResults[source].resample(t=xarrayPeriod).mean()
elif reducer == 'sd':
self.partialResults[node.id] = self.partialResults[source].resample(t=xarrayPeriod).std()
else:
raise Exception("The selected reducer is not supported. Please use one of: " + supportedReducers)
if processName == 'power':
dim = node.arguments['base']
if isinstance(node.arguments['base'],float) or isinstance(node.arguments['base'],int): # We have to distinguish when the input data is a number or a datacube from a previous process
x = node.arguments['base']
else:
x = self.partialResults[node.arguments['base']['from_node']]
self.partialResults[node.id] = (x**node.arguments['p']).astype(np.float32)
if processName == 'absolute':
source = node.arguments['x']['from_node']
self.partialResults[node.id] = abs(self.partialResults[source])
if processName == 'linear_scale_range':
parent = node.parent_process # I need to read the parent apply process
if 'from_node' in parent.arguments['data']:
source = node.parent_process.arguments['data']['from_node']
else:
raise Exception("[!] The current process is missing the ['data']['from_node'] field, can't proceed.")
inputMin = node.arguments['inputMin']
inputMax = node.arguments['inputMax']
outputMax = node.arguments['outputMax']
outputMin = 0
if 'outputMin' in node.arguments:
outputMin = node.arguments['outputMin']
try:
tmp = self.partialResults[source].clip(min=inputMin,max=inputMax)
except Exception as e:
logger.info(e)
try:
tmp = self.partialResults[source].compute()
tmp = tmp.clip(inputMin,inputMax)
except Exception as e:
raise e
self.partialResults[node.id] = ((tmp - inputMin) / (inputMax - inputMin)) * (outputMax - outputMin) + outputMin
if processName == 'clip':
parent = node.parent_process # I need to read the parent apply process
if 'from_node' in parent.arguments['data']:
source = node.parent_process.arguments['data']['from_node']
else:
raise Exception("[!] The current process is missing the ['data']['from_node'] field, can't proceed.")
outputMax = node.arguments['max']
outputMin = 0
if 'min' in node.arguments:
outputMin = node.arguments['min']