Create symmetric percentiles, with ``p`` coverage.
193453
def perc(arr, p=95, **kwargs):
    """"""
    offset = (100 - p) / 2
    return np.percentile(arr, (offset, 100 - offset), **kwargs)
464173
def maskedNanPercentile(maskedArray, percentiles, *args, **kwargs):
    

    #https://docs.scipy.org/doc/numpy/reference/maskedarray.generic.html#accessing-the-data
    awm = ArrayWithMask.createFromMaskedArray(maskedArray)

    maskIdx = awm.maskIndex()
    validData = awm.data[~maskIdx]

    if len(validData) >= 1:
        result = np.nanpercentile(validData, percentiles, *args, **kwargs)
    else:
        # If np.nanpercentile on an empty list only returns a single Nan. We correct this here.
        result = len(percentiles) * [np.nan]

    assert len(result) == len(percentiles), \
        "shape mismatch: {} != {}".format(len(result), len(percentiles))

    return result
573456
def pformat(self, prefix=()):
        '''
        
        '''
        nan = float("nan")

        def sformat(segment, stat):
            FMT = "n={0}, mean={1}, p50/95={2}/{3}, max={4}"
            line_segs = [segment]
            for s in [stat]:
                p = s.get_percentiles()
                p50, p95 = p.get(0.50, nan), p.get(0.95, nan)
                line_segs.append(FMT.format(s.n, s.mean, p50, p95, s.max))
            return '{0}: {1}'.format(*line_segs)

        lines = []
        for path in sorted(self.path_stats.keys()):
            lines.append('=====================')
            for seg, stat in zip(path, self.path_stats[path]):
                lines.append(sformat(seg, stat))
        return lines
1098293
public double percentile(double p) {
    long[] counts = new long[PercentileBuckets.length()];
    for (int i = 0; i < counts.length; ++i) {
      counts[i] = counterFor(i).count();
    }
    return PercentileBuckets.percentile(counts, p);
  }
1118567
def scoreatpercentile(data,per,axis=0):
    ''
    a = np.sort(data,axis=axis)
    idx = per/100. * (data.shape[axis]-1)

    if (idx % 1 == 0):
        return a[[slice(None) if ii != axis else idx for ii in range(a.ndim)]]
    else:
        lowerweight = 1-(idx % 1)
        upperweight = (idx % 1)
        idx = int(np.floor(idx))
        return lowerweight * a[[slice(None) if ii != axis else idx for ii in range(a.ndim)]] \
                + upperweight * a[[slice(None) if ii != axis else idx+1 for ii in range(a.ndim)]]
858073
def _percent_selection(self, non_empty_slices):
        """"""

        return np.around(self._sampler * len(non_empty_slices) / 100).astype('int64')
1100406
def normalize_layout(layout, min_percentile=1, max_percentile=99, relative_margin=0.1):
    """"""

    # compute percentiles
    mins = np.percentile(layout, min_percentile, axis=(0))
    maxs = np.percentile(layout, max_percentile, axis=(0))

    # add margins
    mins -= relative_margin * (maxs - mins)
    maxs += relative_margin * (maxs - mins)

    # `clip` broadcasts, `[None]`s added only for readability
    clipped = np.clip(layout, mins, maxs)

    # embed within [0,1] along both axes
    clipped -= clipped.min(axis=0)
    clipped /= clipped.max(axis=0)

    return clipped
905772
public static Map<Percentage, Long> percentiles(final long[] sortedArray) {
        N.checkArgNotNullOrEmpty(sortedArray, "The spcified 'sortedArray' can not be null or empty");

        final int len = sortedArray.length;
        final Map<Percentage, Long> m = new LinkedHashMap<>(N.initHashCapacity(Percentage.values().length));

        for (Percentage p : Percentage.values()) {
            m.put(p, sortedArray[(int) (len * p.doubleValue())]);
        }

        return ImmutableMap.of(m);
    }
1109604
def _whole_gene_covered_by_nucmer_hits(nucmer_hits, ref_seq, percent_threshold, max_nt_extend):
        ''''''
        coords = AssemblyCompare.nucmer_hits_to_ref_coords(nucmer_hits)
        covered = []
        for coords_list in coords.values():
            covered.extend(coords_list)
        pyfastaq.intervals.merge_overlapping_in_list(covered)
        return (2 * max_nt_extend + pyfastaq.intervals.length_sum_from_list(covered)) / len(ref_seq) >= percent_threshold
558591
def compute_percentile(self, percentage):
        
        all_patches = self.get_all_patches()
        return all_patches[
            int(len(all_patches) * percentage / 100)
        ].start_position
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
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)
534229
public static <T> Collector<T, ?, Optional<T>> percentile(double percentile, Comparator<? super T> comparator) {
        return percentile(percentile, t -> t, comparator);
    }
92510
def take_percentile(arr, percent):
    
    size = len(arr)
    stop = min(int(size * percent), len(arr))
    return arr[0:stop]
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%
        }
      }
389822
def _get_best_percentile(self, cluster, counts):
        '''  '''

        if len(cluster) == 1:
            return list(cluster)
        else:
            threshold = np.median(list(counts.values()))/100
            return [read for read in cluster if counts[read] > threshold]
1143534
def _generatePattern(numBits, totalSize):
    
    indices = random.sample(xrange(totalSize), numBits)
    return set(indices)