class PageRank::Main

Attributes

nodes[R]
score[R]

Public Class Methods

new() click to toggle source

creat instance

# File lib/pagerank/pagerank.rb, line 16
def initialize
  @nodes        = []
  @score        = {}
  @follow_links = {}
  @back_links = {}
  @iterates = 0
end

Public Instance Methods

add(from, to) click to toggle source

add node into nodes and edge into follow_links

# File lib/pagerank/pagerank.rb, line 32
def add from, to
  @nodes << from unless @nodes.include?(from)
  @nodes << to unless @nodes.include?(to)
  @follow_links[from] ||= []
  @follow_links[from] << to
  @back_links[to] ||= []
  @back_links[to] << from
end
calculate() click to toggle source

calculate pagerank

# File lib/pagerank/pagerank.rb, line 42
def calculate
  if @score == {}
    initial_value
  end

  @score.each do |from, value|
    if @back_links[from]
      score = @score[from]
      @back_links[from].each do |to|
        score += 0.15 + 0.85 * @score[to]
      end
      @score[from] = score
    else
      @score[from] = 0.15
    end
  end

  normalization

  @iterates += 1
  # return true if convergence?
  return calculate unless @iterates == 1
  return true
end
convergence?(convergence=0.01) click to toggle source

check convergence

# File lib/pagerank/pagerank.rb, line 74
def convergence? convergence=0.01
  return (convergence < 1.0)
end
initial_value() click to toggle source

divide among initial value

# File lib/pagerank/pagerank.rb, line 25
def initial_value
  @nodes.each do |node|
    @score[node] = 1.0 / @nodes.size
  end
end
normalization() click to toggle source
# File lib/pagerank/pagerank.rb, line 67
def normalization
  sum = Math.sqrt(@score.inject(0){|sum, (key, value)| sum+=(value**2)})
  norm = @score.map{|key,value|value=value/sum}
  @score.each_with_index{|(key,value),index|@score[key]=norm[index]}
end