Perform Gower normalizion on covariance matrix K.

    The rescaled covariance matrix has sample variance of 1.
352581
def gower_normalization(K, out=None):
    
    c = (K.shape[0] - 1) / (K.trace() - K.mean(0).sum())
    if out is None:
        return c * K

    copyto(out, K)
    out *= c
1268263
public static double covariance(TransposeDataList transposeDataList, boolean isSample) {
        if(transposeDataList.size()!=2) {
            throw new IllegalArgumentException("The collection must contain observations from 2 groups.");
        }
        
        double covariance = 0.0;
        
        Object[] keys = transposeDataList.keySet().toArray();
        Object keyX = keys[0];
        Object keyY = keys[1];
        
        FlatDataCollection flatDataCollectionX = transposeDataList.get(keyX).toFlatDataCollection();
        FlatDataCollection flatDataCollectionY = transposeDataList.get(keyY).toFlatDataCollection();
        
        int n = flatDataCollectionX.size();
        if(n<=1 || n!=flatDataCollectionY.size()) {
            throw new IllegalArgumentException("The number of observations in each group must be equal and larger than 1.");
        }
        
        double meanX = mean(flatDataCollectionX);
        double meanY = mean(flatDataCollectionY);
        
        Iterator<Double> iteratorX = flatDataCollectionX.iteratorDouble();
        Iterator<Double> iteratorY = flatDataCollectionY.iteratorDouble();
        while (iteratorX.hasNext() && iteratorY.hasNext()) {
            covariance+=(iteratorX.next()-meanX)*
                        (iteratorY.next()-meanY);
        }
        
        if(isSample) {
            covariance/=(n-1.0);
        }
        else {
            covariance/=n;
        }
        
        return covariance;
    }
414968
def fit_similarity(fit1, fit2):
    
    cov1 = aligned_covariance(fit1)
    cov2 = aligned_covariance(fit2)
    if fit2.axes[2,2] < 0:
        cov2 *= -1
    v0 = fit1.normal-fit2.normal
    cov0 = cov1+cov2 # Axes are aligned, so no covariances

    # Find distance of point from center

    # Decompose covariance matrix
    U,s,V = N.linalg.svd(cov0)
    rotated = dot(V,v0) # rotate vector into PCA space
    val = rotated**2/N.sqrt(s)
    return N.sqrt(val.sum())
211747
def group_norm(x, filters=None, num_groups=8, epsilon=1e-5):
  """"""
  x_shape = shape_list(x)
  if filters is None:
    filters = x_shape[-1]
  assert len(x_shape) == 4
  assert filters % num_groups == 0
  # Prepare variables.
  scale = tf.get_variable(
      "group_norm_scale", [filters], initializer=tf.ones_initializer())
  bias = tf.get_variable(
      "group_norm_bias", [filters], initializer=tf.zeros_initializer())
  epsilon, scale, bias = [cast_like(t, x) for t in [epsilon, scale, bias]]
  # Reshape and compute group norm.
  x = tf.reshape(x, x_shape[:-1] + [num_groups, filters // num_groups])
  # Calculate mean and variance on heights, width, channels (not groups).
  mean, variance = tf.nn.moments(x, [1, 2, 4], keep_dims=True)
  norm_x = (x - mean) * tf.rsqrt(variance + epsilon)
  return tf.reshape(norm_x, x_shape) * scale + bias
188936
def fitlin(imgarr,refarr):
    
    # Initialize variables
    _mat = np.zeros((3,3),dtype=np.float64)
    _xorg = imgarr[0][0]
    _yorg = imgarr[0][1]
    _xoorg = refarr[0][0]
    _yoorg = refarr[0][1]
    _sigxox = 0.
    _sigxoy = 0.
    _sigxo = 0.
    _sigyox = 0.
    _sigyoy = 0.
    _sigyo = 0.

    _npos = len(imgarr)
    # Populate matrices
    for i in range(_npos):
        _mat[0][0] += np.power((imgarr[i][0] - _xorg),2)
        _mat[0][1] += (imgarr[i][0] - _xorg) * (imgarr[i][1] - _yorg)
        _mat[0][2] += (imgarr[i][0] - _xorg)
        _mat[1][1] += np.power((imgarr[i][1] - _yorg),2)
        _mat[1][2] += imgarr[i][1] - _yorg

        _sigxox += (refarr[i][0] - _xoorg)*(imgarr[i][0] - _xorg)
        _sigxoy += (refarr[i][0] - _xoorg)*(imgarr[i][1] - _yorg)
        _sigxo += refarr[i][0] - _xoorg
        _sigyox += (refarr[i][1] - _yoorg)*(imgarr[i][0] -_xorg)
        _sigyoy += (refarr[i][1] - _yoorg)*(imgarr[i][1] - _yorg)
        _sigyo += refarr[i][1] - _yoorg

    _mat[2][2] = _npos
    _mat[1][0] = _mat[0][1]
    _mat[2][0] = _mat[0][2]
    _mat[2][1] = _mat[1][2]

    # Now invert this matrix
    _mat = linalg.inv(_mat)

    _a  = _sigxox*_mat[0][0]+_sigxoy*_mat[0][1]+_sigxo*_mat[0][2]
    _b  = -1*(_sigxox*_mat[1][0]+_sigxoy*_mat[1][1]+_sigxo*_mat[1][2])
    #_x0 = _sigxox*_mat[2][0]+_sigxoy*_mat[2][1]+_sigxo*_mat[2][2]

    _c  = _sigyox*_mat[1][0]+_sigyoy*_mat[1][1]+_sigyo*_mat[1][2]
    _d  = _sigyox*_mat[0][0]+_sigyoy*_mat[0][1]+_sigyo*_mat[0][2]
    #_y0 = _sigyox*_mat[2][0]+_sigyoy*_mat[2][1]+_sigyo*_mat[2][2]

    _xt = _xoorg - _a*_xorg+_b*_yorg
    _yt = _yoorg - _d*_xorg-_c*_yorg

    return [_a,_b,_xt],[_c,_d,_yt]
144319
def variance(self, param):
        
        param_number = self.model.params.index(param)
        try:
            return self.covariance_matrix[param_number, param_number]
        except TypeError:
            # covariance_matrix can be None
            return None
1025776
def explained_variance(self):
        
        v = N.diagonal(self.covariance_matrix)
        return v[0:2].sum()/v.sum()
689331
def covariance(left, right, where=None, how='sample'):
    
    expr = ops.Covariance(left, right, how, where).to_expr()
    return expr
734187
private function computeCovariance()
    {
        $factorCallable = $this->coVarianceFactor;
        $this->factor = $factorCallable();

        // Cache covariance and inverse covariance of the data
        if (null === $this->_dataInvCov) {
            // original used the numpy.cov function.
            $this->_dataCovariance = pow(Statistics::stdev($this->dataset, true), 2);

            //$this->_dataInvCov = 1/ linalg.inv($this->_dataCovariance)
            $this->_dataInvCov = 1 / $this->_dataCovariance;
        }

        $this->covariance = $this->_dataCovariance * pow($this->factor, 2);
        $this->invCov = $this->_dataInvCov / pow($this->factor, 2);
        $this->normFactor = sqrt(2 * M_PI * $this->covariance) * count($this->dataset);
    }
976081
def _normalize_eigensystem(u, lv, rv):
    
    # first normalize the stationary distribution separately
    lv[:, 0] = lv[:, 0] / np.sum(lv[:, 0])

    for i in range(1, lv.shape[1]):
        # the remaining left eigenvectors to satisfy
        # <\phi_i, \phi_i>_{\mu^{-1}} = 1
        lv[:, i] = lv[:, i] / np.sqrt(np.dot(lv[:, i], lv[:, i] / lv[:, 0]))

    for i in range(rv.shape[1]):
        # the right eigenvectors to satisfy <\phi_i, \psi_j> = \delta_{ij}
        rv[:, i] = rv[:, i] / np.dot(lv[:, i], rv[:, i])

    return u, lv, rv
272128
def normalise_rows(matrix):
    

    lengths = np.apply_along_axis(np.linalg.norm, 1, matrix)
    if not (lengths > 0).all():
        # raise ValueError('Cannot normalise 0 length vector to length 1')
        # print(matrix)
        lengths[lengths == 0] = 1
    return matrix / lengths[:, np.newaxis]
1137687
def K(self, X, X2, target):
        """"""
        self._K_computations(X, X2)
        target += self.variance*self._K_dvar
116787
def rtruncated_normal(mu, tau, a=-np.inf, b=np.inf, size=None):
    

    sigma = 1. / np.sqrt(tau)
    na = utils.normcdf((a - mu) / sigma)
    nb = utils.normcdf((b - mu) / sigma)

    # Use the inverse CDF generation method.
    U = np.random.mtrand.uniform(size=size)
    q = U * nb + (1 - U) * na
    R = utils.invcdf(q)

    # Unnormalize
    return R * sigma + mu
741590
def Kdiag(self, X):
        """"""
        K_ff = np.ones(X.shape[0])
        for i,x in enumerate(X):
            for il,l in enumerate(self.lengthscale):
                idx = il*2
                K_ff[i] *= self.k_ff(x[idx],x[idx],l)
        return K_ff * self.variances[0]
307831
def Kdiag(self, X):
        """"""
        Kdiag = np.zeros(X.shape[0])
        ly=1/self.lengthscale_Y
        lu=np.sqrt(3)/self.lengthscale_U

        Vu = self.variance_U
        Vy=self.variance_Y

        k1 = (2*lu+ly)/(lu+ly)**2
        k2 = (ly-2*lu + 2*lu-ly ) / (ly-lu)**2
        k3 = 1/(lu+ly) + (lu)/(lu+ly)**2

        slices = index_to_slices(X[:,-1])

        for i, ss1 in enumerate(slices):
            for s1 in ss1:
                if i==0:
                    Kdiag[s1]+= self.variance_U + self.ubias
                elif i==1:
                    Kdiag[s1]+= Vu*Vy*(k1+k2+k3)
                else:
                    raise ValueError("invalid input/output index")
        #Kdiag[slices[0][0]]+= self.variance_U   #matern32 diag
        #Kdiag[slices[1][0]]+= self.variance_U*self.variance_Y*(k1+k2+k3)  #  diag
        return Kdiag
328103
def kscale(matrix, k=7, dists=None):
    
    dists = (kdists(matrix, k=k) if dists is None else dists)
    scale = dists.dot(dists.T)
    return scale
763014
def Kdiag(self, X):
        """"""
        ret = np.empty(X.shape[0])
        ret[:] = self.variance
        return ret