simple-annealing 0.1.0__tar.gz
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.
- simple_annealing-0.1.0/.github/workflows/ci.yml +26 -0
- simple_annealing-0.1.0/.gitignore +218 -0
- simple_annealing-0.1.0/CHANGELOG.md +22 -0
- simple_annealing-0.1.0/LICENSE +21 -0
- simple_annealing-0.1.0/PKG-INFO +407 -0
- simple_annealing-0.1.0/README.md +358 -0
- simple_annealing-0.1.0/examples/server.py +110 -0
- simple_annealing-0.1.0/examples/tsp.py +68 -0
- simple_annealing-0.1.0/pyproject.toml +61 -0
- simple_annealing-0.1.0/src/simple_annealing/__init__.py +34 -0
- simple_annealing-0.1.0/src/simple_annealing/calibrate.py +84 -0
- simple_annealing-0.1.0/src/simple_annealing/core.py +247 -0
- simple_annealing-0.1.0/src/simple_annealing/py.typed +0 -0
- simple_annealing-0.1.0/src/simple_annealing/schedules.py +84 -0
- simple_annealing-0.1.0/tests/conftest.py +24 -0
- simple_annealing-0.1.0/tests/test_anneal.py +278 -0
- simple_annealing-0.1.0/tests/test_concurrency.py +42 -0
- simple_annealing-0.1.0/tests/test_schedules_and_calibration.py +115 -0
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
name: CI
|
|
2
|
+
|
|
3
|
+
on:
|
|
4
|
+
push:
|
|
5
|
+
branches: [main]
|
|
6
|
+
pull_request:
|
|
7
|
+
|
|
8
|
+
jobs:
|
|
9
|
+
test:
|
|
10
|
+
runs-on: ubuntu-latest
|
|
11
|
+
strategy:
|
|
12
|
+
fail-fast: false
|
|
13
|
+
matrix:
|
|
14
|
+
# The floor is 3.10 (PEP 604 unions in annotations at runtime); the
|
|
15
|
+
# ceiling is whatever's current — there's nothing version-specific here,
|
|
16
|
+
# so a break on a new release is a break worth seeing.
|
|
17
|
+
python-version: ["3.10", "3.11", "3.12", "3.13"]
|
|
18
|
+
steps:
|
|
19
|
+
- uses: actions/checkout@v4
|
|
20
|
+
- uses: actions/setup-python@v5
|
|
21
|
+
with:
|
|
22
|
+
python-version: ${{ matrix.python-version }}
|
|
23
|
+
- run: pip install -e ".[dev]"
|
|
24
|
+
- run: pytest -q
|
|
25
|
+
- run: ruff check .
|
|
26
|
+
- run: mypy --strict src/simple_annealing
|
|
@@ -0,0 +1,218 @@
|
|
|
1
|
+
# Byte-compiled / optimized / DLL files
|
|
2
|
+
__pycache__/
|
|
3
|
+
*.py[codz]
|
|
4
|
+
*$py.class
|
|
5
|
+
|
|
6
|
+
# C extensions
|
|
7
|
+
*.so
|
|
8
|
+
|
|
9
|
+
# Distribution / packaging
|
|
10
|
+
.Python
|
|
11
|
+
build/
|
|
12
|
+
develop-eggs/
|
|
13
|
+
dist/
|
|
14
|
+
downloads/
|
|
15
|
+
eggs/
|
|
16
|
+
.eggs/
|
|
17
|
+
lib/
|
|
18
|
+
lib64/
|
|
19
|
+
parts/
|
|
20
|
+
sdist/
|
|
21
|
+
var/
|
|
22
|
+
wheels/
|
|
23
|
+
share/python-wheels/
|
|
24
|
+
*.egg-info/
|
|
25
|
+
.installed.cfg
|
|
26
|
+
*.egg
|
|
27
|
+
MANIFEST
|
|
28
|
+
|
|
29
|
+
# PyInstaller
|
|
30
|
+
# Usually these files are written by a python script from a template
|
|
31
|
+
# before PyInstaller builds the exe, so as to inject date/other infos into it.
|
|
32
|
+
*.manifest
|
|
33
|
+
*.spec
|
|
34
|
+
|
|
35
|
+
# Installer logs
|
|
36
|
+
pip-log.txt
|
|
37
|
+
pip-delete-this-directory.txt
|
|
38
|
+
|
|
39
|
+
# Unit test / coverage reports
|
|
40
|
+
htmlcov/
|
|
41
|
+
.tox/
|
|
42
|
+
.nox/
|
|
43
|
+
.coverage
|
|
44
|
+
.coverage.*
|
|
45
|
+
.cache
|
|
46
|
+
nosetests.xml
|
|
47
|
+
coverage.xml
|
|
48
|
+
*.cover
|
|
49
|
+
*.py.cover
|
|
50
|
+
.hypothesis/
|
|
51
|
+
.pytest_cache/
|
|
52
|
+
cover/
|
|
53
|
+
|
|
54
|
+
# Translations
|
|
55
|
+
*.mo
|
|
56
|
+
*.pot
|
|
57
|
+
|
|
58
|
+
# Django stuff:
|
|
59
|
+
*.log
|
|
60
|
+
local_settings.py
|
|
61
|
+
db.sqlite3
|
|
62
|
+
db.sqlite3-journal
|
|
63
|
+
|
|
64
|
+
# Flask stuff:
|
|
65
|
+
instance/
|
|
66
|
+
.webassets-cache
|
|
67
|
+
|
|
68
|
+
# Scrapy stuff:
|
|
69
|
+
.scrapy
|
|
70
|
+
|
|
71
|
+
# Sphinx documentation
|
|
72
|
+
docs/_build/
|
|
73
|
+
|
|
74
|
+
# PyBuilder
|
|
75
|
+
.pybuilder/
|
|
76
|
+
target/
|
|
77
|
+
|
|
78
|
+
# Jupyter Notebook
|
|
79
|
+
.ipynb_checkpoints
|
|
80
|
+
|
|
81
|
+
# IPython
|
|
82
|
+
profile_default/
|
|
83
|
+
ipython_config.py
|
|
84
|
+
|
|
85
|
+
# pyenv
|
|
86
|
+
# For a library or package, you might want to ignore these files since the code is
|
|
87
|
+
# intended to run in multiple environments; otherwise, check them in:
|
|
88
|
+
# .python-version
|
|
89
|
+
|
|
90
|
+
# pipenv
|
|
91
|
+
# According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
|
|
92
|
+
# However, in case of collaboration, if having platform-specific dependencies or dependencies
|
|
93
|
+
# having no cross-platform support, pipenv may install dependencies that don't work, or not
|
|
94
|
+
# install all needed dependencies.
|
|
95
|
+
# Pipfile.lock
|
|
96
|
+
|
|
97
|
+
# UV
|
|
98
|
+
# Similar to Pipfile.lock, it is generally recommended to include uv.lock in version control.
|
|
99
|
+
# This is especially recommended for binary packages to ensure reproducibility, and is more
|
|
100
|
+
# commonly ignored for libraries.
|
|
101
|
+
# uv.lock
|
|
102
|
+
|
|
103
|
+
# poetry
|
|
104
|
+
# Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control.
|
|
105
|
+
# This is especially recommended for binary packages to ensure reproducibility, and is more
|
|
106
|
+
# commonly ignored for libraries.
|
|
107
|
+
# https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control
|
|
108
|
+
# poetry.lock
|
|
109
|
+
# poetry.toml
|
|
110
|
+
|
|
111
|
+
# pdm
|
|
112
|
+
# Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control.
|
|
113
|
+
# pdm recommends including project-wide configuration in pdm.toml, but excluding .pdm-python.
|
|
114
|
+
# https://pdm-project.org/en/latest/usage/project/#working-with-version-control
|
|
115
|
+
# pdm.lock
|
|
116
|
+
# pdm.toml
|
|
117
|
+
.pdm-python
|
|
118
|
+
.pdm-build/
|
|
119
|
+
|
|
120
|
+
# pixi
|
|
121
|
+
# Similar to Pipfile.lock, it is generally recommended to include pixi.lock in version control.
|
|
122
|
+
# pixi.lock
|
|
123
|
+
# Pixi creates a virtual environment in the .pixi directory, just like venv module creates one
|
|
124
|
+
# in the .venv directory. It is recommended not to include this directory in version control.
|
|
125
|
+
.pixi
|
|
126
|
+
|
|
127
|
+
# PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm
|
|
128
|
+
__pypackages__/
|
|
129
|
+
|
|
130
|
+
# Celery stuff
|
|
131
|
+
celerybeat-schedule
|
|
132
|
+
celerybeat.pid
|
|
133
|
+
|
|
134
|
+
# Redis
|
|
135
|
+
*.rdb
|
|
136
|
+
*.aof
|
|
137
|
+
*.pid
|
|
138
|
+
|
|
139
|
+
# RabbitMQ
|
|
140
|
+
mnesia/
|
|
141
|
+
rabbitmq/
|
|
142
|
+
rabbitmq-data/
|
|
143
|
+
|
|
144
|
+
# ActiveMQ
|
|
145
|
+
activemq-data/
|
|
146
|
+
|
|
147
|
+
# SageMath parsed files
|
|
148
|
+
*.sage.py
|
|
149
|
+
|
|
150
|
+
# Environments
|
|
151
|
+
.env
|
|
152
|
+
.envrc
|
|
153
|
+
.venv
|
|
154
|
+
env/
|
|
155
|
+
venv/
|
|
156
|
+
ENV/
|
|
157
|
+
env.bak/
|
|
158
|
+
venv.bak/
|
|
159
|
+
|
|
160
|
+
# Spyder project settings
|
|
161
|
+
.spyderproject
|
|
162
|
+
.spyproject
|
|
163
|
+
|
|
164
|
+
# Rope project settings
|
|
165
|
+
.ropeproject
|
|
166
|
+
|
|
167
|
+
# mkdocs documentation
|
|
168
|
+
/site
|
|
169
|
+
|
|
170
|
+
# mypy
|
|
171
|
+
.mypy_cache/
|
|
172
|
+
.dmypy.json
|
|
173
|
+
dmypy.json
|
|
174
|
+
|
|
175
|
+
# Pyre type checker
|
|
176
|
+
.pyre/
|
|
177
|
+
|
|
178
|
+
# pytype static type analyzer
|
|
179
|
+
.pytype/
|
|
180
|
+
|
|
181
|
+
# Cython debug symbols
|
|
182
|
+
cython_debug/
|
|
183
|
+
|
|
184
|
+
# PyCharm
|
|
185
|
+
# JetBrains specific template is maintained in a separate JetBrains.gitignore that can
|
|
186
|
+
# be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore
|
|
187
|
+
# and can be added to the global gitignore or merged into this file. For a more nuclear
|
|
188
|
+
# option (not recommended) you can uncomment the following to ignore the entire idea folder.
|
|
189
|
+
# .idea/
|
|
190
|
+
|
|
191
|
+
# Abstra
|
|
192
|
+
# Abstra is an AI-powered process automation framework.
|
|
193
|
+
# Ignore directories containing user credentials, local state, and settings.
|
|
194
|
+
# Learn more at https://abstra.io/docs
|
|
195
|
+
.abstra/
|
|
196
|
+
|
|
197
|
+
# Visual Studio Code
|
|
198
|
+
# Visual Studio Code specific template is maintained in a separate VisualStudioCode.gitignore
|
|
199
|
+
# that can be found at https://github.com/github/gitignore/blob/main/Global/VisualStudioCode.gitignore
|
|
200
|
+
# and can be added to the global gitignore or merged into this file. However, if you prefer,
|
|
201
|
+
# you could uncomment the following to ignore the entire vscode folder
|
|
202
|
+
# .vscode/
|
|
203
|
+
# Temporary file for partial code execution
|
|
204
|
+
tempCodeRunnerFile.py
|
|
205
|
+
|
|
206
|
+
# Ruff stuff:
|
|
207
|
+
.ruff_cache/
|
|
208
|
+
|
|
209
|
+
# PyPI configuration file
|
|
210
|
+
.pypirc
|
|
211
|
+
|
|
212
|
+
# Marimo
|
|
213
|
+
marimo/_static/
|
|
214
|
+
marimo/_lsp/
|
|
215
|
+
__marimo__/
|
|
216
|
+
|
|
217
|
+
# Streamlit
|
|
218
|
+
.streamlit/secrets.toml
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
# Changelog
|
|
2
|
+
|
|
3
|
+
## 0.1.0 — unreleased
|
|
4
|
+
|
|
5
|
+
First release.
|
|
6
|
+
|
|
7
|
+
- `anneal()` — simulated annealing over any state type, with `energy` and `move`
|
|
8
|
+
as plain functions rather than an inherited base class.
|
|
9
|
+
- Private seeded RNG. The process-global `random` module is never read or
|
|
10
|
+
written, so concurrent runs stay independent and reproducible.
|
|
11
|
+
- No signal handlers and no stream output, so a run is safe in a worker thread
|
|
12
|
+
and silent unless you pass `on_progress`.
|
|
13
|
+
- Stopping conditions: `max_steps`, `time_budget`, `target_energy`,
|
|
14
|
+
`stall_steps`. At least one budget is required — there is no default.
|
|
15
|
+
- `move()` may return `(state, delta)` to skip the energy call. The winner's
|
|
16
|
+
energy is recomputed at the end and any disagreement surfaces as
|
|
17
|
+
`result.delta_drift`.
|
|
18
|
+
- `copy=` for in-place moves, invoked once per improvement rather than per step.
|
|
19
|
+
- Schedules: `geometric`, `linear`, `constant`, or any
|
|
20
|
+
`Callable[[float], float]`.
|
|
21
|
+
- `calibrate()` sizes `t_max`/`t_min` from a sample of the actual landscape;
|
|
22
|
+
used automatically when no `schedule` is given.
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 k3
|
|
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,407 @@
|
|
|
1
|
+
Metadata-Version: 2.5
|
|
2
|
+
Name: simple-annealing
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Simulated annealing that is safe to run inside a server: deterministic, deadline-bounded, thread-safe, silent.
|
|
5
|
+
Project-URL: Homepage, https://github.com/buoren/simple-annealing
|
|
6
|
+
Project-URL: Issues, https://github.com/buoren/simple-annealing/issues
|
|
7
|
+
Author-email: k3 <buoren@vaguely.nl>
|
|
8
|
+
License: MIT License
|
|
9
|
+
|
|
10
|
+
Copyright (c) 2026 k3
|
|
11
|
+
|
|
12
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
13
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
14
|
+
in the Software without restriction, including without limitation the rights
|
|
15
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
16
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
17
|
+
furnished to do so, subject to the following conditions:
|
|
18
|
+
|
|
19
|
+
The above copyright notice and this permission notice shall be included in all
|
|
20
|
+
copies or substantial portions of the Software.
|
|
21
|
+
|
|
22
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
23
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
24
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
25
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
26
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
27
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
28
|
+
SOFTWARE.
|
|
29
|
+
License-File: LICENSE
|
|
30
|
+
Keywords: combinatorial-optimization,metaheuristic,optimization,scheduling,simulated-annealing
|
|
31
|
+
Classifier: Development Status :: 4 - Beta
|
|
32
|
+
Classifier: Intended Audience :: Developers
|
|
33
|
+
Classifier: Intended Audience :: Science/Research
|
|
34
|
+
Classifier: License :: OSI Approved :: MIT License
|
|
35
|
+
Classifier: Operating System :: OS Independent
|
|
36
|
+
Classifier: Programming Language :: Python :: 3
|
|
37
|
+
Classifier: Programming Language :: Python :: 3.10
|
|
38
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
39
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
40
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
41
|
+
Classifier: Topic :: Scientific/Engineering :: Mathematics
|
|
42
|
+
Classifier: Typing :: Typed
|
|
43
|
+
Requires-Python: >=3.10
|
|
44
|
+
Provides-Extra: dev
|
|
45
|
+
Requires-Dist: mypy>=1.8; extra == 'dev'
|
|
46
|
+
Requires-Dist: pytest>=8.0; extra == 'dev'
|
|
47
|
+
Requires-Dist: ruff<0.15,>=0.14; extra == 'dev'
|
|
48
|
+
Description-Content-Type: text/markdown
|
|
49
|
+
|
|
50
|
+
# simple-annealing
|
|
51
|
+
|
|
52
|
+
Simulated annealing that is safe to run **inside a server**.
|
|
53
|
+
|
|
54
|
+
Deterministic when you ask for it, bounded by a deadline when you need one, silent
|
|
55
|
+
by default, and free of global state — so several optimisations can share a
|
|
56
|
+
process without interfering with each other or with you.
|
|
57
|
+
|
|
58
|
+
Pure Python, no dependencies, one function.
|
|
59
|
+
|
|
60
|
+
```sh
|
|
61
|
+
pip install simple-annealing
|
|
62
|
+
```
|
|
63
|
+
|
|
64
|
+
---
|
|
65
|
+
|
|
66
|
+
## What it's for
|
|
67
|
+
|
|
68
|
+
Simulated annealing finds a good arrangement of things when there are too many
|
|
69
|
+
arrangements to try: routes, rosters, seating plans, timetables, packings. You
|
|
70
|
+
give it a way to score an arrangement and a way to nudge one into a neighbouring
|
|
71
|
+
arrangement, and it wanders the space — accepting the occasional worse
|
|
72
|
+
arrangement early on so it doesn't get stuck in the first decent one it finds, and
|
|
73
|
+
growing fussier as it goes.
|
|
74
|
+
|
|
75
|
+
**Reach for it when** the state is discrete and combinatorial, "good enough,
|
|
76
|
+
quickly" beats "provably optimal, eventually", and you can score an arrangement
|
|
77
|
+
cheaply.
|
|
78
|
+
|
|
79
|
+
**Don't** when you're optimising a smooth function of real numbers (use SciPy),
|
|
80
|
+
when your problem is small enough to solve exactly (use a real solver), or when
|
|
81
|
+
you're tuning hyperparameters (use Optuna). More on all three [below](#what-to-use-instead).
|
|
82
|
+
|
|
83
|
+
The algorithm itself is short — nobody needs a library for the loop. What's worth
|
|
84
|
+
packaging is the handful of decisions that go wrong when you run one as part of a
|
|
85
|
+
**live system** rather than in a script. That's what this is.
|
|
86
|
+
|
|
87
|
+
---
|
|
88
|
+
|
|
89
|
+
## How to use it
|
|
90
|
+
|
|
91
|
+
Two functions and a budget:
|
|
92
|
+
|
|
93
|
+
```python
|
|
94
|
+
from simple_annealing import anneal
|
|
95
|
+
|
|
96
|
+
def energy(route): # lower is better
|
|
97
|
+
return sum(distance(a, b) for a, b in zip(route, route[1:]))
|
|
98
|
+
|
|
99
|
+
def move(route, rng): # one small random change
|
|
100
|
+
i, j = rng.randrange(len(route)), rng.randrange(len(route))
|
|
101
|
+
nudged = list(route)
|
|
102
|
+
nudged[i], nudged[j] = nudged[j], nudged[i]
|
|
103
|
+
return tuple(nudged)
|
|
104
|
+
|
|
105
|
+
result = anneal(
|
|
106
|
+
initial_route,
|
|
107
|
+
energy=energy,
|
|
108
|
+
move=move,
|
|
109
|
+
seed=1234,
|
|
110
|
+
max_steps=50_000,
|
|
111
|
+
)
|
|
112
|
+
|
|
113
|
+
result.state # the best arrangement found — never merely the last one tried
|
|
114
|
+
result.energy # its score, recomputed from scratch rather than accumulated
|
|
115
|
+
result.improvement # how much better than where you started
|
|
116
|
+
result.stopped_by # "max_steps" | "time_budget" | "stall" | "target_energy"
|
|
117
|
+
```
|
|
118
|
+
|
|
119
|
+
That's the whole surface. The rest of this section is the detail behind those five
|
|
120
|
+
arguments.
|
|
121
|
+
|
|
122
|
+
### `energy(state) -> float`
|
|
123
|
+
|
|
124
|
+
Your objective. Lower is better; the units are yours. It's called once per step
|
|
125
|
+
unless your `move` returns deltas (see below), so if it's expensive, that's the
|
|
126
|
+
first thing to look at.
|
|
127
|
+
|
|
128
|
+
### `move(state, rng) -> state`
|
|
129
|
+
|
|
130
|
+
Returns a *neighbouring* arrangement. Two rules:
|
|
131
|
+
|
|
132
|
+
1. **Draw all randomness from the `rng` you're handed**, never from the global
|
|
133
|
+
`random` module — otherwise the run stops being reproducible.
|
|
134
|
+
2. **Return a new state.** Nothing is copied if you do, which is what keeps the
|
|
135
|
+
loop cheap. If you'd rather mutate in place, return the same object and pass
|
|
136
|
+
`copy=` — that gets called once per improvement, not once per step.
|
|
137
|
+
|
|
138
|
+
### Budgets
|
|
139
|
+
|
|
140
|
+
At least one of `max_steps` or `time_budget` is required. There's no default,
|
|
141
|
+
because a search with no stopping condition is a hang, and a silent default step
|
|
142
|
+
count is a hang waiting for a slow objective. See
|
|
143
|
+
[choosing a budget](#choosing-a-budget) for which to pick.
|
|
144
|
+
|
|
145
|
+
You can also pass `target_energy` (stop once the answer is good enough — for
|
|
146
|
+
problems with a known floor, like "zero conflicts", this can end a run in
|
|
147
|
+
milliseconds) and `stall_steps` (give up after N steps with no improvement).
|
|
148
|
+
|
|
149
|
+
### Reporting
|
|
150
|
+
|
|
151
|
+
The library never writes to a stream. Pass `on_progress` to receive an immutable
|
|
152
|
+
`Progress` record every `progress_every` steps and route it wherever you like:
|
|
153
|
+
|
|
154
|
+
```python
|
|
155
|
+
anneal(..., on_progress=lambda p: log.info("step %d best %.2f", p.step, p.best_energy),
|
|
156
|
+
progress_every=10_000)
|
|
157
|
+
```
|
|
158
|
+
|
|
159
|
+
### Bringing a class
|
|
160
|
+
|
|
161
|
+
There's no base class to inherit, but bound methods are functions, so modelling
|
|
162
|
+
the problem as a class works with no support from the library:
|
|
163
|
+
|
|
164
|
+
```python
|
|
165
|
+
class TourProblem:
|
|
166
|
+
def __init__(self, cities):
|
|
167
|
+
self.cities = cities # shared by both methods
|
|
168
|
+
|
|
169
|
+
def energy(self, route): ...
|
|
170
|
+
def move(self, route, rng): ...
|
|
171
|
+
|
|
172
|
+
problem = TourProblem(cities)
|
|
173
|
+
result = anneal(start, energy=problem.energy, move=problem.move, seed=1, max_steps=50_000)
|
|
174
|
+
```
|
|
175
|
+
|
|
176
|
+
You keep the class and the shared data; you just don't inherit a constructor and a
|
|
177
|
+
state contract. See [why it's this way round](#8-functions-not-inheritance--but-classes-still-work).
|
|
178
|
+
|
|
179
|
+
---
|
|
180
|
+
|
|
181
|
+
## Writing a good `move()`
|
|
182
|
+
|
|
183
|
+
This matters more than any parameter here. A tuned schedule with a poor move
|
|
184
|
+
function loses to a default schedule with a good one, every time.
|
|
185
|
+
|
|
186
|
+
**Small.** A move should reach a *neighbour*, not a stranger. If a move changes
|
|
187
|
+
half the state, its energy is uncorrelated with the current one and you're doing
|
|
188
|
+
random sampling with extra steps.
|
|
189
|
+
|
|
190
|
+
**Reachable.** Every arrangement you'd accept as an answer must be reachable from
|
|
191
|
+
the start by some chain of moves. If your moves only ever swap adjacent items,
|
|
192
|
+
whole regions of the space are unreachable and the search can't find what's in
|
|
193
|
+
them.
|
|
194
|
+
|
|
195
|
+
**Roughly reversible.** If a move can be undone by another equally likely move, the
|
|
196
|
+
maths behind the acceptance rule holds. Strongly one-way moves bias the walk.
|
|
197
|
+
|
|
198
|
+
**Structure-aware beats generic.** The classic illustration is the travelling
|
|
199
|
+
salesman: swapping two cities is a legal move, but reversing a *segment* (2-opt)
|
|
200
|
+
is dramatically better, because a long tour's real problem is crossings and
|
|
201
|
+
reversing a segment is exactly what uncrosses them. Both examples in `examples/`
|
|
202
|
+
use 2-opt for that reason.
|
|
203
|
+
|
|
204
|
+
**Cheap.** It runs hundreds of thousands of times.
|
|
205
|
+
|
|
206
|
+
If a run disappoints, suspect the move function before the temperature. A quick
|
|
207
|
+
diagnostic: run with `schedule=constant(0)`, which accepts only improvements. If
|
|
208
|
+
that hill-climb gets nearly as far as annealing did, your moves aren't opening up
|
|
209
|
+
the space and no schedule will fix it.
|
|
210
|
+
|
|
211
|
+
---
|
|
212
|
+
|
|
213
|
+
## Choosing a budget
|
|
214
|
+
|
|
215
|
+
The one real trade-off in the library, stated plainly.
|
|
216
|
+
|
|
217
|
+
| | `max_steps` | `time_budget` |
|
|
218
|
+
|---|---|---|
|
|
219
|
+
| Bounds | work | latency |
|
|
220
|
+
| Same seed, same answer? | **Yes**, on any machine, under any load | No |
|
|
221
|
+
| Use when | you need reproducibility, or you're testing | you have a deadline to hit |
|
|
222
|
+
|
|
223
|
+
Both can be set: the run stops at whichever comes first, cooling is driven by
|
|
224
|
+
whichever is running out faster — so a run cut short by the clock still finishes
|
|
225
|
+
cold rather than mid-wander — and `result.stopped_by` tells you which one fired.
|
|
226
|
+
|
|
227
|
+
That last field is worth logging. A deployment that has quietly got slower shows
|
|
228
|
+
up as a shift from `max_steps` to `time_budget` in your metrics, rather than as
|
|
229
|
+
silence.
|
|
230
|
+
|
|
231
|
+
The difference is real and easy to see for yourself. From `examples/server.py`, 20
|
|
232
|
+
concurrent requests with the same seed:
|
|
233
|
+
|
|
234
|
+
```
|
|
235
|
+
step-bounded distinct routes: 1 stopped_by: max_steps
|
|
236
|
+
deadline-bounded distinct routes: 19 stopped_by: time_budget
|
|
237
|
+
```
|
|
238
|
+
|
|
239
|
+
Nothing is wrong in the second row: twenty runs contending for the same cores each
|
|
240
|
+
fit a different number of steps into the deadline, so each explores a different
|
|
241
|
+
amount. A wall-clock bound buys promptness with exactly that reproducibility.
|
|
242
|
+
|
|
243
|
+
---
|
|
244
|
+
|
|
245
|
+
## Why this one?
|
|
246
|
+
|
|
247
|
+
### 1. It can run in a worker thread
|
|
248
|
+
|
|
249
|
+
Web frameworks serve synchronous handlers from a threadpool. An optimiser that
|
|
250
|
+
registers a `SIGINT` handler in its constructor cannot be constructed there at all
|
|
251
|
+
— `signal.signal` raises `ValueError: signal only works in main thread of the main
|
|
252
|
+
interpreter` — leaving you to run a CPU-bound loop on the event loop and block
|
|
253
|
+
every other request.
|
|
254
|
+
|
|
255
|
+
This library installs no signal handlers and touches no interpreter-global state.
|
|
256
|
+
A test asserts `SIGINT`'s handler is untouched; another runs eight optimisations
|
|
257
|
+
concurrently across a threadpool.
|
|
258
|
+
|
|
259
|
+
### 2. Determinism that survives concurrency
|
|
260
|
+
|
|
261
|
+
The usual way to get a reproducible run is `random.seed(n)` — process-global. Two
|
|
262
|
+
requests annealing at once then interleave draws from the same generator, so
|
|
263
|
+
neither is reproducible, and seeding stamps on every other consumer of `random` in
|
|
264
|
+
the process.
|
|
265
|
+
|
|
266
|
+
Here, `seed=` creates a private `random.Random`. Same seed and same step budget
|
|
267
|
+
give an identical answer whether the run is alone or one of twenty; the global
|
|
268
|
+
generator is provably untouched.
|
|
269
|
+
|
|
270
|
+
This matters beyond testing. People stop trusting a button that answers
|
|
271
|
+
differently each time they press it, even when every answer is good.
|
|
272
|
+
|
|
273
|
+
### 3. Deadlines, not just step counts
|
|
274
|
+
|
|
275
|
+
See [choosing a budget](#choosing-a-budget). A run with no stopping condition at
|
|
276
|
+
all raises rather than defaulting.
|
|
277
|
+
|
|
278
|
+
### 4. It never prints
|
|
279
|
+
|
|
280
|
+
Nothing goes to stdout or stderr. Progress goes to a callback, or nowhere.
|
|
281
|
+
Asserted by a test.
|
|
282
|
+
|
|
283
|
+
### 5. Copies scale with improvements, not with steps
|
|
284
|
+
|
|
285
|
+
The conventional design mutates state in place and copies it constantly to track
|
|
286
|
+
current, previous and best — hundreds of thousands of copies in a 50,000-step run.
|
|
287
|
+
|
|
288
|
+
Here `move()` returns the next state, so nothing is copied at all. Prefer to
|
|
289
|
+
mutate? Pass `copy=`; it runs only when a new best is found, so copying costs
|
|
290
|
+
O(improvements) — typically a few dozen — instead of O(steps).
|
|
291
|
+
|
|
292
|
+
### 6. Deltas, with the usual footgun defused
|
|
293
|
+
|
|
294
|
+
An expensive objective makes full recomputation the bottleneck, so `move()` may
|
|
295
|
+
return `(next_state, delta)` and skip the `energy()` call entirely.
|
|
296
|
+
|
|
297
|
+
The trap is that a *wrong* delta is silent: the run diligently optimises a running
|
|
298
|
+
total that has drifted from the real objective, and reports a confident,
|
|
299
|
+
meaningless number. This library recomputes the winner's energy once at the end,
|
|
300
|
+
reports that as the truth, and exposes the discrepancy as `result.delta_drift`.
|
|
301
|
+
Non-zero means your delta and your energy disagree.
|
|
302
|
+
|
|
303
|
+
### 7. Temperatures sized from your problem
|
|
304
|
+
|
|
305
|
+
`t_max` and `t_min` are in the units of *your* energy function, so a library
|
|
306
|
+
default is meaningless — 25,000 is scorching for a problem scored in fractions and
|
|
307
|
+
freezing for one scored in thousands. Omit `schedule` and the annealer takes a
|
|
308
|
+
short random walk first, measures the uphill moves it actually meets, and picks a
|
|
309
|
+
range accepting a typical one 80% of the time at the start and the smallest one 1%
|
|
310
|
+
of the time at the end. Tens of moves; bypass it with an explicit `schedule=`.
|
|
311
|
+
|
|
312
|
+
### 8. Functions, not inheritance — but classes still work
|
|
313
|
+
|
|
314
|
+
There's no base class to subclass and no framework object holding your state.
|
|
315
|
+
|
|
316
|
+
That isn't austerity; it's what makes point 5 possible. A base class has to own the
|
|
317
|
+
state as `self.state`, and *that* is what forces an annealer to copy on every step
|
|
318
|
+
to track current, previous and best. Make state a value that moves return, and
|
|
319
|
+
there's nothing to copy.
|
|
320
|
+
|
|
321
|
+
If you like modelling the problem as a class, [do](#bringing-a-class) — bound
|
|
322
|
+
methods are functions. The functional API subsumes the class-based one; the
|
|
323
|
+
reverse isn't true.
|
|
324
|
+
|
|
325
|
+
---
|
|
326
|
+
|
|
327
|
+
## What to use instead
|
|
328
|
+
|
|
329
|
+
This library is narrow on purpose.
|
|
330
|
+
|
|
331
|
+
| If you're… | Use |
|
|
332
|
+
|---|---|
|
|
333
|
+
| Optimising a continuous function over ℝⁿ | **`scipy.optimize.dual_annealing`** or `basinhopping`. Mature, well-tested, built for real-valued vectors. This library targets combinatorial state — permutations, assignments, schedules — where "the gradient" isn't a thing |
|
|
334
|
+
| Annealing in a script or notebook: main thread, no deadline, progress on screen | **[`simanneal`](https://github.com/perrygeo/simanneal)** is a fine, long-standing choice with a progress display built in. Its constraints — a global RNG, a `SIGINT` handler installed at construction, step-count budgets, stderr output — are reasonable for interactive use, and are exactly what this library exists to avoid elsewhere |
|
|
335
|
+
| Needing a proven-optimal answer, not a good one | **OR-Tools CP-SAT**. Annealing offers no optimality guarantee. If your problem is small enough to solve exactly, solve it exactly |
|
|
336
|
+
| Tuning hyperparameters | **Optuna** or **Hyperopt**. Different problem, better tools |
|
|
337
|
+
| Running one long optimisation offline | Almost anything works, including this. The properties above stop mattering when nothing else shares the process |
|
|
338
|
+
|
|
339
|
+
---
|
|
340
|
+
|
|
341
|
+
## API
|
|
342
|
+
|
|
343
|
+
### `anneal(initial, *, energy, move, ...) -> Result`
|
|
344
|
+
|
|
345
|
+
| Argument | Meaning |
|
|
346
|
+
|---|---|
|
|
347
|
+
| `initial` | Any object. The annealer never inspects it |
|
|
348
|
+
| `energy` | `state -> float`, lower is better |
|
|
349
|
+
| `move` | `(state, rng) -> next_state` or `-> (next_state, delta)` |
|
|
350
|
+
| `max_steps` | Stop after N steps. Reproducible |
|
|
351
|
+
| `time_budget` | Stop after N seconds. At least one budget is required |
|
|
352
|
+
| `seed` / `rng` | A private generator. Never the global one |
|
|
353
|
+
| `schedule` | `progress(0..1) -> temperature`. Defaults to a calibrated geometric schedule |
|
|
354
|
+
| `stall_steps` | Give up after N steps with no new best |
|
|
355
|
+
| `target_energy` | Stop once this is reached |
|
|
356
|
+
| `copy` | Only for in-place moves. Called per improvement |
|
|
357
|
+
| `on_progress` / `progress_every` | Reporting hook and its cadence |
|
|
358
|
+
| `calibration_samples` | Moves sampled to size the default schedule |
|
|
359
|
+
| `clock` | Injectable time source, so deadlines are testable |
|
|
360
|
+
|
|
361
|
+
### `Result` (frozen)
|
|
362
|
+
|
|
363
|
+
`state`, `energy`, `initial_energy`, `improvement`, `steps`, `accepted`,
|
|
364
|
+
`improved`, `elapsed`, `stopped_by`, `delta_drift`.
|
|
365
|
+
|
|
366
|
+
### `Progress` (frozen)
|
|
367
|
+
|
|
368
|
+
`step`, `energy`, `best_energy`, `temperature`, `accepted`, `elapsed`, `fraction`.
|
|
369
|
+
|
|
370
|
+
### Schedules
|
|
371
|
+
|
|
372
|
+
`geometric(t_max, t_min)` (the usual choice), `linear(t_max, t_min=0)`,
|
|
373
|
+
`constant(t)` (Metropolis without annealing — useful for telling whether a
|
|
374
|
+
disappointing run is the schedule's fault or the move function's). A schedule is
|
|
375
|
+
just `Callable[[float], float]`, so your own works anywhere one is accepted.
|
|
376
|
+
`acceptance_probability(delta, temperature)` is exposed for the same reason.
|
|
377
|
+
|
|
378
|
+
### `calibrate(initial, *, energy, move, rng, ...) -> (t_max, t_min)`
|
|
379
|
+
|
|
380
|
+
Exposed separately so you can size a range once and reuse it across many runs
|
|
381
|
+
rather than paying for the sampling walk each time.
|
|
382
|
+
|
|
383
|
+
---
|
|
384
|
+
|
|
385
|
+
## Examples
|
|
386
|
+
|
|
387
|
+
| | |
|
|
388
|
+
|---|---|
|
|
389
|
+
| `examples/tsp.py` | A 20-city tour, 2-opt moves, progress through a callback. ~500k steps in 2s, 246 → 121 |
|
|
390
|
+
| `examples/server.py` | The case this library exists for: annealing in a request handler, stdlib only. Demonstrates both budget modes under concurrency |
|
|
391
|
+
|
|
392
|
+
---
|
|
393
|
+
|
|
394
|
+
## Development
|
|
395
|
+
|
|
396
|
+
```sh
|
|
397
|
+
pip install -e ".[dev]"
|
|
398
|
+
pytest
|
|
399
|
+
ruff check .
|
|
400
|
+
mypy --strict src/simple_annealing
|
|
401
|
+
```
|
|
402
|
+
|
|
403
|
+
Python 3.10+. No runtime dependencies.
|
|
404
|
+
|
|
405
|
+
## Licence
|
|
406
|
+
|
|
407
|
+
MIT.
|