Computes the average Q given the weights at this cached point
545972
void computeAverageQ(Cache cache) {
		float[] weights = cache.weights.data;
		cache.aveQ.set(0,0);

		for (int i = 0; i < controls.size(); i++) {
			Control c = controls.get(i);
			float w = weights[i];
			cache.aveQ.x += c.q.x * w;
			cache.aveQ.y += c.q.y * w;
		}
		cache.aveQ.x /= cache.totalWeight;
		cache.aveQ.y /= cache.totalWeight;
	}
644685
def moving_average(iterable, n):
    
    it = iter(iterable)
    d = collections.deque(itertools.islice(it, n - 1))
    d.appendleft(0)
    s = sum(d)
    for elem in it:
        s += elem - d.popleft()
        d.append(elem)
        yield s / float(n)
507642
protected void computeGradient(AffinityMatrix pij, double[][] qij, double qij_isum, double[][] sol, double[] meta) {
    final int dim3 = dim * 3;
    int size = pij.size();
    for(int i = 0, off = 0; i < size; i++, off += dim3) {
      final double[] sol_i = sol[i], qij_i = qij[i];
      Arrays.fill(meta, off, off + dim, 0.); // Clear gradient only
      for(int j = 0; j < size; j++) {
        if(i == j) {
          continue;
        }
        final double[] sol_j = sol[j];
        final double qij_ij = qij_i[j];
        // Qij after scaling!
        final double q = MathUtil.max(qij_ij * qij_isum, MIN_QIJ);
        double a = 4 * (pij.get(i, j) - q); // SNE gradient
        for(int k = 0; k < dim; k++) {
          meta[off + k] += a * (sol_i[k] - sol_j[k]);
        }
      }
    }
  }
221018
def weighted_average(rule, artifact):
    
    e = 0
    w = 0
    for i in range(len(rule.R)):
        r = rule.R[i](artifact)
        if r is not None:
            e += r * rule.W[i]
            w += abs(rule.W[i])
    if w == 0.0:
        return 0.0
    return e / w
516363
static float invsqlook(float a) {
        double d = a * (2.f * (float) INVSQ_LOOKUP_SZ) - (float) INVSQ_LOOKUP_SZ;
        int i = (int) d;
        return INVSQ_LOOKUP[i] + ((float) (d - i)) * (INVSQ_LOOKUP[i + 1] - INVSQ_LOOKUP[i]);
    }
1248223
def Q_srk(self, k):
        
        ind = self.index[self.Q_time_var_index, k]
        Q = self.Q[:, :, ind]

        if (Q.shape[0] == 1):  # 1-D case handle simplier. No storage
            # of the result, just compute it each time.
            square_root = np.sqrt(Q)
        else:
            if self.svd_each_time:

                (U, S, Vh) = sp.linalg.svd(Q, full_matrices=False,
                                           compute_uv=True,
                                           overwrite_a=False,
                                           check_finite=True)

                square_root = U * np.sqrt(S)
            else:

                if ind in self.Q_square_root:
                    square_root = self.Q_square_root[ind]
                else:
                    (U, S, Vh) = sp.linalg.svd(Q, full_matrices=False,
                                               compute_uv=True,
                                               overwrite_a=False,
                                               check_finite=True)

                    square_root = U * np.sqrt(S)

                    self.Q_square_root[ind] = square_root

        return square_root
1373946
def _compute(self):
        """"""
        x_len = self._len
        y_len = self._order
        self._box.xmax = x_len
        self._box.ymax = y_len

        self._x_pos = [n / 2 for n in range(1, 2 * x_len, 2)]
        self._y_pos = [n / 2 for n in reversed(range(1, 2 * y_len, 2))]

        for j, serie in enumerate(self.series):
            serie.points = [(self._x_pos[i], self._y_pos[j])
                            for i in range(x_len)]
1312133
def weight(self):
        
        if self.root.stale:
            self.root.update(self.root.now, None)
        return self._weight
937269
def _avg(value1, value2, weight):
        
        if value1 is None:
            return value2
        if value2 is None:
            return value1
        return value2 * weight + value1 * (1 - weight)
708957
def moving_average(average_specifier)
      if average_specifier.kind_of?(Array)
        avg = MovingAverage.weighted(average_specifier)
      elsif average_specifier.kind_of?(Integer)
        avg = MovingAverage.simple(average_specifier)
      else
        raise ArgumentError.new("Unknown weights")
      end
      
      avg.calculate(self)
    end
266866
void computeAverageP(Cache cache) {
		float[] weights = cache.weights.data;
		cache.aveP.set(0,0);

		for (int i = 0; i < controls.size(); i++) {
			Control c = controls.get(i);
			float w = weights[i];
			cache.aveP.x += c.p.x * w;
			cache.aveP.y += c.p.y * w;
		}
		cache.aveP.x /= cache.totalWeight;
		cache.aveP.y /= cache.totalWeight;
	}
582471
def mp2q(p, q):
    
    p, q = flatten(p), flatten(q)
    entropy_dist = 1 / len(p)
    return sum(entropy_dist * np.nan_to_num((p ** 2) / q * np.log(p / q)))
359565
def _calc_q_h0(n, x, h, nt, n_jobs=1, verbose=0, random_state=None):
    
    rng = check_random_state(random_state)
    par, func = parallel_loop(_calc_q_statistic, n_jobs, verbose)
    q = par(func(rng.permutation(x.T).T, h, nt) for _ in range(n))
    
    return np.array(q)
947404
private void computeMean() {
		meanError = 0;

		int size = allPoints.size();
		for (PointIndex<Point> inlier : allPoints) {
			Point pt = inlier.data;

			meanError += modelError.computeDistance(pt);
		}

		meanError /= size;

	}
460069
def compute_q(self, query_antecedent):
    
    ret = mtf.einsum(
        [query_antecedent, self.wq], reduced_dims=[self.query_input_dim])
    if self.combine_dims:
      ret = mtf.replace_dimensions(ret, ret.shape.dims[-1], self.q_dims)
    return ret
99667
def get_means_and_scales_from_q(self):
        
        means = np.zeros(len(self.q))
        scale = np.zeros(len(self.q))
        for i in range(len(self.q)):
            means[i] = self.q[i].mu0
            scale[i] = self.q[i].sigma0 
        return means, scale
908004
def compute_pac(self):
        """"""
        n_segments = sum([len(x['data'].axis['chan'][0]) for x in self.data])
        progress = QProgressDialog('Computing PAC', 'Abort',
                                   0, n_segments - 1, self)
        progress.setWindowModality(Qt.ApplicationModal)

        pac = self.pac
        idpac = (pac['metric'].currentIndex() + 1,
                 pac['surro_method'].currentIndex(),
                 pac['surro_norm'].currentIndex())
        fpha = freq_from_str(self.pac['fpha'].get_value())
        famp = freq_from_str(self.pac['famp'].get_value())
        nbins = self.pac['nbin'][1].get_value()
        nblocks = self.pac['surro']['nblocks'][1].get_value()

        if pac['hilbert_on'].isChecked():
            dcomplex = 'hilbert'
            filt = self.pac['hilbert']['filt'][1].get_value()
            cycle = (self.pac['hilbert']['cycle_pha'][1].get_value(),
                     self.pac['hilbert']['cycle_amp'][1].get_value())
            filtorder = self.pac['hilbert']['order'][1].get_value()
            width = 7 # not used
        elif pac['wavelet_on'].isChecked():
            dcomplex = 'wavelet'
            filt = 'fir1' # not used
            cycle = (3, 6) # not used
            filtorder = 3 # not used
            width = self.pac['wav_width'][1].get_value()

        lg.info(' '.join([str(x) for x in ['Instantiating PAC:', 'idpac:',
                          idpac, 'fpha:', fpha, 'famp:', famp,  'dcomplex:',
                          dcomplex, 'filt:', filt, 'cycle:', cycle,
                          'filtorder:', filtorder, 'width:', width,
                          'nbins:', nbins, 'nblocks:', nblocks]]))
        p = Pac(idpac=idpac, fpha=fpha, famp=famp, dcomplex=dcomplex,
                filt=filt, cycle=cycle, filtorder=filtorder, width=width,
                nbins=nbins, nblocks=nblocks)

        nperm = self.pac['surro']['nperm'][1].get_value()
        optimize = self.pac['optimize'].get_value()
        get_pval = self.pac['surro']['pval'][0].get_value()
        get_surro = self.pac['surro']['save_surro'][0].get_value()
        njobs = self.pac['njobs'].get_value()

        if optimize == 'True':
            optimize = True
        elif optimize == 'False':
            optimize = False

        xpac = {}

        all_chan = sorted(set(
                [x for y in self.data for x in y['data'].axis['chan'][0]]))

        counter = 0
        for chan in all_chan:
            batch = []
            batch_dat = []

            for i, j in enumerate(self.data):

                if self.pac['prep'].get_value():
                    data = j['trans_data']
                else:
                    data = j['data']

                if chan in data.axis['chan'][0]:
                    batch.append(j)

                    if idpac[1] == 1:
                        batch_dat.append(data(chan=chan)[0])

            xpac[chan] = {}
            xpac[chan]['data'] = zeros((len(batch), len(famp), len(fpha)))
            xpac[chan]['times'] = []
            xpac[chan]['duration'] = []
            xpac[chan]['stage'] = []
            xpac[chan]['cycle'] = []
            xpac[chan]['name'] = []
            xpac[chan]['n_stitch'] = []

            if get_pval:
                xpac[chan]['pval'] = zeros((len(batch), len(famp), len(fpha)))

            if idpac[2] > 0:
                xpac[chan]['surro'] = zeros((len(batch), nperm,
                                            len(famp), len(fpha)))

            for i, j in enumerate(batch):
                progress.setValue(counter)
                counter += 1

                if self.pac['prep'].get_value():
                    data = j['trans_data']
                else:
                    data = j['data']

                sf = data.s_freq

                if idpac[1] == 1:
                    new_batch_dat = list(batch_dat)
                    new_batch_dat.insert(0, new_batch_dat.pop(i))
                    dat = asarray(new_batch_dat)
                else:
                    dat = data(chan=chan)[0]

                timeline = data.axis['time'][0]
                xpac[chan]['times'].append((timeline[0], timeline[-1]))
                duration = len(timeline) / sf
                xpac[chan]['duration'].append(duration)
                xpac[chan]['stage'].append(j['stage'])
                xpac[chan]['cycle'].append(j['cycle'])
                xpac[chan]['name'].append(j['name'])
                xpac[chan]['n_stitch'].append(j['n_stitch'])

                out = p.filterfit(sf=sf, xpha=dat, xamp=None, axis=1, traxis=0,
                                  nperm=nperm, optimize=optimize,
                                  get_pval=get_pval, get_surro=get_surro,
                                  njobs=njobs)

                if get_pval:

                    if get_surro:
                        (xpac[chan]['data'][i, :, :],
                         xpac[chan]['pval'][i, :, :],
                         xpac[chan]['surro'][i, :, :, :]) = (out[0][:, :, 0],
                             out[1][:, :, 0], out[2][:, :, :, 0])
                    else:
                        (xpac[chan]['data'][i, :, :],
                         xpac[chan]['pval'][i, :, :]) = (out[0][:, :, 0],
                             out[1][:, :, 0])

                elif get_surro:
                    (xpac[chan]['data'][i, :, :],
                     xpac[chan]['surro'][i, :, :, :]) = (out[0][:, :, 0],
                         out[1][:, :, :, 0])

                else:
                    xpac[chan]['data'][i, :, :] = out[:, :, 0]

                if progress.wasCanceled():
                    msg = 'Analysis canceled by user.'
                    self.parent.statusBar().showMessage(msg)
                    return

        #progress.setValue(counter)

        return xpac, fpha, famp