summaryrefslogtreecommitdiff
path: root/lib/similarity.rb
blob: 5f0257764fc47124ffb0a752ee7ffa619fc8013a (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
=begin
* Name: similarity.rb
* Description: Similarity algorithms
* Author: Andreas Maunz <andreas@maunz.de
* Date: 10/2012
=end

module OpenTox
  module Algorithm

    class Similarity

      # Tanimoto similarity
      # @param [Array] a fingerprints of first compound
      # @param [Array] b fingerprints of second compound
      # @return [Float] Tanimoto similarity
      def self.tanimoto(a,b)
        common_p_sum = 0.0
        all_p_sum = 0.0
        size = [ a.size, b.size ].min
        $logger.warn "fingerprints don't have equal size" if a.size != b.size
        (0...size).each { |idx|
          common_p_sum += [ a[idx].to_f, b[idx].to_f ].min
          all_p_sum += [ a[idx].to_f, b[idx].to_f ].max
        }
        (all_p_sum > 0.0) ? (common_p_sum/all_p_sum) : 0.0
      end


      # Cosine similarity
      # @param [Array] a fingerprints of first compound
      # @param [Array] b fingerprints of second compound
      # @return [Float] Cosine similarity, the cosine of angle enclosed between vectors a and b
      def self.cosine(a, b)
        val = 0.0
        if a.size>0 and b.size>0
          if a.size>12 && b.size>12
            a = a[0..11]
            b = b[0..11]
          end
          a_vec = a.to_gv
          b_vec = b.to_gv
          val = a_vec.dot(b_vec) / (a_vec.norm * b_vec.norm)
        end
        val
      end

    end

  end
end