Skip to content

API reference

GeoArray

The grid carrier: a NumPy or JAX array with its stored dims, coordinates, transform, CRS, fill value and attrs. The coordinates are on their own page, the readable types on theirs.

geoarray.GeoArray dataclass

A georeferenced array whose data is a NumPy or a JAX array.

Every axis has a name (dims); the last two are ("y", "x"). The first transform.ndim - 1 dims are batch dims, one transform row per item (patches, or frames with their own grids). Non-spatial dims may have a coordinate in coords (geoarray.coords: band names and wavelengths, level values, time stamps).

Parameters:

Name Type Description Default
data Any

(..., y, x) array, numpy.ndarray or jax.Array.

required
transform Any

The affine transform (a, b, c, d, e, f): an affine.Affine, six numbers, or a (6,) (or (*batch, 6)) array. Stored as float64 on the data's backend.

required
crs CRS | None

Anything pyproj.CRS.from_user_input accepts, or None.

required
fill_value _FillValue

The nodata marker (NaN allowed); None means none.

None
attrs FrozenAttrs

Whole-carrier metadata, frozen into a hashable FrozenAttrs.

FrozenAttrs()
dims tuple[str, ...]

One name per axis, ending in ("y", "x"), as a tuple or a space-separated string ("band y x"). Omitted, they are read from the rank (DIMS[-ndim:]) with a DeprecationWarning.

cast(Any, None)
coords tuple[Coordinate, ...]

Coordinates of non-spatial dims, at most one per dim, each with one entry per index of its dim.

()

Raises:

Type Description
TypeError

data is neither a NumPy nor a JAX array, or a coords entry is not a coordinate.

ValueError

dims do not fit the data (wrong count, repeated, not ending in y x), a coordinate has the wrong size, or transform / crs cannot be parsed.

X64Error

JAX data without jax_enable_x64.

Example

import numpy as np from geoarray.coords import SpectralAxis swir = SpectralAxis(names=("B11", "B12"), wavelength_nm=(1610.0, 2190.0)) scene = GeoArray( ... np.zeros((2, 600, 600), dtype=np.float32), ... (20.0, 0.0, 600000.0, 0.0, -20.0, 3550000.0), ... "EPSG:32613", ... fill_value=np.nan, ... dims=("band", "y", "x"), ... coords=(swir,), ... ) scene.dims, scene.res (('band', 'y', 'x'), (20.0, 20.0)) scene.sel(band="B12").dims ('y', 'x')

Source code in packages/geotoolz-array/src/geoarray/_src/array.py
 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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
@dataclasses.dataclass(frozen=True, eq=False, repr=False)
class GeoArray:
    """A georeferenced array whose data is a NumPy or a JAX array.

    Every axis has a name (``dims``); the last two are ``("y", "x")``. The
    first ``transform.ndim - 1`` dims are batch dims, one transform row per
    item (patches, or frames with their own grids). Non-spatial dims may
    have a coordinate in ``coords`` (`geoarray.coords`: band names and
    wavelengths, level values, time stamps).

    Args:
        data: ``(..., y, x)`` array, ``numpy.ndarray`` or ``jax.Array``.
        transform: The affine transform (a, b, c, d, e, f): an
            ``affine.Affine``, six numbers, or a ``(6,)`` (or ``(*batch, 6)``)
            array. Stored as float64 on the data's backend.
        crs: Anything ``pyproj.CRS.from_user_input`` accepts, or ``None``.
        fill_value: The nodata marker (NaN allowed); ``None`` means none.
        attrs: Whole-carrier metadata, frozen into a hashable `FrozenAttrs`.
        dims: One name per axis, ending in ``("y", "x")``, as a tuple or a
            space-separated string (``"band y x"``). Omitted, they are read
            from the rank (``DIMS[-ndim:]``) with a ``DeprecationWarning``.
        coords: Coordinates of non-spatial dims, at most one per dim, each
            with one entry per index of its dim.

    Raises:
        TypeError: ``data`` is neither a NumPy nor a JAX array, or a
            ``coords`` entry is not a coordinate.
        ValueError: ``dims`` do not fit the data (wrong count, repeated,
            not ending in ``y x``), a coordinate has the wrong size, or
            ``transform`` / ``crs`` cannot be parsed.
        X64Error: JAX data without ``jax_enable_x64``.

    Example:
        >>> import numpy as np
        >>> from geoarray.coords import SpectralAxis
        >>> swir = SpectralAxis(names=("B11", "B12"), wavelength_nm=(1610.0, 2190.0))
        >>> scene = GeoArray(
        ...     np.zeros((2, 600, 600), dtype=np.float32),
        ...     (20.0, 0.0, 600000.0, 0.0, -20.0, 3550000.0),
        ...     "EPSG:32613",
        ...     fill_value=np.nan,
        ...     dims=("band", "y", "x"),
        ...     coords=(swir,),
        ... )
        >>> scene.dims, scene.res
        (('band', 'y', 'x'), (20.0, 20.0))
        >>> scene.sel(band="B12").dims
        ('y', 'x')
    """

    data: Any
    transform: Any
    crs: pyproj.CRS | None
    fill_value: _FillValue = None
    attrs: FrozenAttrs = dataclasses.field(default_factory=FrozenAttrs)
    # None reads the dims from the rank (deprecated); stored as a tuple
    dims: tuple[str, ...] = dataclasses.field(default=cast(Any, None), kw_only=True)
    coords: tuple[Coordinate, ...] = dataclasses.field(default=(), kw_only=True)

    def __class_getitem__(cls, item: Any) -> Any:
        """``GeoArray["band y x"]``: the carrier annotated with a dims pattern.

        An ``Annotated`` type carrying a `geoarray.types.ReadableType`, which
        `geoarray.types.check_dims` checks. The 0.2 array-type parameter
        (``GeoArray[np.ndarray]``) is deprecated and returns the class.
        """
        return _subscript(cls, item)

    def __post_init__(self) -> None:
        backend = backend_of(self.data)
        transform = _coerce_transform(self.transform, backend)
        batch = tuple(transform.shape[:-1])
        data_shape = tuple(self.data.shape)
        if data_shape[: len(batch)] != batch:
            raise ValueError(
                f"a batched transform {tuple(transform.shape)} needs data with the "
                f"same leading batch shape {batch}, got data {data_shape}"
            )
        if self.dims is None:
            if not 2 <= len(data_shape) - len(batch) <= 4:
                raise ValueError(
                    f"a GeoArray is 2-D to 4-D with dims {DIMS}[-ndim:], got shape "
                    f"{data_shape}"
                    + (f" with batch shape {batch}" if batch else "")
                    + "; pass dims= for any other layout"
                )
            dims = infer_dims(len(data_shape), len(batch))
            warnings.warn(
                _INFER_WARNING.format(dims=dims), DeprecationWarning, stacklevel=3
            )
        else:
            dims = _check_dims(self.dims, data_shape, len(batch))
        object.__setattr__(self, "dims", dims)
        coords = _check_coords(self.coords, dims, data_shape)
        coords = _promote_band_names(self.attrs, dims, data_shape, coords)
        object.__setattr__(self, "coords", coords)
        object.__setattr__(self, "transform", transform)
        object.__setattr__(self, "crs", as_crs(self.crs))
        object.__setattr__(self, "fill_value", _normalize_fill(self.fill_value))
        _check_fill_fits(self.fill_value, self.data.dtype)
        if not isinstance(self.attrs, FrozenAttrs):
            object.__setattr__(self, "attrs", FrozenAttrs(self.attrs or {}))

    @classmethod
    def from_coords(
        cls,
        data: Any,
        *coords: Coordinate | PixelGrid | str,
        transform: Any,
        fill_value: Any = None,
        attrs: Any = None,
    ) -> GeoArray:
        """A carrier from its coordinates, one per dim in axis order.

        Each entry describes the next axis or axes: a 1-D axis
        (`SpectralAxis`, `TimeAxis`, …) one dim, a dim name (``"patch"``) a
        dim without a coordinate, and the last entry a `PixelGrid`, which
        gives ``y x``, the CRS and the expected spatial shape. A
        point-convention grid's transform is shifted to the area convention
        carriers store (`PixelGrid.area_transform`).

        Raises:
            TypeError: The last entry is not a `PixelGrid`.
            ValueError: The data does not fit the coordinates.

        Example:
            >>> import numpy as np
            >>> from geoarray.coords import PixelGrid, SpectralAxis, TimeAxis
            >>> dates = TimeAxis(stamps=["2026-06-01", "2026-06-11"])
            >>> swir = SpectralAxis(names=("B11", "B12"))
            >>> grid = PixelGrid(shape=(4, 4), crs="EPSG:32613")
            >>> t = (20.0, 0.0, 600000.0, 0.0, -20.0, 3550000.0)
            >>> data = np.zeros((2, 2, 4, 4))
            >>> g = GeoArray.from_coords(data, dates, swir, grid, transform=t)
            >>> g.dims
            ('time', 'band', 'y', 'x')
        """
        if not coords or not isinstance(coords[-1], PixelGrid):
            raise TypeError("from_coords ends with a PixelGrid for the y x dims")
        grid = coords[-1]
        leading = coords[:-1]
        dims = tuple(c if isinstance(c, str) else c.dim for c in leading) + SPATIAL_DIMS
        if tuple(data.shape[-2:]) != grid.shape:
            raise ValueError(
                f"the PixelGrid has shape {grid.shape}, but the data's spatial "
                f"shape is {tuple(data.shape[-2:])}"
            )
        backend = backend_of(data)
        t = _coerce_transform(transform, backend)
        return cls(
            data,
            grid.area_transform(t),
            grid.crs,
            fill_value,
            attrs,
            dims=dims,
            coords=tuple(c for c in leading if not isinstance(c, str)),
        )

    # -- what it is ---------------------------------------------------------

    @property
    def backend(self) -> Backend:
        """``"numpy"`` or ``"jax"``."""
        return backend_of(self.data)

    @property
    def xp(self) -> Any:
        """The array module of the data: ``numpy`` or ``jax.numpy``."""
        return namespace(self.data)

    @property
    def shape(self) -> tuple[int, ...]:
        """The data's shape, ``(..., H, W)``."""
        return tuple(self.data.shape)

    @property
    def ndim(self) -> int:
        """The number of axes (``len(dims)``)."""
        return len(self.data.shape)

    @property
    def dtype(self) -> Any:
        """The data's dtype."""
        return self.data.dtype

    @property
    def sizes(self) -> dict[str, int]:
        """Each dim's size: ``{"band": 2, "y": 600, "x": 600}``."""
        return dict(zip(self.dims, self.shape, strict=True))

    @property
    def batch_shape(self) -> tuple[int, ...]:
        """Leading batch axes: ``()`` for one scene, ``(P,)`` for P patches.

        A batched carrier has one transform per item, ``(*batch, 6)``;
        `batch_dims` names those axes.
        """
        return tuple(self.transform.shape[:-1])

    @property
    def batch_dims(self) -> tuple[str, ...]:
        """The dims that index transform rows: ``()``, or ``("patch",)``."""
        return self.dims[: len(self.batch_shape)]

    @property
    def height(self) -> int:
        """H, the number of rows."""
        return int(self.data.shape[-2])

    @property
    def width(self) -> int:
        """W, the number of columns."""
        return int(self.data.shape[-1])

    @property
    def count(self) -> int:
        """The number of bands: the size of the ``band`` dim, or 1 without one."""
        if "band" not in self.dims:
            return 1
        return int(self.data.shape[self.dims.index("band")])

    def coord(self, dim: str) -> Coordinate | None:
        """The coordinate of ``dim``, or ``None``.

        Raises:
            KeyError: ``dim`` is not one of this carrier's dims.
        """
        if dim not in self.dims:
            raise KeyError(f"{dim!r} is not a dim of {self.dims}")
        return _coord_for(self.coords, dim)

    def labels(self, dim: str) -> tuple[Any, ...] | None:
        """The exact labels of ``dim`` (band names, level values), or ``None``."""
        c = self.coord(dim)
        return None if c is None else c.labels

    # -- where it is --------------------------------------------------------

    def _concrete_transform(self, what: str) -> Transform:
        if self.batch_shape:
            raise ValueError(
                f"{what} is per scene, but this carrier is batched {self.batch_shape}: "
                "index it, or read it inside jax.vmap"
            )
        if is_traced(self.transform):
            raise GeoArrayTraceError(
                f"{what} needs a concrete transform, but this GeoArray is traced "
                "(inside jit / grad / vmap): read g.transform there, or compute "
                f"{what} outside the transform"
            )
        return as_transform(np.asarray(self.transform))

    @property
    def grid(self) -> Grid:
        """The pixel grid ``(transform, crs, (H, W))`` as a hashable `Grid`.

        Raises:
            GeoArrayTraceError: Inside ``jit`` / ``grad`` / ``vmap``.
        """
        return Grid(
            self._concrete_transform("grid"), self.crs, (self.height, self.width)
        )

    @property
    def pixel_grid(self) -> PixelGrid:
        """The ``y x`` coordinate: shape and CRS, area convention."""
        return PixelGrid((self.height, self.width), self.crs)

    @property
    def res(self) -> tuple[float, float]:
        """Pixel size ``(x, y)`` in CRS units (see `Grid.res`)."""
        return self.grid.res

    @property
    def bounds(self) -> tuple[float, float, float, float]:
        """``(x_min, y_min, x_max, y_max)`` (see `Grid.bounds`)."""
        return self.grid.bounds

    # -- new carriers from this one ----------------------------------------

    def __reduce__(self) -> tuple[Any, ...]:
        # Rebuild through the constructor, so a NaN fill is the one
        # ``math.nan`` again and attrs are re-frozen in the new process.
        return (
            _restore,
            (
                self.data,
                self.transform,
                self.crs,
                self.fill_value,
                self.attrs,
                self.dims,
                self.coords,
            ),
        )

    def replace(self, **changes: Any) -> GeoArray:
        """A copy with fields replaced (``data``, ``transform``, ``dims``, …).

        Example:
            >>> import numpy as np
            >>> g = GeoArray(np.zeros((4, 4)), (1, 0, 0, 0, -1, 0), None, dims="y x")
            >>> g.replace(fill_value=0).fill_value
            0
        """
        return dataclasses.replace(self, **changes)

    def _dims_for(self, data: Any, transform: Any) -> tuple[str, ...]:
        """Dims for new data when none are given: ours, or a guess with a warning."""
        ndim = len(data.shape)
        if ndim == self.ndim:
            return self.dims
        n_batch = max(len(getattr(transform, "shape", (6,))) - 1, 0)
        if ndim < self.ndim and n_batch == len(self.batch_shape) == 0:
            # fewer axes: the leading dims went (a reduction keeping y x)
            return self.dims[self.ndim - ndim :]
        dims = infer_dims(ndim, n_batch)
        warnings.warn(
            f"with_data could not tell the new dims from {self.dims}; reading "
            f"them from the rank as {dims} is deprecated: pass dims=",
            DeprecationWarning,
            stacklevel=4,
        )
        return dims

    def with_data(
        self,
        data: Any,
        *,
        transform: Any = None,
        fill_value: Any = INHERIT,
        attrs: Any = None,
        dims: Any = None,
        coords: Any = INHERIT,
    ) -> GeoArray:
        """A carrier with new data on this carrier's grid (or ``transform``).

        Args:
            data: The new ``(..., H, W)`` array.
            transform: A new transform, for data on a new grid. When omitted,
                ``data`` must keep this carrier's spatial shape.
            fill_value: The new fill; omitted keeps this carrier's.
            attrs: New attrs; omitted keeps this carrier's, without the
                per-band keys when the band count changed.
            dims: The new data's dims; omitted keeps this carrier's when the
                rank is unchanged, and drops leading dims when it fell.
            coords: New coordinates; omitted keeps each of this carrier's
                whose dim survives with the same size.

        Raises:
            ValueError: The spatial shape changed and no ``transform`` was
                given.

        Example:
            >>> import numpy as np
            >>> t = (1, 0, 0, 0, -1, 0)
            >>> g = GeoArray(np.ones((2, 4, 4)), t, None, dims="band y x")
            >>> g.with_data(np.zeros((1, 4, 4), dtype=bool), fill_value=False).shape
            (1, 4, 4)
        """
        if transform is None:
            if tuple(data.shape[-2:]) != tuple(self.data.shape[-2:]):
                raise ValueError(
                    f"spatial shape changed from {tuple(self.data.shape[-2:])} to "
                    f"{tuple(data.shape[-2:])}: pass transform= for data on a new grid"
                )
            transform = self.transform
        new_dims = self._dims_for(data, transform) if dims is None else dims
        if isinstance(new_dims, str):
            new_dims = tuple(new_dims.split())
        shape = tuple(data.shape)
        if coords is INHERIT:
            coords = tuple(
                c
                for c in self.coords
                if len(new_dims) == len(shape) and _keeps_coord(c, new_dims, shape)
            )
        if attrs is None:
            attrs = self.attrs
            band = (
                shape[new_dims.index("band")]
                if "band" in new_dims and len(new_dims) == len(shape)
                else 1
            )
            if band != self.count:
                attrs = drop_band_keys(attrs)
        return GeoArray(
            data,
            transform,
            self.crs,
            self.fill_value if fill_value is INHERIT else fill_value,
            attrs,
            dims=new_dims,
            coords=coords,
        )

    def with_attrs(self, **items: Any) -> GeoArray:
        """A copy with attrs added or replaced (see `FrozenAttrs.set`)."""
        return dataclasses.replace(self, attrs=self.attrs.set(**items))

    def drop_attrs(self, *keys: str) -> GeoArray:
        """A copy without the given attrs keys (see `FrozenAttrs.drop`)."""
        return dataclasses.replace(self, attrs=self.attrs.drop(*keys))

    def astype(self, dtype: Any, *, fill_value: Any = INHERIT) -> GeoArray:
        """A copy with the data cast to ``dtype``; geometry unchanged.

        Args:
            dtype: The new dtype.
            fill_value: The new fill; omitted keeps this carrier's, which
                ``dtype`` must be able to hold (a NaN fill cannot be cast to
                integers, for example).

        Raises:
            ValueError: ``dtype`` cannot hold the fill.

        Example:
            >>> import numpy as np
            >>> t = (1, 0, 0, 0, -1, 0)
            >>> g = GeoArray(np.ones((4, 4)), t, None, np.nan, dims="y x")
            >>> g.astype(np.uint8, fill_value=255).fill_value
            255
        """
        fill = self.fill_value if fill_value is INHERIT else fill_value
        return dataclasses.replace(self, data=self.data.astype(dtype), fill_value=fill)

    def map(self, f: Any) -> GeoArray:
        """Apply ``f`` to the data and keep the geometry.

        ``f`` may change the leading axes (a band index collapses bands)
        but not the spatial shape. Works inside ``jit``.

        Raises:
            ValueError: ``f`` changed the spatial shape.

        Example:
            >>> import numpy as np
            >>> t = (1, 0, 0, 0, -1, 0)
            >>> g = GeoArray(np.full((2, 2), 9.0), t, None, dims="y x")
            >>> g.map(np.sqrt).data[0, 0]
            np.float64(3.0)
        """
        out = f(self.data)
        if tuple(out.shape[-2:]) != tuple(self.data.shape[-2:]):
            raise ValueError(
                f"map must keep the spatial shape {tuple(self.data.shape[-2:])}, "
                f"got {tuple(out.shape[-2:])}; for a new grid use "
                "with_data(..., transform=)"
            )
        return self.with_data(out)

    # -- indexing --------------------------------------------------------------

    def __getitem__(self, key: Any) -> GeoArray:
        """Index like NumPy; spatial slices move the transform.

        The last two (spatial) axes take slices with positive steps only;
        the leading axes take anything NumPy indexing allows, with at most
        one list / array index. An integer drops its dim and that dim's
        coordinate; other indices slice the coordinate with the data, and
        indexing the band dim selects the per-band attrs too.

        Example:
            >>> import numpy as np
            >>> g = GeoArray(
            ...     np.zeros((3, 8, 8)), (20, 0, 600000, 0, -20, 3550000), 32613,
            ...     attrs={"band_names": ["B04", "B08", "B11"]}, dims="band y x",
            ... )
            >>> sub = g[1:, 2:6, ::2]
            >>> sub.shape, sub.res, sub.attrs["band_names"]
            ((2, 4, 4), (40.0, 20.0), ('B08', 'B11'))
        """
        return self._index(key, guard_band=True)

    def _index(self, key: Any, *, guard_band: bool) -> GeoArray:
        """``g[key]``; ``guard_band`` refuses dropping ``band`` alone (positional)."""
        ndim = self.ndim
        key = _expand_key(key, ndim)
        _require_concrete_spatial(key[-2:])
        rows, cols = key[-2], key[-1]
        if not (isinstance(rows, slice) and isinstance(cols, slice)):
            raise IndexError(
                "the spatial axes take slices only (an integer or list would drop "
                "georeferencing); use g.data for plain arrays"
            )
        r0, _, row_step = rows.indices(self.height)
        c0, _, col_step = cols.indices(self.width)
        if row_step <= 0 or col_step <= 0:
            raise IndexError("spatial slices need positive steps")
        n_batch = len(self.batch_shape)
        leading = key[:-2]
        if sum(_is_advanced(k) for k in leading) > 1:
            raise IndexError("at most one list / array index on the leading axes")
        dims = self.dims
        dropped = {d for d, k in zip(dims, key, strict=True) if _drops_axis(k)}
        if guard_band and _drops_band_alone(dims, dropped):
            raise IndexError(
                "an integer band index on a (T, C, H, W) carrier would leave "
                "(T, H, W), which reads as (C, H, W); index with [k] to keep a "
                "(T, 1, H, W) band axis"
            )
        transform = self.transform[key[:n_batch]] if n_batch else self.transform
        attrs = self.attrs
        coords = []
        for d, k in zip(dims[:-2], leading, strict=True):
            c = _coord_for(self.coords, d)
            full = isinstance(k, slice) and k == slice(None)
            if d == "band" and not full:
                attrs = select_bands(attrs, k, self.count)
            if c is None or d in dropped:
                continue
            if not full and is_traced(k):
                raise GeoArrayTraceError(
                    f"an index on {d!r} must be concrete: its coordinate is static, "
                    "so the selection must be known when tracing; index g.data "
                    "instead, or select outside jit"
                )
            sliced = c if full else sliced_coord(c, k)
            if sliced is not None:
                coords.append(sliced)
        new_dims = tuple(d for d in dims if d not in dropped)
        return GeoArray(
            _index_in_order(self.data, key, dims, new_dims),
            shift_scale_transform(transform, r0, c0, row_step, col_step),
            self.crs,
            self.fill_value,
            attrs,
            dims=new_dims,
            coords=tuple(coords),
        )

    def isel(self, selection: dict[str, Any] | None = None, **by_dim: Any) -> GeoArray:
        """Index by dim name: ``g.isel(band=[0, 2], y=slice(0, 100))``.

        The rules of ``g[...]`` apply: ``y`` and ``x`` take positive-step
        slices and move the origin; other dims take ints, slices or
        positions, and slice their coordinate. By name, an integer may drop
        ``band`` from ``(time, band, y, x)``: the stored dims say what is
        left.

        Raises:
            KeyError: A name is not one of this carrier's dims.

        Example:
            >>> import numpy as np
            >>> t = (20, 0, 0, 0, -20, 0)
            >>> g = GeoArray(np.zeros((3, 8, 8)), t, 32613, dims="band y x")
            >>> g.isel(band=0, x=slice(0, 4)).shape
            (8, 4)
        """
        wanted = {**(selection or {}), **by_dim}
        dims = self.dims
        unknown = set(wanted) - set(dims)
        if unknown:
            raise KeyError(f"cannot select {sorted(unknown)}; dims are {dims}")
        # by name, the result's dims say what is left: no 0.2 band guard
        key = tuple(wanted.get(name, slice(None)) for name in dims)
        return self._index(key, guard_band=False)

    def sel(self, selection: dict[str, Any] | None = None, **by_dim: Any) -> GeoArray:
        """Select by exact label: ``g.sel(band="B12")``, ``g.sel(band=["B8", "B4"])``.

        One label drops its dim; a list, a tuple or a 1-D array keeps it.
        Labels come from the dim's coordinate (`labels`).

        Raises:
            LabelError: The dim has no labels or is spatial, a label is
                missing, or the value is a range (a ``slice``): selection by
                value lives in xarray (``to_xarray()``).
            KeyError: A name is not one of this carrier's dims.

        Example:
            >>> import numpy as np
            >>> from geoarray.coords import SpectralAxis
            >>> bands = SpectralAxis(names=("B4", "B8"))
            >>> g = GeoArray(np.zeros((2, 4, 4)), (20, 0, 0, 0, -20, 0), 32613,
            ...              dims="band y x", coords=(bands,))
            >>> g.sel(band="B8").dims
            ('y', 'x')
        """
        wanted = {**(selection or {}), **by_dim}
        return select_labels(self, wanted)

    def shift_origin(self, delta: Any) -> GeoArray:
        """Move the grid by ``delta = (Δx, Δy)`` in CRS units: c + Δx, f + Δy.

        The pixels do not move; their georeferencing does. Differentiable,
        so ``jax.grad`` can find a sub-pixel co-registration shift.

        Example:
            >>> import numpy as np
            >>> t = (20, 0, 600000, 0, -20, 3550000)
            >>> g = GeoArray(np.zeros((2, 2)), t, 32613, dims="y x")
            >>> g.shift_origin((7.3, 0.0)).transform[2]
            np.float64(600007.3)
        """
        xp = namespace(self.transform)
        dx, dy = (
            xp.asarray(v, dtype=self.transform.dtype) for v in (delta[0], delta[1])
        )
        t = self.transform
        columns = (
            t[..., 0],
            t[..., 1],
            t[..., 2] + dx,
            t[..., 3],
            t[..., 4],
            t[..., 5] + dy,
        )
        return dataclasses.replace(self, transform=xp.stack(columns, axis=-1))

    def squeeze(self, axis: int | tuple[int, ...] | None = None) -> GeoArray:
        """Drop size-1 leading axes (all of them when ``axis`` is ``None``).

        The band axis of a ``(T, 1, H, W)`` stack stays unless time goes
        too: ``(T, H, W)`` would read as ``(C, H, W)``.

        Raises:
            ValueError: ``axis`` names a spatial or batch axis.
        """
        n_batch = len(self.batch_shape)
        leading = range(n_batch, self.ndim - 2)
        dims = self.dims
        if axis is None:
            axes = tuple(i for i in leading if self.data.shape[i] == 1)
            names = {dims[i] for i in axes}
            if _drops_band_alone(dims, names):
                axes = tuple(i for i in axes if dims[i] != "band")
        else:
            requested = (axis,) if isinstance(axis, int) else tuple(axis)
            axes = tuple(i + self.ndim if i < 0 else i for i in requested)
            if any(i not in leading for i in axes):
                raise ValueError(f"squeeze: {axis} is not a leading, non-batch axis")
            if _drops_band_alone(dims, {dims[i] for i in axes}):
                raise ValueError(
                    "squeeze: dropping the band axis of (T, 1, H, W) would leave "
                    "(T, H, W), which reads as (C, H, W)"
                )
        kept = tuple(d for i, d in enumerate(dims) if i not in axes)
        return self.with_data(self.xp.squeeze(self.data, axis=axes), dims=kept)

    def expand_dims(self, axis: int, dim: str | None = None) -> GeoArray:
        """Insert a size-1 leading axis at ``axis``, named ``dim``.

        Args:
            axis: Where the new axis goes, before the spatial axes.
            dim: Its name. Omitted, it is the name the 0.2 layout gives that
                position (``DIMS[-ndim:]``), with a ``DeprecationWarning``.

        Raises:
            ValueError: ``axis`` is not before the spatial axes, or the name
                is taken.
        """
        ndim = self.ndim + 1
        position = axis + ndim if axis < 0 else axis
        n_batch = len(self.batch_shape)
        if not n_batch <= position < ndim - 2:
            raise ValueError(
                f"expand_dims: axis {axis} must come before the spatial axes"
            )
        if dim is None:
            if ndim - n_batch > 4:
                raise ValueError(
                    f"expand_dims: a {ndim}-D result needs a name: pass dim="
                )
            dim = infer_dims(ndim, n_batch)[position]
            warnings.warn(
                f"expand_dims without dim= names the new axis {dim!r} from the "
                "rank; this is deprecated: pass dim=",
                DeprecationWarning,
                stacklevel=2,
            )
        if dim in self.dims:
            raise ValueError(f"expand_dims: {dim!r} is already a dim of {self.dims}")
        dims = (*self.dims[:position], dim, *self.dims[position:])
        return self.with_data(self.xp.expand_dims(self.data, axis=position), dims=dims)

    # -- nodata ----------------------------------------------------------------

    def valid_mask(self, *, keep_time: bool = False) -> Any:
        """Which pixels hold data: ``(H, W)`` booleans, True where valid.

        A pixel is valid when every entry there (over the non-batch,
        non-spatial dims) is finite and differs from the fill value (a NaN
        fill matches NaN). ``keep_time=True`` keeps a ``time`` dim,
        ``(T, H, W)``. Batch axes are kept. Works inside ``jit``.

        v_ij = ∧ₖ [isfinite(x_kij) ∧ x_kij ≠ φ]

        Example:
            >>> import numpy as np
            >>> data = np.array([[[1.0, np.nan]], [[2.0, 3.0]]])
            >>> g = GeoArray(data, (1, 0, 0, 0, -1, 0), None, np.nan, dims="band y x")
            >>> g.valid_mask().tolist()
            [[True, False]]
        """
        xp = self.xp
        data = self.data
        floating = data.dtype.kind in "fc"
        invalid = ~xp.isfinite(data) if floating else xp.zeros(data.shape, dtype=bool)
        fill = self.fill_value
        if fill is not None and not (isinstance(fill, float) and math.isnan(fill)):
            invalid = invalid | (data == fill)
        n_batch = len(self.batch_shape)
        axes = tuple(
            i
            for i in range(n_batch, self.ndim - 2)
            if not (keep_time and self.dims[i] == "time")
        )
        return ~invalid.any(axis=axes) if axes else ~invalid

    # -- RasterSource ----------------------------------------------------------

    def read_window(self, window: PixelWindow, *, boundless: bool = True) -> GeoArray:
        """The pixels of ``window``: `geoarray.read_window` as a method.

        With `load`, this makes a carrier a `RasterSource`, so code written
        for lazy readers takes a loaded carrier too.

        Example:
            >>> import numpy as np
            >>> from geoarray import PixelWindow
            >>> t = (20, 0, 0, 0, -20, 0)
            >>> g = GeoArray(np.ones((4, 4)), t, 32613, 0.0, dims="y x")
            >>> window = PixelWindow(col_off=2, row_off=2, width=4, height=4)
            >>> g.read_window(window).shape
            (4, 4)
        """
        from geoarray._src.geometry import read_window

        return read_window(self, window, boundless=boundless)

    def load(self) -> GeoArray:
        """This carrier: its pixels are already loaded (`RasterSource`)."""
        return self

    # -- backends -------------------------------------------------------------

    def to_jax(self, device: Any = None) -> GeoArray:
        """This carrier with data and transform on a JAX device.

        Args:
            device: A ``jax.Device``; ``None`` is JAX's default device.

        Raises:
            ImportError: JAX is not installed (``geotoolz-array[jax]``).
            X64Error: ``jax_enable_x64`` is off; the transform is float64.

        Example:
            >>> import jax
            >>> import numpy as np
            >>> jax.config.update("jax_enable_x64", True)
            >>> data = np.zeros((4, 4), np.float32)
            >>> g = GeoArray(data, (1, 0, 0, 0, -1, 0), None, dims="y x").to_jax()
            >>> g.backend, str(g.dtype), str(g.transform.dtype)
            ('jax', 'float32', 'float64')
        """
        jax = import_jax()
        require_x64()
        stamps_on_host = any(
            isinstance(c, TimeAxis) and not is_jax_array(c.as_leaf())
            for c in self.coords
        )
        if self.backend == "jax" and device is None and not stamps_on_host:
            return self
        data = jax.device_put(self.data, device)
        transform = jax.device_put(self.transform, device)
        coords = coords_to_jax(self.coords, device)
        return GeoArray(
            data,
            transform,
            self.crs,
            self.fill_value,
            self.attrs,
            dims=self.dims,
            coords=coords,
        )

    def to_numpy(self) -> GeoArray:
        """This carrier with data and transform copied to NumPy on the host.

        Raises:
            GeoArrayTraceError: Inside ``jit`` / ``grad`` / ``vmap``.
        """
        if self.backend == "numpy":
            return self
        if is_traced(self.data) or is_traced(self.transform):
            raise GeoArrayTraceError(
                "to_numpy needs concrete data, but this GeoArray is traced "
                "(inside jit / grad / vmap): call it outside the transform"
            )
        coords = coords_to_host(self.coords)
        return GeoArray(
            np.asarray(self.data),
            np.asarray(self.transform, dtype=np.float64),
            self.crs,
            self.fill_value,
            self.attrs,
            dims=self.dims,
            coords=coords,
        )

    def __array__(self, dtype: Any = None, copy: bool | None = None) -> np.ndarray:
        """The data as a NumPy array, so ``np.asarray(g)`` works.

        NumPy data is returned as it is (no copy unless ``copy=True`` or a
        cast). JAX data is copied to the host, eagerly only: inside ``jit``,
        ``grad`` or ``vmap`` the data are tracers, and NumPy code cannot run
        on them. `pipekit_ops.guard` reports each host copy.

        Raises:
            GeoArrayTraceError: The data are traced.
            ValueError: ``copy=False`` for JAX data or a cast, which need a
                copy.
        """
        if self.backend == "numpy":
            if copy:
                return np.array(self.data, dtype=dtype, copy=True)
            if copy is False and dtype is not None and np.dtype(dtype) != self.dtype:
                raise ValueError(
                    f"casting {self.dtype} data to {np.dtype(dtype)} needs a copy, "
                    "but copy=False was passed"
                )
            return np.asarray(self.data, dtype=dtype)
        if is_traced(self.data):
            raise GeoArrayTraceError(
                "NumPy code received a GeoArray's data inside jit / grad / vmap, "
                "where the data are tracers; use a JAX function "
                "(jax.numpy) or call the NumPy code outside the transform"
            )
        if copy is False:
            raise ValueError(
                "a JAX GeoArray cannot become a NumPy array without a copy"
            )
        report_move("np.asarray(GeoArray)", "JAX data copied to the host")
        if copy:
            # np.asarray of a CPU JAX array can be a read-only view; a copy
            # the caller asked for must be writable.
            return np.array(self.data, dtype=dtype, copy=True)
        return np.asarray(self.data, dtype=dtype)

    # -- xarray ------------------------------------------------------------------

    def to_xarray(self) -> Any:
        """This carrier as an ``xr.DataArray`` (``geotoolz-array[xarray]``).

        Same dims and values; the CRS and the transform in a CF
        ``spatial_ref`` coordinate (``crs_wkt``, ``GeoTransform``), x and y
        centre coordinates when axis-aligned, and each coordinate of
        `geoarray.coords` as CF coordinates. `from_xarray` reads it back
        exactly.

        Raises:
            ImportError: xarray is not installed.
            ValueError: The carrier is batched.
        """
        return xarray_module().grid_to_xarray(self)

    @classmethod
    def from_xarray(cls, da: Any) -> GeoArray:
        """A ``DataArray`` on an affine grid as a `GeoArray` (see `to_xarray`).

        Reads the ``GeoTransform`` first, then centre coordinates, then
        georeader's ``attrs["crs"]`` (deprecated); dask data is computed.

        Raises:
            ImportError: xarray is not installed.
            ValueError: No grid, or irregular coordinates.
            GridMismatchError: Centres disagree with the ``GeoTransform``.
        """
        return xarray_module().grid_from_xarray(da)

    # -- comparison and display ----------------------------------------------

    def identical(self, other: object) -> bool:
        """Equal data (NaN-aware), transform, dims, coords, CRS, fill and attrs.

        Both carriers must be concrete; the backends may differ.

        Example:
            >>> import numpy as np
            >>> t = (1, 0, 0, 0, -1, 0)
            >>> g = GeoArray(np.zeros((2, 2)), t, "EPSG:4326", dims="y x")
            >>> g.identical(g.with_data(np.zeros((2, 2))))
            True
        """
        if not isinstance(other, GeoArray):
            return False
        mine = self.to_numpy()
        theirs = other.to_numpy()
        fill_equal = mine.fill_value is theirs.fill_value or (
            mine.fill_value == theirs.fill_value
            and type(mine.fill_value) is type(theirs.fill_value)
        )
        return (
            mine.data.shape == theirs.data.shape
            and mine.data.dtype == theirs.data.dtype
            and bool(
                np.array_equal(
                    mine.data, theirs.data, equal_nan=mine.data.dtype.kind in "fc"
                )
            )
            and bool(np.array_equal(mine.transform, theirs.transform))
            and mine.dims == theirs.dims
            and mine.coords == theirs.coords
            and mine.crs == theirs.crs
            and fill_equal
            and mine.attrs == theirs.attrs
        )

    def __repr__(self) -> str:
        head = f"{self.backend} {self.dtype} {self.shape}"
        if is_traced(self.data) or is_traced(self.transform) or self.batch_shape:
            where = "traced" if not self.batch_shape else f"batch={self.batch_shape}"
        else:
            grid = self.grid
            where = f"res={grid.res}, bounds={grid.bounds}"
        keys = tuple(self.attrs)
        return (
            f"GeoArray({head}, crs={_crs_label(self.crs)}, {where}, "
            f"fill_value={self.fill_value!r}, attrs={keys}, dims={self.dims})"
        )

backend property

"numpy" or "jax".

batch_dims property

The dims that index transform rows: (), or ("patch",).

batch_shape property

Leading batch axes: () for one scene, (P,) for P patches.

A batched carrier has one transform per item, (*batch, 6); batch_dims names those axes.

bounds property

(x_min, y_min, x_max, y_max) (see Grid.bounds).

count property

The number of bands: the size of the band dim, or 1 without one.

dtype property

The data's dtype.

grid property

The pixel grid (transform, crs, (H, W)) as a hashable Grid.

Raises:

Type Description
GeoArrayTraceError

Inside jit / grad / vmap.

height property

H, the number of rows.

ndim property

The number of axes (len(dims)).

pixel_grid property

The y x coordinate: shape and CRS, area convention.

res property

Pixel size (x, y) in CRS units (see Grid.res).

shape property

The data's shape, (..., H, W).

sizes property

Each dim's size: {"band": 2, "y": 600, "x": 600}.

width property

W, the number of columns.

xp property

The array module of the data: numpy or jax.numpy.

__array__(dtype=None, copy=None)

The data as a NumPy array, so np.asarray(g) works.

NumPy data is returned as it is (no copy unless copy=True or a cast). JAX data is copied to the host, eagerly only: inside jit, grad or vmap the data are tracers, and NumPy code cannot run on them. pipekit_ops.guard reports each host copy.

Raises:

Type Description
GeoArrayTraceError

The data are traced.

ValueError

copy=False for JAX data or a cast, which need a copy.

Source code in packages/geotoolz-array/src/geoarray/_src/array.py
def __array__(self, dtype: Any = None, copy: bool | None = None) -> np.ndarray:
    """The data as a NumPy array, so ``np.asarray(g)`` works.

    NumPy data is returned as it is (no copy unless ``copy=True`` or a
    cast). JAX data is copied to the host, eagerly only: inside ``jit``,
    ``grad`` or ``vmap`` the data are tracers, and NumPy code cannot run
    on them. `pipekit_ops.guard` reports each host copy.

    Raises:
        GeoArrayTraceError: The data are traced.
        ValueError: ``copy=False`` for JAX data or a cast, which need a
            copy.
    """
    if self.backend == "numpy":
        if copy:
            return np.array(self.data, dtype=dtype, copy=True)
        if copy is False and dtype is not None and np.dtype(dtype) != self.dtype:
            raise ValueError(
                f"casting {self.dtype} data to {np.dtype(dtype)} needs a copy, "
                "but copy=False was passed"
            )
        return np.asarray(self.data, dtype=dtype)
    if is_traced(self.data):
        raise GeoArrayTraceError(
            "NumPy code received a GeoArray's data inside jit / grad / vmap, "
            "where the data are tracers; use a JAX function "
            "(jax.numpy) or call the NumPy code outside the transform"
        )
    if copy is False:
        raise ValueError(
            "a JAX GeoArray cannot become a NumPy array without a copy"
        )
    report_move("np.asarray(GeoArray)", "JAX data copied to the host")
    if copy:
        # np.asarray of a CPU JAX array can be a read-only view; a copy
        # the caller asked for must be writable.
        return np.array(self.data, dtype=dtype, copy=True)
    return np.asarray(self.data, dtype=dtype)

__class_getitem__(item)

GeoArray["band y x"]: the carrier annotated with a dims pattern.

An Annotated type carrying a geoarray.types.ReadableType, which geoarray.types.check_dims checks. The 0.2 array-type parameter (GeoArray[np.ndarray]) is deprecated and returns the class.

Source code in packages/geotoolz-array/src/geoarray/_src/array.py
def __class_getitem__(cls, item: Any) -> Any:
    """``GeoArray["band y x"]``: the carrier annotated with a dims pattern.

    An ``Annotated`` type carrying a `geoarray.types.ReadableType`, which
    `geoarray.types.check_dims` checks. The 0.2 array-type parameter
    (``GeoArray[np.ndarray]``) is deprecated and returns the class.
    """
    return _subscript(cls, item)

__getitem__(key)

Index like NumPy; spatial slices move the transform.

The last two (spatial) axes take slices with positive steps only; the leading axes take anything NumPy indexing allows, with at most one list / array index. An integer drops its dim and that dim's coordinate; other indices slice the coordinate with the data, and indexing the band dim selects the per-band attrs too.

Example

import numpy as np g = GeoArray( ... np.zeros((3, 8, 8)), (20, 0, 600000, 0, -20, 3550000), 32613, ... attrs={"band_names": ["B04", "B08", "B11"]}, dims="band y x", ... ) sub = g[1:, 2:6, ::2] sub.shape, sub.res, sub.attrs["band_names"] ((2, 4, 4), (40.0, 20.0), ('B08', 'B11'))

Source code in packages/geotoolz-array/src/geoarray/_src/array.py
def __getitem__(self, key: Any) -> GeoArray:
    """Index like NumPy; spatial slices move the transform.

    The last two (spatial) axes take slices with positive steps only;
    the leading axes take anything NumPy indexing allows, with at most
    one list / array index. An integer drops its dim and that dim's
    coordinate; other indices slice the coordinate with the data, and
    indexing the band dim selects the per-band attrs too.

    Example:
        >>> import numpy as np
        >>> g = GeoArray(
        ...     np.zeros((3, 8, 8)), (20, 0, 600000, 0, -20, 3550000), 32613,
        ...     attrs={"band_names": ["B04", "B08", "B11"]}, dims="band y x",
        ... )
        >>> sub = g[1:, 2:6, ::2]
        >>> sub.shape, sub.res, sub.attrs["band_names"]
        ((2, 4, 4), (40.0, 20.0), ('B08', 'B11'))
    """
    return self._index(key, guard_band=True)

astype(dtype, *, fill_value=INHERIT)

A copy with the data cast to dtype; geometry unchanged.

Parameters:

Name Type Description Default
dtype Any

The new dtype.

required
fill_value Any

The new fill; omitted keeps this carrier's, which dtype must be able to hold (a NaN fill cannot be cast to integers, for example).

INHERIT

Raises:

Type Description
ValueError

dtype cannot hold the fill.

Example

import numpy as np t = (1, 0, 0, 0, -1, 0) g = GeoArray(np.ones((4, 4)), t, None, np.nan, dims="y x") g.astype(np.uint8, fill_value=255).fill_value 255

Source code in packages/geotoolz-array/src/geoarray/_src/array.py
def astype(self, dtype: Any, *, fill_value: Any = INHERIT) -> GeoArray:
    """A copy with the data cast to ``dtype``; geometry unchanged.

    Args:
        dtype: The new dtype.
        fill_value: The new fill; omitted keeps this carrier's, which
            ``dtype`` must be able to hold (a NaN fill cannot be cast to
            integers, for example).

    Raises:
        ValueError: ``dtype`` cannot hold the fill.

    Example:
        >>> import numpy as np
        >>> t = (1, 0, 0, 0, -1, 0)
        >>> g = GeoArray(np.ones((4, 4)), t, None, np.nan, dims="y x")
        >>> g.astype(np.uint8, fill_value=255).fill_value
        255
    """
    fill = self.fill_value if fill_value is INHERIT else fill_value
    return dataclasses.replace(self, data=self.data.astype(dtype), fill_value=fill)

coord(dim)

The coordinate of dim, or None.

Raises:

Type Description
KeyError

dim is not one of this carrier's dims.

Source code in packages/geotoolz-array/src/geoarray/_src/array.py
def coord(self, dim: str) -> Coordinate | None:
    """The coordinate of ``dim``, or ``None``.

    Raises:
        KeyError: ``dim`` is not one of this carrier's dims.
    """
    if dim not in self.dims:
        raise KeyError(f"{dim!r} is not a dim of {self.dims}")
    return _coord_for(self.coords, dim)

drop_attrs(*keys)

A copy without the given attrs keys (see FrozenAttrs.drop).

Source code in packages/geotoolz-array/src/geoarray/_src/array.py
def drop_attrs(self, *keys: str) -> GeoArray:
    """A copy without the given attrs keys (see `FrozenAttrs.drop`)."""
    return dataclasses.replace(self, attrs=self.attrs.drop(*keys))

expand_dims(axis, dim=None)

Insert a size-1 leading axis at axis, named dim.

Parameters:

Name Type Description Default
axis int

Where the new axis goes, before the spatial axes.

required
dim str | None

Its name. Omitted, it is the name the 0.2 layout gives that position (DIMS[-ndim:]), with a DeprecationWarning.

None

Raises:

Type Description
ValueError

axis is not before the spatial axes, or the name is taken.

Source code in packages/geotoolz-array/src/geoarray/_src/array.py
def expand_dims(self, axis: int, dim: str | None = None) -> GeoArray:
    """Insert a size-1 leading axis at ``axis``, named ``dim``.

    Args:
        axis: Where the new axis goes, before the spatial axes.
        dim: Its name. Omitted, it is the name the 0.2 layout gives that
            position (``DIMS[-ndim:]``), with a ``DeprecationWarning``.

    Raises:
        ValueError: ``axis`` is not before the spatial axes, or the name
            is taken.
    """
    ndim = self.ndim + 1
    position = axis + ndim if axis < 0 else axis
    n_batch = len(self.batch_shape)
    if not n_batch <= position < ndim - 2:
        raise ValueError(
            f"expand_dims: axis {axis} must come before the spatial axes"
        )
    if dim is None:
        if ndim - n_batch > 4:
            raise ValueError(
                f"expand_dims: a {ndim}-D result needs a name: pass dim="
            )
        dim = infer_dims(ndim, n_batch)[position]
        warnings.warn(
            f"expand_dims without dim= names the new axis {dim!r} from the "
            "rank; this is deprecated: pass dim=",
            DeprecationWarning,
            stacklevel=2,
        )
    if dim in self.dims:
        raise ValueError(f"expand_dims: {dim!r} is already a dim of {self.dims}")
    dims = (*self.dims[:position], dim, *self.dims[position:])
    return self.with_data(self.xp.expand_dims(self.data, axis=position), dims=dims)

from_coords(data, *coords, transform, fill_value=None, attrs=None) classmethod

A carrier from its coordinates, one per dim in axis order.

Each entry describes the next axis or axes: a 1-D axis (SpectralAxis, TimeAxis, …) one dim, a dim name ("patch") a dim without a coordinate, and the last entry a PixelGrid, which gives y x, the CRS and the expected spatial shape. A point-convention grid's transform is shifted to the area convention carriers store (PixelGrid.area_transform).

Raises:

Type Description
TypeError

The last entry is not a PixelGrid.

ValueError

The data does not fit the coordinates.

Example

import numpy as np from geoarray.coords import PixelGrid, SpectralAxis, TimeAxis dates = TimeAxis(stamps=["2026-06-01", "2026-06-11"]) swir = SpectralAxis(names=("B11", "B12")) grid = PixelGrid(shape=(4, 4), crs="EPSG:32613") t = (20.0, 0.0, 600000.0, 0.0, -20.0, 3550000.0) data = np.zeros((2, 2, 4, 4)) g = GeoArray.from_coords(data, dates, swir, grid, transform=t) g.dims ('time', 'band', 'y', 'x')

Source code in packages/geotoolz-array/src/geoarray/_src/array.py
@classmethod
def from_coords(
    cls,
    data: Any,
    *coords: Coordinate | PixelGrid | str,
    transform: Any,
    fill_value: Any = None,
    attrs: Any = None,
) -> GeoArray:
    """A carrier from its coordinates, one per dim in axis order.

    Each entry describes the next axis or axes: a 1-D axis
    (`SpectralAxis`, `TimeAxis`, …) one dim, a dim name (``"patch"``) a
    dim without a coordinate, and the last entry a `PixelGrid`, which
    gives ``y x``, the CRS and the expected spatial shape. A
    point-convention grid's transform is shifted to the area convention
    carriers store (`PixelGrid.area_transform`).

    Raises:
        TypeError: The last entry is not a `PixelGrid`.
        ValueError: The data does not fit the coordinates.

    Example:
        >>> import numpy as np
        >>> from geoarray.coords import PixelGrid, SpectralAxis, TimeAxis
        >>> dates = TimeAxis(stamps=["2026-06-01", "2026-06-11"])
        >>> swir = SpectralAxis(names=("B11", "B12"))
        >>> grid = PixelGrid(shape=(4, 4), crs="EPSG:32613")
        >>> t = (20.0, 0.0, 600000.0, 0.0, -20.0, 3550000.0)
        >>> data = np.zeros((2, 2, 4, 4))
        >>> g = GeoArray.from_coords(data, dates, swir, grid, transform=t)
        >>> g.dims
        ('time', 'band', 'y', 'x')
    """
    if not coords or not isinstance(coords[-1], PixelGrid):
        raise TypeError("from_coords ends with a PixelGrid for the y x dims")
    grid = coords[-1]
    leading = coords[:-1]
    dims = tuple(c if isinstance(c, str) else c.dim for c in leading) + SPATIAL_DIMS
    if tuple(data.shape[-2:]) != grid.shape:
        raise ValueError(
            f"the PixelGrid has shape {grid.shape}, but the data's spatial "
            f"shape is {tuple(data.shape[-2:])}"
        )
    backend = backend_of(data)
    t = _coerce_transform(transform, backend)
    return cls(
        data,
        grid.area_transform(t),
        grid.crs,
        fill_value,
        attrs,
        dims=dims,
        coords=tuple(c for c in leading if not isinstance(c, str)),
    )

from_xarray(da) classmethod

A DataArray on an affine grid as a GeoArray (see to_xarray).

Reads the GeoTransform first, then centre coordinates, then georeader's attrs["crs"] (deprecated); dask data is computed.

Raises:

Type Description
ImportError

xarray is not installed.

ValueError

No grid, or irregular coordinates.

GridMismatchError

Centres disagree with the GeoTransform.

Source code in packages/geotoolz-array/src/geoarray/_src/array.py
@classmethod
def from_xarray(cls, da: Any) -> GeoArray:
    """A ``DataArray`` on an affine grid as a `GeoArray` (see `to_xarray`).

    Reads the ``GeoTransform`` first, then centre coordinates, then
    georeader's ``attrs["crs"]`` (deprecated); dask data is computed.

    Raises:
        ImportError: xarray is not installed.
        ValueError: No grid, or irregular coordinates.
        GridMismatchError: Centres disagree with the ``GeoTransform``.
    """
    return xarray_module().grid_from_xarray(da)

identical(other)

Equal data (NaN-aware), transform, dims, coords, CRS, fill and attrs.

Both carriers must be concrete; the backends may differ.

Example

import numpy as np t = (1, 0, 0, 0, -1, 0) g = GeoArray(np.zeros((2, 2)), t, "EPSG:4326", dims="y x") g.identical(g.with_data(np.zeros((2, 2)))) True

Source code in packages/geotoolz-array/src/geoarray/_src/array.py
def identical(self, other: object) -> bool:
    """Equal data (NaN-aware), transform, dims, coords, CRS, fill and attrs.

    Both carriers must be concrete; the backends may differ.

    Example:
        >>> import numpy as np
        >>> t = (1, 0, 0, 0, -1, 0)
        >>> g = GeoArray(np.zeros((2, 2)), t, "EPSG:4326", dims="y x")
        >>> g.identical(g.with_data(np.zeros((2, 2))))
        True
    """
    if not isinstance(other, GeoArray):
        return False
    mine = self.to_numpy()
    theirs = other.to_numpy()
    fill_equal = mine.fill_value is theirs.fill_value or (
        mine.fill_value == theirs.fill_value
        and type(mine.fill_value) is type(theirs.fill_value)
    )
    return (
        mine.data.shape == theirs.data.shape
        and mine.data.dtype == theirs.data.dtype
        and bool(
            np.array_equal(
                mine.data, theirs.data, equal_nan=mine.data.dtype.kind in "fc"
            )
        )
        and bool(np.array_equal(mine.transform, theirs.transform))
        and mine.dims == theirs.dims
        and mine.coords == theirs.coords
        and mine.crs == theirs.crs
        and fill_equal
        and mine.attrs == theirs.attrs
    )

isel(selection=None, **by_dim)

Index by dim name: g.isel(band=[0, 2], y=slice(0, 100)).

The rules of g[...] apply: y and x take positive-step slices and move the origin; other dims take ints, slices or positions, and slice their coordinate. By name, an integer may drop band from (time, band, y, x): the stored dims say what is left.

Raises:

Type Description
KeyError

A name is not one of this carrier's dims.

Example

import numpy as np t = (20, 0, 0, 0, -20, 0) g = GeoArray(np.zeros((3, 8, 8)), t, 32613, dims="band y x") g.isel(band=0, x=slice(0, 4)).shape (8, 4)

Source code in packages/geotoolz-array/src/geoarray/_src/array.py
def isel(self, selection: dict[str, Any] | None = None, **by_dim: Any) -> GeoArray:
    """Index by dim name: ``g.isel(band=[0, 2], y=slice(0, 100))``.

    The rules of ``g[...]`` apply: ``y`` and ``x`` take positive-step
    slices and move the origin; other dims take ints, slices or
    positions, and slice their coordinate. By name, an integer may drop
    ``band`` from ``(time, band, y, x)``: the stored dims say what is
    left.

    Raises:
        KeyError: A name is not one of this carrier's dims.

    Example:
        >>> import numpy as np
        >>> t = (20, 0, 0, 0, -20, 0)
        >>> g = GeoArray(np.zeros((3, 8, 8)), t, 32613, dims="band y x")
        >>> g.isel(band=0, x=slice(0, 4)).shape
        (8, 4)
    """
    wanted = {**(selection or {}), **by_dim}
    dims = self.dims
    unknown = set(wanted) - set(dims)
    if unknown:
        raise KeyError(f"cannot select {sorted(unknown)}; dims are {dims}")
    # by name, the result's dims say what is left: no 0.2 band guard
    key = tuple(wanted.get(name, slice(None)) for name in dims)
    return self._index(key, guard_band=False)

labels(dim)

The exact labels of dim (band names, level values), or None.

Source code in packages/geotoolz-array/src/geoarray/_src/array.py
def labels(self, dim: str) -> tuple[Any, ...] | None:
    """The exact labels of ``dim`` (band names, level values), or ``None``."""
    c = self.coord(dim)
    return None if c is None else c.labels

load()

This carrier: its pixels are already loaded (RasterSource).

Source code in packages/geotoolz-array/src/geoarray/_src/array.py
def load(self) -> GeoArray:
    """This carrier: its pixels are already loaded (`RasterSource`)."""
    return self

map(f)

Apply f to the data and keep the geometry.

f may change the leading axes (a band index collapses bands) but not the spatial shape. Works inside jit.

Raises:

Type Description
ValueError

f changed the spatial shape.

Example

import numpy as np t = (1, 0, 0, 0, -1, 0) g = GeoArray(np.full((2, 2), 9.0), t, None, dims="y x") g.map(np.sqrt).data[0, 0] np.float64(3.0)

Source code in packages/geotoolz-array/src/geoarray/_src/array.py
def map(self, f: Any) -> GeoArray:
    """Apply ``f`` to the data and keep the geometry.

    ``f`` may change the leading axes (a band index collapses bands)
    but not the spatial shape. Works inside ``jit``.

    Raises:
        ValueError: ``f`` changed the spatial shape.

    Example:
        >>> import numpy as np
        >>> t = (1, 0, 0, 0, -1, 0)
        >>> g = GeoArray(np.full((2, 2), 9.0), t, None, dims="y x")
        >>> g.map(np.sqrt).data[0, 0]
        np.float64(3.0)
    """
    out = f(self.data)
    if tuple(out.shape[-2:]) != tuple(self.data.shape[-2:]):
        raise ValueError(
            f"map must keep the spatial shape {tuple(self.data.shape[-2:])}, "
            f"got {tuple(out.shape[-2:])}; for a new grid use "
            "with_data(..., transform=)"
        )
    return self.with_data(out)

read_window(window, *, boundless=True)

The pixels of window: geoarray.read_window as a method.

With load, this makes a carrier a RasterSource, so code written for lazy readers takes a loaded carrier too.

Example

import numpy as np from geoarray import PixelWindow t = (20, 0, 0, 0, -20, 0) g = GeoArray(np.ones((4, 4)), t, 32613, 0.0, dims="y x") window = PixelWindow(col_off=2, row_off=2, width=4, height=4) g.read_window(window).shape (4, 4)

Source code in packages/geotoolz-array/src/geoarray/_src/array.py
def read_window(self, window: PixelWindow, *, boundless: bool = True) -> GeoArray:
    """The pixels of ``window``: `geoarray.read_window` as a method.

    With `load`, this makes a carrier a `RasterSource`, so code written
    for lazy readers takes a loaded carrier too.

    Example:
        >>> import numpy as np
        >>> from geoarray import PixelWindow
        >>> t = (20, 0, 0, 0, -20, 0)
        >>> g = GeoArray(np.ones((4, 4)), t, 32613, 0.0, dims="y x")
        >>> window = PixelWindow(col_off=2, row_off=2, width=4, height=4)
        >>> g.read_window(window).shape
        (4, 4)
    """
    from geoarray._src.geometry import read_window

    return read_window(self, window, boundless=boundless)

replace(**changes)

A copy with fields replaced (data, transform, dims, …).

Example

import numpy as np g = GeoArray(np.zeros((4, 4)), (1, 0, 0, 0, -1, 0), None, dims="y x") g.replace(fill_value=0).fill_value 0

Source code in packages/geotoolz-array/src/geoarray/_src/array.py
def replace(self, **changes: Any) -> GeoArray:
    """A copy with fields replaced (``data``, ``transform``, ``dims``, …).

    Example:
        >>> import numpy as np
        >>> g = GeoArray(np.zeros((4, 4)), (1, 0, 0, 0, -1, 0), None, dims="y x")
        >>> g.replace(fill_value=0).fill_value
        0
    """
    return dataclasses.replace(self, **changes)

sel(selection=None, **by_dim)

Select by exact label: g.sel(band="B12"), g.sel(band=["B8", "B4"]).

One label drops its dim; a list, a tuple or a 1-D array keeps it. Labels come from the dim's coordinate (labels).

Raises:

Type Description
LabelError

The dim has no labels or is spatial, a label is missing, or the value is a range (a slice): selection by value lives in xarray (to_xarray()).

KeyError

A name is not one of this carrier's dims.

Example

import numpy as np from geoarray.coords import SpectralAxis bands = SpectralAxis(names=("B4", "B8")) g = GeoArray(np.zeros((2, 4, 4)), (20, 0, 0, 0, -20, 0), 32613, ... dims="band y x", coords=(bands,)) g.sel(band="B8").dims ('y', 'x')

Source code in packages/geotoolz-array/src/geoarray/_src/array.py
def sel(self, selection: dict[str, Any] | None = None, **by_dim: Any) -> GeoArray:
    """Select by exact label: ``g.sel(band="B12")``, ``g.sel(band=["B8", "B4"])``.

    One label drops its dim; a list, a tuple or a 1-D array keeps it.
    Labels come from the dim's coordinate (`labels`).

    Raises:
        LabelError: The dim has no labels or is spatial, a label is
            missing, or the value is a range (a ``slice``): selection by
            value lives in xarray (``to_xarray()``).
        KeyError: A name is not one of this carrier's dims.

    Example:
        >>> import numpy as np
        >>> from geoarray.coords import SpectralAxis
        >>> bands = SpectralAxis(names=("B4", "B8"))
        >>> g = GeoArray(np.zeros((2, 4, 4)), (20, 0, 0, 0, -20, 0), 32613,
        ...              dims="band y x", coords=(bands,))
        >>> g.sel(band="B8").dims
        ('y', 'x')
    """
    wanted = {**(selection or {}), **by_dim}
    return select_labels(self, wanted)

shift_origin(delta)

Move the grid by delta = (Δx, Δy) in CRS units: c + Δx, f + Δy.

The pixels do not move; their georeferencing does. Differentiable, so jax.grad can find a sub-pixel co-registration shift.

Example

import numpy as np t = (20, 0, 600000, 0, -20, 3550000) g = GeoArray(np.zeros((2, 2)), t, 32613, dims="y x") g.shift_origin((7.3, 0.0)).transform[2] np.float64(600007.3)

Source code in packages/geotoolz-array/src/geoarray/_src/array.py
def shift_origin(self, delta: Any) -> GeoArray:
    """Move the grid by ``delta = (Δx, Δy)`` in CRS units: c + Δx, f + Δy.

    The pixels do not move; their georeferencing does. Differentiable,
    so ``jax.grad`` can find a sub-pixel co-registration shift.

    Example:
        >>> import numpy as np
        >>> t = (20, 0, 600000, 0, -20, 3550000)
        >>> g = GeoArray(np.zeros((2, 2)), t, 32613, dims="y x")
        >>> g.shift_origin((7.3, 0.0)).transform[2]
        np.float64(600007.3)
    """
    xp = namespace(self.transform)
    dx, dy = (
        xp.asarray(v, dtype=self.transform.dtype) for v in (delta[0], delta[1])
    )
    t = self.transform
    columns = (
        t[..., 0],
        t[..., 1],
        t[..., 2] + dx,
        t[..., 3],
        t[..., 4],
        t[..., 5] + dy,
    )
    return dataclasses.replace(self, transform=xp.stack(columns, axis=-1))

squeeze(axis=None)

Drop size-1 leading axes (all of them when axis is None).

The band axis of a (T, 1, H, W) stack stays unless time goes too: (T, H, W) would read as (C, H, W).

Raises:

Type Description
ValueError

axis names a spatial or batch axis.

Source code in packages/geotoolz-array/src/geoarray/_src/array.py
def squeeze(self, axis: int | tuple[int, ...] | None = None) -> GeoArray:
    """Drop size-1 leading axes (all of them when ``axis`` is ``None``).

    The band axis of a ``(T, 1, H, W)`` stack stays unless time goes
    too: ``(T, H, W)`` would read as ``(C, H, W)``.

    Raises:
        ValueError: ``axis`` names a spatial or batch axis.
    """
    n_batch = len(self.batch_shape)
    leading = range(n_batch, self.ndim - 2)
    dims = self.dims
    if axis is None:
        axes = tuple(i for i in leading if self.data.shape[i] == 1)
        names = {dims[i] for i in axes}
        if _drops_band_alone(dims, names):
            axes = tuple(i for i in axes if dims[i] != "band")
    else:
        requested = (axis,) if isinstance(axis, int) else tuple(axis)
        axes = tuple(i + self.ndim if i < 0 else i for i in requested)
        if any(i not in leading for i in axes):
            raise ValueError(f"squeeze: {axis} is not a leading, non-batch axis")
        if _drops_band_alone(dims, {dims[i] for i in axes}):
            raise ValueError(
                "squeeze: dropping the band axis of (T, 1, H, W) would leave "
                "(T, H, W), which reads as (C, H, W)"
            )
    kept = tuple(d for i, d in enumerate(dims) if i not in axes)
    return self.with_data(self.xp.squeeze(self.data, axis=axes), dims=kept)

to_jax(device=None)

This carrier with data and transform on a JAX device.

Parameters:

Name Type Description Default
device Any

A jax.Device; None is JAX's default device.

None

Raises:

Type Description
ImportError

JAX is not installed (geotoolz-array[jax]).

X64Error

jax_enable_x64 is off; the transform is float64.

Example

import jax import numpy as np jax.config.update("jax_enable_x64", True) data = np.zeros((4, 4), np.float32) g = GeoArray(data, (1, 0, 0, 0, -1, 0), None, dims="y x").to_jax() g.backend, str(g.dtype), str(g.transform.dtype) ('jax', 'float32', 'float64')

Source code in packages/geotoolz-array/src/geoarray/_src/array.py
def to_jax(self, device: Any = None) -> GeoArray:
    """This carrier with data and transform on a JAX device.

    Args:
        device: A ``jax.Device``; ``None`` is JAX's default device.

    Raises:
        ImportError: JAX is not installed (``geotoolz-array[jax]``).
        X64Error: ``jax_enable_x64`` is off; the transform is float64.

    Example:
        >>> import jax
        >>> import numpy as np
        >>> jax.config.update("jax_enable_x64", True)
        >>> data = np.zeros((4, 4), np.float32)
        >>> g = GeoArray(data, (1, 0, 0, 0, -1, 0), None, dims="y x").to_jax()
        >>> g.backend, str(g.dtype), str(g.transform.dtype)
        ('jax', 'float32', 'float64')
    """
    jax = import_jax()
    require_x64()
    stamps_on_host = any(
        isinstance(c, TimeAxis) and not is_jax_array(c.as_leaf())
        for c in self.coords
    )
    if self.backend == "jax" and device is None and not stamps_on_host:
        return self
    data = jax.device_put(self.data, device)
    transform = jax.device_put(self.transform, device)
    coords = coords_to_jax(self.coords, device)
    return GeoArray(
        data,
        transform,
        self.crs,
        self.fill_value,
        self.attrs,
        dims=self.dims,
        coords=coords,
    )

to_numpy()

This carrier with data and transform copied to NumPy on the host.

Raises:

Type Description
GeoArrayTraceError

Inside jit / grad / vmap.

Source code in packages/geotoolz-array/src/geoarray/_src/array.py
def to_numpy(self) -> GeoArray:
    """This carrier with data and transform copied to NumPy on the host.

    Raises:
        GeoArrayTraceError: Inside ``jit`` / ``grad`` / ``vmap``.
    """
    if self.backend == "numpy":
        return self
    if is_traced(self.data) or is_traced(self.transform):
        raise GeoArrayTraceError(
            "to_numpy needs concrete data, but this GeoArray is traced "
            "(inside jit / grad / vmap): call it outside the transform"
        )
    coords = coords_to_host(self.coords)
    return GeoArray(
        np.asarray(self.data),
        np.asarray(self.transform, dtype=np.float64),
        self.crs,
        self.fill_value,
        self.attrs,
        dims=self.dims,
        coords=coords,
    )

to_xarray()

This carrier as an xr.DataArray (geotoolz-array[xarray]).

Same dims and values; the CRS and the transform in a CF spatial_ref coordinate (crs_wkt, GeoTransform), x and y centre coordinates when axis-aligned, and each coordinate of geoarray.coords as CF coordinates. from_xarray reads it back exactly.

Raises:

Type Description
ImportError

xarray is not installed.

ValueError

The carrier is batched.

Source code in packages/geotoolz-array/src/geoarray/_src/array.py
def to_xarray(self) -> Any:
    """This carrier as an ``xr.DataArray`` (``geotoolz-array[xarray]``).

    Same dims and values; the CRS and the transform in a CF
    ``spatial_ref`` coordinate (``crs_wkt``, ``GeoTransform``), x and y
    centre coordinates when axis-aligned, and each coordinate of
    `geoarray.coords` as CF coordinates. `from_xarray` reads it back
    exactly.

    Raises:
        ImportError: xarray is not installed.
        ValueError: The carrier is batched.
    """
    return xarray_module().grid_to_xarray(self)

valid_mask(*, keep_time=False)

Which pixels hold data: (H, W) booleans, True where valid.

A pixel is valid when every entry there (over the non-batch, non-spatial dims) is finite and differs from the fill value (a NaN fill matches NaN). keep_time=True keeps a time dim, (T, H, W). Batch axes are kept. Works inside jit.

v_ij = ∧ₖ [isfinite(x_kij) ∧ x_kij ≠ φ]

Example

import numpy as np data = np.array([[[1.0, np.nan]], [[2.0, 3.0]]]) g = GeoArray(data, (1, 0, 0, 0, -1, 0), None, np.nan, dims="band y x") g.valid_mask().tolist() [[True, False]]

Source code in packages/geotoolz-array/src/geoarray/_src/array.py
def valid_mask(self, *, keep_time: bool = False) -> Any:
    """Which pixels hold data: ``(H, W)`` booleans, True where valid.

    A pixel is valid when every entry there (over the non-batch,
    non-spatial dims) is finite and differs from the fill value (a NaN
    fill matches NaN). ``keep_time=True`` keeps a ``time`` dim,
    ``(T, H, W)``. Batch axes are kept. Works inside ``jit``.

    v_ij = ∧ₖ [isfinite(x_kij) ∧ x_kij ≠ φ]

    Example:
        >>> import numpy as np
        >>> data = np.array([[[1.0, np.nan]], [[2.0, 3.0]]])
        >>> g = GeoArray(data, (1, 0, 0, 0, -1, 0), None, np.nan, dims="band y x")
        >>> g.valid_mask().tolist()
        [[True, False]]
    """
    xp = self.xp
    data = self.data
    floating = data.dtype.kind in "fc"
    invalid = ~xp.isfinite(data) if floating else xp.zeros(data.shape, dtype=bool)
    fill = self.fill_value
    if fill is not None and not (isinstance(fill, float) and math.isnan(fill)):
        invalid = invalid | (data == fill)
    n_batch = len(self.batch_shape)
    axes = tuple(
        i
        for i in range(n_batch, self.ndim - 2)
        if not (keep_time and self.dims[i] == "time")
    )
    return ~invalid.any(axis=axes) if axes else ~invalid

with_attrs(**items)

A copy with attrs added or replaced (see FrozenAttrs.set).

Source code in packages/geotoolz-array/src/geoarray/_src/array.py
def with_attrs(self, **items: Any) -> GeoArray:
    """A copy with attrs added or replaced (see `FrozenAttrs.set`)."""
    return dataclasses.replace(self, attrs=self.attrs.set(**items))

with_data(data, *, transform=None, fill_value=INHERIT, attrs=None, dims=None, coords=INHERIT)

A carrier with new data on this carrier's grid (or transform).

Parameters:

Name Type Description Default
data Any

The new (..., H, W) array.

required
transform Any

A new transform, for data on a new grid. When omitted, data must keep this carrier's spatial shape.

None
fill_value Any

The new fill; omitted keeps this carrier's.

INHERIT
attrs Any

New attrs; omitted keeps this carrier's, without the per-band keys when the band count changed.

None
dims Any

The new data's dims; omitted keeps this carrier's when the rank is unchanged, and drops leading dims when it fell.

None
coords Any

New coordinates; omitted keeps each of this carrier's whose dim survives with the same size.

INHERIT

Raises:

Type Description
ValueError

The spatial shape changed and no transform was given.

Example

import numpy as np t = (1, 0, 0, 0, -1, 0) g = GeoArray(np.ones((2, 4, 4)), t, None, dims="band y x") g.with_data(np.zeros((1, 4, 4), dtype=bool), fill_value=False).shape (1, 4, 4)

Source code in packages/geotoolz-array/src/geoarray/_src/array.py
def with_data(
    self,
    data: Any,
    *,
    transform: Any = None,
    fill_value: Any = INHERIT,
    attrs: Any = None,
    dims: Any = None,
    coords: Any = INHERIT,
) -> GeoArray:
    """A carrier with new data on this carrier's grid (or ``transform``).

    Args:
        data: The new ``(..., H, W)`` array.
        transform: A new transform, for data on a new grid. When omitted,
            ``data`` must keep this carrier's spatial shape.
        fill_value: The new fill; omitted keeps this carrier's.
        attrs: New attrs; omitted keeps this carrier's, without the
            per-band keys when the band count changed.
        dims: The new data's dims; omitted keeps this carrier's when the
            rank is unchanged, and drops leading dims when it fell.
        coords: New coordinates; omitted keeps each of this carrier's
            whose dim survives with the same size.

    Raises:
        ValueError: The spatial shape changed and no ``transform`` was
            given.

    Example:
        >>> import numpy as np
        >>> t = (1, 0, 0, 0, -1, 0)
        >>> g = GeoArray(np.ones((2, 4, 4)), t, None, dims="band y x")
        >>> g.with_data(np.zeros((1, 4, 4), dtype=bool), fill_value=False).shape
        (1, 4, 4)
    """
    if transform is None:
        if tuple(data.shape[-2:]) != tuple(self.data.shape[-2:]):
            raise ValueError(
                f"spatial shape changed from {tuple(self.data.shape[-2:])} to "
                f"{tuple(data.shape[-2:])}: pass transform= for data on a new grid"
            )
        transform = self.transform
    new_dims = self._dims_for(data, transform) if dims is None else dims
    if isinstance(new_dims, str):
        new_dims = tuple(new_dims.split())
    shape = tuple(data.shape)
    if coords is INHERIT:
        coords = tuple(
            c
            for c in self.coords
            if len(new_dims) == len(shape) and _keeps_coord(c, new_dims, shape)
        )
    if attrs is None:
        attrs = self.attrs
        band = (
            shape[new_dims.index("band")]
            if "band" in new_dims and len(new_dims) == len(shape)
            else 1
        )
        if band != self.count:
            attrs = drop_band_keys(attrs)
    return GeoArray(
        data,
        transform,
        self.crs,
        self.fill_value if fill_value is INHERIT else fill_value,
        attrs,
        dims=new_dims,
        coords=coords,
    )

geoarray.SPATIAL_DIMS = ('y', 'x') module-attribute

geoarray.DIMS = ('time', 'band', 'y', 'x') module-attribute

GeoSwath and GeoPoints

Carriers whose georeference is not an affine grid: per-pixel lat/lon on row col, and scattered samples on obs.

geoarray.GeoSwath dataclass

Bases: _Named

Data in sensor geometry: per-pixel lat/lon on the row col dims.

Rows run along track, columns across (EMIT, AVIRIS, TROPOMI L1B/L2). A model grid with fixed 2-D lat/lon (ORCA) is a swath too (GeoSwath.from_grid).

Parameters:

Name Type Description Default
data Any

(..., row, col), NumPy or JAX.

required
lat Any

(*batch, row, col) latitudes; batch are the leading dims of dims that index per-item geolocation (time for a series of granules), usually none.

required
lon Any

Longitudes, the shape of lat.

required
dims tuple[str, ...]

One name per axis, ending in ("row", "col").

cast(Any, None)
coords tuple[Coordinate, ...]

Coordinates of non-spatial dims (SpectralAxis, …).

()
crs CRS | None

The CRS of lat/lon; WGS 84 by default.

cast(Any, _WGS84)
fill_value Any

The nodata marker.

None
attrs FrozenAttrs

Whole-carrier metadata.

FrozenAttrs()

Raises:

Type Description
ValueError

The dims do not fit, or lat/lon do not match the data's (row, col) or each other.

Example

import numpy as np from geoarray.coords import SpectralAxis lat, lon = np.meshgrid(np.linspace(31, 32, 4), np.linspace(-104, -103, 5), ... indexing="ij") swath = GeoSwath(np.zeros((2, 4, 5)), lat, lon, dims="band row col", ... coords=(SpectralAxis(("b1", "b2")),)) swath.isel(row=slice(0, 2)).lat.shape (2, 5)

Source code in packages/geotoolz-array/src/geoarray/_src/carriers.py
@dataclasses.dataclass(frozen=True, eq=False, repr=False)
class GeoSwath(_Named):
    """Data in sensor geometry: per-pixel lat/lon on the ``row col`` dims.

    Rows run along track, columns across (EMIT, AVIRIS, TROPOMI L1B/L2).
    A model grid with fixed 2-D lat/lon (ORCA) is a swath too
    (`GeoSwath.from_grid`).

    Args:
        data: ``(..., row, col)``, NumPy or JAX.
        lat: ``(*batch, row, col)`` latitudes; ``batch`` are the leading dims
            of ``dims`` that index per-item geolocation (``time`` for a
            series of granules), usually none.
        lon: Longitudes, the shape of ``lat``.
        dims: One name per axis, ending in ``("row", "col")``.
        coords: Coordinates of non-spatial dims (`SpectralAxis`, …).
        crs: The CRS of lat/lon; WGS 84 by default.
        fill_value: The nodata marker.
        attrs: Whole-carrier metadata.

    Raises:
        ValueError: The dims do not fit, or lat/lon do not match the data's
            ``(row, col)`` or each other.

    Example:
        >>> import numpy as np
        >>> from geoarray.coords import SpectralAxis
        >>> lat, lon = np.meshgrid(np.linspace(31, 32, 4), np.linspace(-104, -103, 5),
        ...                        indexing="ij")
        >>> swath = GeoSwath(np.zeros((2, 4, 5)), lat, lon, dims="band row col",
        ...                  coords=(SpectralAxis(("b1", "b2")),))
        >>> swath.isel(row=slice(0, 2)).lat.shape
        (2, 5)
    """

    data: Any
    lat: Any
    lon: Any
    dims: tuple[str, ...] = dataclasses.field(default=cast(Any, None), kw_only=True)
    coords: tuple[Coordinate, ...] = dataclasses.field(default=(), kw_only=True)
    crs: pyproj.CRS | None = dataclasses.field(default=cast(Any, _WGS84), kw_only=True)
    fill_value: Any = dataclasses.field(default=None, kw_only=True)
    attrs: FrozenAttrs = dataclasses.field(default_factory=FrozenAttrs, kw_only=True)

    spatial_dims: ClassVar[tuple[str, ...]] = ("row", "col")

    def __class_getitem__(cls, item: Any) -> Any:
        """``GeoSwath["band row col"]``: the carrier annotated with a dims pattern."""
        return _subscript(cls, item)

    def __post_init__(self) -> None:
        backend = backend_of(self.data)
        lat = _float_leaf(self.lat, backend, "lat")
        lon = _float_leaf(self.lon, backend, "lon")
        if tuple(lat.shape) != tuple(lon.shape) or lat.ndim < 2:
            raise ValueError(
                f"lat and lon are (…, row, col) of one shape, got {tuple(lat.shape)} "
                f"and {tuple(lon.shape)}"
            )
        shape = tuple(self.data.shape)
        n_batch = lat.ndim - 2
        if shape[-2:] != tuple(lat.shape[-2:]) or shape[:n_batch] != tuple(
            lat.shape[:n_batch]
        ):
            raise ValueError(
                f"lat/lon {tuple(lat.shape)} do not match data {shape}: they have "
                "its (row, col) and its leading batch dims"
            )
        object.__setattr__(self, "lat", lat)
        object.__setattr__(self, "lon", lon)
        _init_named(self, n_batch, self.spatial_dims, "GeoSwath")

    @classmethod
    def from_grid(
        cls,
        data: Any,
        grid: CurvilinearGrid,
        *,
        dims: Any,
        coords: tuple[Coordinate, ...] = (),
        fill_value: Any = None,
        attrs: Any = None,
    ) -> GeoSwath:
        """A swath on a fixed curvilinear model grid (ORCA): lat/lon from ``grid``."""
        return cls(
            data,
            grid.lat,
            grid.lon,
            dims=dims,
            coords=coords,
            crs=grid.crs,
            fill_value=fill_value,
            attrs=FrozenAttrs(attrs or {}),
        )

    @property
    def batch_dims(self) -> tuple[str, ...]:
        """The leading dims lat/lon vary along (``()`` for one granule)."""
        return self.dims[: self.lat.ndim - 2]

    def isel(self, selection: dict[str, Any] | None = None, **by_dim: Any) -> GeoSwath:
        """Select by position; lat/lon are sliced with ``row``, ``col`` and batch dims.

        Raises:
            IndexError: An integer or a list on ``row`` / ``col`` (the result
                would not be a swath; index ``data`` for a profile).
        """
        wanted = {**(selection or {}), **by_dim}
        for d in self.spatial_dims:
            if d in wanted and not isinstance(wanted[d], slice):
                raise IndexError(
                    f"GeoSwath.isel: {d} takes a slice (an integer or a list would "
                    "not leave a swath); use the adapter or .data for profiles"
                )
        data, dims, coords, attrs, key = self._leading_index(wanted)
        n_batch = self.lat.ndim - 2
        geo_key = key[:n_batch] + key[-2:]
        return GeoSwath(
            data,
            self.lat[geo_key],
            self.lon[geo_key],
            dims=dims,
            coords=coords,
            crs=self.crs,
            fill_value=self.fill_value,
            attrs=attrs,
        )

    def with_data(
        self, data: Any, *, dims: Any = None, fill_value: Any = ..., attrs: Any = None
    ) -> GeoSwath:
        """New data on this swath's geolocation (same ``row``, ``col``)."""
        new_dims = self.dims if dims is None else dims
        if isinstance(new_dims, str):
            new_dims = tuple(new_dims.split())
        shape = tuple(data.shape)
        coords = tuple(
            c
            for c in self.coords
            if c.dim in new_dims and shape[new_dims.index(c.dim)] == c.size
        )
        return GeoSwath(
            data,
            self.lat,
            self.lon,
            dims=new_dims,
            coords=coords,
            crs=self.crs,
            fill_value=self.fill_value if fill_value is ... else fill_value,
            attrs=self.attrs if attrs is None else attrs,
        )

    def to_jax(self, device: Any = None) -> GeoSwath:
        """Data and lat/lon on a JAX device (needs ``jax_enable_x64``)."""
        jax = import_jax()
        require_x64()
        return dataclasses.replace(
            self,
            data=jax.device_put(self.data, device),
            lat=jax.device_put(self.lat, device),
            lon=jax.device_put(self.lon, device),
            coords=coords_to_jax(self.coords, device),
        )

    def to_numpy(self) -> GeoSwath:
        """Data and lat/lon on the host."""
        return dataclasses.replace(
            self,
            data=_host(self.data, "to_numpy"),
            lat=_host(self.lat, "to_numpy"),
            lon=_host(self.lon, "to_numpy"),
            coords=coords_to_host(self.coords),
        )

    def __array__(self, dtype: Any = None, copy: bool | None = None) -> np.ndarray:
        """The data as a NumPy array (a host copy for JAX data)."""
        out = _host(self.data, "np.asarray(GeoSwath)")
        if self.backend == "jax":
            report_move("np.asarray(GeoSwath)", "JAX data copied to the host")
        return np.array(out, dtype=dtype, copy=True) if copy else np.asarray(out, dtype)

    def to_xarray(self) -> Any:
        """This carrier as a ``DataArray`` with 2-D lat/lon (``[xarray]``)."""
        return xarray_module().swath_to_xarray(self)

    @classmethod
    def from_xarray(cls, obj: Any) -> GeoSwath:
        """A ``DataArray`` with 2-D lat/lon as a `GeoSwath` (see `to_xarray`)."""
        return xarray_module().swath_from_xarray(obj)

    def identical(self, other: object) -> bool:
        """Equal data, lat/lon (NaN-aware), dims, coords, CRS, fill and attrs."""
        if not isinstance(other, GeoSwath):
            return False
        return (
            _same_array(self.data, other.data)
            and _same_array(self.lat, other.lat)
            and _same_array(self.lon, other.lon)
            and self._identical_static(other)
        )

    def __repr__(self) -> str:
        return (
            f"GeoSwath({self.backend} {self.dtype} {self.shape}, "
            f"crs={_crs_label(self.crs)}, fill_value={self.fill_value!r}, "
            f"attrs={tuple(self.attrs)}, dims={self.dims})"
        )

batch_dims property

The leading dims lat/lon vary along (() for one granule).

__array__(dtype=None, copy=None)

The data as a NumPy array (a host copy for JAX data).

Source code in packages/geotoolz-array/src/geoarray/_src/carriers.py
def __array__(self, dtype: Any = None, copy: bool | None = None) -> np.ndarray:
    """The data as a NumPy array (a host copy for JAX data)."""
    out = _host(self.data, "np.asarray(GeoSwath)")
    if self.backend == "jax":
        report_move("np.asarray(GeoSwath)", "JAX data copied to the host")
    return np.array(out, dtype=dtype, copy=True) if copy else np.asarray(out, dtype)

__class_getitem__(item)

GeoSwath["band row col"]: the carrier annotated with a dims pattern.

Source code in packages/geotoolz-array/src/geoarray/_src/carriers.py
def __class_getitem__(cls, item: Any) -> Any:
    """``GeoSwath["band row col"]``: the carrier annotated with a dims pattern."""
    return _subscript(cls, item)

from_grid(data, grid, *, dims, coords=(), fill_value=None, attrs=None) classmethod

A swath on a fixed curvilinear model grid (ORCA): lat/lon from grid.

Source code in packages/geotoolz-array/src/geoarray/_src/carriers.py
@classmethod
def from_grid(
    cls,
    data: Any,
    grid: CurvilinearGrid,
    *,
    dims: Any,
    coords: tuple[Coordinate, ...] = (),
    fill_value: Any = None,
    attrs: Any = None,
) -> GeoSwath:
    """A swath on a fixed curvilinear model grid (ORCA): lat/lon from ``grid``."""
    return cls(
        data,
        grid.lat,
        grid.lon,
        dims=dims,
        coords=coords,
        crs=grid.crs,
        fill_value=fill_value,
        attrs=FrozenAttrs(attrs or {}),
    )

from_xarray(obj) classmethod

A DataArray with 2-D lat/lon as a GeoSwath (see to_xarray).

Source code in packages/geotoolz-array/src/geoarray/_src/carriers.py
@classmethod
def from_xarray(cls, obj: Any) -> GeoSwath:
    """A ``DataArray`` with 2-D lat/lon as a `GeoSwath` (see `to_xarray`)."""
    return xarray_module().swath_from_xarray(obj)

identical(other)

Equal data, lat/lon (NaN-aware), dims, coords, CRS, fill and attrs.

Source code in packages/geotoolz-array/src/geoarray/_src/carriers.py
def identical(self, other: object) -> bool:
    """Equal data, lat/lon (NaN-aware), dims, coords, CRS, fill and attrs."""
    if not isinstance(other, GeoSwath):
        return False
    return (
        _same_array(self.data, other.data)
        and _same_array(self.lat, other.lat)
        and _same_array(self.lon, other.lon)
        and self._identical_static(other)
    )

isel(selection=None, **by_dim)

Select by position; lat/lon are sliced with row, col and batch dims.

Raises:

Type Description
IndexError

An integer or a list on row / col (the result would not be a swath; index data for a profile).

Source code in packages/geotoolz-array/src/geoarray/_src/carriers.py
def isel(self, selection: dict[str, Any] | None = None, **by_dim: Any) -> GeoSwath:
    """Select by position; lat/lon are sliced with ``row``, ``col`` and batch dims.

    Raises:
        IndexError: An integer or a list on ``row`` / ``col`` (the result
            would not be a swath; index ``data`` for a profile).
    """
    wanted = {**(selection or {}), **by_dim}
    for d in self.spatial_dims:
        if d in wanted and not isinstance(wanted[d], slice):
            raise IndexError(
                f"GeoSwath.isel: {d} takes a slice (an integer or a list would "
                "not leave a swath); use the adapter or .data for profiles"
            )
    data, dims, coords, attrs, key = self._leading_index(wanted)
    n_batch = self.lat.ndim - 2
    geo_key = key[:n_batch] + key[-2:]
    return GeoSwath(
        data,
        self.lat[geo_key],
        self.lon[geo_key],
        dims=dims,
        coords=coords,
        crs=self.crs,
        fill_value=self.fill_value,
        attrs=attrs,
    )

to_jax(device=None)

Data and lat/lon on a JAX device (needs jax_enable_x64).

Source code in packages/geotoolz-array/src/geoarray/_src/carriers.py
def to_jax(self, device: Any = None) -> GeoSwath:
    """Data and lat/lon on a JAX device (needs ``jax_enable_x64``)."""
    jax = import_jax()
    require_x64()
    return dataclasses.replace(
        self,
        data=jax.device_put(self.data, device),
        lat=jax.device_put(self.lat, device),
        lon=jax.device_put(self.lon, device),
        coords=coords_to_jax(self.coords, device),
    )

to_numpy()

Data and lat/lon on the host.

Source code in packages/geotoolz-array/src/geoarray/_src/carriers.py
def to_numpy(self) -> GeoSwath:
    """Data and lat/lon on the host."""
    return dataclasses.replace(
        self,
        data=_host(self.data, "to_numpy"),
        lat=_host(self.lat, "to_numpy"),
        lon=_host(self.lon, "to_numpy"),
        coords=coords_to_host(self.coords),
    )

to_xarray()

This carrier as a DataArray with 2-D lat/lon ([xarray]).

Source code in packages/geotoolz-array/src/geoarray/_src/carriers.py
def to_xarray(self) -> Any:
    """This carrier as a ``DataArray`` with 2-D lat/lon (``[xarray]``)."""
    return xarray_module().swath_to_xarray(self)

with_data(data, *, dims=None, fill_value=..., attrs=None)

New data on this swath's geolocation (same row, col).

Source code in packages/geotoolz-array/src/geoarray/_src/carriers.py
def with_data(
    self, data: Any, *, dims: Any = None, fill_value: Any = ..., attrs: Any = None
) -> GeoSwath:
    """New data on this swath's geolocation (same ``row``, ``col``)."""
    new_dims = self.dims if dims is None else dims
    if isinstance(new_dims, str):
        new_dims = tuple(new_dims.split())
    shape = tuple(data.shape)
    coords = tuple(
        c
        for c in self.coords
        if c.dim in new_dims and shape[new_dims.index(c.dim)] == c.size
    )
    return GeoSwath(
        data,
        self.lat,
        self.lon,
        dims=new_dims,
        coords=coords,
        crs=self.crs,
        fill_value=self.fill_value if fill_value is ... else fill_value,
        attrs=self.attrs if attrs is None else attrs,
    )

geoarray.GeoPoints dataclass

Bases: _Named

Scattered samples on the obs dim: positions, optional z, time, valid.

  • xy — (obs, 2) positions in crs (lon, lat for WGS 84).
  • z — (obs,) vertical positions, described by vertical (height, depth or pressure: never a third column of xy).
  • time — (obs,) per-point times, for moving platforms (along-track altimetry, Argo). Shared times are a time dim with a TimeAxis instead; both together raise.
  • valid — (obs,) booleans, False on padding (pad_points).

Parameters:

Name Type Description Default
data Any

(..., obs) values, NumPy or JAX.

required
xy Any

(obs, 2) positions.

required
z Any

Optional (obs,) vertical positions; needs vertical.

None
vertical Vertical | None

What z measures (geoarray.coords.Vertical).

None
time Any

Optional (obs,) times (datetime64 or int64 ns).

None
valid Any

Optional (obs,) booleans; omitted means all valid.

None
dims tuple[str, ...]

One name per axis, ending in "obs".

cast(Any, None)
coords tuple[Coordinate, ...]

Coordinates of non-spatial dims (VariableAxis, …).

()
crs CRS | None

The CRS of xy; WGS 84 by default.

cast(Any, _WGS84)
fill_value Any

The nodata marker.

None
attrs FrozenAttrs

Whole-carrier metadata.

FrozenAttrs()
Example

import numpy as np from geoarray.coords import VariableAxis, Vertical depth = Vertical(kind="depth", units="m", positive="down") cycle = GeoPoints( ... np.zeros((2, 3)), xy=np.zeros((3, 2)), z=[5.0, 10.0, 20.0], ... vertical=depth, dims="variable obs", ... coords=(VariableAxis(("temp", "psal"), ("degC", "1")),), ... ) cycle.isel(obs=[2]).z.tolist() [20.0]

Source code in packages/geotoolz-array/src/geoarray/_src/carriers.py
@dataclasses.dataclass(frozen=True, eq=False, repr=False)
class GeoPoints(_Named):
    """Scattered samples on the ``obs`` dim: positions, optional z, time, valid.

    - **xy** — ``(obs, 2)`` positions in ``crs`` (lon, lat for WGS 84).
    - **z** — ``(obs,)`` vertical positions, described by ``vertical``
      (height, depth or pressure: never a third column of xy).
    - **time** — ``(obs,)`` per-point times, for moving platforms
      (along-track altimetry, Argo). Shared times are a ``time`` dim with a
      `TimeAxis` instead; both together raise.
    - **valid** — ``(obs,)`` booleans, False on padding (`pad_points`).

    Args:
        data: ``(..., obs)`` values, NumPy or JAX.
        xy: ``(obs, 2)`` positions.
        z: Optional ``(obs,)`` vertical positions; needs ``vertical``.
        vertical: What ``z`` measures (`geoarray.coords.Vertical`).
        time: Optional ``(obs,)`` times (``datetime64`` or ``int64`` ns).
        valid: Optional ``(obs,)`` booleans; omitted means all valid.
        dims: One name per axis, ending in ``"obs"``.
        coords: Coordinates of non-spatial dims (`VariableAxis`, …).
        crs: The CRS of xy; WGS 84 by default.
        fill_value: The nodata marker.
        attrs: Whole-carrier metadata.

    Example:
        >>> import numpy as np
        >>> from geoarray.coords import VariableAxis, Vertical
        >>> depth = Vertical(kind="depth", units="m", positive="down")
        >>> cycle = GeoPoints(
        ...     np.zeros((2, 3)), xy=np.zeros((3, 2)), z=[5.0, 10.0, 20.0],
        ...     vertical=depth, dims="variable obs",
        ...     coords=(VariableAxis(("temp", "psal"), ("degC", "1")),),
        ... )
        >>> cycle.isel(obs=[2]).z.tolist()
        [20.0]
    """

    data: Any
    xy: Any
    z: Any = dataclasses.field(default=None, kw_only=True)
    vertical: Vertical | None = dataclasses.field(default=None, kw_only=True)
    time: Any = dataclasses.field(default=None, kw_only=True)
    valid: Any = dataclasses.field(default=None, kw_only=True)
    dims: tuple[str, ...] = dataclasses.field(default=cast(Any, None), kw_only=True)
    coords: tuple[Coordinate, ...] = dataclasses.field(default=(), kw_only=True)
    crs: pyproj.CRS | None = dataclasses.field(default=cast(Any, _WGS84), kw_only=True)
    fill_value: Any = dataclasses.field(default=None, kw_only=True)
    attrs: FrozenAttrs = dataclasses.field(default_factory=FrozenAttrs, kw_only=True)

    spatial_dims: ClassVar[tuple[str, ...]] = ("obs",)

    def __class_getitem__(cls, item: Any) -> Any:
        """``GeoPoints["variable obs"]``: the carrier annotated with a dims pattern."""
        return _subscript(cls, item)

    def __post_init__(self) -> None:
        backend = backend_of(self.data)
        n = int(self.data.shape[-1]) if self.data.ndim else 0
        xy = _float_leaf(self.xy, backend, "xy")
        if tuple(xy.shape) != (n, 2):
            raise ValueError(f"xy is (obs, 2) = ({n}, 2), got {tuple(xy.shape)}")
        object.__setattr__(self, "xy", xy)
        if self.z is not None:
            if self.vertical is None:
                raise ValueError(
                    "z needs vertical= (height, depth or pressure differ in units and "
                    "direction)"
                )
            z = _float_leaf(self.z, backend, "z")
            if tuple(z.shape) != (n,):
                raise ValueError(f"z is (obs,) = ({n},), got {tuple(z.shape)}")
            object.__setattr__(self, "z", z)
        elif self.vertical is not None:
            raise ValueError("vertical= describes z, but no z was given")
        if self.time is not None:
            time = _time_leaf(self.time, backend)
            if tuple(time.shape) != (n,):
                raise ValueError(f"time is (obs,) = ({n},), got {tuple(time.shape)}")
            object.__setattr__(self, "time", time)
        if self.valid is not None:
            valid = self.valid
            if not is_traced(valid):
                valid = namespace(self.data).asarray(valid, dtype=bool)
            if tuple(valid.shape) != (n,):
                raise ValueError(f"valid is (obs,) = ({n},), got {tuple(valid.shape)}")
            object.__setattr__(self, "valid", valid)
        _init_named(self, 0, self.spatial_dims, "GeoPoints")
        if self.time is not None and "time" in self.dims:
            raise ValueError(
                "a time dim and a per-point time leaf together: shared times are "
                "a time dim (TimeAxis), one time per point is the time leaf"
            )

    @property
    def size(self) -> int:
        """N, the number of samples."""
        return int(self.data.shape[-1])

    @property
    def batch_dims(self) -> tuple[str, ...]:
        """``()``: the leaves of a point set do not vary along other dims."""
        return ()

    def _leaves(self) -> dict[str, Any]:
        return {
            k: getattr(self, k)
            for k in ("xy", "z", "time", "valid")
            if getattr(self, k) is not None
        }

    def isel(self, selection: dict[str, Any] | None = None, **by_dim: Any) -> GeoPoints:
        """Select by position; ``obs`` slices xy, z, time and valid together.

        Raises:
            IndexError: An integer on ``obs`` (the result would not be a point
                set; take ``[k]`` to keep one point).
        """
        wanted = {**(selection or {}), **by_dim}
        k = wanted.get("obs", slice(None))
        if isinstance(k, int | np.integer):
            raise IndexError(
                "GeoPoints.isel: an integer on obs would not leave a point set; "
                "take obs=[k]"
            )
        if is_traced(k):
            raise GeoArrayTraceError("an obs index must be concrete")
        data, dims, coords, attrs, _ = self._leading_index(wanted)
        leaves = {name: leaf[k] for name, leaf in self._leaves().items()}
        return GeoPoints(
            data,
            leaves.pop("xy"),
            **leaves,
            vertical=self.vertical,
            dims=dims,
            coords=coords,
            crs=self.crs,
            fill_value=self.fill_value,
            attrs=attrs,
        )

    def with_data(
        self, data: Any, *, dims: Any = None, fill_value: Any = ..., attrs: Any = None
    ) -> GeoPoints:
        """New values at these samples (same ``obs``)."""
        new_dims = self.dims if dims is None else dims
        if isinstance(new_dims, str):
            new_dims = tuple(new_dims.split())
        shape = tuple(data.shape)
        coords = tuple(
            c
            for c in self.coords
            if c.dim in new_dims and shape[new_dims.index(c.dim)] == c.size
        )
        leaves = self._leaves()
        return GeoPoints(
            data,
            leaves.pop("xy"),
            **leaves,
            vertical=self.vertical,
            dims=new_dims,
            coords=coords,
            crs=self.crs,
            fill_value=self.fill_value if fill_value is ... else fill_value,
            attrs=self.attrs if attrs is None else attrs,
        )

    def valid_mask(self) -> Any:
        """``(obs,)`` True where a point holds data: valid, finite, not the fill."""
        xp = self.xp
        data = self.data
        bad = (
            ~xp.isfinite(data)
            if data.dtype.kind in "fc"
            else xp.zeros(data.shape, bool)
        )
        fill = self.fill_value
        if fill is not None and not (isinstance(fill, float) and math.isnan(fill)):
            bad = bad | (data == fill)
        axes = tuple(range(self.ndim - 1))
        ok = ~bad.any(axis=axes) if axes else ~bad
        return ok if self.valid is None else ok & self.valid

    def to_jax(self, device: Any = None) -> GeoPoints:
        """Data and leaves on a JAX device; times as ``int64`` ns."""
        jax = import_jax()
        require_x64()
        moved = {k: _to_jax_leaf(v, device) for k, v in self._leaves().items()}
        return dataclasses.replace(
            self,
            data=jax.device_put(self.data, device),
            coords=coords_to_jax(self.coords, device),
            **moved,
        )

    def to_numpy(self) -> GeoPoints:
        """Data and leaves on the host; times as ``datetime64[ns]``."""
        moved = {k: _host(v, "to_numpy") for k, v in self._leaves().items()}
        if "time" in moved and moved["time"].dtype.kind != "M":
            moved["time"] = moved["time"].astype(np.int64).view("datetime64[ns]")
        return dataclasses.replace(
            self,
            data=_host(self.data, "to_numpy"),
            coords=coords_to_host(self.coords),
            **moved,
        )

    def __array__(self, dtype: Any = None, copy: bool | None = None) -> np.ndarray:
        """The values as a NumPy array (a host copy for JAX data)."""
        out = _host(self.data, "np.asarray(GeoPoints)")
        if self.backend == "jax":
            report_move("np.asarray(GeoPoints)", "JAX data copied to the host")
        return np.array(out, dtype=dtype, copy=True) if copy else np.asarray(out, dtype)

    def to_xarray(self) -> Any:
        """This carrier as a CF DSG ``Dataset`` on ``obs`` (``[xarray]``)."""
        return xarray_module().points_to_xarray(self)

    @classmethod
    def from_xarray(cls, obj: Any) -> GeoPoints:
        """A CF DSG ``Dataset`` on ``obs`` as a `GeoPoints` (see `to_xarray`)."""
        return xarray_module().points_from_xarray(obj)

    def identical(self, other: object) -> bool:
        """Equal values and leaves (NaN-aware), vertical and static fields."""
        if not isinstance(other, GeoPoints):
            return False
        mine, theirs = self.to_numpy(), other.to_numpy()
        return (
            _same_array(mine.data, theirs.data)
            and all(
                _same_array(getattr(mine, k), getattr(theirs, k))
                for k in ("xy", "z", "time", "valid")
            )
            and self.vertical == other.vertical
            and self._identical_static(other)
        )

    def __repr__(self) -> str:
        extra = [k for k in ("z", "time", "valid") if getattr(self, k) is not None]
        return (
            f"GeoPoints({self.backend} {self.dtype} {self.shape}, "
            f"crs={_crs_label(self.crs)}, leaves=xy{''.join(', ' + k for k in extra)}, "
            f"fill_value={self.fill_value!r}, dims={self.dims})"
        )

batch_dims property

(): the leaves of a point set do not vary along other dims.

size property

N, the number of samples.

__array__(dtype=None, copy=None)

The values as a NumPy array (a host copy for JAX data).

Source code in packages/geotoolz-array/src/geoarray/_src/carriers.py
def __array__(self, dtype: Any = None, copy: bool | None = None) -> np.ndarray:
    """The values as a NumPy array (a host copy for JAX data)."""
    out = _host(self.data, "np.asarray(GeoPoints)")
    if self.backend == "jax":
        report_move("np.asarray(GeoPoints)", "JAX data copied to the host")
    return np.array(out, dtype=dtype, copy=True) if copy else np.asarray(out, dtype)

__class_getitem__(item)

GeoPoints["variable obs"]: the carrier annotated with a dims pattern.

Source code in packages/geotoolz-array/src/geoarray/_src/carriers.py
def __class_getitem__(cls, item: Any) -> Any:
    """``GeoPoints["variable obs"]``: the carrier annotated with a dims pattern."""
    return _subscript(cls, item)

from_xarray(obj) classmethod

A CF DSG Dataset on obs as a GeoPoints (see to_xarray).

Source code in packages/geotoolz-array/src/geoarray/_src/carriers.py
@classmethod
def from_xarray(cls, obj: Any) -> GeoPoints:
    """A CF DSG ``Dataset`` on ``obs`` as a `GeoPoints` (see `to_xarray`)."""
    return xarray_module().points_from_xarray(obj)

identical(other)

Equal values and leaves (NaN-aware), vertical and static fields.

Source code in packages/geotoolz-array/src/geoarray/_src/carriers.py
def identical(self, other: object) -> bool:
    """Equal values and leaves (NaN-aware), vertical and static fields."""
    if not isinstance(other, GeoPoints):
        return False
    mine, theirs = self.to_numpy(), other.to_numpy()
    return (
        _same_array(mine.data, theirs.data)
        and all(
            _same_array(getattr(mine, k), getattr(theirs, k))
            for k in ("xy", "z", "time", "valid")
        )
        and self.vertical == other.vertical
        and self._identical_static(other)
    )

isel(selection=None, **by_dim)

Select by position; obs slices xy, z, time and valid together.

Raises:

Type Description
IndexError

An integer on obs (the result would not be a point set; take [k] to keep one point).

Source code in packages/geotoolz-array/src/geoarray/_src/carriers.py
def isel(self, selection: dict[str, Any] | None = None, **by_dim: Any) -> GeoPoints:
    """Select by position; ``obs`` slices xy, z, time and valid together.

    Raises:
        IndexError: An integer on ``obs`` (the result would not be a point
            set; take ``[k]`` to keep one point).
    """
    wanted = {**(selection or {}), **by_dim}
    k = wanted.get("obs", slice(None))
    if isinstance(k, int | np.integer):
        raise IndexError(
            "GeoPoints.isel: an integer on obs would not leave a point set; "
            "take obs=[k]"
        )
    if is_traced(k):
        raise GeoArrayTraceError("an obs index must be concrete")
    data, dims, coords, attrs, _ = self._leading_index(wanted)
    leaves = {name: leaf[k] for name, leaf in self._leaves().items()}
    return GeoPoints(
        data,
        leaves.pop("xy"),
        **leaves,
        vertical=self.vertical,
        dims=dims,
        coords=coords,
        crs=self.crs,
        fill_value=self.fill_value,
        attrs=attrs,
    )

to_jax(device=None)

Data and leaves on a JAX device; times as int64 ns.

Source code in packages/geotoolz-array/src/geoarray/_src/carriers.py
def to_jax(self, device: Any = None) -> GeoPoints:
    """Data and leaves on a JAX device; times as ``int64`` ns."""
    jax = import_jax()
    require_x64()
    moved = {k: _to_jax_leaf(v, device) for k, v in self._leaves().items()}
    return dataclasses.replace(
        self,
        data=jax.device_put(self.data, device),
        coords=coords_to_jax(self.coords, device),
        **moved,
    )

to_numpy()

Data and leaves on the host; times as datetime64[ns].

Source code in packages/geotoolz-array/src/geoarray/_src/carriers.py
def to_numpy(self) -> GeoPoints:
    """Data and leaves on the host; times as ``datetime64[ns]``."""
    moved = {k: _host(v, "to_numpy") for k, v in self._leaves().items()}
    if "time" in moved and moved["time"].dtype.kind != "M":
        moved["time"] = moved["time"].astype(np.int64).view("datetime64[ns]")
    return dataclasses.replace(
        self,
        data=_host(self.data, "to_numpy"),
        coords=coords_to_host(self.coords),
        **moved,
    )

to_xarray()

This carrier as a CF DSG Dataset on obs ([xarray]).

Source code in packages/geotoolz-array/src/geoarray/_src/carriers.py
def to_xarray(self) -> Any:
    """This carrier as a CF DSG ``Dataset`` on ``obs`` (``[xarray]``)."""
    return xarray_module().points_to_xarray(self)

valid_mask()

(obs,) True where a point holds data: valid, finite, not the fill.

Source code in packages/geotoolz-array/src/geoarray/_src/carriers.py
def valid_mask(self) -> Any:
    """``(obs,)`` True where a point holds data: valid, finite, not the fill."""
    xp = self.xp
    data = self.data
    bad = (
        ~xp.isfinite(data)
        if data.dtype.kind in "fc"
        else xp.zeros(data.shape, bool)
    )
    fill = self.fill_value
    if fill is not None and not (isinstance(fill, float) and math.isnan(fill)):
        bad = bad | (data == fill)
    axes = tuple(range(self.ndim - 1))
    ok = ~bad.any(axis=axes) if axes else ~bad
    return ok if self.valid is None else ok & self.valid

with_data(data, *, dims=None, fill_value=..., attrs=None)

New values at these samples (same obs).

Source code in packages/geotoolz-array/src/geoarray/_src/carriers.py
def with_data(
    self, data: Any, *, dims: Any = None, fill_value: Any = ..., attrs: Any = None
) -> GeoPoints:
    """New values at these samples (same ``obs``)."""
    new_dims = self.dims if dims is None else dims
    if isinstance(new_dims, str):
        new_dims = tuple(new_dims.split())
    shape = tuple(data.shape)
    coords = tuple(
        c
        for c in self.coords
        if c.dim in new_dims and shape[new_dims.index(c.dim)] == c.size
    )
    leaves = self._leaves()
    return GeoPoints(
        data,
        leaves.pop("xy"),
        **leaves,
        vertical=self.vertical,
        dims=new_dims,
        coords=coords,
        crs=self.crs,
        fill_value=self.fill_value if fill_value is ... else fill_value,
        attrs=self.attrs if attrs is None else attrs,
    )

geoarray.pad_points(points, n)

points padded to n samples, with valid=False on the pad.

Pad points sit at the first point's position (finite, so gradients through a sampling operator stay finite), carry the fill value (NaN for float data without one) and time / z of the first point. A cost that masks with valid is then unchanged by the pad length (GA-G16).

Raises:

Type Description
ValueError

n is smaller than the number of samples, or there are none to copy a position from.

Example

import numpy as np p = GeoPoints(np.ones(3), xy=np.zeros((3, 2)), dims="obs") padded = pad_points(p, 5) padded.size, padded.valid.tolist() (5, [True, True, True, False, False])

Source code in packages/geotoolz-array/src/geoarray/_src/carriers.py
def pad_points(points: GeoPoints, n: int) -> GeoPoints:
    """``points`` padded to ``n`` samples, with ``valid=False`` on the pad.

    Pad points sit at the first point's position (finite, so gradients
    through a sampling operator stay finite), carry the fill value (NaN for
    float data without one) and time / z of the first point. A cost that
    masks with ``valid`` is then unchanged by the pad length (GA-G16).

    Raises:
        ValueError: ``n`` is smaller than the number of samples, or there
            are none to copy a position from.

    Example:
        >>> import numpy as np
        >>> p = GeoPoints(np.ones(3), xy=np.zeros((3, 2)), dims="obs")
        >>> padded = pad_points(p, 5)
        >>> padded.size, padded.valid.tolist()
        (5, [True, True, True, False, False])
    """
    have = points.size
    if n < have:
        raise ValueError(f"pad_points: n={n} is smaller than the {have} samples")
    if have == 0:
        raise ValueError("pad_points needs at least one point to place the pad")
    xp = points.xp
    extra = n - have
    fill = points.fill_value
    if fill is None:
        if points.dtype.kind not in "fc":
            raise ValueError(
                "pad_points: integer values need a fill_value for the padded samples"
            )
        fill = math.nan
    lead = points.shape[:-1]
    data = xp.concatenate(
        [points.data, xp.full((*lead, extra), fill, points.dtype)], -1
    )

    def repeat_first(leaf: Any) -> Any:
        lx = namespace(leaf) if not isinstance(leaf, np.ndarray) else np
        reps = lx.repeat(leaf[:1], extra, axis=0)
        return lx.concatenate([leaf, reps], axis=0)

    valid = points.valid if points.valid is not None else xp.ones(have, dtype=bool)
    leaves = {
        "xy": repeat_first(points.xy),
        "z": None if points.z is None else repeat_first(points.z),
        "time": None if points.time is None else repeat_first(points.time),
        "valid": xp.concatenate([valid, xp.zeros(extra, dtype=bool)]),
    }
    return GeoPoints(
        data,
        leaves.pop("xy"),
        **leaves,
        vertical=points.vertical,
        dims=points.dims,
        coords=points.coords,
        crs=points.crs,
        fill_value=fill,
        attrs=points.attrs,
    )

geoarray.to_geoswath(f, grid, *, crs='EPSG:4326', coords=(), fill_value=None, attrs=None)

A cell-centred model field on a latitude-longitude grid as a GeoSwath.

The grid's y and x become row and col, the ghost ring is dropped, and every pixel gets the latitude and longitude of its cell centre, in degrees. The values are not touched.

Parameters:

Name Type Description Default
f Any

A field with data, named dims ("y" and "x" among them) and a stagger that is empty at the cell centres, such as a gridax.CField.

required
grid Any

The grid of the field: its ghost width, and coords("y", at="T") and coords("x", at="T") in radians on a sphere of radius R (gridax's spherical grids), or 2-D lat_T and lon_T in radians.

required
crs Any

The CRS of the latitudes and longitudes.

'EPSG:4326'
coords tuple[Coordinate, ...]

Coordinates of the other dims of the result.

()
fill_value Any

The nodata marker.

None
attrs Any

Whole-carrier metadata.

None

Returns:

Type Description
GeoSwath

The interior of the field, (..., row, col); the other dims keep

GeoSwath

their order.

Raises:

Type Description
ValueError

The field is not at the cell centres, has no y or x dim, or its (y, x) do not match the grid.

TypeError

The grid has no latitudes and longitudes.

Example

import numpy as np from types import SimpleNamespace y, x = np.deg2rad([9.0, 10.0, 11.0, 12.0]), np.deg2rad([-1.0, 0.0, 1.0]) grid = SimpleNamespace( ... ghost=1, R=6.371e6, coords=lambda axis, at: {"y": y, "x": x}[axis] ... ) h = SimpleNamespace(data=np.ones((4, 3)), dims=("y", "x"), stagger=()) swath = to_geoswath(h, grid) swath.dims, np.round(swath.lat[:, 0], 6).tolist() (('row', 'col'), [10.0, 11.0])

Source code in packages/geotoolz-array/src/geoarray/_src/model.py
def to_geoswath(
    f: Any,
    grid: Any,
    *,
    crs: Any = "EPSG:4326",
    coords: tuple[Coordinate, ...] = (),
    fill_value: Any = None,
    attrs: Any = None,
) -> GeoSwath:
    """A cell-centred model field on a latitude-longitude grid as a `GeoSwath`.

    The grid's ``y`` and ``x`` become ``row`` and ``col``, the ghost ring is
    dropped, and every pixel gets the latitude and longitude of its cell
    centre, in degrees. The values are not touched.

    Args:
        f: A field with ``data``, named ``dims`` (``"y"`` and ``"x"`` among
            them) and a ``stagger`` that is empty at the cell centres, such
            as a `gridax.CField`.
        grid: The grid of the field: its ``ghost`` width, and
            ``coords("y", at="T")`` and ``coords("x", at="T")`` in radians on
            a sphere of radius ``R`` (gridax's spherical grids), or 2-D
            ``lat_T`` and ``lon_T`` in radians.
        crs: The CRS of the latitudes and longitudes.
        coords: Coordinates of the other dims of the result.
        fill_value: The nodata marker.
        attrs: Whole-carrier metadata.

    Returns:
        The interior of the field, ``(..., row, col)``; the other dims keep
        their order.

    Raises:
        ValueError: The field is not at the cell centres, has no ``y`` or
            ``x`` dim, or its ``(y, x)`` do not match the grid.
        TypeError: The grid has no latitudes and longitudes.

    Example:
        >>> import numpy as np
        >>> from types import SimpleNamespace
        >>> y, x = np.deg2rad([9.0, 10.0, 11.0, 12.0]), np.deg2rad([-1.0, 0.0, 1.0])
        >>> grid = SimpleNamespace(
        ...     ghost=1, R=6.371e6, coords=lambda axis, at: {"y": y, "x": x}[axis]
        ... )
        >>> h = SimpleNamespace(data=np.ones((4, 3)), dims=("y", "x"), stagger=())
        >>> swath = to_geoswath(h, grid)
        >>> swath.dims, np.round(swath.lat[:, 0], 6).tolist()
        (('row', 'col'), [10.0, 11.0])
    """
    stagger = tuple(f.stagger)
    if stagger:
        where = getattr(f, "loc", None) or dict(stagger)
        raise ValueError(
            f"the field sits at {where}, not at the cell centres: move it there"
            ' first, e.g. gridax.interpolate(f, grid, dst="T")'
        )
    dims = tuple(f.dims)
    missing = [dim for dim in ("y", "x") if dim not in dims]
    if missing:
        raise ValueError(f"the field has dims {dims}, without {missing}")
    lat, lon = _latlon(grid)
    ghost = int(grid.ghost)
    axes = tuple(getattr(grid, "axes", ("y", "x")))
    others = tuple(dim for dim in dims if dim not in ("y", "x"))
    data = f.data.transpose([dims.index(dim) for dim in (*others, "y", "x")])
    if tuple(data.shape[-2:]) != lat.shape:
        raise ValueError(
            f"the field is {tuple(data.shape[-2:])} along (y, x), not {lat.shape}"
        )
    inner = slice(ghost, -ghost) if ghost else slice(None)
    # the ring of every grid axis is dropped, also of a vertical one
    index = tuple(inner if dim in axes else slice(None) for dim in others)
    cells = CurvilinearGrid(lat[inner, inner], lon[inner, inner], crs)
    return GeoSwath.from_grid(
        data[(*index, inner, inner)],
        cells,
        dims=(*others, "row", "col"),
        coords=coords,
        fill_value=fill_value,
        attrs=FrozenAttrs(attrs or {}),
    )

Dim-level functions

pipekit-array's functions, re-exported: geoarray.isel is pipekit_array.isel. The named reductions compute, so geoarray does not re-export them: use geoops.compositing.reduce / argreduce, which leave nodata out, or pipekit_array.reduce / argreduce as they are (GA-B6). They are documented in pipekit-array; geoarray's adapters are registered with pipekit at import, and give carriers these fast paths:

Function On a geoarray carrier
isel(x, **dims), sel(x, **labels) slice the data, coordinates and geometry; an index that breaks the grid gives a DimArray
transpose(x, order) a carrier while the spatial dims stay last; else a DimArray
reduce(x, fn, dim), argreduce(x, fn, dim), take_along(x, index, dim) a carrier while the spatial (and batch) dims survive; else a DimArray
map_over(x, fn, dim) one jax.vmap over the data and the matching leaves on JAX; a loop on NumPy
concat(xs, dim) joins coordinates, per-band attrs and, along a batch dim, transforms
combine(fn, *xs) one exact grid, one fill; NumPy inputs join JAX ones (pipekit_ops.guard reports it)

The named-array adapters

geoarray.GeoArrayAdapter

Bases: _SharedMethods

The pipekit_ops.NamedArrayAdapter for GeoArray.

Example

import numpy as np import pipekit_array as pa from geoarray import GeoArray t = (20, 0, 0, 0, -20, 0) g = GeoArray(np.ones((3, 4, 4)), t, 32613, dims="time y x") mean = pa.reduce(g, "mean", "time") type(mean).name, mean.dims ('GeoArray', ('y', 'x')) type(pa.reduce(g, "mean", "y")).name 'DimArray'

Source code in packages/geotoolz-array/src/geoarray/_src/adapter.py
class GeoArrayAdapter(_SharedMethods):
    """The `pipekit_ops.NamedArrayAdapter` for `GeoArray`.

    Example:
        >>> import numpy as np
        >>> import pipekit_array as pa
        >>> from geoarray import GeoArray
        >>> t = (20, 0, 0, 0, -20, 0)
        >>> g = GeoArray(np.ones((3, 4, 4)), t, 32613, dims="time y x")
        >>> mean = pa.reduce(g, "mean", "time")
        >>> type(mean).__name__, mean.dims
        ('GeoArray', ('y', 'x'))
        >>> type(pa.reduce(g, "mean", "y")).__name__
        'DimArray'
    """

    def dims(self, x: GeoArray) -> tuple[str, ...]:
        """The stored dims."""
        return x.dims

    def data(self, x: GeoArray) -> Any:
        """The raw NumPy or JAX array."""
        return x.data

    def labels(self, x: GeoArray, dim: str) -> tuple[Any, ...] | None:
        """The dim's coordinate labels; ``None`` for ``y``, ``x`` and bare dims.

        pipekit-array also reads back the ``DimArray`` that `rewrap` returns
        off the grid, so that carrier is read as a ``DimArray``.
        """
        if isinstance(x, DimArray):
            return _DIMARRAY.labels(x, dim)
        return None if dim in SPATIAL_DIMS else x.labels(dim)

    def batch_dims(self, x: GeoArray) -> tuple[str, ...]:
        """The dims with one transform per item (F4)."""
        return x.batch_dims

    def isel(self, x: GeoArray, indexers: dict[str, Any]) -> Any:
        """Select by position; dropping or picking spatial indices loses the grid."""
        spatial_ok = all(
            isinstance(k, slice) and (k.step is None or k.step > 0)
            for d, k in indexers.items()
            if d in SPATIAL_DIMS
        )
        if spatial_ok:
            return x.isel(indexers)
        geo = {d: k for d, k in indexers.items() if d not in SPATIAL_DIMS}
        rest = {d: k for d, k in indexers.items() if d in SPATIAL_DIMS}
        partial = x.isel(geo) if geo else x
        return _DIMARRAY.isel(to_dimarray(partial), rest)

    def rewrap(self, x: GeoArray, data: Any, dims: tuple[str, ...]) -> Any:
        """A `GeoArray` on ``x``'s grid while it still describes the data.

        That is when ``dims`` end in ``y x`` with ``x``'s spatial shape and
        start with ``x``'s batch dims and shape. Coordinates and per-band
        attrs are kept for dims that survive with their size; a fill the new
        dtype cannot hold is dropped. Otherwise a ``DimArray`` with the
        surviving labels.
        """
        dims = tuple(dims)
        shape = tuple(data.shape)
        n_batch = len(x.batch_shape)
        on_grid = (
            dims[-2:] == SPATIAL_DIMS
            and shape[-2:] == x.shape[-2:]
            and dims[:n_batch] == x.batch_dims
            and shape[:n_batch] == x.batch_shape
        )
        kept = tuple(
            c for c in x.coords if c.dim in dims and shape[dims.index(c.dim)] == c.size
        )
        if not on_grid:
            labels = {c.dim: c.labels for c in kept if c.labels is not None}
            return DimArray(data, dims, labels)
        attrs = x.attrs
        if "band" not in dims or shape[dims.index("band")] != x.count:
            attrs = drop_band_keys(attrs)
        transform = x.transform
        if backend_of(data) != backend_of(transform):
            # a JAX kernel on NumPy carriers: keep data and transform together
            transform = (
                x.to_jax().transform
                if backend_of(data) == "jax"
                else (np.asarray(transform, dtype=np.float64))
            )
        fill = _fill_for_dtype(x.fill_value, data.dtype)
        return build(data, transform, x.crs, fill, attrs, dims, kept)

    def check_compatible(self, *xs: GeoArray) -> tuple[GeoArray, ...]:
        """The carriers, checked to share one exact grid; use what it returns.

        Raises:
            TypeError: One of them is not a `GeoArray`.
            GridMismatchError: CRS, spatial shape, batch shape or transform
                differ (a traced transform: at run time).
        """
        gs = _require_carriers(xs, "check_compatible")
        return tuple(_require_same_grid(gs, "check_compatible"))

    def signature(self, x: GeoArray) -> Signature:
        """Dims with their sizes, and the dtype's name."""
        return Signature(
            dims=tuple(zip(x.dims, x.shape, strict=True)), dtype=str(x.dtype)
        )

    # -- fast paths ------------------------------------------------------------

    def combine(self, fn: Callable[..., Any], *xs: GeoArray) -> GeoArray:
        """``geoarray.combine``: one grid, one fill, inputs in the first's order."""
        return combine_carriers(fn, *xs)

    def stack(self, xs: Sequence[GeoArray], dim: str) -> GeoArray:
        """``geoarray.stack`` with a named dim."""
        return stack(xs, dim)

    def concat(self, xs: Sequence[GeoArray], dim: str) -> GeoArray:
        """``geoarray.concat``: coordinates and per-band attrs joined."""
        return concat_carriers(xs, dim)

    def stack_items(self, xs: Sequence[GeoArray], dim: str) -> GeoArray:
        """Items on their own grids along a new batch dim (transform rows)."""
        return stack_items_carriers(xs, dim)

    def map_over(self, x: GeoArray, fn: Callable[[Any], Any], dim: str) -> Any:
        """``fn`` on each item along ``dim``, stacked along ``dim``.

        ``dim`` comes first, after any batch dims the items keep, so the
        transform's batch axes still lead the data. Per-band attrs follow
        the items when ``dim`` is ``band``. Each item is ``x`` without
        ``dim``: its own transform row when
        ``dim`` is a batch dim (patches, per-frame grids), its own stamp
        when ``dim`` is ``time``. On JAX this is one ``jax.vmap`` over the
        data and the matching leaves, so 64 patches with 64 transforms are
        one trace (GA-G15); on NumPy, a loop.

        Raises:
            ValueError: ``dim`` is spatial or not a dim, or ``fn`` returns
                something other than one named carrier.
        """
        if dim not in x.dims or dim in SPATIAL_DIMS:
            raise ValueError(f"map_over: {dim!r} is not a non-spatial dim of {x.dims}")
        if x.backend == "jax":
            return _map_over_jax(x, fn, dim)
        n = x.sizes[dim]
        items = [fn(x.isel({dim: i})) for i in range(n)]
        return _restack(x, items, dim)

batch_dims(x)

The dims with one transform per item (F4).

Source code in packages/geotoolz-array/src/geoarray/_src/adapter.py
def batch_dims(self, x: GeoArray) -> tuple[str, ...]:
    """The dims with one transform per item (F4)."""
    return x.batch_dims

check_compatible(*xs)

The carriers, checked to share one exact grid; use what it returns.

Raises:

Type Description
TypeError

One of them is not a GeoArray.

GridMismatchError

CRS, spatial shape, batch shape or transform differ (a traced transform: at run time).

Source code in packages/geotoolz-array/src/geoarray/_src/adapter.py
def check_compatible(self, *xs: GeoArray) -> tuple[GeoArray, ...]:
    """The carriers, checked to share one exact grid; use what it returns.

    Raises:
        TypeError: One of them is not a `GeoArray`.
        GridMismatchError: CRS, spatial shape, batch shape or transform
            differ (a traced transform: at run time).
    """
    gs = _require_carriers(xs, "check_compatible")
    return tuple(_require_same_grid(gs, "check_compatible"))

combine(fn, *xs)

geoarray.combine: one grid, one fill, inputs in the first's order.

Source code in packages/geotoolz-array/src/geoarray/_src/adapter.py
def combine(self, fn: Callable[..., Any], *xs: GeoArray) -> GeoArray:
    """``geoarray.combine``: one grid, one fill, inputs in the first's order."""
    return combine_carriers(fn, *xs)

concat(xs, dim)

geoarray.concat: coordinates and per-band attrs joined.

Source code in packages/geotoolz-array/src/geoarray/_src/adapter.py
def concat(self, xs: Sequence[GeoArray], dim: str) -> GeoArray:
    """``geoarray.concat``: coordinates and per-band attrs joined."""
    return concat_carriers(xs, dim)

data(x)

The raw NumPy or JAX array.

Source code in packages/geotoolz-array/src/geoarray/_src/adapter.py
def data(self, x: GeoArray) -> Any:
    """The raw NumPy or JAX array."""
    return x.data

dims(x)

The stored dims.

Source code in packages/geotoolz-array/src/geoarray/_src/adapter.py
def dims(self, x: GeoArray) -> tuple[str, ...]:
    """The stored dims."""
    return x.dims

isel(x, indexers)

Select by position; dropping or picking spatial indices loses the grid.

Source code in packages/geotoolz-array/src/geoarray/_src/adapter.py
def isel(self, x: GeoArray, indexers: dict[str, Any]) -> Any:
    """Select by position; dropping or picking spatial indices loses the grid."""
    spatial_ok = all(
        isinstance(k, slice) and (k.step is None or k.step > 0)
        for d, k in indexers.items()
        if d in SPATIAL_DIMS
    )
    if spatial_ok:
        return x.isel(indexers)
    geo = {d: k for d, k in indexers.items() if d not in SPATIAL_DIMS}
    rest = {d: k for d, k in indexers.items() if d in SPATIAL_DIMS}
    partial = x.isel(geo) if geo else x
    return _DIMARRAY.isel(to_dimarray(partial), rest)

labels(x, dim)

The dim's coordinate labels; None for y, x and bare dims.

pipekit-array also reads back the DimArray that rewrap returns off the grid, so that carrier is read as a DimArray.

Source code in packages/geotoolz-array/src/geoarray/_src/adapter.py
def labels(self, x: GeoArray, dim: str) -> tuple[Any, ...] | None:
    """The dim's coordinate labels; ``None`` for ``y``, ``x`` and bare dims.

    pipekit-array also reads back the ``DimArray`` that `rewrap` returns
    off the grid, so that carrier is read as a ``DimArray``.
    """
    if isinstance(x, DimArray):
        return _DIMARRAY.labels(x, dim)
    return None if dim in SPATIAL_DIMS else x.labels(dim)

map_over(x, fn, dim)

fn on each item along dim, stacked along dim.

dim comes first, after any batch dims the items keep, so the transform's batch axes still lead the data. Per-band attrs follow the items when dim is band. Each item is x without dim: its own transform row when dim is a batch dim (patches, per-frame grids), its own stamp when dim is time. On JAX this is one jax.vmap over the data and the matching leaves, so 64 patches with 64 transforms are one trace (GA-G15); on NumPy, a loop.

Raises:

Type Description
ValueError

dim is spatial or not a dim, or fn returns something other than one named carrier.

Source code in packages/geotoolz-array/src/geoarray/_src/adapter.py
def map_over(self, x: GeoArray, fn: Callable[[Any], Any], dim: str) -> Any:
    """``fn`` on each item along ``dim``, stacked along ``dim``.

    ``dim`` comes first, after any batch dims the items keep, so the
    transform's batch axes still lead the data. Per-band attrs follow
    the items when ``dim`` is ``band``. Each item is ``x`` without
    ``dim``: its own transform row when
    ``dim`` is a batch dim (patches, per-frame grids), its own stamp
    when ``dim`` is ``time``. On JAX this is one ``jax.vmap`` over the
    data and the matching leaves, so 64 patches with 64 transforms are
    one trace (GA-G15); on NumPy, a loop.

    Raises:
        ValueError: ``dim`` is spatial or not a dim, or ``fn`` returns
            something other than one named carrier.
    """
    if dim not in x.dims or dim in SPATIAL_DIMS:
        raise ValueError(f"map_over: {dim!r} is not a non-spatial dim of {x.dims}")
    if x.backend == "jax":
        return _map_over_jax(x, fn, dim)
    n = x.sizes[dim]
    items = [fn(x.isel({dim: i})) for i in range(n)]
    return _restack(x, items, dim)

rewrap(x, data, dims)

A GeoArray on x's grid while it still describes the data.

That is when dims end in y x with x's spatial shape and start with x's batch dims and shape. Coordinates and per-band attrs are kept for dims that survive with their size; a fill the new dtype cannot hold is dropped. Otherwise a DimArray with the surviving labels.

Source code in packages/geotoolz-array/src/geoarray/_src/adapter.py
def rewrap(self, x: GeoArray, data: Any, dims: tuple[str, ...]) -> Any:
    """A `GeoArray` on ``x``'s grid while it still describes the data.

    That is when ``dims`` end in ``y x`` with ``x``'s spatial shape and
    start with ``x``'s batch dims and shape. Coordinates and per-band
    attrs are kept for dims that survive with their size; a fill the new
    dtype cannot hold is dropped. Otherwise a ``DimArray`` with the
    surviving labels.
    """
    dims = tuple(dims)
    shape = tuple(data.shape)
    n_batch = len(x.batch_shape)
    on_grid = (
        dims[-2:] == SPATIAL_DIMS
        and shape[-2:] == x.shape[-2:]
        and dims[:n_batch] == x.batch_dims
        and shape[:n_batch] == x.batch_shape
    )
    kept = tuple(
        c for c in x.coords if c.dim in dims and shape[dims.index(c.dim)] == c.size
    )
    if not on_grid:
        labels = {c.dim: c.labels for c in kept if c.labels is not None}
        return DimArray(data, dims, labels)
    attrs = x.attrs
    if "band" not in dims or shape[dims.index("band")] != x.count:
        attrs = drop_band_keys(attrs)
    transform = x.transform
    if backend_of(data) != backend_of(transform):
        # a JAX kernel on NumPy carriers: keep data and transform together
        transform = (
            x.to_jax().transform
            if backend_of(data) == "jax"
            else (np.asarray(transform, dtype=np.float64))
        )
    fill = _fill_for_dtype(x.fill_value, data.dtype)
    return build(data, transform, x.crs, fill, attrs, dims, kept)

signature(x)

Dims with their sizes, and the dtype's name.

Source code in packages/geotoolz-array/src/geoarray/_src/adapter.py
def signature(self, x: GeoArray) -> Signature:
    """Dims with their sizes, and the dtype's name."""
    return Signature(
        dims=tuple(zip(x.dims, x.shape, strict=True)), dtype=str(x.dtype)
    )

stack(xs, dim)

geoarray.stack with a named dim.

Source code in packages/geotoolz-array/src/geoarray/_src/adapter.py
def stack(self, xs: Sequence[GeoArray], dim: str) -> GeoArray:
    """``geoarray.stack`` with a named dim."""
    return stack(xs, dim)

stack_items(xs, dim)

Items on their own grids along a new batch dim (transform rows).

Source code in packages/geotoolz-array/src/geoarray/_src/adapter.py
def stack_items(self, xs: Sequence[GeoArray], dim: str) -> GeoArray:
    """Items on their own grids along a new batch dim (transform rows)."""
    return stack_items_carriers(xs, dim)

geoarray.GeoSwathAdapter

Bases: _GeolocatedAdapter

The pipekit_ops.NamedArrayAdapter for GeoSwath: lat/lon must match exactly.

A reduction over row or col (per-column statistics) is a DimArray.

Source code in packages/geotoolz-array/src/geoarray/_src/adapter.py
class GeoSwathAdapter(_GeolocatedAdapter):
    """The `pipekit_ops.NamedArrayAdapter` for `GeoSwath`: lat/lon must match exactly.

    A reduction over ``row`` or ``col`` (per-column statistics) is a
    ``DimArray``.
    """

    carrier = GeoSwath
    leaves = ("lat", "lon")

geoarray.GeoPointsAdapter

Bases: _GeolocatedAdapter

The pipekit_ops.NamedArrayAdapter for GeoPoints: xy, z, time, valid match.

A reduction over obs is a DimArray.

Source code in packages/geotoolz-array/src/geoarray/_src/adapter.py
class GeoPointsAdapter(_GeolocatedAdapter):
    """The `pipekit_ops.NamedArrayAdapter` for `GeoPoints`: xy, z, time, valid match.

    A reduction over ``obs`` is a ``DimArray``.
    """

    carrier = GeoPoints
    leaves = ("xy", "z", "time", "valid")

    def _static_fields(self) -> tuple[str, ...]:
        return ("crs", "attrs", "vertical")

geoarray.to_dimarray(g)

A carrier's data, dims and labels as a pipekit_array.DimArray; no grid.

Source code in packages/geotoolz-array/src/geoarray/_src/adapter.py
def to_dimarray(g: Any) -> DimArray:
    """A carrier's data, dims and labels as a ``pipekit_array.DimArray``; no grid."""
    labels = {c.dim: c.labels for c in g.coords if c.labels is not None}
    return DimArray(g.data, g.dims, labels)

Coordinates to pixels

geoarray.to_pixel(transform, xy)

Map coordinates (x, y) to fractional pixel (row, col), centres at integers.

Inverting the 2 × 2 linear part A = [[a, b], [d, e]] of T,

(j, i)ᵀ = A⁻¹ (x − c, y − f)ᵀ,

and subtracting ½ from both puts integers at pixel centres, so (0, 0) is the centre of the top-left pixel.

Parameters:

Name Type Description Default
transform Any

T = (a, b, c, d, e, f), six numbers, NumPy or JAX.

required
xy Any

The positions (x, y) in the transform's CRS, shape (..., 2).

required

Returns:

Type Description
Any

The fractional (row, col), shape (..., 2), in the namespace of

Any

the inputs (JAX if either is a JAX array).

Raises:

Type Description
GeometryError

If a concrete transform is singular. A traced one is not checked; AffineGrid guarantees an invertible transform.

Examples:

>>> import numpy as np
>>> from functax.geometry import to_pixel
>>> north_up = np.array([20.0, 0.0, 600000.0, 0.0, -20.0, 3550000.0])
>>> to_pixel(north_up, np.array([[600010.0, 3549990.0]])).tolist()
[[0.0, 0.0]]
>>> to_pixel(north_up, np.array([[600000.0, 3550000.0]])).tolist()
[[-0.5, -0.5]]
Source code in .venv/lib/python3.12/site-packages/functax/_src/geometry/_affine.py
def to_pixel(transform: Any, xy: Any) -> Any:
    """Map coordinates (x, y) to fractional pixel (row, col), centres at integers.

    Inverting the 2 × 2 linear part A = [[a, b], [d, e]] of T,

        (j, i)ᵀ = A⁻¹ (x − c, y − f)ᵀ,

    and subtracting ½ from both puts integers at pixel centres, so (0, 0) is
    the centre of the top-left pixel.

    Args:
        transform: T = (a, b, c, d, e, f), six numbers, NumPy or JAX.
        xy: The positions (x, y) in the transform's CRS, shape ``(..., 2)``.

    Returns:
        The fractional (row, col), shape ``(..., 2)``, in the namespace of
        the inputs (JAX if either is a JAX array).

    Raises:
        GeometryError: If a concrete ``transform`` is singular. A traced one
            is not checked; `AffineGrid` guarantees an invertible transform.

    Examples:
        >>> import numpy as np
        >>> from functax.geometry import to_pixel
        >>> north_up = np.array([20.0, 0.0, 600000.0, 0.0, -20.0, 3550000.0])
        >>> to_pixel(north_up, np.array([[600010.0, 3549990.0]])).tolist()
        [[0.0, 0.0]]
        >>> to_pixel(north_up, np.array([[600000.0, 3550000.0]])).tolist()
        [[-0.5, -0.5]]
    """
    xp = namespace(transform, xy)
    _require_invertible(transform)
    a, b, c, d, e, f = (transform[k] for k in range(6))
    # det A = a·e − b·d
    determinant = a * e - b * d
    # (x − c, y − f)
    dx = xy[..., 0] - c
    dy = xy[..., 1] - f
    # A⁻¹ = [[e, −b], [−d, a]] / det A, then − ½ for the centre convention
    col = (e * dx - b * dy) / determinant - 0.5
    row = (-d * dx + a * dy) / determinant - 0.5
    return xp.stack([row, col], axis=-1)

Reading a grid at points, H(x), blends pixels, so it is geoops': geoops.geom.interp_at.

Grid

A pixel grid without data.

geoarray.Grid dataclass

A pixel grid with no data: transform, CRS and spatial shape.

Hashable, so it can be a warp target, an operator's static config or a dictionary key. == is exact equality; isclose allows a tolerance.

Parameters:

Name Type Description Default
transform Transform

The affine transform (anything as_transform accepts).

required
crs CRS | None

The CRS (anything as_crs accepts), or None.

required
shape tuple[int, int]

(H, W).

required
Example

transform = (20.0, 0.0, 600000.0, 0.0, -20.0, 3550000.0) grid = Grid(transform, "EPSG:32613", (600, 600)) grid.res (20.0, 20.0) grid.bounds (600000.0, 3538000.0, 612000.0, 3550000.0)

Source code in packages/geotoolz-array/src/geoarray/_src/grid.py
@dataclass(frozen=True)
class Grid:
    """A pixel grid with no data: transform, CRS and spatial shape.

    Hashable, so it can be a warp target, an operator's static config or a
    dictionary key. ``==`` is exact equality; `isclose` allows a tolerance.

    Args:
        transform: The affine transform (anything `as_transform` accepts).
        crs: The CRS (anything `as_crs` accepts), or ``None``.
        shape: ``(H, W)``.

    Example:
        >>> transform = (20.0, 0.0, 600000.0, 0.0, -20.0, 3550000.0)
        >>> grid = Grid(transform, "EPSG:32613", (600, 600))
        >>> grid.res
        (20.0, 20.0)
        >>> grid.bounds
        (600000.0, 3538000.0, 612000.0, 3550000.0)
    """

    transform: Transform
    crs: pyproj.CRS | None
    shape: tuple[int, int]

    def __post_init__(self) -> None:
        object.__setattr__(self, "transform", as_transform(self.transform))
        object.__setattr__(self, "crs", as_crs(self.crs))
        shape = tuple(self.shape)
        if len(shape) != 2:
            raise ValueError(f"a grid's shape is (H, W), got {self.shape!r}")
        object.__setattr__(
            self, "shape", (_as_index(shape[0], "H"), _as_index(shape[1], "W"))
        )

    @property
    def height(self) -> int:
        """H, the number of rows."""
        return self.shape[0]

    @property
    def width(self) -> int:
        """W, the number of columns."""
        return self.shape[1]

    @property
    def affine(self) -> Affine:
        """The transform as an ``affine.Affine`` (what rasterio expects)."""
        return Affine(*self.transform)

    @property
    def is_axis_aligned(self) -> bool:
        """Whether the grid has no rotation or shear: b = d = 0."""
        _, b, _, d, _, _ = self.transform
        return b == 0.0 and d == 0.0

    @property
    def res(self) -> tuple[float, float]:
        """Pixel size ``(x, y)`` in CRS units, always positive.

        For a rotated grid, the lengths of the column and row vectors:
        (√(a² + d²), √(b² + e²)).
        """
        a, b, _, d, e, _ = self.transform
        return (math.hypot(a, d), math.hypot(b, e))

    @property
    def bounds(self) -> tuple[float, float, float, float]:
        """``(x_min, y_min, x_max, y_max)`` of the grid's outer edges."""
        h, w = self.shape
        corners = [
            apply_transform(self.transform, j, i) for j in (0, w) for i in (0, h)
        ]
        xs, ys = zip(*corners, strict=True)
        return (min(xs), min(ys), max(xs), max(ys))

    @classmethod
    def from_affine(cls, affine: Affine, crs: Any, shape: Sequence[int]) -> Grid:
        """A grid from an ``affine.Affine`` (or rasterio ``Affine``)."""
        h, w = shape
        return cls(as_transform(affine), crs, (h, w))

    def shift(self, rows: float, cols: float) -> Grid:
        """The same grid with its origin moved by ``rows`` × ``cols`` pixels.

        c′ = c + a·cols + b·rows, f′ = f + d·cols + e·rows.

        Example:
            >>> grid = Grid((20.0, 0.0, 0.0, 0.0, -20.0, 0.0), None, (4, 4))
            >>> grid.shift(1, 2).transform
            (20.0, 0.0, 40.0, 0.0, -20.0, -20.0)
        """
        a, b, _, d, e, _ = self.transform
        c, f = apply_transform(self.transform, cols, rows)
        return Grid((a, b, c, d, e, f), self.crs, self.shape)

    @classmethod
    def from_bounds(
        cls,
        bounds: Sequence[float],
        res: float | Sequence[float],
        crs: Any,
        *,
        atol: float = 1e-6,
    ) -> Grid:
        """The north-up grid that covers ``bounds`` with square-edged pixels.

        The origin is the top-left corner (x_min, y_max); the shape rounds
        up to whole pixels, ignoring overshoots below ``atol`` pixels.

        Args:
            bounds: ``(x_min, y_min, x_max, y_max)`` in CRS units.
            res: Pixel size, one number or ``(x, y)``, positive.
            crs: The CRS (anything `as_crs` accepts).
            atol: Tolerance, in pixels, for a size that is almost whole.

        Example:
            >>> Grid.from_bounds((600000, 3538000, 612000, 3550000), 20, 32613).shape
            (600, 600)
        """
        x_min, y_min, x_max, y_max = (float(v) for v in bounds)
        rx, ry = (float(v) for v in np.broadcast_to(np.asarray(res, float), (2,)))
        if rx <= 0 or ry <= 0 or x_max <= x_min or y_max <= y_min:
            raise ValueError(
                f"need positive res and non-empty bounds, got {bounds}, {res}"
            )
        width = math.ceil(_snap((x_max - x_min) / rx, atol))
        height = math.ceil(_snap((y_max - y_min) / ry, atol))
        return cls((rx, 0.0, x_min, 0.0, -ry, y_max), crs, (height, width))

    def window(self, bounds: Sequence[float], *, atol: float = 1e-6) -> PixelWindow:
        """The pixels that cover ``bounds``, rounded outward to whole pixels.

        Corners within ``atol`` pixels of a pixel edge snap to it, so bounds
        on the grid map to exactly the pixels inside them. The window may
        extend outside the grid; `PixelWindow.intersection` clips it. The
        kernel is functax's (`functax.geometry.window`).

        Args:
            bounds: ``(x_min, y_min, x_max, y_max)`` in this grid's CRS.
            atol: Snapping tolerance, in pixels.

        Raises:
            ValueError: ``bounds`` has a min above its max, or the transform
                is singular (functax's ``GeometryError``, a ``ValueError``).

        Example:
            >>> transform = (20.0, 0.0, 600000.0, 0.0, -20.0, 3550000.0)
            >>> grid = Grid(transform, None, (600, 600))
            >>> grid.window((600100, 3549000, 600400, 3549900))
            PixelWindow(col_off=5, row_off=5, width=15, height=45)
        """
        rows, cols = functax_window(self, bounds, atol=atol)
        return PixelWindow.from_slices(rows, cols)

    def to_functax(self) -> Any:
        """This grid as a functax ``AffineGrid``: the transform and the shape.

        The CRS stays here, since functax never sees one. The ``AffineGrid``
        is an Equinox module, so this needs the ``functax[jax]`` extra (JAX
        with ``jax_enable_x64``; ``geotoolz-ops[interp]`` brings it) and
        raises functax's ``MissingExtraError`` (an ``ImportError``) without.

        Example:
            >>> grid = Grid((20.0, 0.0, 0.0, 0.0, -20.0, 0.0), "EPSG:32613", (2, 3))
            >>> grid.to_functax().shape  # doctest: +SKIP
            (2, 3)
        """
        from functax.geometry import AffineGrid

        return AffineGrid.from_affine(self.transform, self.shape)

    def crop(self, window: PixelWindow) -> Grid:
        """The grid of ``window``: its origin and its shape.

        Example:
            >>> grid = Grid((20.0, 0.0, 0.0, 0.0, -20.0, 0.0), None, (8, 8))
            >>> window = PixelWindow(col_off=3, row_off=2, width=4, height=4)
            >>> grid.crop(window).transform
            (20.0, 0.0, 60.0, 0.0, -20.0, -40.0)
        """
        shifted = self.shift(window.row_off, window.col_off)
        return Grid(shifted.transform, self.crs, window.shape)

    def bounds_of(self, window: PixelWindow) -> tuple[float, float, float, float]:
        """``(x_min, y_min, x_max, y_max)`` of ``window`` on this grid.

        The inverse of `window` for bounds on pixel edges:
        ``grid.bounds_of(grid.window(b)) == b``.
        """
        return self.crop(window).bounds

    def isclose(self, other: Grid, atol: float = 1e-6) -> bool:
        """Equal CRS and shape, and transforms within ``atol`` (map units).

        Example:
            >>> g = Grid((1.0, 0.0, 0.0, 0.0, -1.0, 0.0), None, (2, 2))
            >>> g.isclose(g.shift(1e-9, 0.0))
            True
        """
        return (
            self.shape == other.shape
            and self.crs == other.crs
            and all(
                abs(u - v) <= atol
                for u, v in zip(self.transform, other.transform, strict=True)
            )
        )

    def get_config(self) -> dict[str, Any]:
        """A strict-JSON config: the transform, the CRS string and the shape.

        Example:
            >>> grid = Grid((20.0, 0.0, 0.0, 0.0, -20.0, 0.0), "EPSG:32613", (2, 3))
            >>> grid.get_config()["crs"], grid.get_config()["shape"]
            ('EPSG:32613', [2, 3])
        """
        return {
            "transform": list(self.transform),
            "crs": crs_string(self.crs),
            "shape": list(self.shape),
        }

    @classmethod
    def from_config(cls, config: dict[str, Any]) -> Grid:
        """Rebuild a grid from `get_config`; ``from_config(g.get_config()) == g``."""
        return cls(tuple(config["transform"]), config["crs"], tuple(config["shape"]))

affine property

The transform as an affine.Affine (what rasterio expects).

bounds property

(x_min, y_min, x_max, y_max) of the grid's outer edges.

height property

H, the number of rows.

is_axis_aligned property

Whether the grid has no rotation or shear: b = d = 0.

res property

Pixel size (x, y) in CRS units, always positive.

For a rotated grid, the lengths of the column and row vectors: (√(a² + d²), √(b² + e²)).

width property

W, the number of columns.

bounds_of(window)

(x_min, y_min, x_max, y_max) of window on this grid.

The inverse of window for bounds on pixel edges: grid.bounds_of(grid.window(b)) == b.

Source code in packages/geotoolz-array/src/geoarray/_src/grid.py
def bounds_of(self, window: PixelWindow) -> tuple[float, float, float, float]:
    """``(x_min, y_min, x_max, y_max)`` of ``window`` on this grid.

    The inverse of `window` for bounds on pixel edges:
    ``grid.bounds_of(grid.window(b)) == b``.
    """
    return self.crop(window).bounds

crop(window)

The grid of window: its origin and its shape.

Example

grid = Grid((20.0, 0.0, 0.0, 0.0, -20.0, 0.0), None, (8, 8)) window = PixelWindow(col_off=3, row_off=2, width=4, height=4) grid.crop(window).transform (20.0, 0.0, 60.0, 0.0, -20.0, -40.0)

Source code in packages/geotoolz-array/src/geoarray/_src/grid.py
def crop(self, window: PixelWindow) -> Grid:
    """The grid of ``window``: its origin and its shape.

    Example:
        >>> grid = Grid((20.0, 0.0, 0.0, 0.0, -20.0, 0.0), None, (8, 8))
        >>> window = PixelWindow(col_off=3, row_off=2, width=4, height=4)
        >>> grid.crop(window).transform
        (20.0, 0.0, 60.0, 0.0, -20.0, -40.0)
    """
    shifted = self.shift(window.row_off, window.col_off)
    return Grid(shifted.transform, self.crs, window.shape)

from_affine(affine, crs, shape) classmethod

A grid from an affine.Affine (or rasterio Affine).

Source code in packages/geotoolz-array/src/geoarray/_src/grid.py
@classmethod
def from_affine(cls, affine: Affine, crs: Any, shape: Sequence[int]) -> Grid:
    """A grid from an ``affine.Affine`` (or rasterio ``Affine``)."""
    h, w = shape
    return cls(as_transform(affine), crs, (h, w))

from_bounds(bounds, res, crs, *, atol=1e-06) classmethod

The north-up grid that covers bounds with square-edged pixels.

The origin is the top-left corner (x_min, y_max); the shape rounds up to whole pixels, ignoring overshoots below atol pixels.

Parameters:

Name Type Description Default
bounds Sequence[float]

(x_min, y_min, x_max, y_max) in CRS units.

required
res float | Sequence[float]

Pixel size, one number or (x, y), positive.

required
crs Any

The CRS (anything as_crs accepts).

required
atol float

Tolerance, in pixels, for a size that is almost whole.

1e-06
Example

Grid.from_bounds((600000, 3538000, 612000, 3550000), 20, 32613).shape (600, 600)

Source code in packages/geotoolz-array/src/geoarray/_src/grid.py
@classmethod
def from_bounds(
    cls,
    bounds: Sequence[float],
    res: float | Sequence[float],
    crs: Any,
    *,
    atol: float = 1e-6,
) -> Grid:
    """The north-up grid that covers ``bounds`` with square-edged pixels.

    The origin is the top-left corner (x_min, y_max); the shape rounds
    up to whole pixels, ignoring overshoots below ``atol`` pixels.

    Args:
        bounds: ``(x_min, y_min, x_max, y_max)`` in CRS units.
        res: Pixel size, one number or ``(x, y)``, positive.
        crs: The CRS (anything `as_crs` accepts).
        atol: Tolerance, in pixels, for a size that is almost whole.

    Example:
        >>> Grid.from_bounds((600000, 3538000, 612000, 3550000), 20, 32613).shape
        (600, 600)
    """
    x_min, y_min, x_max, y_max = (float(v) for v in bounds)
    rx, ry = (float(v) for v in np.broadcast_to(np.asarray(res, float), (2,)))
    if rx <= 0 or ry <= 0 or x_max <= x_min or y_max <= y_min:
        raise ValueError(
            f"need positive res and non-empty bounds, got {bounds}, {res}"
        )
    width = math.ceil(_snap((x_max - x_min) / rx, atol))
    height = math.ceil(_snap((y_max - y_min) / ry, atol))
    return cls((rx, 0.0, x_min, 0.0, -ry, y_max), crs, (height, width))

from_config(config) classmethod

Rebuild a grid from get_config; from_config(g.get_config()) == g.

Source code in packages/geotoolz-array/src/geoarray/_src/grid.py
@classmethod
def from_config(cls, config: dict[str, Any]) -> Grid:
    """Rebuild a grid from `get_config`; ``from_config(g.get_config()) == g``."""
    return cls(tuple(config["transform"]), config["crs"], tuple(config["shape"]))

get_config()

A strict-JSON config: the transform, the CRS string and the shape.

Example

grid = Grid((20.0, 0.0, 0.0, 0.0, -20.0, 0.0), "EPSG:32613", (2, 3)) grid.get_config()["crs"], grid.get_config()["shape"] ('EPSG:32613', [2, 3])

Source code in packages/geotoolz-array/src/geoarray/_src/grid.py
def get_config(self) -> dict[str, Any]:
    """A strict-JSON config: the transform, the CRS string and the shape.

    Example:
        >>> grid = Grid((20.0, 0.0, 0.0, 0.0, -20.0, 0.0), "EPSG:32613", (2, 3))
        >>> grid.get_config()["crs"], grid.get_config()["shape"]
        ('EPSG:32613', [2, 3])
    """
    return {
        "transform": list(self.transform),
        "crs": crs_string(self.crs),
        "shape": list(self.shape),
    }

isclose(other, atol=1e-06)

Equal CRS and shape, and transforms within atol (map units).

Example

g = Grid((1.0, 0.0, 0.0, 0.0, -1.0, 0.0), None, (2, 2)) g.isclose(g.shift(1e-9, 0.0)) True

Source code in packages/geotoolz-array/src/geoarray/_src/grid.py
def isclose(self, other: Grid, atol: float = 1e-6) -> bool:
    """Equal CRS and shape, and transforms within ``atol`` (map units).

    Example:
        >>> g = Grid((1.0, 0.0, 0.0, 0.0, -1.0, 0.0), None, (2, 2))
        >>> g.isclose(g.shift(1e-9, 0.0))
        True
    """
    return (
        self.shape == other.shape
        and self.crs == other.crs
        and all(
            abs(u - v) <= atol
            for u, v in zip(self.transform, other.transform, strict=True)
        )
    )

shift(rows, cols)

The same grid with its origin moved by rows × cols pixels.

c′ = c + a·cols + b·rows, f′ = f + d·cols + e·rows.

Example

grid = Grid((20.0, 0.0, 0.0, 0.0, -20.0, 0.0), None, (4, 4)) grid.shift(1, 2).transform (20.0, 0.0, 40.0, 0.0, -20.0, -20.0)

Source code in packages/geotoolz-array/src/geoarray/_src/grid.py
def shift(self, rows: float, cols: float) -> Grid:
    """The same grid with its origin moved by ``rows`` × ``cols`` pixels.

    c′ = c + a·cols + b·rows, f′ = f + d·cols + e·rows.

    Example:
        >>> grid = Grid((20.0, 0.0, 0.0, 0.0, -20.0, 0.0), None, (4, 4))
        >>> grid.shift(1, 2).transform
        (20.0, 0.0, 40.0, 0.0, -20.0, -20.0)
    """
    a, b, _, d, e, _ = self.transform
    c, f = apply_transform(self.transform, cols, rows)
    return Grid((a, b, c, d, e, f), self.crs, self.shape)

to_functax()

This grid as a functax AffineGrid: the transform and the shape.

The CRS stays here, since functax never sees one. The AffineGrid is an Equinox module, so this needs the functax[jax] extra (JAX with jax_enable_x64; geotoolz-ops[interp] brings it) and raises functax's MissingExtraError (an ImportError) without.

Example

grid = Grid((20.0, 0.0, 0.0, 0.0, -20.0, 0.0), "EPSG:32613", (2, 3)) grid.to_functax().shape # doctest: +SKIP (2, 3)

Source code in packages/geotoolz-array/src/geoarray/_src/grid.py
def to_functax(self) -> Any:
    """This grid as a functax ``AffineGrid``: the transform and the shape.

    The CRS stays here, since functax never sees one. The ``AffineGrid``
    is an Equinox module, so this needs the ``functax[jax]`` extra (JAX
    with ``jax_enable_x64``; ``geotoolz-ops[interp]`` brings it) and
    raises functax's ``MissingExtraError`` (an ``ImportError``) without.

    Example:
        >>> grid = Grid((20.0, 0.0, 0.0, 0.0, -20.0, 0.0), "EPSG:32613", (2, 3))
        >>> grid.to_functax().shape  # doctest: +SKIP
        (2, 3)
    """
    from functax.geometry import AffineGrid

    return AffineGrid.from_affine(self.transform, self.shape)

window(bounds, *, atol=1e-06)

The pixels that cover bounds, rounded outward to whole pixels.

Corners within atol pixels of a pixel edge snap to it, so bounds on the grid map to exactly the pixels inside them. The window may extend outside the grid; PixelWindow.intersection clips it. The kernel is functax's (functax.geometry.window).

Parameters:

Name Type Description Default
bounds Sequence[float]

(x_min, y_min, x_max, y_max) in this grid's CRS.

required
atol float

Snapping tolerance, in pixels.

1e-06

Raises:

Type Description
ValueError

bounds has a min above its max, or the transform is singular (functax's GeometryError, a ValueError).

Example

transform = (20.0, 0.0, 600000.0, 0.0, -20.0, 3550000.0) grid = Grid(transform, None, (600, 600)) grid.window((600100, 3549000, 600400, 3549900)) PixelWindow(col_off=5, row_off=5, width=15, height=45)

Source code in packages/geotoolz-array/src/geoarray/_src/grid.py
def window(self, bounds: Sequence[float], *, atol: float = 1e-6) -> PixelWindow:
    """The pixels that cover ``bounds``, rounded outward to whole pixels.

    Corners within ``atol`` pixels of a pixel edge snap to it, so bounds
    on the grid map to exactly the pixels inside them. The window may
    extend outside the grid; `PixelWindow.intersection` clips it. The
    kernel is functax's (`functax.geometry.window`).

    Args:
        bounds: ``(x_min, y_min, x_max, y_max)`` in this grid's CRS.
        atol: Snapping tolerance, in pixels.

    Raises:
        ValueError: ``bounds`` has a min above its max, or the transform
            is singular (functax's ``GeometryError``, a ``ValueError``).

    Example:
        >>> transform = (20.0, 0.0, 600000.0, 0.0, -20.0, 3550000.0)
        >>> grid = Grid(transform, None, (600, 600))
        >>> grid.window((600100, 3549000, 600400, 3549900))
        PixelWindow(col_off=5, row_off=5, width=15, height=45)
    """
    rows, cols = functax_window(self, bounds, atol=atol)
    return PixelWindow.from_slices(rows, cols)

PixelWindow

A rectangle of pixels.

geoarray.PixelWindow dataclass

A rectangle of pixels: col_off, row_off, width, height.

rasterio's Window without importing rasterio, with its field order (columns before rows), so PixelWindow(*rasterio_window.flatten()) is the same rectangle. Offsets may be negative (a window that starts outside the array); sizes may not.

Example

w = PixelWindow.from_slices(slice(10, 42), slice(5, 37)) w PixelWindow(col_off=5, row_off=10, width=32, height=32) w.to_slices() (slice(10, 42, None), slice(5, 37, None))

Source code in packages/geotoolz-array/src/geoarray/_src/grid.py
@dataclass(frozen=True)
class PixelWindow:
    """A rectangle of pixels: ``col_off``, ``row_off``, ``width``, ``height``.

    rasterio's ``Window`` without importing rasterio, with its field order
    (columns before rows), so ``PixelWindow(*rasterio_window.flatten())``
    is the same rectangle. Offsets may be negative (a window that starts
    outside the array); sizes may not.

    Example:
        >>> w = PixelWindow.from_slices(slice(10, 42), slice(5, 37))
        >>> w
        PixelWindow(col_off=5, row_off=10, width=32, height=32)
        >>> w.to_slices()
        (slice(10, 42, None), slice(5, 37, None))
    """

    col_off: int
    row_off: int
    width: int
    height: int

    def __post_init__(self) -> None:
        for name in ("col_off", "row_off"):
            value = getattr(self, name)
            if isinstance(value, bool) or not isinstance(value, int | np.integer):
                raise TypeError(f"{name} must be an integer, got {value!r}")
            object.__setattr__(self, name, int(value))
        object.__setattr__(self, "height", _as_index(self.height, "height"))
        object.__setattr__(self, "width", _as_index(self.width, "width"))

    @property
    def shape(self) -> tuple[int, int]:
        """``(height, width)``."""
        return (self.height, self.width)

    @classmethod
    def from_slices(cls, rows: slice, cols: slice) -> PixelWindow:
        """The window two step-1 slices with explicit bounds select.

        Raises:
            ValueError: A slice has a step other than 1 or an open bound.
        """
        bounds = []
        for name, s in (("rows", rows), ("cols", cols)):
            if s.step not in (None, 1):
                raise ValueError(f"{name}: a window needs step 1, got {s.step}")
            if s.start is None or s.stop is None:
                raise ValueError(
                    f"{name}: a window needs explicit start and stop, got {s}"
                )
            bounds.append((int(s.start), int(s.stop)))
        (r0, r1), (c0, c1) = bounds
        return cls(
            col_off=c0, row_off=r0, width=max(c1 - c0, 0), height=max(r1 - r0, 0)
        )

    def to_slices(self) -> tuple[slice, slice]:
        """``(rows, cols)`` slices selecting this window."""
        return (
            slice(self.row_off, self.row_off + self.height),
            slice(self.col_off, self.col_off + self.width),
        )

    def intersection(self, other: PixelWindow) -> PixelWindow | None:
        """The overlap of two windows, or ``None`` when they do not overlap.

        Example:
            >>> a = PixelWindow(col_off=0, row_off=0, width=10, height=10)
            >>> a.intersection(PixelWindow(col_off=5, row_off=5, width=10, height=10))
            PixelWindow(col_off=5, row_off=5, width=5, height=5)
        """
        r0 = max(self.row_off, other.row_off)
        c0 = max(self.col_off, other.col_off)
        r1 = min(self.row_off + self.height, other.row_off + other.height)
        c1 = min(self.col_off + self.width, other.col_off + other.width)
        if r1 <= r0 or c1 <= c0:
            return None
        return PixelWindow(col_off=c0, row_off=r0, width=c1 - c0, height=r1 - r0)

shape property

(height, width).

from_slices(rows, cols) classmethod

The window two step-1 slices with explicit bounds select.

Raises:

Type Description
ValueError

A slice has a step other than 1 or an open bound.

Source code in packages/geotoolz-array/src/geoarray/_src/grid.py
@classmethod
def from_slices(cls, rows: slice, cols: slice) -> PixelWindow:
    """The window two step-1 slices with explicit bounds select.

    Raises:
        ValueError: A slice has a step other than 1 or an open bound.
    """
    bounds = []
    for name, s in (("rows", rows), ("cols", cols)):
        if s.step not in (None, 1):
            raise ValueError(f"{name}: a window needs step 1, got {s.step}")
        if s.start is None or s.stop is None:
            raise ValueError(
                f"{name}: a window needs explicit start and stop, got {s}"
            )
        bounds.append((int(s.start), int(s.stop)))
    (r0, r1), (c0, c1) = bounds
    return cls(
        col_off=c0, row_off=r0, width=max(c1 - c0, 0), height=max(r1 - r0, 0)
    )

intersection(other)

The overlap of two windows, or None when they do not overlap.

Example

a = PixelWindow(col_off=0, row_off=0, width=10, height=10) a.intersection(PixelWindow(col_off=5, row_off=5, width=10, height=10)) PixelWindow(col_off=5, row_off=5, width=5, height=5)

Source code in packages/geotoolz-array/src/geoarray/_src/grid.py
def intersection(self, other: PixelWindow) -> PixelWindow | None:
    """The overlap of two windows, or ``None`` when they do not overlap.

    Example:
        >>> a = PixelWindow(col_off=0, row_off=0, width=10, height=10)
        >>> a.intersection(PixelWindow(col_off=5, row_off=5, width=10, height=10))
        PixelWindow(col_off=5, row_off=5, width=5, height=5)
    """
    r0 = max(self.row_off, other.row_off)
    c0 = max(self.col_off, other.col_off)
    r1 = min(self.row_off + self.height, other.row_off + other.height)
    c1 = min(self.col_off + self.width, other.col_off + other.width)
    if r1 <= r0 or c1 <= c0:
        return None
    return PixelWindow(col_off=c0, row_off=r0, width=c1 - c0, height=r1 - r0)

to_slices()

(rows, cols) slices selecting this window.

Source code in packages/geotoolz-array/src/geoarray/_src/grid.py
def to_slices(self) -> tuple[slice, slice]:
    """``(rows, cols)`` slices selecting this window."""
    return (
        slice(self.row_off, self.row_off + self.height),
        slice(self.col_off, self.col_off + self.width),
    )

FrozenAttrs

Hashable metadata.

geoarray.FrozenAttrs

Bases: Mapping[str, Any]

An immutable, hashable mapping of string keys to frozen values.

Parameters:

Name Type Description Default
items Mapping[str, Any] | Any

A mapping or iterable of (key, value) pairs.

None
**kwargs Any

More items, added after items.

{}

Raises:

Type Description
TypeError

A key is not a string, or a value cannot be frozen.

Example

import numpy as np wavelengths = np.array([1610.0, 2190.0]) attrs = FrozenAttrs(band_names=["B11", "B12"], wavelengths=wavelengths) attrs["band_names"] ('B11', 'B12') attrs["wavelengths"] (1610.0, 2190.0) attrs.set(sensor="S2A").drop("wavelengths") FrozenAttrs({'band_names': ('B11', 'B12'), 'sensor': 'S2A'})

Source code in packages/geotoolz-array/src/geoarray/_src/attrs.py
class FrozenAttrs(Mapping[str, Any]):
    """An immutable, hashable mapping of string keys to frozen values.

    Args:
        items: A mapping or iterable of ``(key, value)`` pairs.
        **kwargs: More items, added after ``items``.

    Raises:
        TypeError: A key is not a string, or a value cannot be frozen.

    Example:
        >>> import numpy as np
        >>> wavelengths = np.array([1610.0, 2190.0])
        >>> attrs = FrozenAttrs(band_names=["B11", "B12"], wavelengths=wavelengths)
        >>> attrs["band_names"]
        ('B11', 'B12')
        >>> attrs["wavelengths"]
        (1610.0, 2190.0)
        >>> attrs.set(sensor="S2A").drop("wavelengths")
        FrozenAttrs({'band_names': ('B11', 'B12'), 'sensor': 'S2A'})
    """

    __slots__ = ("_hash", "_items")

    def __init__(
        self,
        items: Mapping[str, Any] | Any = None,
        /,
        **kwargs: Any,
    ) -> None:
        merged = dict(items) if items is not None else {}
        merged.update(kwargs)
        frozen: dict[str, Any] = {}
        for key, value in merged.items():
            if not isinstance(key, str):
                raise TypeError(f"attrs keys must be strings, got {key!r}")
            frozen[key] = _freeze(value, key)
        self._items = frozen
        self._hash = hash(frozenset(frozen.items()))

    def __getitem__(self, key: str) -> Any:
        return self._items[key]

    def __reduce__(self) -> tuple[Any, ...]:
        # Rebuild through the constructor: the cached hash of string keys
        # differs between processes (hash randomisation), and every NaN
        # must become the one ``math.nan`` again.
        return (FrozenAttrs, (self.to_dict(),))

    def __iter__(self) -> Iterator[str]:
        return iter(self._items)

    def __len__(self) -> int:
        return len(self._items)

    def __hash__(self) -> int:
        return self._hash

    def __eq__(self, other: object) -> bool:
        if isinstance(other, FrozenAttrs):
            return self._hash == other._hash and self._items == other._items
        if isinstance(other, Mapping):
            return self == FrozenAttrs(other)
        return NotImplemented

    def __repr__(self) -> str:
        return f"FrozenAttrs({self._items!r})"

    def set(self, **items: Any) -> FrozenAttrs:
        """A copy with ``items`` added or replaced.

        Example:
            >>> FrozenAttrs(a=1).set(b=2)
            FrozenAttrs({'a': 1, 'b': 2})
        """
        return FrozenAttrs(self._items, **items)

    def drop(self, *keys: str) -> FrozenAttrs:
        """A copy without ``keys``; missing keys are ignored.

        Example:
            >>> FrozenAttrs(a=1, b=2).drop("b", "c")
            FrozenAttrs({'a': 1})
        """
        return FrozenAttrs({k: v for k, v in self._items.items() if k not in keys})

    def to_dict(self) -> dict[str, Any]:
        """A plain ``dict``; nested `FrozenAttrs` become dicts, tuples stay tuples.

        Example:
            >>> FrozenAttrs(tags={"AREA_OR_POINT": "Area"}).to_dict()
            {'tags': {'AREA_OR_POINT': 'Area'}}
        """
        return {k: _thaw(v) for k, v in self._items.items()}

drop(*keys)

A copy without keys; missing keys are ignored.

Example

FrozenAttrs(a=1, b=2).drop("b", "c") FrozenAttrs({'a': 1})

Source code in packages/geotoolz-array/src/geoarray/_src/attrs.py
def drop(self, *keys: str) -> FrozenAttrs:
    """A copy without ``keys``; missing keys are ignored.

    Example:
        >>> FrozenAttrs(a=1, b=2).drop("b", "c")
        FrozenAttrs({'a': 1})
    """
    return FrozenAttrs({k: v for k, v in self._items.items() if k not in keys})

set(**items)

A copy with items added or replaced.

Example

FrozenAttrs(a=1).set(b=2) FrozenAttrs({'a': 1, 'b': 2})

Source code in packages/geotoolz-array/src/geoarray/_src/attrs.py
def set(self, **items: Any) -> FrozenAttrs:
    """A copy with ``items`` added or replaced.

    Example:
        >>> FrozenAttrs(a=1).set(b=2)
        FrozenAttrs({'a': 1, 'b': 2})
    """
    return FrozenAttrs(self._items, **items)

to_dict()

A plain dict; nested FrozenAttrs become dicts, tuples stay tuples.

Example

FrozenAttrs(tags={"AREA_OR_POINT": "Area"}).to_dict() {'tags': {'AREA_OR_POINT': 'Area'}}

Source code in packages/geotoolz-array/src/geoarray/_src/attrs.py
def to_dict(self) -> dict[str, Any]:
    """A plain ``dict``; nested `FrozenAttrs` become dicts, tuples stay tuples.

    Example:
        >>> FrozenAttrs(tags={"AREA_OR_POINT": "Area"}).to_dict()
        {'tags': {'AREA_OR_POINT': 'Area'}}
    """
    return {k: _thaw(v) for k, v in self._items.items()}

geoarray.PER_BAND_KEYS = ('band_names', 'descriptions', 'bands', 'band_descriptions', 'wavelengths', 'wavelengths_nm') module-attribute

Geometry

Re-index or re-describe pixels without computing new values.

geoarray.crop(g, offset, size)

The size pixels starting at offset, with the matching transform.

offset may be traced (inside jit / vmap); size must be static. Like jax.lax.dynamic_slice, an offset that would run past the edge is clamped so the crop fits, and the transform follows the pixels actually returned, so georeferencing is always right.

x_p = x[..., r₀ : r₀ + h, c₀ : c₀ + w], c′ = c + a·c₀ + b·r₀, f′ = f + d·c₀ + e·r₀.

Parameters:

Name Type Description Default
g GeoArray

The carrier, (..., H, W).

required
offset Any

(row, col) of the crop's top-left pixel.

required
size tuple[int, int]

(h, w), at most (H, W).

required

Raises:

Type Description
ValueError

size exceeds the spatial shape.

Example

import numpy as np from geoarray import GeoArray g = GeoArray(np.zeros((2, 8, 8)), (20, 0, 600000, 0, -20, 3550000), 32613) patch = crop(g, (2, 4), (4, 4)) patch.shape, patch.bounds[:2] ((2, 4, 4), (600080.0, 3549880.0))

Source code in packages/geotoolz-array/src/geoarray/_src/geometry.py
def crop(g: GeoArray, offset: Any, size: tuple[int, int]) -> GeoArray:
    """The ``size`` pixels starting at ``offset``, with the matching transform.

    ``offset`` may be traced (inside ``jit`` / ``vmap``); ``size`` must be
    static. Like ``jax.lax.dynamic_slice``, an offset that would run past
    the edge is clamped so the crop fits, and the transform follows the
    pixels actually returned, so georeferencing is always right.

    x_p = x[..., r₀ : r₀ + h, c₀ : c₀ + w], c′ = c + a·c₀ + b·r₀,
    f′ = f + d·c₀ + e·r₀.

    Args:
        g: The carrier, ``(..., H, W)``.
        offset: ``(row, col)`` of the crop's top-left pixel.
        size: ``(h, w)``, at most ``(H, W)``.

    Raises:
        ValueError: ``size`` exceeds the spatial shape.

    Example:
        >>> import numpy as np
        >>> from geoarray import GeoArray
        >>> g = GeoArray(np.zeros((2, 8, 8)), (20, 0, 600000, 0, -20, 3550000), 32613)
        >>> patch = crop(g, (2, 4), (4, 4))
        >>> patch.shape, patch.bounds[:2]
        ((2, 4, 4), (600080.0, 3549880.0))
    """
    h, w = (int(v) for v in size)
    height, width = g.height, g.width
    if not (0 < h <= height and 0 < w <= width):
        raise ValueError(
            f"crop size {(h, w)} must fit in the spatial shape {(height, width)}"
        )
    lead = tuple(g.data.shape[:-2])
    traced = is_traced(offset) or any(is_traced(v) for v in offset)
    if g.backend == "numpy" and not traced:
        row = min(max(int(offset[0]), 0), height - h)
        col = min(max(int(offset[1]), 0), width - w)
        data = g.data[..., row : row + h, col : col + w]
        return g.with_data(data, transform=_shifted(g, row, col))

    require_x64()
    import jax.numpy as jnp
    from jax import lax

    data = g.data if backend_of(g.data) == "jax" else jnp.asarray(g.data)
    offsets = jnp.asarray(offset)
    row = jnp.clip(offsets[0], 0, height - h)
    col = jnp.clip(offsets[1], 0, width - w)
    starts = (0,) * len(lead) + (row, col)
    data = lax.dynamic_slice(data, starts, (*lead, h, w))
    transform = shift_scale_transform(
        jnp.asarray(g.transform),
        row.astype(jnp.float64),
        col.astype(jnp.float64),
    )
    return g.with_data(data, transform=transform)

geoarray.read_window(g, window, *, boundless=True, fill_value=INHERIT)

The pixels of window, padding with fill where it leaves the array.

The result's fill value is the padding value, so padded pixels read as nodata (GeoArray.valid_mask).

Parameters:

Name Type Description Default
g GeoArray

The carrier.

required
window PixelWindow

The pixels to read; may extend past the edges.

required
boundless bool

True returns exactly window.shape, padded with fill outside the array. False returns only the part inside.

True
fill_value Any

The padding value, and the result's fill; defaults to g.fill_value (rules as in pad).

INHERIT

Raises:

Type Description
ValueError

boundless=False and the window misses the array, or padding is needed and there is no fill value.

Example

import numpy as np from geoarray import GeoArray, PixelWindow g = GeoArray(np.ones((4, 4)), (20, 0, 0, 0, -20, 0), 32613, fill_value=0.0) window = PixelWindow(col_off=-1, row_off=-1, width=3, height=3) read_window(g, window).data array([[0., 0., 0.], [0., 1., 1.], [0., 1., 1.]])

Source code in packages/geotoolz-array/src/geoarray/_src/geometry.py
def read_window(
    g: GeoArray,
    window: PixelWindow,
    *,
    boundless: bool = True,
    fill_value: Any = INHERIT,
) -> GeoArray:
    """The pixels of ``window``, padding with fill where it leaves the array.

    The result's fill value is the padding value, so padded pixels read as
    nodata (`GeoArray.valid_mask`).

    Args:
        g: The carrier.
        window: The pixels to read; may extend past the edges.
        boundless: ``True`` returns exactly ``window.shape``, padded with
            fill outside the array. ``False`` returns only the part inside.
        fill_value: The padding value, and the result's fill; defaults to
            ``g.fill_value`` (rules as in `pad`).

    Raises:
        ValueError: ``boundless=False`` and the window misses the array, or
            padding is needed and there is no fill value.

    Example:
        >>> import numpy as np
        >>> from geoarray import GeoArray, PixelWindow
        >>> g = GeoArray(np.ones((4, 4)), (20, 0, 0, 0, -20, 0), 32613, fill_value=0.0)
        >>> window = PixelWindow(col_off=-1, row_off=-1, width=3, height=3)
        >>> read_window(g, window).data
        array([[0., 0., 0.],
               [0., 1., 1.],
               [0., 1., 1.]])
    """
    inside = window.intersection(_whole(g))
    if not boundless:
        if inside is None:
            raise ValueError(
                f"window {window} does not overlap the array {g.shape[-2:]}"
            )
        rows, cols = inside.to_slices()
        return g[..., rows, cols]
    if inside == window:
        rows, cols = window.to_slices()
        return g[..., rows, cols]
    value = _fill_for(g, fill_value, "read_window")
    lead = tuple(g.data.shape[:-2])
    if inside is None:
        data = g.xp.full((*lead, *window.shape), value, dtype=g.dtype)
        transform = _shifted(g, window.row_off, window.col_off)
        return g.with_data(data, transform=transform, fill_value=value)
    rows, cols = inside.to_slices()
    top = inside.row_off - window.row_off
    left = inside.col_off - window.col_off
    bottom = window.height - top - inside.height
    right = window.width - left - inside.width
    return pad(g[..., rows, cols], ((top, bottom), (left, right)), fill_value=value)

geoarray.write_window(g, values, window)

A copy of g with values written into window.

The part of window outside the array is ignored, and values are cast to the carrier's dtype. JAX values promote a NumPy carrier to JAX (C1), so this works inside jit. JAX data is immutable, so this always returns a new carrier (the NumPy input is not modified either).

Parameters:

Name Type Description Default
g GeoArray

The carrier.

required
values Any

(..., h, w) with (h, w) == window.shape and the carrier's leading shape; a GeoArray's data is used.

required
window PixelWindow

Where to write.

required

Raises:

Type Description
ValueError

values does not match window and the leading shape.

TypeError

values would change kind when cast (float into integer data, say).

X64Error

JAX values for a NumPy carrier, which then moves to JAX, with x64 off.

Example

import numpy as np from geoarray import GeoArray, PixelWindow g = GeoArray(np.zeros((3, 3)), (20, 0, 0, 0, -20, 0), 32613) window = PixelWindow(col_off=2, row_off=2, width=2, height=2) write_window(g, np.ones((2, 2)), window).data array([[0., 0., 0.], [0., 0., 0.], [0., 0., 1.]])

Source code in packages/geotoolz-array/src/geoarray/_src/geometry.py
def write_window(g: GeoArray, values: Any, window: PixelWindow) -> GeoArray:
    """A copy of ``g`` with ``values`` written into ``window``.

    The part of ``window`` outside the array is ignored, and ``values``
    are cast to the carrier's dtype. JAX values promote a NumPy carrier to
    JAX (C1), so this works inside ``jit``. JAX data is
    immutable, so this always returns a new carrier (the NumPy input is
    not modified either).

    Args:
        g: The carrier.
        values: ``(..., h, w)`` with ``(h, w) == window.shape`` and the
            carrier's leading shape; a GeoArray's data is used.
        window: Where to write.

    Raises:
        ValueError: ``values`` does not match ``window`` and the leading
            shape.
        TypeError: ``values`` would change kind when cast (float into
            integer data, say).
        X64Error: JAX values for a NumPy carrier, which then moves to JAX,
            with x64 off.

    Example:
        >>> import numpy as np
        >>> from geoarray import GeoArray, PixelWindow
        >>> g = GeoArray(np.zeros((3, 3)), (20, 0, 0, 0, -20, 0), 32613)
        >>> window = PixelWindow(col_off=2, row_off=2, width=2, height=2)
        >>> write_window(g, np.ones((2, 2)), window).data
        array([[0., 0., 0.],
               [0., 0., 0.],
               [0., 0., 1.]])
    """
    values = values.data if isinstance(values, GeoArray) else values
    lead = tuple(g.data.shape[:-2])
    if tuple(values.shape) != (*lead, *window.shape):
        raise ValueError(
            f"values of shape {tuple(values.shape)} do not fit window {window.shape} "
            f"with leading shape {lead}"
        )
    inside = window.intersection(_whole(g))
    if inside is None:
        return g
    rows, cols = inside.to_slices()
    v_rows = slice(
        inside.row_off - window.row_off, inside.row_off - window.row_off + inside.height
    )
    v_cols = slice(
        inside.col_off - window.col_off, inside.col_off - window.col_off + inside.width
    )
    part = values[..., v_rows, v_cols]
    if not np.can_cast(part.dtype, g.dtype, casting="same_kind"):
        raise TypeError(
            f"write_window: {part.dtype} values cannot be written into "
            f"{g.dtype} data without changing their kind; cast them first"
        )
    if g.backend == "numpy" and backend_of(part) == "jax":
        if not is_traced(part):
            report_move("write_window", "NumPy data joined jax")
        g = g.to_jax()
    if g.backend == "numpy":
        data = np.array(g.data, copy=True)
        data[..., rows, cols] = np.asarray(part)
    else:
        data = g.data.at[..., rows, cols].set(g.xp.asarray(part, dtype=g.dtype))
    return g.with_data(data)

geoarray.pad(g, pad_width, *, fill_value=INHERIT)

Add fill pixels around the spatial axes; the transform moves with them.

Parameters:

Name Type Description Default
g GeoArray

The carrier.

required
pad_width Any

One int for every side, or ((top, bottom), (left, right)).

required
fill_value Any

The value of the new pixels, and the result's fill; defaults to g.fill_value. A carrier without a fill takes this one; a carrier with a different fill raises.

INHERIT

Raises:

Type Description
ValueError

No fill value, or a NaN fill for integer data.

Example

import numpy as np from geoarray import GeoArray transform = (20, 0, 600000, 0, -20, 3550000) g = GeoArray(np.ones((1, 2, 2)), transform, 32613, fill_value=0.0) padded = pad(g, ((1, 0), (2, 0))) padded.shape, padded.transform[2], padded.transform[5] ((1, 3, 4), np.float64(599960.0), np.float64(3550020.0))

Source code in packages/geotoolz-array/src/geoarray/_src/geometry.py
def pad(g: GeoArray, pad_width: Any, *, fill_value: Any = INHERIT) -> GeoArray:
    """Add fill pixels around the spatial axes; the transform moves with them.

    Args:
        g: The carrier.
        pad_width: One int for every side, or ``((top, bottom), (left, right))``.
        fill_value: The value of the new pixels, and the result's fill;
            defaults to ``g.fill_value``. A carrier without a fill takes
            this one; a carrier with a different fill raises.

    Raises:
        ValueError: No fill value, or a NaN fill for integer data.

    Example:
        >>> import numpy as np
        >>> from geoarray import GeoArray
        >>> transform = (20, 0, 600000, 0, -20, 3550000)
        >>> g = GeoArray(np.ones((1, 2, 2)), transform, 32613, fill_value=0.0)
        >>> padded = pad(g, ((1, 0), (2, 0)))
        >>> padded.shape, padded.transform[2], padded.transform[5]
        ((1, 3, 4), np.float64(599960.0), np.float64(3550020.0))
    """
    (top, bottom), (left, right) = _pad_widths(pad_width)
    value = _fill_for(g, fill_value, "pad")
    widths = [(0, 0)] * (g.ndim - 2) + [(top, bottom), (left, right)]
    data = g.xp.pad(g.data, widths, mode="constant", constant_values=value)
    return g.with_data(data, transform=_shifted(g, -top, -left), fill_value=value)

geoarray.pixel_coords(g, *, center=True)

Map coordinates of every pixel, (2, H, W): x then y.

x_ij = a·(j + ½) + b·(i + ½) + c, y_ij = d·(j + ½) + e·(i + ½) + f (drop the ½ with center=False for the top-left corners). Runs inside jit; float64 like the transform.

Raises:

Type Description
ValueError

The carrier is batched; use jax.vmap.

Example

import numpy as np from geoarray import GeoArray g = GeoArray(np.zeros((2, 3)), (20, 0, 600000, 0, -20, 3550000), 32613) pixel_coords(g)[:, 0, 0] array([ 600010., 3549990.])

Source code in packages/geotoolz-array/src/geoarray/_src/geometry.py
def pixel_coords(g: GeoArray, *, center: bool = True) -> Any:
    """Map coordinates of every pixel, ``(2, H, W)``: x then y.

    x_ij = a·(j + ½) + b·(i + ½) + c, y_ij = d·(j + ½) + e·(i + ½) + f
    (drop the ½ with ``center=False`` for the top-left corners). Runs
    inside ``jit``; float64 like the transform.

    Raises:
        ValueError: The carrier is batched; use ``jax.vmap``.

    Example:
        >>> import numpy as np
        >>> from geoarray import GeoArray
        >>> g = GeoArray(np.zeros((2, 3)), (20, 0, 600000, 0, -20, 3550000), 32613)
        >>> pixel_coords(g)[:, 0, 0]
        array([ 600010., 3549990.])
    """
    if g.batch_shape:
        raise ValueError(
            "pixel_coords is per scene; use jax.vmap for a batched carrier"
        )
    xp = namespace(g.transform)
    offset = 0.5 if center else 0.0
    cols = xp.arange(g.width, dtype=g.transform.dtype) + offset
    rows = xp.arange(g.height, dtype=g.transform.dtype) + offset
    jj, ii = xp.meshgrid(cols, rows)
    return xp.stack(apply_transform(g.transform, jj, ii))

geoarray.footprint(g, crs=None, *, densify=21)

The outline of the carrier's grid as a shapely Polygon.

Parameters:

Name Type Description Default
g GeoArray

The carrier (concrete, not batched).

required
crs Any

Reproject the outline to this CRS; None keeps the carrier's. Each edge is densified to densify points first, so curved edges stay accurate.

None
densify int

Points per edge when reprojecting.

21

Raises:

Type Description
ImportError

shapely is not installed (geotoolz-array[vector]).

ValueError

crs is given but the carrier has no CRS.

Example

import numpy as np from geoarray import GeoArray g = GeoArray(np.zeros((2, 2)), (20, 0, 600000, 0, -20, 3550000), 32613) footprint(g).bounds (600000.0, 3549960.0, 600040.0, 3550000.0)

Source code in packages/geotoolz-array/src/geoarray/_src/geometry.py
def footprint(g: GeoArray, crs: Any = None, *, densify: int = 21) -> Any:
    """The outline of the carrier's grid as a shapely ``Polygon``.

    Args:
        g: The carrier (concrete, not batched).
        crs: Reproject the outline to this CRS; ``None`` keeps the
            carrier's. Each edge is densified to ``densify`` points first,
            so curved edges stay accurate.
        densify: Points per edge when reprojecting.

    Raises:
        ImportError: shapely is not installed (``geotoolz-array[vector]``).
        ValueError: ``crs`` is given but the carrier has no CRS.

    Example:
        >>> import numpy as np
        >>> from geoarray import GeoArray
        >>> g = GeoArray(np.zeros((2, 2)), (20, 0, 600000, 0, -20, 3550000), 32613)
        >>> footprint(g).bounds
        (600000.0, 3549960.0, 600040.0, 3550000.0)
    """
    try:
        from shapely.geometry import Polygon
    except ImportError as exc:  # pragma: no cover - exercised by the base-install job
        raise ImportError(_SHAPELY_HINT) from exc
    grid = g.grid
    h, w = grid.shape
    if crs is None:
        corners = [(0, 0), (w, 0), (w, h), (0, h)]
        return Polygon([apply_transform(grid.transform, j, i) for j, i in corners])
    if grid.crs is None:
        raise ValueError("footprint(crs=...) needs a carrier with a CRS")
    import pyproj

    steps = np.linspace(0.0, 1.0, densify)[:-1]
    ring = (
        [(w * s, 0.0) for s in steps]
        + [(w, h * s) for s in steps]
        + [(w * (1 - s), h) for s in steps]
        + [(0.0, h * (1 - s)) for s in steps]
    )
    xs, ys = apply_transform(grid.transform, *np.array(ring).T)
    to_crs = pyproj.Transformer.from_crs(grid.crs, crs, always_xy=True)
    tx, ty = to_crs.transform(xs, ys)
    return Polygon(list(zip(tx, ty, strict=True)))

Joining carriers

Carriers on one grid: the same CRS, spatial shape and transform (combine and concat are above).

geoarray.stack(carriers, dim=None, *, axis=None)

Stack carriers on one grid along a new dim.

Three (band, y, x) scenes become one (time, band, y, x) stack. The new dim goes first, after any batch dims, unless axis puts it elsewhere; the result keeps the first carrier's coordinates, fill value and attrs.

Parameters:

Name Type Description Default
carriers Sequence[GeoArray]

GeoArrays on one grid with the same dims.

required
dim str | None

The new dim's name. Omitted (or an int, the 0.2 axis), it is named from the rank with a DeprecationWarning.

None
axis int | None

Where the new dim goes; the default is first.

None

Raises:

Type Description
GridMismatchError

The grids differ.

ValueError

The fill values differ, the name is taken, or axis is a batch or spatial axis.

Example

import numpy as np from geoarray import GeoArray t = (20, 0, 0, 0, -20, 0) g = GeoArray(np.zeros((2, 4, 4)), t, 32613, dims="band y x") stack([g, g, g], "time").dims ('time', 'band', 'y', 'x')

Source code in packages/geotoolz-array/src/geoarray/_src/geometry.py
def stack(
    carriers: Sequence[GeoArray], dim: str | None = None, *, axis: int | None = None
) -> GeoArray:
    """Stack carriers on one grid along a new dim.

    Three ``(band, y, x)`` scenes become one ``(time, band, y, x)`` stack.
    The new dim goes first, after any batch dims, unless ``axis`` puts it
    elsewhere; the result keeps the first carrier's coordinates, fill value
    and attrs.

    Args:
        carriers: GeoArrays on one grid with the same dims.
        dim: The new dim's name. Omitted (or an int, the 0.2 ``axis``), it
            is named from the rank with a ``DeprecationWarning``.
        axis: Where the new dim goes; the default is first.

    Raises:
        GridMismatchError: The grids differ.
        ValueError: The fill values differ, the name is taken, or ``axis``
            is a batch or spatial axis.

    Example:
        >>> import numpy as np
        >>> from geoarray import GeoArray
        >>> t = (20, 0, 0, 0, -20, 0)
        >>> g = GeoArray(np.zeros((2, 4, 4)), t, 32613, dims="band y x")
        >>> stack([g, g, g], "time").dims
        ('time', 'band', 'y', 'x')
    """
    gs = _require_carriers(carriers, "stack")
    gs = _promote(gs, "stack")
    gs = _require_same_grid(gs, "stack")
    _require_same_fill(gs, "stack")
    gs = _in_first_order(gs, "stack")
    first = gs[0]
    dims, position = _stacked_dims(first, dim, axis)
    data = first.xp.stack([g.data for g in gs], axis=position)

    def moved(i: int) -> int:
        return i + 1 if i >= position else i

    # a coordinate stays only where its dim kept its name (the unnamed form
    # may rename every dim)
    coords = tuple(
        c for c in first.coords if dims[moved(first.dims.index(c.dim))] == c.dim
    )
    return first.with_data(data, dims=dims, coords=coords)

geoarray.concatenate(carriers, axis=-3)

Join carriers on one grid along an existing leading axis, by position.

The 0.2 form of concat: axis picks the dim (−3, the default, is band in the 0.2 layout). Prefer geoarray.concat(carriers, dim).

Raises:

Type Description
GridMismatchError

The grids differ.

ValueError

The fill values differ, or axis is a batch or spatial axis.

Example

import numpy as np from geoarray import GeoArray t = (20, 0, 0, 0, -20, 0) b04 = GeoArray(np.zeros((1, 4, 4)), t, 32613, attrs={"band_names": ["B04"]}, ... dims="band y x") b08 = b04.with_data(np.ones((1, 4, 4)), attrs={"band_names": ["B08"]}) concatenate([b04, b08]).attrs["band_names"] ('B04', 'B08')

Source code in packages/geotoolz-array/src/geoarray/_src/geometry.py
def concatenate(carriers: Sequence[GeoArray], axis: int = -3) -> GeoArray:
    """Join carriers on one grid along an existing leading axis, by position.

    The 0.2 form of `concat`: ``axis`` picks the dim (−3, the default, is
    ``band`` in the 0.2 layout). Prefer ``geoarray.concat(carriers, dim)``.

    Raises:
        GridMismatchError: The grids differ.
        ValueError: The fill values differ, or ``axis`` is a batch or
            spatial axis.

    Example:
        >>> import numpy as np
        >>> from geoarray import GeoArray
        >>> t = (20, 0, 0, 0, -20, 0)
        >>> b04 = GeoArray(np.zeros((1, 4, 4)), t, 32613, attrs={"band_names": ["B04"]},
        ...                dims="band y x")
        >>> b08 = b04.with_data(np.ones((1, 4, 4)), attrs={"band_names": ["B08"]})
        >>> concatenate([b04, b08]).attrs["band_names"]
        ('B04', 'B08')
    """
    gs = _require_carriers(carriers, "concatenate")
    position = _leading_axis(gs[0], axis, "concatenate")
    return concat_carriers(gs, gs[0].dims[position])

Lazy readers

What a reader provides so code can read windows of it on demand; a GeoArray is one too.

geoarray.RasterSource

Bases: Protocol

A raster whose grid is known and whose pixels are read on demand.

Implemented by every lazy reader of the stack, and by GeoArray itself (load returns the carrier, read_window slices it). isinstance(x, RasterSource) checks that the members exist.

Attributes:

Name Type Description
grid Grid

The pixel grid: transform, CRS and (H, W).

shape tuple[int, ...]

(..., H, W), the shape load returns.

dtype Any

The dtype of the pixels.

fill_value Any

The nodata value of the pixels read (None for none).

attrs Mapping[str, Any]

Metadata every read carries (band_names, …).

Example

A function that works on any raster, lazy or loaded::

def corner(source: RasterSource) -> GeoArray:
    window = PixelWindow(col_off=0, row_off=0, width=256, height=256)
    return source.read_window(window)  # (..., 256, 256)
Source code in packages/geotoolz-array/src/geoarray/_src/source.py
@runtime_checkable
class RasterSource(Protocol):
    """A raster whose grid is known and whose pixels are read on demand.

    Implemented by every lazy reader of the stack, and by `GeoArray`
    itself (``load`` returns the carrier, ``read_window`` slices it).
    ``isinstance(x, RasterSource)`` checks that the members exist.

    Attributes:
        grid: The pixel grid: transform, CRS and ``(H, W)``.
        shape: ``(..., H, W)``, the shape `load` returns.
        dtype: The dtype of the pixels.
        fill_value: The nodata value of the pixels read (``None`` for none).
        attrs: Metadata every read carries (``band_names``, …).

    Example:
        A function that works on any raster, lazy or loaded::

            def corner(source: RasterSource) -> GeoArray:
                window = PixelWindow(col_off=0, row_off=0, width=256, height=256)
                return source.read_window(window)  # (..., 256, 256)
    """

    @property
    def grid(self) -> Grid: ...

    @property
    def shape(self) -> tuple[int, ...]: ...

    @property
    def dtype(self) -> Any: ...

    @property
    def fill_value(self) -> Any: ...

    @property
    def attrs(self) -> Mapping[str, Any]: ...

    def read_window(self, window: PixelWindow, *, boundless: bool = True) -> GeoArray:
        """The pixels of ``window`` as a `GeoArray` on the window's grid.

        ``boundless=True`` returns exactly ``window.shape``, filled with
        ``fill_value`` where the window leaves the grid; ``False`` returns
        only the part inside.
        """
        ...

    def load(self) -> GeoArray:
        """Every pixel, as a `GeoArray` of `shape`."""
        ...

load()

Every pixel, as a GeoArray of shape.

Source code in packages/geotoolz-array/src/geoarray/_src/source.py
def load(self) -> GeoArray:
    """Every pixel, as a `GeoArray` of `shape`."""
    ...

read_window(window, *, boundless=True)

The pixels of window as a GeoArray on the window's grid.

boundless=True returns exactly window.shape, filled with fill_value where the window leaves the grid; False returns only the part inside.

Source code in packages/geotoolz-array/src/geoarray/_src/source.py
def read_window(self, window: PixelWindow, *, boundless: bool = True) -> GeoArray:
    """The pixels of ``window`` as a `GeoArray` on the window's grid.

    ``boundless=True`` returns exactly ``window.shape``, filled with
    ``fill_value`` where the window leaves the grid; ``False`` returns
    only the part inside.
    """
    ...

geoarray.AsyncRasterSource

Bases: Protocol

RasterSource with coroutine reads, for sources behind a network.

The metadata members are the same and synchronous; aread_window and aload are the awaitable reads. An object may implement both protocols.

Source code in packages/geotoolz-array/src/geoarray/_src/source.py
@runtime_checkable
class AsyncRasterSource(Protocol):
    """`RasterSource` with coroutine reads, for sources behind a network.

    The metadata members are the same and synchronous; ``aread_window`` and
    ``aload`` are the awaitable reads. An object may implement both
    protocols.
    """

    @property
    def grid(self) -> Grid: ...

    @property
    def shape(self) -> tuple[int, ...]: ...

    @property
    def dtype(self) -> Any: ...

    @property
    def fill_value(self) -> Any: ...

    @property
    def attrs(self) -> Mapping[str, Any]: ...

    async def aread_window(
        self, window: PixelWindow, *, boundless: bool = True
    ) -> GeoArray:
        """Awaitable `RasterSource.read_window`."""
        ...

    async def aload(self) -> GeoArray:
        """Awaitable `RasterSource.load`."""
        ...

aload() async

Awaitable RasterSource.load.

Source code in packages/geotoolz-array/src/geoarray/_src/source.py
async def aload(self) -> GeoArray:
    """Awaitable `RasterSource.load`."""
    ...

aread_window(window, *, boundless=True) async

Awaitable RasterSource.read_window.

Source code in packages/geotoolz-array/src/geoarray/_src/source.py
async def aread_window(
    self, window: PixelWindow, *, boundless: bool = True
) -> GeoArray:
    """Awaitable `RasterSource.read_window`."""
    ...

Backends and interop

to_jax() / to_numpy() cross between the backends (see When to jit). NumPy inputs of a join move to JAX when another input is on JAX, and np.asarray(g) copies JAX data to the host (it raises GeoArrayTraceError under a trace). Neither says so, unless pipekit_ops.guard is on:

import pipekit_ops as pk

with pk.guard("warn"):  # or "raise", in a test
    out = pipeline(scene)

geoarray.interop.georeader.from_georeader(gt)

A NumPy GeoArray from a georeader GeoTensor, sharing its memory.

Parameters:

Name Type Description Default
gt Any

A georeader.geotensor.GeoTensor (2-D to 4-D). A lazy reader (GeoData) must be loaded first: gt.load().

required

Returns:

Type Description
GeoArray

The carrier with the same values (no copy), transform, CRS, fill

value and attrs (frozen

lists become tuples).

Raises:

Type Description
ImportError

georeader is not installed.

TypeError

gt is not a GeoTensor, or an attr value cannot be frozen (the error names the key).

Example

import numpy as np from affine import Affine from georeader.geotensor import GeoTensor gt = GeoTensor( ... np.zeros((2, 4, 4), np.float32), Affine(20, 0, 600000, 0, -20, 3550000), ... "EPSG:32613", fill_value_default=np.nan, ... ) g = from_georeader(gt) g.shape, g.grid.bounds[0], np.shares_memory(g.data, gt.values) ((2, 4, 4), 600000.0, True)

Source code in packages/geotoolz-array/src/geoarray/_src/georeader.py
def from_georeader(gt: Any) -> GeoArray:
    """A NumPy `GeoArray` from a georeader ``GeoTensor``, sharing its memory.

    Args:
        gt: A ``georeader.geotensor.GeoTensor`` (2-D to 4-D). A lazy
            reader (``GeoData``) must be loaded first: ``gt.load()``.

    Returns:
        The carrier with the same values (no copy), transform, CRS, fill
        value and attrs (frozen: lists become tuples).

    Raises:
        ImportError: georeader is not installed.
        TypeError: ``gt`` is not a ``GeoTensor``, or an attr value cannot
            be frozen (the error names the key).

    Example:
        >>> import numpy as np
        >>> from affine import Affine
        >>> from georeader.geotensor import GeoTensor
        >>> gt = GeoTensor(
        ...     np.zeros((2, 4, 4), np.float32), Affine(20, 0, 600000, 0, -20, 3550000),
        ...     "EPSG:32613", fill_value_default=np.nan,
        ... )
        >>> g = from_georeader(gt)
        >>> g.shape, g.grid.bounds[0], np.shares_memory(g.data, gt.values)
        ((2, 4, 4), 600000.0, True)
    """
    geotensor = _geotensor_module()
    if not isinstance(gt, geotensor.GeoTensor):
        hint = "; load a lazy reader first with .load()" if hasattr(gt, "load") else ""
        raise TypeError(
            f"from_georeader takes a GeoTensor, got {type(gt).__name__}{hint}"
        )
    values = np.asarray(gt.values)
    return GeoArray(
        values,
        gt.transform,
        gt.crs,
        fill_value=gt.fill_value_default,
        attrs=FrozenAttrs(dict(gt.attrs or {})),
        # georeader's layout is the 0.2 one: ("time", "band", "y", "x")[-ndim:]
        dims=infer_dims(values.ndim, 0),
    )

geoarray.interop.georeader.to_georeader(g)

A georeader GeoTensor from a NumPy GeoArray, sharing its memory.

Parameters:

Name Type Description Default
g GeoArray

A NumPy carrier, not batched. Move a JAX carrier to the host first with GeoArray.to_numpy.

required

Returns:

Type Description
Any

A GeoTensor with the same values (no copy), an affine.Affine

transform, the CRS as ``"AUTH

CODE"`` when that is exact (else

Any

WKT), the fill value (None stays None; georeader's default

Any

of 0 is never assumed) and the attrs as a plain dict.

Raises:

Type Description
ImportError

georeader is not installed.

TypeError

g is not a GeoArray, or holds JAX data.

ValueError

g is batched (GeoTensor has one transform).

Example

import numpy as np from geoarray import GeoArray g = GeoArray(np.ones((4, 4)), (20, 0, 600000, 0, -20, 3550000), 32613) gt = to_georeader(g) gt.crs, gt.transform.c, gt.fill_value_default is None ('EPSG:32613', 600000.0, True)

Source code in packages/geotoolz-array/src/geoarray/_src/georeader.py
def to_georeader(g: GeoArray) -> Any:
    """A georeader ``GeoTensor`` from a NumPy `GeoArray`, sharing its memory.

    Args:
        g: A NumPy carrier, not batched. Move a JAX carrier to the host
            first with `GeoArray.to_numpy`.

    Returns:
        A ``GeoTensor`` with the same values (no copy), an ``affine.Affine``
        transform, the CRS as ``"AUTH:CODE"`` when that is exact (else
        WKT), the fill value (``None`` stays ``None``; georeader's default
        of 0 is never assumed) and the attrs as a plain dict.

    Raises:
        ImportError: georeader is not installed.
        TypeError: ``g`` is not a GeoArray, or holds JAX data.
        ValueError: ``g`` is batched (GeoTensor has one transform).

    Example:
        >>> import numpy as np
        >>> from geoarray import GeoArray
        >>> g = GeoArray(np.ones((4, 4)), (20, 0, 600000, 0, -20, 3550000), 32613)
        >>> gt = to_georeader(g)
        >>> gt.crs, gt.transform.c, gt.fill_value_default is None
        ('EPSG:32613', 600000.0, True)
    """
    geotensor = _geotensor_module()
    if not isinstance(g, GeoArray):
        raise TypeError(f"to_georeader takes a GeoArray, got {type(g).__name__}")
    if g.backend != "numpy":
        raise TypeError(
            "GeoTensor holds NumPy data: move the carrier to the host first "
            "with g.to_numpy()"
        )
    if g.batch_shape:
        raise ValueError(
            f"a batched GeoArray (batch {g.batch_shape}) has one transform per "
            "element; convert each element, e.g. [to_georeader(g[i]) for i ...]"
        )
    return geotensor.GeoTensor(
        g.data,
        transform=Affine(*np.asarray(g.transform).tolist()),
        crs=crs_string(g.crs),
        fill_value_default=g.fill_value,
        attrs=g.attrs.to_dict(),
    )

geoarray.interop.georeader.source_from_georeader(reader)

A georeader GeoData (or GeoTensor) as a RasterSource.

Parameters:

Name Type Description Default
reader Any

A lazy georeader reader (RasterioReader, …), read on demand; or a GeoTensor, converted at once (zero-copy).

required

Returns:

Type Description
RasterSource

A RasterSource whose reads return GeoArray. The wrapped reader

RasterSource

is its reader attribute.

Raises:

Type Description
ImportError

georeader is not installed.

TypeError

reader has no georeader read surface.

Example

from georeader.rasterio_reader import RasterioReader # doctest: +SKIP reader = RasterioReader("scene.tif") # doctest: +SKIP source = source_from_georeader(reader) # doctest: +SKIP source.grid.shape, source.read_window(window).shape # doctest: +SKIP

Source code in packages/geotoolz-array/src/geoarray/_src/georeader.py
def source_from_georeader(reader: Any) -> RasterSource:
    """A georeader ``GeoData`` (or ``GeoTensor``) as a `RasterSource`.

    Args:
        reader: A lazy georeader reader (``RasterioReader``, …), read on
            demand; or a ``GeoTensor``, converted at once (zero-copy).

    Returns:
        A `RasterSource` whose reads return `GeoArray`. The wrapped reader
        is its ``reader`` attribute.

    Raises:
        ImportError: georeader is not installed.
        TypeError: ``reader`` has no georeader read surface.

    Example:
        >>> from georeader.rasterio_reader import RasterioReader  # doctest: +SKIP
        >>> reader = RasterioReader("scene.tif")  # doctest: +SKIP
        >>> source = source_from_georeader(reader)  # doctest: +SKIP
        >>> source.grid.shape, source.read_window(window).shape  # doctest: +SKIP
    """
    geotensor = _geotensor_module()
    if isinstance(reader, geotensor.GeoTensor):
        return from_georeader(reader)
    missing = [
        name
        for name in ("transform", "crs", "shape", "read_from_window", "load")
        if not hasattr(reader, name)
    ]
    if missing:
        raise TypeError(
            f"source_from_georeader takes a georeader GeoData; "
            f"{type(reader).__name__} lacks {missing}"
        )
    return _GeoreaderSource(reader)

geoarray.interop.georeader.source_to_georeader(source)

A RasterSource as a georeader GeoData, for georeader's functions.

georeader's read module (read_from_bounds, read_reproject, …) works on any GeoData; this view lets it read a geotoolz reader window by window. A GeoArray becomes a GeoTensor (to_georeader); a source_from_georeader source gives back the reader it wraps.

Parameters:

Name Type Description Default
source RasterSource

Any RasterSource with NumPy reads.

required

Returns:

Type Description
Any

A GeoData whose reads return GeoTensor.

Raises:

Type Description
ImportError

georeader is not installed.

TypeError

source is not a RasterSource.

Example

from georeader import read # doctest: +SKIP view = source_to_georeader(reader) # doctest: +SKIP tile = read.read_from_bounds(view, bounds) # doctest: +SKIP from_georeader(tile) # doctest: +SKIP

Source code in packages/geotoolz-array/src/geoarray/_src/georeader.py
def source_to_georeader(source: RasterSource) -> Any:
    """A `RasterSource` as a georeader ``GeoData``, for georeader's functions.

    georeader's ``read`` module (``read_from_bounds``, ``read_reproject``,
    …) works on any ``GeoData``; this view lets it read a geotoolz reader
    window by window. A `GeoArray` becomes a ``GeoTensor``
    (`to_georeader`); a `source_from_georeader` source gives back the
    reader it wraps.

    Args:
        source: Any `RasterSource` with NumPy reads.

    Returns:
        A ``GeoData`` whose reads return ``GeoTensor``.

    Raises:
        ImportError: georeader is not installed.
        TypeError: ``source`` is not a `RasterSource`.

    Example:
        >>> from georeader import read  # doctest: +SKIP
        >>> view = source_to_georeader(reader)  # doctest: +SKIP
        >>> tile = read.read_from_bounds(view, bounds)  # doctest: +SKIP
        >>> from_georeader(tile)  # doctest: +SKIP
    """
    if isinstance(source, GeoArray):
        return to_georeader(source)
    if isinstance(source, _GeoreaderSource):
        return source.reader
    if not isinstance(source, RasterSource):
        raise TypeError(
            f"source_to_georeader takes a RasterSource, got {type(source).__name__}"
        )
    return _geodata_class()(source)

xarray

Lossless converters with a CF spatial_ref and GDAL GeoTransform (geotoolz-array[xarray]); see Cross to xarray.

geoarray.interop.xarray.to_xarray(carrier)

A carrier as xarray: a DataArray (grid, swath) or a Dataset (points).

Raises:

Type Description
TypeError

Not a geoarray carrier.

ValueError

A batched grid (one transform per item).

GeoArrayTraceError

Inside jit / grad / vmap.

Example

import numpy as np from geoarray import GeoArray g = GeoArray(np.zeros((2, 3)), (20, 0, 600000, 0, -20, 3550000), 32613, ... dims="y x") da = to_xarray(g) da.coords["spatial_ref"].attrs["GeoTransform"] '600000.0 20.0 0.0 3550000.0 0.0 -20.0'

Source code in packages/geotoolz-array/src/geoarray/_src/xarray.py
def to_xarray(carrier: Any) -> Any:
    """A carrier as xarray: a ``DataArray`` (grid, swath) or a ``Dataset`` (points).

    Raises:
        TypeError: Not a geoarray carrier.
        ValueError: A batched grid (one transform per item).
        GeoArrayTraceError: Inside ``jit`` / ``grad`` / ``vmap``.

    Example:
        >>> import numpy as np
        >>> from geoarray import GeoArray
        >>> g = GeoArray(np.zeros((2, 3)), (20, 0, 600000, 0, -20, 3550000), 32613,
        ...              dims="y x")
        >>> da = to_xarray(g)
        >>> da.coords["spatial_ref"].attrs["GeoTransform"]
        '600000.0 20.0 0.0 3550000.0 0.0 -20.0'
    """
    if isinstance(carrier, GeoArray):
        return grid_to_xarray(carrier)
    if isinstance(carrier, GeoSwath):
        return swath_to_xarray(carrier)
    if isinstance(carrier, GeoPoints):
        return points_to_xarray(carrier)
    raise TypeError(
        "to_xarray takes a GeoArray, GeoSwath or GeoPoints, got "
        f"{type(carrier).__name__}"
    )

geoarray.interop.xarray.from_xarray(obj)

A DataArray or a point Dataset as the matching geoarray carrier.

A DataArray with 2-D lat/lon becomes a GeoSwath; one on an affine grid a GeoArray (its horizontal dims named y x); a Dataset with an obs dim (a CF DSG) a GeoPoints. Lazy (dask) data is computed.

Raises:

Type Description
ValueError

The object has no georeference geoarray can read, or a grid's coordinates are irregular.

GridMismatchError

Centre coordinates disagree with the GeoTransform by more than 10⁻⁹ of a pixel.

Source code in packages/geotoolz-array/src/geoarray/_src/xarray.py
def from_xarray(obj: Any) -> Any:
    """A ``DataArray`` or a point ``Dataset`` as the matching geoarray carrier.

    A ``DataArray`` with 2-D lat/lon becomes a `GeoSwath`; one on an
    affine grid a `GeoArray` (its horizontal dims named ``y x``); a
    ``Dataset`` with an ``obs`` dim (a CF DSG) a `GeoPoints`. Lazy (dask)
    data is computed.

    Raises:
        ValueError: The object has no georeference geoarray can read, or a
            grid's coordinates are irregular.
        GridMismatchError: Centre coordinates disagree with the
            ``GeoTransform`` by more than 10⁻⁹ of a pixel.
    """
    if isinstance(obj, xr.Dataset):
        return points_from_xarray(obj)
    if not isinstance(obj, xr.DataArray):
        raise TypeError(
            f"from_xarray takes a DataArray or a Dataset, got {type(obj).__name__}"
        )
    kind = read_kind(obj)
    if kind is not None and kind.kind == "swath":
        return swath_from_xarray(obj)
    return grid_from_xarray(obj)

geoarray.interop.xarray.to_dataset(carriers)

Carriers on one grid as the variables of one Dataset (LL-F3).

Raises:

Type Description
GridMismatchError

The carriers are on different grids; use to_datatree for several grids.

ValueError

A shared non-spatial dim has different coordinates (red here, nir there): xarray would align them.

Source code in packages/geotoolz-array/src/geoarray/_src/xarray.py
def to_dataset(carriers: Mapping[str, GeoArray]) -> Any:
    """Carriers on one grid as the variables of one ``Dataset`` (LL-F3).

    Raises:
        GridMismatchError: The carriers are on different grids; use
            `to_datatree` for several grids.
        ValueError: A shared non-spatial dim has different coordinates
            (``red`` here, ``nir`` there): xarray would align them.
    """
    from geoarray._src.geometry import _require_same_grid

    items = list(carriers.items())
    if not items:
        raise ValueError("to_dataset needs at least one carrier")
    _require_same_grid([g for _, g in items], "to_dataset")
    arrays = {name: grid_to_xarray(g) for name, g in items}
    try:
        # one Dataset shares coordinates: never let xarray align (union) them
        xr.align(*arrays.values(), join="exact", copy=False)
    except ValueError as exc:
        raise ValueError(
            "to_dataset: the carriers' coordinates differ (band names, levels, "
            "times, …), so xarray would align them and insert NaN; give them "
            f"one layout first, or use to_datatree: {exc}"
        ) from exc
    return xr.Dataset(arrays)

geoarray.interop.xarray.from_dataset(ds)

Each grid variable of a Dataset as a GeoArray, by name.

Source code in packages/geotoolz-array/src/geoarray/_src/xarray.py
def from_dataset(ds: Any) -> dict[str, GeoArray]:
    """Each grid variable of a ``Dataset`` as a `GeoArray`, by name."""
    out = {}
    for name, da in ds.data_vars.items():
        if read_kind(da) is not None:
            out[str(name)] = from_xarray(da)
    return out

geoarray.interop.xarray.to_datatree(groups)

Several grids as one DataTree: one node per grid (LL-F3).

Parameters:

Name Type Description Default
groups Mapping[str, GeoArray | Mapping[str, GeoArray]]

Node name → a carrier (stored under the node's name) or a mapping of carriers on that node's grid.

required
Example

import numpy as np from geoarray import GeoArray t10 = (10, 0, 600000, 0, -10, 3550000) t20 = (20, 0, 600000, 0, -20, 3550000) r10 = GeoArray(np.zeros((4, 4)), t10, 32613, dims="y x") r20 = GeoArray(np.zeros((2, 2)), t20, 32613, dims="y x") sorted(to_datatree({"r10m": r10, "r20m": r20}).children) ['r10m', 'r20m']

Source code in packages/geotoolz-array/src/geoarray/_src/xarray.py
def to_datatree(groups: Mapping[str, GeoArray | Mapping[str, GeoArray]]) -> Any:
    """Several grids as one ``DataTree``: one node per grid (LL-F3).

    Args:
        groups: Node name → a carrier (stored under the node's name) or a
            mapping of carriers on that node's grid.

    Example:
        >>> import numpy as np
        >>> from geoarray import GeoArray
        >>> t10 = (10, 0, 600000, 0, -10, 3550000)
        >>> t20 = (20, 0, 600000, 0, -20, 3550000)
        >>> r10 = GeoArray(np.zeros((4, 4)), t10, 32613, dims="y x")
        >>> r20 = GeoArray(np.zeros((2, 2)), t20, 32613, dims="y x")
        >>> sorted(to_datatree({"r10m": r10, "r20m": r20}).children)
        ['r10m', 'r20m']
    """
    nodes = {}
    for name, value in groups.items():
        mapping: Mapping[str, GeoArray] = (
            {name: value} if isinstance(value, GeoArray) else value
        )
        nodes[f"/{name}"] = to_dataset(mapping)
    return xr.DataTree.from_dict(nodes)

geoarray.interop.xarray.from_datatree(tree)

Every node of a DataTree holding grids: node path → its carriers.

Source code in packages/geotoolz-array/src/geoarray/_src/xarray.py
def from_datatree(tree: Any) -> dict[str, dict[str, GeoArray]]:
    """Every node of a ``DataTree`` holding grids: node path → its carriers."""
    out = {}
    for node in tree.subtree:
        carriers = from_dataset(node.to_dataset())
        if carriers:
            out[node.path] = carriers
    return out

Coercions

Turn transforms and CRSs from other libraries into geoarray's.

geoarray.as_transform(transform)

Coerce a transform to a tuple of six Python floats (a, b, c, d, e, f).

Parameters:

Name Type Description Default
transform Any

An affine.Affine (rasterio's Affine is the same class), six numbers, the nine numbers of a 3 × 3 affine matrix, or a (2, 3) / (3, 3) array.

required

Returns:

Type Description
Transform

(a, b, c, d, e, f) as Python floats.

Raises:

Type Description
ValueError

The input does not describe an affine transform.

Example

as_transform(Affine(20.0, 0.0, 600000.0, 0.0, -20.0, 3550000.0)) (20.0, 0.0, 600000.0, 0.0, -20.0, 3550000.0)

Source code in packages/geotoolz-array/src/geoarray/_src/grid.py
def as_transform(transform: Any) -> Transform:
    """Coerce a transform to a tuple of six Python floats (a, b, c, d, e, f).

    Args:
        transform: An ``affine.Affine`` (rasterio's ``Affine`` is the same
            class), six numbers, the nine numbers of a 3 × 3 affine matrix,
            or a ``(2, 3)`` / ``(3, 3)`` array.

    Returns:
        ``(a, b, c, d, e, f)`` as Python floats.

    Raises:
        ValueError: The input does not describe an affine transform.

    Example:
        >>> as_transform(Affine(20.0, 0.0, 600000.0, 0.0, -20.0, 3550000.0))
        (20.0, 0.0, 600000.0, 0.0, -20.0, 3550000.0)
    """
    if isinstance(transform, Affine):
        return (
            float(transform.a),
            float(transform.b),
            float(transform.c),
            float(transform.d),
            float(transform.e),
            float(transform.f),
        )
    try:
        arr = np.asarray(transform, dtype=np.float64)
    except (TypeError, ValueError) as exc:
        raise ValueError(f"not an affine transform: {transform!r}") from exc
    flat = arr.reshape(-1)
    if flat.size == 9:
        if not np.allclose(flat[6:], (0.0, 0.0, 1.0)):
            raise ValueError(
                f"the last row of an affine matrix must be (0, 0, 1): {flat[6:]}"
            )
        flat = flat[:6]
    if flat.size != 6:
        raise ValueError(
            "an affine transform has 6 numbers (a, b, c, d, e, f); "
            f"got shape {arr.shape}"
        )
    a, b, c, d, e, f = (float(v) for v in flat)
    return (a, b, c, d, e, f)

geoarray.as_crs(crs)

Coerce crs to a pyproj.CRS; None stays None.

Accepts anything pyproj.CRS.from_user_input does: "EPSG:32613", an EPSG integer, WKT, PROJ JSON, or an object with to_wkt() such as a rasterio CRS.

Raises:

Type Description
ValueError

crs is not a CRS pyproj understands.

Example

as_crs(32613).to_epsg() 32613

Source code in packages/geotoolz-array/src/geoarray/_src/grid.py
def as_crs(crs: Any) -> pyproj.CRS | None:
    """Coerce ``crs`` to a ``pyproj.CRS``; ``None`` stays ``None``.

    Accepts anything ``pyproj.CRS.from_user_input`` does: ``"EPSG:32613"``,
    an EPSG integer, WKT, PROJ JSON, or an object with ``to_wkt()`` such as
    a rasterio ``CRS``.

    Raises:
        ValueError: ``crs`` is not a CRS pyproj understands.

    Example:
        >>> as_crs(32613).to_epsg()
        32613
    """
    if crs is None or isinstance(crs, pyproj.CRS):
        return crs
    try:
        return pyproj.CRS.from_user_input(crs)
    except pyproj.exceptions.CRSError as exc:
        raise ValueError(f"not a CRS: {crs!r}") from exc

Errors

Every error geoarray raises on its own account subclasses GeoArrayError.

geoarray.GeoArrayError

Bases: Exception

Base class of every error geoarray raises on its own account.

Source code in packages/geotoolz-array/src/geoarray/_src/errors.py
class GeoArrayError(Exception):
    """Base class of every error geoarray raises on its own account."""

geoarray.X64Error

Bases: GeoArrayError, RuntimeError

A JAX carrier needs jax_enable_x64: its transform is float64.

In float32 the spacing of representable numbers is 0.25 m at a UTM northing of 3.55 × 10⁶ m, so a float32 transform silently misplaces pixels. geoarray refuses rather than rounding.

Source code in packages/geotoolz-array/src/geoarray/_src/errors.py
class X64Error(GeoArrayError, RuntimeError):
    """A JAX carrier needs ``jax_enable_x64``: its transform is float64.

    In float32 the spacing of representable numbers is 0.25 m at a UTM
    northing of 3.55 × 10⁶ m, so a float32 transform silently misplaces
    pixels. geoarray refuses rather than rounding.
    """

geoarray.GeoArrayTraceError

Bases: GeoArrayError, TypeError

An operation needs concrete values but got JAX tracers.

Inside jit, grad or vmap a GeoArray's data and transform are tracers. Anything that must read their values on the host (a Grid, a NumPy function, GeoArray.to_numpy) raises this instead of JAX's TracerArrayConversionError, naming what to do instead.

Source code in packages/geotoolz-array/src/geoarray/_src/errors.py
class GeoArrayTraceError(GeoArrayError, TypeError):
    """An operation needs concrete values but got JAX tracers.

    Inside ``jit``, ``grad`` or ``vmap`` a GeoArray's data and transform are
    tracers. Anything that must read their values on the host (a `Grid`, a
    NumPy function, `GeoArray.to_numpy`) raises this instead of JAX's
    ``TracerArrayConversionError``, naming what to do instead.
    """

geoarray.GridMismatchError

Bases: GeoArrayError, ValueError

Carriers that must share one pixel grid do not.

combine, stack and concatenate need the same CRS, spatial shape, batch shape and (when concrete) an exactly equal transform. Resample one carrier onto the other's grid first (geoops.geom).

Source code in packages/geotoolz-array/src/geoarray/_src/errors.py
class GridMismatchError(GeoArrayError, ValueError):
    """Carriers that must share one pixel grid do not.

    `combine`, `stack` and `concatenate` need the same CRS, spatial shape,
    batch shape and (when concrete) an exactly equal transform. Resample
    one carrier onto the other's grid first (``geoops.geom``).
    """

geoarray.LabelError

Bases: GeoArrayError, KeyError

A selection by label that a carrier cannot do.

GeoArray.sel looks up exact labels of a dim's coordinate (band names, level values, time stamps). A dim without labels, a label that is not there, or a range or nearest-neighbour lookup raises this; selection by value lives in xarray (g.to_xarray().sel(...)).

Source code in packages/geotoolz-array/src/geoarray/_src/errors.py
class LabelError(GeoArrayError, KeyError):
    """A selection by label that a carrier cannot do.

    `GeoArray.sel` looks up exact labels of a dim's coordinate (band names,
    level values, time stamps). A dim without labels, a label that is not
    there, or a range or nearest-neighbour lookup raises this; selection by
    value lives in xarray (``g.to_xarray().sel(...)``).
    """

    def __str__(self) -> str:
        # KeyError quotes its message; show it as written
        return str(self.args[0]) if self.args else ""

geoarray.types.DimsError

Bases: GeoArrayError, TypeError

A carrier's dims (or kind) do not fit the readable type a function declares.

Source code in packages/geotoolz-array/src/geoarray/_src/types.py
class DimsError(GeoArrayError, TypeError):
    """A carrier's dims (or kind) do not fit the readable type a function declares."""