Skip to content

API documentation

Bases: NDArrayOperatorsMixin

Source code in src/rasterra/_array.py
 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
class RasterArray(np.lib.mixins.NDArrayOperatorsMixin):
    def __init__(
        self,
        data: RasterData,
        transform: Affine = _IDENTITY_TRANSFORM,
        crs: RawCRS | None = None,
        no_data_value: SupportedDtypes | None = NO_DATA_UNSET,
    ):
        """
        Initialize a RasterArray.

        Parameters
        ----------
        data
            2D NumPy array representing raster data.
        transform
            Affine transform to georeference the raster.
        crs
            Coordinate reference system.
        no_data_value
            Value representing no data.

        """
        self._ndarray = data
        self._transform = transform
        if crs is not None and not isinstance(crs, CRS):
            crs = CRS.from_user_input(crs)
        self._crs: CRS | None = crs
        self._no_data_value = no_data_value

    # ----------------------------------------------------------------
    # Array data

    @property
    def flags(self) -> flagsobj:
        """Flags of the raster."""
        return self._ndarray.flags

    @property
    def shape(self) -> tuple[int, ...]:
        """Shape of the raster."""
        return self._ndarray.shape  # type: ignore[no-any-return]

    @property
    def strides(self) -> tuple[int, ...]:
        """Strides of the raster."""
        return self._ndarray.strides

    @property
    def ndim(self) -> int:
        """Number of dimensions of the raster."""
        return 2

    @property
    def data(self) -> memoryview:
        """Python buffer object pooint to the start of the raster's data."""
        return self._ndarray.data

    @property
    def size(self) -> int:
        """Number of elements in the raster."""
        return self._ndarray.size

    @property
    def itemsize(self) -> int:
        """Size of each element in the raster."""
        return self._ndarray.itemsize

    @property
    def nbytes(self) -> int:
        """Number of bytes in the raster."""
        return self._ndarray.nbytes

    @property
    def base(self) -> RasterData | None:
        """Base object of the raster."""
        return self._ndarray.base

    @property
    def dtype(self) -> np.dtype[DataDtypes]:
        """Data type of the raster."""
        return self._ndarray.dtype

    @property
    def T(self) -> typing.NoReturn:  # noqa: N802
        """Transpose of the raster."""
        msg = "Transpose of a raster is not defined."
        raise TypeError(msg)

    @property
    def real(self) -> typing.NoReturn:
        """Real part of the raster."""
        msg = "Complex raster data is not supported."
        raise NotImplementedError(msg)

    @property
    def imag(self) -> typing.NoReturn:
        """Imaginary part of the raster."""
        msg = "Complex raster data is not supported."
        raise NotImplementedError(msg)

    @property
    def flat(self) -> np.flatiter:  # type: ignore[type-arg]
        """Flat iterator of the raster."""
        return self._ndarray.flat

    @property
    def ctypes(self) -> typing.NoReturn:
        """ctypes object of the raster."""
        msg = "ctypes object of a raster is not defined."
        raise TypeError(msg)

    def __getitem__(self, item: int | slice | tuple[int, int] | tuple[slice, slice]):  # type: ignore[no-untyped-def]
        def _process_item(_item: int | slice) -> int | slice:
            if isinstance(_item, int):
                return _item
            elif isinstance(_item, slice):
                if _item.step is not None:
                    msg = "Slicing with a step is not supported."
                    raise ValueError(msg)
                return _item.start or 0
            else:
                msg = "Invalid index type"
                raise TypeError(msg)

        new_data = self._ndarray[item]
        if not isinstance(new_data, np.ndarray):
            return new_data

        if isinstance(item, tuple):
            if len(item) != 2:  # noqa: PLR2004
                msg = "Invalid number of indices"
                raise ValueError(msg)
            y_item, x_item = item

            yi = _process_item(y_item)
            xi = _process_item(x_item)
        else:
            yi = _process_item(item)
            xi = 0

        new_transform = Affine(
            self._transform.a,
            self._transform.b,
            self._transform.c + xi * self._transform.a,
            self._transform.d,
            self._transform.e,
            self._transform.f + yi * self._transform.e,
        )

        return RasterArray(new_data, new_transform, self._crs, self._no_data_value)

    # ----------------------------------------------------------------
    # NumPy array interface

    def astype(self, dtype: type[DataDtypes]) -> "RasterArray":
        """Cast the raster to a new data type."""
        return RasterArray(
            self._ndarray.astype(dtype), self._transform, self._crs, self._no_data_value
        )

    def to_numpy(self) -> RasterData:
        """Convert the raster to a NumPy array."""
        return self._ndarray.copy()

    def __array__(self, dtype: type[DataDtypes] | None = None) -> RasterData:
        return np.asarray(self._ndarray, dtype=dtype)

    def __array_ufunc__(  # noqa: C901
        self,
        ufunc: np.ufunc,
        method: NumpyUFuncMethod,
        *inputs: typing.Union[RasterData, SupportedDtypes, "RasterArray"],
        **kwargs: typing.Any,
    ) -> typing.Union[tuple["RasterArray", ...], "RasterArray"]:
        out = kwargs.get("out", ())
        for x in inputs + out:
            # Only support operations with instances of _HANDLED_TYPES.
            # Use RasterArray instead of type(self) for isinstance to
            # allow subclasses that don't override __array_ufunc__ to
            # handle RasterArray objects.
            handled_types = (np.ndarray, numbers.Number, RasterArray)
            if not isinstance(x, handled_types):
                return NotImplemented
            if isinstance(x, RasterArray):
                if x._crs != self._crs:  # noqa: SLF001
                    msg = "Coordinate reference systems do not match."
                    raise ValueError(msg)
                if not self._no_data_equal(x._no_data_value):  # noqa: SLF001
                    msg = "No data values do not match."
                    raise ValueError(msg)
                if x._transform != self._transform:  # noqa: SLF001
                    msg = "Affine transforms do not match."
                    raise ValueError(msg)

        # Propagate the no_data_value to the output array.
        no_data_mask = self.no_data_mask
        for x in inputs:
            if isinstance(x, RasterArray):
                no_data_mask |= x.no_data_mask

        # Defer to the implementation of the ufunc on unwrapped values.
        inputs = tuple(x._ndarray if isinstance(x, RasterArray) else x for x in inputs)  # noqa: SLF001
        if out:
            kwargs["out"] = tuple(
                x._ndarray if isinstance(x, RasterArray) else x  # noqa: SLF001
                for x in out
            )
        result = getattr(ufunc, method)(*inputs, **kwargs)
        result[no_data_mask] = self._no_data_value

        if type(result) is tuple:
            # multiple return values
            return tuple(
                type(self)(x, self._transform, self._crs, self._no_data_value)
                for x in result
            )
        else:
            # one return value
            return type(self)(result, self._transform, self._crs, self._no_data_value)

    # ----------------------------------------------------------------
    # Specialized array methods

    def all(self) -> bool:
        """Return True if all elements evaluate to True."""
        return self._ndarray.all()  # type: ignore[return-value]

    def any(self) -> bool:
        """Return True if any element evaluates to True."""
        return self._ndarray.any()  # type: ignore[return-value]

    # ----------------------------------------------------------------
    # Raster data

    @property
    def transform(self) -> Affine:
        """Affine transform to georeference the raster."""
        return self._transform

    @property
    def x_min(self) -> float:
        """Minimum x coordinate."""
        return self.transform.c  # type: ignore[no-any-return]

    @property
    def x_max(self) -> float:
        """Maximum x coordinate."""
        return self.x_min + self.x_resolution * self.width

    @property
    def y_min(self) -> float:
        """Minimum y coordinate."""
        return self.y_max + self.y_resolution * self.height

    @property
    def y_max(self) -> float:
        """Maximum y coordinate."""
        return self.transform.f  # type: ignore[no-any-return]

    @property
    def width(self) -> int:
        """Width of the raster."""
        return self._ndarray.shape[1]  # type: ignore[no-any-return]

    @property
    def height(self) -> int:
        """Height of the raster."""
        return self._ndarray.shape[0]  # type: ignore[no-any-return]

    @property
    def x_resolution(self) -> float:
        """Resolution in x direction."""
        return self.transform.a  # type: ignore[no-any-return]

    @property
    def y_resolution(self) -> float:
        """Resolution in y direction."""
        return self.transform.e  # type: ignore[no-any-return]

    @property
    def resolution(self) -> tuple[float, float]:
        """Resolution in x and y directions."""
        return self.x_resolution, self.y_resolution

    def x_coordinates(self, *, center: bool = False) -> npt.NDArray[np.float64]:
        """x coordinates of the raster."""
        if center:
            return np.linspace(
                self.x_min + self.x_resolution / 2,
                self.x_max - self.x_resolution / 2,
                self.width,
            )
        else:
            return np.linspace(
                self.x_min,
                self.x_max - self.x_resolution,
                self.width,
            )

    def y_coordinates(self, *, center: bool = False) -> npt.NDArray[np.float64]:
        """y coordinates of the raster."""
        if center:
            return np.linspace(
                self.y_min - self.y_resolution / 2,
                self.y_max + self.y_resolution / 2,
                self.height,
            )
        else:
            return np.linspace(
                self.y_min - self.y_resolution,
                self.y_max,
                self.height,
            )

    @property
    def bounds(self) -> tuple[float, float, float, float]:
        """Bounding box of the raster."""
        return self.x_min, self.x_max, self.y_min, self.y_max

    @property
    def crs(self) -> str | None:
        """Coordinate reference system."""
        if isinstance(self._crs, CRS):
            return self._crs.to_string()  # type: ignore[no-any-return]
        else:
            return self._crs

    def set_crs(self, new_crs: RawCRS) -> "RasterArray":
        if self._crs is not None:
            msg = (
                "Coordinate reference system is already set. Use to_crs() to reproject "
                "to a new coordinate reference system."
            )
            raise ValueError(msg)
        return RasterArray(
            self._ndarray.copy(), self._transform, new_crs, self._no_data_value
        )

    def to_crs(self, new_crs: str, resampling: str = "nearest") -> "RasterArray":
        """Reproject the raster to a new coordinate reference system."""
        if self._crs is None:
            msg = "Coordinate reference system is not set."
            raise ValueError(msg)
        return self.reproject(
            dst_crs=new_crs,
            resampling=resampling,
        )

    @property
    def no_data_value(self) -> SupportedDtypes:
        """Value representing no data."""
        if self._no_data_value is NO_DATA_UNSET:
            msg = "No data value is not set."
            raise ValueError(msg)
        return self._no_data_value

    def set_no_data_value(self, new_no_data_value: SupportedDtypes) -> "RasterArray":
        new_data = self._ndarray.copy()
        if self._no_data_value is not NO_DATA_UNSET:
            new_data[self.no_data_mask] = new_no_data_value
        return RasterArray(new_data, self._transform, self._crs, new_no_data_value)

    def _no_data_equal(self, other_no_data_value: SupportedDtypes | None) -> bool:
        if self._no_data_value is NO_DATA_UNSET:
            return other_no_data_value is NO_DATA_UNSET
        elif other_no_data_value is NO_DATA_UNSET:
            return False
        elif np.isnan(self._no_data_value):
            return np.isnan(other_no_data_value)  # type: ignore[no-any-return]
        elif np.isinf(self._no_data_value):
            other_inf = np.isinf(other_no_data_value)
            sign_match = np.sign(self._no_data_value) == np.sign(other_no_data_value)
            return other_inf and sign_match  # type: ignore[no-any-return]
        else:
            return self._no_data_value == other_no_data_value

    def unset_no_data_value(self) -> "RasterArray":
        """Unset value representing no data."""
        return RasterArray(
            self._ndarray.copy(), self._transform, self._crs, NO_DATA_UNSET
        )

    @property
    def no_data_mask(self) -> RasterMask:
        """Mask representing no data."""
        if self._no_data_value is NO_DATA_UNSET:
            return np.zeros_like(self._ndarray, dtype=bool)
        elif np.isnan(self._no_data_value):
            return np.isnan(self._ndarray)
        elif np.isinf(self._no_data_value):
            return np.isinf(self._ndarray)
        else:
            return np.equal(self._ndarray, self._no_data_value)

    def resample(self, scale: float, resampling: str = "nearest") -> "RasterArray":
        """Resample the raster."""
        dest_width = int(self.width * scale)
        dest_height = int(self.height * scale)
        destination = np.empty((dest_height, dest_width), dtype=self._ndarray.dtype)
        return self.reproject(
            destination=destination,
            dst_crs=self._crs,
            resampling=resampling,
        )

    def resample_to(
        self, target: "RasterArray", resampling: str = "nearest"
    ) -> "RasterArray":
        """Resample the raster to match the resolution of another raster."""
        destination = np.empty_like(target._ndarray, dtype=self._ndarray.dtype)  # noqa: SLF001
        return self.reproject(
            destination=destination,
            dst_transform=target.transform,
            dst_crs=target._crs,  # noqa: SLF001
            resampling=resampling,
        )

    def reproject(
        self,
        destination: RasterData | None = None,
        dst_transform: Affine | None = None,
        dst_resolution: float | tuple[float, float] | None = None,
        dst_crs: RawCRS | None = None,
        resampling: str = "nearest",
    ) -> "RasterArray":
        """Reproject the raster to match the resolution of another raster."""
        resampling = _RESAMPLING_MAP[resampling]

        dst_crs = self._crs if dst_crs is None else CRS.from_user_input(dst_crs)
        new_data, transform = reproject(
            source=self._ndarray,
            src_transform=self._transform,
            src_crs=self._crs,
            src_nodata=self._no_data_value,
            destination=destination,
            dst_transform=dst_transform,
            dst_resolution=dst_resolution,
            dst_crs=dst_crs,
            resampling=resampling,
        )
        if len(new_data.shape) == 3:  # noqa: PLR2004
            # Some operations assume and prepend a channel dimension
            new_data = new_data[0]
        return RasterArray(
            new_data,
            transform,
            dst_crs,
            self.no_data_value,
        )

    def _coerce_to_shapely(
        self, shape: Polygon | MultiPolygon | gpd.GeoDataFrame | gpd.GeoSeries
    ) -> Polygon | MultiPolygon:
        if isinstance(shape, (gpd.GeoDataFrame, gpd.GeoSeries)):
            if shape.crs != self._crs:
                msg = "Coordinate reference systems do not match."
                raise ValueError(msg)
            return shape.geometry.unary_union
        return shape

    def clip(
        self, shape: Polygon | MultiPolygon | gpd.GeoDataFrame | gpd.GeoSeries
    ) -> "RasterArray":
        """Clip the raster to a shape."""
        shape = self._coerce_to_shapely(shape)
        _, transform, window = raster_geometry_mask(
            data_transform=self.transform,
            data_width=self._ndarray.shape[1],
            data_height=self._ndarray.shape[0],
            shapes=[shape],
            crop=True,
        )

        x_start, x_end = window.col_off, window.col_off + window.width
        y_start, y_end = window.row_off, window.row_off + window.height
        new_data = self._ndarray[y_start:y_end, x_start:x_end].copy()
        return RasterArray(
            new_data, transform, self._crs, no_data_value=self.no_data_value
        )

    def mask(
        self,
        shape: Polygon | MultiPolygon | gpd.GeoDataFrame | gpd.GeoSeries,
        *,
        fill_value: SupportedDtypes | None = None,
        all_touched: bool = False,
        invert: bool = False,
    ) -> "RasterArray":
        """Mask the raster with a shape."""
        shape = self._coerce_to_shapely(shape)
        if fill_value is None and self._no_data_value is NO_DATA_UNSET:
            msg = "No fill value is set."
            raise ValueError(msg)

        if fill_value is None:
            fill_value = self.no_data_value

        shape_mask, *_ = raster_geometry_mask(
            data_transform=self.transform,
            data_width=self._ndarray.shape[1],
            data_height=self._ndarray.shape[0],
            shapes=[shape],
            all_touched=all_touched,
            invert=invert,
        )
        new_data = self._ndarray.copy()
        new_data[shape_mask] = fill_value

        return RasterArray(
            new_data, self.transform, self._crs, no_data_value=self.no_data_value
        )

    def select(
        self,
        x_coordinates: npt.NDArray[np.float64],
        y_coordinates: npt.NDArray[np.float64],
        method: str = "nearest",
    ) -> npt.NDArray[DataDtypes]:
        """Select values at specific coordinates."""
        if x_coordinates.size != y_coordinates.size:
            msg = "x and y coordinates must have the same size."
            raise ValueError(msg)

        if method == "nearest":
            x_indices = np.clip(
                np.searchsorted(self.x_coordinates(), x_coordinates),
                0,
                self.width - 1,
            )
            y_indices = np.searchsorted(
                self.y_coordinates(), y_coordinates, side="right"
            )
            # Flip y indices to match raster coordinatesok
            y_indices = np.clip(
                self.height - y_indices,
                0,
                self.height - 1,
            )

            return self._ndarray[y_indices, x_indices].copy()
        else:
            msg = "Only 'nearest' method is supported."
            raise NotImplementedError(msg)

    def __repr__(self) -> str:
        out = "RasterArray\n"
        out += "===========\n"
        out += f"dimensions    : {self.width}, {self.height} (x, y)\n"
        out += f"resolution    : {self.transform.a}, {self.transform.e} (x, y)\n"
        bounds = ", ".join(
            str(s) for s in [self.x_min, self.x_max, self.y_min, self.y_max]
        )
        out += f"extent        : {bounds} (xmin, xmax, ymin, ymax)\n"
        out += f"crs           : {self.crs}\n"
        out += f"no_data_value : {self._no_data_value}\n"
        out += f"size          : {self.nbytes / 1024 ** 2:.2f} MB\n"
        out += f"dtype         : {self._ndarray.dtype}\n"
        return out

    def to_file(self, path: FilePath, **kwargs: typing.Any) -> None:
        """Write the raster to a file."""
        from rasterra._io import write_raster

        write_raster(self, path, **kwargs)

    def to_gdf(self) -> gpd.GeoDataFrame:
        return to_gdf(self)

    @property
    def plot(self) -> Plotter:
        return Plotter(self._ndarray, self.no_data_mask, self.transform)

T: typing.NoReturn property

Transpose of the raster.

base: RasterData | None property

Base object of the raster.

bounds: tuple[float, float, float, float] property

Bounding box of the raster.

crs: str | None property

Coordinate reference system.

ctypes: typing.NoReturn property

ctypes object of the raster.

data: memoryview property

Python buffer object pooint to the start of the raster's data.

dtype: np.dtype[DataDtypes] property

Data type of the raster.

flags: flagsobj property

Flags of the raster.

flat: np.flatiter property

Flat iterator of the raster.

height: int property

Height of the raster.

imag: typing.NoReturn property

Imaginary part of the raster.

itemsize: int property

Size of each element in the raster.

nbytes: int property

Number of bytes in the raster.

ndim: int property

Number of dimensions of the raster.

no_data_mask: RasterMask property

Mask representing no data.

no_data_value: SupportedDtypes property

Value representing no data.

real: typing.NoReturn property

Real part of the raster.

resolution: tuple[float, float] property

Resolution in x and y directions.

shape: tuple[int, ...] property

Shape of the raster.

size: int property

Number of elements in the raster.

strides: tuple[int, ...] property

Strides of the raster.

transform: Affine property

Affine transform to georeference the raster.

width: int property

Width of the raster.

x_max: float property

Maximum x coordinate.

x_min: float property

Minimum x coordinate.

x_resolution: float property

Resolution in x direction.

y_max: float property

Maximum y coordinate.

y_min: float property

Minimum y coordinate.

y_resolution: float property

Resolution in y direction.

__init__(data: RasterData, transform: Affine = _IDENTITY_TRANSFORM, crs: RawCRS | None = None, no_data_value: SupportedDtypes | None = NO_DATA_UNSET)

Initialize a RasterArray.

Parameters

data 2D NumPy array representing raster data. transform Affine transform to georeference the raster. crs Coordinate reference system. no_data_value Value representing no data.

Source code in src/rasterra/_array.py
def __init__(
    self,
    data: RasterData,
    transform: Affine = _IDENTITY_TRANSFORM,
    crs: RawCRS | None = None,
    no_data_value: SupportedDtypes | None = NO_DATA_UNSET,
):
    """
    Initialize a RasterArray.

    Parameters
    ----------
    data
        2D NumPy array representing raster data.
    transform
        Affine transform to georeference the raster.
    crs
        Coordinate reference system.
    no_data_value
        Value representing no data.

    """
    self._ndarray = data
    self._transform = transform
    if crs is not None and not isinstance(crs, CRS):
        crs = CRS.from_user_input(crs)
    self._crs: CRS | None = crs
    self._no_data_value = no_data_value

all() -> bool

Return True if all elements evaluate to True.

Source code in src/rasterra/_array.py
def all(self) -> bool:
    """Return True if all elements evaluate to True."""
    return self._ndarray.all()  # type: ignore[return-value]

any() -> bool

Return True if any element evaluates to True.

Source code in src/rasterra/_array.py
def any(self) -> bool:
    """Return True if any element evaluates to True."""
    return self._ndarray.any()  # type: ignore[return-value]

astype(dtype: type[DataDtypes]) -> RasterArray

Cast the raster to a new data type.

Source code in src/rasterra/_array.py
def astype(self, dtype: type[DataDtypes]) -> "RasterArray":
    """Cast the raster to a new data type."""
    return RasterArray(
        self._ndarray.astype(dtype), self._transform, self._crs, self._no_data_value
    )

clip(shape: Polygon | MultiPolygon | gpd.GeoDataFrame | gpd.GeoSeries) -> RasterArray

Clip the raster to a shape.

Source code in src/rasterra/_array.py
def clip(
    self, shape: Polygon | MultiPolygon | gpd.GeoDataFrame | gpd.GeoSeries
) -> "RasterArray":
    """Clip the raster to a shape."""
    shape = self._coerce_to_shapely(shape)
    _, transform, window = raster_geometry_mask(
        data_transform=self.transform,
        data_width=self._ndarray.shape[1],
        data_height=self._ndarray.shape[0],
        shapes=[shape],
        crop=True,
    )

    x_start, x_end = window.col_off, window.col_off + window.width
    y_start, y_end = window.row_off, window.row_off + window.height
    new_data = self._ndarray[y_start:y_end, x_start:x_end].copy()
    return RasterArray(
        new_data, transform, self._crs, no_data_value=self.no_data_value
    )

mask(shape: Polygon | MultiPolygon | gpd.GeoDataFrame | gpd.GeoSeries, *, fill_value: SupportedDtypes | None = None, all_touched: bool = False, invert: bool = False) -> RasterArray

Mask the raster with a shape.

Source code in src/rasterra/_array.py
def mask(
    self,
    shape: Polygon | MultiPolygon | gpd.GeoDataFrame | gpd.GeoSeries,
    *,
    fill_value: SupportedDtypes | None = None,
    all_touched: bool = False,
    invert: bool = False,
) -> "RasterArray":
    """Mask the raster with a shape."""
    shape = self._coerce_to_shapely(shape)
    if fill_value is None and self._no_data_value is NO_DATA_UNSET:
        msg = "No fill value is set."
        raise ValueError(msg)

    if fill_value is None:
        fill_value = self.no_data_value

    shape_mask, *_ = raster_geometry_mask(
        data_transform=self.transform,
        data_width=self._ndarray.shape[1],
        data_height=self._ndarray.shape[0],
        shapes=[shape],
        all_touched=all_touched,
        invert=invert,
    )
    new_data = self._ndarray.copy()
    new_data[shape_mask] = fill_value

    return RasterArray(
        new_data, self.transform, self._crs, no_data_value=self.no_data_value
    )

reproject(destination: RasterData | None = None, dst_transform: Affine | None = None, dst_resolution: float | tuple[float, float] | None = None, dst_crs: RawCRS | None = None, resampling: str = 'nearest') -> RasterArray

Reproject the raster to match the resolution of another raster.

Source code in src/rasterra/_array.py
def reproject(
    self,
    destination: RasterData | None = None,
    dst_transform: Affine | None = None,
    dst_resolution: float | tuple[float, float] | None = None,
    dst_crs: RawCRS | None = None,
    resampling: str = "nearest",
) -> "RasterArray":
    """Reproject the raster to match the resolution of another raster."""
    resampling = _RESAMPLING_MAP[resampling]

    dst_crs = self._crs if dst_crs is None else CRS.from_user_input(dst_crs)
    new_data, transform = reproject(
        source=self._ndarray,
        src_transform=self._transform,
        src_crs=self._crs,
        src_nodata=self._no_data_value,
        destination=destination,
        dst_transform=dst_transform,
        dst_resolution=dst_resolution,
        dst_crs=dst_crs,
        resampling=resampling,
    )
    if len(new_data.shape) == 3:  # noqa: PLR2004
        # Some operations assume and prepend a channel dimension
        new_data = new_data[0]
    return RasterArray(
        new_data,
        transform,
        dst_crs,
        self.no_data_value,
    )

resample(scale: float, resampling: str = 'nearest') -> RasterArray

Resample the raster.

Source code in src/rasterra/_array.py
def resample(self, scale: float, resampling: str = "nearest") -> "RasterArray":
    """Resample the raster."""
    dest_width = int(self.width * scale)
    dest_height = int(self.height * scale)
    destination = np.empty((dest_height, dest_width), dtype=self._ndarray.dtype)
    return self.reproject(
        destination=destination,
        dst_crs=self._crs,
        resampling=resampling,
    )

resample_to(target: RasterArray, resampling: str = 'nearest') -> RasterArray

Resample the raster to match the resolution of another raster.

Source code in src/rasterra/_array.py
def resample_to(
    self, target: "RasterArray", resampling: str = "nearest"
) -> "RasterArray":
    """Resample the raster to match the resolution of another raster."""
    destination = np.empty_like(target._ndarray, dtype=self._ndarray.dtype)  # noqa: SLF001
    return self.reproject(
        destination=destination,
        dst_transform=target.transform,
        dst_crs=target._crs,  # noqa: SLF001
        resampling=resampling,
    )

select(x_coordinates: npt.NDArray[np.float64], y_coordinates: npt.NDArray[np.float64], method: str = 'nearest') -> npt.NDArray[DataDtypes]

Select values at specific coordinates.

Source code in src/rasterra/_array.py
def select(
    self,
    x_coordinates: npt.NDArray[np.float64],
    y_coordinates: npt.NDArray[np.float64],
    method: str = "nearest",
) -> npt.NDArray[DataDtypes]:
    """Select values at specific coordinates."""
    if x_coordinates.size != y_coordinates.size:
        msg = "x and y coordinates must have the same size."
        raise ValueError(msg)

    if method == "nearest":
        x_indices = np.clip(
            np.searchsorted(self.x_coordinates(), x_coordinates),
            0,
            self.width - 1,
        )
        y_indices = np.searchsorted(
            self.y_coordinates(), y_coordinates, side="right"
        )
        # Flip y indices to match raster coordinatesok
        y_indices = np.clip(
            self.height - y_indices,
            0,
            self.height - 1,
        )

        return self._ndarray[y_indices, x_indices].copy()
    else:
        msg = "Only 'nearest' method is supported."
        raise NotImplementedError(msg)

to_crs(new_crs: str, resampling: str = 'nearest') -> RasterArray

Reproject the raster to a new coordinate reference system.

Source code in src/rasterra/_array.py
def to_crs(self, new_crs: str, resampling: str = "nearest") -> "RasterArray":
    """Reproject the raster to a new coordinate reference system."""
    if self._crs is None:
        msg = "Coordinate reference system is not set."
        raise ValueError(msg)
    return self.reproject(
        dst_crs=new_crs,
        resampling=resampling,
    )

to_file(path: FilePath, **kwargs: typing.Any) -> None

Write the raster to a file.

Source code in src/rasterra/_array.py
def to_file(self, path: FilePath, **kwargs: typing.Any) -> None:
    """Write the raster to a file."""
    from rasterra._io import write_raster

    write_raster(self, path, **kwargs)

to_numpy() -> RasterData

Convert the raster to a NumPy array.

Source code in src/rasterra/_array.py
def to_numpy(self) -> RasterData:
    """Convert the raster to a NumPy array."""
    return self._ndarray.copy()

unset_no_data_value() -> RasterArray

Unset value representing no data.

Source code in src/rasterra/_array.py
def unset_no_data_value(self) -> "RasterArray":
    """Unset value representing no data."""
    return RasterArray(
        self._ndarray.copy(), self._transform, self._crs, NO_DATA_UNSET
    )

x_coordinates(*, center: bool = False) -> npt.NDArray[np.float64]

x coordinates of the raster.

Source code in src/rasterra/_array.py
def x_coordinates(self, *, center: bool = False) -> npt.NDArray[np.float64]:
    """x coordinates of the raster."""
    if center:
        return np.linspace(
            self.x_min + self.x_resolution / 2,
            self.x_max - self.x_resolution / 2,
            self.width,
        )
    else:
        return np.linspace(
            self.x_min,
            self.x_max - self.x_resolution,
            self.width,
        )

y_coordinates(*, center: bool = False) -> npt.NDArray[np.float64]

y coordinates of the raster.

Source code in src/rasterra/_array.py
def y_coordinates(self, *, center: bool = False) -> npt.NDArray[np.float64]:
    """y coordinates of the raster."""
    if center:
        return np.linspace(
            self.y_min - self.y_resolution / 2,
            self.y_max + self.y_resolution / 2,
            self.height,
        )
    else:
        return np.linspace(
            self.y_min - self.y_resolution,
            self.y_max,
            self.height,
        )

Load a raster from a file.

Source code in src/rasterra/_io.py
def load_raster(
    path: FilePath,
    bounds: Bounds | None = None,
) -> RasterArray:
    """Load a raster from a file."""

    with rasterio.open(path) as f:
        if bounds is not None:
            if isinstance(bounds, Polygon):
                bounds = bounds.bounds
            window = from_bounds(*bounds, transform=f.transform)
            data = f.read(window=window, boundless=True)
            transform = f.window_transform(window)
        else:
            data = f.read()
            transform = f.transform

        if data.shape[0] == 1:
            return RasterArray(
                data[0],
                transform=transform,
                crs=f.crs,
                no_data_value=f.nodata,
            )
        else:
            msg = "Only single-band rasters are supported"
            raise NotImplementedError(msg)

Load multiple files into a single raster.

Source code in src/rasterra/_io.py
def load_mf_raster(paths: Sequence[FilePath]) -> RasterArray:
    """Load multiple files into a single raster."""
    with rasterio.open(paths[0]) as f:
        data = f.read()
        if data.shape[0] == 1:
            merged, transform = merge(paths)
            return RasterArray(
                merged[0],
                transform=transform,
                crs=f.crs,
                no_data_value=f.nodata,
            )
        else:
            msg = "Only single-band rasters are supported."
            raise NotImplementedError(msg)