Class: TabuSearch::Context

Inherits:
Object
  • Object
show all
Defined in:
lib/tabu_search/context.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(tabu_size = 10) ⇒ Context

Returns a new instance of Context.



8
9
10
11
12
13
14
15
# File 'lib/tabu_search/context.rb', line 8

def initialize(tabu_size = 10)
  @tabu_list = []
  @tabu_set = Set.new
  @tabu_size = tabu_size

  @best_genome = nil
  @best_fitness = nil
end

Instance Attribute Details

#best_fitnessObject

Returns the value of attribute best_fitness.



5
6
7
# File 'lib/tabu_search/context.rb', line 5

def best_fitness
  @best_fitness
end

#best_genomeObject

Returns the value of attribute best_genome.



5
6
7
# File 'lib/tabu_search/context.rb', line 5

def best_genome
  @best_genome
end

#tabu_listObject

Returns the value of attribute tabu_list.



6
7
8
# File 'lib/tabu_search/context.rb', line 6

def tabu_list
  @tabu_list
end

#tabu_setObject

Returns the value of attribute tabu_set.



6
7
8
# File 'lib/tabu_search/context.rb', line 6

def tabu_set
  @tabu_set
end

#tabu_sizeObject

Returns the value of attribute tabu_size.



6
7
8
# File 'lib/tabu_search/context.rb', line 6

def tabu_size
  @tabu_size
end

Instance Method Details

#search(unit, times) ⇒ Object



17
18
19
20
21
22
23
24
25
26
27
# File 'lib/tabu_search/context.rb', line 17

def search(unit, times)
  @best_genome = unit.genome.dup
  @best_fitness = unit.fitness

  times.times do
    data = search_best_neighbour(unit)
    unit.step(self, data)
  end
  unit.genome = best_genome
  unit
end

#search_best_neighbour(unit) ⇒ Object



42
43
44
45
46
47
48
49
50
# File 'lib/tabu_search/context.rb', line 42

def search_best_neighbour(unit)
  actions = unit.search_neighbour(self).sort_by! {|data| -data[-1] }
  return actions[0] if actions[0][-1] > best_fitness

  actions.each do |data|
    return data unless tabu_set.include?(data[0])
  end
  return actions.first
end

#update(id, genome, fitness) ⇒ Object



29
30
31
32
33
34
35
36
37
38
39
40
# File 'lib/tabu_search/context.rb', line 29

def update(id, genome, fitness)
  if fitness > best_fitness
    self.best_genome = genome.dup
    self.best_fitness = fitness
  end

  unless tabu_set.include?(id)
    tabu_set << id
    tabu_list << id
    tabu_set.delete(tabu_list.shift) if tabu_list.length > tabu_size
  end
end