-
Notifications
You must be signed in to change notification settings - Fork 86
Expand file tree
/
Copy path__init__.py
More file actions
703 lines (601 loc) · 21.2 KB
/
__init__.py
File metadata and controls
703 lines (601 loc) · 21.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
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
"""Out-of-core CRS reprojection and multi-raster merge.
Public API
----------
reproject(raster, target_crs, ...)
Reproject a DataArray to a new coordinate reference system.
merge(rasters, ...)
Merge multiple DataArrays into a single mosaic.
"""
from __future__ import annotations
import numpy as np
import xarray as xr
from ._crs_utils import _detect_nodata, _detect_source_crs, _resolve_crs
from ._grid import (
_chunk_bounds,
_compute_chunk_layout,
_compute_output_grid,
_make_output_coords,
)
from ._interpolate import _resample_cupy, _resample_numpy, _validate_resampling
from ._merge import _merge_arrays_cupy, _merge_arrays_numpy, _validate_strategy
from ._transform import ApproximateTransform
__all__ = ['reproject', 'merge']
# ---------------------------------------------------------------------------
# Source geometry helpers
# ---------------------------------------------------------------------------
def _source_bounds(raster):
"""Extract (left, bottom, right, top) from a DataArray's coordinates."""
ydim = raster.dims[-2]
xdim = raster.dims[-1]
y = raster.coords[ydim].values
x = raster.coords[xdim].values
# Compute pixel-edge bounds from pixel-center coords
if len(y) > 1:
res_y = abs(float(y[1] - y[0]))
else:
res_y = 1.0
if len(x) > 1:
res_x = abs(float(x[1] - x[0]))
else:
res_x = 1.0
x_min, x_max = float(np.min(x)), float(np.max(x))
y_min, y_max = float(np.min(y)), float(np.max(y))
left = x_min - res_x / 2
right = x_max + res_x / 2
bottom = y_min - res_y / 2
top = y_max + res_y / 2
return (left, bottom, right, top)
def _is_y_descending(raster):
"""Check if Y axis goes from top (large) to bottom (small)."""
ydim = raster.dims[-2]
y = raster.coords[ydim].values
if len(y) < 2:
return True
return float(y[0]) > float(y[-1])
# ---------------------------------------------------------------------------
# Per-chunk worker functions
# ---------------------------------------------------------------------------
def _reproject_chunk_numpy(
source_data, source_bounds_tuple, source_shape, source_y_desc,
src_wkt, tgt_wkt,
chunk_bounds_tuple, chunk_shape,
resampling, nodata, transform_precision,
):
"""Reproject a single output chunk (numpy backend).
Called inside ``dask.delayed`` for the dask path, or directly for numpy.
CRS objects are passed as WKT strings for pickle safety.
"""
from ._crs_utils import _require_pyproj
pyproj = _require_pyproj()
src_crs = pyproj.CRS.from_wkt(src_wkt)
tgt_crs = pyproj.CRS.from_wkt(tgt_wkt)
# Build inverse transformer: target -> source
transformer = pyproj.Transformer.from_crs(
tgt_crs, src_crs, always_xy=True
)
height, width = chunk_shape
approx = ApproximateTransform(
transformer, chunk_bounds_tuple, chunk_shape,
precision=transform_precision,
)
# All output pixel positions (broadcast 1-D arrays to avoid HxW meshgrid)
row_grid = np.arange(height, dtype=np.float64)[:, np.newaxis]
col_grid = np.arange(width, dtype=np.float64)[np.newaxis, :]
row_grid = np.broadcast_to(row_grid, (height, width))
col_grid = np.broadcast_to(col_grid, (height, width))
# Source CRS coordinates for each output pixel
src_y, src_x = approx(row_grid, col_grid)
# Convert source CRS coordinates to source pixel coordinates
src_left, src_bottom, src_right, src_top = source_bounds_tuple
src_h, src_w = source_shape
src_res_x = (src_right - src_left) / src_w
src_res_y = (src_top - src_bottom) / src_h
src_col_px = (src_x - src_left) / src_res_x - 0.5
if source_y_desc:
src_row_px = (src_top - src_y) / src_res_y - 0.5
else:
src_row_px = (src_y - src_bottom) / src_res_y - 0.5
# Determine source window needed
r_min = int(np.floor(np.nanmin(src_row_px))) - 2
r_max = int(np.ceil(np.nanmax(src_row_px))) + 3
c_min = int(np.floor(np.nanmin(src_col_px))) - 2
c_max = int(np.ceil(np.nanmax(src_col_px))) + 3
# Check overlap
if r_min >= src_h or r_max <= 0 or c_min >= src_w or c_max <= 0:
return np.full(chunk_shape, nodata, dtype=np.float64)
# Clip to source bounds
r_min_clip = max(0, r_min)
r_max_clip = min(src_h, r_max)
c_min_clip = max(0, c_min)
c_max_clip = min(src_w, c_max)
# Extract source window
window = source_data[r_min_clip:r_max_clip, c_min_clip:c_max_clip]
if hasattr(window, 'compute'):
window = window.compute()
window = np.asarray(window, dtype=np.float64)
# Convert sentinel nodata to NaN so numba kernels can detect it
if not np.isnan(nodata):
window = window.copy()
window[window == nodata] = np.nan
# Adjust coordinates relative to window
local_row = src_row_px - r_min_clip
local_col = src_col_px - c_min_clip
return _resample_numpy(window, local_row, local_col,
resampling=resampling, nodata=nodata)
def _reproject_chunk_cupy(
source_data, source_bounds_tuple, source_shape, source_y_desc,
src_wkt, tgt_wkt,
chunk_bounds_tuple, chunk_shape,
resampling, nodata, transform_precision,
):
"""CuPy variant of ``_reproject_chunk_numpy``."""
import cupy as cp
from ._crs_utils import _require_pyproj
pyproj = _require_pyproj()
src_crs = pyproj.CRS.from_wkt(src_wkt)
tgt_crs = pyproj.CRS.from_wkt(tgt_wkt)
transformer = pyproj.Transformer.from_crs(
tgt_crs, src_crs, always_xy=True
)
height, width = chunk_shape
approx = ApproximateTransform(
transformer, chunk_bounds_tuple, chunk_shape,
precision=transform_precision,
)
row_grid = np.arange(height, dtype=np.float64)[:, np.newaxis]
col_grid = np.arange(width, dtype=np.float64)[np.newaxis, :]
row_grid = np.broadcast_to(row_grid, (height, width))
col_grid = np.broadcast_to(col_grid, (height, width))
# Control grid is on CPU
src_y, src_x = approx(row_grid, col_grid)
src_left, src_bottom, src_right, src_top = source_bounds_tuple
src_h, src_w = source_shape
src_res_x = (src_right - src_left) / src_w
src_res_y = (src_top - src_bottom) / src_h
src_col_px = (src_x - src_left) / src_res_x - 0.5
if source_y_desc:
src_row_px = (src_top - src_y) / src_res_y - 0.5
else:
src_row_px = (src_y - src_bottom) / src_res_y - 0.5
r_min = int(np.floor(np.nanmin(src_row_px))) - 2
r_max = int(np.ceil(np.nanmax(src_row_px))) + 3
c_min = int(np.floor(np.nanmin(src_col_px))) - 2
c_max = int(np.ceil(np.nanmax(src_col_px))) + 3
if r_min >= src_h or r_max <= 0 or c_min >= src_w or c_max <= 0:
return cp.full(chunk_shape, nodata, dtype=cp.float64)
r_min_clip = max(0, r_min)
r_max_clip = min(src_h, r_max)
c_min_clip = max(0, c_min)
c_max_clip = min(src_w, c_max)
window = source_data[r_min_clip:r_max_clip, c_min_clip:c_max_clip]
if hasattr(window, 'compute'):
window = window.compute()
if not isinstance(window, cp.ndarray):
window = cp.asarray(window)
window = window.astype(cp.float64)
# Convert sentinel nodata to NaN
if not np.isnan(nodata):
window = window.copy()
window[window == nodata] = cp.nan
local_row = src_row_px - r_min_clip
local_col = src_col_px - c_min_clip
return _resample_cupy(window, local_row, local_col,
resampling=resampling, nodata=nodata)
# ---------------------------------------------------------------------------
# reproject()
# ---------------------------------------------------------------------------
def reproject(
raster,
target_crs,
*,
source_crs=None,
resolution=None,
bounds=None,
width=None,
height=None,
resampling='bilinear',
nodata=None,
transform_precision=16,
chunk_size=None,
name=None,
):
"""Reproject a raster DataArray to a new coordinate reference system.
Supports numpy, cupy, dask+numpy, and dask+cupy backends. For dask
inputs, the computation is fully lazy: each output chunk independently
reads only the source pixels it needs.
Parameters
----------
raster : xr.DataArray
Input raster with y/x coordinates.
target_crs
Target CRS in any format accepted by ``pyproj.CRS()``.
source_crs : optional
Source CRS. Auto-detected from *raster* if None.
resolution : float or (float, float) or None
Output pixel size in target CRS units.
bounds : (left, bottom, right, top) or None
Explicit output extent in target CRS.
width, height : int or None
Explicit output grid dimensions.
resampling : str
One of 'nearest', 'bilinear', 'cubic'.
nodata : float or None
Nodata value. Auto-detected if None.
transform_precision : int
Coarse grid subdivisions for approximate transform (default 16).
chunk_size : int or (int, int) or None
Output chunk size for dask. Defaults to 512.
name : str or None
Name for the output DataArray.
Returns
-------
xr.DataArray
"""
from ._crs_utils import _require_pyproj
if not isinstance(raster, xr.DataArray):
raise TypeError(
f"reproject(): raster must be an xr.DataArray, "
f"got {type(raster).__name__}"
)
_validate_resampling(resampling)
_require_pyproj()
# Resolve CRS
src_crs = _resolve_crs(source_crs)
if src_crs is None:
src_crs = _detect_source_crs(raster)
if src_crs is None:
raise ValueError(
"Could not detect source CRS. Pass source_crs explicitly."
)
tgt_crs = _resolve_crs(target_crs)
# Detect nodata
nd = _detect_nodata(raster, nodata)
# Source geometry
src_bounds = _source_bounds(raster)
src_shape = (raster.sizes[raster.dims[-2]], raster.sizes[raster.dims[-1]])
y_desc = _is_y_descending(raster)
# Compute output grid
grid = _compute_output_grid(
src_bounds, src_shape, src_crs, tgt_crs,
resolution=resolution, bounds=bounds,
width=width, height=height,
)
out_bounds = grid['bounds']
out_shape = grid['shape']
# Output coordinates
y_coords, x_coords = _make_output_coords(out_bounds, out_shape)
# Detect backend
from ..utils import has_dask_array, is_cupy_array
data = raster.data
is_dask = False
if has_dask_array():
import dask.array as _da
is_dask = isinstance(data, _da.Array)
is_cupy = False
if is_dask:
# Check underlying type
try:
from ..utils import is_cupy_backed
is_cupy = is_cupy_backed(raster)
except (ImportError, Exception):
pass
else:
is_cupy = is_cupy_array(data)
# Serialize CRS for pickle safety
src_wkt = src_crs.to_wkt()
tgt_wkt = tgt_crs.to_wkt()
if is_dask:
result_data = _reproject_dask(
raster, src_bounds, src_shape, y_desc,
src_wkt, tgt_wkt,
out_bounds, out_shape,
resampling, nd, transform_precision,
chunk_size, is_cupy,
)
elif is_cupy:
result_data = _reproject_inmemory_cupy(
raster, src_bounds, src_shape, y_desc,
src_wkt, tgt_wkt,
out_bounds, out_shape,
resampling, nd, transform_precision,
)
else:
result_data = _reproject_inmemory_numpy(
raster, src_bounds, src_shape, y_desc,
src_wkt, tgt_wkt,
out_bounds, out_shape,
resampling, nd, transform_precision,
)
ydim = raster.dims[-2]
xdim = raster.dims[-1]
result = xr.DataArray(
result_data,
dims=[ydim, xdim],
coords={ydim: y_coords, xdim: x_coords},
name=name or raster.name,
attrs={
'crs': tgt_wkt,
'nodata': nd,
},
)
return result
def _reproject_inmemory_numpy(
raster, src_bounds, src_shape, y_desc,
src_wkt, tgt_wkt,
out_bounds, out_shape,
resampling, nodata, precision,
):
"""Single-chunk numpy reproject."""
return _reproject_chunk_numpy(
raster.values,
src_bounds, src_shape, y_desc,
src_wkt, tgt_wkt,
out_bounds, out_shape,
resampling, nodata, precision,
)
def _reproject_inmemory_cupy(
raster, src_bounds, src_shape, y_desc,
src_wkt, tgt_wkt,
out_bounds, out_shape,
resampling, nodata, precision,
):
"""Single-chunk cupy reproject."""
return _reproject_chunk_cupy(
raster.data,
src_bounds, src_shape, y_desc,
src_wkt, tgt_wkt,
out_bounds, out_shape,
resampling, nodata, precision,
)
def _reproject_dask(
raster, src_bounds, src_shape, y_desc,
src_wkt, tgt_wkt,
out_bounds, out_shape,
resampling, nodata, precision,
chunk_size, is_cupy,
):
"""Dask backend: build output as ``da.block`` of delayed chunks."""
import dask
import dask.array as da
row_chunks, col_chunks = _compute_chunk_layout(out_shape, chunk_size)
n_row = len(row_chunks)
n_col = len(col_chunks)
chunk_fn = _reproject_chunk_cupy if is_cupy else _reproject_chunk_numpy
dtype = np.float64
blocks = [[None] * n_col for _ in range(n_row)]
row_offset = 0
for i in range(n_row):
col_offset = 0
for j in range(n_col):
rchunk = row_chunks[i]
cchunk = col_chunks[j]
cb = _chunk_bounds(
out_bounds, out_shape,
row_offset, row_offset + rchunk,
col_offset, col_offset + cchunk,
)
delayed_chunk = dask.delayed(chunk_fn)(
raster.data,
src_bounds, src_shape, y_desc,
src_wkt, tgt_wkt,
cb, (rchunk, cchunk),
resampling, nodata, precision,
)
blocks[i][j] = da.from_delayed(
delayed_chunk, shape=(rchunk, cchunk), dtype=dtype
)
col_offset += cchunk
row_offset += rchunk
return da.block(blocks)
# ---------------------------------------------------------------------------
# merge()
# ---------------------------------------------------------------------------
def merge(
rasters,
*,
target_crs=None,
resolution=None,
bounds=None,
resampling='bilinear',
nodata=None,
strategy='first',
chunk_size=None,
name=None,
):
"""Merge multiple rasters into a single mosaic.
Each input is reprojected to the target CRS (if needed) and placed
into a unified output grid. Overlapping regions are resolved using
the selected *strategy*.
Parameters
----------
rasters : list of xr.DataArray
Input rasters to merge.
target_crs : optional
Target CRS. Defaults to the CRS of the first raster.
resolution : float or (float, float) or None
Output resolution in target CRS units.
bounds : (left, bottom, right, top) or None
Explicit output extent.
resampling : str
Interpolation method: 'nearest', 'bilinear', 'cubic'.
nodata : float or None
Nodata value for the output.
strategy : str
Merge strategy: 'first', 'last', 'mean', 'max', 'min'.
chunk_size : int or (int, int) or None
Chunk size for dask output.
name : str or None
Name for the output DataArray.
Returns
-------
xr.DataArray
"""
from ._crs_utils import _require_pyproj
if not rasters:
raise ValueError("merge(): rasters list must not be empty")
_validate_resampling(resampling)
_validate_strategy(strategy)
pyproj = _require_pyproj()
# Resolve target CRS
tgt_crs = _resolve_crs(target_crs)
if tgt_crs is None:
tgt_crs = _detect_source_crs(rasters[0])
if tgt_crs is None:
raise ValueError(
"Could not detect target CRS. Pass target_crs explicitly."
)
# Detect nodata
nd = nodata if nodata is not None else _detect_nodata(rasters[0], nodata)
# Gather source info for each raster
raster_infos = []
for r in rasters:
src_crs = _detect_source_crs(r)
if src_crs is None:
raise ValueError(
f"Could not detect CRS for raster '{r.name}'. "
"Ensure all rasters have CRS metadata."
)
sb = _source_bounds(r)
ss = (r.sizes[r.dims[-2]], r.sizes[r.dims[-1]])
yd = _is_y_descending(r)
raster_infos.append({
'raster': r,
'src_crs': src_crs,
'src_bounds': sb,
'src_shape': ss,
'y_desc': yd,
'src_wkt': src_crs.to_wkt(),
})
# Compute unified output grid
if bounds is None:
# Union of all raster bounds in target CRS
all_bounds = []
for info in raster_infos:
grid = _compute_output_grid(
info['src_bounds'], info['src_shape'],
info['src_crs'], tgt_crs,
resolution=resolution,
)
all_bounds.append(grid['bounds'])
left = min(b[0] for b in all_bounds)
bottom = min(b[1] for b in all_bounds)
right = max(b[2] for b in all_bounds)
top = max(b[3] for b in all_bounds)
merged_bounds = (left, bottom, right, top)
else:
merged_bounds = bounds
# Use first raster's info for resolution estimation if needed
info0 = raster_infos[0]
grid = _compute_output_grid(
info0['src_bounds'], info0['src_shape'],
info0['src_crs'], tgt_crs,
resolution=resolution, bounds=merged_bounds,
)
out_bounds = grid['bounds']
out_shape = grid['shape']
tgt_wkt = tgt_crs.to_wkt()
# Detect if any input is dask
from ..utils import has_dask_array
any_dask = False
if has_dask_array():
import dask.array as _da
any_dask = any(isinstance(r.data, _da.Array) for r in rasters)
if any_dask:
result_data = _merge_dask(
raster_infos, tgt_wkt, out_bounds, out_shape,
resampling, nd, strategy, chunk_size,
)
else:
result_data = _merge_inmemory(
raster_infos, tgt_wkt, out_bounds, out_shape,
resampling, nd, strategy,
)
y_coords, x_coords = _make_output_coords(out_bounds, out_shape)
ydim = rasters[0].dims[-2]
xdim = rasters[0].dims[-1]
result = xr.DataArray(
result_data,
dims=[ydim, xdim],
coords={ydim: y_coords, xdim: x_coords},
name=name or 'merged',
attrs={
'crs': tgt_wkt,
'nodata': nd,
},
)
return result
def _merge_inmemory(
raster_infos, tgt_wkt, out_bounds, out_shape,
resampling, nodata, strategy,
):
"""In-memory merge using numpy."""
arrays = []
for info in raster_infos:
reprojected = _reproject_chunk_numpy(
info['raster'].values,
info['src_bounds'], info['src_shape'], info['y_desc'],
info['src_wkt'], tgt_wkt,
out_bounds, out_shape,
resampling, nodata, 16,
)
arrays.append(reprojected)
return _merge_arrays_numpy(arrays, nodata, strategy)
def _merge_chunk_worker(
raster_data_list, src_bounds_list, src_shape_list, y_desc_list,
src_wkt_list, tgt_wkt,
chunk_bounds_tuple, chunk_shape,
resampling, nodata, strategy, precision,
):
"""Worker for a single merge chunk."""
arrays = []
for i in range(len(raster_data_list)):
reprojected = _reproject_chunk_numpy(
raster_data_list[i],
src_bounds_list[i], src_shape_list[i], y_desc_list[i],
src_wkt_list[i], tgt_wkt,
chunk_bounds_tuple, chunk_shape,
resampling, nodata, precision,
)
arrays.append(reprojected)
return _merge_arrays_numpy(arrays, nodata, strategy)
def _merge_dask(
raster_infos, tgt_wkt, out_bounds, out_shape,
resampling, nodata, strategy, chunk_size,
):
"""Dask merge backend."""
import dask
import dask.array as da
row_chunks, col_chunks = _compute_chunk_layout(out_shape, chunk_size)
n_row = len(row_chunks)
n_col = len(col_chunks)
# Prepare lists for the worker
data_list = [info['raster'].data for info in raster_infos]
bounds_list = [info['src_bounds'] for info in raster_infos]
shape_list = [info['src_shape'] for info in raster_infos]
ydesc_list = [info['y_desc'] for info in raster_infos]
wkt_list = [info['src_wkt'] for info in raster_infos]
dtype = np.float64
blocks = [[None] * n_col for _ in range(n_row)]
row_offset = 0
for i in range(n_row):
col_offset = 0
for j in range(n_col):
rchunk = row_chunks[i]
cchunk = col_chunks[j]
cb = _chunk_bounds(
out_bounds, out_shape,
row_offset, row_offset + rchunk,
col_offset, col_offset + cchunk,
)
delayed_chunk = dask.delayed(_merge_chunk_worker)(
data_list, bounds_list, shape_list, ydesc_list,
wkt_list, tgt_wkt,
cb, (rchunk, cchunk),
resampling, nodata, strategy, 16,
)
blocks[i][j] = da.from_delayed(
delayed_chunk, shape=(rchunk, cchunk), dtype=dtype
)
col_offset += cchunk
row_offset += rchunk
return da.block(blocks)