+ # Class method to convert a SAM entry
+ # to a Biopiece record.
+ def self.to_bp(sam)
+ bp = {}
+
+ bp[:REC_TYPE] = 'SAM'
+ bp[:Q_ID] = sam[:QNAME]
+ bp[:STRAND] = sam[:FLAG].revcomp? ? '-' : '+'
+ bp[:S_ID] = sam[:RNAME]
+ bp[:S_BEG] = sam[:POS]
+ bp[:S_END] = sam[:POS] + sam[:SEQ].length - 1
+ bp[:MAPQ] = sam[:MAPQ]
+ bp[:CIGAR] = sam[:CIGAR].to_s
+
+ unless sam[:RNEXT] == '*'
+ bp[:Q_ID2] = sam[:RNEXT]
+ bp[:S_BEG2] = sam[:PNEXT]
+ bp[:TLEN] = sam[:TLEN]
+ end
+
+ bp[:SEQ] = sam[:SEQ].seq
+
+ unless sam[:SEQ].qual.nil?
+ bp[:SCORES] = sam[:SEQ].qual_convert!(:base_33, :base_64).qual
+ end
+
+ if sam[:NM] and sam[:NM].to_i > 0
+ bp[:NM] = sam[:NM]
+ bp[:MD] = sam[:MD]
+ bp[:ALIGN] = self.align_descriptors(sam)
+ end
+
+ bp
+ end
+
+ # Class method to create a new SAM entry from a Biopiece record.
+ # FIXME
+ def self.new_bp(bp)
+ qname = bp[:Q_ID]
+ flag = 0
+ rname = bp[:S_ID]
+ pos = bp[:S_BEG]
+ mapq = bp[:MAPQ]
+ cigar = bp[:CIGAR]
+ rnext = bp[:Q_ID2] || '*'
+ pnext = bp[:S_BEG2] || 0
+ tlen = bp[:TLEN] || 0
+ seq = bp[:SEQ]
+ qual = bp[:SCORES] || '*'
+ nm = "NM:i:#{bp[:NM]}" if bp[:NM]
+ md = "MD:Z:#{bp[:MD]}" if bp[:MD]
+
+ flag |= FLAG_REVCOMP if bp[:STRAND] == '+'
+
+ if qname && flag && rname && pos && mapq && cigar && rnext && pnext && tlen && seq && qual
+ ary = [qname, flag, rname, pos, mapq, cigar, rnext, pnext, tlen, seq, qual]
+ ary << nm if nm
+ ary << md if md
+
+ ary.join("\t")
+ end
+ end
+
+ # Create alignment descriptors according to the KISS
+ # format description:
+ # http://code.google.com/p/biopieces/wiki/KissFormat
+ def self.align_descriptors(sam)
+ offset = 0
+ align = []
+
+ # Insertions
+ sam[:CIGAR].each do |len, op|
+ if op == 'I'
+ (0 ... len).each_with_index do |i|
+ nt = sam[:SEQ].seq[offset + i]
+
+ align << [offset + i, "->#{nt}"]
+ end
+ end
+
+ offset += len
+ end
+
+ offset = 0
+ deletions = 0
+
+ sam[:MD].scan(/\d+|\^[A-Z]+|[A-Z]+/).each do |m|
+ if m =~ /\d+/ # Matches
+ offset += m.to_i
+ elsif m[0] == '^' # Deletions
+ m.each_char do |nt|
+ unless nt == '^'
+ align << [offset, "#{nt}>-"]
+ deletions += 1
+ offset += 1
+ end
+ end
+ else # Mismatches
+ m.each_char do |nt|
+ nt2 = sam[:SEQ].seq[offset - deletions]
+
+ align << [offset, "#{nt}>#{nt2}"]
+
+ offset += 1
+ end
+ end
+ end
+
+ align.sort_by { |a| a.first }.map { |k, v| "#{k}:#{v}" }.join(",")
+ end
+