Returns the correlation coefficient between two vectors.
6828
public static double cor(int[] x, int[] y) {
        if (x.length != y.length) {
            throw new IllegalArgumentException("Arrays have different length.");
        }

        if (x.length < 3) {
            throw new IllegalArgumentException("array length has to be at least 3.");
        }

        double Sxy = cov(x, y);
        double Sxx = var(x);
        double Syy = var(y);

        if (Sxx == 0 || Syy == 0) {
            return Double.NaN;
        }

        return Sxy / java.lang.Math.sqrt(Sxx * Syy);
    }
128277
def orthogonal_vector(v):
    """"""
    if v[1] != 0 or v[2] != 0:
        c = (1, 0, 0)
    else:
        c = (0, 1, 0)
    return np.cross(v, c)
1028465
def get_scalar_product(self, other):
        """"""
        return self.x*other.x+self.y*other.y
857653
public static double coefficient(double[] x, double[] y) {
    final int xdim = x.length;
    final int ydim = y.length;
    if(xdim != ydim) {
      throw new IllegalArgumentException("Invalid arguments: arrays differ in length.");
    }
    if(xdim == 0) {
      throw new IllegalArgumentException("Empty vector.");
    }
    // Inlined computation of Pearson correlation, to avoid allocating objects!
    // This is a numerically stabilized version, avoiding sum-of-squares.
    double sumXX = 0., sumYY = 0., sumXY = 0.;
    double sumX = x[0], sumY = y[0];
    int i = 1;
    while(i < xdim) {
      final double xv = x[i], yv = y[i];
      // Delta to previous mean
      final double deltaX = xv * i - sumX;
      final double deltaY = yv * i - sumY;
      // Increment count first
      final double oldi = i; // Convert to double!
      ++i;
      final double f = 1. / (i * oldi);
      // Update
      sumXX += f * deltaX * deltaX;
      sumYY += f * deltaY * deltaY;
      // should equal deltaY * neltaX!
      sumXY += f * deltaX * deltaY;
      // Update sums
      sumX += xv;
      sumY += yv;
    }
    // One or both series were constant:
    if(!(sumXX > 0. && sumYY > 0.)) {
      return (sumXX == sumYY) ? 1. : 0.;
    }
    return sumXY / FastMath.sqrt(sumXX * sumYY);
  }
664805
def ndim(self):
        """"""
        try:
            return self.__ndim
        except AttributeError:
            ndim = len(self.coord_vectors)
            self.__ndim = ndim
            return ndim
78870
def vectors_between_pts(pts=[]):
    '''
    '''
    assert isinstance(pts, list) and len(pts) > 0
    l_pts = len(pts)
    l_pt_prev = None
    for pt in pts:
        assert isinstance(pt, tuple)
        l_pt = len(pt)
        assert l_pt > 1
        for i in pt:
            assert isinstance(i, float)
        if l_pt_prev is not None:
            assert l_pt == l_pt_prev
        l_pt_prev = l_pt

    return [tuple([pts[(i+1) % l_pts][j] - pts[i][j] for j in range(l_pt)]) \
            for i in range(l_pts)]
4242
def column_vectors(self):
        """"""
        a, b, c, d, e, f, _, _, _ = self
        return (a, d), (b, e), (c, f)
1235772
public static double uncenteredCorrelation(double[] x, double[] y) {
    final int xdim = x.length, ydim = y.length;
    if(xdim != ydim) {
      throw new IllegalArgumentException("Invalid arguments: number vectors differ in dimensionality.");
    }
    double sumXX = 0., sumYY = 0., sumXY = 0.;
    for(int i = 0; i < xdim; i++) {
      final double xv = x[i], yv = y[i];
      sumXX += xv * xv;
      sumYY += yv * yv;
      sumXY += xv * yv;
    }
    // One or both series were constant:
    if(!(sumXX > 0. && sumYY > 0.)) {
      return (sumXX == sumYY) ? 1. : 0.;
    }
    return sumXY / FastMath.sqrt(sumXX * sumYY);
  }
976545
def coefficients(self):
        """"""
        out = numpy.array([self.A[key] for key in self.keys])
        out = numpy.rollaxis(out, -1)
        return out
870485
public static double Correlation(double[] p, double[] q) {

        double x = 0;
        double y = 0;

        for (int i = 0; i < p.length; i++) {
            x += -p[i];
            y += -q[i];
        }

        x /= p.length;
        y /= q.length;

        double num = 0;
        double den1 = 0;
        double den2 = 0;
        for (int i = 0; i < p.length; i++) {
            num += (p[i] + x) * (q[i] + y);

            den1 += Math.abs(Math.pow(p[i] + x, 2));
            den2 += Math.abs(Math.pow(q[i] + x, 2));
        }

        return 1 - (num / (Math.sqrt(den1) * Math.sqrt(den2)));

    }
1046080
def _compute_reference_correlations(reference_sources, filters_len):
    """"""

    # reshape references as nsrc X nchan X nsampl
    (nsrc, nsampl, nchan) = reference_sources.shape
    reference_sources = np.moveaxis(reference_sources, (1), (2))

    # zero padding and FFT of references
    reference_sources = _zeropad(reference_sources, filters_len - 1, axis=2)
    n_fft = int(2**np.ceil(np.log2(nsampl + filters_len - 1.)))
    sf = scipy.fftpack.fft(reference_sources, n=n_fft, axis=2)

    # compute intercorrelation between sources
    G = np.zeros((nsrc, nsrc, nchan, nchan, filters_len, filters_len))
    for ((i, c1), (j, c2)) in itertools.combinations_with_replacement(
        itertools.product(
            list(range(nsrc)), list(range(nchan))
        ),
        2
    ):

        ssf = sf[j, c2] * np.conj(sf[i, c1])
        ssf = np.real(scipy.fftpack.ifft(ssf))
        ss = toeplitz(
            np.hstack((ssf[0], ssf[-1:-filters_len:-1])),
            r=ssf[:filters_len]
        )
        G[j, i, c2, c1] = ss
        G[i, j, c1, c2] = ss.T
    return G, sf
399161
def get_vectors(self, indices=None):
        ''''''
        H_ = self._deflated_solver.H
        (n_, n) = H_.shape
        coeffs = self.coeffs if indices is None else self.coeffs[:, indices]
        return numpy.c_[self._deflated_solver.V[:, :n],
                        self._deflated_solver.projection.U].dot(coeffs)
608190
def vector(p1, p2):
    
    return None if len(p1) != len(p2) else np.array([p2[i] - p1[i] for i in xrange(len(p1))])
5393
public static double uncenteredCorrelation(NumberVector x, NumberVector y) {
    final int xdim = x.getDimensionality(), ydim = y.getDimensionality();
    if(xdim != ydim) {
      throw new IllegalArgumentException("Invalid arguments: number vectors differ in dimensionality.");
    }
    double sumXX = 0., sumYY = 0., sumXY = 0.;
    for(int i = 0; i < xdim; i++) {
      final double xv = x.doubleValue(i), yv = y.doubleValue(i);
      sumXX += xv * xv;
      sumYY += yv * yv;
      sumXY += xv * yv;
    }
    // One or both series were constant:
    if(!(sumXX > 0. && sumYY > 0.)) {
      return (sumXX == sumYY) ? 1. : 0.;
    }
    return sumXY / FastMath.sqrt(sumXX * sumYY);
  }
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())
731013
def getCovariance(self,normalize=True,i0=None,i1=None,pos0=None,pos1=None,chrom=None,center=True,unit=True,pos_cum0=None,pos_cum1=None,blocksize=None,X=None,**kw_args):
        """"""
        if X is not None:
            K=X.dot(X.T)
            Nsnp=X.shape[1]
        else:
            if (i0 is None) and (i1 is None) and ((pos0 is not None) & (pos1 is not None) & (chrom is not None)) or ((pos_cum0 is not None) & (pos_cum1 is not None)):
                i0,i1=self.getGenoIndex(pos0=pos0,pos1=pos1,chrom=chrom,pos_cum0=pos_cum0,pos_cum1=pose_cum1)

            [N,M]=self.genoM.shape
            if blocksize is None:
                blocksize=M
            if i0 is None:
                i0=0
            if i1 is None:
                i1=M
            nread = i0
            K=None
            Nsnp=i1-i0
            while nread<i1:
                thisblock=min(blocksize,i1-nread)
                X=self.getGenotypes(i0=nread,i1=(nread+thisblock),center=center,unit=unit,**kw_args)    
                if K is None:
                    K=X.dot(X.T)
                else:
                    K+=X.dot(X.T)
                nread+=thisblock
        if normalize:
            K/=(K.diagonal().mean())
        else:#divide by number of SNPs in K
            K/=Nsnp
        return K
802976
def composite_correlation(df, size=(12, 8)):
    
    fig = plt.figure(1, size)
    ax1 = plt.subplot2grid((2, 2), (0, 0))
    ax2 = plt.subplot2grid((2, 2), (0, 1))
    ax3 = plt.subplot2grid((2, 2), (1, 0))
    ax4 = plt.subplot2grid((2, 2), (1, 1))
    chemistry = ["V1", "V2", "V2.5", float("nan")]
    colors = sns.color_palette("Set2", 8)
    color_map = dict(zip(chemistry, colors))

    age_label = "Chronological age (yr)"
    ax1.scatter(df["hli_calc_age_sample_taken"], df["teloLength"],
                s=10, marker='.',
                color=df["Chemistry"].map(color_map))
    ax1.set_ylim(0, 15)
    ax1.set_ylabel("Telomere length (Kb)")

    ax2.scatter(df["hli_calc_age_sample_taken"], df["ccn.chrX"],
                s=10, marker='.',
                color=df["Chemistry"].map(color_map))
    ax2.set_ylim(1.8, 2.1)
    ax2.set_ylabel("ChrX copy number")

    ax4.scatter(df["hli_calc_age_sample_taken"], df["ccn.chrY"],
                s=10, marker='.',
                color=df["Chemistry"].map(color_map))
    ax4.set_ylim(0.8, 1.1)
    ax4.set_ylabel("ChrY copy number")

    ax3.scatter(df["hli_calc_age_sample_taken"], df["TRA.PPM"],
                s=10, marker='.',
                color=df["Chemistry"].map(color_map))
    ax3.set_ylim(0, 250)
    ax3.set_ylabel("$TCR-\\alpha$ deletions (count per million reads)")

    from matplotlib.lines import Line2D
    legend_elements = [Line2D([0], [0], marker='.', color='w', label=chem,
                          markerfacecolor=color, markersize=16) \
                        for (chem, color) in zip(chemistry, colors)[:3]]
    for ax in (ax1, ax2, ax3, ax4):
        ax.set_xlabel(age_label)
        ax.legend(handles=legend_elements, loc="upper right")

    plt.tight_layout()
    root = fig.add_axes((0, 0, 1, 1))
    labels = ((.02, .98, "A"),
              (.52, .98, "B"),
              (.02, .5, "C"),
              (.52, .5, "D"))
    panel_labels(root, labels)
    root.set_xlim(0, 1)
    root.set_ylim(0, 1)
    root.set_axis_off()