| 1 |
# cython: language_level=3, boundscheck=False, cdivision=True, wraparound=False, initializedcheck=False, nonecheck=False |
| 2 |
from functools import wraps |
| 3 |
|
| 4 |
cimport cython |
| 5 |
cimport numpy as np |
| 6 |
from libc.math cimport asin, sin, cos, sqrt, acos, M_PI |
| 7 |
import numpy as np |
| 8 |
|
| 9 |
np.import_array() |
| 10 |
|
| 11 |
try: |
| 12 |
import dask.array as da |
| 13 |
except ImportError: |
| 14 |
# if dask can't be imported then we aren't going to be given dask arrays |
| 15 |
da = None |
| 16 |
|
| 17 |
try: |
| 18 |
import xarray as xr |
| 19 |
except ImportError: |
| 20 |
xr = None |
| 21 |
|
| 22 |
|
| 23 |
DEF EARTH_RADIUS = 6370997.0 |
| 24 |
|
| 25 |
|
| 26 |
cdef void lonlat2xyz( |
| 27 |
floating[:, ::1] lons, |
| 28 |
floating[:, ::1] lats, |
| 29 |
floating[:, :, ::1] xyz, |
| 30 |
) noexcept nogil: |
| 31 |
"""Convert lons and lats to cartesian coordinates.""" |
| 32 |
cdef Py_ssize_t i, j, k |
| 33 |
cdef floating lon_rad, lat_rad |
| 34 |
for i in range(lons.shape[0]): |
| 35 |
for j in range(lons.shape[1]): |
| 36 |
lon_rad = deg2rad(lons[i, j]) |
| 37 |
lat_rad = deg2rad(lats[i, j]) |
| 38 |
xyz[i, j, 0] = EARTH_RADIUS * cos(lat_rad) * cos(lon_rad) |
| 39 |
xyz[i, j, 1] = EARTH_RADIUS * cos(lat_rad) * sin(lon_rad) |
| 40 |
xyz[i, j, 2] = EARTH_RADIUS * sin(lat_rad) |
| 41 |
|
| 42 |
|
| 43 |
cdef void xyz2lonlat( |
| 44 |
floating[:, :, ::1] xyz, |
| 45 |
floating[:, ::1] lons, |
| 46 |
floating[:, ::1] lats, |
| 47 |
bint low_lat_z=True, |
| 48 |
floating thr=0.8) noexcept nogil: |
| 49 |
"""Get longitudes from cartesian coordinates.""" |
| 50 |
cdef Py_ssize_t i, j |
| 51 |
cdef np.float64_t x, y, z |
| 52 |
for i in range(xyz.shape[0]): |
| 53 |
for j in range(xyz.shape[1]): |
| 54 |
# 64-bit precision matters apparently |
| 55 |
x = <np.float64_t>xyz[i, j, 0] |
| 56 |
y = <np.float64_t>xyz[i, j, 1] |
| 57 |
z = <np.float64_t>xyz[i, j, 2] |
| 58 |
lons[i, j] = rad2deg(acos(x / sqrt(x ** 2 + y ** 2))) * _sign(y) |
| 59 |
# if we are at low latitudes - small z, then get the |
| 60 |
# latitudes only from z. If we are at high latitudes (close to the poles) |
| 61 |
# then derive the latitude using x and y: |
| 62 |
if low_lat_z and (z < thr * EARTH_RADIUS) and (z > -1.0 * thr * EARTH_RADIUS): |
| 63 |
lats[i, j] = 90 - rad2deg(acos(z / EARTH_RADIUS)) |
| 64 |
else: |
| 65 |
lats[i, j] = _sign(z) * (90 - rad2deg(asin(sqrt(x ** 2 + y ** 2) / EARTH_RADIUS))) |
| 66 |
|
| 67 |
|
| 68 |
cdef inline int _sign(floating x) noexcept nogil: |
| 69 |
return 1 if x > 0 else (-1 if x < 0 else 0) |
| 70 |
|
| 71 |
|
| 72 |
cdef inline floating rad2deg(floating x) noexcept nogil: |
| 73 |
return x * (180.0 / M_PI) |
| 74 |
|
| 75 |
|
| 76 |
cdef inline floating deg2rad(floating x) noexcept nogil: |
| 77 |
return x * (M_PI / 180.0) |
| 78 |
|
| 79 |
|
| 80 |
def rows_per_scan_for_resolution(res): |
| 81 |
return { |
| 82 |
5000: 2, |
| 83 |
1000: 10, |
| 84 |
500: 20, |
| 85 |
250: 40, |
| 86 |
}[res] |
| 87 |
|
| 88 |
|
| 89 |
def scanline_mapblocks(func): |
| 90 |
"""Convert dask array inputs to appropriate map_blocks calls. |
| 91 |
|
| 92 |
This function, applied as a decorator, will call the wrapped function |
| 93 |
using dask's ``map_blocks``. It will rechunk dask array inputs when |
| 94 |
necessary to make sure that the input chunks are entire scanlines to |
| 95 |
avoid incorrect interpolation. |
| 96 |
|
| 97 |
""" |
| 98 |
@wraps(func) |
| 99 |
def _wrapper(*args, coarse_resolution=None, fine_resolution=None, **kwargs): |
| 100 |
if coarse_resolution is None or fine_resolution is None: |
| 101 |
raise ValueError("'coarse_resolution' and 'fine_resolution' are required keyword arguments.") |
| 102 |
first_arr = [arr for arr in args if hasattr(arr, "ndim")][0] |
| 103 |
if first_arr.ndim != 2 or first_arr.ndim != 2: |
| 104 |
raise ValueError("Expected 2D input arrays.") |
| 105 |
if hasattr(first_arr, "compute"): |
| 106 |
# assume it is dask or xarray with dask, ensure proper chunk size |
| 107 |
# if DataArray get just the dask array |
| 108 |
dask_args = _extract_dask_arrays_from_args(args) |
| 109 |
rows_per_scan = rows_per_scan_for_resolution(coarse_resolution) |
| 110 |
rechunked_args = _rechunk_dask_arrays_if_needed(dask_args, rows_per_scan) |
| 111 |
results = _call_map_blocks_interp( |
| 112 |
func, |
| 113 |
coarse_resolution, |
| 114 |
fine_resolution, |
| 115 |
*rechunked_args, |
| 116 |
**kwargs |
| 117 |
) |
| 118 |
if hasattr(first_arr, "dims"): |
| 119 |
# recreate DataArrays |
| 120 |
results = _results_to_data_arrays(first_arr.dims, *results) |
| 121 |
return results |
| 122 |
return func( |
| 123 |
*args, |
| 124 |
coarse_resolution=coarse_resolution, |
| 125 |
fine_resolution=fine_resolution, |
| 126 |
**kwargs |
| 127 |
) |
| 128 |
|
| 129 |
return _wrapper |
| 130 |
|
| 131 |
|
| 132 |
def _extract_dask_arrays_from_args(args): |
| 133 |
return [arr_obj.data if hasattr(arr_obj, "dims") else arr_obj for arr_obj in args] |
| 134 |
|
| 135 |
|
| 136 |
def _call_map_blocks_interp(func, coarse_resolution, fine_resolution, *args, **kwargs): |
| 137 |
first_arr = [arr for arr in args if hasattr(arr, "ndim")][0] |
| 138 |
res_factor = coarse_resolution // fine_resolution |
| 139 |
new_row_chunks = tuple(x * res_factor for x in first_arr.chunks[0]) |
| 140 |
fine_pixels_per_1km = {250: 4, 500: 2, 1000: 1}[fine_resolution] |
| 141 |
fine_scan_width = 1354 * fine_pixels_per_1km |
| 142 |
new_col_chunks = (fine_scan_width,) |
| 143 |
wrapped_func = _map_blocks_handler(func) |
| 144 |
res = da.map_blocks(wrapped_func, *args, |
| 145 |
coarse_resolution=coarse_resolution, |
| 146 |
fine_resolution=fine_resolution, |
| 147 |
**kwargs, |
| 148 |
new_axis=[0], |
| 149 |
chunks=(2, new_row_chunks, new_col_chunks), |
| 150 |
dtype=first_arr.dtype, |
| 151 |
meta=np.empty((2, 2, 2), dtype=first_arr.dtype)) |
| 152 |
return tuple(res[idx] for idx in range(res.shape[0])) |
| 153 |
|
| 154 |
|
| 155 |
def _results_to_data_arrays(dims, *results): |
| 156 |
new_results = [] |
| 157 |
for result in results: |
| 158 |
if not isinstance(result, da.Array): |
| 159 |
continue |
| 160 |
data_arr = xr.DataArray(result, dims=dims) |
| 161 |
new_results.append(data_arr) |
| 162 |
return new_results |
| 163 |
|
| 164 |
|
| 165 |
def _rechunk_dask_arrays_if_needed(args, rows_per_scan: int): |
| 166 |
# take current chunk size and get a relatively similar chunk size |
| 167 |
first_arr = [arr for arr in args if hasattr(arr, "ndim")][0] |
| 168 |
row_chunks = first_arr.chunks[0] |
| 169 |
col_chunks = first_arr.chunks[1] |
| 170 |
num_rows = first_arr.shape[0] |
| 171 |
num_cols = first_arr.shape[1] |
| 172 |
good_row_chunks = all(x % rows_per_scan == 0 for x in row_chunks) |
| 173 |
good_col_chunks = len(col_chunks) == 1 and col_chunks[0] != num_cols |
| 174 |
all_orig_chunks = [arr.chunks for arr in args if hasattr(arr, "chunks")] |
| 175 |
|
| 176 |
if num_rows % rows_per_scan != 0: |
| 177 |
raise ValueError("Input longitude/latitude data does not consist of " |
| 178 |
"whole scans (10 rows per scan).") |
| 179 |
all_same_chunks = all( |
| 180 |
all_orig_chunks[0] == some_chunks |
| 181 |
for some_chunks in all_orig_chunks[1:] |
| 182 |
) |
| 183 |
if good_row_chunks and good_col_chunks and all_same_chunks: |
| 184 |
return args |
| 185 |
|
| 186 |
new_row_chunks = (row_chunks[0] // rows_per_scan) * rows_per_scan |
| 187 |
new_args = [arr.rechunk((new_row_chunks, -1)) if hasattr(arr, "chunks") else arr for arr in args] |
| 188 |
return new_args |
| 189 |
|
| 190 |
|
| 191 |
def _map_blocks_handler(func): |
| 192 |
@wraps(func) |
| 193 |
def _map_blocks_wrapper(*args, **kwargs): |
| 194 |
results = func(*args, **kwargs) |
| 195 |
return np.concatenate( |
| 196 |
tuple(result[np.newaxis] for result in results), |
| 197 |
axis=0) |
| 198 |
return _map_blocks_wrapper |
| 199 |
|
| 200 |
|