Class: VMM::PPM

Inherits:
Object
  • Object
show all
Defined in:
lib/lite/vmm.rb

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(ab, d = 5) ⇒ PPM

Returns a new instance of PPM.



7
8
9
10
11
# File 'lib/lite/vmm.rb', line 7

def initialize ab,d=5
  @trie = Trie.new
  @ab = ABet.new ab
  @d = d
end

Class Method Details

.deserialize(serialization_str) ⇒ Object



40
41
42
43
44
45
# File 'lib/lite/vmm.rb', line 40

def self.deserialize serialization_str
  model = MessagePack.unpack( serialization_str )
  ppm = PPM.new( model['ab'],model['d'] )
  ppm.instance_variable_set( :@trie, Trie.new( model['trie'] ) )
  ppm
end

.from_file(file_path) ⇒ Object



54
55
56
57
58
59
# File 'lib/lite/vmm.rb', line 54

def self.from_file file_path
  model = MessagePack.unpack( File.new( file_path,"rb").readlines.join )
  ppm = PPM.new( model['ab'],model['d'] )
  ppm.instance_variable_set( :@trie, Trie.new( model['trie'] ) )
  ppm
end

Instance Method Details

#learn(str) ⇒ Object



13
14
15
# File 'lib/lite/vmm.rb', line 13

def learn str
  (str.size - @d-1 ).times{|i| @trie.grow(str[i..i+@d-1].chars.map{|sym| @ab.sym_to_i( sym )}, @ab.sym_to_i( str[i+@d] ) ) }
end

#log_eval(str) ⇒ Object



17
18
19
20
21
# File 'lib/lite/vmm.rb', line 17

def log_eval str
  (str.size - @d).times.inject(0.0) do |agg,i|
    agg += path_predict( @ab.sym_to_i(str[@d]) , @trie.path( str[i..i+@d-1].chars.map{|sym| @ab.sym_to_i(sym)} ) )
  end
end

#path_predict(sym, path) ⇒ Object



23
24
25
26
27
28
29
# File 'lib/lite/vmm.rb', line 23

def path_predict sym, path
  path.reverse.inject( 0.0 ) do |agg, context|
    agg += Math.log( single_pr( sym, context ), 2.0 )
    break( agg ) if context===@trie.root or !context[0].has_key?( sym )
    agg
  end
end

#serializeObject



36
37
38
# File 'lib/lite/vmm.rb', line 36

def serialize 
  { 'trie' => @trie.root, 'ab' => @ab.sym_arr, 'd' => @d }.to_msgpack
end

#single_pr(sym, context) ⇒ Object



31
32
33
34
# File 'lib/lite/vmm.rb', line 31

def single_pr sym, context
  ( context[1].has_key?( sym ) ? context[1][sym] : context[1].size ) /  
    (context[1].values.inject(:+) + context[1].size).to_f  
end

#to_file(file_path) ⇒ Object



47
48
49
50
51
52
# File 'lib/lite/vmm.rb', line 47

def to_file file_path 
  msg = serialize
  out = File.new( file_path, "w" )
  out.print msg
  out.close
end