Class: StringEntropy::Info

Inherits:
Object
  • Object
show all
Defined in:
lib/string_entropy/info.rb

Constant Summary collapse

POSSIBLE_CHARS =

Supports only ASCII_8BIT encoding

95.freeze

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(string = nil) ⇒ Info

Returns a new instance of Info.



18
19
20
21
22
23
24
25
26
27
28
29
30
# File 'lib/string_entropy/info.rb', line 18

def initialize(string=nil)
  @string    = ascii(string)
  @count     = @string.split("").each.with_object(Hash.new(0.to_f)) { |char, hash| hash[char] += 1 }.freeze
  @frequency = @count.each_with_object(Hash.new) { |(char,count),frequency| frequency[char] = (count / @string.length) }.freeze

  @information_entropy = Math.log2(POSSIBLE_CHARS**@string.length).freeze
  @shannon_entropy     = -(@frequency.values.map { |x| x * Math.log2(x) }.inject(:+)).freeze
  @metric_entropy      = (@shannon_entropy / @string.length).freeze

  @shannon_formulas    = shannon_formulas

  self.freeze
end

Instance Attribute Details

#countObject (readonly)

Returns the value of attribute count.



4
5
6
# File 'lib/string_entropy/info.rb', line 4

def count
  @count
end

#encodingObject (readonly)

Returns the value of attribute encoding.



4
5
6
# File 'lib/string_entropy/info.rb', line 4

def encoding
  @encoding
end

#frequencyObject (readonly)

Returns the value of attribute frequency.



4
5
6
# File 'lib/string_entropy/info.rb', line 4

def frequency
  @frequency
end

#information_entropyObject (readonly) Also known as: entropy

Returns the value of attribute information_entropy.



4
5
6
# File 'lib/string_entropy/info.rb', line 4

def information_entropy
  @information_entropy
end

#metric_entropyObject (readonly)

Returns the value of attribute metric_entropy.



4
5
6
# File 'lib/string_entropy/info.rb', line 4

def metric_entropy
  @metric_entropy
end

#shannon_entropyObject (readonly)

Returns the value of attribute shannon_entropy.



4
5
6
# File 'lib/string_entropy/info.rb', line 4

def shannon_entropy
  @shannon_entropy
end

#stringObject (readonly)

Returns the value of attribute string.



4
5
6
# File 'lib/string_entropy/info.rb', line 4

def string
  @string
end

Instance Method Details

#shannon_formulasObject

Show the math behind calculating Shannon Entropy as an array of the steps taken



33
34
35
36
37
38
39
40
41
42
# File 'lib/string_entropy/info.rb', line 33

def shannon_formulas
  formulas = []
  formulas << @frequency.values.map { |x| "(#{x} * Math.log2(#{x}))" }.join("+")
  formulas << @frequency.values.map { |x| "(#{x * Math.log2(x)})" }.join("+")
  formulas << "#{@frequency.values.map { |x| x * Math.log2(x) }.inject(:+)}"
  formulas.map! { |x| "-[ (#{x}) ]" }
  formulas << "#{@shannon_entropy}"
  formulas.map! { |x| "H(X) = #{x}"}
  formulas.freeze
end