-
Notifications
You must be signed in to change notification settings - Fork 4
/
model_objective_unplanned.go
96 lines (84 loc) · 2.35 KB
/
model_objective_unplanned.go
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
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
// © 2019-present nextmv.io inc
package nextroute
import "fmt"
// UnPlannedObjective is an objective that uses the un-planned stops as an
// objective. Each unplanned stop is scored by the given expression.
type UnPlannedObjective interface {
ModelObjective
}
// NewUnPlannedObjective returns a new UnPlannedObjective.
func NewUnPlannedObjective(
expression StopExpression,
) UnPlannedObjective {
return &unplannedObjectiveImpl{
expression: expression,
}
}
type unplannedObjectiveImpl struct {
expression StopExpression
costs []float64
}
func (t *unplannedObjectiveImpl) calculateCosts(
planUnit ModelPlanUnit,
) (float64, error) {
switch unit := planUnit.(type) {
case ModelPlanStopsUnit:
cost := 0.0
for _, stop := range unit.Stops() {
cost += t.expression.Value(nil, nil, stop)
}
return cost, nil
case ModelPlanUnitsUnit:
cost := 0.0
for _, planUnit := range unit.PlanUnits() {
c, err := t.calculateCosts(planUnit)
if err != nil {
return 0, err
}
cost += c
}
if unit.PlanOneOf() {
// we take the average cost of planing one unit
return cost / float64(len(unit.PlanUnits())), nil
}
return cost, nil
default:
return 0, fmt.Errorf(
"model plan unit type is not recognized for the unplanned objective",
)
}
}
func (t *unplannedObjectiveImpl) Lock(model Model) error {
units := model.PlanUnits()
t.costs = make([]float64, len(units))
for _, planUnit := range units {
cost, err := t.calculateCosts(planUnit)
if err != nil {
return err
}
t.costs[planUnit.Index()] = cost
}
return nil
}
func (t *unplannedObjectiveImpl) ModelExpressions() ModelExpressions {
return ModelExpressions{}
}
func (t *unplannedObjectiveImpl) EstimateDeltaValue(move SolutionMoveStops) float64 {
return -1 * t.costs[move.(*solutionMoveStopsImpl).planUnit.modelPlanStopsUnit.Index()]
}
func (t *unplannedObjectiveImpl) Value(solution Solution) float64 {
unplannedScore := 0.0
units := solution.UnPlannedPlanUnits().(*solutionPlanUnitCollectionBaseImpl).solutionPlanUnits
for _, upu := range units {
switch upu := upu.(type) {
case *solutionPlanStopsUnitImpl:
unplannedScore += t.costs[upu.modelPlanStopsUnit.Index()]
case *solutionPlanUnitsUnitImpl:
unplannedScore += t.costs[upu.modelPlanUnitsUnit.Index()]
}
}
return unplannedScore
}
func (t *unplannedObjectiveImpl) String() string {
return "unplanned_penalty"
}