RSA analysis will compare the similarity of two matrices
3979
def RSA(m1,m2):
    '''
    '''
    from scipy.stats import pearsonr
    import scipy.linalg
    import numpy

    # This will take the diagonal of each matrix (and the other half is changed to nan) and flatten to vector
    vectorm1 = m1.mask(numpy.triu(numpy.ones(m1.shape)).astype(numpy.bool)).values.flatten()
    vectorm2 = m2.mask(numpy.triu(numpy.ones(m2.shape)).astype(numpy.bool)).values.flatten()
    # Now remove the nans
    m1defined = numpy.argwhere(~numpy.isnan(numpy.array(vectorm1,dtype=float)))
    m2defined = numpy.argwhere(~numpy.isnan(numpy.array(vectorm2,dtype=float)))
    idx = numpy.intersect1d(m1defined,m2defined)
    return pearsonr(vectorm1[idx],vectorm2[idx])[0]
267032
public static boolean sameDimensions(Matrix A, Matrix B)
    {
        return A.rows() == B.rows() && A.cols() == B.cols();
    }
1231963
def compare(self, vertex0, vertex1, subject_graph):
        """"""
        return (
            self.pattern_graph.vertex_fingerprints[vertex0] ==
            subject_graph.vertex_fingerprints[vertex1]
        ).all()
317061
@Override
    public double similarity(String label1, String label2) {
        if (label1 == null || label2 == null) {
            log.debug("LABELS: " + label1 + ": " + (label1 == null ? "null" : "exists") + ";" + label2 + " vec2:"
                            + (label2 == null ? "null" : "exists"));
            return Double.NaN;
        }

        INDArray vec1 = getWordVectorMatrix(label1).dup();
        INDArray vec2 = getWordVectorMatrix(label2).dup();

        if (vec1 == null || vec2 == null) {
            log.debug(label1 + ": " + (vec1 == null ? "null" : "exists") + ";" + label2 + " vec2:"
                            + (vec2 == null ? "null" : "exists"));
            return Double.NaN;
        }

        if (label1.equals(label2))
            return 1.0;

        vec1 = Transforms.unitVec(vec1);
        vec2 = Transforms.unitVec(vec2);

        return Transforms.cosineSim(vec1, vec2);
    }
51832
def _similarity_matrix(self, concepts):
        
        n_cons = len(concepts)
        sim_mat = np.zeros((n_cons, n_cons))
        for i, c1 in enumerate(concepts):
            for j, c2 in enumerate(concepts):
                # Just build the lower triangle
                if i >= j:
                    sim_mat[i,j] = self._semsim(c1, c2) if i != j else 1.
        return sim_mat + sim_mat.T - np.diag(sim_mat.diagonal())
321294
def similarity(self, other):
        """"""
        ratio = SequenceMatcher(a=self.value, b=other.value).ratio()
        similarity = self.Similarity(ratio)
        return similarity
1107273
public IMatrix similar(IMatrix U) {
        IMatrix result = new IMatrix(rows, columns);
        similar(U, result);
        return result;
    }
943969
public static void checkIdenticalShape(DMatrixRBlock A , DMatrixRBlock B ) {
        if( A.blockLength != B.blockLength )
            throw new IllegalArgumentException("Block size is different");
        if( A.numRows != B.numRows )
            throw new IllegalArgumentException("Number of rows is different");
        if( A.numCols != B.numCols )
            throw new IllegalArgumentException("NUmber of columns is different");
    }
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())
826348
def hungarian(A, B):
    

    # should be kabasch here i think
    distances = cdist(A, B, 'euclidean')

    # Perform Hungarian analysis on distance matrix between atoms of 1st
    # structure and trial structure
    indices_a, indices_b = linear_sum_assignment(distances)

    return indices_b
782343
def is_equal(self, another, limit=0.8):
        
        if another is None:
            raise Exception("Parameter another is null")

        if isinstance(another, int):
            distance = self.hamming_distance(another)
        elif isinstance(another, Simhash):
            assert self.hash_bit_number == another.hash_bit_number
            distance = self.hamming_distance(another.hash)
        else:
            raise Exception("Unsupported parameter type %s" % type(another))

        similarity = float(self.hash_bit_number - distance) / self.hash_bit_number
        if similarity > limit:
            return True
        return False
1366009
def secure_compare(a, b)
      return false unless a.bytesize == b.bytesize

      l = a.unpack("C*")

      r, i = 0, -1
      b.each_byte { |v| r |= v ^ l[i+=1] }
      r == 0
    end
1374199
def similarity(self, other):
        """"""
        if self.magnitude == 0 or other.magnitude == 0:
            return 0

        return self.dot(other) / self.magnitude
354578
private boolean lessThanOrEqual(
         byte[] a,
         byte[] b)
    {
         if (a.length <= b.length)
         {
             for (int i = 0; i != a.length; i++)
             {
                 int    l = a[i] & 0xff;
                 int    r = b[i] & 0xff;

                 if (r > l)
                 {
                     return true;
                 }
                 else if (l > r)
                 {
                     return false;
                 }
             }

             return true;
         }
         else
         {
             for (int i = 0; i != b.length; i++)
             {
                 int    l = a[i] & 0xff;
                 int    r = b[i] & 0xff;

                 if (r > l)
                 {
                     return true;
                 }
                 else if (l > r)
                 {
                     return false;
                 }
             }

             return false;
         }
    }
330531
private static int compareLexical(BitVector a, BitVector b) {
		final int aSize = a.size();
		final int bSize = b.size();
		if (aSize == bSize) return compareNumeric(a, b); // more efficient
		final int size = Math.min(aSize, bSize);
		final int aStart = a.finish - size;
		final int bStart = b.finish - size;
		for (int i = size - 1; i >= 0; i--) {
			boolean aBit = a.getBitAdj(aStart + i);
			boolean bBit = b.getBitAdj(bStart + i);
			if (aBit != bBit) return bBit ? -1 : 1;
		}
		return aSize < bSize ? -1 : 1;
	}
946499
def evenCompare(a: str, b: str) -> bool:
    
    ab = a.encode('utf-8')
    bb = b.encode('utf-8')
    ac = crypto_hash_sha256(ab)
    bc = crypto_hash_sha256(bb)
    return ac < bc
1108755
def cosine_similarity_vec(num_tokens, num_removed_vec):
    
    remaining = -np.array(num_removed_vec) + num_tokens
    return remaining / (np.sqrt(num_tokens + 1e-6) * np.sqrt(remaining + 1e-6))