annealing 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,7 @@
1
+ ---
2
+ SHA256:
3
+ metadata.gz: f897b42e638f2f0f3d951ef0ad9c159352758d120d0978cc522867c2049c0e45
4
+ data.tar.gz: de092114cab627c60484995e8c22f87a9eca73b5965bd90de57f0f177efebadb
5
+ SHA512:
6
+ metadata.gz: 5fc76aa32422d56ed36193cab617bafc6ffa0c72c6f3328dc5d48c691caf1385984e682fecde729b4c8c3f033a48b666b03ea9a4918ae9575ff6146f1382e157
7
+ data.tar.gz: 0e21c28aa803232597f46cd26b6a5167df07ce044d77425e9caeba07181e1cfd4ac0de1709d895f7fe1acac5eeecde6e2eaabb805d11b6f84626a600001407a5
@@ -0,0 +1,8 @@
1
+ /.bundle/
2
+ /.yardoc
3
+ /_yardoc/
4
+ /coverage/
5
+ /doc/
6
+ /pkg/
7
+ /spec/reports/
8
+ /tmp/
@@ -0,0 +1,18 @@
1
+ inherit_from: .rubocop_todo.yml
2
+
3
+ Metrics/AbcSize:
4
+ Max: 25
5
+ Metrics/MethodLength:
6
+ Max: 15
7
+ Layout/LineLength:
8
+ Max: 120
9
+ Lint/RaiseException:
10
+ Enabled: true
11
+ Lint/StructNewOverride:
12
+ Enabled: false
13
+ Style/HashEachMethods:
14
+ Enabled: true
15
+ Style/HashTransformKeys:
16
+ Enabled: true
17
+ Style/HashTransformValues:
18
+ Enabled: true
@@ -0,0 +1,20 @@
1
+ # This configuration was generated by
2
+ # `rubocop --auto-gen-config`
3
+ # on 2020-06-15 23:46:36 -0500 using RuboCop version 0.81.0.
4
+ # The point is for the user to remove these configuration records
5
+ # one by one as the offenses are removed from the code base.
6
+ # Note that changes in the inspected code, or installation of new
7
+ # versions of RuboCop, may require this file to be generated again.
8
+
9
+ # Offense count: 1
10
+ # Configuration parameters: IgnoredMethods.
11
+
12
+
13
+ # Offense count: 1
14
+ # Configuration parameters: CountComments, ExcludedMethods.
15
+
16
+
17
+ # Offense count: 2
18
+ Style/Documentation:
19
+ Exclude:
20
+ - 'test/**/*'
@@ -0,0 +1,6 @@
1
+ ---
2
+ language: ruby
3
+ cache: bundler
4
+ rvm:
5
+ - 2.7.1
6
+ before_install: gem install bundler -v 2.1.4
@@ -0,0 +1,76 @@
1
+ # Contributor Covenant Code of Conduct
2
+
3
+ ## Our Pledge
4
+
5
+ In the interest of fostering an open and welcoming environment, we as
6
+ contributors and maintainers pledge to making participation in our project and
7
+ our community a harassment-free experience for everyone, regardless of age, body
8
+ size, disability, ethnicity, sex characteristics, gender identity and expression,
9
+ level of experience, education, socio-economic status, nationality, personal
10
+ appearance, race, religion, or sexual identity and orientation.
11
+
12
+ ## Our Standards
13
+
14
+ Examples of behavior that contributes to creating a positive environment
15
+ include:
16
+
17
+ * Using welcoming and inclusive language
18
+ * Being respectful of differing viewpoints and experiences
19
+ * Gracefully accepting constructive criticism
20
+ * Focusing on what is best for the community
21
+ * Showing empathy towards other community members
22
+
23
+ Examples of unacceptable behavior by participants include:
24
+
25
+ * The use of sexualized language or imagery and unwelcome sexual attention or
26
+ advances
27
+ * Trolling, insulting/derogatory comments, and personal or political attacks
28
+ * Public or private harassment
29
+ * Publishing others' private information, such as a physical or electronic
30
+ address, without explicit permission
31
+ * Other conduct which could reasonably be considered inappropriate in a
32
+ professional setting
33
+
34
+ ## Our Responsibilities
35
+
36
+ Project maintainers are responsible for clarifying the standards of acceptable
37
+ behavior and are expected to take appropriate and fair corrective action in
38
+ response to any instances of unacceptable behavior.
39
+
40
+ Project maintainers have the right and responsibility to remove, edit, or
41
+ reject comments, commits, code, wiki edits, issues, and other contributions
42
+ that are not aligned to this Code of Conduct, or to ban temporarily or
43
+ permanently any contributor for other behaviors that they deem inappropriate,
44
+ threatening, offensive, or harmful.
45
+
46
+ ## Scope
47
+
48
+ This Code of Conduct applies both within project spaces and in public spaces
49
+ when an individual is representing the project or its community. Examples of
50
+ representing a project or community include using an official project e-mail
51
+ address, posting via an official social media account, or acting as an appointed
52
+ representative at an online or offline event. Representation of a project may be
53
+ further defined and clarified by project maintainers.
54
+
55
+ ## Enforcement
56
+
57
+ Instances of abusive, harassing, or otherwise unacceptable behavior may be
58
+ reported by contacting the project team at ing.ezcurdia@gmail.com. All
59
+ complaints will be reviewed and investigated and will result in a response that
60
+ is deemed necessary and appropriate to the circumstances. The project team is
61
+ obligated to maintain confidentiality with regard to the reporter of an incident.
62
+ Further details of specific enforcement policies may be posted separately.
63
+
64
+ Project maintainers who do not follow or enforce the Code of Conduct in good
65
+ faith may face temporary or permanent repercussions as determined by other
66
+ members of the project's leadership.
67
+
68
+ ## Attribution
69
+
70
+ This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4,
71
+ available at https://www.contributor-covenant.org/version/1/4/code-of-conduct.html
72
+
73
+ [homepage]: https://www.contributor-covenant.org
74
+
75
+ For answers to common questions about this code of conduct, see
76
+ https://www.contributor-covenant.org/faq
data/Gemfile ADDED
@@ -0,0 +1,9 @@
1
+ # frozen_string_literal: true
2
+
3
+ source 'https://rubygems.org'
4
+
5
+ # Specify your gem's dependencies in annealing.gemspec
6
+ gemspec
7
+
8
+ gem 'minitest', '~> 5.0'
9
+ gem 'rake', '~> 12.0'
@@ -0,0 +1,21 @@
1
+ PATH
2
+ remote: .
3
+ specs:
4
+ annealing (0.1.0)
5
+
6
+ GEM
7
+ remote: https://rubygems.org/
8
+ specs:
9
+ minitest (5.14.1)
10
+ rake (12.3.3)
11
+
12
+ PLATFORMS
13
+ ruby
14
+
15
+ DEPENDENCIES
16
+ annealing!
17
+ minitest (~> 5.0)
18
+ rake (~> 12.0)
19
+
20
+ BUNDLED WITH
21
+ 2.1.4
data/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2020 Luis Ezcurdia
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,117 @@
1
+ # Annealing
2
+
3
+ Find the optimal solution in a complex problem through a simulated annealing implementation for enumerable objects. Where the energy of each object can be measured by a distance method between two elements or a lambda function where the total energy is calculated in the objects.
4
+
5
+ ## Installation
6
+
7
+ Add this line to your application's Gemfile:
8
+
9
+ ```ruby
10
+ gem 'annealing'
11
+ ```
12
+
13
+ And then execute:
14
+
15
+ $ bundle install
16
+
17
+ Or install it yourself as:
18
+
19
+ $ gem install annealing
20
+
21
+ ## Usage
22
+
23
+ To use this gem, you must have an object that implements a `distance` method or a lambda function where you calculate the total energy of an enumerable object.
24
+
25
+ Lets solve the traveling salesman, for that we will need an object with a distance method
26
+ to mesure the distance between two locations.
27
+
28
+ ```ruby
29
+ Location = Struct.new(:x, :y) do
30
+ def inspect
31
+ "(#{x},#{y})"
32
+ end
33
+
34
+ def distance(location)
35
+ dx = (x - location.x).abs
36
+ dy = (y - location.y).abs
37
+ Math.sqrt(dx**2 + dy**2)
38
+ end
39
+ end
40
+ ```
41
+
42
+ Now we can create an array of the locations
43
+
44
+ ```ruby
45
+ locations = [
46
+ Location.new(60, 200),
47
+ Location.new(180, 200),
48
+ Location.new(40, 120),
49
+ Location.new(100, 120),
50
+ Location.new(20, 40)
51
+ ]
52
+ ```
53
+
54
+ Now we can just pass the locations argumen.
55
+
56
+ ```ruby
57
+ puts Annealing.simulate(locations)
58
+ [(20,40), (40,120), (100,120), (60,200), (180,200)]
59
+ ```
60
+
61
+ This will run the simulation with the default parameters and it could take a while to finish.
62
+ But if you want to iterate with other parameters you can send the parameters `temperature` and `cooling_rate`.
63
+
64
+ ```ruby
65
+ simulator = Annealing::Simulator.new(temperature: 10_000, cooling_rate: 0.5)
66
+ solution = simulator.run(locations)
67
+ solution.energy
68
+ 351.901234
69
+ solution.collection
70
+ [(20,40), (40,120), (100,120), (60,200), (180,200)]
71
+ ```
72
+
73
+ You can also configure the default parameters
74
+
75
+ ```ruby
76
+ Annealing.configure do |c|
77
+ c.temperature = 10_000.0
78
+ c.cooling_rate = 0.003
79
+ end
80
+ ```
81
+
82
+ ### Custom total energy calculator
83
+
84
+ You can set a lambda function to customize the total energy in a collection by setting in the default parameters
85
+
86
+ ```ruby
87
+ Annealing.configure do |c|
88
+ c.total_energy_calculator = lambda do |enumerable|
89
+ enumerable.each_cons(2).sum { |a, b| a.distance(b) }
90
+ end
91
+ end
92
+ ```
93
+
94
+ or in the simulator as a parameter
95
+
96
+ ```ruby
97
+ calc = lambda do |enumerable|
98
+ enumerable.each_cons(2).sum { |a, b| a.distance(b) }
99
+ end
100
+ solution = simulator.run(locations, energy_calculator: calc).collection
101
+ [(20,40), (40,120), (100,120), (60,200), (180,200)]
102
+ ```
103
+
104
+ ## Development
105
+
106
+ After checking out the repo, run `bin/setup` to install dependencies. Then, run `rake test` to run the tests. You can also run `bin/console` for an interactive prompt that will allow you to experiment.
107
+
108
+ To install this gem onto your local machine, run `bundle exec rake install`. To release a new version, update the version number in `version.rb`, and then run `bundle exec rake release`, which will create a git tag for the version, push git commits and tags, and push the `.gem` file to [rubygems.org](https://rubygems.org).
109
+
110
+ ## Contributing
111
+
112
+ Bug reports and pull requests are welcome on GitHub at https://github.com/3zcurdia/annealing. This project is intended to be a safe, welcoming space for collaboration, and contributors are expected to adhere to the [code of conduct](https://github.com/3zcurdia/annealing/blob/master/CODE_OF_CONDUCT.md).
113
+
114
+
115
+ ## Code of Conduct
116
+
117
+ Everyone interacting in the Annealing project's codebases, issue trackers, chat rooms and mailing lists is expected to follow the [code of conduct](https://github.com/3zcurdia/annealing/blob/master/CODE_OF_CONDUCT.md).
@@ -0,0 +1,12 @@
1
+ # frozen_string_literal: true
2
+
3
+ require 'bundler/gem_tasks'
4
+ require 'rake/testtask'
5
+
6
+ Rake::TestTask.new(:test) do |t|
7
+ t.libs << 'test'
8
+ t.libs << 'lib'
9
+ t.test_files = FileList['test/**/*_test.rb']
10
+ end
11
+
12
+ task default: :test
@@ -0,0 +1,31 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative 'lib/annealing/version'
4
+
5
+ Gem::Specification.new do |spec|
6
+ spec.name = 'annealing'
7
+ spec.version = Annealing::VERSION
8
+ spec.authors = ['Luis Ezcurdia Razo']
9
+ spec.email = ['ing.ezcurdia@gmail.com']
10
+ spec.license = 'MIT'
11
+
12
+ spec.summary = 'Simulated Annealing algoritm'
13
+ spec.description = 'Simulated Annealing algoritm implementation.'
14
+ spec.homepage = 'https://github.com/3zcurdia/annealing'
15
+ spec.required_ruby_version = Gem::Requirement.new('>= 2.3.0')
16
+
17
+ # spec.metadata["allowed_push_host"] = "TODO: Set to 'http://mygemserver.com'"
18
+
19
+ spec.metadata['homepage_uri'] = spec.homepage
20
+ spec.metadata['source_code_uri'] = 'https://github.com/3zcurdia/annealing'
21
+ # spec.metadata["changelog_uri"] = "TODO: Put your gem's CHANGELOG.md URL here."
22
+
23
+ # Specify which files should be added to the gem when it is released.
24
+ # The `git ls-files -z` loads the files in the RubyGem that have been added into git.
25
+ spec.files = Dir.chdir(File.expand_path(__dir__)) do
26
+ `git ls-files -z`.split("\x0").reject { |f| f.match(%r{^(test|spec|features)/}) }
27
+ end
28
+ spec.bindir = 'exe'
29
+ spec.executables = spec.files.grep(%r{^exe/}) { |f| File.basename(f) }
30
+ spec.require_paths = ['lib']
31
+ end
@@ -0,0 +1,15 @@
1
+ #!/usr/bin/env ruby
2
+ # frozen_string_literal: true
3
+
4
+ require 'bundler/setup'
5
+ require 'annealing'
6
+
7
+ # You can add fixtures and/or initialization code here to make experimenting
8
+ # with your gem easier. You can also use a different console, if you like.
9
+
10
+ # (If you use this, don't forget to add pry to your Gemfile!)
11
+ # require "pry"
12
+ # Pry.start
13
+
14
+ require 'irb'
15
+ IRB.start(__FILE__)
@@ -0,0 +1,8 @@
1
+ #!/usr/bin/env bash
2
+ set -euo pipefail
3
+ IFS=$'\n\t'
4
+ set -vx
5
+
6
+ bundle install
7
+
8
+ # Do any other automated setup that you need to do here
@@ -0,0 +1,36 @@
1
+ # frozen_string_literal: true
2
+
3
+ require 'logger'
4
+ require 'annealing/version'
5
+ require 'annealing/configuration'
6
+ require 'annealing/pool'
7
+ require 'annealing/simulator'
8
+
9
+ # Simulated Annealing algoritm
10
+ # https://en.wikipedia.org/wiki/Simulated_annealing
11
+ module Annealing
12
+ # Default error class
13
+ class Error < StandardError; end
14
+ class << self
15
+ attr_writer :configuration
16
+ end
17
+
18
+ def self.configuration
19
+ @configuration ||= Configuration.new
20
+ end
21
+
22
+ def self.configure
23
+ yield(configuration)
24
+ end
25
+
26
+ def self.simulate(collection)
27
+ return [] if collection.empty?
28
+
29
+ simulator = Simulator.new
30
+ simulator.run(collection).collection
31
+ end
32
+
33
+ def self.logger
34
+ configuration.logger
35
+ end
36
+ end
@@ -0,0 +1,19 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Annealing
4
+ # It enables the gem configuration
5
+ class Configuration
6
+ attr_accessor :temperature, :cooling_rate, :total_energy_calculator, :logger
7
+
8
+ def initialize
9
+ @temperature = 10_000.0
10
+ @cooling_rate = 0.0003
11
+ @total_energy_calculator = lambda do |enumerable|
12
+ enumerable.each_cons(2).sum do |value_a, value_b|
13
+ value_a.distance(value_b)
14
+ end
15
+ end
16
+ @logger = Logger.new(STDOUT)
17
+ end
18
+ end
19
+ end
@@ -0,0 +1,55 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Annealing
4
+ # It manages the total energy of a given collection
5
+ class Pool
6
+ attr_reader :collection
7
+
8
+ def initialize(collection, energy_calculator: nil)
9
+ @collection = collection.dup
10
+ @energy_calculator = energy_calculator || Annealing.configuration.total_energy_calculator
11
+ end
12
+
13
+ def energy
14
+ @energy ||= energy_calculator.call(collection)
15
+ end
16
+
17
+ def better_than?(pool)
18
+ energy < pool.energy
19
+ end
20
+
21
+ def solution_at(temperature)
22
+ move = self.next
23
+ energy_delta = energy - move.energy
24
+ if energy_delta.positive? || (Math::E**(energy_delta / temperature)) > rand
25
+ move
26
+ else
27
+ self
28
+ end
29
+ end
30
+
31
+ def to_s
32
+ format('%<energy>.4f:%<value>s', energy: energy, value: collection)
33
+ end
34
+
35
+ private
36
+
37
+ attr_reader :energy_calculator
38
+
39
+ def next
40
+ Pool.new(swap_collection, energy_calculator: energy_calculator)
41
+ end
42
+
43
+ def swap_collection
44
+ swapped = collection.dup
45
+ idx_a = rand(size)
46
+ idx_b = rand(size)
47
+ swapped[idx_b], swapped[idx_a] = swapped[idx_a], swapped[idx_b]
48
+ swapped
49
+ end
50
+
51
+ def size
52
+ collection.size
53
+ end
54
+ end
55
+ end
@@ -0,0 +1,38 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Annealing
4
+ # It runs simulated annealing
5
+ class Simulator
6
+ attr_reader :temperature, :cooling_rate
7
+
8
+ def initialize(temperature: nil, cooling_rate: nil)
9
+ @temperature = temperature || Annealing.configuration.temperature
10
+ @cooling_rate = cooling_rate || Annealing.configuration.cooling_rate
11
+
12
+ raise 'Invalid initial temperature' if @temperature.negative?
13
+
14
+ normalize_cooling_rate
15
+ end
16
+
17
+ def run(collection, energy_calculator: nil)
18
+ best = current = Pool.new(collection.shuffle, energy_calculator: energy_calculator)
19
+ Annealing.logger.debug(" Original: #{current}")
20
+ cool_down do |temp|
21
+ current = current.solution_at(temp)
22
+ best = current if current.better_than?(best)
23
+ end
24
+ Annealing.logger.debug("Optimized: #{best}")
25
+ best
26
+ end
27
+
28
+ private
29
+
30
+ def cool_down
31
+ (temperature..0).step(cooling_rate).each { |temp| yield temp }
32
+ end
33
+
34
+ def normalize_cooling_rate
35
+ @cooling_rate = -1.0 * cooling_rate if cooling_rate.positive?
36
+ end
37
+ end
38
+ end
@@ -0,0 +1,5 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Annealing
4
+ VERSION = '0.1.0'
5
+ end
metadata ADDED
@@ -0,0 +1,63 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: annealing
3
+ version: !ruby/object:Gem::Version
4
+ version: 0.1.0
5
+ platform: ruby
6
+ authors:
7
+ - Luis Ezcurdia Razo
8
+ autorequire:
9
+ bindir: exe
10
+ cert_chain: []
11
+ date: 2020-06-17 00:00:00.000000000 Z
12
+ dependencies: []
13
+ description: Simulated Annealing algoritm implementation.
14
+ email:
15
+ - ing.ezcurdia@gmail.com
16
+ executables: []
17
+ extensions: []
18
+ extra_rdoc_files: []
19
+ files:
20
+ - ".gitignore"
21
+ - ".rubocop.yml"
22
+ - ".rubocop_todo.yml"
23
+ - ".travis.yml"
24
+ - CODE_OF_CONDUCT.md
25
+ - Gemfile
26
+ - Gemfile.lock
27
+ - LICENSE
28
+ - README.md
29
+ - Rakefile
30
+ - annealing.gemspec
31
+ - bin/console
32
+ - bin/setup
33
+ - lib/annealing.rb
34
+ - lib/annealing/configuration.rb
35
+ - lib/annealing/pool.rb
36
+ - lib/annealing/simulator.rb
37
+ - lib/annealing/version.rb
38
+ homepage: https://github.com/3zcurdia/annealing
39
+ licenses:
40
+ - MIT
41
+ metadata:
42
+ homepage_uri: https://github.com/3zcurdia/annealing
43
+ source_code_uri: https://github.com/3zcurdia/annealing
44
+ post_install_message:
45
+ rdoc_options: []
46
+ require_paths:
47
+ - lib
48
+ required_ruby_version: !ruby/object:Gem::Requirement
49
+ requirements:
50
+ - - ">="
51
+ - !ruby/object:Gem::Version
52
+ version: 2.3.0
53
+ required_rubygems_version: !ruby/object:Gem::Requirement
54
+ requirements:
55
+ - - ">="
56
+ - !ruby/object:Gem::Version
57
+ version: '0'
58
+ requirements: []
59
+ rubygems_version: 3.1.3
60
+ signing_key:
61
+ specification_version: 4
62
+ summary: Simulated Annealing algoritm
63
+ test_files: []