vrp-solver 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.
@@ -0,0 +1,48 @@
1
+ # See https://help.github.com/articles/ignoring-files/ for more about ignoring files.
2
+
3
+ # dependencies
4
+ /node_modules
5
+ /.pnp
6
+ .pnp.*
7
+ .yarn/*
8
+ !.yarn/patches
9
+ !.yarn/plugins
10
+ !.yarn/releases
11
+ !.yarn/versions
12
+
13
+ # testing
14
+ /coverage
15
+
16
+ # next.js
17
+ /.next/
18
+ /out/
19
+
20
+ # production
21
+ /build
22
+
23
+ # misc
24
+ .DS_Store
25
+ ._*
26
+ Thumbs.db
27
+ *.pem
28
+ .eslintcache
29
+
30
+ # debug
31
+ npm-debug.log*
32
+ yarn-debug.log*
33
+ yarn-error.log*
34
+ .pnpm-debug.log*
35
+
36
+ # env files (can opt-in for committing if needed)
37
+ .env*
38
+ !.env.example
39
+
40
+ # vercel
41
+ .vercel
42
+
43
+ # typescript
44
+ *.tsbuildinfo
45
+
46
+ # generated artifacts
47
+ /repomix-output.md
48
+ /project-structure.txt
@@ -0,0 +1 @@
1
+ 3.13
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Alan Shabrandi
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,158 @@
1
+ Metadata-Version: 2.5
2
+ Name: vrp-solver
3
+ Version: 0.1.0
4
+ Summary: A standalone Python implementation of a Genetic Algorithm for the Vehicle Routing Problem (open VRP, fixed start/end points).
5
+ Project-URL: Homepage, https://vrp-demo-phi.vercel.app
6
+ Project-URL: Repository, https://github.com/alan-shabrandi/vrp-demo
7
+ Project-URL: Bug Tracker, https://github.com/alan-shabrandi/vrp-demo/issues
8
+ Project-URL: Web Demo, https://vrp-demo-phi.vercel.app
9
+ Author-email: Alan Shabrandi <alan.shabrandi@gmail.com>
10
+ License: MIT
11
+ License-File: LICENSE
12
+ Keywords: genetic-algorithm,haversine,metaheuristics,optimization,vehicle-routing,vrp
13
+ Classifier: Development Status :: 3 - Alpha
14
+ Classifier: Intended Audience :: Science/Research
15
+ Classifier: License :: OSI Approved :: MIT License
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
+ Classifier: Topic :: Scientific/Engineering
22
+ Requires-Python: >=3.10
23
+ Requires-Dist: pydantic>=2.0
24
+ Requires-Dist: typer>=0.9.0
25
+ Description-Content-Type: text/markdown
26
+
27
+ # vrp-solver
28
+
29
+ [![PyPI version](https://img.shields.io/pypi/v/vrp-solver.svg)](https://pypi.org/project/vrp-solver/)
30
+ [![Python versions](https://img.shields.io/pypi/pyversions/vrp-solver.svg)](https://pypi.org/project/vrp-solver/)
31
+ [![License: MIT](https://img.shields.io/badge/License-MIT-blue.svg)](./LICENSE)
32
+ [![Live Demo](https://img.shields.io/badge/demo-vrp--demo--phi.vercel.app-4f9eff)](https://vrp-demo-phi.vercel.app)
33
+
34
+ A standalone Python implementation of a **Genetic Algorithm** for the **Vehicle Routing Problem** (open VRP with fixed start and end points).
35
+
36
+ This package is the Python counterpart to my [vrp-demo web application](https://vrp-demo-phi.vercel.app), and is **validated bit-exactly** against the TypeScript implementation there using shared golden test vectors. For the same seed and inputs, both versions produce identical routes, fitness values, and convergence histories.
37
+
38
+ The algorithm originates from my BSc thesis in Geomatics Engineering (GIS), where it was implemented in Python. The web demo later reimplemented it in TypeScript for visualization; this package brings the algorithm back to Python as a reusable, installable library.
39
+
40
+ ## Install
41
+
42
+ ```bash
43
+ pip install vrp-solver
44
+ ```
45
+
46
+ Or with `uv`:
47
+
48
+ ```bash
49
+ uv add vrp-solver
50
+ ```
51
+
52
+ ## Quick start (CLI)
53
+
54
+ Save a problem definition to `problem.json`:
55
+
56
+ ```json
57
+ {
58
+ "points": [
59
+ { "id": "start", "lat": 35.6892, "lng": 51.389, "role": "start" },
60
+ { "id": "s1", "lat": 35.7005, "lng": 51.4013, "role": "stop" },
61
+ { "id": "s2", "lat": 35.6500, "lng": 51.4500, "role": "stop" },
62
+ { "id": "end", "lat": 35.7795, "lng": 51.4033, "role": "end" }
63
+ ],
64
+ "config": {
65
+ "objective": "distance",
66
+ "populationSize": 50,
67
+ "generations": 30,
68
+ "mutationRate": 0.15,
69
+ "elitismCount": 2,
70
+ "tournamentSize": 3,
71
+ "randomSeed": 42
72
+ }
73
+ }
74
+ ```
75
+
76
+ Then:
77
+
78
+ ```bash
79
+ vrp-solver problem.json
80
+ ```
81
+
82
+ The output is a JSON object with three keys: `ga` (the evolved route), `baseline` (a greedy nearest-neighbor comparison), and `improvementPercent` (how much better the GA is, clamped to `[0, 1]`).
83
+
84
+ ## Quick start (Python API)
85
+
86
+ ```python
87
+ from vrp_solver import Point, GAConfig, solve_ga, solve_nearest_neighbor, compute_improvement
88
+
89
+ points = [
90
+ Point(id="start", lat=35.6892, lng=51.389, role="start"),
91
+ Point(id="s1", lat=35.7005, lng=51.4013, role="stop"),
92
+ Point(id="s2", lat=35.6500, lng=51.4500, role="stop"),
93
+ Point(id="end", lat=35.7795, lng=51.4033, role="end"),
94
+ ]
95
+
96
+ config = GAConfig(
97
+ populationSize=50,
98
+ generations=30,
99
+ mutationRate=0.15,
100
+ elitismCount=2,
101
+ tournamentSize=3,
102
+ objective="distance",
103
+ randomSeed=42,
104
+ )
105
+
106
+ ga = solve_ga(points, config)
107
+ baseline = solve_nearest_neighbor(points, config)
108
+
109
+ print(ga.sequence) # ['start', 's2', 's1', 'end']
110
+ print(ga.fitness) # total distance in meters
111
+ print(ga.history[-1].best) # final best fitness
112
+ print(compute_improvement(baseline.fitness, ga.fitness))
113
+ ```
114
+
115
+ ## What it does
116
+
117
+ - **Problem formulation:** open VRP with a fixed start, a fixed end, and any number of intermediate stops.
118
+ - **Chromosome:** a permutation of stop IDs only. Start and end are fixed wrappers, so the search space is `n!` for `n` stops instead of `(n+2)!`.
119
+ - **Initial population:** shuffled permutations.
120
+ - **Selection:** k-way tournament.
121
+ - **Crossover:** Order Crossover (OX), which always produces a valid permutation — no repair step required.
122
+ - **Mutation:** swap mutation, applied per offspring at the configured rate.
123
+ - **Elitism:** the top `elitismCount` individuals survive unchanged, guaranteeing monotonic non-increasing best fitness.
124
+ - **Fitness:** total Haversine distance, or total time at a constant 40 km/h.
125
+
126
+ ## Determinism
127
+
128
+ Pass an integer `randomSeed` and the run becomes fully reproducible — same seed, same points, same config, **same route** — across machines, Python versions, and repeated calls.
129
+
130
+ This is not an accident: the RNG is a bit-exact port of `mulberry32` as used in the TypeScript reference implementation, and the golden test suite (`tests/test_cross_validation.py`) asserts that both implementations produce identical sequences and fitness values for a fixed scenario. This makes the package safe to use for benchmarking and regression testing.
131
+
132
+ ## Validation
133
+
134
+ All inputs are validated with Pydantic:
135
+
136
+ - Points: `id` (non-empty string), `lat` in `[-90, 90]`, `lng` in `[-180, 180]`, `role` in `{start, stop, end}`.
137
+ - Point set: between 3 and 25 points, exactly one `start`, exactly one `end`, no duplicate IDs.
138
+ - Config: every numeric field checked against its documented bounds; `elitismCount <= populationSize`.
139
+
140
+ Invalid input raises `ValidationError` with a descriptive message.
141
+
142
+ ## Testing
143
+
144
+ ```bash
145
+ uv run pytest -v
146
+ ```
147
+
148
+ 36 tests covering Haversine math, OX permutation invariants, mutation invariants, tournament selection, GA pipeline structure, monotonic convergence, Pydantic validation, and cross-validation against the TypeScript implementation.
149
+
150
+ ## Links
151
+
152
+ - **Web demo:** [vrp-demo-phi.vercel.app](https://vrp-demo-phi.vercel.app)
153
+ - **Source:** [github.com/alan-shabrandi/vrp-demo](https://github.com/alan-shabrandi/vrp-demo) (the `packages/vrp-solver/` directory)
154
+ - **BSc thesis:** _link to be added_
155
+
156
+ ## License
157
+
158
+ MIT — see [LICENSE](./LICENSE).
@@ -0,0 +1,132 @@
1
+ # vrp-solver
2
+
3
+ [![PyPI version](https://img.shields.io/pypi/v/vrp-solver.svg)](https://pypi.org/project/vrp-solver/)
4
+ [![Python versions](https://img.shields.io/pypi/pyversions/vrp-solver.svg)](https://pypi.org/project/vrp-solver/)
5
+ [![License: MIT](https://img.shields.io/badge/License-MIT-blue.svg)](./LICENSE)
6
+ [![Live Demo](https://img.shields.io/badge/demo-vrp--demo--phi.vercel.app-4f9eff)](https://vrp-demo-phi.vercel.app)
7
+
8
+ A standalone Python implementation of a **Genetic Algorithm** for the **Vehicle Routing Problem** (open VRP with fixed start and end points).
9
+
10
+ This package is the Python counterpart to my [vrp-demo web application](https://vrp-demo-phi.vercel.app), and is **validated bit-exactly** against the TypeScript implementation there using shared golden test vectors. For the same seed and inputs, both versions produce identical routes, fitness values, and convergence histories.
11
+
12
+ The algorithm originates from my BSc thesis in Geomatics Engineering (GIS), where it was implemented in Python. The web demo later reimplemented it in TypeScript for visualization; this package brings the algorithm back to Python as a reusable, installable library.
13
+
14
+ ## Install
15
+
16
+ ```bash
17
+ pip install vrp-solver
18
+ ```
19
+
20
+ Or with `uv`:
21
+
22
+ ```bash
23
+ uv add vrp-solver
24
+ ```
25
+
26
+ ## Quick start (CLI)
27
+
28
+ Save a problem definition to `problem.json`:
29
+
30
+ ```json
31
+ {
32
+ "points": [
33
+ { "id": "start", "lat": 35.6892, "lng": 51.389, "role": "start" },
34
+ { "id": "s1", "lat": 35.7005, "lng": 51.4013, "role": "stop" },
35
+ { "id": "s2", "lat": 35.6500, "lng": 51.4500, "role": "stop" },
36
+ { "id": "end", "lat": 35.7795, "lng": 51.4033, "role": "end" }
37
+ ],
38
+ "config": {
39
+ "objective": "distance",
40
+ "populationSize": 50,
41
+ "generations": 30,
42
+ "mutationRate": 0.15,
43
+ "elitismCount": 2,
44
+ "tournamentSize": 3,
45
+ "randomSeed": 42
46
+ }
47
+ }
48
+ ```
49
+
50
+ Then:
51
+
52
+ ```bash
53
+ vrp-solver problem.json
54
+ ```
55
+
56
+ The output is a JSON object with three keys: `ga` (the evolved route), `baseline` (a greedy nearest-neighbor comparison), and `improvementPercent` (how much better the GA is, clamped to `[0, 1]`).
57
+
58
+ ## Quick start (Python API)
59
+
60
+ ```python
61
+ from vrp_solver import Point, GAConfig, solve_ga, solve_nearest_neighbor, compute_improvement
62
+
63
+ points = [
64
+ Point(id="start", lat=35.6892, lng=51.389, role="start"),
65
+ Point(id="s1", lat=35.7005, lng=51.4013, role="stop"),
66
+ Point(id="s2", lat=35.6500, lng=51.4500, role="stop"),
67
+ Point(id="end", lat=35.7795, lng=51.4033, role="end"),
68
+ ]
69
+
70
+ config = GAConfig(
71
+ populationSize=50,
72
+ generations=30,
73
+ mutationRate=0.15,
74
+ elitismCount=2,
75
+ tournamentSize=3,
76
+ objective="distance",
77
+ randomSeed=42,
78
+ )
79
+
80
+ ga = solve_ga(points, config)
81
+ baseline = solve_nearest_neighbor(points, config)
82
+
83
+ print(ga.sequence) # ['start', 's2', 's1', 'end']
84
+ print(ga.fitness) # total distance in meters
85
+ print(ga.history[-1].best) # final best fitness
86
+ print(compute_improvement(baseline.fitness, ga.fitness))
87
+ ```
88
+
89
+ ## What it does
90
+
91
+ - **Problem formulation:** open VRP with a fixed start, a fixed end, and any number of intermediate stops.
92
+ - **Chromosome:** a permutation of stop IDs only. Start and end are fixed wrappers, so the search space is `n!` for `n` stops instead of `(n+2)!`.
93
+ - **Initial population:** shuffled permutations.
94
+ - **Selection:** k-way tournament.
95
+ - **Crossover:** Order Crossover (OX), which always produces a valid permutation — no repair step required.
96
+ - **Mutation:** swap mutation, applied per offspring at the configured rate.
97
+ - **Elitism:** the top `elitismCount` individuals survive unchanged, guaranteeing monotonic non-increasing best fitness.
98
+ - **Fitness:** total Haversine distance, or total time at a constant 40 km/h.
99
+
100
+ ## Determinism
101
+
102
+ Pass an integer `randomSeed` and the run becomes fully reproducible — same seed, same points, same config, **same route** — across machines, Python versions, and repeated calls.
103
+
104
+ This is not an accident: the RNG is a bit-exact port of `mulberry32` as used in the TypeScript reference implementation, and the golden test suite (`tests/test_cross_validation.py`) asserts that both implementations produce identical sequences and fitness values for a fixed scenario. This makes the package safe to use for benchmarking and regression testing.
105
+
106
+ ## Validation
107
+
108
+ All inputs are validated with Pydantic:
109
+
110
+ - Points: `id` (non-empty string), `lat` in `[-90, 90]`, `lng` in `[-180, 180]`, `role` in `{start, stop, end}`.
111
+ - Point set: between 3 and 25 points, exactly one `start`, exactly one `end`, no duplicate IDs.
112
+ - Config: every numeric field checked against its documented bounds; `elitismCount <= populationSize`.
113
+
114
+ Invalid input raises `ValidationError` with a descriptive message.
115
+
116
+ ## Testing
117
+
118
+ ```bash
119
+ uv run pytest -v
120
+ ```
121
+
122
+ 36 tests covering Haversine math, OX permutation invariants, mutation invariants, tournament selection, GA pipeline structure, monotonic convergence, Pydantic validation, and cross-validation against the TypeScript implementation.
123
+
124
+ ## Links
125
+
126
+ - **Web demo:** [vrp-demo-phi.vercel.app](https://vrp-demo-phi.vercel.app)
127
+ - **Source:** [github.com/alan-shabrandi/vrp-demo](https://github.com/alan-shabrandi/vrp-demo) (the `packages/vrp-solver/` directory)
128
+ - **BSc thesis:** _link to be added_
129
+
130
+ ## License
131
+
132
+ MIT — see [LICENSE](./LICENSE).
@@ -0,0 +1,80 @@
1
+ [project]
2
+ name = "vrp-solver"
3
+ version = "0.1.0"
4
+ description = "A standalone Python implementation of a Genetic Algorithm for the Vehicle Routing Problem (open VRP, fixed start/end points)."
5
+ readme = "README.md"
6
+ requires-python = ">=3.10"
7
+ license = { text = "MIT" }
8
+ authors = [
9
+ { name = "Alan Shabrandi", email = "alan.shabrandi@gmail.com" }
10
+ ]
11
+ keywords = [
12
+ "vrp",
13
+ "vehicle-routing",
14
+ "genetic-algorithm",
15
+ "optimization",
16
+ "haversine",
17
+ "metaheuristics",
18
+ ]
19
+ classifiers = [
20
+ "Development Status :: 3 - Alpha",
21
+ "Intended Audience :: Science/Research",
22
+ "License :: OSI Approved :: MIT License",
23
+ "Programming Language :: Python :: 3",
24
+ "Programming Language :: Python :: 3.10",
25
+ "Programming Language :: Python :: 3.11",
26
+ "Programming Language :: Python :: 3.12",
27
+ "Programming Language :: Python :: 3.13",
28
+ "Topic :: Scientific/Engineering",
29
+ ]
30
+ dependencies = [
31
+ "pydantic>=2.0",
32
+ "typer>=0.9.0",
33
+ ]
34
+
35
+ [project.scripts]
36
+ vrp-solver = "vrp_solver.cli:app"
37
+
38
+ [project.urls]
39
+ Homepage = "https://vrp-demo-phi.vercel.app"
40
+ Repository = "https://github.com/alan-shabrandi/vrp-demo"
41
+ "Bug Tracker" = "https://github.com/alan-shabrandi/vrp-demo/issues"
42
+ "Web Demo" = "https://vrp-demo-phi.vercel.app"
43
+
44
+ [build-system]
45
+ requires = ["hatchling"]
46
+ build-backend = "hatchling.build"
47
+
48
+ [dependency-groups]
49
+ dev = [
50
+ "pytest>=8.0",
51
+ "ruff>=0.3.0",
52
+ "mypy>=1.8",
53
+ "build>=1.2",
54
+ "twine>=5.0",
55
+ ]
56
+
57
+ [tool.pytest.ini_options]
58
+ testpaths = ["tests"]
59
+ pythonpath = ["src"]
60
+
61
+ [tool.ruff]
62
+ line-length = 100
63
+ target-version = "py310"
64
+
65
+ [tool.ruff.lint]
66
+ select = ["E", "F", "W", "I", "N", "UP", "B", "C4", "SIM"]
67
+
68
+ [tool.ruff.lint.per-file-ignores]
69
+ # JSON contract fields are camelCase to match the TypeScript API; keep them that way.
70
+ "src/vrp_solver/validation.py" = ["N815"]
71
+ "src/vrp_solver/types.py" = ["N815"]
72
+ # Test helpers legitimately use dict() for **kwargs spreading.
73
+ "tests/*.py" = ["C408"]
74
+ # Typer requires Argument()/Option() calls in argument defaults.
75
+ "src/vrp_solver/cli.py" = ["B008"]
76
+
77
+ [tool.mypy]
78
+ python_version = "3.10"
79
+ strict = true
80
+ ignore_missing_imports = true
@@ -0,0 +1,35 @@
1
+ """
2
+ vrp-solver: A Genetic Algorithm for the Vehicle Routing Problem.
3
+
4
+ Ported from the original TypeScript web implementation.
5
+ """
6
+
7
+ from .distance import compute_improvement, evaluate_sequence, haversine_distance
8
+ from .ga import solve_ga
9
+ from .nearest_neighbor import solve_nearest_neighbor
10
+ from .types import (
11
+ BaselineResult,
12
+ GAConfig,
13
+ GAResult,
14
+ OptimizeResponse,
15
+ Point,
16
+ RouteSolution,
17
+ )
18
+ from .validation import parse_optimize_request
19
+
20
+ __version__ = "0.1.0"
21
+
22
+ __all__ = [
23
+ "Point",
24
+ "GAConfig",
25
+ "RouteSolution",
26
+ "GAResult",
27
+ "BaselineResult",
28
+ "OptimizeResponse",
29
+ "solve_ga",
30
+ "solve_nearest_neighbor",
31
+ "evaluate_sequence",
32
+ "haversine_distance",
33
+ "compute_improvement",
34
+ "parse_optimize_request",
35
+ ]
@@ -0,0 +1,66 @@
1
+ import dataclasses
2
+ import json
3
+ from pathlib import Path
4
+
5
+ import typer
6
+ from rich.console import Console
7
+
8
+ from .distance import compute_improvement
9
+ from .ga import solve_ga
10
+ from .nearest_neighbor import solve_nearest_neighbor
11
+ from .types import OptimizeResponse
12
+ from .validation import ValidationError, parse_optimize_request
13
+
14
+ app = typer.Typer(help="VRP Solver — Genetic Algorithm (Python port).")
15
+ console = Console()
16
+
17
+
18
+ @app.command()
19
+ def solve(
20
+ input_file: Path = typer.Argument(..., help="Path to input JSON file."),
21
+ output_file: Path | None = typer.Option(
22
+ None, "--output", "-o", help="Path to output JSON file. If omitted, prints to stdout."
23
+ ),
24
+ ) -> None:
25
+ """
26
+ Read a VRP problem from JSON, run the GA and nearest-neighbor baseline,
27
+ and output the result.
28
+ """
29
+ try:
30
+ raw = json.loads(input_file.read_text(encoding="utf-8"))
31
+ except Exception as e:
32
+ console.print(f"[red]Error reading file:[/red] {e}")
33
+ raise typer.Exit(code=1) from e
34
+
35
+ try:
36
+ req = parse_optimize_request(raw)
37
+ except ValidationError as e:
38
+ console.print(f"[red]Validation error:[/red] {e}")
39
+ raise typer.Exit(code=1) from e
40
+
41
+ console.print("[cyan]Running Genetic Algorithm...[/cyan]")
42
+ ga_result = solve_ga(req.points, req.config)
43
+
44
+ console.print("[cyan]Running Nearest-Neighbor baseline...[/cyan]")
45
+ nn_result = solve_nearest_neighbor(req.points, req.config)
46
+
47
+ improvement = compute_improvement(nn_result.fitness, ga_result.fitness)
48
+
49
+ response = OptimizeResponse(
50
+ ga=ga_result,
51
+ baseline=nn_result,
52
+ improvementPercent=improvement,
53
+ )
54
+
55
+ out_dict = dataclasses.asdict(response)
56
+ out_json = json.dumps(out_dict, indent=2, ensure_ascii=False)
57
+
58
+ if output_file:
59
+ output_file.write_text(out_json, encoding="utf-8")
60
+ console.print(f"[green]Done. Result written to {output_file}[/green]")
61
+ else:
62
+ print(out_json)
63
+
64
+
65
+ if __name__ == "__main__":
66
+ app()
@@ -0,0 +1,36 @@
1
+ from typing import TypedDict
2
+
3
+ from .types import GAConfig
4
+
5
+ EARTH_RADIUS_M = 6_371_000
6
+ AVERAGE_SPEED_KMH = 40
7
+ AVERAGE_SPEED_MS = (AVERAGE_SPEED_KMH * 1000) / 3600
8
+
9
+ MIN_POINTS = 3
10
+ MAX_POINTS = 25
11
+
12
+ VALID_ROLES = ["start", "stop", "end"]
13
+ VALID_OBJECTIVES = ["distance", "time"]
14
+
15
+ DEFAULT_GA_CONFIG = GAConfig(
16
+ populationSize=80,
17
+ generations=150,
18
+ mutationRate=0.15,
19
+ elitismCount=2,
20
+ tournamentSize=3,
21
+ objective="distance",
22
+ )
23
+
24
+
25
+ class Bound(TypedDict):
26
+ min: float
27
+ max: float
28
+
29
+
30
+ GA_CONFIG_BOUNDS: dict[str, Bound] = {
31
+ "populationSize": {"min": 10, "max": 300},
32
+ "generations": {"min": 10, "max": 500},
33
+ "mutationRate": {"min": 0.0, "max": 1.0},
34
+ "elitismCount": {"min": 1, "max": 10},
35
+ "tournamentSize": {"min": 2, "max": 10},
36
+ }
@@ -0,0 +1,64 @@
1
+ import math
2
+
3
+ from .constants import AVERAGE_SPEED_MS, EARTH_RADIUS_M
4
+ from .types import Objective, Point, RouteSolution
5
+
6
+
7
+ def _to_rad(deg: float) -> float:
8
+ return (deg * math.pi) / 180.0
9
+
10
+
11
+ def haversine_distance(a: Point, b: Point) -> float:
12
+ """Great-circle distance between two WGS84 points, in meters."""
13
+ d_lat = _to_rad(b.lat - a.lat)
14
+ d_lng = _to_rad(b.lng - a.lng)
15
+ lat1 = _to_rad(a.lat)
16
+ lat2 = _to_rad(b.lat)
17
+ h = math.sin(d_lat / 2) ** 2 + math.cos(lat1) * math.cos(lat2) * math.sin(d_lng / 2) ** 2
18
+ # Guard against floating-point overshoot. In JS, Math.asin returns NaN
19
+ # for inputs > 1; Python's math.asin raises ValueError. Clamp to match
20
+ # the "safe" behavior for valid WGS84 coordinates.
21
+ return 2 * EARTH_RADIUS_M * math.asin(math.sqrt(min(1.0, h)))
22
+
23
+
24
+ def evaluate_sequence(
25
+ points: list[Point],
26
+ sequence: list[str],
27
+ objective: Objective,
28
+ ) -> RouteSolution:
29
+ """
30
+ Evaluate a full route.
31
+
32
+ ``sequence`` must include start, end, and every stop, in visit order,
33
+ starting with the start point and ending with the end point.
34
+ """
35
+ by_id = {p.id: p for p in points}
36
+ total_distance = 0.0
37
+
38
+ for i in range(len(sequence) - 1):
39
+ a = by_id.get(sequence[i])
40
+ b = by_id.get(sequence[i + 1])
41
+ if a is None or b is None:
42
+ raise ValueError(f"Unknown point in sequence: {sequence[i]} or {sequence[i + 1]}")
43
+ total_distance += haversine_distance(a, b)
44
+
45
+ total_time = total_distance / AVERAGE_SPEED_MS
46
+ fitness = total_distance if objective == "distance" else total_time
47
+
48
+ return RouteSolution(
49
+ sequence=sequence,
50
+ totalDistance=total_distance,
51
+ totalTime=total_time,
52
+ fitness=fitness,
53
+ )
54
+
55
+
56
+ def compute_improvement(baseline_fitness: float, candidate_fitness: float) -> float:
57
+ """
58
+ Fractional improvement of ``candidate`` over ``baseline``, clamped to [0, 1].
59
+ ``0.111`` means the candidate is 11.1% better.
60
+ """
61
+ if baseline_fitness <= 0:
62
+ return 0.0
63
+ raw = (baseline_fitness - candidate_fitness) / baseline_fitness
64
+ return max(0.0, min(1.0, raw))