-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathsolution.go
1363 lines (1174 loc) · 38.2 KB
/
solution.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
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// © 2019-present nextmv.io inc
package nextroute
import (
"context"
"fmt"
"math"
"math/rand"
"reflect"
"slices"
"strings"
"sync"
"github.com/nextmv-io/nextroute/common"
)
// Solution is a solution to a model.
type Solution interface {
// BestMove returns the best move for the given solution plan unit. The
// best move is the move that has the lowest score. If there are no moves
// available for the given solution plan unit, a move is returned which
// is not executable, SolutionMoveStops.IsExecutable.
BestMove(context.Context, SolutionPlanUnit) SolutionMove
// ConstraintData returns the data of the constraint for the solution. The
// constraint data of a solution is set by the
// ConstraintSolutionDataUpdater.UpdateConstraintSolutionData method of the
// constraint.
ConstraintData(constraint ModelConstraint) any
// Copy returns a deep copy of the solution.
Copy() Solution
// FixedPlanUnits returns the solution plan units that are fixed.
// Fixed plan units are plan units that are not allowed to be planned or
// unplanned. The union of fixed, planned and unplanned plan units
// is the set of all plan units in the model.
FixedPlanUnits() ImmutableSolutionPlanUnitCollection
// Model returns the model of the solution.
Model() Model
// ObjectiveData returns the value of the objective for the solution. The
// objective value of a solution is set by the
// ObjectiveSolutionDataUpdater.UpdateObjectiveSolutionData method of the
// objective. If the objective is not set on the solution, nil is returned.
ObjectiveData(objective ModelObjective) any
// ObjectiveValue returns the objective value for the objective in the
// solution. Also returns 0.0 if the objective is not part of the solution.
ObjectiveValue(objective ModelObjective) float64
// PlannedPlanUnits returns the solution plan units that are planned as
// a collection of solution plan units.
PlannedPlanUnits() ImmutableSolutionPlanUnitCollection
// Random returns the random number generator of the solution.
Random() *rand.Rand
// Score returns the score of the solution.
Score() float64
// SetRandom sets the random number generator of the solution. Returns an
// error if the random number generator is nil.
SetRandom(random *rand.Rand) error
// SolutionPlanStopsUnit returns the [SolutionPlanStopsUnit] for the given
// model plan unit.
SolutionPlanStopsUnit(planUnit ModelPlanStopsUnit) SolutionPlanStopsUnit
// SolutionPlanUnit returns the [SolutionPlanUnit] for the given
// model plan unit.
SolutionPlanUnit(planUnit ModelPlanUnit) SolutionPlanUnit
// SolutionStop returns the solution stop for the given model stop.
SolutionStop(stop ModelStop) SolutionStop
// SolutionVehicle returns the solution vehicle for the given model vehicle.
SolutionVehicle(vehicle ModelVehicle) SolutionVehicle
// UnPlannedPlanUnits returns the solution plan units that are not
// planned.
UnPlannedPlanUnits() ImmutableSolutionPlanUnitCollection
// Vehicles returns the vehicles of the solution.
Vehicles() SolutionVehicles
}
// Solutions is a slice of solutions.
type Solutions []Solution
// NewSolution returns a new Solution.
func NewSolution(
m Model,
) (Solution, error) {
model := m.(*modelImpl)
err := model.lock()
if err != nil {
return nil, err
}
model.OnNewSolution(m)
nrStops := 0
nrFixedPlanUnits := 0
nrPropositionPlanUnits := 0
nrVehicles := len(model.vehicles)
for _, planUnit := range model.PlanUnits() {
if planStopsUnit, ok := planUnit.(ModelPlanStopsUnit); ok {
nrStops += len(planStopsUnit.Stops())
}
if planUnit.IsFixed() {
nrFixedPlanUnits++
}
if _, isElementOfPlanUnitsUnit := planUnit.PlanUnitsUnit(); isElementOfPlanUnitsUnit {
nrPropositionPlanUnits++
}
}
random := rand.New(rand.NewSource(m.Random().Int63()))
nExpressions := len(model.expressions)
solution := &solutionImpl{
model: m,
vehicleIndices: make([]int, 0, nrVehicles),
vehicles: make([]SolutionVehicle, 0, nrVehicles),
solutionVehicles: make([]SolutionVehicle, 0, nrVehicles),
first: make([]int, 0, nrVehicles),
last: make([]int, 0, nrVehicles),
stop: make([]int, 0, nrStops),
inVehicle: make([]int, 0, nrStops),
previous: make([]int, 0, nrStops),
next: make([]int, 0, nrStops),
stopPosition: make([]int, 0, nrStops),
cumulativeTravelDuration: make([]float64, 0, nrStops),
arrival: make([]float64, 0, nrStops),
slack: make([]float64, 0, nrStops),
start: make([]float64, 0, nrStops),
end: make([]float64, 0, nrStops),
values: make(map[int][]float64, nExpressions),
cumulativeValues: make(map[int][]float64, nExpressions),
stopToPlanUnit: make([]*solutionPlanStopsUnitImpl, nrStops),
constraintStopData: make(map[ModelConstraint][]Copier),
objectiveStopData: make(map[ModelObjective][]Copier),
constraintSolutionData: make(map[ModelConstraint]Copier),
objectiveSolutionData: make(map[ModelObjective]Copier),
random: random,
fixedPlanUnits: newSolutionPlanUnitCollectionBaseImpl(
random,
len(model.planUnits),
),
plannedPlanUnits: newSolutionPlanUnitCollectionBaseImpl(
random,
len(model.planUnits),
),
unPlannedPlanUnits: newSolutionPlanUnitCollectionBaseImpl(
random,
len(model.planUnits),
),
propositionPlanUnits: newSolutionPlanUnitCollectionBaseImpl(
random,
len(model.planUnits),
),
}
for _, expression := range model.expressions {
solution.values[expression.Index()] = make([]float64, nrStops)
solution.cumulativeValues[expression.Index()] = make([]float64, nrStops)
}
for _, constraint := range model.constraintsWithStopUpdater {
solution.constraintStopData[constraint] = make([]Copier, nrStops)
}
for _, objective := range model.objectivesWithStopUpdater {
solution.objectiveStopData[objective] = make([]Copier, nrStops)
}
stopsUsed := make(map[int]bool)
stopIdx := 0
idxToPlanUnit := make(map[int]SolutionPlanUnit)
for _, planUnit := range model.PlanStopsUnits() {
solutionPlanUnit := &solutionPlanStopsUnitImpl{
modelPlanStopsUnit: planUnit,
solutionStops: make(
[]SolutionStop,
len(planUnit.Stops()),
),
}
idxToPlanUnit[planUnit.Index()] = solutionPlanUnit
for idx, stop := range planUnit.Stops() {
if _, ok := stopsUsed[stop.Index()]; ok {
return nil, fmt.Errorf(
"stop %v is used more than once in one or"+
"more plan planUnit %v",
stop,
planUnit,
)
}
solutionStop := toSolutionStop(
solution,
stopIdx,
)
solutionPlanUnit.solutionStops[idx] = solutionStop
solution.stopToPlanUnit[solutionStop.Index()] = solutionPlanUnit
stopIdx++
solution.stop = append(
solution.stop,
stop.Index(),
)
solution.inVehicle = append(
solution.inVehicle,
-1,
)
solution.previous = append(
solution.previous,
solutionPlanUnit.solutionStops[idx].Index(),
)
solution.next = append(
solution.next,
solutionPlanUnit.solutionStops[idx].Index(),
)
solution.stopPosition = append(
solution.stopPosition,
-1,
)
solution.cumulativeTravelDuration = append(
solution.cumulativeTravelDuration,
0,
)
solution.arrival = append(
solution.arrival,
0,
)
solution.slack = append(
solution.slack,
math.MaxFloat64,
)
solution.start = append(
solution.start,
0,
)
solution.end = append(
solution.end,
0,
)
}
if _, isElementOfPlanUnitsUnit := planUnit.PlanUnitsUnit(); isElementOfPlanUnitsUnit {
solution.propositionPlanUnits.add(solutionPlanUnit)
} else {
solution.unPlannedPlanUnits.add(solutionPlanUnit)
}
}
for _, planUnit := range model.PlanUnits() {
if modelPlanUnitsUnit, ok := planUnit.(ModelPlanUnitsUnit); ok {
solutionPlanUnitsUnit := &solutionPlanUnitsUnitImpl{
modelPlanUnitsUnit: modelPlanUnitsUnit,
solutionPlanUnits: make(
SolutionPlanUnits,
len(modelPlanUnitsUnit.PlanUnits()),
),
}
for idx, modelPlanUnit := range modelPlanUnitsUnit.PlanUnits() {
if _, ok := idxToPlanUnit[modelPlanUnit.Index()]; !ok {
return nil, fmt.Errorf(
"can not find the solution plan unit for mode plan unit %v,"+
", should never happen, contact support",
modelPlanUnit,
)
}
solutionPlanUnitsUnit.solutionPlanUnits[idx] = idxToPlanUnit[modelPlanUnit.Index()]
}
idxToPlanUnit[modelPlanUnitsUnit.Index()] = solutionPlanUnitsUnit
if _, isElementOfPlanUnitsUnit := modelPlanUnitsUnit.PlanUnitsUnit(); isElementOfPlanUnitsUnit {
solution.propositionPlanUnits.add(solutionPlanUnitsUnit)
} else {
solution.unPlannedPlanUnits.add(solutionPlanUnitsUnit)
}
}
}
for _, vehicle := range model.vehicles {
v, err := solution.newVehicle(vehicle)
if err != nil {
return nil, err
}
if v.Index() != vehicle.Index() {
return nil, fmt.Errorf(
"vehicle index %v does not match expected %v",
v.Index(),
vehicle.Index(),
)
}
}
if err := solution.addInitialSolution(m); err != nil {
return nil, err
}
m.OnNewSolutionCreated(solution)
return solution, nil
}
func (s *solutionImpl) unwrapRootPlanUnit(planUnit SolutionPlanUnit) SolutionPlanUnit {
planUnitsUnit, isElementOfPlanUnitsUnit := planUnit.ModelPlanUnit().PlanUnitsUnit()
for isElementOfPlanUnitsUnit {
planUnit = s.solutionPlanUnitsUnit(planUnitsUnit)
planUnitsUnit, isElementOfPlanUnitsUnit = planUnit.ModelPlanUnit().PlanUnitsUnit()
}
return planUnit
}
func reportInfeasibleInitialSolution(
move SolutionMoveStops,
constraint ModelConstraint,
) string {
stopIDs := common.MapSlice(
move.StopPositions(),
func(stopPosition StopPosition) []string {
return []string{stopPosition.Stop().ModelStop().ID()}
})
name := reflect.TypeOf(constraint).Name()
stringer, ok := constraint.(fmt.Stringer)
if ok {
name = stringer.String()
}
identifier, ok := constraint.(Identifier)
if ok {
name = identifier.ID()
}
return fmt.Sprintf("infeasible initial solution: vehicle `%v` violates constraint `%v` for stops [%v]",
move.Vehicle().ModelVehicle().ID(),
name,
strings.Join(stopIDs, ", "),
)
}
func (s *solutionImpl) addInitialSolution(m Model) error {
model := m.(*modelImpl)
solutionObserver := newInitialSolutionObserver()
model.AddSolutionObserver(solutionObserver)
defer model.RemoveSolutionObserver(solutionObserver)
for _, modelVehicle := range model.vehicles {
solutionVehicle, ok := s.solutionVehicle(modelVehicle)
if !ok {
return fmt.Errorf(
"vehicle %v not found in solution",
modelVehicle.ID(),
)
}
initialModelStops := modelVehicle.Stops()
if len(initialModelStops) == 0 {
continue
}
planUnits := common.UniqueDefined(
common.Map(
initialModelStops,
func(modelStop ModelStop) SolutionPlanStopsUnit {
return s.SolutionStop(modelStop).PlanStopsUnit()
}),
func(planUnit SolutionPlanStopsUnit) int {
return planUnit.ModelPlanStopsUnit().Index()
},
)
infeasiblePlanUnits := map[SolutionPlanUnit]bool{}
allPlanUnits := map[SolutionPlanUnit]bool{}
PlanUnitLoop:
for _, planUnit := range planUnits {
stopPositions := make(StopPositions, 0, len(planUnit.SolutionStops()))
previousStop := solutionVehicle.First()
solutionPlanUnit := s.unwrapRootPlanUnit(planUnit)
allPlanUnits[solutionPlanUnit] = true
ModelStopLoop:
for modelStopIdx, modelStop := range initialModelStops {
if len(stopPositions) == len(planUnit.SolutionStops()) {
break
}
planUnitsUnit, hasPlanUnitsUnit := planUnit.ModelPlanUnit().PlanUnitsUnit()
if hasPlanUnitsUnit && planUnitsUnit.PlanOneOf() {
solutionPlanUnitsUnit := s.solutionPlanUnitsUnit(planUnitsUnit)
if solutionPlanUnitsUnit.IsPlanned() {
return fmt.Errorf(
"infeasible initial solution: stop %v on vehicle %v is part of one-of plan unit [%v]"+
" which is already planned",
modelStop.ID(),
modelVehicle.ID(),
strings.Join(
common.MapSlice(
planUnitsUnit.PlanUnits(),
func(stop ModelPlanUnit) []string {
return []string{fmt.Sprintf("%v", stop)}
}),
", ",
),
)
}
}
solutionStop := s.SolutionStop(modelStop)
if solutionStop.IsPlanned() {
previousStop = solutionStop
}
if modelStop.PlanStopsUnit().Index() == planUnit.ModelPlanStopsUnit().Index() {
for nextIdx := modelStopIdx + 1; nextIdx < len(initialModelStops); nextIdx++ {
nextModelStop := initialModelStops[nextIdx]
nextSolutionStop := s.SolutionStop(nextModelStop)
if nextSolutionStop.IsPlanned() ||
nextModelStop.PlanStopsUnit().Index() == planUnit.ModelPlanStopsUnit().Index() {
stopPositions = append(
stopPositions,
newStopPosition(
previousStop,
solutionStop,
nextSolutionStop,
),
)
previousStop = solutionStop
continue ModelStopLoop
}
if nextSolutionStop.IsPlanned() {
previousStop = solutionStop
}
}
stopPositions = append(
stopPositions,
newStopPosition(
previousStop,
solutionStop,
solutionVehicle.Last(),
),
)
}
}
move, err := newMoveStops(planUnit, stopPositions, false)
if err != nil {
return err
}
for _, constraint := range model.constraints {
if filterConstraint(constraint, false) {
continue
}
isViolated, hint := constraint.EstimateIsViolated(move)
if hint == nil {
return newErrorOnNilHint(constraint)
}
s.Model().OnEstimatedIsViolated(move, constraint, isViolated, hint)
if isViolated {
if solutionPlanUnit.IsFixed() {
return fmt.Errorf(
reportInfeasibleInitialSolution(
move,
constraint,
),
)
}
infeasiblePlanUnits[solutionPlanUnit] = true
continue PlanUnitLoop
}
}
index, err := move.(*solutionMoveStopsImpl).attach()
if err != nil {
return err
}
constraint, _, err := s.isFeasible(index, false)
if err != nil {
return err
}
if constraint != nil {
if planUnit.IsFixed() {
return fmt.Errorf(
reportInfeasibleInitialSolution(
move,
solutionObserver.Constraint(),
),
)
}
for _, position := range move.(*solutionMoveStopsImpl).stopPositions {
position.Stop().detach()
}
infeasiblePlanUnits[solutionPlanUnit] = true
continue
}
}
constraint, index, err := s.isFeasible(solutionVehicle.First().Index(), true)
for ; constraint != nil; constraint, index, err = s.isFeasible(solutionVehicle.First().Index(), true) {
if err != nil {
return err
}
if index == solutionVehicle.First().Index() {
return fmt.Errorf("infeasible initial solution at start of vehicle: %v", constraint)
}
for index == solutionVehicle.Last().Index() ||
s.unwrapRootPlanUnit(s.stopToPlanUnit[index]).IsFixed() {
index = s.previous[index]
if index == solutionVehicle.First().Index() {
return fmt.Errorf(
"no feasible route from start to end found for vehicle %v"+
" due to constraint %v, no further stops to remove",
solutionVehicle.ModelVehicle().ID(),
constraint)
}
}
for _, solutionPlanUnit := range s.unwrapRootPlanUnit(s.stopToPlanUnit[index]).PlannedPlanStopsUnits() {
if solutionPlanUnit.IsPlanned() {
for _, solutionStop := range solutionPlanUnit.SolutionStops() {
solutionStop.detach()
}
}
}
infeasiblePlanUnits[s.unwrapRootPlanUnit(s.stopToPlanUnit[index])] = true
}
for solutionPlanUnit := range allPlanUnits {
if _, ok := infeasiblePlanUnits[solutionPlanUnit]; ok {
continue
}
s.unPlannedPlanUnits.remove(solutionPlanUnit)
if solutionPlanUnit.IsFixed() {
s.fixedPlanUnits.add(solutionPlanUnit)
} else {
s.plannedPlanUnits.add(solutionPlanUnit)
}
}
// Make sure all constraints and objectives are up-to-date
_, _, err = s.isFeasible(solutionVehicle.First().Index(), true)
if err != nil {
return err
}
}
return nil
}
type solutionImpl struct {
model Model
scores map[ModelObjective]float64
values map[int][]float64
objectiveStopData map[ModelObjective][]Copier
constraintStopData map[ModelConstraint][]Copier
objectiveSolutionData map[ModelObjective]Copier
constraintSolutionData map[ModelConstraint]Copier
cumulativeValues map[int][]float64
// TODO: explore if stopToPlanUnit should rather contain interfaces
stopToPlanUnit []*solutionPlanStopsUnitImpl
random *rand.Rand
plannedPlanUnits solutionPlanUnitCollectionBaseImpl
fixedPlanUnits solutionPlanUnitCollectionBaseImpl
unPlannedPlanUnits solutionPlanUnitCollectionBaseImpl
propositionPlanUnits solutionPlanUnitCollectionBaseImpl
vehicleIndices []int
// TODO: explore if vehicles should rather be interfaces, then we can avoid creating new vehicles on the fly
vehicles []SolutionVehicle
solutionVehicles []SolutionVehicle
start []float64
slack []float64
arrival []float64
next []int
stopPosition []int
first []int
stop []int
cumulativeTravelDuration []float64
end []float64
previous []int
inVehicle []int
last []int
randomMutex sync.Mutex
}
func (s *solutionImpl) SolutionPlanStopsUnit(planUnit ModelPlanStopsUnit) SolutionPlanStopsUnit {
if planUnit == nil {
return nil
}
return s.solutionPlanStopsUnit(planUnit)
}
func (s *solutionImpl) SolutionPlanUnit(planUnit ModelPlanUnit) SolutionPlanUnit {
if planUnit == nil {
return nil
}
return s.solutionPlanUnit(planUnit)
}
func (s *solutionImpl) solutionPlanUnit(planUnit ModelPlanUnit) SolutionPlanUnit {
solutionPlanUnit := s.plannedPlanUnits.SolutionPlanUnit(planUnit)
if solutionPlanUnit != nil {
return solutionPlanUnit
}
solutionPlanUnit = s.unPlannedPlanUnits.SolutionPlanUnit(planUnit)
if solutionPlanUnit != nil {
return solutionPlanUnit
}
solutionPlanUnit = s.fixedPlanUnits.SolutionPlanUnit(planUnit)
if solutionPlanUnit != nil {
return solutionPlanUnit
}
solutionPlanUnit = s.propositionPlanUnits.SolutionPlanUnit(planUnit)
if solutionPlanUnit != nil {
return solutionPlanUnit
}
return nil
}
func (s *solutionImpl) solutionPlanStopsUnit(planUnit ModelPlanStopsUnit) *solutionPlanStopsUnitImpl {
return s.solutionPlanUnit(planUnit).(*solutionPlanStopsUnitImpl)
}
func (s *solutionImpl) solutionPlanUnitsUnit(planUnit ModelPlanUnitsUnit) *solutionPlanUnitsUnitImpl {
return s.solutionPlanUnit(planUnit).(*solutionPlanUnitsUnitImpl)
}
func (s *solutionImpl) SolutionStop(stop ModelStop) SolutionStop {
if stop != nil && stop.HasPlanStopsUnit() {
return s.SolutionPlanStopsUnit(stop.PlanStopsUnit()).SolutionStop(stop)
}
return SolutionStop{}
}
func (s *solutionImpl) SolutionVehicle(vehicle ModelVehicle) SolutionVehicle {
if solutionVehicle, ok := s.solutionVehicle(vehicle); ok {
return solutionVehicle
}
return SolutionVehicle{}
}
func (s *solutionImpl) solutionVehicle(vehicle ModelVehicle) (SolutionVehicle, bool) {
if vehicle != nil {
return SolutionVehicle{
index: vehicle.Index(),
solution: s,
}, true
}
return SolutionVehicle{}, false
}
func (s *solutionImpl) Copy() Solution {
model := s.model.(*modelImpl)
model.OnCopySolution(s)
s.randomMutex.Lock()
random := rand.New(rand.NewSource(s.random.Int63()))
s.randomMutex.Unlock()
// in order to reduce the number of allocations, we allocate
// larger chunks of memory for the slices and then slice them
// to the correct size
nrStops := len(s.stop)
nrVehicles := len(s.vehicles)
nrExpressions := len(model.expressions)
ints := make([]int, 5*nrStops+3*nrVehicles)
first, ints := common.CopySliceFrom(ints, s.first)
vehicleIndices, ints := common.CopySliceFrom(ints, s.vehicleIndices)
last, ints := common.CopySliceFrom(ints, s.last)
inVehicle, ints := common.CopySliceFrom(ints, s.inVehicle)
previous, ints := common.CopySliceFrom(ints, s.previous)
next, ints := common.CopySliceFrom(ints, s.next)
stopPosition, ints := common.CopySliceFrom(ints, s.stopPosition)
stop, _ := common.CopySliceFrom(ints, s.stop)
floats := make([]float64, (5+2*nrExpressions)*nrStops)
start, floats := common.CopySliceFrom(floats, s.start)
end, floats := common.CopySliceFrom(floats, s.end)
arrival, floats := common.CopySliceFrom(floats, s.arrival)
slack, floats := common.CopySliceFrom(floats, s.slack)
cumulativeTravelDuration, floats := common.CopySliceFrom(floats, s.cumulativeTravelDuration)
solution := &solutionImpl{
arrival: arrival,
slack: slack,
constraintStopData: make(map[ModelConstraint][]Copier, len(s.constraintStopData)),
objectiveStopData: make(map[ModelObjective][]Copier, len(s.objectiveStopData)),
constraintSolutionData: make(map[ModelConstraint]Copier, len(s.constraintSolutionData)),
objectiveSolutionData: make(map[ModelObjective]Copier, len(s.objectiveSolutionData)),
cumulativeTravelDuration: cumulativeTravelDuration,
cumulativeValues: make(map[int][]float64, len(s.cumulativeValues)),
stopToPlanUnit: make([]*solutionPlanStopsUnitImpl, len(s.stopToPlanUnit)),
end: end,
first: first,
inVehicle: inVehicle,
last: last,
model: model,
next: next,
previous: previous,
start: start,
stop: stop,
stopPosition: stopPosition,
values: make(map[int][]float64, len(s.values)),
vehicleIndices: vehicleIndices,
random: random,
fixedPlanUnits: newSolutionPlanUnitCollectionBaseImpl(
random, s.fixedPlanUnits.Size(),
),
plannedPlanUnits: newSolutionPlanUnitCollectionBaseImpl(
random, s.plannedPlanUnits.Size(),
),
unPlannedPlanUnits: newSolutionPlanUnitCollectionBaseImpl(
random, s.unPlannedPlanUnits.Size(),
),
propositionPlanUnits: newSolutionPlanUnitCollectionBaseImpl(
random, s.propositionPlanUnits.Size(),
),
scores: make(map[ModelObjective]float64, len(s.scores)),
}
solution.vehicles = slices.Clone(s.vehicles)
solution.solutionVehicles = slices.Clone(s.solutionVehicles)
// update solution reference
for idx := range solution.vehicles {
solution.vehicles[idx].solution = solution
solution.solutionVehicles[idx] = solution.vehicles[idx]
}
for _, expression := range model.expressions {
eIndex := expression.Index()
solution.cumulativeValues[eIndex], floats = common.CopySliceFrom(floats, s.cumulativeValues[eIndex])
solution.values[eIndex], floats = common.CopySliceFrom(floats, s.values[eIndex])
}
for _, constraint := range model.constraintsWithStopUpdater {
solution.constraintStopData[constraint] = make(
[]Copier,
len(s.constraintStopData[constraint]),
)
for idx, data := range s.constraintStopData[constraint] {
if data == nil {
solution.constraintStopData[constraint][idx] = nil
} else {
solution.constraintStopData[constraint][idx] = data.Copy()
}
}
}
for _, constraint := range model.constraintsWithSolutionUpdater {
if s.constraintSolutionData[constraint] != nil {
solution.constraintSolutionData[constraint] = s.constraintSolutionData[constraint].Copy()
}
}
for _, objective := range model.objectivesWithStopUpdater {
solution.objectiveStopData[objective] = make(
[]Copier,
len(s.objectiveStopData[objective]),
)
for idx, data := range s.objectiveStopData[objective] {
if data == nil {
solution.objectiveStopData[objective][idx] = nil
} else {
solution.objectiveStopData[objective][idx] = data.Copy()
}
}
}
for _, objective := range model.objectivesWithSolutionUpdater {
if s.objectiveSolutionData[objective] != nil {
solution.objectiveSolutionData[objective] = s.objectiveSolutionData[objective].Copy()
}
}
for _, solutionPlanUnit := range s.fixedPlanUnits.solutionPlanUnits {
solution.fixedPlanUnits.add(copySolutionPlanUnit(solutionPlanUnit, solution))
}
for _, solutionPlanUnit := range s.plannedPlanUnits.solutionPlanUnits {
solution.plannedPlanUnits.add(copySolutionPlanUnit(solutionPlanUnit, solution))
}
for _, solutionPlanUnit := range s.unPlannedPlanUnits.solutionPlanUnits {
solution.unPlannedPlanUnits.add(copySolutionPlanUnit(solutionPlanUnit, solution))
}
for idx, score := range s.scores {
solution.scores[idx] = score
}
model.OnCopiedSolution(solution)
return solution
}
func (s *solutionImpl) SetRandom(random *rand.Rand) error {
if random == nil {
return fmt.Errorf("random is nil")
}
s.random = random
return nil
}
func (s *solutionImpl) Random() *rand.Rand {
return s.random
}
func (s *solutionImpl) newVehicle(
modelVehicle ModelVehicle,
) (SolutionVehicle, error) {
if modelVehicle == nil {
return SolutionVehicle{}, fmt.Errorf("modelVehicle is nil")
}
model := s.model.(*modelImpl)
start := modelVehicle.Start().Sub(model.Epoch()) / model.DurationUnit()
s.arrival = append(s.arrival, float64(start), 0)
s.slack = append(s.slack, math.MaxFloat64, math.MaxFloat64)
s.cumulativeTravelDuration = append(s.cumulativeTravelDuration, 0, 0)
s.end = append(s.end, float64(start), 0)
s.first = append(s.first, len(s.stop))
s.inVehicle = append(s.inVehicle, len(s.vehicles), len(s.vehicles))
s.last = append(s.last, len(s.stop)+1)
s.next = append(s.next, len(s.next)+1, len(s.next)+1)
s.previous = append(s.previous, len(s.previous), len(s.previous))
s.stopPosition = append(s.stopPosition, 0, 1)
s.start = append(s.start, float64(start), 0)
s.stop = append(
s.stop,
modelVehicle.First().Index(),
modelVehicle.Last().Index(),
)
s.vehicleIndices = append(s.vehicleIndices, modelVehicle.Index())
s.vehicles = append(s.vehicles, SolutionVehicle{
index: modelVehicle.Index(),
solution: s,
})
s.solutionVehicles = append(s.solutionVehicles, SolutionVehicle{
index: modelVehicle.Index(),
solution: s,
})
for _, expression := range model.expressions {
value := expression.Value(
modelVehicle.VehicleType(),
modelVehicle.First(),
modelVehicle.First(),
)
s.values[expression.Index()] = append(
s.values[expression.Index()],
value,
0,
)
s.cumulativeValues[expression.Index()] = append(
s.cumulativeValues[expression.Index()],
value,
value,
)
}
for _, constraint := range model.constraintsWithStopUpdater {
s.constraintStopData[constraint] = append(
s.constraintStopData[constraint],
nil,
nil,
)
}
for _, objective := range model.objectivesWithStopUpdater {
s.objectiveStopData[objective] = append(
s.objectiveStopData[objective],
nil,
nil,
)
}
constraint, _, err := s.isFeasible(len(s.stop)-2, true)
if err != nil {
return SolutionVehicle{}, err
}
if constraint != nil {
return SolutionVehicle{}, fmt.Errorf("failed creating new vehicle: %v", constraint)
}
return toSolutionVehicle(s, len(s.vehicles)-1), nil
}
func (s *solutionImpl) checkConstraintsAndEstimateDeltaScore(
m SolutionMoveStops,
) (deltaScore float64, feasible bool, planPositionsHint StopPositionsHint) {
model := s.model.(*modelImpl)
for _, constraint := range model.constraints {
s.model.OnEstimateIsViolated(
constraint,
)
var isViolated bool
var hint *stopPositionHintImpl
isViolatedTemp, hintTemp := constraint.EstimateIsViolated(m)
if hintTemp == nil {
panic(newErrorOnNilHint(constraint))
}
hint = hintTemp.(*stopPositionHintImpl)
isViolated = isViolatedTemp
s.model.OnEstimatedIsViolated(
m,
constraint,
isViolated,
hint,
)
if isViolated {
return 0.0, false, hint
}
}
s.model.OnEstimateDeltaObjectiveScore()
objectiveEstimate := 0.0
objectiveEstimate = s.Model().Objective().EstimateDeltaValue(m)
s.model.OnEstimatedDeltaObjectiveScore(objectiveEstimate)
return objectiveEstimate,
true,
constNoPositionsHint
}
var constNoPositionsHintImpl = noPositionsHint()
func (s *solutionImpl) checkConstraints(
m SolutionMoveStops,
) (feasible bool, planPositionsHint *stopPositionHintImpl) {
model := s.model.(*modelImpl)
for _, constraint := range model.constraints {
s.model.OnEstimateIsViolated(
constraint,
)
var isViolated bool
var hint *stopPositionHintImpl
isViolatedTemp, hintTemp := constraint.EstimateIsViolated(m)
if hintTemp == nil {
panic(newErrorOnNilHint(constraint))
}
hint = hintTemp.(*stopPositionHintImpl)
isViolated = isViolatedTemp
s.model.OnEstimatedIsViolated(
m,
constraint,
isViolated,
hint,
)
if isViolated {
return false, hint
}
}
return true, constNoPositionsHintImpl
}
func (s *solutionImpl) estimateDeltaScore(
m SolutionMoveStops,
) (deltaScore float64) {
s.model.OnEstimateDeltaObjectiveScore()