Average the timeseries into a dimension-1 image.
    image: input time series image
    idx:  indices over which to average
504436
def get_average_of_timeseries( image, idx=None ):
    
    imagedim = image.dimension
    if idx is None:
        idx = range( image.shape[ imagedim - 1 ] )
    i0 = utils.slice_image( image, axis=image.dimension-1, idx=idx[0] ) * 0
    wt = 1.0 / len( idx )
    for k in idx:
        i0 = i0 + utils.slice_image( image, axis=image.dimension-1, idx=k ) * wt
    return( i0 )
203352
def _transform_col(self, x, i):
        
        return x.fillna(NAN_INT).map(self.target_encoders[i]).fillna(self.target_mean)
785567
def symmetry_average(image, symmetry):
    
    img_sym = np.zeros_like(image)
    angle = 360./symmetry
    for i in range(symmetry):
        img_sym += rotateImage(image, angle*i)
    img_sym /= symmetry
    return img_sym
1366553
def ind2sub(ind, dimensions):
    
    # check that the index is within range
    if ind >= np.prod(dimensions):
        raise RuntimeError("ind2sub: index exceeds array size")
    cum_dims = list(dimensions)
    cum_dims.reverse()
    m = 1
    mult = []
    for d in cum_dims:
        m = m*d
        mult.append(m)
    mult.pop()
    mult.reverse()
    mult.append(1)
    indices = []
    for d in mult:
        indices.append((ind/d)+1)
        ind = ind - (ind/d)*d
    return indices
910168
def raster(times, indices, max_time=None, max_index=None, 
           x_label="Timestep", y_label="Index", **kwargs):
    """"""
    # set default size to 1
    if 's' not in kwargs:
        kwargs['s'] = 1
    scatter(times, indices, **kwargs)
    
    if max_time is None:
        max_time = max(times)
    if max_index is None:
        max_index = max(indices)
    axis((0, max_time, 0, max_index))
    if x_label is not None: xlabel(x_label)
    if y_label is not None: ylabel(y_label)
267405
def index(m, val):
    
    mm = np.array(m)
    idx_tuple = np.where(mm == val)
    idx = idx_tuple[0].tolist()

    return idx
1170911
def averagingData(array, windowSize=None, averagingType='median'):
    
    assert averagingType in ['median', 'mean']
    if windowSize is None:
        windowSize = int(len(array) / 50) if int(len(array) / 50) > 100 else 100

    if averagingType == 'median':
        averagedData = runningMedian(array, windowSize)
    elif averagingType == 'mean':
        averagedData = runningMean(array, len(array), windowSize)
    return averagedData
790011
def moving_average(data, periods, type='simple'):
    
    data = np.asarray(data)
    if type == 'simple':
        weights = np.ones(periods)
    else:
        weights = np.exp(np.linspace(-1., 0., periods))

    weights /= weights.sum()

    mavg = np.convolve(data, weights, mode='full')[:len(data)]
    mavg[:periods] = mavg[periods]
    return mavg
498580
def time_serie_subsample(data, sampling):
    
    if len(data) <= sampling:
        return data
    t = [t[0] for t in data]
    v = [t[1] for t in data]
    sampling_length = int(round(len(data) / float(sampling)))
    t_subsampled = [t[s * sampling_length:(s + 1) * sampling_length][0] for s in range(0, sampling)]
    v_subsampled = [mean(v[s * sampling_length:(s + 1) * sampling_length]) for s in range(0, sampling)]
    return list(zip(t_subsampled, v_subsampled))
820063
def indices(self, data):
        '''
        '''
        duration = self.data_duration(data)

        for start in range(0, duration - self.duration, self.stride):
            yield start
897327
def _index_into(self, idx, data):
        
        try:
            if is_dataframe(data):
                # Assume column indexing
                return data[idx]
            # Otherwise assume numpy array-like indexing
            return data[:,idx]
        except Exception as e:
            raise IndexError(
                "could not index column '{}' into type {}: {}".format(
                    self.columns, data.__class__.__name__, e
            ))
402826
def ssim(x, y, data_range=None, scaled = False, verbose = False):
    
    if not x.shape == y.shape:
        raise ValueError('Input images must have the same dimensions.')

    K1 = 0.01
    K2 = 0.03
    sigma = 1.5
    win_size = 7


    if scaled:
        x = x.astype(np.float32)
        y = y.astype(np.float32)

        # center it first for numerical stability...
        my = np.mean(y)
        mx = np.mean(x)
        y = y - my
        sxy = np.mean(x * y)  # mean(y)=0
        sy = np.std(y)
        a, b = sxy / (sy ** 2 + 1.e-30), mx
        if verbose:
            print("scaling in ssim: y2 = %.2g*y+%.2g" % (a, b-my))
        y = a * y + b

        # my = np.mean(y)
        # y = y - my
        # sxy = np.mean(x * y)  # - np.mean(x) * np.mean(y)
        # sy = np.std(y)
        # sx = np.std(x)
        # mx = np.mean(x)
        # a, b = sx / sy, mx
        # print("scaling in ssim: y2 = %.2g*y+%.2g" % (a, b-my))
        # y = a * y + b
        #

    if np.any((np.asarray(x.shape) - win_size) < 0):
        raise ValueError("win_size exceeds image extent.")

    if data_range is None:
        dmin, dmax = np.amin(x), np.amax(x)
        data_range = dmax - dmin+1.e-10

    x_g = OCLArray.from_array(x.astype(np.float32, copy=False))
    y_g = OCLArray.from_array(y.astype(np.float32, copy=False))

    ndim = x.ndim
    NP = win_size ** ndim
    cov_norm = 1. * NP / (NP - 1)  # sample covariance

    filter_func = uniform_filter
    filter_args = {'size': win_size}

    ux = filter_func(x_g, **filter_args)
    uy = filter_func(y_g, **filter_args)

    # compute (weighted) variances and covariances
    uxx = filter_func(x_g * x_g, **filter_args)
    uyy = filter_func(y_g * y_g, **filter_args)
    uxy = filter_func(x_g * y_g, **filter_args)
    vx = cov_norm * (uxx - ux * ux)
    vy = cov_norm * (uyy - uy * uy)
    vxy = cov_norm * (uxy - ux * uy)


    R = 1. * data_range
    C1 = (K1 * R) ** 2
    C2 = (K2 * R) ** 2

    # save some gpu space by minimizing intermediate buffers

    # A1 = 2. * ux * uy+C1
    A1 = np.float32(2.) * ux
    A1 *= uy
    A1 += np.float32(C1)



    # A2 =  2. * vxy + C2
    # overwrite vxy to save space
    A2 = vxy
    A2 *= np.float32(2.)
    A2 += np.float32(C2)


    # B1 =  ux ** 2 + uy ** 2 + C1
    # overwrite ux to save space
    B1 = ux
    B1 *= ux
    uy *= uy
    B1 += uy
    B1 += np.float32(C1)

    # B2 =  vx + vy + C2
    # overwrite vx to save space
    B2 = vx
    B2 += vy
    B2 += np.float32(C2)

    D = B1
    D *= B2
    S = A1
    S *= A2
    S /= D


    # import time
    # time.sleep(2)
    # return 1

    # to avoid edge effects will ignore filter radius strip around edges
    pad = (win_size - 1) // 2

    ss = tuple(slice(pad, s - pad) for s in x.shape)
    # compute (weighted) mean of ssim
    mssim = S.get()[ss].mean()

    return mssim
206828
def AvgPooling(
        inputs,
        pool_size,
        strides=None,
        padding='valid',
        data_format='channels_last'):
    
    if strides is None:
        strides = pool_size
    layer = tf.layers.AveragePooling2D(pool_size, strides, padding=padding, data_format=data_format)
    ret = layer.apply(inputs, scope=tf.get_variable_scope())
    return tf.identity(ret, name='output')
1275065
def load_image(self, idx):
        
        im = Image.open('{}/Images/spatial_envelope_256x256_static_8outdoorcategories/{}.jpg'.format(self.siftflow_dir, idx))
        in_ = np.array(im, dtype=np.float32)
        in_ = in_[:,:,::-1]
        in_ -= self.mean
        in_ = in_.transpose((2,0,1))
        return in_
305837
def sub_dimension(self, index, dimension, propagate=True, inplace=False):
        
        filter_ = self._propagate_dim(index, dimension, propagate)
        return self.subindex(filter_, inplace)
304163
def positionToIntensityUncertaintyForPxGroup(image, std, y0, y1, x0, x1):
    '''
    
    '''
    fy, fx = y1 - y0, x1 - x0
    if fy != fx:
        raise Exception('averaged area need to be square ATM')
    image = _coarsenImage(image, fx)
    k = _kSizeFromStd(std)
    y0 = int(round(y0 / fy))
    x0 = int(round(x0 / fx))
    arr = image[y0 - k:y0 + k, x0 - k:x0 + k]
    U = positionToIntensityUncertainty(arr, std / fx, std / fx)
    return U[k:-k, k:-k]
166355
def with_index(self, new_index):
        
        return TimeSeriesRDD(None, None, self._jtsrdd.withIndex(new_index._jdt_index), self.ctx)