Sha256: 5556fefc591deeceb351ee751f5c53cc0b8c3f18d5e0db6867a608a10f60c72a

Contents?: true

Size: 1.66 KB

Versions: 6

Compression:

Stored size: 1.66 KB

Contents

require 'rubygems'
require 'gsl'

include GSL

class Node
  
  attr_reader :name, :labels, :probabilities, :likelihood
  
  def initialize(*args)
    @name = args.shift
    raise ArgumentError, "Must provide a node name" unless self.name
    if args.empty?
      extract_from_array([:true, :false])
    elsif args.length == 1 and args.first.is_a?(Hash)
      extract_from_hash(args.first)
    elsif args.length == 1 and args.first.is_a?(Array)
      extract_from_array(args.first)
    else
      extract_from_array(args)
    end
    assert_likelihood
  end
  
  def inspect
    "Node: #{self.labels.inspect} #{self.probabilities.inspect}"
  end
  
  def belief
    probabilities * likelihood
  end
  
  alias :b :belief
  alias :l :likelihood
  alias :p :probabilities
  
  protected

    def assert_likelihood
      @likelihood = Vector.ary_to_gv(Array.new(@probabilities.size, 1))
    end
    
    def extract_from_array(array)
      @labels = array
      @probabilities = Vector.ary_to_gv(uniform_distribution(array.size))
    end
    
    def uniform_distribution(n)
      Array.new(n, 1/n.to_f)
    end

    def extract_from_hash(hash)
      @labels, probabilities = [], []
      hash.each do |k, v|
        @labels << k
        probabilities << v
      end
      @probabilities = Vector.ary_to_gv(probabilities)
      normalize_probabilities!
    end
    
    # I don't like GSL::Vector#normalize!, it's not accurate, or has a different
    # idea of what a normalized vector looks like.
    def normalize_probabilities!
      sum = 0.0
      @probabilities.each do |value|
        sum += value
      end
      @probabilities.map! do |value|
        value.to_f / sum
      end
    end
    
end

Version data entries

6 entries across 6 versions & 1 rubygems

Version Path
fathom-0.3.0 lib/fathom/archive/node.rb
fathom-0.2.3 lib/fathom/archive/node.rb
fathom-0.2.2 lib/fathom/archive/node.rb
fathom-0.2.1 lib/fathom/archive/node.rb
fathom-0.2.0 lib/fathom/archive/node.rb
fathom-0.1.0 lib/fathom/archive/node.rb