vrp-solver 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.
vrp_solver/__init__.py ADDED
@@ -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
+ ]
vrp_solver/cli.py ADDED
@@ -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
+ }
vrp_solver/distance.py ADDED
@@ -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))
vrp_solver/ga.py ADDED
@@ -0,0 +1,100 @@
1
+ from collections.abc import Callable
2
+
3
+ from .distance import evaluate_sequence
4
+ from .operators import order_crossover, swap_mutation, tournament_select
5
+ from .rng import Rng, create_rng, shuffle
6
+ from .types import FitnessHistoryPoint, GAConfig, GAResult, Point, RouteSolution
7
+ from .validation import require_start_and_end
8
+
9
+ Evaluator = Callable[[list[str]], RouteSolution]
10
+
11
+
12
+ def solve_ga(points: list[Point], config: GAConfig) -> GAResult:
13
+ """
14
+ Run the genetic algorithm.
15
+ Chromosome = permutation of stop IDs only; start and end are fixed wrappers.
16
+ """
17
+ start, end = require_start_and_end(points)
18
+ stops = [p for p in points if p.role == "stop"]
19
+
20
+ if not stops:
21
+ sequence = [start.id, end.id]
22
+ result = evaluate_sequence(points, sequence, config.objective)
23
+ return GAResult(
24
+ sequence=result.sequence,
25
+ totalDistance=result.totalDistance,
26
+ totalTime=result.totalTime,
27
+ fitness=result.fitness,
28
+ history=[],
29
+ generationsRun=0,
30
+ )
31
+
32
+ rng = create_rng(config.randomSeed)
33
+ stop_ids = [p.id for p in stops]
34
+
35
+ def evaluate(perm: list[str]) -> RouteSolution:
36
+ return evaluate_sequence(points, [start.id, *perm, end.id], config.objective)
37
+
38
+ population: list[RouteSolution] = [
39
+ evaluate(shuffle(stop_ids, rng)) for _ in range(config.populationSize)
40
+ ]
41
+
42
+ history: list[FitnessHistoryPoint] = []
43
+
44
+ for gen in range(config.generations):
45
+ population.sort(key=lambda x: x.fitness)
46
+ history.append(snapshot_generation(population, gen + 1))
47
+ population = breed_next_generation(population, config, evaluate, rng)
48
+
49
+ population.sort(key=lambda x: x.fitness)
50
+ best = population[0]
51
+
52
+ return GAResult(
53
+ sequence=best.sequence,
54
+ totalDistance=best.totalDistance,
55
+ totalTime=best.totalTime,
56
+ fitness=best.fitness,
57
+ history=history,
58
+ generationsRun=config.generations,
59
+ )
60
+
61
+
62
+ def snapshot_generation(sorted_pop: list[RouteSolution], generation: int) -> FitnessHistoryPoint:
63
+ total = sum(ind.fitness for ind in sorted_pop)
64
+ return FitnessHistoryPoint(
65
+ generation=generation,
66
+ best=sorted_pop[0].fitness,
67
+ average=total / len(sorted_pop),
68
+ )
69
+
70
+
71
+ def breed_next_generation(
72
+ population: list[RouteSolution],
73
+ config: GAConfig,
74
+ evaluate: Evaluator,
75
+ rng: Rng,
76
+ ) -> list[RouteSolution]:
77
+ next_pop = population[: config.elitismCount]
78
+ while len(next_pop) < config.populationSize:
79
+ next_pop.append(breed_offspring(population, config, evaluate, rng))
80
+ return next_pop
81
+
82
+
83
+ def breed_offspring(
84
+ population: list[RouteSolution],
85
+ config: GAConfig,
86
+ evaluate: Evaluator,
87
+ rng: Rng,
88
+ ) -> RouteSolution:
89
+ p1 = tournament_select(population, config.tournamentSize, rng)
90
+ p2 = tournament_select(population, config.tournamentSize, rng)
91
+
92
+ # Slice off the start/end wrappers to get permutations of stops only.
93
+ stop_p1 = p1.sequence[1:-1]
94
+ stop_p2 = p2.sequence[1:-1]
95
+
96
+ child_perm = order_crossover(stop_p1, stop_p2, rng)
97
+ if rng() < config.mutationRate:
98
+ child_perm = swap_mutation(child_perm, rng)
99
+
100
+ return evaluate(child_perm)
@@ -0,0 +1,37 @@
1
+ from .distance import evaluate_sequence, haversine_distance
2
+ from .types import BaselineResult, GAConfig, Point
3
+ from .validation import require_start_and_end
4
+
5
+
6
+ def solve_nearest_neighbor(points: list[Point], config: GAConfig) -> BaselineResult:
7
+ """
8
+ Greedy nearest-neighbor baseline.
9
+ From the current point, hop to the nearest unvisited stop; terminate
10
+ at the fixed end.
11
+ """
12
+ start, end = require_start_and_end(points)
13
+
14
+ remaining = [p for p in points if p.role == "stop"]
15
+ sequence: list[str] = [start.id]
16
+ current: Point = start
17
+
18
+ while remaining:
19
+ best_idx = 0
20
+ best_dist = float("inf")
21
+ for i, p in enumerate(remaining):
22
+ d = haversine_distance(current, p)
23
+ if d < best_dist:
24
+ best_dist = d
25
+ best_idx = i
26
+ next_point = remaining.pop(best_idx)
27
+ sequence.append(next_point.id)
28
+ current = next_point
29
+ sequence.append(end.id)
30
+
31
+ result = evaluate_sequence(points, sequence, config.objective)
32
+ return BaselineResult(
33
+ sequence=result.sequence,
34
+ totalDistance=result.totalDistance,
35
+ totalTime=result.totalTime,
36
+ fitness=result.fitness,
37
+ )
@@ -0,0 +1,67 @@
1
+ from .rng import Rng, random_index
2
+ from .types import RouteSolution
3
+
4
+
5
+ def order_crossover(p1: list[str], p2: list[str], rng: Rng) -> list[str]:
6
+ """
7
+ Order Crossover (OX). Always yields a valid permutation of the same set.
8
+
9
+ See ``operators.ts`` for the full rationale.
10
+ """
11
+ n = len(p1)
12
+ if n < 2:
13
+ return list(p1)
14
+
15
+ a = int(rng() * n)
16
+ b = int(rng() * n)
17
+ start, end = (a, b) if a < b else (b, a)
18
+
19
+ child: list[str | None] = [None] * n
20
+ used: set[str] = set()
21
+
22
+ for i in range(start, end + 1):
23
+ child[i] = p1[i]
24
+ used.add(p1[i])
25
+
26
+ j = 0
27
+ for i in range(n):
28
+ if child[i] is not None:
29
+ continue
30
+ while p2[j] in used:
31
+ j += 1
32
+ child[i] = p2[j]
33
+ j += 1
34
+
35
+ # All positions must be filled by construction; if not, that's a bug.
36
+ assert all(c is not None for c in child), "OX left null slots"
37
+ return child # type: ignore[return-value]
38
+
39
+
40
+ def swap_mutation(chrom: list[str], rng: Rng) -> list[str]:
41
+ """Picks two distinct positions and swaps them. Returns a new list."""
42
+ out = list(chrom)
43
+ if len(out) < 2:
44
+ return out
45
+ i = random_index(len(out), rng)
46
+ j = random_index(len(out), rng)
47
+ while j == i:
48
+ j = random_index(len(out), rng)
49
+ out[i], out[j] = out[j], out[i]
50
+ return out
51
+
52
+
53
+ def tournament_select(
54
+ population: list[RouteSolution],
55
+ k: int,
56
+ rng: Rng,
57
+ ) -> RouteSolution:
58
+ """
59
+ k-way tournament selection. Samples ``k`` individuals uniformly (with
60
+ replacement) and returns the one with the lowest ``fitness``.
61
+ """
62
+ best = population[random_index(len(population), rng)]
63
+ for _ in range(1, k):
64
+ candidate = population[random_index(len(population), rng)]
65
+ if candidate.fitness < best.fitness:
66
+ best = candidate
67
+ return best
vrp_solver/py.typed ADDED
File without changes
vrp_solver/rng.py ADDED
@@ -0,0 +1,46 @@
1
+ import random
2
+ from collections.abc import Callable
3
+ from typing import TypeVar
4
+
5
+ T = TypeVar("T")
6
+ Rng = Callable[[], float]
7
+
8
+
9
+ def _imul(a: int, b: int) -> int:
10
+ """Equivalent to JavaScript's Math.imul (32-bit integer multiplication)."""
11
+ return (a * b) & 0xFFFFFFFF
12
+
13
+
14
+ def create_rng(seed: int | None = None) -> Rng:
15
+ """
16
+ Mulberry32 PRNG.
17
+ Without a seed, returns `random.random` so production runs stay non-deterministic.
18
+ """
19
+ if seed is None:
20
+ return random.random
21
+
22
+ s = seed & 0xFFFFFFFF
23
+
24
+ def next_val() -> float:
25
+ nonlocal s
26
+ s = (s + 0x6D2B79F5) & 0xFFFFFFFF
27
+ t = s
28
+ t = _imul(t ^ (t >> 15), t | 1)
29
+ t = (t ^ (t + _imul(t ^ (t >> 7), t | 61))) & 0xFFFFFFFF
30
+ return ((t ^ (t >> 14)) & 0xFFFFFFFF) / 4294967296.0
31
+
32
+ return next_val
33
+
34
+
35
+ def shuffle(arr: list[T], rng: Rng) -> list[T]:
36
+ """Fisher-Yates shuffle. Returns a new array; does not mutate the input."""
37
+ out = list(arr)
38
+ for i in range(len(out) - 1, 0, -1):
39
+ j = int(rng() * (i + 1))
40
+ out[i], out[j] = out[j], out[i]
41
+ return out
42
+
43
+
44
+ def random_index(length: int, rng: Rng) -> int:
45
+ """Uniform integer in [0, length)."""
46
+ return int(rng() * length)
vrp_solver/types.py ADDED
@@ -0,0 +1,65 @@
1
+ from dataclasses import dataclass, field
2
+ from typing import Literal
3
+
4
+ PointRole = Literal["start", "stop", "end"]
5
+ Objective = Literal["distance", "time"]
6
+
7
+
8
+ @dataclass(frozen=True)
9
+ class Point:
10
+ id: str
11
+ lat: float
12
+ lng: float
13
+ role: PointRole
14
+ label: str | None = None
15
+
16
+
17
+ @dataclass(frozen=True)
18
+ class GAConfig:
19
+ populationSize: int
20
+ generations: int
21
+ mutationRate: float
22
+ elitismCount: int
23
+ tournamentSize: int
24
+ objective: Objective
25
+ randomSeed: int | None = None
26
+
27
+
28
+ @dataclass(frozen=True)
29
+ class FitnessHistoryPoint:
30
+ generation: int
31
+ best: float
32
+ average: float
33
+
34
+
35
+ @dataclass(frozen=True)
36
+ class RouteSolution:
37
+ sequence: list[str]
38
+ totalDistance: float
39
+ totalTime: float
40
+ fitness: float
41
+
42
+
43
+ @dataclass(frozen=True)
44
+ class GAResult(RouteSolution):
45
+ algorithm: str = "genetic"
46
+ history: list[FitnessHistoryPoint] = field(default_factory=list)
47
+ generationsRun: int = 0
48
+
49
+
50
+ @dataclass(frozen=True)
51
+ class BaselineResult(RouteSolution):
52
+ algorithm: str = "nearest-neighbor"
53
+
54
+
55
+ @dataclass(frozen=True)
56
+ class OptimizeResponse:
57
+ ga: GAResult
58
+ baseline: BaselineResult
59
+ improvementPercent: float
60
+
61
+
62
+ @dataclass(frozen=True)
63
+ class OptimizeRequest:
64
+ points: list[Point]
65
+ config: GAConfig
@@ -0,0 +1,130 @@
1
+ from typing import Any
2
+
3
+ from pydantic import BaseModel, Field, field_validator, model_validator
4
+
5
+ from .constants import (
6
+ DEFAULT_GA_CONFIG,
7
+ GA_CONFIG_BOUNDS,
8
+ MAX_POINTS,
9
+ MIN_POINTS,
10
+ VALID_ROLES,
11
+ )
12
+ from .types import GAConfig, Objective, OptimizeRequest, Point, PointRole
13
+
14
+
15
+ class ValidationError(ValueError):
16
+ pass
17
+
18
+
19
+ class PointSchema(BaseModel):
20
+ id: str = Field(min_length=1)
21
+ lat: float = Field(ge=-90, le=90)
22
+ lng: float = Field(ge=-180, le=180)
23
+ role: PointRole
24
+ label: str | None = None
25
+
26
+ @field_validator("role")
27
+ @classmethod
28
+ def validate_role(cls, v: str) -> str:
29
+ if v not in VALID_ROLES:
30
+ raise ValueError(f"role must be one of {', '.join(VALID_ROLES)}")
31
+ return v
32
+
33
+
34
+ class ConfigSchema(BaseModel):
35
+ populationSize: int = Field(
36
+ default=DEFAULT_GA_CONFIG.populationSize,
37
+ ge=GA_CONFIG_BOUNDS["populationSize"]["min"],
38
+ le=GA_CONFIG_BOUNDS["populationSize"]["max"],
39
+ )
40
+ generations: int = Field(
41
+ default=DEFAULT_GA_CONFIG.generations,
42
+ ge=GA_CONFIG_BOUNDS["generations"]["min"],
43
+ le=GA_CONFIG_BOUNDS["generations"]["max"],
44
+ )
45
+ mutationRate: float = Field(
46
+ default=DEFAULT_GA_CONFIG.mutationRate,
47
+ ge=GA_CONFIG_BOUNDS["mutationRate"]["min"],
48
+ le=GA_CONFIG_BOUNDS["mutationRate"]["max"],
49
+ )
50
+ elitismCount: int = Field(
51
+ default=DEFAULT_GA_CONFIG.elitismCount,
52
+ ge=GA_CONFIG_BOUNDS["elitismCount"]["min"],
53
+ le=GA_CONFIG_BOUNDS["elitismCount"]["max"],
54
+ )
55
+ tournamentSize: int = Field(
56
+ default=DEFAULT_GA_CONFIG.tournamentSize,
57
+ ge=GA_CONFIG_BOUNDS["tournamentSize"]["min"],
58
+ le=GA_CONFIG_BOUNDS["tournamentSize"]["max"],
59
+ )
60
+ objective: Objective = DEFAULT_GA_CONFIG.objective
61
+ randomSeed: int | None = None
62
+
63
+ @model_validator(mode="after")
64
+ def check_elitism(self) -> "ConfigSchema":
65
+ if self.elitismCount > self.populationSize:
66
+ raise ValueError("elitismCount must be <= populationSize")
67
+ return self
68
+
69
+
70
+ class OptimizeRequestSchema(BaseModel):
71
+ points: list[PointSchema]
72
+ config: ConfigSchema | None = None
73
+
74
+ @field_validator("points")
75
+ @classmethod
76
+ def validate_points_length(cls, v: list[PointSchema]) -> list[PointSchema]:
77
+ if len(v) < MIN_POINTS:
78
+ raise ValueError(f"At least {MIN_POINTS} points are required")
79
+ if len(v) > MAX_POINTS:
80
+ raise ValueError(f"At most {MAX_POINTS} points are allowed")
81
+ return v
82
+
83
+ @model_validator(mode="after")
84
+ def check_roles_and_ids(self) -> "OptimizeRequestSchema":
85
+ starts = [p for p in self.points if p.role == "start"]
86
+ ends = [p for p in self.points if p.role == "end"]
87
+ if len(starts) != 1:
88
+ raise ValueError('Exactly one point must have role "start"')
89
+ if len(ends) != 1:
90
+ raise ValueError('Exactly one point must have role "end"')
91
+
92
+ ids = [p.id for p in self.points]
93
+ if len(ids) != len(set(ids)):
94
+ raise ValueError("Point IDs must be unique")
95
+ return self
96
+
97
+
98
+ def parse_optimize_request(body: dict[str, Any]) -> OptimizeRequest:
99
+ try:
100
+ schema = OptimizeRequestSchema.model_validate(body)
101
+ except Exception as e:
102
+ raise ValidationError(str(e)) from e
103
+
104
+ points = [
105
+ Point(id=p.id, lat=p.lat, lng=p.lng, role=p.role, label=p.label) for p in schema.points
106
+ ]
107
+
108
+ if schema.config:
109
+ config = GAConfig(
110
+ populationSize=schema.config.populationSize,
111
+ generations=schema.config.generations,
112
+ mutationRate=schema.config.mutationRate,
113
+ elitismCount=schema.config.elitismCount,
114
+ tournamentSize=schema.config.tournamentSize,
115
+ objective=schema.config.objective,
116
+ randomSeed=schema.config.randomSeed,
117
+ )
118
+ else:
119
+ config = DEFAULT_GA_CONFIG
120
+
121
+ return OptimizeRequest(points=points, config=config)
122
+
123
+
124
+ def require_start_and_end(points: list[Point]) -> tuple[Point, Point]:
125
+ """Defensive invariant used by both solvers."""
126
+ start = next((p for p in points if p.role == "start"), None)
127
+ end = next((p for p in points if p.role == "end"), None)
128
+ if start is None or end is None:
129
+ raise ValueError("Points must include exactly one start and one end")
130
+ return start, end
@@ -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,16 @@
1
+ vrp_solver/__init__.py,sha256=ThJt3wbTsaaXUs9fjaHUbvqmW6yXi7Owg655nbwCL2E,764
2
+ vrp_solver/cli.py,sha256=bdr1x6SRW5pb3PvXbfjGxq49hxH2rGy0JOmvnaRFr-I,2051
3
+ vrp_solver/constants.py,sha256=rSDPGZM7i1IhxnUijNJLyNkmpcwAid52h8ILATD1Lqs,802
4
+ vrp_solver/distance.py,sha256=MB0Anpror86070FVmMDpCcW25LCRFnAEfEA76zeNwss,2193
5
+ vrp_solver/ga.py,sha256=qCCFxvMEowfQ7xv94hsP3A-jEwP2cCeZRiGBmxkt44c,3307
6
+ vrp_solver/nearest_neighbor.py,sha256=ZYRl1sKQxeIB4R5aJjnAEf7aoRghw6DfxsFF9xRUaQ4,1240
7
+ vrp_solver/operators.py,sha256=ZF-ckNwWOoacB4BeX2C4nya9z5jiyEkfD-SyiYzYCcA,1905
8
+ vrp_solver/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
9
+ vrp_solver/rng.py,sha256=MpuX4eIMcx6CC0sMvWB2E79vLnDueKXlTPSjNB1JiyE,1261
10
+ vrp_solver/types.py,sha256=cMHlLH_X6USixEbzU_TCexNEjtLv6c8OmE-OYpuTAXU,1316
11
+ vrp_solver/validation.py,sha256=u8YBL2PCdYH6brB191cN97Mg0_oZAs_fQezGHiZqZ_A,4481
12
+ vrp_solver-0.1.0.dist-info/METADATA,sha256=H-xstGCHG2GCqToN-k4NsD53G5-bmAvpKa8fmIv5-I0,6480
13
+ vrp_solver-0.1.0.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
14
+ vrp_solver-0.1.0.dist-info/entry_points.txt,sha256=JTsnvQXHqEM4HXqlDPSGgIo2hRx2jwgph1JfX3u0Fd4,50
15
+ vrp_solver-0.1.0.dist-info/licenses/LICENSE,sha256=JJMgFUHOch_NxMj6nKPd2K1xI91egZeWQNNB4CPVKyU,1092
16
+ vrp_solver-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.33.0
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
@@ -0,0 +1,2 @@
1
+ [console_scripts]
2
+ vrp-solver = vrp_solver.cli:app
@@ -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.