summaryrefslogtreecommitdiff
path: root/lib/similarity.rb
blob: 91e18db4a894d4ba9b6c00a3d778753e612d866f (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
52
53
54
55
56
57
58
=begin
* Name: similarity.rb
* Description: Similarity algorithms
* Author: Andreas Maunz <andreas@maunz.de
* Date: 10/2012
=end

module OpenTox
  module Algorithm

    class Similarity

      #TODO weighted tanimoto

      # 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)
        bad_request_error "fingerprints #{a} and #{b} don't have equal size" unless a.size == b.size
        #common = 0.0
        #a.each_with_index do |n,i|
          #common += 1 if n == b[i]
        #end
        #common/a.size
        # TODO check if calculation speed can be improved
        common_p_sum = 0.0
        all_p_sum = 0.0
        (0...a.size).each { |idx|
          common_p_sum += [ a[idx], b[idx] ].min
          all_p_sum += [ a[idx], b[idx] ].max
        }
        common_p_sum/all_p_sum
      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