Class: Musikov::MarkovModel
- Inherits:
-
Object
- Object
- Musikov::MarkovModel
- Defined in:
- lib/musikov/markov_model.rb
Overview
This class represents a generic markov chain. It holds a hash of frequencies of subsequent states, for each state.
Instance Attribute Summary collapse
-
#frequencies ⇒ Object
readonly
Returns the value of attribute frequencies.
Instance Method Summary collapse
-
#add_input(value_chain = []) ⇒ Object
Passes the argument array of state values to be included in the model.
-
#generate(initial_value, value_number) ⇒ Object
Generate a random sequence from a markov chain * The initial_value is a state where the random chain must start * The initial_value may be nil * The value_number indicates the number of elements on the result random sequence.
-
#initialize(value_chain = []) ⇒ MarkovModel
constructor
Initialize the hashes used to build the markov chain.
Constructor Details
#initialize(value_chain = []) ⇒ MarkovModel
Initialize the hashes used to build the markov chain. Passes the initial array of values to be included in the model.
-
The “transitions” hash maps a state into another hash mapping the subsequent states to its number of subsequent occurrences
-
The “frequencies” hash maps a state into another hash mapping the subsequent states to a frequency indicating the probability of subsequent occurrences.
18 19 20 21 22 |
# File 'lib/musikov/markov_model.rb', line 18 def initialize(value_chain = []) @transitions = {} @frequencies = {} add_input(value_chain) end |
Instance Attribute Details
#frequencies ⇒ Object (readonly)
Returns the value of attribute frequencies.
8 9 10 |
# File 'lib/musikov/markov_model.rb', line 8 def frequencies @frequencies end |
Instance Method Details
#add_input(value_chain = []) ⇒ Object
Passes the argument array of state values to be included in the model.
41 42 43 44 45 46 47 48 49 50 |
# File 'lib/musikov/markov_model.rb', line 41 def add_input(value_chain = []) prev_value = nil value_chain.each { |value| add_value(prev_value, value) prev_value = value } compute_frequencies end |
#generate(initial_value, value_number) ⇒ Object
Generate a random sequence from a markov chain
-
The initial_value is a state where the random chain must start
-
The initial_value may be nil
-
The value_number indicates the number of elements on the result random sequence
28 29 30 31 32 33 34 35 36 37 38 |
# File 'lib/musikov/markov_model.rb', line 28 def generate(initial_value, value_number) generated_sequence = [] selected_value = initial_value until generated_sequence.count == value_number do selected_value = pick_value(rand(0.1..1.0), selected_value) generated_sequence << selected_value end return generated_sequence end |