Detect mean shift in a time series. B is number of bootstrapped
            samples to draw.
185972
def detect_mean_shift(self, ts, B=1000):
        
        x = np.arange(0, len(ts))
        stat_ts_func = self.compute_balance_mean_ts
        null_ts_func = self.shuffle_timeseries
        stats_ts, pvals, nums = self.get_ts_stats_significance(x, ts, stat_ts_func, null_ts_func, B=B, permute_fast=True)
        return stats_ts, pvals, nums
41561
def bootstrap_statistics(series, statistic, n_samples=1000,
                         confidence_interval=0.95, random_state=None):
    
    if random_state is None:
        random_state = np.random

    alpha = 1 - confidence_interval
    size = (n_samples, len(series))
    inds = random_state.randint(0, len(series), size=size)
    samples = series.values[inds]
    means = np.sort(statistic(samples, axis=1))
    return pd.DataFrame({'ymin': means[int((alpha/2)*n_samples)],
                         'ymax': means[int((1-alpha/2)*n_samples)],
                         'y': [statistic(series)]})
123200
def smoothed_moving_average(data, period):
    
    catch_errors.check_for_period_error(data, period)
    series = pd.Series(data)
    return series.ewm(alpha = 1.0/period).mean().values.flatten()
377386
def estimate_cp(ts, method="mean", Q=1, penalty_value=0.175):
    

    """ 
        ts: time series
        method: look for a single changepoint in 'mean' , 'var', 'mean and var'
                or use binary segmentatiom to detect multiple changepoints in
                mean (binseg).
        Q: Number of change points to look for (only for binseg)
        penalty_value: Penalty to use as threshold (only for binseg)

        Returns: returns indices of the changepoints
    """
    robjects.r("library(changepoint)")
    method_map = {
        "mean": "cpt.mean({})",
        "var": "cpt.var({})",
        "meanvar": "cpt.meanvar({})",
        "binseg.mean.CUSUM": "cpt.mean({},penalty='Manual', test.stat='CUSUM',method='BinSeg',Q={},pen.value={})"
    }
    mt = robjects.FloatVector(ts)
    robjects.globalenv["mt"] = mt
    if method == "binseg.mean.CUSUM":
        cmd = method_map[method].format("mt", Q, penalty_value)
    else:
        cmd = method_map[method].format("mt")
    robjects.globalenv["mycpt"] = robjects.r(cmd)
    ecp = robjects.r("cpts(mycpt)")
    return ecp
21351
def tick(self, d):
        
        if self.test_blocks:
            if not (self.counter["blocks"] or 0) % self.test_blocks:
                self.test()
            self.counter["blocks"] += 1
769366
function bnpRShiftTo(n, r) {
  r.s = this.s;
  var ds = Math.floor(n / this.DB);
  if (ds >= this.t) {
    r.t = 0;
    return;
  }
  var bs = n % this.DB;
  var cbs = this.DB - bs;
  var bm = (1 << bs) - 1;
  r[0] = this[ds] >> bs;
  for (var i = ds + 1; i < this.t; ++i) {
    r[i - ds - 1] |= (this[i] & bm) << cbs;
    r[i - ds] = this[i] >> bs;
  }
  if (bs > 0) r[this.t - ds - 1] |= (this.s & bm) << cbs;
  r.t = this.t - ds;
  r.clamp();
}
1102124
def util_pattern_space(time_series, lag, dim):
    
    n = len(time_series)

    if lag * dim > n:
        raise Exception('Result matrix exceeded size limit, try to change lag or dim.')
    elif lag < 1:
        raise Exception('Lag should be greater or equal to 1.')

    pattern_space = np.empty((n - lag * (dim - 1), dim))
    for i in range(n - lag * (dim - 1)):
        for j in range(dim):
            pattern_space[i][j] = time_series[i + j * lag]

    return pattern_space
816003
def alert!
      t = time.round( 9 )
      t2 = next_time.round( 9 )
      if t >= t2 then # it's time to sample
        sample!
        @next_time += sampling
      end
    end
204873
function buildSample (sampleNumber, rawData, sendCounts) {
  let sample;
  if (sendCounts) {
    sample = newSampleNoScale(sampleNumber);
    sample.channelDataCounts = rawData;
  } else {
    sample = newSample(sampleNumber);
    for (let j = 0; j < k.OBCINumberOfChannelsGanglion; j++) {
      sample.channelData.push(rawData[j] * k.OBCIGanglionScaleFactorPerCountVolts);
    }
  }
  sample.timestamp = Date.now();
  return sample;
}
226413
def plot_signal(signal, sig_len, n_sig, fs, time_units, sig_style, axes):
    ""

    # Extend signal style if necesary
    if len(sig_style) == 1:
        sig_style = n_sig * sig_style

    # Figure out time indices
    if time_units == 'samples':
        t = np.linspace(0, sig_len-1, sig_len)
    else:
        downsample_factor = {'seconds':fs, 'minutes':fs * 60,
                             'hours':fs * 3600}
        t = np.linspace(0, sig_len-1, sig_len) / downsample_factor[time_units]

    # Plot the signals
    if signal.ndim == 1:
        axes[0].plot(t, signal, sig_style[0], zorder=3)
    else:
        for ch in range(n_sig):
            axes[ch].plot(t, signal[:,ch], sig_style[ch], zorder=3)
493865
def at_time(self, time, nearest_sample=False):
        
        if nearest_sample:
            time += self.delta_t / 2.0
        return self[int((time-self.start_time)*self.sample_rate)]
182540
def senkou_b(data, period=52):
    
    sb = conversion_base_line_helper(data, period)
    shift_by = np.repeat(np.nan, 26)
    sb = np.append(shift_by, sb)
    return sb
1231844
def mean(series):
    

    if np.issubdtype(series.dtype, np.number):
        return series.mean()
    else:
        return np.nan
441877
def util_granulate_time_series(time_series, scale):
    
    n = len(time_series)
    b = int(np.fix(n / scale))
    temp = np.reshape(time_series[0:b*scale], (b, scale))
    cts = np.mean(temp, axis = 1)
    return cts
4897
def samples(self):
        """"""
        names = self.series.dimensions
        for n, offset in enumerate(self.series.offsets):
            dt = datetime.timedelta(microseconds=offset * 1000)
            d = {"ts": self.ts + dt}
            for name in names:
                d[name] = getattr(self.series, name)[n]
            yield d
312432
def sample(self, num_samples=1):
        
        self.check_fit()
        return np.random.normal(self.mean, self.std, num_samples)
185990
def pt_shift(pt=(0.0, 0.0), shift=[0.0, 0.0]):
    '''
    '''
    assert isinstance(pt, tuple)
    l_pt = len(pt)
    assert l_pt > 1
    for i in pt:
        assert isinstance(i, float)
    assert isinstance(shift, list)
    l_sh = len(shift)
    assert l_sh == l_pt
    for i in shift:
        assert isinstance(i, float)

    return tuple([pt[i] + shift[i] for i in range(l_pt)])