def _balanced_spatial_average(array, kernel):
    """
    Compute the balanced spatial average of an array using a given kernel while handling
    missing or invalid values.
    """
    array = array.copy()
    mask_valid = np.isfinite(array)
    array[~mask_valid] = 0.0
    array_conv = convolve(array, kernel, mode="same")
    array_conv /= convolve(mask_valid, kernel, mode="same")
    array_conv[~mask_valid] = np.nan
    return array_conv
Compute the balanced spatial average of an array using a given kernel while handling
missing or invalid values.
pysteps/downscaling/rainfarm.py