def flatten(values, mask):
    """Flatten the spatial dimensions of the input array
    and removed masked points
    """
    
    # Flatten and mask the input array
    args = [-1] if values.ndim < 4 else values.shape[:2]
    maskflat = mask.ravel().astype(bool)
    valuesflat = values.reshape(*args, len(maskflat))[..., maskflat]
    
    return valuesflat