]> git.donarmstrong.com Git - biopieces.git/blob - code_ruby/lib/maasha/seq/hamming.rb
implemented hamming_dist in inline C
[biopieces.git] / code_ruby / lib / maasha / seq / hamming.rb
1 # Copyright (C) 2013 Martin A. Hansen.
2
3 # This program is free software; you can redistribute it and/or
4 # modify it under the terms of the GNU General Public License
5 # as published by the Free Software Foundation; either version 2
6 # of the License, or (at your option) any later version.
7
8 # This program is distributed in the hope that it will be useful,
9 # but WITHOUT ANY WARRANTY; without even the implied warranty of
10 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
11 # GNU General Public License for more details.
12
13 # You should have received a copy of the GNU General Public License
14 # along with this program; if not, write to the Free Software
15 # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
16
17 # http://www.gnu.org/copyleft/gpl.html
18
19 # >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>><<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
20
21 # This software is part of the Biopieces framework (www.biopieces.org).
22
23 # >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>><<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
24
25 require 'inline'
26 require 'maasha/seq/ambiguity'
27
28 # Class to calculate the Hamming distance between two
29 # given strings.
30 # http://en.wikipedia.org/wiki/Hamming_distance
31 class Hamming
32   extend Ambiguity
33
34   # Class method for calculating the Hamming distance between
35   # two given strings allowing for IUPAC ambiguity codes.
36   def self.distance(str1, str2)
37     raise "string length mismatch: #{str1.length} != #{str2.length}" if str1.length != str2.length
38
39     hd = self.new
40     hd.hamming_distance_C(str1, str2, str1.length)
41   end
42
43   # >>>>>>>>>>>>>>> RubyInline C code <<<<<<<<<<<<<<<
44
45   inline do |builder|
46     add_ambiguity_macro(builder)
47
48     # C method for calculating Hamming Distance.
49     builder.c %{
50       VALUE hamming_distance_C(
51         VALUE _str1,   // String 1
52         VALUE _str2,   // String 2
53         VALUE _len     // String length
54       )
55       {
56         char         *str1 = StringValuePtr(_str1);
57         char         *str2 = StringValuePtr(_str2);
58         unsigned int  len  = FIX2UINT(_len);
59
60         unsigned int hamming_dist = 0;
61         unsigned int i            = 0;
62
63         for (i = 0; i < len; i++)
64         {
65           if (! MATCH(str1[i], str2[i]))
66           {
67             hamming_dist++;
68           }
69         }
70
71         return UINT2NUM(hamming_dist);
72       }
73     }
74   end
75 end
76
77 # >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>><<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
78
79
80 __END__