Class: Markov::TransitionMatrix
- Inherits:
-
Object
- Object
- Markov::TransitionMatrix
- Defined in:
- lib/markov/transition_matrix.rb
Instance Attribute Summary collapse
-
#depth ⇒ Object
readonly
Returns the value of attribute depth.
-
#transitions ⇒ Object
readonly
Returns the value of attribute transitions.
Instance Method Summary collapse
- #add_transition(states) ⇒ Object
-
#initialize(transitions = {}, depth:) ⇒ TransitionMatrix
constructor
A new instance of TransitionMatrix.
- #transitions_from(states) ⇒ Object
Constructor Details
#initialize(transitions = {}, depth:) ⇒ TransitionMatrix
Returns a new instance of TransitionMatrix.
5 6 7 8 |
# File 'lib/markov/transition_matrix.rb', line 5 def initialize(transitions={}, depth:) @depth = depth @transitions = transitions end |
Instance Attribute Details
#depth ⇒ Object (readonly)
Returns the value of attribute depth.
3 4 5 |
# File 'lib/markov/transition_matrix.rb', line 3 def depth @depth end |
#transitions ⇒ Object (readonly)
Returns the value of attribute transitions.
3 4 5 |
# File 'lib/markov/transition_matrix.rb', line 3 def transitions @transitions end |
Instance Method Details
#add_transition(states) ⇒ Object
10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 |
# File 'lib/markov/transition_matrix.rb', line 10 def add_transition(states) # p [ :add_transition, states: states, depth: depth ] if states.is_a?(Array) && states.count > @depth states = states[-(@depth)..-1] end unless states.count == depth raise "This transition matrix is depth #@depth, not #{states.count}!" end *key, last = states key.inject(@transitions) { |h,k| h[k] ||= {}; h[k] } key.inject(@transitions, :fetch)[last] ||= 0 key.inject(@transitions, :fetch)[last] += 1 end |
#transitions_from(states) ⇒ Object
26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 |
# File 'lib/markov/transition_matrix.rb', line 26 def transitions_from(states) states = [states] unless states.is_a?(Array) if states.count >= @depth states = states[-(@depth-1)..-1] end if @depth == 1 states = [] end if states.count > 0 @transitions.dig(*states) else @transitions end end |