geneticsar 0.1.0__py3-none-any.whl

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.
geneticsar/__init__.py ADDED
@@ -0,0 +1,12 @@
1
+ """Genetic algorithm optimisation of nested species-area relationship sampling."""
2
+
3
+ from importlib.metadata import PackageNotFoundError, version
4
+
5
+ from geneticsar._ga import Result, evolve, order_crossover, swap_mutation
6
+
7
+ try:
8
+ __version__ = version("geneticsar")
9
+ except PackageNotFoundError: # running from a source tree without an install
10
+ __version__ = "0.0.0"
11
+
12
+ __all__ = ["Result", "__version__", "evolve", "order_crossover", "swap_mutation"]
geneticsar/_ga.py ADDED
@@ -0,0 +1,98 @@
1
+ """A small genetic algorithm over permutations.
2
+
3
+ The search space is an ordering of ``n`` items. ``fitness`` scores an
4
+ ordering; higher is better. Selection is tournament, crossover is order
5
+ crossover (OX), mutation is a swap. Nothing here knows about species-area
6
+ relationships: that arrives when the fitness is a nested SAR fit.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ from collections.abc import Callable
12
+ from dataclasses import dataclass, field
13
+
14
+ import numpy as np
15
+
16
+ Fitness = Callable[[np.ndarray], float]
17
+
18
+
19
+ @dataclass(frozen=True)
20
+ class Result:
21
+ """Outcome of :func:`evolve`."""
22
+
23
+ best: np.ndarray
24
+ best_fitness: float
25
+ history: list[float] = field(default_factory=list)
26
+ """Best fitness after each generation, including the initial population."""
27
+
28
+ @property
29
+ def generations(self) -> int:
30
+ return max(len(self.history) - 1, 0)
31
+
32
+
33
+ def order_crossover(a: np.ndarray, b: np.ndarray, rng: np.random.Generator) -> np.ndarray:
34
+ """Order crossover: keep a slice of ``a``, fill the rest in ``b``'s order."""
35
+ n = len(a)
36
+ i, j = sorted(rng.integers(0, n + 1, size=2))
37
+ child = np.full(n, -1)
38
+ child[i:j] = a[i:j]
39
+ fill = [x for x in b if x not in set(child[i:j].tolist())]
40
+ k = 0
41
+ for pos in range(n):
42
+ if child[pos] == -1:
43
+ child[pos] = fill[k]
44
+ k += 1
45
+ return child
46
+
47
+
48
+ def swap_mutation(p: np.ndarray, rng: np.random.Generator) -> np.ndarray:
49
+ q = p.copy()
50
+ i, j = rng.choice(len(q), size=2, replace=False)
51
+ q[i], q[j] = q[j], q[i]
52
+ return q
53
+
54
+
55
+ def evolve(
56
+ n: int,
57
+ fitness: Fitness,
58
+ *,
59
+ population_size: int = 30,
60
+ generations: int = 50,
61
+ tournament: int = 3,
62
+ crossover_rate: float = 0.9,
63
+ mutation_rate: float = 0.2,
64
+ elite: int = 1,
65
+ seed: int | None = None,
66
+ ) -> Result:
67
+ """Evolve an ordering of ``n`` items that maximises ``fitness``."""
68
+ if n < 2:
69
+ raise ValueError("n must be at least 2")
70
+ if population_size < 2:
71
+ raise ValueError("population_size must be at least 2")
72
+ if not 0 <= elite < population_size:
73
+ raise ValueError("elite must be in [0, population_size)")
74
+ rng = np.random.default_rng(seed)
75
+
76
+ pop = [rng.permutation(n) for _ in range(population_size)]
77
+ scores = np.array([fitness(p) for p in pop], dtype=float)
78
+ history = [float(scores.max())]
79
+
80
+ def select() -> np.ndarray:
81
+ idx = rng.choice(population_size, size=min(tournament, population_size), replace=False)
82
+ return pop[idx[np.argmax(scores[idx])]]
83
+
84
+ for _ in range(generations):
85
+ order = np.argsort(-scores)
86
+ new_pop = [pop[i].copy() for i in order[:elite]]
87
+ while len(new_pop) < population_size:
88
+ a, b = select(), select()
89
+ child = order_crossover(a, b, rng) if rng.random() < crossover_rate else a.copy()
90
+ if rng.random() < mutation_rate:
91
+ child = swap_mutation(child, rng)
92
+ new_pop.append(child)
93
+ pop = new_pop
94
+ scores = np.array([fitness(p) for p in pop], dtype=float)
95
+ history.append(float(scores.max()))
96
+
97
+ best = int(np.argmax(scores))
98
+ return Result(best=pop[best].copy(), best_fitness=float(scores[best]), history=history)
@@ -0,0 +1,48 @@
1
+ Metadata-Version: 2.5
2
+ Name: geneticsar
3
+ Version: 0.1.0
4
+ Summary: Genetic algorithm optimisation of nested species-area relationship sampling
5
+ Project-URL: Homepage, https://github.com/jmcmeen/geneticsar
6
+ Project-URL: Source, https://github.com/jmcmeen/geneticsar
7
+ Project-URL: Changelog, https://github.com/jmcmeen/geneticsar/blob/main/CHANGELOG.md
8
+ Project-URL: Bug Tracker, https://github.com/jmcmeen/geneticsar/issues
9
+ Author-email: John McMeen <johnmcmeen@gmail.com>
10
+ License-Expression: MIT
11
+ License-File: LICENSE
12
+ Classifier: Development Status :: 3 - Alpha
13
+ Classifier: Intended Audience :: Developers
14
+ Classifier: Intended Audience :: Science/Research
15
+ Classifier: Operating System :: OS Independent
16
+ Classifier: Programming Language :: Python :: 3
17
+ Classifier: Programming Language :: Python :: 3.10
18
+ Classifier: Programming Language :: Python :: 3.11
19
+ Classifier: Programming Language :: Python :: 3.12
20
+ Classifier: Programming Language :: Python :: 3.13
21
+ Requires-Python: >=3.10
22
+ Requires-Dist: numpy>=1.22
23
+ Provides-Extra: dev
24
+ Requires-Dist: pytest-cov; extra == 'dev'
25
+ Requires-Dist: pytest>=7.0; extra == 'dev'
26
+ Requires-Dist: ruff<0.18,>=0.17; extra == 'dev'
27
+ Description-Content-Type: text/markdown
28
+
29
+ # geneticsar
30
+
31
+ Genetic algorithm optimisation of nested species-area relationship sampling.
32
+ Searches over orderings with a small permutation GA; the fitness that scores
33
+ an ordering by its SAR fit is built on [nestsar](https://pypi.org/project/nestsar/)
34
+ and [sars](https://pypi.org/project/sars/).
35
+
36
+ ```python
37
+ import geneticsar
38
+
39
+ result = geneticsar.evolve(n=20, fitness=my_score, generations=100, seed=0)
40
+ result.best, result.best_fitness
41
+ ```
42
+
43
+ ## Development
44
+
45
+ ```sh
46
+ make install # create .venv with dev tooling
47
+ make check # lint, format check, tests
48
+ ```
@@ -0,0 +1,6 @@
1
+ geneticsar/__init__.py,sha256=80HtSl71MJbWRlEZU1SVSBIdWfJ6KP0SE9P-U0boFFc,453
2
+ geneticsar/_ga.py,sha256=52-DLT4cZF2xibokBUdsa7nt2uxPJGFl8t1ZjbmN41o,3205
3
+ geneticsar-0.1.0.dist-info/METADATA,sha256=aj4CKaSSzvvVAqSlKr8FCqROqJKBKKo1HmpjQm_lNug,1748
4
+ geneticsar-0.1.0.dist-info/WHEEL,sha256=W3fkpkm7-wf9vBI5Z-7s0eWkeM-spu78I8Neb98DeEg,87
5
+ geneticsar-0.1.0.dist-info/licenses/LICENSE,sha256=qzmCAeakObqZTPFNxWt_xwcfdG7J_3DWvuq_M9UnjFI,1068
6
+ geneticsar-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.32.4
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 John McMeen
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.