From ``bruges``

    Extrapolate up and down an array from the first and last non-NaN samples.

    E.g. Continue the first and last non-NaN values of a log up and down.
512332
def extrapolate(a):
    
    nans = np.where(~np.isnan(a))[0]
    first, last = nans[0], nans[-1]
    a[:first] = a[first]
    a[last + 1:] = a[last]
    return a
1151159
def downsample_with_averaging(array, factor):
    
    factor = tuple(factor)
    output_shape = tuple(int(math.ceil(s / f)) for s, f in zip(array.shape, factor))
    temp = np.zeros(output_shape, dtype=np.float32)
    counts = np.zeros(output_shape, np.int)
    for offset in np.ndindex(factor):
        part = array[tuple(np.s_[o::f] for o, f in zip(offset, factor))]
        indexing_expr = tuple(np.s_[:s] for s in part.shape)
        temp[indexing_expr] += part
        counts[indexing_expr] += 1
    return np.cast[array.dtype](temp / counts)
1284108
def _before_after(n_samples):
    """"""
    if not isinstance(n_samples, (tuple, list)):
        before = n_samples // 2
        after = n_samples - before
    else:
        assert len(n_samples) == 2
        before, after = n_samples
        n_samples = before + after
    assert before >= 0
    assert after >= 0
    assert before + after == n_samples
    return before, after
42562
def multi_reciprocal_extra(xs, ys, noise=False):
    
    ns = np.linspace(0.5, 6.0, num=56)
    best = ['', np.inf]
    fit_results = {}
    weights = get_weights(xs, ys)
    for n in ns:
        popt = extrapolate_reciprocal(xs, ys, n, noise)
        m = measure(reciprocal, xs, ys, popt, weights)
        pcov = []
        fit_results.update({n: {'measure': m, 'popt': popt, 'pcov': pcov}})
    for n in fit_results:
        if fit_results[n]['measure'] <= best[1]:
            best = reciprocal, fit_results[n]['measure'], n
    return fit_results[best[2]]['popt'], fit_results[best[2]]['pcov'], best
1303067
def extrap1d(interpolator):
    
    
    xs = interpolator.x
    ys = interpolator.y

    def pointwise(x):
        if x < xs[0]:
            return ys[0] # +(x-xs[0])*(ys[1]-ys[0])/(xs[1]-xs[0])
        elif x > xs[-1]:
            return ys[-1] # +(x-xs[-1])*(ys[-1]-ys[-2])/(xs[-1]-xs[-2])
        else:
            return interpolator(x)

    def ufunclike(xs):
        return N.array(map(pointwise, N.array(xs)))

    return ufunclike
744806
def peaks(samples):
    
    max_index = numpy.argmax(samples)
    max_value = samples[max_index]

    min_index = numpy.argmin(samples)
    min_value = samples[min_index]

    if min_index < max_index:
        return (min_value, max_value)
    else:
        return (max_value, min_value)
1226304
def interpolate(p, axis_values, pixelgrid, order=1, mode='constant', cval=0.0):
    
    # convert requested parameter combination into a coordinate
    p_ = np.array([np.searchsorted(av_,val) for av_, val in zip(axis_values,p)])
    lowervals_stepsize = np.array([[av_[p__-1], av_[p__]-av_[p__-1]] \
                         for av_, p__ in zip(axis_values,p_)])
    p_coord = (p-lowervals_stepsize[:,0])/lowervals_stepsize[:,1] + p_-1
    
    # interpolate
    if order > 1:
        prefilter = False
    else:
        prefilter = False

    return [ndimage.map_coordinates(pixelgrid[...,i],p_coord, order=order,
                                    prefilter=prefilter, mode=mode, cval=cval) \
                for i in range(np.shape(pixelgrid)[-1])]
75233
function interpolatePairs( _ps, t1, t2 ) {
  var pn = [];
  for (var i=0; i<_ps.length; i++) {
    var next = (i==_ps.length-1) ? 0 : i+1;
    pn.push( new Pair( _ps[i].interpolate( t1 ) ).to( _ps[next].interpolate( 1-t2 ) ) );
  }
  return pn;
}
650503
def _extrapolate_rows(self, data, row_indices, first_index, last_index):
        

        pos = row_indices[:2]
        first_row = _linear_extrapolate(pos,
                                        (data[0, :], data[1, :]),
                                        first_index)
        pos = row_indices[-2:]
        last_row = _linear_extrapolate(pos,
                                       (data[-2, :], data[-1, :]),
                                       last_index)
        return np.vstack((np.expand_dims(first_row, 0),
                          data,
                          np.expand_dims(last_row, 0)))
1201604
def sample(N, D):
    """"""
    scale = 31
    result = np.zeros([N, D])
    
    if D > len(directions) + 1:
        raise ValueError("Error in Sobol sequence: not enough dimensions")

    L = int(math.ceil(math.log(N) / math.log(2)))

    if L > scale:
        raise ValueError("Error in Sobol sequence: not enough bits")

    for i in range(D):
        V = np.zeros(L + 1, dtype=long)

        if i == 0:
            for j in range(1, L + 1):
                V[j] = 1 << (scale - j)  # all m's = 1
        else:
            m = np.array(directions[i - 1], dtype=int)
            a = m[0]
            s = len(m) - 1

            # The following code discards the first row of the ``m`` array
            # Because it has floating point errors, e.g. values of 2.24e-314
            if L <= s:
                for j in range(1, L + 1):
                    V[j] = m[j] << (scale - j)
            else:
                for j in range(1, s + 1):
                    V[j] = m[j] << (scale - j)
                for j in range(s + 1, L + 1):
                    V[j] = V[j - s] ^ (V[j - s] >> s)
                    for k in range(1, s):
                        V[j] ^= ((a >> (s - 1 - k)) & 1) * V[j - k]

        X = long(0)
        for j in range(1, N):
            X ^= V[index_of_least_significant_zero_bit(j - 1)]
            result[j][i] = float(X / math.pow(2, scale))

    return result
10933
def _nanmean(array, axis=None):
    """"""

    if isinstance(axis, tuple):
        array = _move_tuple_axes_first(array, axis=axis)
        axis = 0
    return bottleneck.nanmean(array, axis=axis)
313515
def extend_array(edges, binsz, lo, hi):
    """"""

    numlo = int(np.ceil((edges[0] - lo) / binsz))
    numhi = int(np.ceil((hi - edges[-1]) / binsz))

    edges = copy.deepcopy(edges)
    if numlo > 0:
        edges_lo = np.linspace(edges[0] - numlo * binsz, edges[0], numlo + 1)
        edges = np.concatenate((edges_lo[:-1], edges))

    if numhi > 0:
        edges_hi = np.linspace(edges[-1], edges[-1] + numhi * binsz, numhi + 1)
        edges = np.concatenate((edges, edges_hi[1:]))

    return edges
1256683
def _num_samples(x):
    """"""
    if hasattr(x, 'fit'):
        # Don't get num_samples from an ensembles length!
        raise TypeError('Expected sequence or array-like, got '
                        'estimator %s' % x)
    if not hasattr(x, '__len__') and not hasattr(x, 'shape'):
        if hasattr(x, '__array__'):
            x = np.asarray(x)
        else:
            raise TypeError("Expected sequence or array-like, got %s" %
                            type(x))
    if hasattr(x, 'shape'):
        if len(x.shape) == 0:
            raise TypeError("Singleton array %r cannot be considered"
                            " a valid collection." % x)
        return x.shape[0]
    else:
        return len(x)
167216
function createSamples(src) {
  var result = [];

  src
    .replace(/…/, '')
    .trim()
    .replace(/,$/, '')
    .split(',')
    .map(function (val) { return val.trim(); })
    .forEach(function (val) {
      if (val.indexOf('~') !== -1) {
        result = result.concat(fillRange(val));
      } else {
        // push test data as String
        result.push(val);
        // push test data as Number if the same
        if (String(+val) === val) { result.push(+val); }
      }
    });

  return result;
}
363547
function interpolateScalars(values, num) {
  var out = new Float32Array(num*(values.length-1) + 1);
  var index = 0;
  var bf = 0.0, af = 0.0;
  var delta = 1/num;
  for (var i = 0; i < values.length-1; ++i) {
    bf = values[i];
    af = values[i + 1];
    for (var j = 0; j < num; ++j) {
      var t = delta * j;
      out[index+0] = bf*(1-t)+af*t;
      index+=1;
    }
  }
  out[index+0] = af;
  return out;
}
1224133
def _applyMultichan(samples, func):
    # type: (np.ndarray, Callable[[np.ndarray], np.ndarray]) -> np.ndarray
    
    if len(samples.shape) == 1 or samples.shape[1] == 1:
        newsamples = func(samples)
    else:
        y = np.array([])
        for i in range(samples.shape[1]):
            y = np.concatenate((y, func(samples[:,i])))
        newsamples = y.reshape(samples.shape[1], -1).T
    return newsamples
237936
def linseg(self, value, samples):
        '''
        
        '''
        if self.params.length > self.pos and samples > 0:
            len = min(samples, self.params.length - self.pos)
            end = value if len == samples else self.latest + (value - self.latest)*len/samples
            self.data[self.pos:self.pos + len] = np.linspace(self.latest, end, num=len, endpoint=False, dtype=np.float)
            self.pos += len
        self.latest = value
        return self