class HTS::Bam

Attributes

file_path[R]
header[R]
htf[R]
mode[R]

Public Class Methods

new(file_path, mode = "r", create_index: nil) click to toggle source
# File lib/hts/bam.rb, line 16
def initialize(file_path, mode = "r", create_index: nil)
  file_path = File.expand_path(file_path)

  raise("No such SAM/BAM file - #{file_path}") unless File.exist?(file_path)

  @file_path = file_path
  @mode      = mode
  @htf       = LibHTS.hts_open(@file_path, mode)
  @header    = Bam::Header.new(LibHTS.sam_hdr_read(htf))
  # FIXME: should be defined here?
  @b         = LibHTS.bam_init1

  # read
  if mode[0] == "r"
    # load index
    @idx = LibHTS.sam_index_load(htf, file_path)
    # create index
    if create_index || (@idx.null? && create_index.nil?)
      warn "Create index for #{file_path}"
      LibHTS.sam_index_build(file_path, -1)
      @idx = LibHTS.sam_index_load(@htf, @file_path)
    end
  else
    # FIXME: implement
    raise "not implemented yet."
  end
end

Public Instance Methods

close() click to toggle source

Close the current file.

# File lib/hts/bam.rb, line 51
def close
  LibHTS.hts_close(htf)
end
each(&block) click to toggle source
# File lib/hts/bam.rb, line 61
def each(&block)
  # Each does not always start at the beginning of the file.
  # This is the common behavior of IO objects in Ruby.
  # This may change in the future.
  while LibHTS.sam_read1(htf, header.h, @b) > 0
    record = Record.new(@b, header.h)
    block.call(record)
  end
end
flush() click to toggle source

Flush the current file.

# File lib/hts/bam.rb, line 56
def flush
  raise
  # LibHTS.bgzf_flush(@htf.fp.bgzf)
end
query(region) { |record| ... } click to toggle source

query [WIP]

# File lib/hts/bam.rb, line 72
def query(region)
  qiter = LibHTS.sam_itr_querys(@idx, header.h, region)
  begin
    slen = LibHTS.sam_itr_next(htf, qiter, @b)
    while slen > 0
      yield Record.new(@b, header.h)
      slen = LibHTS.sam_itr_next(htf, qiter, @b)
    end
  ensure
    LibHTS.hts_itr_destroy(qiter)
  end
end
write(alns) click to toggle source
# File lib/hts/bam.rb, line 44
def write(alns)
  alns.each do
    LibHTS.sam_write1(htf, header, alns.b) > 0 || raise
  end
end