-
Notifications
You must be signed in to change notification settings - Fork 109
/
Copy pathbase.py
1479 lines (1179 loc) · 50.9 KB
/
base.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
"""rio_tiler.io.base: ABC class for rio-tiler readers."""
import abc
import contextlib
import re
import warnings
from functools import cached_property
from typing import Any, Dict, List, Optional, Sequence, Tuple, Type, Union
import attr
import numpy
from affine import Affine
from morecantile import Tile, TileMatrixSet
from rasterio.crs import CRS
from rasterio.rio.overview import get_maximum_overview_level
from rasterio.warp import calculate_default_transform, transform_bounds
from rio_tiler.constants import WEB_MERCATOR_TMS
from rio_tiler.errors import (
AssetAsBandError,
ExpressionMixingWarning,
InvalidExpression,
MissingAssets,
MissingBands,
TileOutsideBounds,
)
from rio_tiler.models import BandStatistics, ImageData, Info, PointData
from rio_tiler.tasks import multi_arrays, multi_points, multi_values
from rio_tiler.types import AssetInfo, BBox, Indexes
from rio_tiler.utils import CRS_to_uri, cast_to_sequence, normalize_bounds
@attr.s
class SpatialMixin:
"""Spatial Info Mixin.
Attributes:
tms (morecantile.TileMatrixSet, optional): TileMatrixSet grid definition. Defaults to `WebMercatorQuad`.
"""
tms: TileMatrixSet = attr.ib(default=WEB_MERCATOR_TMS)
bounds: BBox = attr.ib(init=False)
crs: CRS = attr.ib(init=False)
transform: Optional[Affine] = attr.ib(default=None, init=False)
height: Optional[int] = attr.ib(default=None, init=False)
width: Optional[int] = attr.ib(default=None, init=False)
def get_geographic_bounds(self, crs: CRS) -> BBox:
"""Return Geographic Bounds for a Geographic CRS."""
if self.crs == crs:
if self.bounds[1] > self.bounds[3]:
warnings.warn(
"BoundingBox of the dataset is inverted (minLat > maxLat).",
UserWarning,
)
return (
self.bounds[0],
self.bounds[3],
self.bounds[2],
self.bounds[1],
)
return self.bounds
try:
bounds = transform_bounds(self.crs, crs, *self.bounds, densify_pts=21)
except: # noqa
warnings.warn(
"Cannot determine bounds in geographic CRS, will default to (-180.0, -90.0, 180.0, 90.0).",
UserWarning,
)
bounds = (-180.0, -90, 180.0, 90)
if not all(numpy.isfinite(bounds)):
warnings.warn(
"Transformation to geographic CRS returned invalid values, will default to (-180.0, -90.0, 180.0, 90.0).",
UserWarning,
)
bounds = (-180.0, -90, 180.0, 90)
return bounds
@cached_property
def _dst_geom_in_tms_crs(self):
"""Return dataset geom info in TMS projection."""
tms_crs = self.tms.rasterio_crs
if self.crs != tms_crs:
dst_affine, w, h = calculate_default_transform(
self.crs,
tms_crs,
self.width,
self.height,
*self.bounds,
)
else:
dst_affine = list(self.transform)
w = self.width
h = self.height
return dst_affine, w, h
@cached_property
def _minzoom(self) -> int:
"""Calculate dataset minimum zoom level."""
# We assume the TMS tilesize to be constant over all matrices
# ref: https://github.com/OSGeo/gdal/blob/dc38aa64d779ecc45e3cd15b1817b83216cf96b8/gdal/frmts/gtiff/cogdriver.cpp#L274
tilesize = self.tms.tileMatrices[0].tileWidth
if all([self.transform, self.height, self.width]):
try:
dst_affine, w, h = self._dst_geom_in_tms_crs
# The minzoom is defined by the resolution of the maximum theoretical overview level
# We assume `tilesize`` is the smallest overview size
overview_level = get_maximum_overview_level(w, h, minsize=tilesize)
# Get the resolution of the overview
resolution = max(abs(dst_affine[0]), abs(dst_affine[4]))
ovr_resolution = resolution * (2**overview_level)
# Find what TMS matrix match the overview resolution
return self.tms.zoom_for_res(ovr_resolution)
except: # noqa
# if we can't get max zoom from the dataset we default to TMS maxzoom
warnings.warn(
"Cannot determine minzoom based on dataset information, will default to TMS minzoom.",
UserWarning,
)
return self.tms.minzoom
@cached_property
def _maxzoom(self) -> int:
"""Calculate dataset maximum zoom level."""
if all([self.transform, self.height, self.width]):
try:
dst_affine, _, _ = self._dst_geom_in_tms_crs
# The maxzoom is defined by finding the minimum difference between
# the raster resolution and the zoom level resolution
resolution = max(abs(dst_affine[0]), abs(dst_affine[4]))
return self.tms.zoom_for_res(resolution)
except: # noqa
# if we can't get min/max zoom from the dataset we default to TMS maxzoom
warnings.warn(
"Cannot determine maxzoom based on dataset information, will default to TMS maxzoom.",
UserWarning,
)
return self.tms.maxzoom
def tile_exists(self, tile_x: int, tile_y: int, tile_z: int) -> bool:
"""Check if a tile intersects the dataset bounds.
Args:
tile_x (int): Tile's horizontal index.
tile_y (int): Tile's vertical index.
tile_z (int): Tile's zoom level index.
Returns:
bool: True if the tile intersects the dataset bounds.
"""
# bounds in TileMatrixSet's CRS
tile_bounds = self.tms.xy_bounds(Tile(x=tile_x, y=tile_y, z=tile_z))
if not self.tms.rasterio_crs == self.crs:
# Transform the bounds to the dataset's CRS
try:
tile_bounds = transform_bounds(
self.tms.rasterio_crs,
self.crs,
*tile_bounds,
densify_pts=21,
)
except: # noqa
# HACK: gdal will first throw an error for invalid transformation
# but if retried it will then pass.
# Note: It might return `+/-inf` values
tile_bounds = transform_bounds(
self.tms.rasterio_crs,
self.crs,
*tile_bounds,
densify_pts=21,
)
# If tile_bounds has non-finite value in the dataset CRS we return True
if not all(numpy.isfinite(tile_bounds)):
return True
tile_bounds = normalize_bounds(tile_bounds)
dst_bounds = normalize_bounds(self.bounds)
return (
(tile_bounds[0] < dst_bounds[2])
and (tile_bounds[2] > dst_bounds[0])
and (tile_bounds[3] > dst_bounds[1])
and (tile_bounds[1] < dst_bounds[3])
)
@attr.s
class BaseReader(SpatialMixin, metaclass=abc.ABCMeta):
"""Rio-tiler.io BaseReader.
Attributes:
input (any): Reader's input.
tms (morecantile.TileMatrixSet, optional): TileMatrixSet grid definition. Defaults to `WebMercatorQuad`.
"""
input: Any = attr.ib()
tms: TileMatrixSet = attr.ib(default=WEB_MERCATOR_TMS)
def __enter__(self):
"""Support using with Context Managers."""
return self
def __exit__(self, exc_type, exc_value, traceback):
"""Support using with Context Managers."""
pass
@abc.abstractmethod
def info(self) -> Info:
"""Return Dataset's info.
Returns:
rio_tile.models.Info: Dataset info.
"""
...
@abc.abstractmethod
def statistics(self) -> Dict[str, BandStatistics]:
"""Return bands statistics from a dataset.
Returns:
Dict[str, rio_tiler.models.BandStatistics]: bands statistics.
"""
...
@abc.abstractmethod
def tile(self, tile_x: int, tile_y: int, tile_z: int) -> ImageData:
"""Read a Map tile from the Dataset.
Args:
tile_x (int): Tile's horizontal index.
tile_y (int): Tile's vertical index.
tile_z (int): Tile's zoom level index.
Returns:
rio_tiler.models.ImageData: ImageData instance with data, mask and tile spatial info.
"""
...
@abc.abstractmethod
def part(self, bbox: BBox) -> ImageData:
"""Read a Part of a Dataset.
Args:
bbox (tuple): Output bounds (left, bottom, right, top) in target crs.
Returns:
rio_tiler.models.ImageData: ImageData instance with data, mask and input spatial info.
"""
...
@abc.abstractmethod
def preview(self) -> ImageData:
"""Read a preview of a Dataset.
Returns:
rio_tiler.models.ImageData: ImageData instance with data, mask and input spatial info.
"""
...
@abc.abstractmethod
def point(self, lon: float, lat: float) -> PointData:
"""Read a value from a Dataset.
Args:
lon (float): Longitude.
lat (float): Latitude.
Returns:
rio_tiler.models.PointData: PointData instance with data, mask and spatial info.
"""
...
@abc.abstractmethod
def feature(self, shape: Dict) -> ImageData:
"""Read a Dataset for a GeoJSON feature.
Args:
shape (dict): Valid GeoJSON feature.
Returns:
rio_tiler.models.ImageData: ImageData instance with data, mask and input spatial info.
"""
...
@attr.s
class MultiBaseReader(SpatialMixin, metaclass=abc.ABCMeta):
"""MultiBaseReader Reader.
This Abstract Base Class Reader is suited for dataset that are composed of multiple assets (e.g. STAC).
Attributes:
input (any): input data.
tms (morecantile.TileMatrixSet, optional): TileMatrixSet grid definition. Defaults to `WebMercatorQuad`.
minzoom (int, optional): Set dataset's minzoom.
maxzoom (int, optional): Set dataset's maxzoom.
reader_options (dict, option): options to forward to the reader. Defaults to `{}`.
"""
input: Any = attr.ib()
tms: TileMatrixSet = attr.ib(default=WEB_MERCATOR_TMS)
minzoom: int = attr.ib(default=None)
maxzoom: int = attr.ib(default=None)
reader: Type[BaseReader] = attr.ib(init=False)
reader_options: Dict = attr.ib(factory=dict)
assets: Sequence[str] = attr.ib(init=False)
default_assets: Optional[Sequence[str]] = attr.ib(init=False, default=None)
ctx: Type[contextlib.AbstractContextManager] = attr.ib(
init=False, default=contextlib.nullcontext
)
def __enter__(self):
"""Support using with Context Managers."""
return self
def __exit__(self, exc_type, exc_value, traceback):
"""Support using with Context Managers."""
pass
@abc.abstractmethod
def _get_asset_info(self, asset: str) -> AssetInfo:
"""Validate asset name and construct url."""
...
def _get_reader(self, asset_info: AssetInfo) -> Tuple[Type[BaseReader], Dict]:
"""Get Asset Reader and options."""
return self.reader, {}
def parse_expression(self, expression: str, asset_as_band: bool = False) -> Tuple:
"""Parse rio-tiler band math expression."""
input_assets = "|".join(self.assets)
if asset_as_band:
_re = re.compile(rf"\b({input_assets})\b")
else:
_re = re.compile(rf"\b({input_assets})_b\d+\b")
assets = tuple(set(re.findall(_re, expression)))
if not assets:
raise InvalidExpression(
f"Could not find any valid assets in '{expression}' expression. Assets are: {self.assets}"
if asset_as_band
else f"Could not find any valid assets in '{expression}' expression, maybe try with `asset_as_band=True`. Assets are: {self.assets}"
)
return assets
def _update_statistics(
self,
img: ImageData,
indexes: Optional[Indexes] = None,
statistics: Optional[Sequence[Tuple[float, float]]] = None,
):
"""Update ImageData Statistics from AssetInfo."""
indexes = cast_to_sequence(indexes)
if indexes is None:
indexes = tuple(range(1, img.count + 1))
if not img.dataset_statistics and statistics:
if max(max(indexes), len(indexes)) > len(statistics): # type: ignore
return
img.dataset_statistics = [statistics[bidx - 1] for bidx in indexes]
def info(
self,
assets: Optional[Union[Sequence[str], str]] = None,
**kwargs: Any,
) -> Dict[str, Info]:
"""Return metadata from multiple assets.
Args:
assets (sequence of str or str, optional): assets to fetch info from. Required keyword argument.
Returns:
dict: Multiple assets info in form of {"asset1": rio_tile.models.Info}.
"""
if not assets:
warnings.warn(
"No `assets` option passed, will fetch info for all available assets.",
UserWarning,
)
assets = cast_to_sequence(assets or self.assets)
def _reader(asset: str, **kwargs: Any) -> Dict:
asset_info = self._get_asset_info(asset)
reader, options = self._get_reader(asset_info)
with self.ctx(**asset_info.get("env", {})):
with reader(
asset_info["url"],
tms=self.tms,
**{**self.reader_options, **options},
) as src:
return src.info()
return multi_values(assets, _reader, **kwargs)
def statistics(
self,
assets: Optional[Union[Sequence[str], str]] = None,
asset_indexes: Optional[Dict[str, Indexes]] = None,
asset_expression: Optional[Dict[str, str]] = None,
**kwargs: Any,
) -> Dict[str, Dict[str, BandStatistics]]:
"""Return array statistics for multiple assets.
Args:
assets (sequence of str or str): assets to fetch info from.
asset_indexes (dict, optional): Band indexes for each asset (e.g {"asset1": 1, "asset2": (1, 2,)}).
asset_expression (dict, optional): rio-tiler expression for each asset (e.g. {"asset1": "b1/b2+b3", "asset2": ...}).
kwargs (optional): Options to forward to the `self.reader.statistics` method.
Returns:
dict: Multiple assets statistics in form of {"asset1": {"1": rio_tiler.models.BandStatistics, ...}}.
"""
if not assets:
warnings.warn(
"No `assets` option passed, will fetch statistics for all available assets.",
UserWarning,
)
assets = cast_to_sequence(assets or self.assets)
asset_indexes = asset_indexes or {}
asset_expression = asset_expression or {}
def _reader(asset: str, *args: Any, **kwargs: Any) -> Dict:
asset_info = self._get_asset_info(asset)
reader, options = self._get_reader(asset_info)
with self.ctx(**asset_info.get("env", {})):
with reader(
asset_info["url"],
tms=self.tms,
**{**self.reader_options, **options},
) as src:
return src.statistics(
*args,
indexes=asset_indexes.get(asset, kwargs.pop("indexes", None)),
expression=asset_expression.get(asset),
**kwargs,
)
return multi_values(assets, _reader, **kwargs)
def merged_statistics(
self,
assets: Optional[Union[Sequence[str], str]] = None,
expression: Optional[str] = None,
asset_indexes: Optional[Dict[str, Indexes]] = None,
categorical: bool = False,
categories: Optional[List[float]] = None,
percentiles: Optional[List[int]] = None,
hist_options: Optional[Dict] = None,
max_size: int = 1024,
**kwargs: Any,
) -> Dict[str, BandStatistics]:
"""Return array statistics for multiple assets.
Args:
assets (sequence of str or str): assets to fetch info from.
expression (str, optional): rio-tiler expression for the asset list (e.g. asset1/asset2+asset3).
asset_indexes (dict, optional): Band indexes for each asset (e.g {"asset1": 1, "asset2": (1, 2,)}).
categorical (bool): treat input data as categorical data. Defaults to False.
categories (list of numbers, optional): list of categories to return value for.
percentiles (list of numbers, optional): list of percentile values to calculate. Defaults to `[2, 98]`.
hist_options (dict, optional): Options to forward to numpy.histogram function.
max_size (int, optional): Limit the size of the longest dimension of the dataset read, respecting bounds X/Y aspect ratio. Defaults to 1024.
kwargs (optional): Options to forward to the `self.preview` method.
Returns:
Dict[str, rio_tiler.models.BandStatistics]: bands statistics.
"""
if not expression:
if not assets:
warnings.warn(
"No `assets` option passed, will fetch statistics for all available assets.",
UserWarning,
)
assets = cast_to_sequence(assets or self.assets)
data = self.preview(
assets=assets,
expression=expression,
asset_indexes=asset_indexes,
max_size=max_size,
**kwargs,
)
return data.statistics(
categorical=categorical,
categories=categories,
percentiles=percentiles,
hist_options=hist_options,
)
def tile(
self,
tile_x: int,
tile_y: int,
tile_z: int,
assets: Optional[Union[Sequence[str], str]] = None,
expression: Optional[str] = None,
asset_indexes: Optional[Dict[str, Indexes]] = None,
asset_as_band: bool = False,
**kwargs: Any,
) -> ImageData:
"""Read and merge Wep Map tiles from multiple assets.
Args:
tile_x (int): Tile's horizontal index.
tile_y (int): Tile's vertical index.
tile_z (int): Tile's zoom level index.
assets (sequence of str or str, optional): assets to fetch info from.
expression (str, optional): rio-tiler expression for the asset list (e.g. asset1/asset2+asset3).
asset_indexes (dict, optional): Band indexes for each asset (e.g {"asset1": 1, "asset2": (1, 2,)}).
kwargs (optional): Options to forward to the `self.reader.tile` method.
Returns:
rio_tiler.models.ImageData: ImageData instance with data, mask and tile spatial info.
"""
if not self.tile_exists(tile_x, tile_y, tile_z):
raise TileOutsideBounds(
f"Tile(x={tile_x}, y={tile_y}, z={tile_z}) is outside bounds"
)
assets = cast_to_sequence(assets)
if assets and expression:
warnings.warn(
"Both expression and assets passed; expression will overwrite assets parameter.",
ExpressionMixingWarning,
)
if expression:
assets = self.parse_expression(expression, asset_as_band=asset_as_band)
if not assets and self.default_assets:
warnings.warn(
f"No assets/expression passed, defaults to {self.default_assets}",
UserWarning,
)
assets = self.default_assets
if not assets:
raise MissingAssets(
"assets must be passed via `expression` or `assets` options, or via class-level `default_assets`."
)
asset_indexes = asset_indexes or {}
# We fall back to `indexes` if provided
indexes = kwargs.pop("indexes", None)
def _reader(asset: str, *args: Any, **kwargs: Any) -> ImageData:
idx = asset_indexes.get(asset) or indexes
asset_info = self._get_asset_info(asset)
reader, options = self._get_reader(asset_info)
with self.ctx(**asset_info.get("env", {})):
with reader(
asset_info["url"],
tms=self.tms,
**{**self.reader_options, **options},
) as src:
data = src.tile(*args, indexes=idx, **kwargs)
self._update_statistics(
data,
indexes=idx,
statistics=asset_info.get("dataset_statistics"),
)
metadata = data.metadata or {}
if m := asset_info.get("metadata"):
metadata.update(m)
data.metadata = {asset: metadata}
if asset_as_band:
if len(data.band_names) > 1:
raise AssetAsBandError(
"Can't use `asset_as_band` for multibands asset"
)
data.band_names = [asset]
else:
data.band_names = [f"{asset}_{n}" for n in data.band_names]
return data
img = multi_arrays(assets, _reader, tile_x, tile_y, tile_z, **kwargs)
if expression:
return img.apply_expression(expression)
return img
def part(
self,
bbox: BBox,
assets: Optional[Union[Sequence[str], str]] = None,
expression: Optional[str] = None,
asset_indexes: Optional[Dict[str, Indexes]] = None,
asset_as_band: bool = False,
**kwargs: Any,
) -> ImageData:
"""Read and merge parts from multiple assets.
Args:
bbox (tuple): Output bounds (left, bottom, right, top) in target crs.
assets (sequence of str or str, optional): assets to fetch info from.
expression (str, optional): rio-tiler expression for the asset list (e.g. asset1/asset2+asset3).
asset_indexes (dict, optional): Band indexes for each asset (e.g {"asset1": 1, "asset2": (1, 2,)}).
kwargs (optional): Options to forward to the `self.reader.part` method.
Returns:
rio_tiler.models.ImageData: ImageData instance with data, mask and tile spatial info.
"""
assets = cast_to_sequence(assets)
if assets and expression:
warnings.warn(
"Both expression and assets passed; expression will overwrite assets parameter.",
ExpressionMixingWarning,
)
if expression:
assets = self.parse_expression(expression, asset_as_band=asset_as_band)
if not assets and self.default_assets:
warnings.warn(
f"No assets/expression passed, defaults to {self.default_assets}",
UserWarning,
)
assets = self.default_assets
if not assets:
raise MissingAssets(
"assets must be passed via `expression` or `assets` options, or via class-level `default_assets`."
)
asset_indexes = asset_indexes or {}
# We fall back to `indexes` if provided
indexes = kwargs.pop("indexes", None)
def _reader(asset: str, *args: Any, **kwargs: Any) -> ImageData:
idx = asset_indexes.get(asset) or indexes
asset_info = self._get_asset_info(asset)
reader, options = self._get_reader(asset_info)
with self.ctx(**asset_info.get("env", {})):
with reader(
asset_info["url"],
tms=self.tms,
**{**self.reader_options, **options},
) as src:
data = src.part(*args, indexes=idx, **kwargs)
self._update_statistics(
data,
indexes=idx,
statistics=asset_info.get("dataset_statistics"),
)
metadata = data.metadata or {}
if m := asset_info.get("metadata"):
metadata.update(m)
data.metadata = {asset: metadata}
if asset_as_band:
if len(data.band_names) > 1:
raise AssetAsBandError(
"Can't use `asset_as_band` for multibands asset"
)
data.band_names = [asset]
else:
data.band_names = [f"{asset}_{n}" for n in data.band_names]
return data
img = multi_arrays(assets, _reader, bbox, **kwargs)
if expression:
return img.apply_expression(expression)
return img
def preview(
self,
assets: Optional[Union[Sequence[str], str]] = None,
expression: Optional[str] = None,
asset_indexes: Optional[Dict[str, Indexes]] = None,
asset_as_band: bool = False,
**kwargs: Any,
) -> ImageData:
"""Read and merge previews from multiple assets.
Args:
assets (sequence of str or str, optional): assets to fetch info from.
expression (str, optional): rio-tiler expression for the asset list (e.g. asset1/asset2+asset3).
asset_indexes (dict, optional): Band indexes for each asset (e.g {"asset1": 1, "asset2": (1, 2,)}).
kwargs (optional): Options to forward to the `self.reader.preview` method.
Returns:
rio_tiler.models.ImageData: ImageData instance with data, mask and tile spatial info.
"""
assets = cast_to_sequence(assets)
if assets and expression:
warnings.warn(
"Both expression and assets passed; expression will overwrite assets parameter.",
ExpressionMixingWarning,
)
if expression:
assets = self.parse_expression(expression, asset_as_band=asset_as_band)
if not assets and self.default_assets:
warnings.warn(
f"No assets/expression passed, defaults to {self.default_assets}",
UserWarning,
)
assets = self.default_assets
if not assets:
raise MissingAssets(
"assets must be passed via `expression` or `assets` options, or via class-level `default_assets`."
)
asset_indexes = asset_indexes or {}
# We fall back to `indexes` if provided
indexes = kwargs.pop("indexes", None)
def _reader(asset: str, **kwargs: Any) -> ImageData:
idx = asset_indexes.get(asset) or indexes
asset_info = self._get_asset_info(asset)
reader, options = self._get_reader(asset_info)
with self.ctx(**asset_info.get("env", {})):
with reader(
asset_info["url"],
tms=self.tms,
**{**self.reader_options, **options},
) as src:
data = src.preview(indexes=idx, **kwargs)
self._update_statistics(
data,
indexes=idx,
statistics=asset_info.get("dataset_statistics"),
)
metadata = data.metadata or {}
if m := asset_info.get("metadata"):
metadata.update(m)
data.metadata = {asset: metadata}
if asset_as_band:
if len(data.band_names) > 1:
raise AssetAsBandError(
"Can't use `asset_as_band` for multibands asset"
)
data.band_names = [asset]
else:
data.band_names = [f"{asset}_{n}" for n in data.band_names]
return data
img = multi_arrays(assets, _reader, **kwargs)
if expression:
return img.apply_expression(expression)
return img
def point(
self,
lon: float,
lat: float,
assets: Optional[Union[Sequence[str], str]] = None,
expression: Optional[str] = None,
asset_indexes: Optional[Dict[str, Indexes]] = None,
asset_as_band: bool = False,
**kwargs: Any,
) -> PointData:
"""Read pixel value from multiple assets.
Args:
lon (float): Longitude.
lat (float): Latitude.
assets (sequence of str or str, optional): assets to fetch info from.
expression (str, optional): rio-tiler expression for the asset list (e.g. asset1/asset2+asset3).
asset_indexes (dict, optional): Band indexes for each asset (e.g {"asset1": 1, "asset2": (1, 2,)}).
kwargs (optional): Options to forward to the `self.reader.point` method.
Returns:
PointData
"""
assets = cast_to_sequence(assets)
if assets and expression:
warnings.warn(
"Both expression and assets passed; expression will overwrite assets parameter.",
ExpressionMixingWarning,
)
if expression:
assets = self.parse_expression(expression, asset_as_band=asset_as_band)
if not assets and self.default_assets:
warnings.warn(
f"No assets/expression passed, defaults to {self.default_assets}",
UserWarning,
)
assets = self.default_assets
if not assets:
raise MissingAssets(
"assets must be passed via `expression` or `assets` options, or via class-level `default_assets`."
)
asset_indexes = asset_indexes or {}
# We fall back to `indexes` if provided
indexes = kwargs.pop("indexes", None)
def _reader(asset: str, *args: Any, **kwargs: Any) -> PointData:
idx = asset_indexes.get(asset) or indexes
asset_info = self._get_asset_info(asset)
reader, options = self._get_reader(asset_info)
with self.ctx(**asset_info.get("env", {})):
with reader(
asset_info["url"],
tms=self.tms,
**{**self.reader_options, **options},
) as src:
data = src.point(*args, indexes=idx, **kwargs)
metadata = data.metadata or {}
if m := asset_info.get("metadata"):
metadata.update(m)
data.metadata = {asset: metadata}
if asset_as_band:
if len(data.band_names) > 1:
raise AssetAsBandError(
"Can't use `asset_as_band` for multibands asset"
)
data.band_names = [asset]
else:
data.band_names = [f"{asset}_{n}" for n in data.band_names]
return data
data = multi_points(assets, _reader, lon, lat, **kwargs)
if expression:
return data.apply_expression(expression)
return data
def feature(
self,
shape: Dict,
assets: Optional[Union[Sequence[str], str]] = None,
expression: Optional[str] = None,
asset_indexes: Optional[Dict[str, Indexes]] = None,
asset_as_band: bool = False,
**kwargs: Any,
) -> ImageData:
"""Read and merge parts defined by geojson feature from multiple assets.
Args:
shape (dict): Valid GeoJSON feature.
assets (sequence of str or str, optional): assets to fetch info from.
expression (str, optional): rio-tiler expression for the asset list (e.g. asset1/asset2+asset3).
asset_indexes (dict, optional): Band indexes for each asset (e.g {"asset1": 1, "asset2": (1, 2,)}).
kwargs (optional): Options to forward to the `self.reader.feature` method.
Returns:
rio_tiler.models.ImageData: ImageData instance with data, mask and tile spatial info.
"""
assets = cast_to_sequence(assets)
if assets and expression:
warnings.warn(
"Both expression and assets passed; expression will overwrite assets parameter.",
ExpressionMixingWarning,
)
if expression:
assets = self.parse_expression(expression, asset_as_band=asset_as_band)
if not assets and self.default_assets:
warnings.warn(
f"No assets/expression passed, defaults to {self.default_assets}",
UserWarning,
)
assets = self.default_assets
if not assets:
raise MissingAssets(
"assets must be passed via `expression` or `assets` options, or via class-level `default_assets`."
)
asset_indexes = asset_indexes or {}
# We fall back to `indexes` if provided
indexes = kwargs.pop("indexes", None)
def _reader(asset: str, *args: Any, **kwargs: Any) -> ImageData:
idx = asset_indexes.get(asset) or indexes
asset_info = self._get_asset_info(asset)
reader, options = self._get_reader(asset_info)
with self.ctx(**asset_info.get("env", {})):
with reader(
asset_info["url"],
tms=self.tms,
**{**self.reader_options, **options},
) as src:
data = src.feature(*args, indexes=idx, **kwargs)
self._update_statistics(
data,
indexes=idx,
statistics=asset_info.get("dataset_statistics"),
)
metadata = data.metadata or {}
if m := asset_info.get("metadata"):
metadata.update(m)
data.metadata = {asset: metadata}
if asset_as_band:
if len(data.band_names) > 1:
raise AssetAsBandError(
"Can't use `asset_as_band` for multibands asset"
)
data.band_names = [asset]
else:
data.band_names = [f"{asset}_{n}" for n in data.band_names]
return data
img = multi_arrays(assets, _reader, shape, **kwargs)
if expression:
return img.apply_expression(expression)
return img
@attr.s
class MultiBandReader(SpatialMixin, metaclass=abc.ABCMeta):
"""Multi Band Reader.
This Abstract Base Class Reader is suited for dataset that stores spectral bands as separate files (e.g. Sentinel 2).
Attributes:
input (any): input data.