This repository has been archived by the owner on Mar 6, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathcubes.py
2344 lines (1947 loc) · 91.3 KB
/
cubes.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
from datetime import datetime
from os.path import splitext
from pathlib import Path
from typing import Any, Dict, List
import numpy as np
import pandas as pd
import odc.algo
import rioxarray # needed by save_result even if not directly called
import xarray as xr
from shapely.geometry import Point, LineString, Polygon, MultiPolygon
from openeo_processes.extension.odc import write_odc_product
from openeo_processes.utils import process, get_time_dimension_from_data, get_equi7_tiles, derive_datasets_and_filenames_from_tiles
from openeo_processes.errors import DimensionNotAvailable, TooManyDimensions
from scipy import optimize
import datacube
import dask
from datacube.utils.geometry import Geometry
try:
from pyproj import Transformer, CRS
except ImportError:
Transformer = None
CRS = None
import xgboost as xgb
import dask.dataframe as df
import dask_geopandas
from openeo_processes.utils import geometry_mask
import geopandas as gpd
import urllib, json
import os
from functools import partial
DEFAULT_CRS = 4326
###############################################################################
# Load Collection Process
###############################################################################
def odc_load_helper(odc_cube, params: Dict[str, Any]) -> xr.DataArray:
"""Helper method to load a xarray DataArray from ODC."""
datacube = odc_cube.load(skip_broken_datasets=True, **params)
# Improve CPU and MEM USAGE
for name, data_var in datacube.data_vars.items():
datacube[name] = datacube[name].where(datacube[name] != datacube[name].nodata)
datacube.attrs['nodata'] = np.nan
refdata = {'collection': params['product']}
datacube.attrs.update(refdata)
# Convert to xr.DataArray
# TODO: add conversion with multiple and custom dimensions
return datacube.to_array(dim='bands')
@process
def load_collection():
"""
Returns class instance of `LoadCollection`.
For more details, please have a look at the implementations inside
`LoadCollection`.
Returns
-------
LoadCollection :
Class instance implementing all 'load_collection' processes.
"""
return LoadCollection()
class LoadCollection:
"""
Class implementing all 'load_collection' processes.
"""
@staticmethod
def exec_odc(odc_cube, product: str, dask_chunks: dict,
x: tuple = (), y: tuple = (), time: list = [],
measurements: list = [], crs: str = "EPSG:4326"):
odc_params = {
'product': product,
'dask_chunks': dask_chunks
}
if x:
odc_params['x'] = x
if y:
odc_params['y'] = y
if crs:
odc_params['crs'] = crs
# lists are transformed to np.arrays by the wrapper
# update when that step has been removed
if len(time) > 0:
odc_params['time'] = list(time)
if len(measurements) > 0:
odc_params['measurements'] = list(measurements)
return odc_load_helper(odc_cube, odc_params)
###############################################################################
# Load Result Process
###############################################################################
@process
def load_result():
"""
Returns class instance of `LoadResult`.
For more details, please have a look at the implementations inside
`LoadResult`.
Returns
-------
LoadResult :
Class instance implementing all 'load_result' processes.
"""
return LoadResult()
class LoadResult:
"""
Class implementing all 'load_result' processes.
"""
@staticmethod
def exec_odc(odc_cube, product: str, dask_chunks: dict,
x = None, y = None, time = [],
measurements = [], crs = None):
odc_params = {
'product': product,
'dask_chunks': dask_chunks
}
part = False
if crs:
odc_params['crs'] = crs
# lists are transformed to np.arrays by the wrapper
# update when that step has been removed
if len(time) > 0:
odc_params['time'] = list(time)
if len(measurements) > 0:
odc_params['measurements'] = list(measurements)
if x:
odc_params['x'] = x
part = True
if y:
odc_params['y'] = y
part = True
if part:
try:
dataarray = odc_load_helper(odc_cube, odc_params)
except:
if x:
odc_params['longitude'] = x
odc_params.pop('x')
if y:
odc_params['latitude'] = y
odc_params.pop('y')
dataarray = odc_load_helper(odc_cube, odc_params)
else:
dataarray = odc_load_helper(odc_cube, odc_params)
# If data is in geographic coordinate system coords are called longitude/latitude
# for consistency and easier handling in other processes rename them to x/y
if "longitude" in dataarray.coords and "latitude" in dataarray.coords:
dataarray.rename({"longitude": "x", "latitude": "y"})
# In ODC each dataset must have a time dimension also if non exists
# remove it if only a single one exist
if "time" in dataarray.coords and len(dataarray["time"]) == 1:
dataarray = dataarray.squeeze("time", drop=True)
return dataarray
###############################################################################
# Save result process
###############################################################################
@process
def save_result():
"""
Returns class instance of `save_result`.
For more details, please have a look at the implementations inside
`save_result`.
Returns
-------
save_result :
Class instance implementing all 'save_result' processes.
"""
return SaveResult()
class SaveResult:
"""
Class implementing 'save_result' processes.
"""
@staticmethod
def exec_xar(data, output_filepath='out', format='GTiff', options={}, write_prod: bool = True):
"""
Save data to disk in specified format. Data is saved to files reflecting the EQUI7 Tiles that the original data
is loaded from.
Parameters
----------
data : xr.DataArray
An array of numbers. An empty array resolves always with np.nan.
output_filepath: str
Absolute or relative filepath where to store data on disk,
with or without extention
format: str, optional
data format (default: GTiff)
"""
formats = ['gtiff', 'netcdf', 'geotiff']
if format.lower() in formats:
format = format.lower()
else:
raise ValueError(f"Error when saving to file. Format '{format}' is not in {formats}.")
data = data.fillna(-9999)
data.attrs["nodata"] = -9999
# Convert data array to data set, keeping a nice format on the bands.
if 'bands' in data.dims:
data = data.to_dataset(
dim='bands'
)
else:
data = xr.Dataset(
data_vars={'result':data}
)
if "crs" not in data.attrs:
first_data_var = data.data_vars[list(data.data_vars.keys())[0]]
data.attrs["crs"] = first_data_var.geobox.crs.to_wkt()
tiles, gridder = get_equi7_tiles(data)
# Renaming the time dimension
if 'time' in data.dims:
data = data.rename({'time': 't'})
if 't' not in data.dims:
data = data.assign_coords(t=datetime.now())
data = data.expand_dims('t')
# Add back the odc hack
data.attrs["datetime_from_dim"] = str(datetime.now())
# Avoid value error on attrs
if hasattr(data, 't') and hasattr(data.t, 'units'):
data.t.attrs.pop('units', None)
if hasattr(data, 'grid_mapping'):
data.attrs.pop('grid_mapping')
# Group datasets by time. This will help with storing multiple files via dask.
times, datasets = zip(*data.groupby("t"))
if format == 'netcdf':
ext = 'nc'
else:
ext = 'tif'
final_datasets, dataset_filenames = derive_datasets_and_filenames_from_tiles(gridder, times, datasets, tiles, output_filepath, ext)
if (len(final_datasets) == 0) or (len(dataset_filenames) == 0):
raise Exception("No tiles could be derived from given dataset")
# Submit list of netcdfs and filepaths to dask to compute
if format == 'netcdf':
xr.save_mfdataset(final_datasets, dataset_filenames)
# Iterate datasets and save to tif
elif format in ['gtiff','geotiff']:
if len(final_datasets[0].dims) > 3:
raise Exception("[!] Not possible to write a 4-dimensional GeoTiff, use NetCDF instead.")
for idx, dataset in enumerate(final_datasets):
dataset.rio.to_raster(raster_path=dataset_filenames[idx], driver='COG', **options)
# Write and odc product yml file
if write_prod:
write_odc_product(datasets[0], output_filepath)
###############################################################################
# Reduce dimension process
###############################################################################
@process
def reduce_dimension():
"""
Returns class instance of `reduce_dimension`.
For more details, please have a look at the implementations inside
`reduce_dimension`.
Returns
-------
reduce_dimension :
Class instance implementing all 'reduce_dimension' processes.
"""
return ReduceDimension()
class ReduceDimension:
"""
Class implementing all 'reduce_dimension' processes.
"""
@staticmethod
def exec_xar(data, reducer, dimension=None, context={}):
"""
Parameters
----------
data : xr.DataArray
An array of numbers. An empty array resolves always with np.nan.
reducer : callable or dict
the name of an existing process (e.g. `mean`) or a dict for a
process graph
dimension : str, optional
Defines the dimension to calculate the sum along (defaults to first
dimension if not specified). Dimensions are expected in this order:
(dim1, dim2, y, x)
context: dict, optional
keyworded parameters needed by the `reducer`
Returns
-------
xr.DataArray
"""
if callable(reducer):
return reducer(data, dimension=dimension, **context)
elif isinstance(reducer, dict):
# No need to map this
return data
###############################################################################
# Apply process
###############################################################################
@process
def apply():
"""
Returns class instance of `Apply`.
For more details, please have a look at the implementations inside
`Apply`.
Returns
-------
reduce_dimension :
Class instance implementing all 'apply' processes.
"""
return Apply()
class Apply:
"""
Class implementing all 'apply' processes.
"""
@staticmethod
def exec_xar(data, process, context={}):
"""
Parameters
----------
data : xr.DataArray
An array of numbers. An empty array resolves always with np.nan.
process : callable or dict
the name of an existing process (e.g. `mean`) or a dict for a
process graph
context: dict, optional
keyworded parameters needed by the `reducer`
Returns
-------
xr.DataArray
"""
if callable(process):
return process(data, **context)
return data
###############################################################################
# MergeCubes process
###############################################################################
@process
def merge_cubes():
"""
Returns class instance of `Merge Cubes`.
For more details, please have a look at the implementations inside
`Merge Cubes`.
Returns
-------
merged data cube :
See the process description for details regarding the dimensions and dimension properties (name, type, labels, reference system and resolution).
"""
return MergeCubes()
class MergeCubes:
"""
Class implementing 'merge_cubes' process.
The data cubes have to be compatible. A merge operation without overlap should be reversible with (a set of) filter operations for each of the two cubes.
The process performs the join on overlapping dimensions, with the same name and type.
An overlapping dimension has the same name, type, reference system and resolution in both dimensions, but can have different labels.
One of the dimensions can have different labels, for all other dimensions the labels must be equal.
If data overlaps, the parameter overlap_resolver must be specified to resolve the overlap.
"""
@staticmethod
def exec_xar(cube1, cube2, overlap_resolver = None, context={}):
"""
Parameters
----------
cube1 : xr.DataArray
The first data cube.
cube2 : xr.DataArray
The second data cube.
overlap_resolver : callable or dict or xr.DataArray (created in advance due to mapping)
the name of an existing process (e.g. `mean`) or a dict for a
process graph
context: dict, optional
keyworded parameters needed by the `reducer`
Returns
-------
xr.DataArray
"""
if not isinstance(cube1, type(cube2)):
raise Exception(f"Provided cubes have incompatible types. cube1: {type(cube1)}, cube2: {type(cube2)}")
is_geopandas = isinstance(cube1, gpd.geodataframe.GeoDataFrame) and isinstance(cube2, gpd.geodataframe.GeoDataFrame)
is_delayed_geopandas = isinstance(cube1, dask_geopandas.core.GeoDataFrame) and isinstance(cube2, dask_geopandas.core.GeoDataFrame)
if is_geopandas or is_delayed_geopandas:
if list(cube1.columns) == list(cube2.columns):
if is_delayed_geopandas:
merged_cube = cube1.append(cube2)
if is_geopandas:
merged_cube = cube1.append(cube2, ignore_index=True)
print("Warning - Overlap resolver is not implemented for geopandas vector-cubes, cubes are simply appended!")
else:
if 'geometry' in cube1.columns and 'geometry' in cube2.columns:
merged_cube = cube1.merge(cube2, on='geometry')
return merged_cube
if (cube1.dims == cube2.dims): # Check if the dimensions have the same names
matching = 0
not_matching = 0
for c in cube1.coords:
cord = (cube1[c] == cube2[c]) # Check how many dimensions have exactly the same coordinates
if (np.array([cord.values])).shape[-1] == 1: # Special case where dimension has only one coordinate, cannot compute len() of that, so I use shape
cord = (np.array([cord.values])) # cord is set 0 or 1 here (False or True)
else:
cord = len(cord)
if cord == 0: # dimension with different coordinates
dimension = c
elif cord == (np.array([cube1[c].values])).shape[-1]: # dimensions with matching coordinates, shape instead of len, for special case with only one coordinate
matching += 1
else:
not_matching += 1
dim_not_matching = c # dimensions with some matching coordinates
if matching + 1 == len(cube1.coords) and not_matching == 0: # one dimension with different coordinates
merge = xr.concat([cube1, cube2], dim=dimension)
merge = merge.sortby(dimension)
elif matching == len(cube1.coords): # all dimensions match
if overlap_resolver is None: # no overlap resolver, so a new dimension is added
merge = xr.concat([cube1, cube2], dim='cubes')
merge['cubes'] = ["Cube01", "Cube02"]
else:
if callable(overlap_resolver): # overlap resolver, for example add
merge = overlap_resolver(cube1, cube2, **context)
elif isinstance(overlap_resolver, xr.core.dataarray.DataArray):
merge = overlap_resolver
else:
raise Exception('OverlapResolverMissing')
else: # WIP
if not_matching == 1: # one dimension where some coordinates match, others do not, other dimensions match
same1 = []
diff1 = []
index = 0
for t in cube1[dim_not_matching]: # count matching coordinates
if (t == cube2[dim_not_matching]).any():
same1.append(index)
index += 1
else: # count different coordinates
diff1.append(index)
index += 1
same2 = []
diff2 = []
index2 = 0
for t in cube2[dim_not_matching]:
if (t == cube1[dim_not_matching]).any():
same2.append(index2)
index2 += 1
else:
diff2.append(index2)
index2 += 1
if callable(overlap_resolver):
c1 = cube1.transpose(dim_not_matching, ...)
c2 = cube2.transpose(dim_not_matching, ...)
merge = overlap_resolver(c1[same1], c2[same2], **context)
if len(diff1) > 0:
values_cube1 = c1[diff1]
merge = xr.concat([merge, values_cube1], dim=dim_not_matching)
if len(diff2) > 0:
values_cube2 = c2[diff2]
merge = xr.concat([merge, values_cube2], dim=dim_not_matching)
merge = merge.sortby(dim_not_matching)
merge = merge.transpose(*cube1.dims)
else:
merge = xr.concat([cube1, cube2], dim=dim_not_matching)
else: # if dims do not match - WIP
if len(cube1.dims) < len(cube2.dims):
c1 = cube1
c2 = cube2
else:
c1 = cube2
c2 = cube1
check = []
for c in c1.dims:
check.append(c in c1.dims and c in c2.dims)
for c in c2.dims:
if not (c in c1.dims):
dimension = c
if np.array(check).all() and len(c2[dimension]) == 1 and callable(overlap_resolver):
c2 = c2.transpose(dimension, ...)
merge = overlap_resolver(c2[0], c1, **context)
elif isinstance(overlap_resolver, xr.core.dataarray.DataArray):
merge = overlap_resolver
else:
raise Exception('OverlapResolverMissing')
for a in cube1.attrs:
if a in cube2.attrs and (cube1.attrs[a] == cube2.attrs[a]):
merge.attrs[a] = cube1.attrs[a]
return merge
###############################################################################
# FitCurve process
###############################################################################
@process
def fit_curve():
"""
Returns class instance of `Fit Curve`.
For more details, please have a look at the implementations inside
`Fit Curve`.
Returns
-------
fitting parameters for the data cube :
See the process description for details regarding the dimensions and dimension properties (name, type, labels, reference system and resolution).
"""
return FitCurve()
class FitCurve:
"""
Class implementing 'fit_curve' process.
Use non-linear least squares to fit a model function y = f(x, parameters) to data.
The process throws an InvalidValues exception if invalid values are encountered.
Invalid values are finite numbers (see also is_valid).
"""
@staticmethod
def exec_xar(data, parameters, function, dimension):
"""
Parameters
----------
data : xr.DataArray
A data cube.
parameters : array
Defined the number of parameters for the model function and provides an initial guess for them. At least one parameter is required.
function : child process
The model function. It must take the parameters to fit as array through the first argument and the independent variable x as the second argument.
It is recommended to store the model function as a user-defined process on the back-end to be able to re-use the model function with the computed optimal values for the parameters afterwards.
child process parameters:
x : number
The value for the independent variable x.
parameters : array
The parameters for the model function, contains at least one parameter.
Child process return value : number
The computed value y for the given independent variable x and the parameters.
dimension : str
The name of the dimension for curve fitting.
Must be a dimension with labels that have a order (i.e. numerical labels or a temporal dimension).
Fails with a DimensionNotAvailable exception if the specified dimension does not exist.
Returns
-------
xr.DataArray
A data cube with the optimal values for the parameters.
"""
data = data.fillna(0) # zero values (masked) are not considered
if dimension in ['time', 't', 'times']: # time dimension must be converted into values
dimension = get_time_dimension_from_data(data, dimension)
dates = data[dimension].values
timestep = [((x - np.datetime64('1970-01-01')) / np.timedelta64(1, 's')) for x in dates]
step = np.array(timestep)
data[dimension] = step
else:
step = dimension
if isinstance(parameters, xr.core.dataarray.DataArray):
apply_f = (lambda x, y, p: optimize.curve_fit(function, x[np.nonzero(y)], y[np.nonzero(y)], p)[0])
in_dims = [[dimension], [dimension], ['params']]
add_arg = [step, data, parameters]
output_size = len(parameters['params'])
else:
apply_f = (lambda x, y: optimize.curve_fit(function, x[np.nonzero(y)], y[np.nonzero(y)], parameters)[0])
in_dims = [[dimension], [dimension]]
add_arg = [step, data]
output_size = len(parameters)
values = xr.apply_ufunc(
apply_f, *add_arg,
vectorize=True,
input_core_dims=in_dims,
output_core_dims=[['params']],
dask="parallelized",
output_dtypes=[np.float32],
dask_gufunc_kwargs={'allow_rechunk': True, 'output_sizes': {'params': output_size}}
)
values['params'] = list(range(len(values['params'])))
values.attrs = data.attrs
return values
###############################################################################
# PredictCurve process
###############################################################################
@process
def predict_curve():
"""
Returns class instance of `Predict Curve`.
For more details, please have a look at the implementations inside
`Predict Curve`.
Returns
-------
A data cube with the predicted values.
See the process description for details regarding the dimensions and dimension properties (name, type, labels, reference system and resolution).
"""
return PredictCurve()
class PredictCurve:
"""
Class implementing 'predict_curve' process.
Predict values using a model function and pre-computed parameters.
"""
@staticmethod
def exec_xar(data, parameters, function, dimension, labels = None):
"""
Parameters
----------
data : xr.DataArray
A data cube to predict values for.
parameters : xr.DataArray
A data cube with optimal values from a result of e.g. fit_curve.
function : child process
The model function. It must take the parameters to fit as array through the first argument and the independent variable x as the second argument.
It is recommended to store the model function as a user-defined process on the back-end.
child process parameters:
x : number
The value for the independent variable x.
parameters : array
The parameters for the model function, contains at least one parameter.
Child process return value : number
The computed value y for the given independent variable x and the parameters.
dimension : str
The name of the dimension for curve fitting.
Must be a dimension with labels that have a order (i.e. numerical labels or a temporal dimension).
Fails with a DimensionNotAvailable exception if the specified dimension does not exist.
labels : number, date or date-time
The labels to predict values for. If no labels are given, predicts values only for no-data (null) values in the data cube.
Returns
-------
xr.DataArray
A data cube with the predicted values.
"""
data = data.fillna(0)
if (np.array([labels])).shape[-1] > 1:
test = [labels]
else:
test = labels
if dimension in ['time', 't', 'times']: # time dimension must be converted into values
dimension = get_time_dimension_from_data(data, dimension)
dates = data[dimension].values
if test is None:
timestep = [((np.datetime64(x) - np.datetime64('1970-01-01')) / np.timedelta64(1, 's')) for x in dates]
labels = np.array(timestep)
else:
coords = labels
labels = [((np.datetime64(x) - np.datetime64('1970-01-01')) / np.timedelta64(1, 's')) for x in labels]
labels = np.array(labels)
else:
if test is None:
labels = data[dimension].values
else:
coords = labels
values = xr.apply_ufunc(lambda a: function(labels, *a), parameters,
vectorize=True,
input_core_dims=[['params']],
output_core_dims=[[dimension]],
dask="parallelized",
output_dtypes=[np.float32],
dask_gufunc_kwargs={'allow_rechunk': True, 'output_sizes': {dimension: len(labels)}}
)
if test is None:
values = values.transpose(*data.dims)
values[dimension] = data[dimension]
predicted = data.where(data != 0, values)
else:
predicted = values.transpose(*data.dims)
predicted[dimension] = coords
if dimension in ['t', 'times']:
predicted = predicted.rename({dimension: 'time'})
predicted.attrs = data.attrs
return predicted
###############################################################################
# Resample cube spatial process
###############################################################################
@process
def resample_cube_spatial():
"""
Returns class instance of `resample_cube_spatial`.
For more details, please have a look at the implementations inside
`resample_cube_spatial`.
Returns
-------
save_result :
Class instance implementing 'resample_cube_spatial' process.
"""
return ResampleCubeSpatial()
class ResampleCubeSpatial:
"""
Class implementing 'resample_cube_spatial' processe.
"""
@staticmethod
def exec_xar(data, target, method=None, options={}):
"""
Save data to disk in specified format.
Parameters
----------
data : xr.DataArray
A data cube.
target: str,
A data cube that describes the spatial target resolution.
method: str,
Resampling method. Methods are inspired by GDAL, see [gdalwarp](https://www.gdal.org/gdalwarp.html) for more information.
"near","bilinear","cubic","cubicspline","lanczos","average","mode","max","min","med","q1","q3"
(default: near)
"""
try:
methods_list = ["near","bilinear","cubic","cubicspline","lanczos","average","mode","max","min","med","q1","q3"]
if method is None or method == 'near':
method = 'nearest'
elif method not in methods_list:
raise Exception(f"Selected resampling method \"{method}\" is not available! Please select one of "
f"[{', '.join(methods_list)}]")
return odc.algo._warp.xr_reproject(data,target.geobox,resampling=method)
except Exception as e:
raise e
###############################################################################
# Resample cube temporal process
###############################################################################
@process
def resample_cube_temporal():
"""
Returns class instance of `resample_cube_temporal`.
For more details, please have a look at the implementations inside
`resample_cube_temporal`.
Returns
-------
save_result :
Class instance implementing 'resample_cube_temporal' process.
"""
return ResampleCubeTemporal()
class ResampleCubeTemporal:
"""
Class implementing 'resample_cube_temporal' process.
"""
@staticmethod
def exec_xar(data, target, dimension = None, valid_within = None):
"""
Resamples one or more given temporal dimensions from a source data cube to align with the corresponding dimensions of the given target data cube using the nearest neighbor method.
Returns a new data cube with the resampled dimensions. By default, this process simply takes the nearest neighbor independent of the value (including values such as no-data / null).
Depending on the data cubes this may lead to values being assigned to two target timestamps.
To only consider valid values in a specific range around the target timestamps, use the parameter valid_within.
The rare case of ties is resolved by choosing the earlier timestamps.
Parameters
----------
data : xr.DataArray
A data cube.
target : str,
A data cube that describes the temporal target resolution.
dimension : str, null
The name of the temporal dimension to resample, which must exist with this name in both data cubes.
If the dimension is not set or is set to null, the process resamples all temporal dimensions that exist with the same names in both data cubes.
The following exceptions may occur:
A dimension is given, but it does not exist in any of the data cubes: DimensionNotAvailable
A dimension is given, but one of them is not temporal: DimensionMismatch
No specific dimension name is given and there are no temporal dimensions with the same name in the data: DimensionMismatch
valid_within : number, null
Setting this parameter to a numerical value enables that the process searches for valid values within the given period of days before and after the target timestamps.
Valid values are determined based on the function is_valid.
For example, the limit of 7 for the target timestamps 2020-01-15 12:00:00 looks for a nearest neighbor after 2020-01-08 12:00:00 and before 2020-01-22 12:00:00.
If no valid value is found within the given period, the value will be set to no-data (null).
"""
if dimension is None:
dimension = 'time'
if dimension in ['time', 't', 'times']: # time dimension must be converted into values
dimension = get_time_dimension_from_data(data, dimension)
else:
raise Exception('DimensionNotAvailable')
if dimension not in target.dims:
target_time = get_time_dimension_from_data(target, dimension)
target = target.rename({target_time: dimension})
index = []
for d in target[dimension].values:
difference = (np.abs(d - data[dimension].values))
nearest = np.argwhere(difference == np.min(difference))
index.append(int(nearest))
times_at_target_time = data[dimension].values[index]
new_data = data.loc[{dimension: times_at_target_time}]
filter_values = new_data[dimension].values
new_data[dimension] = target[dimension].values
if valid_within is None:
new_data = new_data
else:
minimum = np.timedelta64(valid_within, 'D')
filter = (np.abs(filter_values - new_data[dimension].values) <= minimum)
times_valid = new_data[dimension].values[filter]
new_data = new_data.loc[{dimension: times_valid}]
new_data.attrs = data.attrs
return new_data
###############################################################################
# CreateRasterCube process
###############################################################################
@process
def create_raster_cube():
"""
Create an empty raster data cube.
Returns
-------
data cube :
Creates a new raster data cube without dimensions. Dimensions can be added with add_dimension.
"""
return CreateRasterCube()
class CreateRasterCube:
"""
Creates a new raster data cube without dimensions. Dimensions can be added with add_dimension.
"""
@staticmethod
def exec_num():
"""
Parameters
----------
This process has no parameters.
Returns
-------
xr.DataArray :
An empty raster data cube with zero dimensions.
"""
return xr.DataArray([])
###############################################################################
# AddDimension process
###############################################################################
@process
def add_dimension():
"""
Adds a new named dimension to the data cube.
Returns
-------
data cube :
The data cube with a newly added dimension. The new dimension has exactly one dimension label.
All other dimensions remain unchanged.
"""
return AddDimension()
class AddDimension:
"""
Adds a new named dimension to the data cube.
Afterwards, the dimension can be referred to with the specified name.
If a dimension with the specified name exists, the process fails with a DimensionExists exception.
The dimension label of the dimension is set to the specified label.
"""
@staticmethod
def exec_xar(data=None, name=None, label=None, type='other'):
"""
Parameters
----------
data : xr.DataArray
A data cube to add the dimension to.
name : str
Name for the dimension.
labels : number, str
A dimension label.
type : str, optional
The type of dimension, defaults to other.
Returns
-------
xr.DataArray :
The data cube with a newly added dimension. The new dimension has exactly one dimension label.
All other dimensions remain unchanged.
"""
if name in data.dims:
raise Exception('DimensionExists - A dimension with the specified name already exists. The existing dimensions are: {}'.format(data.dims))
data_e = data.assign_coords(placeholder = label)
data_e = data_e.expand_dims('placeholder')
data_e = data_e.rename({'placeholder' : name})
return data_e
###############################################################################
# DimensionLabels process
###############################################################################
@process
def dimension_labels():
"""
Get the dimension labels.
Returns
-------
Array :