]> git.donarmstrong.com Git - biopieces.git/blob - code_ruby/lib/maasha/bits.rb
temporary fix of bzip2 read problem
[biopieces.git] / code_ruby / lib / maasha / bits.rb
1 # Copyright (C) 2007-2011 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 'narray'
26
27 # Error class for all exceptions to do with String.
28 class StringError < StandardError; end
29
30 # Monkey patching Class String to add bitwise operators.
31 class String
32   # Method to that returns the case senstive Hamming Distance between two strings.
33   # http://en.wikipedia.org/wiki/Hamming_distance
34   def hamming_distance(str)
35     (self ^ str).tr("\x00",'').length
36   end
37
38   # Method that performs bitwise AND operation where bits
39   # are copied if they exists in BOTH operands.
40   def &(str)
41     narray1, narray2 = to_narray(self, str)
42
43     (narray1 & narray2).to_s
44   end
45
46   # Method that performs bitwise OR operation where bits
47   # are copied if they exists in EITHER operands.
48   def |(str)
49     narray1, narray2 = to_narray(self, str)
50
51     (narray1 | narray2).to_s
52   end
53
54   # Method that performs bitwise XOR operation where bits
55   # are copied if they exists in ONE BUT NOT BOTH operands.
56   def ^(str)
57     narray1, narray2 = to_narray(self, str)
58
59     (narray1 ^ narray2).to_s
60   end
61
62   private
63
64   def to_narray(str1, str2)
65     if str1.length != str2.length
66       raise StringError, "Uneven string lengths: #{str1.length} != #{str2.length}"
67     end
68
69     narray1 = NArray.to_na(str1, "byte")
70     narray2 = NArray.to_na(str2, "byte")
71
72     [narray1, narray2]
73   end
74 end