# create an Affine from shape and (optionally) bbox
def from_dim(dim, bbox = None):
if bbox is None:
bbox = (0.0, 0.0, dim[0], dim[1])
gdal = (bbox[0], (bbox[2] - bbox[0]) / dim[0], 0.0,
bbox[3], 0.0, (bbox[1] - bbox[3]) / dim[1] )
return(affine.Affine.from_gdal(*gdal))
bbox = (-180, -90, 180, 90)
shape = (4, 2) ## a 4x2 chunk world
from_dim(shape, bbox)
#Affine(90.0, 0.0, -180.0,
# 0.0, -90.0, 90.0)
from xarray.indexes import CoordinateTransformIndex
transform = Affine2DCoordinateTransform(
from_dim(shape, bbox),
coord_names=("xc", "yc"),
dim_size={"x": shape[0], "y": shape[1]},
)
index = CoordinateTransformIndex(transform)
ds = xr.Dataset(coords=index.create_coordinates())
print(ds.xc.values)
print(ds.yc.values)
## compare to the cell centres
af = from_dim(shape, bbox)
#[[-180. -90. 0. 90.]
# [-180. -90. 0. 90.]]
#[[90. 90. 90. 90.]
# [ 0. 0. 0. 0.]]
print([x + af.a/2 for x in ds.xc.values])
print([y + af.e/2 for y in ds.yc.values])
#[array([-135., -45., 45., 135.]), array([-135., -45., 45., 135.])]
#[array([45., 45., 45., 45.]), array([-45., -45., -45., -45.])]
I put in a bit more experimentation, creating lazy coords with a polar dataset
https://github.com/mdsumner/xarraycoords/blob/main/xarray_coords.ipynb
(coords are probably off and at least aren't ordered dimension wise sensibly)