class Rubykov::MarkovModel

Public Class Methods

new(order, training_data) click to toggle source
# File lib/rubykov/markov_model.rb, line 3
def initialize(order, training_data)
  raise ArgumentError unless order.is_a? Integer
  raise ArgumentError unless training_data.is_a? Array

  @order = order
  @representation = {}
  add_data_to_model(training_data)
end

Public Instance Methods

chain() click to toggle source
# File lib/rubykov/markov_model.rb, line 16
def chain
  chain_enumerator
end
chain_with_seed(seed_state) click to toggle source
# File lib/rubykov/markov_model.rb, line 20
def chain_with_seed(seed_state)
  chain_enumerator(seed_state)
end
states() click to toggle source
# File lib/rubykov/markov_model.rb, line 24
def states
  @representation.keys
end
train(training_data) click to toggle source
# File lib/rubykov/markov_model.rb, line 12
def train(training_data)
  add_data_to_model(training_data)
end
transitions() click to toggle source
# File lib/rubykov/markov_model.rb, line 28
def transitions
  @representation
end

Private Instance Methods

add_data_to_model(training_data) click to toggle source
# File lib/rubykov/markov_model.rb, line 34
def add_data_to_model(training_data)
  training_data.each_cons(@order + 1).each do |datum|
    key = datum.first(@order)
    value = datum.last
    if @representation.include? key
      @representation[key] << value
    else
      @representation[key] = [value]
    end
  end
end
chain_enumerator(seed_state = states.sample) click to toggle source
# File lib/rubykov/markov_model.rb, line 46
def chain_enumerator(seed_state = states.sample)
  Enumerator.new do |output|
    current_state = seed_state
    current_state.each do |word|
      output << word
    end

    loop do
      break if @representation[current_state].nil?
      next_word = @representation[current_state].sample
      output << next_word
      current_state = current_state.last(@order-1) + [next_word]
    end
  end
end