class Lindenmayer::Production
Base Production
Replaces a single character with a string, or applies stochastic weighting
Attributes
transform[R]
Public Class Methods
new(transform, options = {})
click to toggle source
transform - (string) Replacement if matching
# File lib/production.rb, line 12 def initialize(transform, options = {}) @transform = transform post_init(options) end
Protected Instance Methods
apply_stochastic_transform()
click to toggle source
# File lib/production.rb, line 36 def apply_stochastic_transform random_value = @random.rand transform_idx = nil summed_stochastic_weights.each_with_index do |weight, weight_idx| transform_idx = weight_idx and break if random_value <= weight end @transform[:successors][transform_idx][:successor] end
apply_transform()
click to toggle source
# File lib/production.rb, line 28 def apply_transform if stochastic? apply_stochastic_transform else @transform end end
post_init(options)
click to toggle source
# File lib/production.rb, line 23 def post_init(options) @random = options[:random] || Random.new validate_stochastic if stochastic? end
stochastic?()
click to toggle source
# File lib/production.rb, line 55 def stochastic? return false if @transform.is_a?(String) if @transform.is_a?(Hash) && @transform[:successors].any? true else # Whatever you are, we don't suppor it raise InvalidProductionError end end
stochastic_weights()
click to toggle source
# File lib/production.rb, line 51 def stochastic_weights @stochastic_weights ||= @transform[:successors].map { |s| s[:weight] } end
summed_stochastic_weights()
click to toggle source
# File lib/production.rb, line 47 def summed_stochastic_weights @summed_weights ||= stochastic_weights.each_with_index.map { |weight, idx| stochastic_weights[0..idx].reduce(:+) } end
validate_stochastic()
click to toggle source
# File lib/production.rb, line 65 def validate_stochastic raise InvalidProductionError unless summed_stochastic_weights.last == 1 end