harmonix-opt 1.0.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.
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2025 Abdulkadir Özcan
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,431 @@
1
+ Metadata-Version: 2.4
2
+ Name: harmonix-opt
3
+ Version: 1.0.0
4
+ Summary: Harmony Search optimisation with dependent variable spaces and engineering domain catalogues
5
+ Author-email: Abdulkadir Özcan <a.kdr.ozcn@gmail.com>
6
+ License: MIT License
7
+
8
+ Copyright (c) 2025 Abdulkadir Özcan
9
+
10
+ Permission is hereby granted, free of charge, to any person obtaining a copy
11
+ of this software and associated documentation files (the "Software"), to deal
12
+ in the Software without restriction, including without limitation the rights
13
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
14
+ copies of the Software, and to permit persons to whom the Software is
15
+ furnished to do so, subject to the following conditions:
16
+
17
+ The above copyright notice and this permission notice shall be included in all
18
+ copies or substantial portions of the Software.
19
+
20
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
21
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
22
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
23
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
24
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
25
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
26
+ SOFTWARE.
27
+
28
+ Project-URL: Homepage, https://github.com/AutoPyloter/harmonix
29
+ Project-URL: Source, https://github.com/AutoPyloter/harmonix
30
+ Project-URL: Bug Tracker, https://github.com/AutoPyloter/harmonix/issues
31
+ Project-URL: Documentation, https://github.com/AutoPyloter/harmonix/wiki
32
+ Project-URL: Changelog, https://github.com/AutoPyloter/harmonix/releases
33
+ Keywords: harmony search,metaheuristic,optimisation,optimization,structural engineering,multi-objective,pareto,aci-318,ec2,engineering optimization
34
+ Classifier: Development Status :: 5 - Production/Stable
35
+ Classifier: Programming Language :: Python :: 3
36
+ Classifier: Programming Language :: Python :: 3.8
37
+ Classifier: Programming Language :: Python :: 3.9
38
+ Classifier: Programming Language :: Python :: 3.10
39
+ Classifier: Programming Language :: Python :: 3.11
40
+ Classifier: Programming Language :: Python :: 3.12
41
+ Classifier: Topic :: Scientific/Engineering
42
+ Classifier: Topic :: Scientific/Engineering :: Mathematics
43
+ Classifier: Intended Audience :: Science/Research
44
+ Classifier: Intended Audience :: Developers
45
+ Classifier: Operating System :: OS Independent
46
+ Classifier: Typing :: Typed
47
+ Requires-Python: >=3.8
48
+ Description-Content-Type: text/markdown
49
+ License-File: LICENSE
50
+ Dynamic: license-file
51
+
52
+ # harmonix
53
+
54
+ [![CI](https://github.com/AutoPyloter/harmonix/actions/workflows/ci.yml/badge.svg)](https://github.com/AutoPyloter/harmonix/actions/workflows/ci.yml)
55
+ [![Python](https://img.shields.io/badge/python-3.8%20%7C%203.9%20%7C%203.10%20%7C%203.11%20%7C%203.12-blue)](https://www.python.org)
56
+ [![Tests](https://img.shields.io/badge/tests-325%20passed-brightgreen)](#testing)
57
+ [![License: MIT](https://img.shields.io/badge/License-MIT-green.svg)](LICENSE)
58
+
59
+ **Harmony Search optimisation with dependent variable spaces and engineering domain catalogues.**
60
+
61
+ harmonix is a Python library for solving single- and multi-objective optimisation problems using the [Harmony Search](https://en.wikipedia.org/wiki/Harmony_search) metaheuristic. Its key design principle is *search-space first*: instead of just minimising a function, you describe the domain of each variable precisely — including dependencies between variables, discrete grids, catalogue lookups, and domain-specific feasibility rules — and let the algorithm handle the rest.
62
+
63
+ ```python
64
+ from harmonix import DesignSpace, Continuous, Discrete, Minimization
65
+
66
+ space = DesignSpace()
67
+ space.add("h", Continuous(0.30, 1.20))
68
+ space.add("bf", Continuous(lo=lambda ctx: ctx["h"] * 0.5,
69
+ hi=lambda ctx: ctx["h"] * 2.0))
70
+ space.add("n", Discrete(4, 2, 20))
71
+
72
+ def objective(harmony):
73
+ h, bf, n = harmony["h"], harmony["bf"], harmony["n"]
74
+ cost = 1.1 * h * bf + 0.04 * n
75
+ penalty = max(0.0, h - 2 * bf)
76
+ return cost, penalty
77
+
78
+ result = Minimization(space, objective).optimize(
79
+ memory_size=20, hmcr=0.85, par=0.35, max_iter=5000
80
+ )
81
+ print(result)
82
+ ```
83
+
84
+ ---
85
+
86
+ ## Installation
87
+
88
+ ```bash
89
+ pip install harmonix-opt
90
+ ```
91
+
92
+ Requires Python 3.8+. No mandatory dependencies beyond the standard library.
93
+
94
+ For development:
95
+
96
+ ```bash
97
+ pip install -r requirements-dev.txt
98
+ pip install -e .
99
+ ```
100
+
101
+ ---
102
+
103
+ ## Core concepts
104
+
105
+ ### Design variables
106
+
107
+ Every variable implements three methods that the algorithm calls internally:
108
+
109
+ | Method | Purpose |
110
+ |--------|---------|
111
+ | `sample(ctx)` | Draw a random feasible value |
112
+ | `filter(candidates, ctx)` | Keep only feasible values from harmony memory |
113
+ | `neighbor(value, ctx)` | Return an adjacent feasible value (pitch adjustment) |
114
+
115
+ The `ctx` argument is a dict of all variable values assigned earlier in the same harmony. This enables **dependent bounds** — the domain of a variable can depend on previously assigned variables.
116
+
117
+ ### Built-in variable types
118
+
119
+ | Type | Domain |
120
+ |------|--------|
121
+ | `Continuous(lo, hi)` | ℝ ∩ [lo, hi] |
122
+ | `Discrete(lo, step, hi)` | {lo, lo+step, …, hi} |
123
+ | `Integer(lo, hi)` | {lo, lo+1, …, hi} |
124
+ | `Categorical(choices)` | finite label set |
125
+
126
+ All bounds accept callables for dependent domains:
127
+
128
+ ```python
129
+ space.add("d", Continuous(0.40, 1.20))
130
+ space.add("tw", Continuous(lo=lambda ctx: ctx["d"] / 50,
131
+ hi=lambda ctx: ctx["d"] / 10))
132
+ ```
133
+
134
+ ### Domain-specific variable spaces
135
+
136
+ harmonix ships a catalogue of ready-made variable types for common engineering and mathematical domains:
137
+
138
+ ```python
139
+ from harmonix import ACIRebar, SteelSection, ConcreteGrade, PrimeVariable
140
+
141
+ # ACI 318 ductile bar arrangement — bounds depend on d and fc
142
+ space.add("rebar", ACIRebar(d_expr=lambda ctx: ctx["d"],
143
+ cc_expr=60.0,
144
+ fc=lambda ctx: ctx["grade"].fck_MPa,
145
+ fy=420.0))
146
+
147
+ # Standard steel I-section from built-in catalogue (IPE, HEA, HEB, W)
148
+ space.add("section", SteelSection(series=["IPE", "HEA"]))
149
+
150
+ # EN 206 concrete grade (C12/15 to C90/105)
151
+ space.add("concrete", ConcreteGrade(min_grade="C25/30", max_grade="C50/60"))
152
+
153
+ # Prime numbers
154
+ space.add("p", PrimeVariable(lo=2, hi=500))
155
+ ```
156
+
157
+ Full catalogue:
158
+
159
+ | Category | Types |
160
+ |----------|-------|
161
+ | **Mathematical** | `NaturalNumber`, `WholeNumber`, `NegativeInt`, `NegativeReal`, `PositiveReal`, `PrimeVariable`, `PowerOfTwo`, `Fibonacci` |
162
+ | **Structural** | `ACIRebar`, `ACIDoubleRebar`, `SteelSection`, `ConcreteGrade` |
163
+ | **Geotechnical** | `SoilSPT` |
164
+ | **Seismic** | `SeismicZoneTBDY` |
165
+
166
+ All types are also accessible via the plugin registry:
167
+
168
+ ```python
169
+ from harmonix import create_variable, list_variable_types
170
+ print(list_variable_types())
171
+ var = create_variable("aci_rebar", d_expr=0.55, cc_expr=40.0)
172
+ ```
173
+
174
+ ### Custom variables
175
+
176
+ **Subclass** `Variable` for full control:
177
+
178
+ ```python
179
+ from harmonix import Variable, register_variable
180
+
181
+ @register_variable("my_type")
182
+ class MyVariable(Variable):
183
+ def sample(self, ctx): ...
184
+ def filter(self, candidates, ctx): ...
185
+ def neighbor(self, value, ctx): ...
186
+ ```
187
+
188
+ **Factory function** for quick prototyping:
189
+
190
+ ```python
191
+ from harmonix import make_variable
192
+ import random
193
+
194
+ EvenVar = make_variable(
195
+ sample = lambda ctx: random.choice(range(2, 101, 2)),
196
+ filter = lambda cands, ctx: [c for c in cands if c % 2 == 0],
197
+ neighbor = lambda val, ctx: val + random.choice([-2, 2]),
198
+ name = "even",
199
+ )
200
+ space.add("n", EvenVar())
201
+ ```
202
+
203
+ ---
204
+
205
+ ## Optimisers
206
+
207
+ ### Minimization
208
+
209
+ ```python
210
+ result = Minimization(space, objective).optimize(
211
+ memory_size = 20, # Harmony Memory Size (HMS)
212
+ hmcr = 0.85, # Harmony Memory Considering Rate
213
+ par = 0.35, # Pitch Adjusting Rate
214
+ max_iter = 5000,
215
+ bw_max = 0.05, # Initial bandwidth (5% of domain width)
216
+ bw_min = 0.001, # Final bandwidth (exponential decay)
217
+ resume = "auto", # "auto" | "new" | "resume"
218
+ checkpoint_path = "run.json",
219
+ checkpoint_every = 500,
220
+ use_cache = False, # Cache identical harmony evaluations
221
+ cache_maxsize = 4096,
222
+ log_init = False, # Write initial memory to CSV
223
+ log_history = False, # Write best-per-iteration to CSV
224
+ log_evaluations = False, # Write every evaluated harmony to CSV
225
+ history_every = 1,
226
+ verbose = True,
227
+ callback = my_callback,
228
+ )
229
+ print(result.best_harmony)
230
+ print(result.best_fitness)
231
+ ```
232
+
233
+ ### Maximization
234
+
235
+ Same interface — negates internally, reports original sign.
236
+
237
+ ```python
238
+ result = Maximization(space, objective).optimize(...)
239
+ ```
240
+
241
+ ### MultiObjective
242
+
243
+ ```python
244
+ def objective(harmony):
245
+ f1 = harmony["x"] ** 2
246
+ f2 = (harmony["x"] - 2) ** 2
247
+ return (f1, f2), 0.0 # tuple of objectives, penalty
248
+
249
+ result = MultiObjective(space, objective).optimize(
250
+ max_iter = 10_000,
251
+ archive_size = 100,
252
+ )
253
+
254
+ for entry in result.front:
255
+ print(entry.objectives, entry.harmony)
256
+ ```
257
+
258
+ ### Callback and early stopping
259
+
260
+ ```python
261
+ def my_callback(iteration, partial_result):
262
+ print(iteration, partial_result.best_fitness)
263
+ if partial_result.best_fitness < 1e-4:
264
+ raise StopIteration # stops the loop cleanly
265
+ ```
266
+
267
+ ---
268
+
269
+ ## Advanced features
270
+
271
+ ### Dynamic bandwidth narrowing
272
+
273
+ The pitch adjustment step size decays exponentially from `bw_max` to `bw_min` over the run — wide exploration early, fine convergence late.
274
+
275
+ ```python
276
+ result = Minimization(space, objective).optimize(
277
+ bw_max=0.10, # 10% of domain width at iteration 0
278
+ bw_min=0.001, # 0.1% at final iteration
279
+ max_iter=5000,
280
+ )
281
+ ```
282
+
283
+ Set `bw_max == bw_min` for constant bandwidth (original HS behaviour). Discrete and categorical variables are unaffected by bandwidth.
284
+
285
+ ### Resume control
286
+
287
+ ```python
288
+ # "auto" — continue if checkpoint exists, start fresh otherwise (safe default)
289
+ # "new" — always start fresh, overwrite any existing checkpoint
290
+ # "resume" — always continue; raises FileNotFoundError if checkpoint missing
291
+
292
+ result = optimizer.optimize(
293
+ max_iter = 50_000,
294
+ checkpoint_path = "run.json",
295
+ resume = "auto",
296
+ )
297
+ ```
298
+
299
+ The initial harmony memory is saved immediately at startup — even a run interrupted in the first seconds can be resumed cleanly.
300
+
301
+ ### Evaluation cache
302
+
303
+ Identical harmonies are never re-evaluated when `use_cache=True`. Particularly valuable for expensive objectives (FEM, CFD, etc.).
304
+
305
+ ```python
306
+ result = optimizer.optimize(use_cache=True, cache_maxsize=4096)
307
+ print(optimizer._cache.stats())
308
+ # EvaluationCache: 412 hits / 1005 total (41.0% hit rate) size=593/4096
309
+ ```
310
+
311
+ ### CSV logging
312
+
313
+ ```python
314
+ result = optimizer.optimize(
315
+ checkpoint_path = "run.json",
316
+ log_init = True, # → run_init.csv (initial memory)
317
+ log_history = True, # → run_history.csv (best per iteration)
318
+ log_evaluations = True, # → run_evals.csv (every evaluation)
319
+ history_every = 10, # write history every 10 iterations
320
+ )
321
+ ```
322
+
323
+ All CSV files are readable directly in Excel or with `pandas.read_csv()`.
324
+
325
+ ---
326
+
327
+ ## Decoding engineering variables
328
+
329
+ Variables like `ACIRebar` and `SteelSection` store integer codes in the harmony. Use `decode()` to get full properties:
330
+
331
+ ```python
332
+ rebar_var = ACIRebar(d_expr=0.55, cc_expr=40.0)
333
+ code = result.best_harmony["rebar"]
334
+ diameter_mm, bar_count = rebar_var.decode(code)
335
+ print(rebar_var.describe(code)) # "8 bars of Ø19.00 mm"
336
+
337
+ section_var = SteelSection(series=["IPE"])
338
+ sec = section_var.decode(result.best_harmony["section"])
339
+ print(sec.name, sec.Iy_cm4, "cm4")
340
+
341
+ grade_var = ConcreteGrade()
342
+ grade = grade_var.decode(result.best_harmony["concrete"])
343
+ print(grade.name, grade.fck_MPa, "MPa", grade.Ecm_GPa, "GPa")
344
+ ```
345
+
346
+ ### Steel section catalogue
347
+
348
+ The built-in catalogue covers IPE 80–600, HEA 100–500, HEB 100–500, and W-sections. Override with your own file:
349
+
350
+ ```python
351
+ var = SteelSection(catalogue="my_sections.json") # custom catalogue
352
+ var = SteelSection(series=["HEA", "HEB"]) # filter series
353
+ ```
354
+
355
+ ---
356
+
357
+ ## Algorithm background
358
+
359
+ harmonix implements Harmony Search with several enhancements:
360
+
361
+ **Dynamic bandwidth narrowing** — pitch adjustment step size decays exponentially. Early iterations explore broadly; late iterations converge precisely.
362
+
363
+ **Intelligent pitch adjustment** — `neighbor()` is called with the current dependency context so the perturbed value stays feasible. The common incorrect approach of calling `sample()` on PAR is avoided.
364
+
365
+ **Dependent search spaces** — variables are sampled in definition order; each receives a context dict of previously assigned values. Dependent bounds, catalogue filters, and feasibility checks can reference earlier variables without any special handling in the optimiser loop.
366
+
367
+ **Deb constraint handling** — feasible solutions always rank above infeasible ones; among infeasible solutions ranking is by total penalty.
368
+
369
+ ### References
370
+
371
+ - Geem, Z. W., Kim, J. H., & Loganathan, G. V. (2001). A new heuristic optimization algorithm: Harmony search. *Simulation*, 76(2), 60–68.
372
+ - Lee, K. S., & Geem, Z. W. (2005). A new meta-heuristic algorithm for continuous engineering optimization. *Computer Methods in Applied Mechanics and Engineering*, 194(36–38), 3902–3933.
373
+ - Deb, K. (2000). An efficient constraint handling method for genetic algorithms. *Computer Methods in Applied Mechanics and Engineering*, 186(2–4), 311–338.
374
+ - Ricart, J., Hüttemann, G., Lima, J., & Barán, B. (2011). Multiobjective harmony search algorithm proposals. *Electronic Notes in Theoretical Computer Science*, 281, 51–67.
375
+
376
+ ---
377
+
378
+ ## Testing
379
+
380
+ ```bash
381
+ pip install -r requirements-dev.txt
382
+ pytest tests/ -v
383
+ ```
384
+
385
+ 325 tests across 9 test files covering:
386
+
387
+ - All variable types — `sample`, `filter`, `neighbor`, edge cases, `lo > hi` validation
388
+ - DesignSpace — dependency chains, empty space, 50-variable stress test
389
+ - Optimisers — Minimization, Maximization, MultiObjective
390
+ - New features — bandwidth decay, resume modes, evaluation cache, CSV logging
391
+ - Pareto archive — dominance, crowding distance, serialization
392
+ - Engineering physics — EC2 formulas, ACI 318 feasibility, steel section properties
393
+ - Determinism — same seed produces identical results
394
+ - Numerical correctness — Sphere, Rosenbrock, constrained minimization
395
+
396
+ ---
397
+
398
+ ## Project structure
399
+
400
+ ```
401
+ harmonix/
402
+ ├── harmonix/
403
+ │ ├── variables.py # Continuous, Discrete, Integer, Categorical
404
+ │ ├── space.py # DesignSpace
405
+ │ ├── optimizer.py # Minimization, Maximization, MultiObjective
406
+ │ ├── pareto.py # Pareto archive, crowding distance
407
+ │ ├── registry.py # register_variable, make_variable
408
+ │ ├── logging.py # EvaluationCache, RunLogger
409
+ │ └── spaces/
410
+ │ ├── math.py # Mathematical search spaces
411
+ │ └── engineering.py # Engineering domain spaces
412
+ ├── examples/
413
+ │ ├── 01_quickstart.py
414
+ │ ├── 02_dependent_bounds.py
415
+ │ ├── 03_engineering_rc_beam.py
416
+ │ ├── 04_custom_variables.py
417
+ │ ├── 05_multi_objective.py
418
+ │ ├── 06_steel_beam_design.py
419
+ │ └── 07_rc_section_full.py
420
+ ├── tests/ # 325 tests across 9 files
421
+ ├── requirements-dev.txt
422
+ ├── ruff.toml
423
+ ├── pyproject.toml
424
+ └── LICENSE
425
+ ```
426
+
427
+ ---
428
+
429
+ ## License
430
+
431
+ MIT © Abdulkadir Özcan