-
Notifications
You must be signed in to change notification settings - Fork 39
/
Result.py
75 lines (62 loc) · 2.01 KB
/
Result.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
import math
from dataclasses import dataclass
from pyvrp.Statistics import Statistics
from pyvrp._pyvrp import CostEvaluator, Solution
@dataclass
class Result:
"""
Stores the outcomes of a single run. An instance of this class is returned
once the GeneticAlgorithm completes.
Parameters
----------
best
The best observed solution.
stats
A Statistics object containing runtime statistics.
num_iterations
Number of iterations performed by the genetic algorithm.
runtime
Total runtime of the main genetic algorithm loop.
Raises
------
ValueError
When the number of iterations or runtime are negative.
"""
best: Solution
stats: Statistics
num_iterations: int
runtime: float
def __post_init__(self):
if self.num_iterations < 0:
raise ValueError("Negative number of iterations not understood.")
if self.runtime < 0:
raise ValueError("Negative runtime not understood.")
def cost(self) -> float:
"""
Returns the cost (objective) value of the best solution. Returns inf
if the best solution is infeasible.
"""
if not self.best.is_feasible():
return math.inf
return CostEvaluator(0, 0, 0).cost(self.best)
def is_feasible(self) -> bool:
"""
Returns whether the best solution is feasible.
"""
return self.best.is_feasible()
def __str__(self) -> str:
obj_str = f"{self.cost():.2f}" if self.is_feasible() else "INFEASIBLE"
summary = [
"Solution results",
"================",
f" # routes: {self.best.num_routes()}",
f" # clients: {self.best.num_clients()}",
f" objective: {obj_str}",
f"# iterations: {self.num_iterations}",
f" run-time: {self.runtime:.2f} seconds",
"",
"Routes",
"------",
str(self.best),
]
return "\n".join(summary)