Class: PageRank::Base
- Inherits:
-
Object
- Object
- PageRank::Base
- Defined in:
- lib/page_rank/base.rb
Overview
A base class for PageRank implementations. This class provides the basic framework for adding (optionall weighted) nodes to the graph and then performing iterations of PageRank to within the desired tolerance (or maximum allowed number of iterations).
Instance Method Summary collapse
-
#add(_source, _dest, **_options) ⇒ nil
Adds a directed (and optionally weighted) edge to the graph.
-
#calculate(max_iterations: -1,, **_) ⇒ Hash<Object, Float>
Perform the PageRank calculation.
-
#damping=(damping) ⇒ Float
Set the damping probability.
-
#initialize(damping: nil, tolerance: nil, **_) ⇒ Base
constructor
A new instance of Base.
-
#tolerance=(tolerance) ⇒ Float
Set the tolerance value.
Constructor Details
#initialize(damping: nil, tolerance: nil, **_) ⇒ Base
Returns a new instance of Base.
12 13 14 15 |
# File 'lib/page_rank/base.rb', line 12 def initialize(damping: nil, tolerance: nil, **_) self.damping = damping self.tolerance = tolerance end |
Instance Method Details
#add(_source, _dest, **_options) ⇒ nil
Adds a directed (and optionally weighted) edge to the graph
37 38 39 |
# File 'lib/page_rank/base.rb', line 37 def add(_source, _dest, **) raise NotImplementedError end |
#calculate(max_iterations: -1,, **_) ⇒ Hash<Object, Float>
Perform the PageRank calculation
44 45 46 47 48 49 50 51 52 53 54 55 56 |
# File 'lib/page_rank/base.rb', line 44 def calculate(max_iterations: -1, **_) ranks = initial_ranks loop do break if max_iterations.zero? prev_ranks = ranks ranks = calculate_step(ranks) break if distance(ranks, prev_ranks) < @tolerance max_iterations -= 1 end sort_ranks(ranks) end |
#damping=(damping) ⇒ Float
Set the damping probability
20 21 22 23 |
# File 'lib/page_rank/base.rb', line 20 def damping=(damping) @damping = damping || 0.85 raise ArgumentError, 'Invalid damping factor' if @damping <= 0 || @damping > 1 end |
#tolerance=(tolerance) ⇒ Float
Set the tolerance value
28 29 30 31 |
# File 'lib/page_rank/base.rb', line 28 def tolerance=(tolerance) @tolerance = tolerance || 0.0001 raise ArgumentError, 'Invalid tolerance factor' if @tolerance.negative? || @tolerance > 1 end |