Class: Suimin::Sleeper

Inherits:
Object
  • Object
show all
Defined in:
lib/suimin/sleeper.rb

Defined Under Namespace

Classes: InvalidRuleException

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(_config) ⇒ Sleeper

_config:i The name of the sleeper instance. _config: An array of arrays whose element is [probablility, sleep_duration_in_second]

For example [0.5, 1] means the probablity of sleeping for 1 second is 0.5
If sum of the probability isn't 1.0, the probablities are normalized automatically.
For example, [[1.0, 1], [1.0, 3]] => [[0.5, 1], [0.5, 3]]


12
13
14
15
# File 'lib/suimin/sleeper.rb', line 12

def initialize(_config)
  @distribution = normalize_distribution(_config[:distribution]).sort{|a,b| a[0] <=> b[0]}
  @name = _config[:name]
end

Instance Attribute Details

#distributionObject (readonly)

Returns the value of attribute distribution.



5
6
7
# File 'lib/suimin/sleeper.rb', line 5

def distribution
  @distribution
end

#nameObject (readonly)

Returns the value of attribute name.



5
6
7
# File 'lib/suimin/sleeper.rb', line 5

def name
  @name
end

Instance Method Details

#expected_sleep_duration_valueObject



34
35
36
# File 'lib/suimin/sleeper.rb', line 34

def expected_sleep_duration_value
  distribution.inject(0.0) {|res, elm| res += elm[0] * elm[1] }
end

#ruleObject

converts the distribution to cdf



18
19
20
21
# File 'lib/suimin/sleeper.rb', line 18

def rule
  @rule || @distribution.inject([]){|result, elm| result << [(result.empty? ? 0.0 : result.last[0]) + elm[0], elm[1]]}\
                        .tap{|array| array.last[0] = 1.0 } # make sure the last element's cdf is 1.0
end

#sleepObject



23
24
25
# File 'lib/suimin/sleeper.rb', line 23

def sleep
  Kernel.sleep sleep_duration
end

#sleep_durationObject



27
28
29
30
31
32
# File 'lib/suimin/sleeper.rb', line 27

def sleep_duration
  return 0 if rule.empty?

  _rand = SecureRandom.random_number
  rule.find{|elm| elm[0] >= _rand}[1]
end