-
Notifications
You must be signed in to change notification settings - Fork 16
/
CbsNode.cs
3155 lines (2885 loc) · 160 KB
/
CbsNode.cs
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
using System;
using System.Linq;
using System.Collections.Generic;
using System.Diagnostics;
using ExtensionMethods;
namespace mapf;
[DebuggerDisplay("hash = {GetHashCode()}, f = {f}, g = {g}, h = {h}")]
public class CbsNode : IComparable<IBinaryHeapItem>, IBinaryHeapItem, IHeuristicSearchNode
{
public int g { set; get; } // Value depends on Constants.costFunction and Constants.sumOfCostsVariant, Sum of agent makespans until they reach their goal
public int h { get; set; }
public int hBonus { get; set; }
/// <summary>
/// The size of the minimum vertex cover of the node's cardinal conflict graph.
/// Needs to be saved separately from h to allow speeding up the computation of the heuristic
/// of the children.
/// </summary>
public int minimumVertexCover;
public bool[] newPlans;
public SinglePlan[] singleAgentPlans;
public int[] singleAgentCosts;
/// <summary>
/// A lower estimate of the number of operations (replanning or merging) needed to solve the node.
/// Used for tie-breaking.
/// </summary>
public int minOpsToSolve;
/// <summary>
/// For each agent in the problem instance, saves the number of agents from the problem instance that it conflicts with.
/// Used for choosing the next conflict to resolve by replanning/merging/shuffling, and for tie-breaking.
/// </summary>
public int[] countsOfInternalAgentsThatConflict;
/// <summary>
/// Counts the number of external agents this node conflicts with.
/// Used for tie-breaking.
/// </summary>
public int totalExternalAgentsThatConflict;
/// <summary>
/// Used for tie-breaking.
/// </summary>
public int totalConflictsWithExternalAgents;
/// <summary>
/// For each agent in the problem instance, maps agent _nums_ it conflicts with, internal or external,
/// to the number of conflicts betweem them.
/// Used for book-keeping to maintain countsOfInternalAgentsThatConflict,
/// totalExternalAgentsThatConflict and minOpsToSolve, and other counts.
/// </summary>
public Dictionary<int, int>[] conflictCountsPerAgent;
/// <summary>
/// For each agent in the problem instance, maps agent _nums_ of agents it collides with to the time of their first collision.
/// </summary>
public Dictionary<int, List<int>>[] conflictTimesPerAgent;
private int binaryHeapIndex;
public CbsConflict conflict;
//public ISet<CbsConstraint> externalConstraints;
//public ISet<CbsConstraint> externalPositiveConstraints;
public CbsConstraint constraint;
/// <summary>
/// Forcing an agent to be at a certain place at a certain time
/// </summary>
CbsConstraint mustConstraint;
public CbsNode prev;
public ushort depth;
public ushort[] agentsGroupAssignment;
public ushort replanSize;
public enum ExpansionState: byte
{
NOT_EXPANDED = 0,
DEFERRED,
EXPANDED
}
/// <summary>
/// For partial expansion
/// </summary>
public ExpansionState agentAExpansion;
/// <summary>
/// For partial expansion
/// </summary>
public ExpansionState agentBExpansion;
protected ICbsSolver solver;
protected ICbsSolver singleAgentSolver;
public CBS cbs;
public Dictionary<int, int> agentNumToIndex;
public bool parentAlreadyLookedAheadOf;
/// <summary>
/// For tie-breaking
/// </summary>
public int totalInternalAgentsThatConflict;
/// <summary>
/// For tie-breaking
/// </summary>
public int largerConflictingGroupSize;
/// <summary>
/// For tie-breaking
/// </summary>
public int totalConflictsBetweenInternalAgents;
/// <summary>
/// For each agent, map each level (timestep) of its mdd to a narrowness degree.
/// Non-narrow levels are omitted.
/// </summary>
public Dictionary<int, MDD.LevelNarrowness>[] mddNarrownessValues;
/// <summary>
/// FIXME: We're currently saving both the MDDs and their much smaller narrowness values in
/// order to have a fair comparison with the past
/// </summary>
public MDD[] mdds;
/// <summary>
/// Root node constructor
/// </summary>
/// <param name="numberOfAgents"></param>
/// <param name="solver"></param>
/// <param name="singleAgentSolver"></param>
/// <param name="cbs"></param>
/// <param name="agentsGroupAssignment"></param>
public CbsNode(int numberOfAgents, ICbsSolver solver, ICbsSolver singleAgentSolver,
CBS cbs, ushort[] agentsGroupAssignment = null, ISet<CbsConstraint> externalConstraints = null, ISet<CbsConstraint> externalPositiveConstraints = null)
{
this.cbs = cbs;
singleAgentPlans = new SinglePlan[numberOfAgents];
newPlans = new bool[numberOfAgents];
singleAgentCosts = new int[numberOfAgents];
mddNarrownessValues = new Dictionary<int, MDD.LevelNarrowness>[numberOfAgents];
mdds = new MDD[numberOfAgents];
countsOfInternalAgentsThatConflict = new int[numberOfAgents];
conflictCountsPerAgent = new Dictionary<int, int>[numberOfAgents]; // Populated after Solve()
conflictTimesPerAgent = new Dictionary<int, List<int>>[numberOfAgents]; // Populated after Solve()
if (agentsGroupAssignment == null)
{
this.agentsGroupAssignment = new ushort[numberOfAgents];
for (ushort i = 0; i < numberOfAgents; i++)
this.agentsGroupAssignment[i] = i;
}
else
this.agentsGroupAssignment = agentsGroupAssignment.ToArray<ushort>();
agentNumToIndex = new Dictionary<int, int>();
for (int i = 0; i < numberOfAgents; i++)
{
agentNumToIndex[this.cbs.GetProblemInstance().agents[i].agent.agentNum] = i;
}
depth = 0;
replanSize = 1;
agentAExpansion = ExpansionState.NOT_EXPANDED;
agentBExpansion = ExpansionState.NOT_EXPANDED;
this.prev = null;
this.constraint = null;
this.solver = solver;
this.singleAgentSolver = singleAgentSolver;
this.minimumVertexCover = (int) ConflictGraph.MinVertexCover.NOT_SET;
}
/// <summary>
/// Child from branch action constructor
/// </summary>
/// <param name="parent"></param>
/// <param name="newConstraint"></param>
/// <param name="agentToReplan"></param>
public CbsNode(CbsNode parent, CbsConstraint newConstraint, int agentToReplan)
{
this.cbs = parent.cbs;
this.singleAgentPlans = parent.singleAgentPlans.ToArray();
newPlans = new bool[this.singleAgentPlans.Length];
this.singleAgentCosts = parent.singleAgentCosts.ToArray();
this.mdds = parent.mdds.ToArray();
this.mddNarrownessValues = parent.mddNarrownessValues.ToArray();
// Adapt the MDDs for the agent to replan, if possible
// The cost may increase, so the old MDD might not be relevant anymore.
if (this.mdds[agentToReplan] != null &&
this.mdds[agentToReplan].levels.Length - 1 > newConstraint.time &&
(this.mddNarrownessValues[agentToReplan].ContainsKey(newConstraint.time) == false ||
(this.mddNarrownessValues[agentToReplan][newConstraint.time] == MDD.LevelNarrowness.ONE_LOCATION_MULTIPLE_DIRECTIONS &&
newConstraint.move.direction != Move.Direction.NO_DIRECTION)))
{
// We have an MDD and same cost can still be achieved - adapt the existing MDD
double startTime = this.cbs.runner.ElapsedMilliseconds();
this.mdds[agentToReplan] = new MDD(this.mdds[agentToReplan], newConstraint);
this.mddNarrownessValues[agentToReplan] = this.mdds[agentToReplan].getLevelNarrownessValues();
double endTime = this.cbs.runner.ElapsedMilliseconds();
this.cbs.mddsAdapted++;
this.cbs.timeBuildingMdds += endTime - startTime;
}
else
{
this.mdds[agentToReplan] = null;
this.mddNarrownessValues[agentToReplan] = null;
}
this.countsOfInternalAgentsThatConflict = parent.countsOfInternalAgentsThatConflict.ToArray();
this.conflictCountsPerAgent = new Dictionary<int, int>[parent.conflictCountsPerAgent.Length];
for (int i = 0; i < this.conflictCountsPerAgent.Length; i++)
this.conflictCountsPerAgent[i] = new Dictionary<int, int>(parent.conflictCountsPerAgent[i]); // Need a separate copy because unlike plans, the conflict counts for agents that aren't replanned do change.
this.conflictTimesPerAgent = new Dictionary<int, List<int>>[parent.conflictTimesPerAgent.Length];
for (int i = 0; i < this.conflictTimesPerAgent.Length; i++)
{
this.conflictTimesPerAgent[i] = new Dictionary<int, List<int>>(); // Need a separate copy because unlike plans, the conflict counts for agents that aren't replanned do change.
foreach (var kvp in parent.conflictTimesPerAgent[i])
this.conflictTimesPerAgent[i][kvp.Key] = new List<int>(kvp.Value);
}
this.agentsGroupAssignment = parent.agentsGroupAssignment.ToArray();
for (int i = 0; i < this.singleAgentPlans.Length; i++)
{
newPlans[i] = false;
}
ISet<int> group = this.GetGroup(agentToReplan);
foreach (int i in group)
newPlans[i] = true;
this.agentNumToIndex = parent.agentNumToIndex;
this.prev = parent;
this.constraint = newConstraint;
this.depth = (ushort)(this.prev.depth + 1);
this.agentAExpansion = ExpansionState.NOT_EXPANDED;
this.agentBExpansion = ExpansionState.NOT_EXPANDED;
this.replanSize = 1;
this.solver = parent.solver;
this.singleAgentSolver = parent.singleAgentSolver;
this.minimumVertexCover = (int) ConflictGraph.MinVertexCover.NOT_SET;
//this.externalConstraints = parent.externalConstraints;
}
/// <summary>
/// Child from merge action constructor. FIXME: Code dup with previous constructor.
/// </summary>
/// <param name="parent"></param>
/// <param name="mergeGroupA"></param>
/// <param name="mergeGroupB"></param>
public CbsNode(CbsNode parent, int mergeGroupA, int mergeGroupB)
{
this.singleAgentPlans = parent.singleAgentPlans.ToArray();
newPlans = new bool[this.singleAgentPlans.Length];
this.singleAgentCosts = parent.singleAgentCosts.ToArray();
this.mdds = parent.mdds.ToArray();
this.mddNarrownessValues = parent.mddNarrownessValues.ToArray(); // No new constraint was added so all of the parent's MDDs are valid
this.countsOfInternalAgentsThatConflict = parent.countsOfInternalAgentsThatConflict.ToArray<int>();
this.conflictCountsPerAgent = new Dictionary<int, int>[parent.conflictCountsPerAgent.Length];
for (int i = 0; i < this.conflictCountsPerAgent.Length; i++)
this.conflictCountsPerAgent[i] = new Dictionary<int, int>(parent.conflictCountsPerAgent[i]); // Need a separate copy because unlike plans, the conflict counts for agents that aren't replanned do change.
this.conflictTimesPerAgent = new Dictionary<int, List<int>>[parent.conflictTimesPerAgent.Length];
for (int i = 0; i < this.conflictTimesPerAgent.Length; i++)
{
this.conflictTimesPerAgent[i] = new Dictionary<int, List<int>>(); // Need a separate copy because unlike plans, the conflict counts for agents that aren't replanned do change.
foreach (var kvp in parent.conflictTimesPerAgent[i])
this.conflictTimesPerAgent[i][kvp.Key] = new List<int>(kvp.Value);
}
this.agentsGroupAssignment = parent.agentsGroupAssignment.ToArray();
this.agentNumToIndex = parent.agentNumToIndex;
this.prev = parent;
this.constraint = null;
this.depth = (ushort)(this.prev.depth + 1);
this.agentAExpansion = ExpansionState.NOT_EXPANDED;
this.agentBExpansion = ExpansionState.NOT_EXPANDED;
this.replanSize = 1;
this.solver = parent.solver;
this.singleAgentSolver = parent.singleAgentSolver;
this.cbs = parent.cbs;
this.MergeGroups(mergeGroupA, mergeGroupB);
for (int i = 0; i < this.singleAgentPlans.Length; i++)
{
newPlans[i] = false;
}
ISet<int> mergedGroup = (mergeGroupA < mergeGroupB) ? this.GetGroup(mergeGroupA) : this.GetGroup(mergeGroupB);
foreach (int i in mergedGroup)
newPlans[i] = true;
this.minimumVertexCover = (int) ConflictGraph.MinVertexCover.NOT_SET;
//this.externalConstraints = parent.externalConstraints;
}
/// <summary>
/// Total cost + heuristic estimate
/// </summary>
public int f
{
get { return this.g + this.h; }
}
public int GetTargetH(int f) => f - g;
/// <summary>
/// Solves the entire node - finds a plan for every agent group.
/// This method is only called for the root of the constraint tree.
/// </summary>
/// <param name="depthToReplan"></param>
/// <returns>Whether solving was successful. Solving fails if a timeout occurs.</returns>
public bool Solve(int depthToReplan)
{
this.g = 0;
ProblemInstance problem = this.cbs.GetProblemInstance();
for (int i = 0; i < newPlans.Length; i++)
{
newPlans[i] = true;
}
var internalCAT = new ConflictAvoidanceTable();
ConflictAvoidanceTable CAT = internalCAT;
if (this.cbs.externalCAT != null)
{
CAT = new CAT_U();
((CAT_U)CAT).Join(this.cbs.externalCAT);
((CAT_U)CAT).Join(internalCAT);
}
HashSet<CbsConstraint> newConstraints = this.GetConstraints(); // Probably empty as this is probably the root of the CT.
ISet<CbsConstraint> constraints = newConstraints;
if (this.cbs.externalConstraints != null)
{
constraints = new HashSet_U<CbsConstraint>();
((HashSet_U<CbsConstraint>)constraints).Join(this.cbs.externalConstraints);
((HashSet_U<CbsConstraint>)constraints).Join(newConstraints);
}
ISet<CbsConstraint> positiveConstraints = null;
Dictionary<int,int> agentsWithPositiveConstraints = null;
HashSet<CbsConstraint> newPositiveConstraints = null;
if (this.cbs.doMalte)
newPositiveConstraints = this.GetPositiveConstraints();
if (this.cbs.externalPositiveConstraints != null && this.cbs.externalPositiveConstraints.Count != 0 &&
newPositiveConstraints != null && newPositiveConstraints.Count != 0)
{
positiveConstraints = new HashSet_U<CbsConstraint>();
((HashSet_U<CbsConstraint>)positiveConstraints).Join(this.cbs.externalPositiveConstraints);
((HashSet_U<CbsConstraint>)positiveConstraints).Join(newPositiveConstraints);
}
else if (this.cbs.externalPositiveConstraints != null && this.cbs.externalPositiveConstraints.Count != 0)
positiveConstraints = this.cbs.externalPositiveConstraints;
else if (newPositiveConstraints != null && newPositiveConstraints.Count != 0)
positiveConstraints = newPositiveConstraints;
if (positiveConstraints != null)
agentsWithPositiveConstraints = positiveConstraints.Select<CbsConstraint, int>(constraint => constraint.agentNum).Distinct().ToDictionary(x => x); // ToDictionary because there's no ToSet...
Dictionary<int, int> agentsWithConstraints = null;
if (constraints.Count != 0)
{
int maxConstraintTimeStep = constraints.Max(constraint => constraint.time);
depthToReplan = Math.Max(depthToReplan, maxConstraintTimeStep); // Give all constraints a chance to affect the plan
agentsWithConstraints = constraints.Select<CbsConstraint, int>(constraint => constraint.agentNum).Distinct().ToDictionary(x => x); // ToDictionary because there's no ToSet...
}
// This mechanism of adding the constraints to the possibly pre-existing constraints allows having
// layers of CBS/ID solvers, each one adding its own constraints and respecting those of the solvers above it.
// Find all the agents groups:
var subGroups = new List<AgentState>[problem.agents.Length];
for (int i = 0; i < agentsGroupAssignment.Length; i++)
{
if (subGroups[agentsGroupAssignment[i]] == null)
subGroups[agentsGroupAssignment[i]] = new List<AgentState>() { problem.agents[i] };
else
subGroups[this.agentsGroupAssignment[i]].Add(problem.agents[i]);
}
bool success = true;
for (int i = 0; i < subGroups.Length; i++)
{
if (subGroups[i] == null) // This isn't the first agent in its group - we've already solved its group.
continue;
List<AgentState> subGroup = subGroups[i];
bool agentGroupHasConstraints = (agentsWithConstraints != null) && subGroup.Any<AgentState>(state => agentsWithConstraints.ContainsKey(state.agent.agentNum));
bool agentGroupHasMustConstraints = (agentsWithPositiveConstraints != null) && subGroup.Any<AgentState>(state => agentsWithPositiveConstraints.ContainsKey(state.agent.agentNum));
// Solve for a single agent:
if (agentGroupHasConstraints == false &&
agentGroupHasMustConstraints == false &&
subGroup.Count == 1) // No constraints on this agent. Shortcut available (that doesn't consider the CAT, though!).
{
singleAgentPlans[i] = new SinglePlan(problem.agents[i]); // All moves up to starting pos, if any
singleAgentPlans[i].agentNum = problem.agents[this.agentsGroupAssignment[i]].agent.agentNum; // Use the group's representative
SinglePlan optimalPlan = problem.GetSingleAgentOptimalPlan(problem.agents[i]);
// Count conflicts:
this.conflictCountsPerAgent[i] = new Dictionary<int, int>();
this.conflictTimesPerAgent[i] = new Dictionary<int, List<int>>();
foreach (var move in optimalPlan.locationAtTimes)
{
var timedMove = (TimedMove)move; // GetSingleAgentOptimalPlan actually creates a plan with TimedMove instances
timedMove.IncrementConflictCounts(CAT, this.conflictCountsPerAgent[i], this.conflictTimesPerAgent[i]);
}
singleAgentPlans[i].ContinueWith(optimalPlan);
singleAgentCosts[i] = problem.agents[i].g + problem.GetSingleAgentOptimalCost(problem.agents[i]);
if (Constants.costFunction == Constants.CostFunction.SUM_OF_COSTS)
{
g += (ushort)singleAgentCosts[i];
}
else if (Constants.costFunction == Constants.CostFunction.MAKESPAN ||
Constants.costFunction == Constants.CostFunction.MAKESPAN_THEN_SUM_OF_COSTS)
{
g = Math.Max(g, (ushort)singleAgentCosts[i]);
}
else
throw new NotImplementedException($"Unsupported cost function {Constants.costFunction}");
this.UpdateAtGoalConflictCounts(i, CAT);
}
else
{
success = this.Replan(i, depthToReplan, subGroup, CAT, constraints, positiveConstraints);
if (!success) // Usually means a timeout occured.
break;
}
// Add the group's plan to the internal CAT. In the case we use ready-made plans from the heuristic, this is still needed to allow us to track conflicts.
foreach (AgentState agentState in subGroup)
{
internalCAT.AddPlan(singleAgentPlans[this.agentNumToIndex[agentState.agent.agentNum]]);
}
}
if (!success)
return false;
// Update conflict counts: All agents but the last saw an incomplete CAT. Update counts backwards.
for (int i = this.conflictCountsPerAgent.Length - 1; i >= 0; i--)
{
foreach (KeyValuePair<int, int> pair in this.conflictCountsPerAgent[i])
{
if (this.agentNumToIndex.ContainsKey(pair.Key) && // An internal conflict, rather than external
this.agentNumToIndex[pair.Key] < i) // Just an optimization. Would also be correct without this check.
{
this.conflictCountsPerAgent[this.agentNumToIndex[pair.Key]] // Yes, index here, num there
[problem.agents[i].agent.agentNum] = pair.Value; // Collisions are symmetrical, and agent "key" didn't see the route for agent "i" when planning.
this.conflictTimesPerAgent[this.agentNumToIndex[pair.Key]]
[problem.agents[i].agent.agentNum] = this.conflictTimesPerAgent[i][pair.Key];
}
}
}
this.CountConflicts();
this.CalcMinOpsToSolve();
this.isGoal = this.countsOfInternalAgentsThatConflict.All(i => i == 0);
return true;
}
/// <summary>
/// Replan for a given agent (when constraints for that agent have changed, or its group was enlarged).
/// </summary>
/// <param name="agentToReplan"></param>
/// <param name="minPathTimeStep"></param>
/// <param name="subGroup">If given, assume CAT, constraints and positiveConstraints are all populated too</param>
/// <param name="CAT"></param>
/// <param name="constraints"></param>
/// <param name="positiveConstraints"></param>
/// <param name="minPathCost"></param>
/// <param name="maxPathCost"></param>
/// <returns>Whether a path was successfully found</returns>
public bool Replan(int agentToReplan, int minPathTimeStep,
List<AgentState> subGroup = null,
ConflictAvoidanceTable CAT = null,
ISet<CbsConstraint> constraints = null, ISet<CbsConstraint> positiveConstraints = null,
int minPathCost = -1, int maxPathCost = int.MaxValue)
{
ConflictAvoidanceTable internalCAT = null; // To quiet the compiler
ProblemInstance problem = this.cbs.GetProblemInstance();
int groupNum = this.agentsGroupAssignment[agentToReplan];
bool underSolve = true;
if (subGroup == null)
{
underSolve = false;
// Construct the subgroup of agents that are of the same group as agentForReplan,
// and add the plans of all other agents to CAT
internalCAT = new ConflictAvoidanceTable();
subGroup = new List<AgentState>();
for (int i = 0; i < agentsGroupAssignment.Length; i++)
{
if (this.agentsGroupAssignment[i] == groupNum)
subGroup.Add(problem.agents[i]);
else
internalCAT.AddPlan(singleAgentPlans[i]);
}
if (this.cbs.externalCAT != null)
{
CAT = new CAT_U();
((CAT_U)CAT).Join(this.cbs.externalCAT);
((CAT_U)CAT).Join(internalCAT);
}
else
CAT = internalCAT;
HashSet<CbsConstraint> newConstraints = this.GetConstraints();
if (this.cbs.externalConstraints != null && this.cbs.externalConstraints.Count != 0)
{
constraints = new HashSet_U<CbsConstraint>();
((HashSet_U<CbsConstraint>)constraints).Join(this.cbs.externalConstraints);
((HashSet_U<CbsConstraint>)constraints).Join(newConstraints);
}
else
constraints = newConstraints;
HashSet<CbsConstraint> newPositiveConstraints = null;
if (this.cbs.doMalte)
newPositiveConstraints = this.GetPositiveConstraints();
if (this.cbs.externalPositiveConstraints != null && this.cbs.externalPositiveConstraints.Count != 0 &&
newPositiveConstraints != null && newPositiveConstraints.Count != 0)
{
positiveConstraints = new HashSet_U<CbsConstraint>();
((HashSet_U<CbsConstraint>)positiveConstraints).Join(this.cbs.externalPositiveConstraints);
((HashSet_U<CbsConstraint>)positiveConstraints).Join(newPositiveConstraints);
}
else if (this.cbs.externalPositiveConstraints != null && this.cbs.externalPositiveConstraints.Count != 0)
positiveConstraints = this.cbs.externalPositiveConstraints;
else if (newPositiveConstraints != null && newPositiveConstraints.Count != 0)
positiveConstraints = newPositiveConstraints;
}
this.replanSize = (ushort)subGroup.Count;
ICbsSolver relevantSolver = this.solver;
if (subGroup.Count == 1)
relevantSolver = this.singleAgentSolver;
ProblemInstance subProblem = problem.Subproblem(subGroup.ToArray());
Dictionary<int, int> subGroupAgentNums = subGroup.Select(state => state.agent.agentNum).ToDictionary(num => num); // No need to call Distinct(). Each agent appears at most once
IEnumerable<CbsConstraint> myConstraints = constraints.Where(constraint => subGroupAgentNums.ContainsKey(constraint.agentNum)); // TODO: Consider passing only myConstraints to the low level to speed things up.
if (myConstraints.Count() != 0)
{
int maxConstraintTimeStep = myConstraints.Max(constraint => constraint.time);
minPathTimeStep = Math.Max(minPathTimeStep, maxConstraintTimeStep); // Give all constraints a chance to affect the plan
}
if (positiveConstraints != null)
{
IEnumerable<CbsConstraint> myMustConstraints = positiveConstraints.Where(constraint => subGroupAgentNums.ContainsKey(constraint.agentNum));
if (myMustConstraints.Count() != 0)
{
int maxMustConstraintTimeStep = myMustConstraints.Max(constraint => constraint.time);
minPathTimeStep = Math.Max(minPathTimeStep, maxMustConstraintTimeStep); // Give all must constraints a chance to affect the plan
}
}
MDD mdd = null;
if (this.cbs.replanSameCostWithMdd)
mdd = this.mdds[agentToReplan];
double startTime = this.cbs.runner.ElapsedMilliseconds();
relevantSolver.Setup(subProblem, minPathTimeStep, this.cbs.runner, CAT, constraints, positiveConstraints,
minPathCost, maxPathCost, mdd);
bool solved = relevantSolver.Solve();
double endTime = this.cbs.runner.ElapsedMilliseconds();
this.cbs.timePlanningPaths += endTime - startTime;
relevantSolver.AccumulateStatistics();
relevantSolver.ClearStatistics();
if (solved == false) // Usually means a timeout occured.
{
return false;
}
// Copy the SinglePlans for the solved agent group from the solver to the appropriate places in this.allSingleAgentPlans
SinglePlan[] singlePlans = relevantSolver.GetSinglePlans();
int[] singleCosts = relevantSolver.GetSingleCosts();
Dictionary<int, int> perAgent = null; // To quiet the compiler
Dictionary<int, List<int>> conflictTimes = null;
if (CAT != null)
{
perAgent = relevantSolver.GetExternalConflictCounts();
conflictTimes = relevantSolver.GetConflictTimes();
}
else
{
perAgent = new Dictionary<int, int>();
conflictTimes = new Dictionary<int, List<int>>();
foreach (var singlePlan in singlePlans)
{
foreach (var move in singlePlan.locationAtTimes)
{
var timedMove = (TimedMove)move; // The solver actually creates a plan with TimedMove instances
if (CAT != null)
timedMove.IncrementConflictCounts(CAT, perAgent, conflictTimes);
else
timedMove.IncrementConflictCounts(internalCAT, perAgent, conflictTimes);
}
}
}
for (int i = 0; i < subGroup.Count; i++)
{
int agentNum = subGroup[i].agent.agentNum;
int agentIndex = this.agentNumToIndex[agentNum];
this.singleAgentPlans[agentIndex] = singlePlans[i];
this.singleAgentPlans[agentIndex].agentNum = problem.agents[groupNum].agent.agentNum; // Use the group's representative - that's how the plans will be inserted into the CAT later too.
this.singleAgentCosts[agentIndex] = singleCosts[i];
if (i == 0) // This is the group representative
{
this.conflictCountsPerAgent[agentIndex] = perAgent;
this.conflictTimesPerAgent[agentIndex] = conflictTimes;
}
else
{
if (underSolve == false)
{
this.conflictCountsPerAgent[agentIndex].Clear(); // Don't over-count. Leave it to the group's representative.
this.conflictTimesPerAgent[agentIndex].Clear();
}
else
{
this.conflictCountsPerAgent[agentIndex] = new Dictionary<int, int>();
this.conflictTimesPerAgent[agentIndex] = new Dictionary<int, List<int>>();
}
}
}
// Update conflict counts with what happens after the plan finishes
foreach (var agentNumAndAgentNum in subGroupAgentNums)
{
int i = this.agentNumToIndex[agentNumAndAgentNum.Key];
if (CAT != null)
this.UpdateAtGoalConflictCounts(i, CAT);
// Can't use the null coalescing operator because it requires the operands be of the same type :(
else
this.UpdateAtGoalConflictCounts(i, internalCAT);
}
if (underSolve == false)
{
// Update conflictCountsPerAgent and conflictTimes for all agents
int representativeAgentNum = subGroup[0].agent.agentNum;
for (int i = 0; i < this.conflictCountsPerAgent.Length; i++)
{
int agentNum = problem.agents[i].agent.agentNum;
if (perAgent.ContainsKey(agentNum))
{
this.conflictCountsPerAgent[i][representativeAgentNum] = perAgent[agentNum];
this.conflictTimesPerAgent[i][representativeAgentNum] = conflictTimes[agentNum];
}
else
{
this.conflictCountsPerAgent[i].Remove(representativeAgentNum); // This part could have been done before replanning
this.conflictTimesPerAgent[i].Remove(representativeAgentNum); // This part could have been done before replanning
}
}
this.CountConflicts();
this.CalcMinOpsToSolve();
}
// Calc g
if (Constants.costFunction == Constants.CostFunction.SUM_OF_COSTS)
{
this.g = (ushort)Math.Max(this.singleAgentCosts.Sum(), this.g); // Conserve g from partial
// expansion if it's higher
// (only happens when shuffling a partially expanded node)
}
else if (Constants.costFunction == Constants.CostFunction.MAKESPAN ||
Constants.costFunction == Constants.CostFunction.MAKESPAN_THEN_SUM_OF_COSTS)
{
this.g = (ushort)Math.Max(this.singleAgentCosts.Max(), this.g); // Conserve g from partial
// expansion if it's higher
// (only happens when shuffling a partially expanded node)
}
else
throw new NotImplementedException($"Unsupported cost function {Constants.costFunction}");
this.isGoal = this.countsOfInternalAgentsThatConflict.All(i => i == 0);
return true;
}
public void DebugPrint()
{
Debug.WriteLine("");
Debug.WriteLine("");
var hashCode = this.GetHashCode();
Debug.WriteLine($"Node hash: {hashCode}");
var parent = this.prev;
Debug.Write("Ancestor hashes (parent to root): ");
while (parent != null)
{
Debug.Write($"{parent.GetHashCode()} ");
parent = parent.prev;
}
Debug.WriteLine("");
Debug.WriteLine($"g: {this.g}");
Debug.WriteLine($"h: {this.h}");
Debug.WriteLine($"Min estimated ops needed: {this.minOpsToSolve}");
Debug.WriteLine($"Expansion state: {this.agentAExpansion}, {this.agentBExpansion}");
Debug.WriteLine($"Num of external agents that conflict: {totalExternalAgentsThatConflict}");
Debug.WriteLine($"Num of internal agents that conflict: {totalInternalAgentsThatConflict}");
Debug.WriteLine($"Num of conflicts between internal agents: {totalConflictsBetweenInternalAgents}");
Debug.WriteLine($"Node depth: {this.depth}");
IList<CbsConstraint> constraints = this.GetConstraintsOrdered();
Debug.WriteLine($"{constraints.Count} relevant internal constraints so far (this node's, then parent's and so on): ");
foreach (CbsConstraint constraint in constraints)
{
Debug.WriteLine(constraint);
}
ISet<CbsConstraint> mustConstraints = this.GetPositiveConstraints(); // TODO: Ordered
Debug.WriteLine($"{mustConstraints.Count} relevant internal must constraints so far: ");
foreach (CbsConstraint mustConstraint in mustConstraints)
{
Debug.WriteLine(mustConstraint);
}
ProblemInstance problem = this.cbs.GetProblemInstance();
if (this.cbs.externalConstraints != null)
{
Debug.WriteLine($"{this.cbs.externalConstraints.Count} external constraints: ");
foreach (CbsConstraint constraint in this.cbs.externalConstraints)
{
Debug.WriteLine(constraint);
}
}
Debug.WriteLine($"Conflict: {this.GetConflict()}");
Debug.Write("Agent group assignments: ");
for (int j = 0; j < this.agentsGroupAssignment.Length; j++)
{
Debug.Write($" {this.agentsGroupAssignment[j],3}");
}
Debug.WriteLine("");
Debug.Write("Single agent costs: "); // Extra spaces to align with the group assignments line
for (int j = 0; j < this.singleAgentCosts.Length; j++)
{
Debug.Write($" {this.singleAgentCosts[j],3}");
}
Debug.WriteLine("");
Debug.Write("Internal agents that conflict with each agent: ");
for (int j = 0; j < this.countsOfInternalAgentsThatConflict.Length; j++)
{
Debug.Write($" {this.countsOfInternalAgentsThatConflict[j]}");
}
Debug.WriteLine("");
Debug.Write("New plans: ");
for (int j = 0; j < this.newPlans.Length; j++)
{
Debug.Write($" {(this.newPlans[j] ? 1 : 0)}");
}
Debug.WriteLine("");
for (int j = 0; j < this.conflictCountsPerAgent.Length; j++)
{
if (this.conflictCountsPerAgent[j].Count != 0)
{
Debug.Write($"Agent {problem.agents[j].agent.agentNum} conflict counts: ");
foreach (var pair in this.conflictCountsPerAgent[j])
{
Debug.Write($"{pair.Key}:{pair.Value} ");
}
Debug.WriteLine("");
}
}
for (int j = 0; j < this.conflictTimesPerAgent.Length; j++)
{
if (this.conflictCountsPerAgent[j].Count != 0)
{
Debug.Write($"Agent {problem.agents[j].agent.agentNum} conflict times: ");
foreach (var pair in this.conflictTimesPerAgent[j])
{
Debug.Write($"{pair.Key}:[{String.Join(",", pair.Value)}], ");
}
Debug.WriteLine("");
}
}
if (this.cbs.GetType() == typeof(MACBS_WholeTreeThreshold) && this.cbs.mergeThreshold != -1)
{
for (int i = 0; i < ((MACBS_WholeTreeThreshold)this.cbs).globalConflictsCounter.Length; i++)
{
Debug.Write($"Agent {i} global historic conflict counts: ");
for (int j = 0; j < i; j++)
{
Debug.Write($"a{j}:{((MACBS_WholeTreeThreshold)this.cbs).globalConflictsCounter[i][j]} ");
}
Debug.WriteLine("");
}
}
var plan = this.CalculateJointPlan();
plan.PrintPlanIfShort();
Debug.WriteLine("");
Debug.WriteLine("");
}
/// <summary>
/// Update conflict counts according to what happens after the plan finishes -
/// needed if the plan is shorter than one of the previous plans and collides
/// with it while at the goal.
/// It's cheaper to do it this way than to force the solver the go more deeply.
/// The conflict counts are saved at the group's representative.
/// </summary>
protected void UpdateAtGoalConflictCounts(int agentIndex, ConflictAvoidanceTable CAT)
{
ProblemInstance problem = this.cbs.GetProblemInstance();
var afterGoal = new TimedMove(
problem.agents[agentIndex].agent.Goal.x, problem.agents[agentIndex].agent.Goal.y,
Move.Direction.Wait, time: 0);
for (int time = singleAgentPlans[agentIndex].GetSize(); time < CAT.GetMaxPlanSize(); time++)
{
afterGoal.time = time;
afterGoal.IncrementConflictCounts(CAT,
this.conflictCountsPerAgent[this.agentsGroupAssignment[agentIndex]],
this.conflictTimesPerAgent[this.agentsGroupAssignment[agentIndex]]);
}
}
/// <summary>
/// Calculates the minimum number of replans to solve, and from it the minimum number of replans or merges to solve.
///
/// A replan can resolve all of the agent's conflicts by luck, even if it was only targeting a single conflict.
///
/// To calculate the minimum number of replans to solve,
/// what we want is the size of the minimum vertex cover of the conflict graph.
/// Sadly, it's an NP-hard problem. Its decision variant is NP-complete.
/// Happily, it has a 2-approximation: Just choose both endpoints of each uncovered edge
/// repeatedly until no uncovered edges are left. So we can just take half the count from
/// that approximation.
///
/// TODO: the graph is small enough that we can try to solve optimally.
///
/// Notice a merge is like two replans in one, so we might need to take ceil(num_replans/2).
/// Luckily, in MA-CBS which considers only conflicts in the same CT branch,
/// a merge is only possible once every B+1 depth steps,
/// because we only count selected conflicts (they're guaranteed to be unequal),
/// so we can cap the number of possible merges and subtract less.
///
/// In Cbs_GlobalConflicts, we could use the global table to discount some merges.
/// </summary>
protected void CalcMinOpsToSolve()
{
if (this.cbs.disableTieBreakingByMinOpsEstimate == false)
{
var vertexCover = new HashSet<int>();
for (int i = 0; i < this.conflictCountsPerAgent.Length; i++)
{
if (vertexCover.Contains(i)) // This node is already in the cover - all its edges are already covered.
continue;
foreach (KeyValuePair<int, int> otherEndAgentNumAndCount in this.conflictCountsPerAgent[i])
{
if (this.agentNumToIndex.ContainsKey(otherEndAgentNumAndCount.Key)) // It's an internal conflict
{
int otherEndIndex = this.agentNumToIndex[otherEndAgentNumAndCount.Key];
if (vertexCover.Contains(otherEndAgentNumAndCount.Key) == false) // The vertex isn't covered from its other end yet
{
vertexCover.Add(i);
vertexCover.Add(otherEndIndex);
break; // All of this node's edges are now covered.
}
}
}
}
int minReplansToSolve = vertexCover.Count / 2; // We have a 2-approximation of the size of the cover -
// half that is at least half the value we're trying to approximate.
// (The size of the approximation is always even)
//if (this.cbs.debug)
// Debug.WriteLine("min replans lower estimate: " + minReplansToSolve);
if (this.cbs.mergeThreshold != -1) // Merges possible, account for them
// This assumes the current merging strategy is used.
{
if (this.cbs.GetType() == typeof(CBS))
{
if (this.cbs.mergeThreshold > 0)
{
int maxPotentialMergeSavings = (int)Math.Floor(((double)minReplansToSolve) / 2);
int depthToGoTo = this.depth + minReplansToSolve;
int chainSize = this.cbs.mergeThreshold + 1; // Every series of B+1 downwards consecutive nodes may end with a merge.
int maxMerges = depthToGoTo / chainSize; // Round down to discount the last unfinished chain.
// Count the minimum amount of merges already done and subtract it from maxMerges:
var groupSizes = new Dictionary<int, int>();
for (int i = 0; i < this.agentsGroupAssignment.Length; i++)
{
if (groupSizes.ContainsKey(this.agentsGroupAssignment[i]) == false)
groupSizes[this.agentsGroupAssignment[i]] = 0;
groupSizes[this.agentsGroupAssignment[i]]++;
}
// Not using this.GetGroupSizes() because what we want is actually
// a list of the sizes of the different groups, not the size of each agent's group
foreach (int groupSize in groupSizes.Values)
maxMerges -= (int)Math.Ceiling(Math.Log(groupSize, 2)); // A group of size 1 has had zero merges, a group of size 2 has had 1, larger groups have had at least ceil(log2) their size merges.
int maxMergeSavings = Math.Min(maxPotentialMergeSavings, maxMerges);
this.minOpsToSolve = minReplansToSolve - maxMergeSavings;
}
else
this.minOpsToSolve = (int)Math.Ceiling(((double)minReplansToSolve) / 2);
}
else
this.minOpsToSolve = (int)Math.Ceiling(((double)minReplansToSolve) / 2); // TODO: We could look at the global table and maybe deduce something, but I'm not interested in that right now.
}
else
this.minOpsToSolve = (int)minReplansToSolve;
}
}
/// <summary>
/// Populates the totalInternalAgentsThatConflict, totalConflictsBetweenInternalAgents,
/// totalConflictsWithExternalAgents, and countsOfInternalAgentsThatConflict counters
/// from the conflictCountsPerAgent values that are created while solving or replanning.
/// Those counters are used for tie-breaking.
/// </summary>
protected void CountConflicts()
{
var externalConflictingAgentNums = new HashSet<int>();
this.totalInternalAgentsThatConflict = 0;
this.totalConflictsBetweenInternalAgents = 0;
this.totalConflictsWithExternalAgents = 0;
for (int i = 0; i < this.conflictCountsPerAgent.Length; i++)
{
this.countsOfInternalAgentsThatConflict[i] = 0;
if (conflictCountsPerAgent[i].Count != 0)
totalInternalAgentsThatConflict++;
foreach (KeyValuePair<int, int> conflictingAgentNumAndCount in conflictCountsPerAgent[i])
{
if (this.agentNumToIndex.ContainsKey(conflictingAgentNumAndCount.Key)) // It's an internal conflict
{
this.countsOfInternalAgentsThatConflict[i]++; // Counts one conflict for each agent the i'th agent conflicts with
this.totalConflictsBetweenInternalAgents += conflictingAgentNumAndCount.Value;
}
else
{
externalConflictingAgentNums.Add(conflictingAgentNumAndCount.Key);
this.totalConflictsWithExternalAgents += conflictingAgentNumAndCount.Value;
this.conflictTimesPerAgent[i].Remove(conflictingAgentNumAndCount.Key); // Not needed
}
}
}
this.totalExternalAgentsThatConflict = externalConflictingAgentNums.Count;
this.totalConflictsBetweenInternalAgents /= 2; // Each conflict was counted twice
this.totalConflictsWithExternalAgents /= 2; // Each conflict was counted twice
}
/// <summary>
/// Used to preserve state of conflict iteration.
/// </summary>
private IEnumerator<CbsConflict> nextConflicts;
/// <summary>
/// The iterator holds the state of the generator, with all the different queues etc - a lot of memory.
/// We also clear the MDD narrowness values that were computed - if no child uses them, they'll be garbage-collected.
/// </summary>
public void ClearConflictChoiceData()
{
this.nextConflicts = null;
}
/// <summary>
/// Use after expanding a node and finding the conflict wasn't cardinal
/// </summary>
/// <returns>Whether we found a new potentially cardinal conflict to work on</returns>
public bool ChooseNextPotentiallyCardinalConflicts()
{
if (this.nextConflictCouldBeCardinal)
{
bool cycled = this.ChooseNextConflict();
if (cycled)
return true;
else
return false;
}
return false;
}
/// <summary>
///
/// </summary>
/// <returns>Whether another conflict was found</returns>
public bool ChooseNextConflict()
{
bool hadNext = this.nextConflicts.MoveNext();
if (hadNext)
this.conflict = this.nextConflicts.Current;
return hadNext;
}
/// <summary>
/// Chooses an internal conflict to work on.
/// Resets conflicts iteration if it's used.
/// </summary>
public void ChooseConflict()
{
if (this.singleAgentPlans.Length == 1) // A single internal agent can't conflict with anything internally
return;
if (this.isGoal) // Goal nodes don't have conflicts