class BinaryMarkov

A class that behaves as if it were two Markov chains, called Chain A and Chain B. Whereas a normal Markov chain would expose the log probability of a transition, this class exposes the difference between the log probabilities of the two Markov chains.

Constants

BINARY_TAG

Magic number used to identify this object in byte streams. (Reads in ASCII as “BMARKOV ”)

BINARY_VERSION

Current serial format version number, used in association with the magic number.

Attributes

log_probability_differences[R]

Public Class Methods

new(stream) click to toggle source
# File lib/myanmar-tools/binary_markov.rb, line 29
def initialize(stream)
  # Check magic number and serial version number
  binary_tag = stream.read(8).unpack('H*')[0]
  if binary_tag != BINARY_TAG
    raise "Unexpected magic number: expected #{BINARY_TAG} but got #{binary_tag}"
  end
  
  binary_version = stream.read(4).unpack('H*')[0].to_i
  if binary_version != BINARY_VERSION
    raise "Unexpected serial version number: expected #{BINARY_VERSION} but got #{binary_version}"
  end

  generate_probability_differences(stream)
end

Private Instance Methods

generate_probability_differences(stream) click to toggle source
# File lib/myanmar-tools/binary_markov.rb, line 46
def generate_probability_differences(stream)
  size = stream.read(2).unpack('n*')[0]
  probability_diffs = Array.new(size){ Array.new(size) }
  i1 = 0
  while i1 < size
    entries = stream.read(2).unpack('n*')[0]
    fallback = entries == 0 ? 0.0 : stream.read(4).unpack('g*')[0]
    next_target = -1
    i2 = 0
    while i2 < size
      if entries > 0 && next_target < i2
        next_target = stream.read(2).unpack('n*')[0]
        entries -= 1
      end
      probability_diffs[i1][i2] = next_target == i2 ? stream.read(4).unpack('g*')[0] : fallback
      i2 += 1
    end
    i1 += 1
  end
  @log_probability_differences = probability_diffs
end