Permute the dimensions of a Timeseries.
549051
def transpose(self, *axes):
        """"""
        if self.ndim <= 1:
            return self
        ar = np.asarray(self).transpose(*axes)
        if axes[0] != 0:
            # then axis 0 is unaffected by the transposition
            newlabels = [self.labels[ax] for ax in axes]
            return Timeseries(ar, self.tspan, newlabels)
        else:
            return ar
601592
final void doPopulateTimeDimensions() {
        final List<TimeDimension> timeDimensions = this.timeDimensionDao.getTimeDimensions();
        if (timeDimensions.isEmpty()) {
            logger.info("No TimeDimensions exist, creating them");
        } else if (timeDimensions.size() != (24 * 60)) {
            this.logger.info(
                    "There are only "
                            + timeDimensions.size()
                            + " time dimensions in the database, there should be "
                            + (24 * 60)
                            + " creating missing dimensions");
        } else {
            this.logger.debug("Found expected " + timeDimensions.size() + " time dimensions");
            return;
        }

        LocalTime nextTime = new LocalTime(0, 0);
        final LocalTime lastTime = new LocalTime(23, 59);

        for (final TimeDimension timeDimension : timeDimensions) {
            LocalTime dimensionTime = timeDimension.getTime();
            if (nextTime.isBefore(dimensionTime)) {
                do {
                    checkShutdown();
                    this.timeDimensionDao.createTimeDimension(nextTime);
                    nextTime = nextTime.plusMinutes(1);
                } while (nextTime.isBefore(dimensionTime));
            } else if (nextTime.isAfter(dimensionTime)) {
                do {
                    checkShutdown();
                    this.timeDimensionDao.createTimeDimension(dimensionTime);
                    dimensionTime = dimensionTime.plusMinutes(1);
                } while (nextTime.isAfter(dimensionTime));
            }

            nextTime = dimensionTime.plusMinutes(1);
        }

        // Add any missing times from the tail
        while (nextTime.isBefore(lastTime) || nextTime.equals(lastTime)) {
            checkShutdown();
            this.timeDimensionDao.createTimeDimension(nextTime);
            if (nextTime.equals(lastTime)) {
                break;
            }
            nextTime = nextTime.plusMinutes(1);
        }
    }
1107331
def _adjust_shape(dat, k_vars):
    
    dat = np.asarray(dat)
    if dat.ndim > 2:
        dat = np.squeeze(dat)
    if dat.ndim == 1 and k_vars > 1:  # one obs many vars
        nobs = 1
    elif dat.ndim == 1 and k_vars == 1:  # one obs one var
        nobs = len(dat)
    else:
        if np.shape(dat)[0] == k_vars and np.shape(dat)[1] != k_vars:
            dat = dat.T

        nobs = np.shape(dat)[0]  # ndim >1 so many obs many vars

    dat = np.reshape(dat, (nobs, k_vars))
    return dat
998647
def hilbert(ts):
    """"""
    output = signal.hilbert(signal.detrend(ts, axis=0), axis=0)
    return Timeseries(output, ts.tspan, labels=ts.labels)
402495
def get_timeseries(self, *args, **kwargs):
        
        import predix.data.timeseries
        ts = predix.data.timeseries.TimeSeries(*args, **kwargs)
        return ts
529613
def _expand_dims(x, input_shape, output_shape):
  
  verify_no_new_dims([output_shape], input_shape)
  if input_shape == output_shape or input_shape.ndims == 0:
    return x
  perm = [input_shape.dims.index(d) for d in output_shape.dims
          if d in input_shape.dims]
  x = tf.transpose(x, perm)
  for i, d in enumerate(output_shape.dims):
    if d not in input_shape.dims:
      x = tf.expand_dims(x, i)
  return x
294391
def roll(vari, shift, axis=None):
    """"""
    if isinstance(vari, Poly):
        core = vari.A.copy()
        for key in vari.keys:
            core[key] = roll(core[key], shift, axis)
        return Poly(core, vari.dim, None, vari.dtype)

    return numpy.roll(vari, shift, axis)
62546
def shift(self, periods, axis=0, fill_value=None):
        

        # convert integer to float if necessary. need to do a lot more than
        # that, handle boolean etc also
        new_values, fill_value = maybe_upcast(self.values, fill_value)

        # make sure array sent to np.roll is c_contiguous
        f_ordered = new_values.flags.f_contiguous
        if f_ordered:
            new_values = new_values.T
            axis = new_values.ndim - axis - 1

        if np.prod(new_values.shape):
            new_values = np.roll(new_values, ensure_platform_int(periods),
                                 axis=axis)

        axis_indexer = [slice(None)] * self.ndim
        if periods > 0:
            axis_indexer[axis] = slice(None, periods)
        else:
            axis_indexer[axis] = slice(periods, None)
        new_values[tuple(axis_indexer)] = fill_value

        # restore original order
        if f_ordered:
            new_values = new_values.T

        return [self.make_block(new_values)]
911045
def permute(self, ordering: np.ndarray, *, axis: int) -> None:
		
		if axis not in (0, 1):
			raise ValueError("Axis must be 0 (rows) or 1 (columns)")
		for layer in self.layers.values():
			layer._permute(ordering, axis=axis)
		if axis == 0:
			if self.row_graphs is not None:
				for g in self.row_graphs.values():
					g._permute(ordering)
			for a in self.row_attrs.values():
				a._permute(ordering)
		elif axis == 1:
			if self.col_graphs is not None:
				for g in self.col_graphs.values():
					g._permute(ordering)
			for a in self.col_attrs.values():
				a._permute(ordering)
875029
def convert_timespan(timespan):
    """"""
    start, end = timespan.split('-->')
    start = convert_timestamp(start)
    end = convert_timestamp(end)
    return start, end
730629
def _ts_slice(self, Xt, y):
        '''  '''
        Ns = len(Xt)
        Xt_new = []
        for i in range(self.n_splits):
            for j in range(Ns):
                Njs = int(len(Xt[j]) / self.n_splits)
                Xt_new.append(Xt[j][(Njs * i):(Njs * (i + 1))])
        Xt_new = np.array(Xt_new)

        if len(np.atleast_1d(y[0])) == len(Xt[0]):
            # y is a time series
            y_new = []
            for i in range(self.n_splits):
                for j in range(Ns):
                    Njs = int(len(y[j]) / self.n_splits)
                    y_new.append(y[j][(Njs * i):(Njs * (i + 1))])
            y_new = np.array(y_new)
        else:
            # y is contextual to each series
            y_new = np.concatenate([y for i in range(self.n_splits)])

        return Xt_new, y_new
772479
def split_timesteps(data, consistent_abmn=False):
    """"""
    if has_multiple_timesteps(data):
        grouped = data.groupby("timestep")
        return [group[1] for group in grouped]
    else:
        return data
685534
private void randomPermute(int[] permute) {
        for (int i = 0; i < indexVectorSize; i++)
            permute[i] = i;
        for (int i = indexVectorSize - 1; i > 0; i--) {
            int w = (int) Math.floor(Math.random() * (i+1));
            int temp = permute[w];
            permute[w] = permute[i];
            permute[i] = permute[w];
        }
    }
701938
def rolling_window_sequences(X, index, window_size, target_size, target_column):
    """"""
    out_X = list()
    out_y = list()
    X_index = list()
    y_index = list()

    target = X[:, target_column]

    for start in range(len(X) - window_size - target_size + 1):
        end = start + window_size
        out_X.append(X[start:end])
        out_y.append(target[end:end + target_size])
        X_index.append(index[start])
        y_index.append(index[end])

    return np.asarray(out_X), np.asarray(out_y), np.asarray(X_index), np.asarray(y_index)
1176360
def genslices_ndim(ndim, shape):
    """"""
    iterables = [genslices(shape[n]) for n in range(ndim)]
    yield from product(*iterables)
800199
def zero_pad(ts, n_zeros):
    
    
    zeros_shape = ts.shape[:-1] + (n_zeros,)
    zzs = np.zeros(zeros_shape)
    # Concatenate along the time-dimension:
    new_data = np.concatenate((zzs, ts.data, zzs), axis=-1)

    return nts.TimeSeries(new_data, sampling_rate=ts.sampling_rate)
146190
def reindex_timeseries(ts_string, new_timestamps):
    
    #If a single timestamp is passed in, turn it into a list
    #Reindexing can't work if it's not a list
    if not isinstance(new_timestamps, list):
        new_timestamps = [new_timestamps]

    #Convert the incoming timestamps to datetimes
    #if they are not datetimes.
    new_timestamps_converted = []
    for t in new_timestamps:
        new_timestamps_converted.append(get_datetime(t))

    new_timestamps = new_timestamps_converted

    seasonal_year = config.get('DEFAULT','seasonal_year', '1678')
    seasonal_key = config.get('DEFAULT', 'seasonal_key', '9999')

    ts = ts_string.replace(seasonal_key, seasonal_year)

    timeseries = pd.read_json(ts)

    idx = timeseries.index

    ts_timestamps = new_timestamps

    #'Fix' the incoming timestamp in case it's a seasonal value
    if type(idx) == pd.DatetimeIndex:
        if set(idx.year) == set([int(seasonal_year)]):
            if isinstance(new_timestamps,  list):
                seasonal_timestamp = []
                for t in ts_timestamps:
                    t_1900 = t.replace(year=int(seasonal_year))
                    seasonal_timestamp.append(t_1900)
                ts_timestamps = seasonal_timestamp

    #Reindex the timeseries to reflect the requested timestamps
    reindexed_ts = timeseries.reindex(ts_timestamps, method='ffill')

    i = reindexed_ts.index

    reindexed_ts.index = pd.Index(new_timestamps, names=i.names)

    #If there are no values at all, just return None
    if len(reindexed_ts.dropna()) == 0:
        return None

    #Replace all numpy NAN values with None
    pandas_ts = reindexed_ts.where(reindexed_ts.notnull(), None)

    return pandas_ts