2121
2222from rasterix .odc_compat import BoundingBox , bbox_intersection , bbox_union , maybe_int , snap_grid
2323from rasterix .rioxarray_compat import guess_dims
24+ from rasterix .utils import get_affine
2425
2526T_Xarray = TypeVar ("T_Xarray" , "DataArray" , "Dataset" )
2627
@@ -37,10 +38,14 @@ def assign_index(
3738) -> T_Xarray :
3839 """Assign a RasterIndex to an Xarray DataArray or Dataset.
3940
41+ By default, the affine transform is guessed by first looking for a ``GeoTransform`` attribute
42+ on a CF "grid mapping" variable (commonly ``"spatial_ref"``). If not present, then the affine is determined from 1D coordinate
43+ variables named ``x_dim`` and ``y_dim`` provided to this function.
44+
4045 Parameters
4146 ----------
4247 obj : xarray.DataArray or xarray.Dataset
43- The object to assign the index to. Must have a rio accessor with a transform.
48+ The object to assign the index to.
4449 x_dim : str, optional
4550 Name of the x dimension. If None, will be automatically detected.
4651 y_dim : str, optional
@@ -53,22 +58,37 @@ def assign_index(
5358 xarray.DataArray or xarray.Dataset
5459 The input object with RasterIndex coordinates assigned.
5560
61+ Notes
62+ -----
63+ The "grid mapping" variable is determined following the CF conventions:
64+
65+ - If a DataArray is provided, we look for an attribute named ``"grid_mapping"``.
66+ - For a Dataset, we pull the first detected ``"grid_mapping"`` attribute when iterating over data variables.
67+
68+ The value of this attribute is a variable name containing projection information (commonly ``"spatial_ref"``).
69+ We then look for a ``"GeoTransform"`` attribute on this variable (following GDAL convention).
70+
71+ References
72+ ----------
73+ - `CF conventions document <http://cfconventions.org/Data/cf-conventions/cf-conventions-1.11/cf-conventions.html#grid-mappings-and-projections>`_.
74+ - `GDAL docs on GeoTransform <https://gdal.org/en/stable/tutorials/geotransforms_tut.html>`_.
75+
5676 Examples
5777 --------
5878 >>> import xarray as xr
59- >>> import rioxarray # Required for rio accessor
79+ >>> import rioxarray # Required for reading TIFF
6080 >>> da = xr.open_dataset("path/to/raster.tif", engine="rasterio")
6181 >>> indexed_da = assign_index(da)
6282 """
63- import rioxarray # noqa
64-
6583 if x_dim is None or y_dim is None :
6684 guessed_x , guessed_y = guess_dims (obj )
6785 x_dim = x_dim or guessed_x
6886 y_dim = y_dim or guessed_y
6987
88+ affine = get_affine (obj , x_dim = x_dim , y_dim = y_dim , clear_transform = True )
89+
7090 index = RasterIndex .from_transform (
71- obj . rio . transform () ,
91+ affine ,
7292 width = obj .sizes [x_dim ],
7393 height = obj .sizes [y_dim ],
7494 x_dim = x_dim ,
0 commit comments