carmelolg-gapoly 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.
- carmelolg_gapoly-0.1.0/PKG-INFO +82 -0
- carmelolg_gapoly-0.1.0/README.md +63 -0
- carmelolg_gapoly-0.1.0/pyproject.toml +36 -0
- carmelolg_gapoly-0.1.0/setup.cfg +4 -0
- carmelolg_gapoly-0.1.0/src/carmelolg/gapoly/__init__.py +5 -0
- carmelolg_gapoly-0.1.0/src/carmelolg/gapoly/__main__.py +4 -0
- carmelolg_gapoly-0.1.0/src/carmelolg/gapoly/cli.py +153 -0
- carmelolg_gapoly-0.1.0/src/carmelolg/gapoly/fast_render.py +87 -0
- carmelolg_gapoly-0.1.0/src/carmelolg/gapoly/help_format.py +96 -0
- carmelolg_gapoly-0.1.0/src/carmelolg/gapoly/operators.py +82 -0
- carmelolg_gapoly-0.1.0/src/carmelolg/gapoly/problem.py +48 -0
- carmelolg_gapoly-0.1.0/src/carmelolg/gapoly/render.py +20 -0
- carmelolg_gapoly-0.1.0/src/carmelolg/gapoly/shapes.py +116 -0
- carmelolg_gapoly-0.1.0/src/carmelolg/gapoly/viewer.py +126 -0
- carmelolg_gapoly-0.1.0/src/carmelolg_gapoly.egg-info/PKG-INFO +82 -0
- carmelolg_gapoly-0.1.0/src/carmelolg_gapoly.egg-info/SOURCES.txt +19 -0
- carmelolg_gapoly-0.1.0/src/carmelolg_gapoly.egg-info/dependency_links.txt +1 -0
- carmelolg_gapoly-0.1.0/src/carmelolg_gapoly.egg-info/entry_points.txt +2 -0
- carmelolg_gapoly-0.1.0/src/carmelolg_gapoly.egg-info/requires.txt +11 -0
- carmelolg_gapoly-0.1.0/src/carmelolg_gapoly.egg-info/top_level.txt +1 -0
- carmelolg_gapoly-0.1.0/tests/test_gapoly.py +181 -0
|
@@ -0,0 +1,82 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: carmelolg-gapoly
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Evolve semi-transparent polygons with a genetic algorithm (GALib) until they look like a target photo.
|
|
5
|
+
Project-URL: Homepage, https://github.com/carmelolg/genetic-evolving-polygons
|
|
6
|
+
Project-URL: Source, https://github.com/carmelolg/genetic-evolving-polygons
|
|
7
|
+
Project-URL: Issues, https://github.com/carmelolg/genetic-evolving-polygons/issues
|
|
8
|
+
Requires-Python: >=3.10
|
|
9
|
+
Description-Content-Type: text/markdown
|
|
10
|
+
Requires-Dist: carmelolg-galib>=0.3.0
|
|
11
|
+
Requires-Dist: numpy>=1.24
|
|
12
|
+
Requires-Dist: Pillow>=10
|
|
13
|
+
Requires-Dist: numba>=0.60
|
|
14
|
+
Provides-Extra: live
|
|
15
|
+
Requires-Dist: matplotlib>=3.7; extra == "live"
|
|
16
|
+
Provides-Extra: dev
|
|
17
|
+
Requires-Dist: pytest>=8; extra == "dev"
|
|
18
|
+
Requires-Dist: ruff>=0.6; extra == "dev"
|
|
19
|
+
|
|
20
|
+
# gapoly
|
|
21
|
+
|
|
22
|
+
`gapoly` = GA + polygons (distribution `carmelolg-gapoly`, import `carmelolg.gapoly`, command `gapoly`).
|
|
23
|
+
|
|
24
|
+
Genetic algorithm that evolves semi-transparent polygons until, stacked, they look like a target photo.
|
|
25
|
+
Built on [GALib](https://github.com/carmelolg/GALib) (`carmelolg.galib`, on PyPI as `carmelolg-galib`).
|
|
26
|
+
|
|
27
|
+
- **Genome**: float32 array, one row per polygon (3-6 vertices in [0,1] coordinates, RGBA), drawn in row order.
|
|
28
|
+
- **Fitness**: pixel MSE between render and target (lower is better, `maximize = False`).
|
|
29
|
+
- **Mutation**: move a vertex, shift a polygon, change colour/alpha, add / remove a polygon, change overlap order.
|
|
30
|
+
- **Crossover**: swap tails of the two polygon lists.
|
|
31
|
+
|
|
32
|
+
## Genome layout
|
|
33
|
+
|
|
34
|
+
A genome is a float32 array, one row per polygon, drawn in row order (later rows on top). Values are in [0, 1];
|
|
35
|
+
coordinates are fractions of the image side.
|
|
36
|
+
|
|
37
|
+
```
|
|
38
|
+
column: 0 | 1 2 | 3 4 | ... | 11 12 | 13 14 15 16
|
|
39
|
+
meaning: n | x0 y0 x1 y1 ... x5 y5 | r g b a
|
|
40
|
+
```
|
|
41
|
+
|
|
42
|
+
`n` is the number of vertices used (3-6), the rest are ignored. Do not index rows with bare numbers: use the names
|
|
43
|
+
in `shapes.py` (`N_VERTICES`, `X(v)`, `Y(v)`, `RED`..`ALPHA`, `vertices`, `color`, `make_row`).
|
|
44
|
+
`describe(genome)` prints a genome as text, one line per polygon. The numba kernel (`fast_render.py`) reads the
|
|
45
|
+
same layout; `test_row_layout_is_the_documented_one` fails if the columns change.
|
|
46
|
+
|
|
47
|
+
## Setup
|
|
48
|
+
|
|
49
|
+
```bash
|
|
50
|
+
pip install carmelolg-gapoly # from PyPI
|
|
51
|
+
pip install "carmelolg-gapoly[live]" # plus the live matplotlib window
|
|
52
|
+
```
|
|
53
|
+
|
|
54
|
+
From a clone (development):
|
|
55
|
+
|
|
56
|
+
```bash
|
|
57
|
+
python -m venv .venv && source .venv/bin/activate
|
|
58
|
+
pip install -e ".[live,dev]"
|
|
59
|
+
```
|
|
60
|
+
|
|
61
|
+
## Run
|
|
62
|
+
|
|
63
|
+
```bash
|
|
64
|
+
python -m carmelolg.gapoly photo.jpg --generations 5000 --live # live window
|
|
65
|
+
python -m carmelolg.gapoly photo.jpg --snapshot-every 1 --generations 300 # one PNG per generation
|
|
66
|
+
```
|
|
67
|
+
|
|
68
|
+
Output in `out/<name>/`: `snapshots/gen_*.png`, `final.png`, `evolution.gif`, `history.csv`.
|
|
69
|
+
Polygons shrink coarse-to-fine: from `--start-size` (0.5) to `--max-size` (0.12, fraction of image side) over the first 70% of the run.
|
|
70
|
+
The live window lays out its panels by photo orientation: stacked for landscape, side by side for portrait/square.
|
|
71
|
+
Rendering and error are one compiled Numba loop (`fast_render.py`, releases the GIL). Fitness runs in parallel with GALib `workers=`: `--workers N` (default all CPUs), `--parallel thread|process` (default thread).
|
|
72
|
+
Useful options: `--polygons`, `--population`, `--mutation-rate`, `--size` (working resolution: smaller = faster), `--seed`.
|
|
73
|
+
|
|
74
|
+
## Tests
|
|
75
|
+
|
|
76
|
+
```bash
|
|
77
|
+
python -m pytest
|
|
78
|
+
```
|
|
79
|
+
|
|
80
|
+
## Ideas not done yet
|
|
81
|
+
|
|
82
|
+
More shape types, region weights (face counts more), SSIM fitness, greedy hill-climbing baseline.
|
|
@@ -0,0 +1,63 @@
|
|
|
1
|
+
# gapoly
|
|
2
|
+
|
|
3
|
+
`gapoly` = GA + polygons (distribution `carmelolg-gapoly`, import `carmelolg.gapoly`, command `gapoly`).
|
|
4
|
+
|
|
5
|
+
Genetic algorithm that evolves semi-transparent polygons until, stacked, they look like a target photo.
|
|
6
|
+
Built on [GALib](https://github.com/carmelolg/GALib) (`carmelolg.galib`, on PyPI as `carmelolg-galib`).
|
|
7
|
+
|
|
8
|
+
- **Genome**: float32 array, one row per polygon (3-6 vertices in [0,1] coordinates, RGBA), drawn in row order.
|
|
9
|
+
- **Fitness**: pixel MSE between render and target (lower is better, `maximize = False`).
|
|
10
|
+
- **Mutation**: move a vertex, shift a polygon, change colour/alpha, add / remove a polygon, change overlap order.
|
|
11
|
+
- **Crossover**: swap tails of the two polygon lists.
|
|
12
|
+
|
|
13
|
+
## Genome layout
|
|
14
|
+
|
|
15
|
+
A genome is a float32 array, one row per polygon, drawn in row order (later rows on top). Values are in [0, 1];
|
|
16
|
+
coordinates are fractions of the image side.
|
|
17
|
+
|
|
18
|
+
```
|
|
19
|
+
column: 0 | 1 2 | 3 4 | ... | 11 12 | 13 14 15 16
|
|
20
|
+
meaning: n | x0 y0 x1 y1 ... x5 y5 | r g b a
|
|
21
|
+
```
|
|
22
|
+
|
|
23
|
+
`n` is the number of vertices used (3-6), the rest are ignored. Do not index rows with bare numbers: use the names
|
|
24
|
+
in `shapes.py` (`N_VERTICES`, `X(v)`, `Y(v)`, `RED`..`ALPHA`, `vertices`, `color`, `make_row`).
|
|
25
|
+
`describe(genome)` prints a genome as text, one line per polygon. The numba kernel (`fast_render.py`) reads the
|
|
26
|
+
same layout; `test_row_layout_is_the_documented_one` fails if the columns change.
|
|
27
|
+
|
|
28
|
+
## Setup
|
|
29
|
+
|
|
30
|
+
```bash
|
|
31
|
+
pip install carmelolg-gapoly # from PyPI
|
|
32
|
+
pip install "carmelolg-gapoly[live]" # plus the live matplotlib window
|
|
33
|
+
```
|
|
34
|
+
|
|
35
|
+
From a clone (development):
|
|
36
|
+
|
|
37
|
+
```bash
|
|
38
|
+
python -m venv .venv && source .venv/bin/activate
|
|
39
|
+
pip install -e ".[live,dev]"
|
|
40
|
+
```
|
|
41
|
+
|
|
42
|
+
## Run
|
|
43
|
+
|
|
44
|
+
```bash
|
|
45
|
+
python -m carmelolg.gapoly photo.jpg --generations 5000 --live # live window
|
|
46
|
+
python -m carmelolg.gapoly photo.jpg --snapshot-every 1 --generations 300 # one PNG per generation
|
|
47
|
+
```
|
|
48
|
+
|
|
49
|
+
Output in `out/<name>/`: `snapshots/gen_*.png`, `final.png`, `evolution.gif`, `history.csv`.
|
|
50
|
+
Polygons shrink coarse-to-fine: from `--start-size` (0.5) to `--max-size` (0.12, fraction of image side) over the first 70% of the run.
|
|
51
|
+
The live window lays out its panels by photo orientation: stacked for landscape, side by side for portrait/square.
|
|
52
|
+
Rendering and error are one compiled Numba loop (`fast_render.py`, releases the GIL). Fitness runs in parallel with GALib `workers=`: `--workers N` (default all CPUs), `--parallel thread|process` (default thread).
|
|
53
|
+
Useful options: `--polygons`, `--population`, `--mutation-rate`, `--size` (working resolution: smaller = faster), `--seed`.
|
|
54
|
+
|
|
55
|
+
## Tests
|
|
56
|
+
|
|
57
|
+
```bash
|
|
58
|
+
python -m pytest
|
|
59
|
+
```
|
|
60
|
+
|
|
61
|
+
## Ideas not done yet
|
|
62
|
+
|
|
63
|
+
More shape types, region weights (face counts more), SSIM fitness, greedy hill-climbing baseline.
|
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
[build-system]
|
|
2
|
+
requires = ["setuptools>=77"]
|
|
3
|
+
build-backend = "setuptools.build_meta"
|
|
4
|
+
|
|
5
|
+
[project]
|
|
6
|
+
name = "carmelolg-gapoly"
|
|
7
|
+
version = "0.1.0"
|
|
8
|
+
description = "Evolve semi-transparent polygons with a genetic algorithm (GALib) until they look like a target photo."
|
|
9
|
+
readme = "README.md"
|
|
10
|
+
requires-python = ">=3.10"
|
|
11
|
+
dependencies = ["carmelolg-galib>=0.3.0", "numpy>=1.24", "Pillow>=10", "numba>=0.60"]
|
|
12
|
+
|
|
13
|
+
[project.urls]
|
|
14
|
+
Homepage = "https://github.com/carmelolg/genetic-evolving-polygons"
|
|
15
|
+
Source = "https://github.com/carmelolg/genetic-evolving-polygons"
|
|
16
|
+
Issues = "https://github.com/carmelolg/genetic-evolving-polygons/issues"
|
|
17
|
+
|
|
18
|
+
[project.optional-dependencies]
|
|
19
|
+
live = ["matplotlib>=3.7"]
|
|
20
|
+
dev = ["pytest>=8", "ruff>=0.6"]
|
|
21
|
+
|
|
22
|
+
[project.scripts]
|
|
23
|
+
gapoly = "carmelolg.gapoly.cli:main"
|
|
24
|
+
|
|
25
|
+
# `carmelolg` (shared with GALib) is a PEP 420 namespace package (no __init__.py); `carmelolg.gapoly` is the package.
|
|
26
|
+
[tool.setuptools.packages.find]
|
|
27
|
+
where = ["src"]
|
|
28
|
+
include = ["carmelolg.gapoly*"]
|
|
29
|
+
namespaces = true
|
|
30
|
+
|
|
31
|
+
[tool.pytest.ini_options]
|
|
32
|
+
testpaths = ["tests"]
|
|
33
|
+
pythonpath = ["src"]
|
|
34
|
+
|
|
35
|
+
[tool.ruff]
|
|
36
|
+
line-length = 110
|
|
@@ -0,0 +1,153 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import argparse
|
|
4
|
+
import os
|
|
5
|
+
from pathlib import Path
|
|
6
|
+
|
|
7
|
+
import numpy as np
|
|
8
|
+
from carmelolg.galib import GenerationStats, GeneticAlgorithm, PrintProgress
|
|
9
|
+
from PIL import Image, ImageOps
|
|
10
|
+
|
|
11
|
+
from .help_format import colorize, use_color
|
|
12
|
+
from .problem import PolygonProblem
|
|
13
|
+
from .shapes import Limits
|
|
14
|
+
from .viewer import LiveView, SizeSchedule, Snapshots
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
class Progress(PrintProgress):
|
|
18
|
+
def format_line(self, stats: GenerationStats) -> str:
|
|
19
|
+
return (f"gen {stats.generation:6d} | best mse {stats.best_fitness:.5f} | "
|
|
20
|
+
f"mean {stats.mean_fitness:.5f} | polygons {len(stats.best_genome)}")
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
def load_target(path: Path, size: int) -> np.ndarray:
|
|
24
|
+
"""Load an image, scaled so its longest side is ``size`` pixels; float32 RGB in [0, 1]."""
|
|
25
|
+
image = ImageOps.exif_transpose(Image.open(path)).convert("RGB") # honour the camera's rotation
|
|
26
|
+
scale = size / max(image.size)
|
|
27
|
+
image = image.resize((max(1, round(image.width * scale)), max(1, round(image.height * scale))), Image.LANCZOS)
|
|
28
|
+
return np.asarray(image, dtype=np.float32) / 255.0
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
class _Formatter(argparse.ArgumentDefaultsHelpFormatter, argparse.RawDescriptionHelpFormatter):
|
|
32
|
+
"""Keep the line breaks of description / epilog, print every default value, colour it on a terminal."""
|
|
33
|
+
|
|
34
|
+
def format_help(self) -> str:
|
|
35
|
+
text = super().format_help()
|
|
36
|
+
return colorize(text) if use_color() else text
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
DESCRIPTION = """\
|
|
40
|
+
Ricrea una foto con poligoni semitrasparenti, usando un algoritmo genetico.
|
|
41
|
+
|
|
42
|
+
Ogni individuo è un'immagine fatta di poligoni (vertici e colore RGBA). A ogni generazione
|
|
43
|
+
sopravvivono gli individui più vicini alla foto (MSE più basso), si mutano e si incrociano.
|
|
44
|
+
"""
|
|
45
|
+
|
|
46
|
+
EPILOG = """\
|
|
47
|
+
Esempi:
|
|
48
|
+
prova veloce: gapoly foto.jpg --generations 300
|
|
49
|
+
più fedele: gapoly foto.jpg --generations 5000 --polygons 1500 --size 192 \\
|
|
50
|
+
--start-size 0.2 --max-size 0.04 --live
|
|
51
|
+
|
|
52
|
+
Tempi:
|
|
53
|
+
Una generazione costa circa population x polygons x size². Parti da valori piccoli,
|
|
54
|
+
leggi i secondi per generazione nel log (ogni 50) e poi scala.
|
|
55
|
+
A parità di tempo, poca popolazione e molte generazioni rendono di più di una popolazione enorme.
|
|
56
|
+
|
|
57
|
+
Output in --out: final.png, evolution.gif, history.csv, snapshots/gen_*.png.
|
|
58
|
+
"""
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
METAVARS = {
|
|
62
|
+
"generations": "N", "population": "N", "seed": "N", "polygons": "N", "initial_polygons": "N",
|
|
63
|
+
"start_size": "FRAZIONE", "max_size": "FRAZIONE", "mutations_per_child": "N", "mutation_rate": "0-1",
|
|
64
|
+
"crossover_rate": "0-1", "size": "PX", "output_width": "PX", "snapshot_every": "N", "history_every": "N", "out": "CARTELLA",
|
|
65
|
+
"workers": "N", "live_every": "N",
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
def main(argv: list[str] | None = None) -> int:
|
|
70
|
+
p = argparse.ArgumentParser(prog="gapoly", description=DESCRIPTION, epilog=EPILOG,
|
|
71
|
+
formatter_class=_Formatter, add_help=False)
|
|
72
|
+
p.add_argument("-h", "--help", action="help", help="mostra questo aiuto ed esci")
|
|
73
|
+
p.add_argument("target", type=Path, help="foto da riprodurre (JPEG, PNG...); la rotazione EXIF viene applicata")
|
|
74
|
+
|
|
75
|
+
run = p.add_argument_group("evoluzione")
|
|
76
|
+
run.add_argument("--generations", type=int, default=3000,
|
|
77
|
+
help="generazioni da evolvere: più ne fai, più l'immagine si avvicina alla foto")
|
|
78
|
+
run.add_argument("--population", type=int, default=40,
|
|
79
|
+
help="immagini candidate per generazione. Il costo cresce in modo lineare. "
|
|
80
|
+
"Non è il numero di poligoni (--polygons)")
|
|
81
|
+
run.add_argument("--seed", type=int, default=None,
|
|
82
|
+
help="seme casuale: stesso seme, stessa evoluzione. Senza seme ogni corsa è diversa")
|
|
83
|
+
|
|
84
|
+
shapes = p.add_argument_group("poligoni")
|
|
85
|
+
shapes.add_argument("--polygons", type=int, default=400,
|
|
86
|
+
help="poligoni massimi per immagine. Più poligoni permettono più dettaglio "
|
|
87
|
+
"e rallentano ogni valutazione")
|
|
88
|
+
shapes.add_argument("--initial-polygons", type=int, default=60,
|
|
89
|
+
help="poligoni di partenza di ogni individuo; salgono fino a --polygons")
|
|
90
|
+
shapes.add_argument("--start-size", type=float, default=0.5,
|
|
91
|
+
help="lato massimo di un poligono all'inizio, come frazione del lato dell'immagine "
|
|
92
|
+
"(0.5 = metà immagine). Poligoni grandi coprono subito le zone di colore uniforme")
|
|
93
|
+
shapes.add_argument("--max-size", type=float, default=0.12,
|
|
94
|
+
help="lato massimo finale. Il limite scende da --start-size a questo valore "
|
|
95
|
+
"nel primo 70 per cento delle generazioni, poi resta fisso. Più piccolo, più dettaglio")
|
|
96
|
+
|
|
97
|
+
ops = p.add_argument_group("operatori genetici")
|
|
98
|
+
ops.add_argument("--mutations-per-child", type=float, default=3.0,
|
|
99
|
+
help="poligoni modificati in media per figlio (vertice, spostamento, colore). "
|
|
100
|
+
"Troppi e quasi ogni figlio peggiora, pochi e l'evoluzione ristagna")
|
|
101
|
+
ops.add_argument("--mutation-rate", type=float, default=0.2,
|
|
102
|
+
help="probabilità, per figlio, di aggiungere un poligono, di rimuoverne uno "
|
|
103
|
+
"e di cambiare l'ordine di sovrapposizione (ognuna per conto suo, da 0 a 1)")
|
|
104
|
+
ops.add_argument("--crossover-rate", type=float, default=0.2,
|
|
105
|
+
help="probabilità che due genitori scambino una parte dei poligoni (da 0 a 1). "
|
|
106
|
+
"Con molti poligoni peggiora spesso i figli: tienila bassa")
|
|
107
|
+
|
|
108
|
+
res = p.add_argument_group("risoluzione e output")
|
|
109
|
+
res.add_argument("--size", type=int, default=96,
|
|
110
|
+
help="lato lungo in pixel a cui la foto viene ridotta per calcolare l'errore. "
|
|
111
|
+
"Decide velocità (cresce col quadrato) e dettaglio raggiungibile")
|
|
112
|
+
res.add_argument("--output-width", type=int, default=512,
|
|
113
|
+
help="larghezza in pixel di final.png e degli snapshot. Non cambia l'evoluzione: "
|
|
114
|
+
"i poligoni si ridisegnano nitidi a qualsiasi misura")
|
|
115
|
+
res.add_argument("--snapshot-every", type=int, default=100,
|
|
116
|
+
help="salva un PNG del migliore ogni N generazioni (1 = ogni generazione)")
|
|
117
|
+
res.add_argument("--history-every", type=int, default=1000,
|
|
118
|
+
help="conserva in memoria il genoma migliore di una generazione ogni N, e di tutte le altre "
|
|
119
|
+
"solo l'errore. Evita che una corsa lunga con molti poligoni riempia la RAM "
|
|
120
|
+
"(history.csv e risultato finale non cambiano)")
|
|
121
|
+
res.add_argument("--out", type=Path, default=None,
|
|
122
|
+
help="cartella di output. Se manca: out/<nome della foto>")
|
|
123
|
+
|
|
124
|
+
perf = p.add_argument_group("prestazioni e finestra live")
|
|
125
|
+
perf.add_argument("--workers", type=int, default=os.cpu_count() or 1,
|
|
126
|
+
help="worker che valutano gli individui in parallelo (vedi --parallel). 1 = nessun parallelismo; "
|
|
127
|
+
"il default è il numero di CPU")
|
|
128
|
+
perf.add_argument("--parallel", choices=["thread", "process"], default="thread",
|
|
129
|
+
help="tipo di worker. thread: il rendering Numba rilascia il GIL, nessuna copia dei dati. "
|
|
130
|
+
"process: processi separati (più memoria, utile solo se la fitness non rilascia il GIL)")
|
|
131
|
+
perf.add_argument("--live", action="store_true",
|
|
132
|
+
help="apre una finestra con foto, miglior immagine e curva dell'errore; "
|
|
133
|
+
"i pannelli seguono l'orientamento della foto")
|
|
134
|
+
perf.add_argument("--live-every", type=int, default=10,
|
|
135
|
+
help="aggiorna la finestra ogni N generazioni (richiede --live). Valori bassi la rallentano")
|
|
136
|
+
for action in p._actions: # short value placeholders read better than GENERATIONS, MAX_SIZE...
|
|
137
|
+
action.metavar = METAVARS.get(action.dest, action.metavar)
|
|
138
|
+
args = p.parse_args(argv)
|
|
139
|
+
|
|
140
|
+
out = args.out or Path("out") / args.target.stem
|
|
141
|
+
out.mkdir(parents=True, exist_ok=True)
|
|
142
|
+
problem = PolygonProblem(load_target(args.target, args.size), Limits(max_polygons=args.polygons, max_size=max(args.start_size, args.max_size)),
|
|
143
|
+
args.initial_polygons, args.mutations_per_child)
|
|
144
|
+
callbacks = [Progress(every=50), Snapshots(problem, out, args.snapshot_every, args.output_width),
|
|
145
|
+
SizeSchedule(problem, args.max_size, args.generations)]
|
|
146
|
+
if args.live:
|
|
147
|
+
callbacks.append(LiveView(problem, args.live_every))
|
|
148
|
+
result = GeneticAlgorithm(problem, population_size=args.population, max_generations=args.generations,
|
|
149
|
+
mutation_rate=args.mutation_rate, crossover_rate=args.crossover_rate, callbacks=callbacks, seed=args.seed, diversity=None,
|
|
150
|
+
history_genome_every=args.history_every,
|
|
151
|
+
workers=args.workers if args.workers > 1 else None, parallel=args.parallel).run()
|
|
152
|
+
print(f"best mse {result.best.fitness:.5f} after {result.generations} generations -> {out}/")
|
|
153
|
+
return 0
|
|
@@ -0,0 +1,87 @@
|
|
|
1
|
+
"""Numba rasteriser: draws a whole genome in one compiled loop (no Python per polygon, no allocations).
|
|
2
|
+
|
|
3
|
+
Pixels are sampled at their centres and a polygon covers a pixel by the even-odd rule. The kernels release the
|
|
4
|
+
GIL (``nogil``), so threads evaluate several genomes in parallel.
|
|
5
|
+
"""
|
|
6
|
+
from __future__ import annotations
|
|
7
|
+
|
|
8
|
+
import numpy as np
|
|
9
|
+
from numba import njit
|
|
10
|
+
|
|
11
|
+
from .shapes import ( # column layout: see shapes.py
|
|
12
|
+
ALPHA,
|
|
13
|
+
BLUE,
|
|
14
|
+
GREEN,
|
|
15
|
+
MAX_VERTICES,
|
|
16
|
+
N_VERTICES,
|
|
17
|
+
RED,
|
|
18
|
+
VERTEX_START,
|
|
19
|
+
)
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
@njit(cache=True, nogil=True, fastmath=True)
|
|
23
|
+
def _draw(genome, canvas): # type: ignore[no-untyped-def]
|
|
24
|
+
height, width = canvas.shape[0], canvas.shape[1]
|
|
25
|
+
xs = np.empty(MAX_VERTICES, dtype=np.float32)
|
|
26
|
+
ys = np.empty(MAX_VERTICES, dtype=np.float32)
|
|
27
|
+
for k in range(genome.shape[0]):
|
|
28
|
+
n = int(genome[k, N_VERTICES])
|
|
29
|
+
if n < 3:
|
|
30
|
+
continue
|
|
31
|
+
min_x, max_x = width, 0.0
|
|
32
|
+
min_y, max_y = height, 0.0
|
|
33
|
+
for v in range(n):
|
|
34
|
+
xs[v] = genome[k, VERTEX_START + 2 * v] * width
|
|
35
|
+
ys[v] = genome[k, VERTEX_START + 2 * v + 1] * height
|
|
36
|
+
min_x, max_x = min(min_x, xs[v]), max(max_x, xs[v])
|
|
37
|
+
min_y, max_y = min(min_y, ys[v]), max(max_y, ys[v])
|
|
38
|
+
x0, x1 = max(0, int(np.floor(min_x))), min(width, int(np.ceil(max_x)) + 1)
|
|
39
|
+
y0, y1 = max(0, int(np.floor(min_y))), min(height, int(np.ceil(max_y)) + 1)
|
|
40
|
+
alpha = genome[k, ALPHA]
|
|
41
|
+
keep = 1.0 - alpha
|
|
42
|
+
r = genome[k, RED] * alpha
|
|
43
|
+
g = genome[k, GREEN] * alpha
|
|
44
|
+
b = genome[k, BLUE] * alpha
|
|
45
|
+
for py in range(y0, y1):
|
|
46
|
+
yc = py + 0.5
|
|
47
|
+
for px in range(x0, x1):
|
|
48
|
+
xc = px + 0.5
|
|
49
|
+
inside = False
|
|
50
|
+
j = n - 1
|
|
51
|
+
for i in range(n):
|
|
52
|
+
if (ys[i] > yc) != (ys[j] > yc) and xc < (xs[j] - xs[i]) * (yc - ys[i]) / (ys[j] - ys[i]) + xs[i]:
|
|
53
|
+
inside = not inside
|
|
54
|
+
j = i
|
|
55
|
+
if inside:
|
|
56
|
+
canvas[py, px, 0] = canvas[py, px, 0] * keep + r
|
|
57
|
+
canvas[py, px, 1] = canvas[py, px, 1] * keep + g
|
|
58
|
+
canvas[py, px, 2] = canvas[py, px, 2] * keep + b
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
@njit(cache=True, nogil=True, fastmath=True)
|
|
62
|
+
def render_into(genome, background, canvas): # type: ignore[no-untyped-def]
|
|
63
|
+
for y in range(canvas.shape[0]):
|
|
64
|
+
for x in range(canvas.shape[1]):
|
|
65
|
+
for c in range(3):
|
|
66
|
+
canvas[y, x, c] = background[c]
|
|
67
|
+
_draw(genome, canvas)
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
@njit(cache=True, nogil=True, fastmath=True)
|
|
71
|
+
def render_mse(genome, target, background): # type: ignore[no-untyped-def]
|
|
72
|
+
"""Mean squared error between the rendered genome and ``target`` (float32, (h, w, 3))."""
|
|
73
|
+
canvas = np.empty_like(target)
|
|
74
|
+
render_into(genome, background, canvas)
|
|
75
|
+
total = 0.0
|
|
76
|
+
for y in range(target.shape[0]):
|
|
77
|
+
for x in range(target.shape[1]):
|
|
78
|
+
for c in range(3):
|
|
79
|
+
d = canvas[y, x, c] - target[y, x, c]
|
|
80
|
+
total += d * d
|
|
81
|
+
return total / target.size
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
def render_image(genome: np.ndarray, width: int, height: int, background: np.ndarray) -> np.ndarray:
|
|
85
|
+
canvas = np.empty((height, width, 3), dtype=np.float32)
|
|
86
|
+
render_into(np.ascontiguousarray(genome, dtype=np.float32), background, canvas)
|
|
87
|
+
return canvas
|
|
@@ -0,0 +1,96 @@
|
|
|
1
|
+
"""Coloured ``--help``: argparse builds the plain text, this module paints it.
|
|
2
|
+
|
|
3
|
+
Colours are added only on a terminal (and not when ``NO_COLOR`` is set; ``FORCE_COLOR`` forces them).
|
|
4
|
+
They never change the layout: removing the escape codes gives back the plain help text.
|
|
5
|
+
"""
|
|
6
|
+
from __future__ import annotations
|
|
7
|
+
|
|
8
|
+
import os
|
|
9
|
+
import re
|
|
10
|
+
import sys
|
|
11
|
+
|
|
12
|
+
RESET = "\033[0m"
|
|
13
|
+
BOLD = "\033[1m"
|
|
14
|
+
DIM = "\033[2m"
|
|
15
|
+
GREEN = "\033[32m"
|
|
16
|
+
YELLOW = "\033[33m"
|
|
17
|
+
BOLD_CYAN = "\033[1;36m"
|
|
18
|
+
BOLD_MAGENTA = "\033[1;35m"
|
|
19
|
+
|
|
20
|
+
_OPTION = re.compile(r"(?<![\w-])(--?[A-Za-z][\w-]*)")
|
|
21
|
+
_METAVAR = re.compile(r"\b([A-Z][A-Z_]+|[A-Z]|0-1)\b")
|
|
22
|
+
_DEFAULT = re.compile(r"\(default:[^)]*\)")
|
|
23
|
+
_INVOCATION = re.compile(r"^( -\S.*?)(\s{2,})(\S.*)?$")
|
|
24
|
+
_POSITIONAL = re.compile(r"^ (target)(?=\s)")
|
|
25
|
+
_HEADING = re.compile(r"^\S.*:$")
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
def use_color() -> bool:
|
|
29
|
+
if os.environ.get("NO_COLOR"):
|
|
30
|
+
return False
|
|
31
|
+
if os.environ.get("FORCE_COLOR"):
|
|
32
|
+
return True
|
|
33
|
+
return sys.stdout.isatty()
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
def _paint(text: str, code: str) -> str:
|
|
37
|
+
return f"{code}{text}{RESET}"
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
def _paint_options(text: str) -> str:
|
|
41
|
+
return _OPTION.sub(lambda m: _paint(m.group(1), GREEN), text)
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
def _paint_invocation(text: str) -> str:
|
|
45
|
+
"""Option names green, value placeholders (N, PX, 0-1...) yellow."""
|
|
46
|
+
parts = re.split(r"(--?[A-Za-z][\w-]*)", text)
|
|
47
|
+
return "".join(
|
|
48
|
+
_paint(part, GREEN) if i % 2 else _METAVAR.sub(lambda m: _paint(m.group(1), YELLOW), part)
|
|
49
|
+
for i, part in enumerate(parts)
|
|
50
|
+
)
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
def _dim_defaults(text: str) -> str:
|
|
54
|
+
def dim(match: re.Match[str]) -> str: # a default can wrap onto two lines: close the colour per line
|
|
55
|
+
return "\n".join(_paint(line, DIM) for line in match.group(0).split("\n"))
|
|
56
|
+
|
|
57
|
+
return _DEFAULT.sub(dim, text)
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
def colorize(text: str) -> str:
|
|
61
|
+
if "\033[" in text: # already coloured (newer argparse versions do it themselves)
|
|
62
|
+
return text
|
|
63
|
+
lines = _dim_defaults(text).split("\n")
|
|
64
|
+
in_usage = True
|
|
65
|
+
title_done = False
|
|
66
|
+
out: list[str] = []
|
|
67
|
+
for line in lines:
|
|
68
|
+
plain = re.sub(r"\033\[[0-9;]*m", "", line)
|
|
69
|
+
if in_usage:
|
|
70
|
+
if not plain.strip():
|
|
71
|
+
in_usage = False
|
|
72
|
+
out.append(line)
|
|
73
|
+
continue
|
|
74
|
+
line = line.replace("usage:", _paint("usage:", BOLD), 1)
|
|
75
|
+
out.append(_paint_invocation(line) if not plain.startswith("usage:") else _usage_line(line))
|
|
76
|
+
continue
|
|
77
|
+
if not title_done and plain.strip():
|
|
78
|
+
title_done = True
|
|
79
|
+
out.append(_paint(line, BOLD))
|
|
80
|
+
continue
|
|
81
|
+
if _HEADING.match(plain):
|
|
82
|
+
out.append(_paint(line, BOLD_CYAN))
|
|
83
|
+
continue
|
|
84
|
+
match = _INVOCATION.match(plain)
|
|
85
|
+
if match and match.group(1) == plain[: len(match.group(1))]:
|
|
86
|
+
left_len = len(match.group(1))
|
|
87
|
+
out.append(_paint_invocation(line[:left_len]) + _paint_options(line[left_len:]))
|
|
88
|
+
continue
|
|
89
|
+
line = _POSITIONAL.sub(lambda m: " " + _paint(m.group(1), YELLOW), line)
|
|
90
|
+
out.append(_paint_options(line))
|
|
91
|
+
return "\n".join(out).replace("gapoly", _paint("gapoly", BOLD_MAGENTA))
|
|
92
|
+
|
|
93
|
+
|
|
94
|
+
def _usage_line(line: str) -> str:
|
|
95
|
+
head, _, rest = line.partition("gapoly")
|
|
96
|
+
return head + "gapoly" + _paint_invocation(rest)
|
|
@@ -0,0 +1,82 @@
|
|
|
1
|
+
"""Mutation and crossover on array genomes. Inputs are never modified."""
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
|
|
4
|
+
import math
|
|
5
|
+
from random import Random
|
|
6
|
+
|
|
7
|
+
import numpy as np
|
|
8
|
+
|
|
9
|
+
from .shapes import ALPHA, GREEN, N_VERTICES, RED, Genome, Limits, X, Y, clamp, extent, random_row
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
def _selected(rng: Random, count: int, probability: float) -> list[int]:
|
|
13
|
+
"""Indices in ``range(count)`` picked independently with ``probability`` (geometric jumps: one draw per pick)."""
|
|
14
|
+
if probability >= 1.0:
|
|
15
|
+
return list(range(count))
|
|
16
|
+
if probability <= 0.0:
|
|
17
|
+
return []
|
|
18
|
+
log_miss = math.log1p(-probability)
|
|
19
|
+
picked, i = [], -1
|
|
20
|
+
while True:
|
|
21
|
+
i += 1 + int(math.log(1.0 - rng.random()) / log_miss)
|
|
22
|
+
if i >= count:
|
|
23
|
+
return picked
|
|
24
|
+
picked.append(i)
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
def move_vertex(row: np.ndarray, rng: Random, limits: Limits, sigma: float = 0.015) -> None:
|
|
28
|
+
"""Move one vertex in place (``row`` is a private copy); undone if the polygon would grow past the cap."""
|
|
29
|
+
before, old = row.copy(), extent(row)
|
|
30
|
+
v = rng.randrange(int(row[N_VERTICES]))
|
|
31
|
+
row[X(v)] = clamp(float(row[X(v)]) + rng.gauss(0, sigma))
|
|
32
|
+
row[Y(v)] = clamp(float(row[Y(v)]) + rng.gauss(0, sigma))
|
|
33
|
+
if extent(row) > max(limits.max_size, old): # never grow past the cap
|
|
34
|
+
row[:] = before
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
def shift_polygon(row: np.ndarray, rng: Random, sigma: float = 0.02) -> None:
|
|
38
|
+
dx, dy = rng.gauss(0, sigma), rng.gauss(0, sigma)
|
|
39
|
+
for v in range(int(row[N_VERTICES])):
|
|
40
|
+
row[X(v)] = clamp(float(row[X(v)]) + dx)
|
|
41
|
+
row[Y(v)] = clamp(float(row[Y(v)]) + dy)
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
def change_color(row: np.ndarray, rng: Random, limits: Limits, sigma: float = 0.06) -> None:
|
|
45
|
+
for channel in range(RED, GREEN + 2): # red, green, blue
|
|
46
|
+
row[channel] = clamp(float(row[channel]) + rng.gauss(0, sigma))
|
|
47
|
+
row[ALPHA] = clamp(float(row[ALPHA]) + rng.gauss(0, sigma), limits.min_alpha, limits.max_alpha)
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
def mutate(genome: Genome, rng: Random, rate: float, limits: Limits, per_polygon: float | None = None) -> Genome:
|
|
51
|
+
"""``per_polygon``: probability that each polygon changes shape / colour (default ``rate``).
|
|
52
|
+
``rate``: probability, per genome, of each add / remove / reorder operation."""
|
|
53
|
+
g = genome.copy()
|
|
54
|
+
p = rate if per_polygon is None else per_polygon
|
|
55
|
+
for k in _selected(rng, len(g), p):
|
|
56
|
+
if rng.random() < 0.7:
|
|
57
|
+
move_vertex(g[k], rng, limits)
|
|
58
|
+
else:
|
|
59
|
+
shift_polygon(g[k], rng)
|
|
60
|
+
for k in _selected(rng, len(g), p):
|
|
61
|
+
change_color(g[k], rng, limits)
|
|
62
|
+
if rng.random() < rate and len(g) < limits.max_polygons:
|
|
63
|
+
g = np.insert(g, rng.randrange(len(g) + 1), random_row(rng, limits), axis=0)
|
|
64
|
+
if rng.random() < rate and len(g) > limits.min_polygons:
|
|
65
|
+
g = np.delete(g, rng.randrange(len(g)), axis=0)
|
|
66
|
+
if rng.random() < rate and len(g) > 1: # change overlap order
|
|
67
|
+
source = rng.randrange(len(g))
|
|
68
|
+
row = g[source].copy()
|
|
69
|
+
g = np.insert(np.delete(g, source, axis=0), rng.randrange(len(g)), row, axis=0)
|
|
70
|
+
return g
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
def crossover(a: Genome, b: Genome, rng: Random, limits: Limits) -> tuple[Genome, Genome]:
|
|
74
|
+
"""Swap tails of the two polygon lists (cut points differ per parent, so lengths change)."""
|
|
75
|
+
cut_a, cut_b = rng.randint(0, len(a)), rng.randint(0, len(b))
|
|
76
|
+
return (_fit(np.concatenate((a[:cut_a], b[cut_b:])), a, limits),
|
|
77
|
+
_fit(np.concatenate((b[:cut_b], a[cut_a:])), b, limits))
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
def _fit(child: Genome, fallback: Genome, limits: Limits) -> Genome:
|
|
81
|
+
child = child[: limits.max_polygons]
|
|
82
|
+
return child if len(child) >= limits.min_polygons else fallback.copy()
|
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
"""GALib Problem: minimise the MSE between the rendered polygons and the target image."""
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
|
|
4
|
+
from random import Random
|
|
5
|
+
|
|
6
|
+
import numpy as np
|
|
7
|
+
from carmelolg.galib import Problem
|
|
8
|
+
|
|
9
|
+
from . import operators
|
|
10
|
+
from .fast_render import render_mse
|
|
11
|
+
from .render import Array, render
|
|
12
|
+
from .shapes import COLS, Genome, Limits, random_row
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
class PolygonProblem(Problem[Genome]):
|
|
16
|
+
maximize = False # fitness is an error: lower is better
|
|
17
|
+
|
|
18
|
+
def __init__(self, target: Array, limits: Limits | None = None, initial_polygons: int = 20,
|
|
19
|
+
mutations_per_child: float = 3.0) -> None:
|
|
20
|
+
self.target = np.ascontiguousarray(target, dtype=np.float32) # (height, width, 3), values in [0, 1]
|
|
21
|
+
self.height, self.width = self.target.shape[:2]
|
|
22
|
+
self.limits = limits or Limits()
|
|
23
|
+
self.mutations_per_child = mutations_per_child # expected polygons edited per child, whatever the genome size
|
|
24
|
+
self.initial_polygons = max(self.limits.min_polygons, min(initial_polygons, self.limits.max_polygons))
|
|
25
|
+
self.background = tuple(float(c) for c in self.target.reshape(-1, 3).mean(axis=0))
|
|
26
|
+
self._background = np.asarray(self.background, dtype=np.float32)
|
|
27
|
+
render_mse(np.zeros((0, COLS), dtype=np.float32), self.target, self._background) # compile before any thread
|
|
28
|
+
|
|
29
|
+
def render(self, genome: Genome, width: int | None = None, height: int | None = None) -> Array:
|
|
30
|
+
return render(genome, width or self.width, height or self.height, self.background) # type: ignore[arg-type]
|
|
31
|
+
|
|
32
|
+
def random_genome(self, rng: Random) -> Genome:
|
|
33
|
+
rows = []
|
|
34
|
+
for _ in range(self.initial_polygons):
|
|
35
|
+
cx, cy = rng.random(), rng.random()
|
|
36
|
+
color = self.target[min(int(cy * self.height), self.height - 1), min(int(cx * self.width), self.width - 1)]
|
|
37
|
+
rows.append(random_row(rng, self.limits, tuple(float(c) for c in color), (cx, cy)))
|
|
38
|
+
return np.stack(rows)
|
|
39
|
+
|
|
40
|
+
def fitness(self, genome: Genome) -> float:
|
|
41
|
+
return float(render_mse(genome, self.target, self._background))
|
|
42
|
+
|
|
43
|
+
def mutate(self, genome: Genome, rng: Random, rate: float) -> Genome:
|
|
44
|
+
per_polygon = min(1.0, self.mutations_per_child / max(1, len(genome)))
|
|
45
|
+
return operators.mutate(genome, rng, rate, self.limits, per_polygon)
|
|
46
|
+
|
|
47
|
+
def crossover(self, a: Genome, b: Genome, rng: Random) -> tuple[Genome, Genome]:
|
|
48
|
+
return operators.crossover(a, b, rng, self.limits)
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
"""Rendering helpers on top of the numba kernels."""
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
|
|
4
|
+
import numpy as np
|
|
5
|
+
from numpy.typing import NDArray
|
|
6
|
+
from PIL import Image
|
|
7
|
+
|
|
8
|
+
from .fast_render import render_image
|
|
9
|
+
from .shapes import Genome
|
|
10
|
+
|
|
11
|
+
Array = NDArray[np.float32]
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
def render(genome: Genome, width: int, height: int, background: tuple[float, float, float]) -> Array:
|
|
15
|
+
"""RGB float32 image in [0, 1], shape (height, width, 3)."""
|
|
16
|
+
return render_image(genome, width, height, np.asarray(background, dtype=np.float32))
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
def to_image(array: Array) -> Image.Image:
|
|
20
|
+
return Image.fromarray((np.clip(array, 0.0, 1.0) * 255.0 + 0.5).astype(np.uint8), "RGB")
|
|
@@ -0,0 +1,116 @@
|
|
|
1
|
+
"""Genome layout and limits.
|
|
2
|
+
|
|
3
|
+
A genome is a float32 array of shape ``(polygons, COLS)``: one row per polygon, drawn top to bottom in row
|
|
4
|
+
order (later rows on top). Every value is in [0, 1]; coordinates are fractions of the image side, so a genome
|
|
5
|
+
renders at any resolution.
|
|
6
|
+
|
|
7
|
+
Layout of one row (17 columns)::
|
|
8
|
+
|
|
9
|
+
column: 0 | 1 2 | 3 4 | ... | 11 12 | 13 14 15 16
|
|
10
|
+
meaning: n | x0 y0 x1 y1 ... x5 y5 | r g b a
|
|
11
|
+
|
|
12
|
+
- ``n`` is how many vertices are used (3 to 6); the vertices after the n-th are ignored.
|
|
13
|
+
- ``r g b`` is the colour, ``a`` the opacity of the polygon (0 transparent, 1 opaque).
|
|
14
|
+
|
|
15
|
+
Example: a half-transparent red triangle::
|
|
16
|
+
|
|
17
|
+
[3, 0.10 0.10, 0.30 0.10, 0.20 0.30, 0 0 0 0 0 0, 1.0 0.0 0.0 0.5]
|
|
18
|
+
|
|
19
|
+
Never index a row with bare numbers: use ``N_VERTICES``, ``X(v)``, ``Y(v)``, ``RED``..``ALPHA``, ``vertices``,
|
|
20
|
+
``color`` and ``make_row``. ``describe(genome)`` prints a genome as text, handy when debugging.
|
|
21
|
+
"""
|
|
22
|
+
from __future__ import annotations
|
|
23
|
+
|
|
24
|
+
from dataclasses import dataclass
|
|
25
|
+
from random import Random
|
|
26
|
+
|
|
27
|
+
import numpy as np
|
|
28
|
+
from numpy.typing import NDArray
|
|
29
|
+
|
|
30
|
+
MAX_VERTICES = 6
|
|
31
|
+
|
|
32
|
+
N_VERTICES = 0 # column holding the number of vertices used
|
|
33
|
+
VERTEX_START = 1 # first vertex coordinate; vertex v is at columns X(v), Y(v)
|
|
34
|
+
RED = VERTEX_START + 2 * MAX_VERTICES # 13
|
|
35
|
+
GREEN, BLUE, ALPHA = RED + 1, RED + 2, RED + 3
|
|
36
|
+
COLS = ALPHA + 1 # 17
|
|
37
|
+
|
|
38
|
+
Genome = NDArray[np.float32]
|
|
39
|
+
Row = NDArray[np.float32]
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
def X(vertex: int) -> int:
|
|
43
|
+
"""Column of the x coordinate of vertex number ``vertex`` (0-based)."""
|
|
44
|
+
return VERTEX_START + 2 * vertex
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
def Y(vertex: int) -> int:
|
|
48
|
+
"""Column of the y coordinate of vertex number ``vertex`` (0-based)."""
|
|
49
|
+
return VERTEX_START + 2 * vertex + 1
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
@dataclass(frozen=True)
|
|
53
|
+
class Limits:
|
|
54
|
+
min_polygons: int = 1
|
|
55
|
+
max_polygons: int = 150
|
|
56
|
+
min_vertices: int = 3
|
|
57
|
+
max_vertices: int = MAX_VERTICES
|
|
58
|
+
min_alpha: float = 0.05
|
|
59
|
+
max_alpha: float = 0.95
|
|
60
|
+
max_size: float = 0.12 # max width / height of a polygon, as a fraction of the image side
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
def clamp(value: float, low: float = 0.0, high: float = 1.0) -> float:
|
|
64
|
+
return low if value < low else min(value, high)
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
def empty_genome() -> Genome:
|
|
68
|
+
return np.zeros((0, COLS), dtype=np.float32)
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
def make_row(points: list[tuple[float, float]], rgba: tuple[float, float, float, float]) -> Row:
|
|
72
|
+
"""Build one polygon row from its vertices ``[(x, y), ...]`` and its colour ``(r, g, b, a)``."""
|
|
73
|
+
row = np.zeros(COLS, dtype=np.float32)
|
|
74
|
+
row[N_VERTICES] = len(points)
|
|
75
|
+
for v, (x, y) in enumerate(points):
|
|
76
|
+
row[X(v)], row[Y(v)] = x, y
|
|
77
|
+
row[RED : ALPHA + 1] = rgba
|
|
78
|
+
return row
|
|
79
|
+
|
|
80
|
+
|
|
81
|
+
def vertices(row: Row) -> tuple[NDArray[np.float32], NDArray[np.float32]]:
|
|
82
|
+
"""The used x and y coordinates of a polygon (views into the row)."""
|
|
83
|
+
n = int(row[N_VERTICES])
|
|
84
|
+
return row[VERTEX_START : VERTEX_START + 2 * n : 2], row[VERTEX_START + 1 : VERTEX_START + 2 * n : 2]
|
|
85
|
+
|
|
86
|
+
|
|
87
|
+
def color(row: Row) -> NDArray[np.float32]:
|
|
88
|
+
"""The ``(r, g, b, a)`` of a polygon (a view into the row)."""
|
|
89
|
+
return row[RED : ALPHA + 1]
|
|
90
|
+
|
|
91
|
+
|
|
92
|
+
def extent(row: Row) -> float:
|
|
93
|
+
xs, ys = vertices(row)
|
|
94
|
+
return float(max(xs.max() - xs.min(), ys.max() - ys.min()))
|
|
95
|
+
|
|
96
|
+
|
|
97
|
+
def describe(genome: Genome) -> str:
|
|
98
|
+
"""One line per polygon, in drawing order: vertices and colour."""
|
|
99
|
+
lines = []
|
|
100
|
+
for k, row in enumerate(genome):
|
|
101
|
+
xs, ys = vertices(row)
|
|
102
|
+
points = " ".join(f"({x:.2f},{y:.2f})" for x, y in zip(xs, ys, strict=True))
|
|
103
|
+
r, g, b, a = color(row)
|
|
104
|
+
lines.append(f"#{k} {len(xs)} vertices {points} rgba({r:.2f},{g:.2f},{b:.2f},{a:.2f})")
|
|
105
|
+
return "\n".join(lines)
|
|
106
|
+
|
|
107
|
+
|
|
108
|
+
def random_row(rng: Random, limits: Limits, rgb: tuple[float, float, float] | None = None,
|
|
109
|
+
center: tuple[float, float] | None = None) -> Row:
|
|
110
|
+
"""Small random polygon around ``center`` (random if omitted). ``rgb`` is the colour; alpha is random."""
|
|
111
|
+
spread = limits.max_size / 2
|
|
112
|
+
cx, cy = center if center is not None else (rng.random(), rng.random())
|
|
113
|
+
n = rng.randint(limits.min_vertices, limits.max_vertices)
|
|
114
|
+
points = [(clamp(cx + rng.uniform(-spread, spread)), clamp(cy + rng.uniform(-spread, spread))) for _ in range(n)]
|
|
115
|
+
rgb = rgb if rgb is not None else (rng.random(), rng.random(), rng.random())
|
|
116
|
+
return make_row(points, (*rgb, rng.uniform(max(limits.min_alpha, 0.1), min(limits.max_alpha, 0.6))))
|
|
@@ -0,0 +1,126 @@
|
|
|
1
|
+
"""Callbacks that show or save the best image while the algorithm runs."""
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
|
|
4
|
+
import csv
|
|
5
|
+
from collections.abc import Iterator
|
|
6
|
+
from dataclasses import replace
|
|
7
|
+
from pathlib import Path
|
|
8
|
+
from typing import Any, TextIO
|
|
9
|
+
|
|
10
|
+
from carmelolg.galib import Callback, GenerationStats, GeneticAlgorithm, Result
|
|
11
|
+
from PIL import Image
|
|
12
|
+
|
|
13
|
+
from .problem import PolygonProblem
|
|
14
|
+
from .render import to_image
|
|
15
|
+
from .shapes import empty_genome
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
class SizeSchedule(Callback):
|
|
19
|
+
"""Coarse to fine: the polygon size cap shrinks (log scale) from its starting value to ``final`` by
|
|
20
|
+
``until`` (fraction of the run), then stays there. New and mutated polygons obey the current cap."""
|
|
21
|
+
|
|
22
|
+
def __init__(self, problem: PolygonProblem, final: float, total_generations: int, until: float = 0.7) -> None:
|
|
23
|
+
self.problem, self.final = problem, final
|
|
24
|
+
self.start = problem.limits.max_size
|
|
25
|
+
self.span = max(1.0, total_generations * until)
|
|
26
|
+
|
|
27
|
+
def on_generation(self, stats: GenerationStats[Any], engine: GeneticAlgorithm[Any]) -> None:
|
|
28
|
+
t = min(1.0, stats.generation / self.span)
|
|
29
|
+
size = self.start * (self.final / self.start) ** t
|
|
30
|
+
self.problem.limits = replace(self.problem.limits, max_size=size)
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
class Snapshots(Callback):
|
|
34
|
+
"""Write the run to disk as it goes, keeping nothing in memory.
|
|
35
|
+
|
|
36
|
+
- every ``every`` generations: ``snapshots/gen_NNNNNN.png`` (``output_width`` px);
|
|
37
|
+
- every generation: one row of ``history.csv`` (flushed at each snapshot, so it survives an interruption);
|
|
38
|
+
- at the end: ``final.png``, and ``evolution.gif`` composed from the PNG files on disk, one frame at a time.
|
|
39
|
+
"""
|
|
40
|
+
|
|
41
|
+
def __init__(self, problem: PolygonProblem, out_dir: Path, every: int = 100, output_width: int = 512,
|
|
42
|
+
frame_width: int = 256) -> None:
|
|
43
|
+
self.problem, self.out_dir, self.every = problem, out_dir, max(1, every)
|
|
44
|
+
self.output_width, self.frame_width = output_width, frame_width
|
|
45
|
+
self.snapshots = out_dir / "snapshots"
|
|
46
|
+
self.snapshots.mkdir(parents=True, exist_ok=True)
|
|
47
|
+
self._csv_file: TextIO | None = None
|
|
48
|
+
self._csv: Any = None
|
|
49
|
+
|
|
50
|
+
def _image(self, genome: Any, width: int) -> Image.Image:
|
|
51
|
+
height = round(width * self.problem.height / self.problem.width)
|
|
52
|
+
return to_image(self.problem.render(genome, width, height))
|
|
53
|
+
|
|
54
|
+
def on_start(self, engine: GeneticAlgorithm[Any]) -> None:
|
|
55
|
+
self._csv_file = open(self.out_dir / "history.csv", "w", newline="") # noqa: SIM115 (closed in on_end)
|
|
56
|
+
self._csv = csv.writer(self._csv_file)
|
|
57
|
+
self._csv.writerow(["generation", "best_mse", "mean_mse", "polygons"])
|
|
58
|
+
|
|
59
|
+
def on_generation(self, stats: GenerationStats[Any], engine: GeneticAlgorithm[Any]) -> None:
|
|
60
|
+
self._csv.writerow([stats.generation, stats.best_fitness, stats.mean_fitness, len(stats.best_genome)])
|
|
61
|
+
if stats.generation % self.every:
|
|
62
|
+
return
|
|
63
|
+
self._image(stats.best_genome, self.output_width).save(self.snapshots / f"gen_{stats.generation:06d}.png")
|
|
64
|
+
if self._csv_file is not None:
|
|
65
|
+
self._csv_file.flush()
|
|
66
|
+
|
|
67
|
+
def on_end(self, result: Result[Any], engine: GeneticAlgorithm[Any]) -> None:
|
|
68
|
+
if self._csv_file is not None:
|
|
69
|
+
self._csv_file.close()
|
|
70
|
+
self._image(result.best.genome, self.output_width).save(self.out_dir / "final.png")
|
|
71
|
+
self._write_gif()
|
|
72
|
+
|
|
73
|
+
def _frames(self) -> Iterator[Image.Image]:
|
|
74
|
+
height = round(self.frame_width * self.problem.height / self.problem.width)
|
|
75
|
+
for path in [*sorted(self.snapshots.glob("gen_*.png")), self.out_dir / "final.png"]:
|
|
76
|
+
with Image.open(path) as image:
|
|
77
|
+
yield image.convert("RGB").resize((self.frame_width, height), Image.LANCZOS)
|
|
78
|
+
|
|
79
|
+
def _write_gif(self) -> None:
|
|
80
|
+
frames = self._frames()
|
|
81
|
+
first = next(frames)
|
|
82
|
+
first.save(self.out_dir / "evolution.gif", save_all=True, append_images=frames, duration=120, loop=0)
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
class LiveView(Callback):
|
|
86
|
+
"""matplotlib window: target | best render | error curve. Needs ``pip install matplotlib``."""
|
|
87
|
+
|
|
88
|
+
def __init__(self, problem: PolygonProblem, every: int = 10) -> None:
|
|
89
|
+
import matplotlib.pyplot as plt
|
|
90
|
+
|
|
91
|
+
self.plt, self.problem, self.every = plt, problem, max(1, every)
|
|
92
|
+
plt.ion()
|
|
93
|
+
# Landscape photo: panels stacked in a column (wide images fit). Portrait or square: side by side.
|
|
94
|
+
landscape = problem.width > problem.height
|
|
95
|
+
aspect = problem.height / problem.width
|
|
96
|
+
if landscape:
|
|
97
|
+
self.fig, (a_target, self.a_best, self.a_curve) = plt.subplots(3, 1, figsize=(6, 2 * 6 * aspect + 3))
|
|
98
|
+
else:
|
|
99
|
+
self.fig, (a_target, self.a_best, self.a_curve) = plt.subplots(1, 3, figsize=(3 * 4.2, 4.2 * aspect + 1))
|
|
100
|
+
a_target.imshow(problem.target)
|
|
101
|
+
a_target.set_title("target")
|
|
102
|
+
self.a_best.axis("off")
|
|
103
|
+
a_target.axis("off")
|
|
104
|
+
self.image = self.a_best.imshow(problem.render(empty_genome()))
|
|
105
|
+
self.a_curve.set_xlabel("generation")
|
|
106
|
+
self.a_curve.set_ylabel("MSE")
|
|
107
|
+
(self.line,) = self.a_curve.plot([], [])
|
|
108
|
+
self.x: list[int] = []
|
|
109
|
+
self.y: list[float] = []
|
|
110
|
+
|
|
111
|
+
def on_generation(self, stats: GenerationStats[Any], engine: GeneticAlgorithm[Any]) -> None:
|
|
112
|
+
self.x.append(stats.generation)
|
|
113
|
+
self.y.append(stats.best_fitness)
|
|
114
|
+
if stats.generation % self.every:
|
|
115
|
+
return
|
|
116
|
+
self.image.set_data(self.problem.render(stats.best_genome))
|
|
117
|
+
self.a_best.set_title(f"generation {stats.generation} mse {stats.best_fitness:.5f} polygons {len(stats.best_genome)}")
|
|
118
|
+
self.line.set_data(self.x, self.y)
|
|
119
|
+
self.a_curve.relim()
|
|
120
|
+
self.a_curve.autoscale_view()
|
|
121
|
+
self.fig.canvas.draw_idle()
|
|
122
|
+
self.plt.pause(0.001)
|
|
123
|
+
|
|
124
|
+
def on_end(self, result: Result[Any], engine: GeneticAlgorithm[Any]) -> None:
|
|
125
|
+
self.plt.ioff()
|
|
126
|
+
self.plt.show()
|
|
@@ -0,0 +1,82 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: carmelolg-gapoly
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Evolve semi-transparent polygons with a genetic algorithm (GALib) until they look like a target photo.
|
|
5
|
+
Project-URL: Homepage, https://github.com/carmelolg/genetic-evolving-polygons
|
|
6
|
+
Project-URL: Source, https://github.com/carmelolg/genetic-evolving-polygons
|
|
7
|
+
Project-URL: Issues, https://github.com/carmelolg/genetic-evolving-polygons/issues
|
|
8
|
+
Requires-Python: >=3.10
|
|
9
|
+
Description-Content-Type: text/markdown
|
|
10
|
+
Requires-Dist: carmelolg-galib>=0.3.0
|
|
11
|
+
Requires-Dist: numpy>=1.24
|
|
12
|
+
Requires-Dist: Pillow>=10
|
|
13
|
+
Requires-Dist: numba>=0.60
|
|
14
|
+
Provides-Extra: live
|
|
15
|
+
Requires-Dist: matplotlib>=3.7; extra == "live"
|
|
16
|
+
Provides-Extra: dev
|
|
17
|
+
Requires-Dist: pytest>=8; extra == "dev"
|
|
18
|
+
Requires-Dist: ruff>=0.6; extra == "dev"
|
|
19
|
+
|
|
20
|
+
# gapoly
|
|
21
|
+
|
|
22
|
+
`gapoly` = GA + polygons (distribution `carmelolg-gapoly`, import `carmelolg.gapoly`, command `gapoly`).
|
|
23
|
+
|
|
24
|
+
Genetic algorithm that evolves semi-transparent polygons until, stacked, they look like a target photo.
|
|
25
|
+
Built on [GALib](https://github.com/carmelolg/GALib) (`carmelolg.galib`, on PyPI as `carmelolg-galib`).
|
|
26
|
+
|
|
27
|
+
- **Genome**: float32 array, one row per polygon (3-6 vertices in [0,1] coordinates, RGBA), drawn in row order.
|
|
28
|
+
- **Fitness**: pixel MSE between render and target (lower is better, `maximize = False`).
|
|
29
|
+
- **Mutation**: move a vertex, shift a polygon, change colour/alpha, add / remove a polygon, change overlap order.
|
|
30
|
+
- **Crossover**: swap tails of the two polygon lists.
|
|
31
|
+
|
|
32
|
+
## Genome layout
|
|
33
|
+
|
|
34
|
+
A genome is a float32 array, one row per polygon, drawn in row order (later rows on top). Values are in [0, 1];
|
|
35
|
+
coordinates are fractions of the image side.
|
|
36
|
+
|
|
37
|
+
```
|
|
38
|
+
column: 0 | 1 2 | 3 4 | ... | 11 12 | 13 14 15 16
|
|
39
|
+
meaning: n | x0 y0 x1 y1 ... x5 y5 | r g b a
|
|
40
|
+
```
|
|
41
|
+
|
|
42
|
+
`n` is the number of vertices used (3-6), the rest are ignored. Do not index rows with bare numbers: use the names
|
|
43
|
+
in `shapes.py` (`N_VERTICES`, `X(v)`, `Y(v)`, `RED`..`ALPHA`, `vertices`, `color`, `make_row`).
|
|
44
|
+
`describe(genome)` prints a genome as text, one line per polygon. The numba kernel (`fast_render.py`) reads the
|
|
45
|
+
same layout; `test_row_layout_is_the_documented_one` fails if the columns change.
|
|
46
|
+
|
|
47
|
+
## Setup
|
|
48
|
+
|
|
49
|
+
```bash
|
|
50
|
+
pip install carmelolg-gapoly # from PyPI
|
|
51
|
+
pip install "carmelolg-gapoly[live]" # plus the live matplotlib window
|
|
52
|
+
```
|
|
53
|
+
|
|
54
|
+
From a clone (development):
|
|
55
|
+
|
|
56
|
+
```bash
|
|
57
|
+
python -m venv .venv && source .venv/bin/activate
|
|
58
|
+
pip install -e ".[live,dev]"
|
|
59
|
+
```
|
|
60
|
+
|
|
61
|
+
## Run
|
|
62
|
+
|
|
63
|
+
```bash
|
|
64
|
+
python -m carmelolg.gapoly photo.jpg --generations 5000 --live # live window
|
|
65
|
+
python -m carmelolg.gapoly photo.jpg --snapshot-every 1 --generations 300 # one PNG per generation
|
|
66
|
+
```
|
|
67
|
+
|
|
68
|
+
Output in `out/<name>/`: `snapshots/gen_*.png`, `final.png`, `evolution.gif`, `history.csv`.
|
|
69
|
+
Polygons shrink coarse-to-fine: from `--start-size` (0.5) to `--max-size` (0.12, fraction of image side) over the first 70% of the run.
|
|
70
|
+
The live window lays out its panels by photo orientation: stacked for landscape, side by side for portrait/square.
|
|
71
|
+
Rendering and error are one compiled Numba loop (`fast_render.py`, releases the GIL). Fitness runs in parallel with GALib `workers=`: `--workers N` (default all CPUs), `--parallel thread|process` (default thread).
|
|
72
|
+
Useful options: `--polygons`, `--population`, `--mutation-rate`, `--size` (working resolution: smaller = faster), `--seed`.
|
|
73
|
+
|
|
74
|
+
## Tests
|
|
75
|
+
|
|
76
|
+
```bash
|
|
77
|
+
python -m pytest
|
|
78
|
+
```
|
|
79
|
+
|
|
80
|
+
## Ideas not done yet
|
|
81
|
+
|
|
82
|
+
More shape types, region weights (face counts more), SSIM fitness, greedy hill-climbing baseline.
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
README.md
|
|
2
|
+
pyproject.toml
|
|
3
|
+
src/carmelolg/gapoly/__init__.py
|
|
4
|
+
src/carmelolg/gapoly/__main__.py
|
|
5
|
+
src/carmelolg/gapoly/cli.py
|
|
6
|
+
src/carmelolg/gapoly/fast_render.py
|
|
7
|
+
src/carmelolg/gapoly/help_format.py
|
|
8
|
+
src/carmelolg/gapoly/operators.py
|
|
9
|
+
src/carmelolg/gapoly/problem.py
|
|
10
|
+
src/carmelolg/gapoly/render.py
|
|
11
|
+
src/carmelolg/gapoly/shapes.py
|
|
12
|
+
src/carmelolg/gapoly/viewer.py
|
|
13
|
+
src/carmelolg_gapoly.egg-info/PKG-INFO
|
|
14
|
+
src/carmelolg_gapoly.egg-info/SOURCES.txt
|
|
15
|
+
src/carmelolg_gapoly.egg-info/dependency_links.txt
|
|
16
|
+
src/carmelolg_gapoly.egg-info/entry_points.txt
|
|
17
|
+
src/carmelolg_gapoly.egg-info/requires.txt
|
|
18
|
+
src/carmelolg_gapoly.egg-info/top_level.txt
|
|
19
|
+
tests/test_gapoly.py
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
carmelolg
|
|
@@ -0,0 +1,181 @@
|
|
|
1
|
+
import re
|
|
2
|
+
from random import Random
|
|
3
|
+
|
|
4
|
+
import numpy as np
|
|
5
|
+
import pytest
|
|
6
|
+
from carmelolg.galib import GeneticAlgorithm
|
|
7
|
+
from PIL import Image, ImageDraw
|
|
8
|
+
|
|
9
|
+
from carmelolg.gapoly import Limits, PolygonProblem, operators
|
|
10
|
+
from carmelolg.gapoly.render import render
|
|
11
|
+
from carmelolg.gapoly.shapes import (
|
|
12
|
+
ALPHA,
|
|
13
|
+
COLS,
|
|
14
|
+
N_VERTICES,
|
|
15
|
+
RED,
|
|
16
|
+
X,
|
|
17
|
+
Y,
|
|
18
|
+
color,
|
|
19
|
+
describe,
|
|
20
|
+
empty_genome,
|
|
21
|
+
extent,
|
|
22
|
+
make_row,
|
|
23
|
+
random_row,
|
|
24
|
+
vertices,
|
|
25
|
+
)
|
|
26
|
+
|
|
27
|
+
SQUARE = [(0.0, 0.0), (1.0, 0.0), (1.0, 1.0), (0.0, 1.0)]
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
def gradient_target(size: int = 24) -> np.ndarray:
|
|
31
|
+
x = np.linspace(0, 1, size, dtype=np.float32)
|
|
32
|
+
img = np.zeros((size, size, 3), dtype=np.float32)
|
|
33
|
+
img[..., 0] = x[None, :]
|
|
34
|
+
img[..., 2] = x[:, None]
|
|
35
|
+
return img
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
def test_render_opaque_and_blended():
|
|
39
|
+
red = np.stack([make_row(SQUARE, (1.0, 0.0, 0.0, 1.0))])
|
|
40
|
+
assert render(red, 8, 8, (0.0, 0.0, 0.0))[4, 4].tolist() == [1.0, 0.0, 0.0]
|
|
41
|
+
half = np.stack([make_row(SQUARE, (1.0, 0.0, 0.0, 0.5))])
|
|
42
|
+
assert render(half, 8, 8, (0.0, 0.0, 0.0))[4, 4, 0] == pytest.approx(0.5)
|
|
43
|
+
assert render(empty_genome(), 4, 4, (0.2, 0.4, 0.6))[0, 0].tolist() == pytest.approx([0.2, 0.4, 0.6])
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
def pillow_reference(genome, size, background):
|
|
47
|
+
canvas = np.empty((size, size, 3), dtype=np.float32)
|
|
48
|
+
canvas[:] = background
|
|
49
|
+
for r in genome:
|
|
50
|
+
xs, ys = vertices(r)
|
|
51
|
+
mask = Image.new("L", (size, size), 0)
|
|
52
|
+
ImageDraw.Draw(mask).polygon([(x * size, y * size) for x, y in zip(xs, ys, strict=True)], fill=255)
|
|
53
|
+
alpha = np.asarray(mask, dtype=np.float32)[..., None] / 255.0 * color(r)[3]
|
|
54
|
+
canvas = canvas * (1 - alpha) + color(r)[:3] * alpha
|
|
55
|
+
return canvas
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
def test_numba_rasteriser_matches_pillow():
|
|
59
|
+
limits = Limits(max_size=0.4)
|
|
60
|
+
rng = Random(5)
|
|
61
|
+
genome = np.stack([random_row(rng, limits) for _ in range(30)])
|
|
62
|
+
ours = render(genome, 64, 64, (0.5, 0.5, 0.5))
|
|
63
|
+
reference = pillow_reference(genome, 64, (0.5, 0.5, 0.5))
|
|
64
|
+
assert np.abs(ours - reference).mean() < 0.01 # same shapes, only edge pixels differ
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
def test_fitness_zero_for_perfect_and_better_when_closer():
|
|
68
|
+
problem = PolygonProblem(np.zeros((8, 8, 3), dtype=np.float32))
|
|
69
|
+
assert problem.fitness(empty_genome()) == 0.0
|
|
70
|
+
far = np.stack([make_row(SQUARE, (1.0, 1.0, 1.0, 0.9))])
|
|
71
|
+
near = np.stack([make_row(SQUARE, (1.0, 1.0, 1.0, 0.1))])
|
|
72
|
+
assert problem.fitness(near) < problem.fitness(far)
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
def test_fitness_equals_numpy_mse_of_the_render():
|
|
76
|
+
problem = PolygonProblem(gradient_target(), Limits(max_size=0.5), initial_polygons=10)
|
|
77
|
+
genome = problem.random_genome(Random(3))
|
|
78
|
+
expected = float(np.mean((problem.render(genome) - problem.target) ** 2))
|
|
79
|
+
assert problem.fitness(genome) == pytest.approx(expected, rel=1e-4)
|
|
80
|
+
|
|
81
|
+
|
|
82
|
+
def test_operators_keep_genome_valid_and_inputs_untouched():
|
|
83
|
+
limits = Limits(max_polygons=12)
|
|
84
|
+
problem = PolygonProblem(gradient_target(), limits, initial_polygons=6)
|
|
85
|
+
rng = Random(1)
|
|
86
|
+
a, b = problem.random_genome(rng), problem.random_genome(rng)
|
|
87
|
+
a0, b0 = a.copy(), b.copy()
|
|
88
|
+
operators.mutate(a, rng, 1.0, limits)
|
|
89
|
+
operators.crossover(a, b, rng, limits)
|
|
90
|
+
assert np.array_equal(a, a0) and np.array_equal(b, b0)
|
|
91
|
+
for _ in range(300):
|
|
92
|
+
a = operators.mutate(a, rng, 0.3, limits)
|
|
93
|
+
a, b = operators.crossover(a, b, rng, limits)
|
|
94
|
+
for genome in (a, b):
|
|
95
|
+
assert genome.shape[1] == COLS and genome.dtype == np.float32
|
|
96
|
+
assert limits.min_polygons <= len(genome) <= limits.max_polygons
|
|
97
|
+
for r in genome:
|
|
98
|
+
xs, ys = vertices(r)
|
|
99
|
+
assert limits.min_vertices <= len(xs) <= limits.max_vertices
|
|
100
|
+
assert np.all((xs >= 0) & (xs <= 1) & (ys >= 0) & (ys <= 1))
|
|
101
|
+
assert np.all((color(r) >= 0) & (color(r) <= 1))
|
|
102
|
+
assert limits.min_alpha <= r[ALPHA] <= limits.max_alpha
|
|
103
|
+
assert extent(r) <= limits.max_size + 1e-6
|
|
104
|
+
|
|
105
|
+
|
|
106
|
+
def run(seed: int, **kwargs):
|
|
107
|
+
problem = PolygonProblem(gradient_target(), Limits(max_polygons=20), initial_polygons=5)
|
|
108
|
+
return GeneticAlgorithm(problem, population_size=16, max_generations=40, mutation_rate=0.1, seed=seed,
|
|
109
|
+
diversity=None, **kwargs).run()
|
|
110
|
+
|
|
111
|
+
|
|
112
|
+
def test_evolution_improves_and_is_reproducible():
|
|
113
|
+
first = run(7)
|
|
114
|
+
assert first.history[-1].best_fitness < first.history[0].best_fitness
|
|
115
|
+
assert run(7).best.fitness == first.best.fitness
|
|
116
|
+
|
|
117
|
+
|
|
118
|
+
def test_threads_give_the_same_result_as_serial():
|
|
119
|
+
assert run(7, workers=3, parallel="thread").best.fitness == run(7).best.fitness
|
|
120
|
+
|
|
121
|
+
|
|
122
|
+
def test_coloured_help_is_the_plain_help_plus_escape_codes(capsys, monkeypatch):
|
|
123
|
+
from carmelolg.gapoly.cli import main
|
|
124
|
+
|
|
125
|
+
monkeypatch.delenv("FORCE_COLOR", raising=False)
|
|
126
|
+
monkeypatch.setenv("NO_COLOR", "1")
|
|
127
|
+
with pytest.raises(SystemExit):
|
|
128
|
+
main(["-h"])
|
|
129
|
+
plain = capsys.readouterr().out
|
|
130
|
+
monkeypatch.delenv("NO_COLOR")
|
|
131
|
+
monkeypatch.setenv("FORCE_COLOR", "1")
|
|
132
|
+
with pytest.raises(SystemExit):
|
|
133
|
+
main(["-h"])
|
|
134
|
+
coloured = capsys.readouterr().out
|
|
135
|
+
assert "\033[" in coloured and "\033[" not in plain
|
|
136
|
+
assert re.sub(r"\033\[[0-9;]*m", "", coloured) == plain
|
|
137
|
+
|
|
138
|
+
|
|
139
|
+
def test_row_layout_is_the_documented_one():
|
|
140
|
+
"""If this fails, someone changed the columns: update the diagram in shapes.py and the numba kernel too."""
|
|
141
|
+
r = make_row([(0.1, 0.2), (0.3, 0.4), (0.5, 0.6)], (0.7, 0.8, 0.9, 0.5))
|
|
142
|
+
assert COLS == 17 and len(r) == COLS
|
|
143
|
+
assert r[N_VERTICES] == 3 and (N_VERTICES, X(0), Y(0), X(1), Y(1), X(5), Y(5)) == (0, 1, 2, 3, 4, 11, 12)
|
|
144
|
+
assert (RED, ALPHA) == (13, 16)
|
|
145
|
+
assert r[[X(0), Y(0), X(2), Y(2)]].tolist() == pytest.approx([0.1, 0.2, 0.5, 0.6])
|
|
146
|
+
assert color(r).tolist() == pytest.approx([0.7, 0.8, 0.9, 0.5])
|
|
147
|
+
assert not r[X(3) : RED].any() # unused vertices stay zero
|
|
148
|
+
|
|
149
|
+
|
|
150
|
+
def test_describe_prints_one_line_per_polygon():
|
|
151
|
+
text = describe(np.stack([make_row([(0.1, 0.2), (0.3, 0.4), (0.5, 0.6)], (1.0, 0.0, 0.0, 0.5))]))
|
|
152
|
+
assert text == "#0 3 vertices (0.10,0.20) (0.30,0.40) (0.50,0.60) rgba(1.00,0.00,0.00,0.50)"
|
|
153
|
+
|
|
154
|
+
|
|
155
|
+
def test_history_genome_every_keeps_stats_but_drops_most_genomes():
|
|
156
|
+
problem = PolygonProblem(gradient_target(), Limits(max_polygons=20), initial_polygons=5)
|
|
157
|
+
result = GeneticAlgorithm(problem, population_size=10, max_generations=25, seed=2, diversity=None,
|
|
158
|
+
history_genome_every=10).run()
|
|
159
|
+
assert len(result.history) == 26
|
|
160
|
+
for stats in result.history:
|
|
161
|
+
assert (stats.best_genome is not None) == (stats.generation % 10 == 0)
|
|
162
|
+
assert stats.best_fitness > 0 # statistics are still there
|
|
163
|
+
assert len(result.best.genome) > 0 # the final best is untouched
|
|
164
|
+
|
|
165
|
+
|
|
166
|
+
def test_snapshots_write_png_csv_and_gif_from_disk(tmp_path):
|
|
167
|
+
from PIL import Image
|
|
168
|
+
|
|
169
|
+
from carmelolg.gapoly.viewer import Snapshots
|
|
170
|
+
|
|
171
|
+
problem = PolygonProblem(gradient_target(), Limits(max_polygons=20), initial_polygons=5)
|
|
172
|
+
snapshots = Snapshots(problem, tmp_path, every=5, output_width=64, frame_width=32)
|
|
173
|
+
GeneticAlgorithm(problem, population_size=10, max_generations=12, seed=2, diversity=None,
|
|
174
|
+
callbacks=[snapshots]).run()
|
|
175
|
+
pngs = sorted(p.name for p in (tmp_path / "snapshots").glob("gen_*.png"))
|
|
176
|
+
assert pngs == ["gen_000000.png", "gen_000005.png", "gen_000010.png"]
|
|
177
|
+
assert Image.open(tmp_path / "final.png").size == (64, 64)
|
|
178
|
+
with Image.open(tmp_path / "evolution.gif") as gif:
|
|
179
|
+
assert gif.n_frames == len(pngs) + 1 and gif.size == (32, 32) # snapshots + final
|
|
180
|
+
rows = (tmp_path / "history.csv").read_text().splitlines()
|
|
181
|
+
assert rows[0] == "generation,best_mse,mean_mse,polygons" and len(rows) == 14 # header + generations 0..12
|