Compare commits

..

8 Commits

Author SHA1 Message Date
c050f2027f Improve benchmark
Some checks failed
Run unit tests / rubocop (pull_request) Failing after 1m54s
Run unit tests / check-licenses (pull_request) Successful in 1m57s
Run unit tests / copyright_notice (pull_request) Successful in 2m40s
Run unit tests / unit_tests (pull_request) Failing after 4m9s
Run unit tests / build-static-assets (pull_request) Has been skipped
2025-07-22 15:34:45 +02:00
25bd53600e Use frozen versions of tables
Some checks failed
Run unit tests / rubocop (pull_request) Failing after 34s
Run unit tests / copyright_notice (pull_request) Successful in 56s
Run unit tests / check-licenses (pull_request) Successful in 1m12s
Run unit tests / unit_tests (pull_request) Failing after 1m27s
Run unit tests / build-static-assets (pull_request) Has been skipped
2025-07-18 18:12:53 +02:00
bf15184360 Merge branch 'benchmark' into ractors 2025-07-18 16:10:25 +02:00
4e7d59687a Merge remote-tracking branch 'origin/main' into ractors 2025-07-18 15:08:05 +02:00
801e4a280c Merge branch 'main' into ractors
Some checks failed
Run unit tests / rubocop (pull_request) Failing after 52s
Run unit tests / check-licenses (pull_request) Successful in 57s
Run unit tests / copyright_notice (pull_request) Successful in 1m28s
Run unit tests / unit_tests (pull_request) Successful in 2m41s
Run unit tests / build-static-assets (pull_request) Has been skipped
2025-01-27 18:26:16 +00:00
3e62f2b08e Merge branch 'main' into ractors
Some checks failed
Run unit tests / unit_tests (pull_request) Failing after 5m0s
Build docker image / build-static-assets (pull_request) Failing after 1h10m27s
2024-08-12 08:21:57 +00:00
f3d7f76e79 Merge branch 'main' into ractors
Some checks failed
Run unit tests / unit_tests (pull_request) Failing after 2s
2024-08-02 16:46:29 +00:00
7b8cdd2276 WIP ractors
Some checks failed
Run unit tests / unit_tests (pull_request) Failing after 3s
2024-08-02 17:29:04 +02:00
10 changed files with 186 additions and 154 deletions

View File

@ -16,7 +16,6 @@ class AffinityGroupsHierarchy < Array
end end
discomforts discomforts
invitation_counts
freeze freeze
end end
@ -55,16 +54,8 @@ class AffinityGroupsHierarchy < Array
Rational(dist, dist + 1) Rational(dist, dist + 1)
end end
def guest_count(invitation_id)
@invitation_counts[invitation_id] || 0
end
private private
def invitation_counts
@invitation_counts = Guest.where.not(invitation_id: nil).group(:invitation_id).count
end
def discomforts def discomforts
@discomforts ||= GroupAffinity.pluck(:group_a_id, :group_b_id, @discomforts ||= GroupAffinity.pluck(:group_a_id, :group_b_id,
:discomfort).each_with_object({}) do |(id_a, id_b, discomfort), acc| :discomfort).each_with_object({}) do |(id_a, id_b, discomfort), acc|

View File

@ -11,11 +11,12 @@ module Tables
end end
def calculate def calculate
# Rails.logger.info "Calculating discomfort of table with id #{table.object_id}"
breakdown.values.sum breakdown.values.sum
end end
def breakdown def breakdown
@breakdown ||= { table_size_penalty:, cohesion_penalty:, invitations_penalty: } @breakdown ||= { table_size_penalty:, cohesion_penalty: }
end end
private private
@ -39,12 +40,6 @@ module Tables
10 * (cohesion_discomfort * 1.0 / table.size) 10 * (cohesion_discomfort * 1.0 / table.size)
end end
def invitations_penalty
2 * table.map(&:invitation_id)
.tally
.sum { |invitation_id, guests_in_table| hierarchy.guest_count(invitation_id) - guests_in_table }
end
# #
# Calculates the discomfort of the table based on the cohesion of the guests. The total discomfort # Calculates the discomfort of the table based on the cohesion of the guests. The total discomfort
# is calculated as the sum of the discomfort of each pair of guests. The discomfort of a pair of # is calculated as the sum of the discomfort of each pair of guests. The discomfort of a pair of

View File

@ -73,6 +73,8 @@ module Tables
def local_discomfort(table) def local_discomfort(table)
table.discomfort ||= DiscomfortCalculator.new(table:, hierarchy:).calculate table.discomfort ||= DiscomfortCalculator.new(table:, hierarchy:).calculate
table.freeze
table.discomfort
end end
end end
end end

View File

@ -12,19 +12,37 @@ module Tables
def each def each
@initial_solution.tables.permutation(2) do |table_a, table_b| @initial_solution.tables.permutation(2) do |table_a, table_b|
table_a.dup.each do |person| table_a.dup.each do |person|
original_discomfort_a = table_a.reset
original_discomfort_b = table_b.reset
table_a.delete(person) new_solution = Distribution.new(
table_b << person min_per_table: @initial_solution.min_per_table,
max_per_table: @initial_solution.max_per_table,
hierarchy: @initial_solution.hierarchy
)
yield(@initial_solution) new_solution.tables = @initial_solution.tables.dup
ensure
table_b.delete(person)
table_a << person
table_a.discomfort = original_discomfort_a new_solution.tables.delete(table_a)
table_b.discomfort = original_discomfort_b new_solution.tables.delete(table_b)
modified_table_a = table_a.dup.tap(&:reset)
modified_table_b = table_b.dup.tap(&:reset)
new_solution.tables << modified_table_a
new_solution.tables << modified_table_b
# original_discomfort_a = table_a.reset
# original_discomfort_b = table_b.reset
modified_table_a.delete(person)
modified_table_b << person
yield(new_solution)
# ensure
# table_b.delete(person)
# table_a << person
# table_a.discomfort = original_discomfort_a
# table_b.discomfort = original_discomfort_b
end end
end end
end end

View File

@ -12,25 +12,45 @@ module Tables
def each def each
@initial_solution.tables.combination(2) do |table_a, table_b| @initial_solution.tables.combination(2) do |table_a, table_b|
table_a.to_a.product(table_b.to_a).each do |(person_a, person_b)| table_a.to_a.product(table_b.to_a).each do |(person_a, person_b)|
original_discomfort_a = table_a.reset
original_discomfort_b = table_b.reset
table_a.delete(person_a) new_solution = Distribution.new(
table_b.delete(person_b) min_per_table: @initial_solution.min_per_table,
max_per_table: @initial_solution.max_per_table,
hierarchy: @initial_solution.hierarchy
)
table_a << person_b new_solution.tables = @initial_solution.tables.dup
table_b << person_a
yield(@initial_solution) new_solution.tables.delete(table_a)
ensure new_solution.tables.delete(table_b)
table_a.delete(person_b)
table_b.delete(person_a)
table_a << person_a
table_b << person_b
table_a.discomfort = original_discomfort_a modified_table_a = table_a.dup.tap(&:reset)
table_b.discomfort = original_discomfort_b modified_table_b = table_b.dup.tap(&:reset)
new_solution.tables << modified_table_a
new_solution.tables << modified_table_b
# original_discomfort_a = table_a.reset
# original_discomfort_b = table_b.reset
modified_table_a.delete(person_a)
modified_table_b.delete(person_b)
modified_table_a << person_b
modified_table_b << person_a
yield(new_solution)
# ensure
# table_a.delete(person_b)
# table_b.delete(person_a)
# table_a << person_a
# table_b << person_b
# table_a.discomfort = original_discomfort_a
# table_b.discomfort = original_discomfort_b
end end
end end
end end

View File

@ -20,7 +20,16 @@ module VNS
@perturbations << klass @perturbations << klass
end end
attr_writer :initial_solution def initialize_ractors(count: Concurrent.processor_count)
@ractors = count.times.map do |i|
Ractor.new(name: "VNS Ractor #{i}") do
# @target_function.call(Ractor.receive)
Ractor.receive.discomfort # Hard-coded for now, should be dynamic
end
end.cycle
end
attr_writer :initial_solution, :ractors
def run def run
raise 'No target function defined' unless @target_function raise 'No target function defined' unless @target_function
@ -30,6 +39,10 @@ module VNS
@best_solution = @initial_solution @best_solution = @initial_solution
@best_score = @target_function.call(@best_solution) @best_score = @target_function.call(@best_solution)
@best_solution.freeze
@best_solution.tables.freeze
# @best_solution.tables.each(&:freeze)
self.class.sequence(@perturbations).each do |perturbation| self.class.sequence(@perturbations).each do |perturbation|
optimize(perturbation) optimize(perturbation)
end end
@ -44,9 +57,27 @@ module VNS
optimized = false optimized = false
perturbation_klass.new(@best_solution).each do |alternative_solution| perturbation_klass.new(@best_solution).each do |alternative_solution|
score = @target_function.call(alternative_solution) # original_score =
# ractor = @ractors.next
# Rails.logger.info("Processed by ractor #{ractor.name}")
# ractor.send(alternative_solution)
# new_score = ractor.take
# binding.pry if new_score != original_score
# score = new_score
score = @target_function.call(alternative_solution)
# Rails.logger.info("Evaluating alternative solution with score: #{score}")
next if score >= @best_score next if score >= @best_score
# Rails.logger.info("Found better solution with score: #{score} (previous: #{@best_score})")
@best_solution = alternative_solution.deep_dup @best_solution = alternative_solution.deep_dup
@best_score = score @best_score = score
optimized = true optimized = true

View File

@ -10,7 +10,7 @@ Rswag::Ui.configure do |c|
# (under openapi_root) as JSON or YAML endpoints, then the list below should # (under openapi_root) as JSON or YAML endpoints, then the list below should
# correspond to the relative paths for those endpoints. # correspond to the relative paths for those endpoints.
c.openapi_endpoint '/api/api-docs/v1/swagger.yaml', 'API V1 Docs' c.swagger_endpoint '/api/api-docs/v1/swagger.yaml', 'API V1 Docs'
# Add Basic Auth in case your API is private # Add Basic Auth in case your API is private
# c.basic_auth_enabled = true # c.basic_auth_enabled = true

51
lib/tasks/ractors.rake Normal file
View File

@ -0,0 +1,51 @@
namespace :ractors do
desc 'Run the Ractors example'
task run: :environment do
list = (1..20)
number_of_ractors = Concurrent.processor_count
ractors = number_of_ractors.times.map do |i|
Ractor.new(name: "Ractor #{i}") do
loop do
number = Ractor.receive
puts "Processing #{number} in #{Ractor.current.name}"
Ractor.yield "eureka" if number == 17
end
end
end.cycle
list.each do |i|
ractors.next.send(i)
end
puts "all enqueued"
binding.pry
Ractor.select(*ractors)
# binding.pry
# number_of_ractors.times do |i|
# r = Ractor.new(name: "Ractor #{i}") do
# Ractor.receive.each do |i|
# puts "Processing index #{i} in #{Ractor.current.name}"
# end
# end
# r.send((i * 250)...((i + 1) * 250))
# end
# ractor = Ractor.new do
# loop do
# puts 'I will receive a message soon'
# msg = Ractor.receive
# puts 'I will return a tripple of what I receive'
# Ractor.yield(msg * 3)
# end
# end
# heavy_calculation.send(15)
# puts heavy_calculation.take
end
end

View File

@ -4,26 +4,47 @@ namespace :vns do
desc 'Benchmarks the efficiency of the VNS implementation' desc 'Benchmarks the efficiency of the VNS implementation'
task benchmark: :environment do task benchmark: :environment do
ActsAsTenant.with_tenant(Wedding.first) do ActsAsTenant.with_tenant(Wedding.first) do
Rails.logger.info "There are #{Guest.potential.count} potential guests"
engine = VNS::Engine.new iterations = 10
engine.add_perturbation(Tables::Swap) guests = Guest.potential
engine.add_perturbation(Tables::Shift)
Rails.logger.info "There are #{guests.count} potential guests"
time_acc = 0
solution_acc = 0
hierarchy = AffinityGroupsHierarchy.new hierarchy = AffinityGroupsHierarchy.new
initial_solution = Tables::Distribution.new(min_per_table: 8, max_per_table: 10, hierarchy:)
random = Random.new(561_163) iterations.times do |i|
initial_solution.random_distribution(Guest.potential.shuffle(random:), random:) engine = VNS::Engine.new
engine.initial_solution = initial_solution engine.add_perturbation(Tables::Swap)
engine.add_perturbation(Tables::Shift)
engine.target_function(&:discomfort) initial_solution = Tables::Distribution.new(min_per_table: 8, max_per_table: 10, hierarchy:)
solution = Rails.benchmark('VNS Benchmarking') { engine.run } random = Random.new(i)
initial_solution.random_distribution(guests.shuffle(random:), random:)
Rails.logger.info "Best solution found with discomfort: #{solution.discomfort}" engine.initial_solution = initial_solution
engine.target_function(&:discomfort)
start_time = Time.now
solution = engine.run
elapsed = Time.now - start_time
time_acc += elapsed
solution_acc += solution.discomfort
Rails.logger.info "[#{elapsed}] Best solution found with discomfort: #{solution.discomfort}"
end
Rails.logger.info "Average time: #{time_acc / iterations} seconds"
Rails.logger.info "Average discomfort: #{solution_acc / iterations}"
end end
end end
end end

View File

@ -14,14 +14,14 @@ module Tables
describe '#calculate' do describe '#calculate' do
before do before do
allow(calculator).to receive_messages(table_size_penalty: 2, cohesion_penalty: 5, invitations_penalty: 4) allow(calculator).to receive_messages(table_size_penalty: 2, cohesion_discomfort: 3)
end end
let(:table) { Table.new(create_list(:guest, 6)) } let(:table) { Table.new(create_list(:guest, 6)) }
it 'returns the sum of the table size penalty and the average cohesion penalty', :aggregate_failures do it 'returns the sum of the table size penalty and the average cohesion penalty', :aggregate_failures do
expect(calculator.calculate).to eq(11) expect(calculator.calculate).to eq(7)
expect(calculator.breakdown).to eq(table_size_penalty: 2, cohesion_penalty: 5, invitations_penalty: 4) expect(calculator.breakdown).to eq(table_size_penalty: 2, cohesion_penalty: 5)
end end
end end
@ -73,102 +73,5 @@ module Tables
it { expect(calculator.send(:table_size_penalty)).to eq(10) } it { expect(calculator.send(:table_size_penalty)).to eq(10) }
end end
end end
describe '#cohesion_penalty' do
let(:calculator) { described_class.new(table:, hierarchy:) }
let(:table) { Table.new(guests) }
context 'when all guests belong to the same group' do
let(:guests) { create_list(:guest, 6, group: family) }
let(:hierarchy) { instance_double(AffinityGroupsHierarchy, discomfort: 0) }
it 'returns 0 as cohesion penalty' do
expect(calculator.send(:cohesion_penalty)).to eq(0)
end
end
context 'when guests belong to two different groups with discomfort 1' do
let(:guests) do
create_list(:guest, 3, group: family) +
create_list(:guest, 3, group: friends)
end
let(:hierarchy) do
instance_double(AffinityGroupsHierarchy, discomfort: 1)
end
it 'calculates the correct cohesion penalty' do
# 3 from family, 3 from friends: 3*3*1 = 9 discomfort
expect(calculator.send(:cohesion_penalty)).to eq(10 * (9.0 / 6))
end
end
context 'when guests belong to three groups with different discomforts' do
let(:guests) do
create_list(:guest, 2, group: family) +
create_list(:guest, 2, group: friends) +
create_list(:guest, 2, group: work)
end
let(:hierarchy) do
instance_double(AffinityGroupsHierarchy)
end
before do
allow(hierarchy).to receive(:discomfort).with(family.id, friends.id).and_return(0.5)
allow(hierarchy).to receive(:discomfort).with(family.id, work.id).and_return(1)
allow(hierarchy).to receive(:discomfort).with(friends.id, work.id).and_return(0.2)
allow(hierarchy).to receive(:discomfort).with(friends.id, family.id).and_return(0.5)
allow(hierarchy).to receive(:discomfort).with(work.id, family.id).and_return(1)
allow(hierarchy).to receive(:discomfort).with(work.id, friends.id).and_return(0.2)
end
it 'calculates the correct cohesion penalty' do
# pairs: (family, friends): 2*2*0.5 = 2
# (family, work): 2*2*1 = 4
# (friends, work): 2*2*0.2 = 0.8
# total discomfort = 2 + 4 + 0.8 = 6.8
expect(calculator.send(:cohesion_penalty)).to eq(10 * (6.8 / 6))
end
end
end
describe '#invitations_penalty' do
let(:invitation_a) { create(:invitation) }
let(:invitation_b) { create(:invitation) }
let(:invitation_c) { create(:invitation) }
let(:table) do
create_list(:guest, 2, invitation: invitation_a) +
create_list(:guest, 3, invitation: invitation_b) +
create_list(:guest, 4, invitation: invitation_c)
end
context 'when the table contains all members of an invitation' do
it 'returns 0 as penalty' do
expect(calculator.send(:invitations_penalty)).to eq(0)
end
end
context 'when there is an additional guest of one of the invitations that is not included' do
before do
create(:guest, invitation: invitation_a)
end
it 'returns the penalty for the missing guest' do
expect(calculator.send(:invitations_penalty)).to eq(2)
end
end
context 'when there are multiple guests missing from different invitations' do
before do
create(:guest, invitation: invitation_b)
create(:guest, invitation: invitation_c)
end
it 'returns 2x # of guests left out as the total penalty for all missing guests' do
expect(calculator.send(:invitations_penalty)).to eq(4)
end
end
end
end end
end end