Skip to content

dependencies

titiler.core.dependencies

Common dependency.

AssetsBidxExprParams dataclass

Bases: AssetsParams, BidxParams

Assets, Expression and Asset's band Indexes parameters.

Source code in titiler/core/dependencies.py
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
@dataclass
class AssetsBidxExprParams(AssetsParams, BidxParams):
    """Assets, Expression and Asset's band Indexes parameters."""

    expression: Annotated[
        Optional[str],
        Query(
            title="Band Math expression",
            description="Band math expression between assets",
            openapi_examples={
                "simple": {
                    "description": "Return results of expression between assets.",
                    "value": "asset1_b1 + asset2_b1 / asset3_b1",
                },
            },
        ),
    ] = None

    asset_indexes: Annotated[
        Optional[Sequence[str]],
        Query(
            title="Per asset band indexes",
            description="Per asset band indexes (coma separated indexes)",
            alias="asset_bidx",
            openapi_examples={
                "one-asset": {
                    "description": "Return indexes 1,2,3 of asset `data`.",
                    "value": ["data|1,2,3"],
                },
                "multi-assets": {
                    "description": "Return indexes 1,2,3 of asset `data` and indexes 1 of asset `cog`",
                    "value": ["data|1,2,3", "cog|1"],
                },
            },
        ),
    ] = None

    asset_as_band: Annotated[
        Optional[bool],
        Query(
            title="Consider asset as a 1 band dataset",
            description="Asset as Band",
        ),
    ] = None

    def __post_init__(self):
        """Post Init."""
        if not self.assets and not self.expression:
            raise MissingAssets(
                "assets must be defined either via expression or assets options."
            )

        if self.asset_indexes:
            self.asset_indexes = parse_asset_indexes(self.asset_indexes)

        if self.asset_indexes and self.indexes:
            warnings.warn(
                "Both `asset_bidx` and `bidx` passed; only `asset_bidx` will be considered.",
                UserWarning,
            )

AssetsBidxExprParamsOptional dataclass

Bases: AssetsBidxExprParams

Assets, Expression and Asset's band Indexes parameters but with no requirement.

Source code in titiler/core/dependencies.py
239
240
241
242
243
244
245
246
247
248
249
250
251
252
@dataclass
class AssetsBidxExprParamsOptional(AssetsBidxExprParams):
    """Assets, Expression and Asset's band Indexes parameters but with no requirement."""

    def __post_init__(self):
        """Post Init."""
        if self.asset_indexes:
            self.asset_indexes = parse_asset_indexes(self.asset_indexes)

        if self.asset_indexes and self.indexes:
            warnings.warn(
                "Both `asset_bidx` and `bidx` passed; only `asset_bidx` will be considered.",
                UserWarning,
            )

AssetsBidxParams dataclass

Bases: AssetsParams, BidxParams

Assets, Asset's band Indexes and Asset's band Expression parameters.

Source code in titiler/core/dependencies.py
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
@dataclass
class AssetsBidxParams(AssetsParams, BidxParams):
    """Assets, Asset's band Indexes and Asset's band Expression parameters."""

    asset_indexes: Annotated[
        Optional[Sequence[str]],
        Query(
            title="Per asset band indexes",
            description="Per asset band indexes",
            alias="asset_bidx",
            openapi_examples={
                "one-asset": {
                    "description": "Return indexes 1,2,3 of asset `data`.",
                    "value": ["data|1;2;3"],
                },
                "multi-assets": {
                    "description": "Return indexes 1,2,3 of asset `data` and indexes 1 of asset `cog`",
                    "value": ["data|1;2;3", "cog|1"],
                },
            },
        ),
    ] = None

    asset_expression: Annotated[
        Optional[Sequence[str]],
        Query(
            title="Per asset band expression",
            description="Per asset band expression",
            openapi_examples={
                "one-asset": {
                    "description": "Return results for expression `b1*b2+b3` of asset `data`.",
                    "value": ["data|b1*b2+b3"],
                },
                "multi-assets": {
                    "description": "Return results for expressions `b1*b2+b3` for asset `data` and `b1+b3` for asset `cog`.",
                    "value": ["data|b1*b2+b3", "cog|b1+b3"],
                },
            },
        ),
    ] = None

    def __post_init__(self):
        """Post Init."""
        if self.asset_indexes:
            self.asset_indexes = parse_asset_indexes(self.asset_indexes)

        if self.asset_expression:
            self.asset_expression = parse_asset_expression(self.asset_expression)

        if self.asset_indexes and self.indexes:
            warnings.warn(
                "Both `asset_bidx` and `bidx` passed; only `asset_bidx` will be considered.",
                UserWarning,
            )

AssetsParams dataclass

Bases: DefaultDependency

Assets parameters.

Source code in titiler/core/dependencies.py
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
@dataclass
class AssetsParams(DefaultDependency):
    """Assets parameters."""

    assets: Annotated[
        Optional[List[str]],
        Query(
            title="Asset names",
            description="Asset's names.",
            openapi_examples={
                "one-asset": {
                    "description": "Return results for asset `data`.",
                    "value": ["data"],
                },
                "multi-assets": {
                    "description": "Return results for assets `data` and `cog`.",
                    "value": ["data", "cog"],
                },
            },
        ),
    ] = None

BandsExprParams dataclass

Bases: ExpressionParams, BandsParams

Band names and Expression parameters (Band or Expression required).

Source code in titiler/core/dependencies.py
342
343
344
345
346
347
348
349
350
351
@dataclass
class BandsExprParams(ExpressionParams, BandsParams):
    """Band names and Expression parameters (Band or Expression required)."""

    def __post_init__(self):
        """Post Init."""
        if not self.bands and not self.expression:
            raise MissingBands(
                "bands must be defined either via expression or bands options."
            )

BandsExprParamsOptional dataclass

Bases: ExpressionParams, BandsParams

Optional Band names and Expression parameters.

Source code in titiler/core/dependencies.py
335
336
337
338
339
@dataclass
class BandsExprParamsOptional(ExpressionParams, BandsParams):
    """Optional Band names and Expression parameters."""

    pass

BandsParams dataclass

Bases: DefaultDependency

Band names parameters.

Source code in titiler/core/dependencies.py
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
@dataclass
class BandsParams(DefaultDependency):
    """Band names parameters."""

    bands: Annotated[
        Optional[List[str]],
        Query(
            title="Band names",
            description="Band's names.",
            openapi_examples={
                "one-band": {
                    "description": "Return results for band `B01`.",
                    "value": ["B01"],
                },
                "multi-bands": {
                    "description": "Return results for bands `B01` and `B02`.",
                    "value": ["B01", "B02"],
                },
            },
        ),
    ] = None

BidxExprParams dataclass

Bases: ExpressionParams, BidxParams

Band Indexes and Expression parameters.

Source code in titiler/core/dependencies.py
129
130
131
132
133
@dataclass
class BidxExprParams(ExpressionParams, BidxParams):
    """Band Indexes and Expression parameters."""

    pass

BidxParams dataclass

Bases: DefaultDependency

Band Indexes parameters.

Source code in titiler/core/dependencies.py
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
@dataclass
class BidxParams(DefaultDependency):
    """Band Indexes parameters."""

    indexes: Annotated[
        Optional[List[int]],
        Query(
            title="Band indexes",
            alias="bidx",
            description="Dataset band indexes",
            openapi_examples={
                "one-band": {"value": [1]},
                "multi-bands": {"value": [1, 2, 3]},
            },
        ),
    ] = None

DatasetParams dataclass

Bases: DefaultDependency

Low level WarpedVRT Optional parameters.

Source code in titiler/core/dependencies.py
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
@dataclass
class DatasetParams(DefaultDependency):
    """Low level WarpedVRT Optional parameters."""

    nodata: Annotated[
        Optional[Union[str, int, float]],
        Query(
            title="Nodata value",
            description="Overwrite internal Nodata value",
        ),
    ] = None
    unscale: Annotated[
        Optional[bool],
        Query(
            title="Apply internal Scale/Offset",
            description="Apply internal Scale/Offset. Defaults to `False`.",
        ),
    ] = None
    resampling_method: Annotated[
        Optional[RIOResampling],
        Query(
            alias="resampling",
            description="RasterIO resampling algorithm. Defaults to `nearest`.",
        ),
    ] = None
    reproject_method: Annotated[
        Optional[WarpResampling],
        Query(
            alias="reproject",
            description="WarpKernel resampling algorithm (only used when doing re-projection). Defaults to `nearest`.",
        ),
    ] = None

    def __post_init__(self):
        """Post Init."""
        if self.nodata is not None:
            self.nodata = numpy.nan if self.nodata == "nan" else float(self.nodata)

        if self.unscale is not None:
            self.unscale = bool(self.unscale)

DefaultDependency dataclass

Dataclass with dict unpacking

Source code in titiler/core/dependencies.py
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
@dataclass
class DefaultDependency:
    """Dataclass with dict unpacking"""

    def keys(self):
        """Return Keys."""
        warnings.warn(
            "Dict unpacking will be removed for `DefaultDependency` in titiler 0.19.0",
            DeprecationWarning,
        )
        return self.__dict__.keys()

    def __getitem__(self, key):
        """Return value."""
        return self.__dict__[key]

    def as_dict(self, exclude_none: bool = True) -> Dict:
        """Transform dataclass to dict."""
        if exclude_none:
            return {k: v for k, v in self.__dict__.items() if v is not None}

        return dict(self.__dict__.items())

__getitem__

__getitem__(key)

Return value.

Source code in titiler/core/dependencies.py
78
79
80
def __getitem__(self, key):
    """Return value."""
    return self.__dict__[key]

as_dict

as_dict(exclude_none: bool = True) -> Dict

Transform dataclass to dict.

Source code in titiler/core/dependencies.py
82
83
84
85
86
87
def as_dict(self, exclude_none: bool = True) -> Dict:
    """Transform dataclass to dict."""
    if exclude_none:
        return {k: v for k, v in self.__dict__.items() if v is not None}

    return dict(self.__dict__.items())

keys

keys()

Return Keys.

Source code in titiler/core/dependencies.py
70
71
72
73
74
75
76
def keys(self):
    """Return Keys."""
    warnings.warn(
        "Dict unpacking will be removed for `DefaultDependency` in titiler 0.19.0",
        DeprecationWarning,
    )
    return self.__dict__.keys()

ExpressionParams dataclass

Bases: DefaultDependency

Expression parameters.

Source code in titiler/core/dependencies.py
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
@dataclass
class ExpressionParams(DefaultDependency):
    """Expression parameters."""

    expression: Annotated[
        Optional[str],
        Query(
            title="Band Math expression",
            description="rio-tiler's band math expression",
            openapi_examples={
                "simple": {"description": "Simple band math.", "value": "b1/b2"},
                "multi-bands": {
                    "description": "Semicolon (;) delimited expressions (band1: b1/b2, band2: b2+b3).",
                    "value": "b1/b2;b2+b3",
                },
            },
        ),
    ] = None

HistogramParams dataclass

Bases: DefaultDependency

Numpy Histogram options.

Source code in titiler/core/dependencies.py
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
@dataclass
class HistogramParams(DefaultDependency):
    """Numpy Histogram options."""

    bins: Annotated[
        Optional[str],
        Query(
            alias="histogram_bins",
            title="Histogram bins.",
            description="""
Defines the number of equal-width bins in the given range (10, by default).

If bins is a sequence (comma `,` delimited values), it defines a monotonically increasing array of bin edges, including the rightmost edge, allowing for non-uniform bin widths.

link: https://numpy.org/doc/stable/reference/generated/numpy.histogram.html
            """,
            openapi_examples={
                "simple": {
                    "description": "Defines the number of equal-width bins",
                    "value": 8,
                },
                "array": {
                    "description": "Defines custom bin edges (comma `,` delimited values)",
                    "value": "0,100,200,300",
                },
            },
        ),
    ] = None

    range: Annotated[
        Optional[str],
        Query(
            alias="histogram_range",
            title="Histogram range",
            description="""
Comma `,` delimited range of the bins.

The lower and upper range of the bins. If not provided, range is simply (a.min(), a.max()).

Values outside the range are ignored. The first element of the range must be less than or equal to the second.
range affects the automatic bin computation as well.

link: https://numpy.org/doc/stable/reference/generated/numpy.histogram.html
            """,
            examples="0,1000",
        ),
    ] = None

    def __post_init__(self):
        """Post Init."""
        if self.bins:
            bins = self.bins.split(",")
            if len(bins) == 1:
                self.bins = int(bins[0])  # type: ignore
            else:
                self.bins = list(map(float, bins))  # type: ignore
        else:
            self.bins = 10

        if self.range:
            parsed = list(map(float, self.range.split(",")))
            assert (
                len(parsed) == 2
            ), f"Invalid histogram_range values: {self.range}, should be of form 'min,max'"

            self.range = parsed  # type: ignore

ImageRenderingParams dataclass

Bases: DefaultDependency

Image Rendering options.

Source code in titiler/core/dependencies.py
424
425
426
427
428
429
430
431
432
433
434
@dataclass
class ImageRenderingParams(DefaultDependency):
    """Image Rendering options."""

    add_mask: Annotated[
        Optional[bool],
        Query(
            alias="return_mask",
            description="Add mask to the output data. Defaults to `True`",
        ),
    ] = None

PartFeatureParams dataclass

Bases: DefaultDependency

Common parameters for bbox and feature.

Source code in titiler/core/dependencies.py
368
369
370
371
372
373
374
375
376
377
378
379
@dataclass
class PartFeatureParams(DefaultDependency):
    """Common parameters for bbox and feature."""

    max_size: Annotated[Optional[int], "Maximum image size to read onto."] = None
    height: Annotated[Optional[int], "Force output image height."] = None
    width: Annotated[Optional[int], "Force output image width."] = None

    def __post_init__(self):
        """Post Init."""
        if self.width and self.height:
            self.max_size = None

PreviewParams dataclass

Bases: DefaultDependency

Common Preview parameters.

Source code in titiler/core/dependencies.py
354
355
356
357
358
359
360
361
362
363
364
365
@dataclass
class PreviewParams(DefaultDependency):
    """Common Preview parameters."""

    max_size: Annotated[int, "Maximum image size to read onto."] = 1024
    height: Annotated[Optional[int], "Force output image height."] = None
    width: Annotated[Optional[int], "Force output image width."] = None

    def __post_init__(self):
        """Post Init."""
        if self.width and self.height:
            self.max_size = None

StatisticsParams dataclass

Bases: DefaultDependency

Statistics options.

Source code in titiler/core/dependencies.py
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
@dataclass
class StatisticsParams(DefaultDependency):
    """Statistics options."""

    categorical: Annotated[
        Optional[bool],
        Query(
            description="Return statistics for categorical dataset. Defaults to `False`"
        ),
    ] = None
    categories: Annotated[
        Optional[List[Union[float, int]]],
        Query(
            alias="c",
            title="Pixels values for categories.",
            description="List of values for which to report counts.",
            examples=[1, 2, 3],
        ),
    ] = None
    percentiles: Annotated[
        Optional[List[int]],
        Query(
            alias="p",
            title="Percentile values",
            description="List of percentile values (default to [2, 98]).",
            examples=[2, 5, 95, 98],
        ),
    ] = None

    def __post_init__(self):
        """Set percentiles default."""
        if not self.percentiles:
            self.percentiles = [2, 98]

TileParams dataclass

Bases: DefaultDependency

Tile options.

Source code in titiler/core/dependencies.py
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
@dataclass
class TileParams(DefaultDependency):
    """Tile options."""

    buffer: Annotated[
        Optional[float],
        Query(
            gt=0,
            title="Tile buffer.",
            description="Buffer on each side of the given tile. It must be a multiple of `0.5`. Output **tilesize** will be expanded to `tilesize + 2 * buffer` (e.g 0.5 = 257x257, 1.0 = 258x258).",
        ),
    ] = None

    padding: Annotated[
        Optional[int],
        Query(
            gt=0,
            title="Tile padding.",
            description="Padding to apply to each tile edge. Helps reduce resampling artefacts along edges. Defaults to `0`.",
        ),
    ] = None

BufferParams

BufferParams(
    buffer: Annotated[
        Optional[float],
        Query(
            gt=0,
            title="Tile buffer.",
            description="Buffer on each side of the given tile. It must be a multiple of `0.5`. Output **tilesize** will be expanded to `tilesize + 2 * buffer` (e.g 0.5 = 257x257, 1.0 = 258x258).",
        ),
    ] = None
) -> Optional[float]

Tile buffer Parameter.

Source code in titiler/core/dependencies.py
605
606
607
608
609
610
611
612
613
614
615
616
def BufferParams(
    buffer: Annotated[
        Optional[float],
        Query(
            gt=0,
            title="Tile buffer.",
            description="Buffer on each side of the given tile. It must be a multiple of `0.5`. Output **tilesize** will be expanded to `tilesize + 2 * buffer` (e.g 0.5 = 257x257, 1.0 = 258x258).",
        ),
    ] = None,
) -> Optional[float]:
    """Tile buffer Parameter."""
    return buffer

ColorFormulaParams

ColorFormulaParams(
    color_formula: Annotated[
        Optional[str],
        Query(
            title="Color Formula",
            description="rio-color formula (info: https://github.com/mapbox/rio-color)",
        ),
    ] = None
) -> Optional[str]

ColorFormula Parameter.

Source code in titiler/core/dependencies.py
619
620
621
622
623
624
625
626
627
628
629
def ColorFormulaParams(
    color_formula: Annotated[
        Optional[str],
        Query(
            title="Color Formula",
            description="rio-color formula (info: https://github.com/mapbox/rio-color)",
        ),
    ] = None,
) -> Optional[str]:
    """ColorFormula Parameter."""
    return color_formula

CoordCRSParams

CoordCRSParams(
    crs: Annotated[
        Optional[str],
        Query(
            alias=coord_crs,
            description="Coordinate Reference System of the input coords. Default to `epsg:4326`.",
        ),
    ] = None
) -> Optional[CRS]

Coordinate Reference System Coordinates Param.

Source code in titiler/core/dependencies.py
573
574
575
576
577
578
579
580
581
582
583
584
585
586
def CoordCRSParams(
    crs: Annotated[
        Optional[str],
        Query(
            alias="coord_crs",
            description="Coordinate Reference System of the input coords. Default to `epsg:4326`.",
        ),
    ] = None,
) -> Optional[CRS]:
    """Coordinate Reference System Coordinates Param."""
    if crs:
        return CRS.from_user_input(crs)

    return None

DatasetPathParams

DatasetPathParams(url: Annotated[str, Query(description='Dataset URL')]) -> str

Create dataset path from args

Source code in titiler/core/dependencies.py
61
62
63
def DatasetPathParams(url: Annotated[str, Query(description="Dataset URL")]) -> str:
    """Create dataset path from args"""
    return url

DstCRSParams

DstCRSParams(
    crs: Annotated[
        Optional[str], Query(alias=dst_crs, description="Output Coordinate Reference System.")
    ] = None
) -> Optional[CRS]

Coordinate Reference System Coordinates Param.

Source code in titiler/core/dependencies.py
589
590
591
592
593
594
595
596
597
598
599
600
601
602
def DstCRSParams(
    crs: Annotated[
        Optional[str],
        Query(
            alias="dst_crs",
            description="Output Coordinate Reference System.",
        ),
    ] = None,
) -> Optional[CRS]:
    """Coordinate Reference System Coordinates Param."""
    if crs:
        return CRS.from_user_input(crs)

    return None

RescalingParams

RescalingParams(
    rescale: Annotated[
        Optional[List[str]],
        Query(
            title="Min/Max data Rescaling",
            description="comma (',') delimited Min,Max range. Can set multiple time for multiple bands.",
            examples=[(0, 2000), (0, 1000), (0, 10000)],
        ),
    ] = None
) -> Optional[RescaleType]

Min/Max data Rescaling

Source code in titiler/core/dependencies.py
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
def RescalingParams(
    rescale: Annotated[
        Optional[List[str]],
        Query(
            title="Min/Max data Rescaling",
            description="comma (',') delimited Min,Max range. Can set multiple time for multiple bands.",
            examples=["0,2000", "0,1000", "0,10000"],  # band 1  # band 2  # band 3
        ),
    ] = None,
) -> Optional[RescaleType]:
    """Min/Max data Rescaling"""
    if rescale:
        rescale_array = []
        for r in rescale:
            parsed = tuple(
                map(
                    float,
                    r.replace(" ", "").replace("[", "").replace("]", "").split(","),
                )
            )
            assert (
                len(parsed) == 2
            ), f"Invalid rescale values: {rescale}, should be of form ['min,max', 'min,max'] or [[min,max], [min, max]]"
            rescale_array.append(parsed)

        return rescale_array

    return None

create_colormap_dependency

create_colormap_dependency(cmap: ColorMaps) -> Callable

Create Colormap Dependency.

Source code in titiler/core/dependencies.py
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
def create_colormap_dependency(cmap: ColorMaps) -> Callable:
    """Create Colormap Dependency."""

    def deps(
        colormap_name: Annotated[  # type: ignore
            Literal[tuple(cmap.list())],
            Query(description="Colormap name"),
        ] = None,
        colormap: Annotated[
            Optional[str], Query(description="JSON encoded custom Colormap")
        ] = None,
    ):
        if colormap_name:
            return cmap.get(colormap_name)

        if colormap:
            try:
                c = json.loads(
                    colormap,
                    object_hook=lambda x: {
                        int(k): parse_color(v) for k, v in x.items()
                    },
                )

                # Make sure to match colormap type
                if isinstance(c, Sequence):
                    c = [(tuple(inter), parse_color(v)) for (inter, v) in c]

                return c
            except json.JSONDecodeError as e:
                raise HTTPException(
                    status_code=400, detail="Could not parse the colormap value."
                ) from e

        return None

    return deps

parse_asset_expression

parse_asset_expression(asset_expression: Union[Sequence[str], Dict[str, str]]) -> Dict[str, str]

parse asset expression parameters.

Source code in titiler/core/dependencies.py
170
171
172
173
174
def parse_asset_expression(
    asset_expression: Union[Sequence[str], Dict[str, str]],
) -> Dict[str, str]:
    """parse asset expression parameters."""
    return {idx.split("|")[0]: idx.split("|")[1] for idx in asset_expression}

parse_asset_indexes

parse_asset_indexes(
    asset_indexes: Union[Sequence[str], Dict[str, Sequence[int]]]
) -> Dict[str, Sequence[int]]

parse asset indexes parameters.

Source code in titiler/core/dependencies.py
160
161
162
163
164
165
166
167
def parse_asset_indexes(
    asset_indexes: Union[Sequence[str], Dict[str, Sequence[int]]],
) -> Dict[str, Sequence[int]]:
    """parse asset indexes parameters."""
    return {
        idx.split("|")[0]: list(map(int, idx.split("|")[1].split(",")))
        for idx in asset_indexes
    }