diff --git a/examples/tsp.rb b/examples/tsp.rb index a94630c..eca6b7a 100644 --- a/examples/tsp.rb +++ b/examples/tsp.rb @@ -1,9 +1,10 @@ # frozen_string_literal: true -# bundle exec ruby --jit examples/tsp.rb --dot +# bundle exec ruby --jit examples/tsp.rb --dot --png $LOAD_PATH.unshift File.expand_path('../lib', __dir__) require 'optparse' +require 'open3' require 'alns' require 'alns/state' require 'alns/accept/hill_climbing' @@ -14,24 +15,35 @@ module TSP def self.solve - write_dot = false seed = 1234 + max_iterations = 2000 + write_dot = false + write_png = false secure_random = false OptionParser.new do |parser| parser.banner = 'Usage: tsp.rb [options]' - parser.on('-d', '--dot', 'write a dot file with the result') do - write_dot = true - end - parser.on('-sSEED', '--seed=SEED', Integer, 'specify seed') do |v| seed = v end + parser.on('-iCOUNT', '--iteration-count=COUNT', Integer, 'iteration count') do |v| + max_iterations = v + end + parser.on('-r', '--secure-random', 'use secure random') do secure_random = true end + + parser.on('-d', '--dot', 'create a dot file with the result') do + write_dot = true + end + + parser.on('-g', '--png', 'create a png file with the result') do + write_png = true + write_dot = true + end end.parse! nodes = make_nodes(COORDS) @@ -69,7 +81,7 @@ def self.solve select = ALNS::Select::RouletteWheel.new([3, 2, 1, 0.5], 0.8, num_destroy, num_repair) accept = ALNS::Accept::HillClimbing.new - stop = ALNS::Stop::MaxIterations.new(2000) + stop = ALNS::Stop::MaxIterations.new(max_iterations) # stop = ALNS::Stop::MaxRuntime.new(2) start = Process.clock_gettime(Process::CLOCK_MONOTONIC) @@ -92,6 +104,7 @@ def self.solve # neato -Tpng tmp/tsp.dot -o tmp/tsp.png write_dot_file('tmp/tsp.dot', COORDS, result.best_state.edges) if write_dot + write_png_file('tmp/tsp.dot', 'tmp/tsp.png') if write_png end def self.operator_stats_to_s(counter) @@ -435,6 +448,17 @@ def self.write_dot_file(filename, nodes, edges) f.puts '}' end end + + def self.write_png_file(dotfile, pngfile) + stdout, stderr, status = Open3.capture3('neato', '-Tpng', dotfile, '-o', pngfile) + return if status.success? + + puts "neato is failed with status: #{status}" + puts 'STDOUT:' + puts stdout + puts 'STDERR:' + puts stderr + end end TSP.solve if __FILE__ == $PROGRAM_NAME