Class: Bio::MAF::FASTARangeReader

Inherits:
Object
  • Object
show all
Defined in:
lib/bio/maf/tiler.rb

Constant Summary collapse

GT =
'>'.getbyte(0)

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(fspec) ⇒ FASTARangeReader

Returns a new instance of FASTARangeReader.



217
218
219
220
221
222
223
224
225
226
227
228
229
# File 'lib/bio/maf/tiler.rb', line 217

def initialize(fspec)
  if fspec.respond_to? :seek
    @f = fspec
  else
    reader_class = if fspec =~ /.gz$/
                     Zlib::GzipReader
                   else
                     File
                   end
    @f = reader_class.open(fspec)
  end
  position_at_start
end

Instance Attribute Details

#fObject (readonly)

Returns the value of attribute f.



215
216
217
# File 'lib/bio/maf/tiler.rb', line 215

def f
  @f
end

#posObject (readonly)

Returns the value of attribute pos.



215
216
217
# File 'lib/bio/maf/tiler.rb', line 215

def pos
  @pos
end

Instance Method Details

#position_at_startObject



233
234
235
236
237
# File 'lib/bio/maf/tiler.rb', line 233

def position_at_start
  first = f.readline
  raise "expected FASTA comment" unless first =~ /^>/
  @pos = 0
end

#read_interval(z_start, z_end) ⇒ Object



239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
# File 'lib/bio/maf/tiler.rb', line 239

def read_interval(z_start, z_end)
  if z_start < pos
    position_at_start
  end
  data = ''
  region_size = z_end - z_start
  in_region = false
  f.each_line do |line_raw|
    if line_raw.getbyte(0) == GT
      raise "unexpected description line: #{line_raw.inspect}"
    end
    line = line_raw.strip
    end_pos = pos + line.size
    if (! in_region) && pos <= z_start && z_start < end_pos
      offset = z_start - pos
      end_offset = [(offset + region_size), line.size].min
      data << line.slice(offset...end_offset)
      in_region = true
    elsif in_region
      need = region_size - data.size
      raise "should not happen: region #{region_size}, data #{data.size}, need #{need}" if need < 0
      if need > line.size
        data << line
      else
        # last line
        data << line.slice(0, need)
        break
      end
    end
    @pos = end_pos
  end
  return data
end