Calculate percentile of numpy stack and return the index of the chosen pixel.

            numpy percentile function is used with one of the following interpolations {'linear', 'lower', 'higher',
            'midpoint', 'nearest'}
342524
def _numpy_index_by_percentile(self, data, percentile):
        
        data_perc_low = np.nanpercentile(data, percentile, axis=0, interpolation=self.interpolation)

        indices = np.empty(data_perc_low.shape, dtype=np.uint8)
        indices[:] = np.nan

        abs_diff = np.where(np.isnan(data_perc_low), np.inf, abs(data - data_perc_low))

        indices = np.where(np.isnan(data_perc_low), self.max_index, np.nanargmin(abs_diff, axis=0))

        return indices
722565
def percentAt(self, value):
        
        min_val = self.minimum()
        max_val = self.maximum()
        
        if value < min_val:
            return 0.0
        elif max_val < value:
            return 1.0
        
        # round the max value to sync with the values in the grid
        max_val = self.rounded(max_val)
        
        try:
            perc = (value - min_val) / float(max_val - min_val)
        except (TypeError, ZeroDivisionError):
            return 0.0
        
        return max(min(perc, 1.0), 0.0)
282093
def _check_percentile(self, q):
        

        msg = ("percentiles should all be in the interval [0, 1]. "
               "Try {0} instead.")
        q = np.asarray(q)
        if q.ndim == 0:
            if not 0 <= q <= 1:
                raise ValueError(msg.format(q / 100.0))
        else:
            if not all(0 <= qs <= 1 for qs in q):
                raise ValueError(msg.format(q / 100.0))
        return q
92510
def take_percentile(arr, percent):
    
    size = len(arr)
    stop = min(int(size * percent), len(arr))
    return arr[0:stop]
336233
public static <T, U extends Comparable<? super U>> Collector<T, ?, Optional<U>> median(Function<? super T, ? extends U> function) {
        return percentile(0.5, function);
    }
213161
def median(self, name, **kwargs):
        
        data = self.get(name,**kwargs)
        return np.percentile(data,[50])
550452
def get_median(data_np):
    """"""
    i = np.isfinite(data_np)
    if not np.any(i):
        return np.nan
    return np.median(data_np[i])
193453
def perc(arr, p=95, **kwargs):
    """"""
    offset = (100 - p) / 2
    return np.percentile(arr, (offset, 100 - offset), **kwargs)
184017
def _sentinel_stats(
    src_path, percentiles=(2, 98), histogram_bins=10, histogram_range=None
):
    

    with rasterio.open(src_path) as src:
        arr = src.read(indexes=[1], masked=True)
        arr[arr == 0] = np.ma.masked

    params = {}
    if histogram_bins:
        params.update(dict(bins=histogram_bins))
    if histogram_range:
        params.update(dict(range=histogram_range))

    return {1: utils._stats(arr, percentiles=percentiles, **params)}
962630
def quantile(x, q, weights=None):
    
    if weights is None:
        return np.percentile(x, [100. * qi for qi in q])
    else:
        idx = np.argsort(x)
        xsorted = x[idx]
        cdf = np.add.accumulate(weights[idx])
        cdf /= cdf[-1]
        return np.interp(q, cdf, xsorted).tolist()
533503
def percentile(values=None, percentile=None):
    
    if values in [None, tuple(), []] or len(values) < 1:
        raise InsufficientData(
            "Expected a sequence of at least 1 integers, got {0!r}".format(values))
    if percentile is None:
        raise ValueError("Expected a percentile choice, got {0}".format(percentile))

    sorted_values = sorted(values)

    rank = len(values) * percentile / 100
    if rank > 0:
        index = rank - 1
        if index < 0:
            return sorted_values[0]
    else:
        index = rank

    if index % 1 == 0:
        return sorted_values[int(index)]
    else:
        fractional = index % 1
        integer = int(index - fractional)
        lower = sorted_values[integer]
        higher = sorted_values[integer + 1]
        return lower + fractional * (higher - lower)
903686
function percentPx(parentWd, WD, noNeg) {
        var wd = WD || 0; // ensure it is number  // null --> 0

        if (wd >= 1 || wd == 0) return wd;else if (wd <= -1) return noNeg ? 0 : wd;else if (typeof parentWd != 'number') return null;else if (wd >= 0.9999) // 100%
          return parentWd;else if (wd >= 0) return wd * parentWd;else {
          if (noNeg) return 0;
          if (wd > -0.9999) return wd * parentWd;else return -parentWd; // -100%
        }
      }
321901
def x(self):
        '''
        
        '''
        if None not in (self.x_min, self.x_max, self.x_step) and \
                self.x_min != self.x_max:
            x = np.arange(self.x_min, self.x_max+self.x_step-self.y_step*0.1, self.x_step)
        else:
            x = np.array([])
        return x
518551
def percentiles(self, percentiles):
    """"""
    try:
      scores = [0.0]*len(percentiles)

      if self.count > 0:
        values = self.samples()
        values.sort()

        for i in range(len(percentiles)):
          p = percentiles[i]
          pos = p * (len(values) + 1)
          if pos < 1:
            scores[i] = values[0]
          elif pos > len(values):
            scores[i] = values[-1]
          else:
            upper, lower = values[int(pos - 1)], values[int(pos)]
            scores[i] = lower + (pos - floor(pos)) * (upper - lower)

      return scores
    except IndexError:
      return [float('NaN')] * len(percentiles)
120876
def _geoville_index_by_percentile(self, data, percentile):
        
        # no_obs = bn.allnan(arr_tmp["data"], axis=0)
        data_tmp = np.array(data, copy=True)
        valid_obs = np.sum(np.isfinite(data_tmp), axis=0)
        # replace NaN with maximum
        max_val = np.nanmax(data_tmp) + 1
        data_tmp[np.isnan(data_tmp)] = max_val
        # sort - former NaNs will move to the end
        ind_tmp = np.argsort(data_tmp, kind="mergesort", axis=0)
        # desired position as well as floor and ceiling of it
        k_arr = (valid_obs - 1) * (percentile / 100.0)
        k_arr = np.where(k_arr < 0, 0, k_arr)
        f_arr = np.floor(k_arr + 0.5)
        f_arr = f_arr.astype(np.int)
        # get floor value of reference band and index band
        ind = f_arr.astype("int16")
        y_val, x_val = ind_tmp.shape[1], ind_tmp.shape[2]
        y_val, x_val = np.ogrid[0:y_val, 0:x_val]
        idx = np.where(valid_obs == 0, self.max_index, ind_tmp[ind, y_val, x_val])
        return idx
953771
def median(self, default=None):
        
        return numpy.asscalar(numpy.median(self.values)) if self.values else default
382468
def percentile(values, percent):
    
    N = sorted(values)
    if not N:
        return None
    k = (len(N) - 1) * percent
    f = int(math.floor(k))
    c = int(math.ceil(k))
    if f == c:
        return N[int(k)]
    d0 = N[f] * (c - k)
    d1 = N[c] * (k - f)
    return d0 + d1