-
Notifications
You must be signed in to change notification settings - Fork 16
/
Copy pathCBS.cs
1972 lines (1784 loc) · 101 KB
/
CBS.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.Collections.Generic;
using System.IO;
using System.Diagnostics;
using System.Linq;
using ExtensionMethods;
namespace mapf;
/// <summary>
/// Merges agents if they conflict more times than the given threshold in the CT nodes
/// from the root to the current CT nodes only.
/// </summary>
public class CBS : ICbsSolver, IHeuristicSolver<CbsNode>, IIndependenceDetectionSolver
{
/// <summary>
/// For each agent, map sets of constraints to MDDs
/// </summary>
public Dictionary<CbsCacheEntry, MDD>[] mddCache;
/// <summary>
/// For each agent, map sets of constraints to a dictionary that
/// maps each level (timestep) of its mdd to a narrowness degree.
/// Non-narrow levels are omitted.
/// </summary>
public Dictionary<CbsCacheEntry, Dictionary<int, MDD.LevelNarrowness>>[] mddNarrownessValuesCache;
protected ProblemInstance instance;
public OpenList<CbsNode> openList;
/// <summary>
/// Might as well be a HashSet. We don't need to retrieve from it.
/// TODO: Consider a closedList for single agent paths under an unordered set of constraints.
/// It would get more hits.
/// </summary>
public Dictionary<CbsNode, CbsNode> closedList;
protected ILazyHeuristic<CbsNode> heuristic;
protected int highLevelExpanded;
protected int highLevelGenerated;
protected int closedListHits;
protected int partialExpansions;
protected int bypasses;
protected int nodesExpandedWithGoalCost;
protected int bypassLookAheadNodesCreated;
protected int cardinalLookAheadNodesCreated;
protected int conflictsBypassed;
protected int cardinalConflictSplits;
protected int semiCardinalConflictSplits;
protected int nonCardinalConflictSplits;
public int mddsBuilt;
public int mddsAdapted;
protected int restarts;
protected int pathMaxBoosts;
protected int reversePathMaxBoosts;
protected int pathMaxPlusBoosts;
protected int surplusNodesAvoided;
public int mddCacheHits;
public double timePlanningPaths;
public double timeBuildingMdds;
// TODO: Count shuffles
protected int accHLExpanded;
protected int accHLGenerated;
protected int accClosedListHits;
protected int accPartialExpansions;
protected int accBypasses;
protected int accNodesExpandedWithGoalCost;
protected int accBypassLookAheadNodesCreated;
protected int accCardinalLookAheadNodesCreated;
protected int accConflictsBypassed;
protected int accCardinalConflictSplits;
protected int accSemiCardinalConflictSplits;
protected int accNonCardinalConflictSplits;
protected int accMddsBuilt;
protected int accMddsAdapted;
protected int accRestarts;
protected int accPathMaxBoosts;
protected int accReversePathMaxBoosts;
protected int accPathMaxPlusBoosts;
protected int accSurplusNodesAvoided;
protected int accMddCacheHits;
protected double accTimePlanningPaths;
protected double accTimeBuildingMdds;
public int solutionCost;
/// <summary>
/// The difference between the solution's cost and the f of the root node.
/// Notice root.g != 0 in CBS.
/// </summary>
protected int solutionDepth;
public Run runner;
protected CbsNode goalNode;
protected Plan solution;
protected Dictionary<int, int> externalConflictCounts;
protected Dictionary<int, List<int>> externalConflictTimes;
/// <summary>
/// Nodes with a higher F aren't generated. As a result, goal nodes with a higher cost
/// won't be found.
/// </summary>
protected int maxSolutionCost;
/// <summary>
/// Goal Nodes with with a lower cost aren't considered a goal. Used directly by CbsNode.
/// </summary>
public int minSolutionCost;
/// <summary>
/// Search is stopped when the minimum F in the open list reaches the target,
/// regardless of whether a goal node was found. Note maxSolutionCost stops the search when
/// the same F value is exhausted from the open list later.
/// </summary>
public int targetF {
get
{
return this.m_targetF;
}
set
{
this.maxSolutionCost = Math.Min(this.maxSolutionCost, value); // No need to generate nodes with a higher F
this.m_targetF = value;
}
}
protected int m_targetF;
/// <summary>
/// Search is stopped when the low level generated nodes count exceeds the cap
/// </summary>
public int lowLevelGeneratedCap { set; get; }
/// <summary>
/// Search is stopped when the millisecond count exceeds the cap
/// </summary>
public int milliCap { set; get; }
protected ICbsSolver solver;
protected ICbsSolver singleAgentSolver;
public int mergeThreshold;
public int minSolutionTimeStep;
protected int maxSizeGroup;
protected int accMaxSizeGroup;
public BypassStrategy bypassStrategy;
public bool doMalte;
public ConflictChoice conflictChoice;
public bool disableTieBreakingByMinOpsEstimate;
public int lookaheadMaxExpansions;
public enum ConflictChoice : byte
{
FIRST = 0,
MOST_CONFLICTING_SMALLEST_AGENTS,
CARDINAL_MDD,
CARDINAL_LOOKAHEAD,
CARDINAL_MDD_THEN_MERGE_EARLY_MOST_CONFLICTING_SMALLEST_GROUP,
CARDINAL_MDD_THEN_MERGE_EARLY_MOST_CONFLICTING_AND_SMALLEST_GROUP
}
public enum BypassStrategy : byte
{
NONE = 0,
FIRST_FIT_LOOKAHEAD,
BEST_FIT_LOOKAHEAD
}
protected bool mergeCausesRestart;
private bool useOldCost;
public bool replanSameCostWithMdd;
public bool cacheMdds;
public bool useCAT;
public ConflictAvoidanceTable externalCAT;
public ISet<CbsConstraint> externalConstraints;
/// <summary>
/// Note that in this implementation, positive constraints currenly don't act as negative constraints for all other agents, regretably.
/// They only rule out every other location for the agent at that time step.
/// </summary>
public ISet<CbsConstraint> externalPositiveConstraints;
/// <summary>
///
/// </summary>
/// <param name="singleAgentSolver"></param>
/// <param name="generalSolver"></param>
/// <param name="mergeThreshold"></param>
/// <param name="bypassStrategy"></param>
/// <param name="doMalte"></param>
/// <param name="conflictChoice"></param>
/// <param name="heuristic">Assumed to be expensive to compute. Used as late as possible</param>
/// <param name="disableTieBreakingByMinOpsEstimate"></param>
/// <param name="lookaheadMaxExpansions"></param>
/// <param name="mergeCausesRestart"></param>
/// <param name="replanSameCostWithMdd"></param>
/// <param name="cacheMdds"></param>
/// <param name="useOldCost"></param>
/// <param name="useCAT"></param>
public CBS(ICbsSolver singleAgentSolver, ICbsSolver generalSolver,
int mergeThreshold = -1,
BypassStrategy bypassStrategy = BypassStrategy.NONE,
bool doMalte = false,
ConflictChoice conflictChoice = ConflictChoice.FIRST,
ILazyHeuristic<CbsNode> heuristic = null,
bool disableTieBreakingByMinOpsEstimate = true,
int lookaheadMaxExpansions = 1,
bool mergeCausesRestart = false,
bool replanSameCostWithMdd = false,
bool cacheMdds = false,
bool useOldCost = false,
bool useCAT = true
)
{
this.closedList = new Dictionary<CbsNode, CbsNode>();
if (heuristic == null)
this.openList = new OpenList<CbsNode>(this);
else
this.openList = new DynamicLazyOpenList<CbsNode>(this, heuristic);
this.mergeThreshold = mergeThreshold;
this.solver = generalSolver;
this.singleAgentSolver = singleAgentSolver;
this.bypassStrategy = bypassStrategy;
this.doMalte = doMalte;
this.conflictChoice = conflictChoice;
this.heuristic = heuristic;
if (Constants.costFunction != Constants.CostFunction.SUM_OF_COSTS)
{
Trace.Assert(conflictChoice != ConflictChoice.CARDINAL_MDD &&
conflictChoice != ConflictChoice.CARDINAL_LOOKAHEAD &&
conflictChoice != ConflictChoice.CARDINAL_MDD_THEN_MERGE_EARLY_MOST_CONFLICTING_SMALLEST_GROUP &&
conflictChoice != ConflictChoice.CARDINAL_MDD_THEN_MERGE_EARLY_MOST_CONFLICTING_AND_SMALLEST_GROUP, // TODO: Might be OK. Need to look at it.
"Under makespan, increasing the cost for a single agent might not increase the cost for the solution." +
"Before this strategy is enabled we need to add a consideration of whether the agent whose cost will " +
"increase has the highest cost in the solution first");
}
this.disableTieBreakingByMinOpsEstimate = disableTieBreakingByMinOpsEstimate;
this.lookaheadMaxExpansions = lookaheadMaxExpansions;
this.mergeCausesRestart = mergeCausesRestart;
this.replanSameCostWithMdd = replanSameCostWithMdd;
this.cacheMdds = cacheMdds;
this.useOldCost = useOldCost;
this.useCAT = useCAT;
}
/// <summary>
/// Implements IIndependenceDetection.Setup for new groups
/// </summary>
/// <param name="problemInstance"></param>
/// <param name="runner"></param>
/// <param name="CAT"></param>
/// <param name="parentGroup1Cost"></param>
/// <param name="parentGroup2Cost"></param>
/// <param name="parentGroup1Size"></param>
public void Setup(ProblemInstance problemInstance, Run runner, ConflictAvoidanceTable CAT,
int parentGroup1Cost, int parentGroup2Cost, int parentGroup1Size)
{
this.Setup(problemInstance, -1, runner, CAT, null, null, parentGroup1Cost + parentGroup2Cost); // TODO: Support a makespan cost function
// I think we don't want to merge the agents in each group. We'd be left with two large meta-agents,
// and in CBS one conflict isn't a reason to merge agents. The groups are arbitrarily large so we can't
// even increment their conflict counts toward the merge threshold.
}
/// <summary>
/// Implements IIndependenceDetection.Setup for replanning groups to resolve a conflict
/// </summary>
/// <param name="problemInstance"></param>
/// <param name="runner"></param>
/// <param name="CAT"></param>
/// <param name="targetCost">/// </param>
/// <param name="illegalMoves"></param>
public void Setup(ProblemInstance problemInstance, Run runner, ConflictAvoidanceTable CAT,
int targetCost, ISet<TimedMove> illegalMoves)
{
// Turn the set of reserved/illegal moves into constraints for every agent. Not the prettiest solution.
// TODO: Instead, maybe add the agents in the reservation table into the problem instance, and add positive
// constraints for them along their entire path. Would require changing IIndependenceDetectionSolver.Setup
// to specify the agents the reserved moves belong to.
var constraints = new HashSet<CbsConstraint>(illegalMoves.Count * problemInstance.agents.Length);
foreach (var illegalMove in illegalMoves)
{
foreach (var agentState in problemInstance.agents)
{
constraints.Add(new CbsConstraint(agentState.agent.agentNum, illegalMove));
}
}
this.Setup(problemInstance, illegalMoves.Max(move => move.time), runner, CAT, constraints, null, targetCost, targetCost);
}
/// <summary>
/// Implements ICbsSolver.Setup.
/// </summary>
/// <param name="problemInstance"></param>
/// <param name="minSolutionTimeStep"></param>
/// <param name="runner"></param>
/// <param name="minSolutionCost"></param>
/// <param name="maxSolutionCost"></param>
/// <param name="mdd">Currently ignored. FIXME: Need to convert to array of MDDs to use.</param>
public virtual void Setup(ProblemInstance problemInstance, int minSolutionTimeStep, Run runner,
ConflictAvoidanceTable externalCAT, ISet<CbsConstraint> externalConstraints,
ISet<CbsConstraint> externalPositiveConstraints,
int minSolutionCost = -1, int maxSolutionCost = int.MaxValue, MDD mdd = null)
{
this.instance = problemInstance;
this.runner = runner;
if (this.openList is DynamicLazyOpenList<CbsNode>)
((DynamicLazyOpenList<CbsNode>)this.openList).runner = runner;
this.ClearPrivateStatistics();
this.solutionCost = 0;
this.solutionDepth = -1;
this.lowLevelGeneratedCap = int.MaxValue;
this.targetF = int.MaxValue;
this.milliCap = int.MaxValue;
this.goalNode = null;
this.solution = null;
// CBS parameters
this.minSolutionTimeStep = minSolutionTimeStep;
this.minSolutionCost = minSolutionCost;
this.maxSolutionCost = Math.Max(this.maxSolutionCost, maxSolutionCost);
if (this.replanSameCostWithMdd)
Trace.Assert(this.mergeThreshold == -1, "Using MDDs to replan same-cost paths is currently only supported for single agents");
if (this.cacheMdds)
{
this.mddCache = new Dictionary<CbsCacheEntry, MDD>[instance.agents.Length];
this.mddNarrownessValuesCache = new Dictionary<CbsCacheEntry, Dictionary<int, MDD.LevelNarrowness>>[instance.agents.Length];
for (int i = 0; i < instance.agents.Length; i++)
{
this.mddCache[i] = new Dictionary<CbsCacheEntry, MDD>();
this.mddNarrownessValuesCache[i] = new Dictionary<CbsCacheEntry, Dictionary<int, MDD.LevelNarrowness>>();
}
}
this.externalCAT = externalCAT;
CAT_U CAT = null;
if (this.useCAT)
{
CAT = new CAT_U();
if (externalCAT != null)
CAT.Join(externalCAT);
}
this.externalConstraints = externalConstraints;
this.externalPositiveConstraints = externalPositiveConstraints;
if (externalPositiveConstraints == null && this.doMalte)
externalPositiveConstraints = new HashSet<CbsConstraint>();
this.SetGlobals();
CbsNode root = new CbsNode(instance.agents.Length, this.solver, this.singleAgentSolver, this); // Problem instance and various strategy data is all passed under 'this'.
// Solve the root node
bool solved = root.Solve(minSolutionTimeStep);
if (solved)
{
if (root.f <= this.maxSolutionCost)
{
this.addToGlobalConflictCount(root); // TODO: Make MACBS_WholeTreeThreshold use nodes that do this automatically after choosing a conflict
this.openList.Add(root);
this.highLevelGenerated++;
this.closedList.Add(root, root);
}
else
{
this.surplusNodesAvoided++;
}
}
}
/// <summary>
/// Implements ISolver.Setup
/// </summary>
/// <param name="problemInstance"></param>
/// <param name="runner"></param>
public virtual void Setup(ProblemInstance problemInstance, Run runner)
{
this.Setup(problemInstance, 0, runner, null, null, null);
}
public IHeuristicCalculator<CbsNode> GetHeuristic()
{
return this.heuristic;
}
public ICbsSolver GetSolver()
{
return this.solver;
}
public Dictionary<int, int> GetExternalConflictCounts()
{
throw new NotImplementedException(); // For now. Also need to take care of generalised goal nodes!
}
public Dictionary<int, List<int>> GetConflictTimes()
{
throw new NotImplementedException(); // For now. Also need to take care of generalised goal nodes!
}
public ProblemInstance GetProblemInstance()
{
return this.instance;
}
public void Clear()
{
this.openList.Clear();
this.closedList.Clear();
this.solver.Clear();
// Statistics are reset on Setup.
}
public virtual string GetName()
{
string lowLevelSolvers;
if (mergeThreshold == -1 || Object.ReferenceEquals(this.singleAgentSolver, this.solver))
lowLevelSolvers = $"({this.singleAgentSolver})";
else
lowLevelSolvers = $"(single:{singleAgentSolver} multi:{solver})";
string variants = "";
if (this.bypassStrategy == BypassStrategy.FIRST_FIT_LOOKAHEAD)
{
if (this.lookaheadMaxExpansions != int.MaxValue)
{
if (this.lookaheadMaxExpansions != 1)
variants += $" with first fit adoption max expansions: {this.lookaheadMaxExpansions}";
else
variants += " + BP";
}
else
variants += " with first fit adoption max expansions: $\\infty$"; // LaTeX infinity symbol
}
if (this.bypassStrategy == BypassStrategy.BEST_FIT_LOOKAHEAD)
{
if (this.lookaheadMaxExpansions == int.MaxValue)
variants += " with infinite lookahead best fit adoption";
else
variants += $" with {this.lookaheadMaxExpansions} lookahead best fit adoption";
}
if (this.doMalte)
variants += " with Malte";
if (this.conflictChoice == ConflictChoice.FIRST)
variants += " choosing the first conflict in CBS nodes";
else if (this.conflictChoice == ConflictChoice.CARDINAL_MDD)
variants += " + PC";
else if (this.conflictChoice == ConflictChoice.CARDINAL_LOOKAHEAD)
variants += " + PC choosing cardinal conflicts using lookahead";
else if (this.conflictChoice == ConflictChoice.CARDINAL_MDD_THEN_MERGE_EARLY_MOST_CONFLICTING_SMALLEST_GROUP)
variants += " + PC MERGE EARLY MOST CONFLICTING SMALLEST GROUP";
else if (this.conflictChoice == ConflictChoice.CARDINAL_MDD_THEN_MERGE_EARLY_MOST_CONFLICTING_AND_SMALLEST_GROUP)
variants += " + PC MERGE EARLY MOST CONFLICTING & SMALLEST GROUP";
if (this.disableTieBreakingByMinOpsEstimate == true)
variants += " without smart tie breaking";
if (this.mergeCausesRestart == true && mergeThreshold != -1)
variants += " with merge&restart";
if (this.replanSameCostWithMdd)
variants += " with replanning same cost paths with MDDs";
if (this.cacheMdds)
variants += " with caching MDDs";
if (this.useOldCost)
variants += " with using old path costs";
if (this.useCAT == false)
variants += " without a CAT";
if (this.openList.GetType() != typeof(OpenList<CbsNode>))
{
variants += $" using {this.openList.GetName()}";
}
if (mergeThreshold == -1)
return $"CBS/{lowLevelSolvers}{variants}";
return $"MA-CBS-Local-{mergeThreshold}/{lowLevelSolvers}{variants}";
}
public override string ToString()
{
return GetName();
}
public int GetSolutionCost() { return this.solutionCost; }
protected void ClearPrivateStatistics()
{
this.highLevelExpanded = 0;
this.highLevelGenerated = 0;
this.closedListHits = 0;
this.partialExpansions = 0;
this.bypasses = 0;
this.nodesExpandedWithGoalCost = 0;
this.bypassLookAheadNodesCreated = 0;
this.cardinalLookAheadNodesCreated = 0;
this.conflictsBypassed = 0;
this.cardinalConflictSplits = 0;
this.semiCardinalConflictSplits = 0;
this.nonCardinalConflictSplits = 0;
this.mddsBuilt = 0;
this.mddsAdapted = 0;
this.restarts = 0;
this.pathMaxBoosts = 0;
this.reversePathMaxBoosts = 0;
this.pathMaxPlusBoosts = 0;
this.maxSizeGroup = 1;
this.surplusNodesAvoided = 0;
this.mddCacheHits = 0;
this.timePlanningPaths = 0;
this.timeBuildingMdds = 0;
}
public virtual void OutputStatisticsHeader(TextWriter output)
{
output.Write(this.ToString() + " Expanded (HL)");
output.Write(Run.RESULTS_DELIMITER);
output.Write(this.ToString() + " Generated (HL)");
output.Write(Run.RESULTS_DELIMITER);
output.Write(this.ToString() + " Closed List Hits (HL)");
output.Write(Run.RESULTS_DELIMITER);
output.Write(this.ToString() + " Partial Expansions (HL)");
output.Write(Run.RESULTS_DELIMITER);
output.Write(this.ToString() + " Adoptions (HL)");
output.Write(Run.RESULTS_DELIMITER);
output.Write(this.ToString() + " Nodes Expanded With Goal Cost (HL)");
output.Write(Run.RESULTS_DELIMITER);
output.Write(this.ToString() + " Bypass Look Ahead Nodes Created (HL)");
output.Write(Run.RESULTS_DELIMITER);
output.Write(this.ToString() + " Cardinal Look Ahead Nodes Created (HL)");
output.Write(Run.RESULTS_DELIMITER);
output.Write(this.ToString() + " Conflicts Bypassed With Adoption (HL)");
output.Write(Run.RESULTS_DELIMITER);
output.Write(this.ToString() + " Cardinal Conflict Splits (HL)");
output.Write(Run.RESULTS_DELIMITER);
output.Write(this.ToString() + " Semi-Cardinal Conflict Splits (HL)");
output.Write(Run.RESULTS_DELIMITER);
output.Write(this.ToString() + " Non-Cardinal Conflict Splits (HL)");
output.Write(Run.RESULTS_DELIMITER);
output.Write(this.ToString() + " MDDs Built (HL)");
output.Write(Run.RESULTS_DELIMITER);
output.Write(this.ToString() + " MDDs Adapted (HL)");
output.Write(Run.RESULTS_DELIMITER);
output.Write(this.ToString() + " Restarts (HL)");
output.Write(Run.RESULTS_DELIMITER);
output.Write(this.ToString() + " Path-Max Boosts (HL)");
output.Write(Run.RESULTS_DELIMITER);
output.Write(this.ToString() + " Reverse Path-Max Boosts (HL)");
output.Write(Run.RESULTS_DELIMITER);
output.Write(this.ToString() + " Path-Max Plus Boosts (HL)");
output.Write(Run.RESULTS_DELIMITER);
output.Write(this.ToString() + " Max Group Size (HL)");
output.Write(Run.RESULTS_DELIMITER);
output.Write(this.ToString() + " Surplus Nodes Avoided (HL)");
output.Write(Run.RESULTS_DELIMITER);
output.Write(this.ToString() + " MDD Cache Hits (HL)");
output.Write(Run.RESULTS_DELIMITER);
output.Write(this.ToString() + " Time Planning Paths (HL)");
output.Write(Run.RESULTS_DELIMITER);
output.Write(this.ToString() + " Time Building MDDs (HL)");
output.Write(Run.RESULTS_DELIMITER);
this.solver.OutputStatisticsHeader(output);
if (Object.ReferenceEquals(this.singleAgentSolver, this.solver) == false)
this.singleAgentSolver.OutputStatisticsHeader(output);
this.openList.OutputStatisticsHeader(output);
}
public virtual void OutputStatistics(TextWriter output)
{
Console.WriteLine("Total Expanded Nodes (High-Level): {0}", this.GetHighLevelExpanded());
Console.WriteLine("Total Generated Nodes (High-Level): {0}", this.GetHighLevelGenerated());
Console.WriteLine("Closed List Hits (High-Level): {0}", this.closedListHits);
Console.WriteLine("Partial Expansions (High-Level): {0}", this.partialExpansions);
Console.WriteLine("Adoptions (High-Level): {0}", this.bypasses);
Console.WriteLine("Nodes expanded with goal cost (High-Level): {0}", this.nodesExpandedWithGoalCost);
Console.WriteLine("Bypass lookahead nodes created (High-Level): {0}", this.bypassLookAheadNodesCreated);
Console.WriteLine("Cardinal lookahead nodes created (High-Level): {0}", this.cardinalLookAheadNodesCreated);
Console.WriteLine("Conflicts Bypassed With Adoption (High-Level): {0}", this.conflictsBypassed);
Console.WriteLine("Cardinal Conflicts Splits (High-Level): {0}", this.cardinalConflictSplits);
Console.WriteLine("Semi-Cardinal Conflicts Splits (High-Level): {0}", this.semiCardinalConflictSplits);
Console.WriteLine("Non-Cardinal Conflicts Splits (High-Level): {0}", this.nonCardinalConflictSplits);
Console.WriteLine("MDDs Built (High-Level): {0}", this.mddsBuilt);
Console.WriteLine("MDDs adapted (High-Level): {0}", this.mddsAdapted);
Console.WriteLine("Restarts (High-Level): {0}", this.restarts);
Console.WriteLine("Path-Max Boosts (High-Level): {0}", this.pathMaxBoosts);
Console.WriteLine("Reverse Path-Max Boosts (High-Level): {0}", this.reversePathMaxBoosts);
Console.WriteLine("Path-Max Plus Boosts (High-Level): {0}", this.pathMaxPlusBoosts);
Console.WriteLine("Max Group Size (High-Level): {0}", this.maxSizeGroup);
Console.WriteLine("Surplus Nodes Avoided (High-Level): {0}", this.surplusNodesAvoided);
Console.WriteLine("MDD cache hits (High-Level): {0}", this.mddCacheHits);
Console.WriteLine("Time planning paths (High-Level): {0}", this.timePlanningPaths);
Console.WriteLine("Time building mdds (High-Level): {0}", this.timeBuildingMdds);
output.Write(this.highLevelExpanded + Run.RESULTS_DELIMITER);
output.Write(this.highLevelGenerated + Run.RESULTS_DELIMITER);
output.Write(this.closedListHits + Run.RESULTS_DELIMITER);
output.Write(this.partialExpansions + Run.RESULTS_DELIMITER);
output.Write(this.bypasses + Run.RESULTS_DELIMITER);
output.Write(this.nodesExpandedWithGoalCost + Run.RESULTS_DELIMITER);
output.Write(this.bypassLookAheadNodesCreated + Run.RESULTS_DELIMITER);
output.Write(this.cardinalLookAheadNodesCreated + Run.RESULTS_DELIMITER);
output.Write(this.conflictsBypassed + Run.RESULTS_DELIMITER);
output.Write(this.cardinalConflictSplits + Run.RESULTS_DELIMITER);
output.Write(this.semiCardinalConflictSplits + Run.RESULTS_DELIMITER);
output.Write(this.nonCardinalConflictSplits + Run.RESULTS_DELIMITER);
output.Write(this.mddsBuilt + Run.RESULTS_DELIMITER);
output.Write(this.mddsAdapted + Run.RESULTS_DELIMITER);
output.Write(this.restarts + Run.RESULTS_DELIMITER);
output.Write(this.pathMaxBoosts + Run.RESULTS_DELIMITER);
output.Write(this.reversePathMaxBoosts + Run.RESULTS_DELIMITER);
output.Write(this.pathMaxPlusBoosts + Run.RESULTS_DELIMITER);
output.Write(this.maxSizeGroup + Run.RESULTS_DELIMITER);
output.Write(this.surplusNodesAvoided + Run.RESULTS_DELIMITER);
output.Write(this.mddCacheHits + Run.RESULTS_DELIMITER);
output.Write(this.timePlanningPaths + Run.RESULTS_DELIMITER);
output.Write(this.timeBuildingMdds + Run.RESULTS_DELIMITER);
this.solver.OutputAccumulatedStatistics(output);
if (Object.ReferenceEquals(this.singleAgentSolver, this.solver) == false)
this.singleAgentSolver.OutputAccumulatedStatistics(output);
this.openList.OutputStatistics(output);
}
public virtual int NumStatsColumns
{
get
{
int numSolverStats = this.solver.NumStatsColumns;
if (Object.ReferenceEquals(this.singleAgentSolver, this.solver) == false)
numSolverStats += this.singleAgentSolver.NumStatsColumns;
return 23 + numSolverStats + this.openList.NumStatsColumns;
}
}
public virtual void ClearStatistics()
{
this.solver.ClearAccumulatedStatistics(); // Is this correct? Or is it better not to do it?
if (Object.ReferenceEquals(this.singleAgentSolver, this.solver) == false)
this.singleAgentSolver.ClearAccumulatedStatistics();
this.ClearPrivateStatistics();
this.openList.ClearStatistics();
}
public virtual void ClearAccumulatedStatistics()
{
this.accHLExpanded = 0;
this.accHLGenerated = 0;
this.accClosedListHits = 0;
this.accPartialExpansions = 0;
this.accBypasses = 0;
this.accNodesExpandedWithGoalCost = 0;
this.accBypassLookAheadNodesCreated = 0;
this.accCardinalLookAheadNodesCreated = 0;
this.accConflictsBypassed = 0;
this.accCardinalConflictSplits = 0;
this.accSemiCardinalConflictSplits = 0;
this.accNonCardinalConflictSplits = 0;
this.accMddsBuilt = 0;
this.accMddsAdapted = 0;
this.accRestarts = 0;
this.accPathMaxBoosts = 0;
this.accReversePathMaxBoosts = 0;
this.accPathMaxPlusBoosts = 0;
this.accMaxSizeGroup = 1;
this.accSurplusNodesAvoided = 0;
this.accMddCacheHits = 0;
this.accTimePlanningPaths = 0;
this.accTimeBuildingMdds = 0;
this.solver.ClearAccumulatedStatistics();
if (Object.ReferenceEquals(this.singleAgentSolver, this.solver) == false)
this.singleAgentSolver.ClearAccumulatedStatistics();
this.openList.ClearAccumulatedStatistics();
}
public virtual void AccumulateStatistics()
{
this.accHLExpanded += this.highLevelExpanded;
this.accHLGenerated += this.highLevelGenerated;
this.accClosedListHits += this.closedListHits;
this.accPartialExpansions += this.partialExpansions;
this.accBypasses += this.bypasses;
this.accNodesExpandedWithGoalCost += this.nodesExpandedWithGoalCost;
this.accBypassLookAheadNodesCreated += this.bypassLookAheadNodesCreated;
this.accCardinalLookAheadNodesCreated += this.cardinalLookAheadNodesCreated;
this.accConflictsBypassed += this.conflictsBypassed;
this.accCardinalConflictSplits += this.cardinalConflictSplits;
this.accSemiCardinalConflictSplits += this.semiCardinalConflictSplits;
this.accNonCardinalConflictSplits += this.nonCardinalConflictSplits;
this.accMddsBuilt += this.mddsBuilt;
this.accMddsAdapted += this.mddsAdapted;
this.accRestarts += this.restarts;
this.accPathMaxBoosts += this.pathMaxBoosts;
this.accReversePathMaxBoosts += this.reversePathMaxBoosts;
this.accPathMaxPlusBoosts += this.pathMaxPlusBoosts;
this.accMaxSizeGroup = Math.Max(this.accMaxSizeGroup, this.maxSizeGroup);
this.accSurplusNodesAvoided += this.surplusNodesAvoided;
this.accMddCacheHits += this.mddCacheHits;
this.accTimePlanningPaths += this.timePlanningPaths;
this.accTimeBuildingMdds += this.timeBuildingMdds;
// this.solver statistics are accumulated every time it's used.
this.openList.AccumulateStatistics();
}
public virtual void OutputAccumulatedStatistics(TextWriter output)
{
Console.WriteLine("{0} Accumulated Expanded Nodes (High-Level): {1}", this, this.accHLExpanded);
Console.WriteLine("{0} Accumulated Generated Nodes (High-Level): {1}", this, this.accHLGenerated);
Console.WriteLine("{0} Accumulated Closed List Hits (High-Level): {1}", this, this.accClosedListHits);
Console.WriteLine("{0} Accumulated Partial Expansions (High-Level): {1}", this, this.accPartialExpansions);
Console.WriteLine("{0} Accumulated Adoptions (High-Level): {1}", this, this.accBypasses);
Console.WriteLine("{0} Accumulated Nodes Expanded With Goal Cost (High-Level): {1}", this, this.accNodesExpandedWithGoalCost);
Console.WriteLine("{0} Accumulated Look Ahead Nodes Created (High-Level): {1}", this, this.accNodesExpandedWithGoalCost);
Console.WriteLine("{0} Accumulated Conflicts Bypassed With Adoption (High-Level): {1}", this, this.accConflictsBypassed);
Console.WriteLine("{0} Accumulated Cardinal Conflicts Splits (High-Level): {1}", this, this.accCardinalConflictSplits);
Console.WriteLine("{0} Accumulated Semi-Cardinal Conflicts Splits (High-Level): {1}", this, this.accSemiCardinalConflictSplits);
Console.WriteLine("{0} Accumulated Non-Cardinal Conflicts Splits (High-Level): {1}", this, this.accNonCardinalConflictSplits);
Console.WriteLine("{0} Accumulated MDDs Built (High-Level): {1}", this, this.accMddsBuilt);
Console.WriteLine("{0} Accumulated MDDs adapted (High-Level): {1}", this, this.accMddsAdapted);
Console.WriteLine("{0} Accumulated Restarts (High-Level): {1}", this, this.accRestarts);
Console.WriteLine("{0} Accumulated Path-Max Boosts (High-Level): {1}", this, this.accPathMaxBoosts);
Console.WriteLine("{0} Accumulated Reverse Path-Max Boosts (High-Level): {1}", this, this.accReversePathMaxBoosts);
Console.WriteLine("{0} Accumulated Path-Max Plus Boosts (High-Level): {1}", this, this.accPathMaxPlusBoosts);
Console.WriteLine("{0} Max Group Size (High-Level): {1}", this, this.accMaxSizeGroup);
Console.WriteLine("{0} Accumulated Surplus Nodes Avoided (High-Level): {1}", this, this.accSurplusNodesAvoided);
Console.WriteLine("{0} Accumulated MDD cache hits (High-Level): {1}", this, this.accMddCacheHits);
Console.WriteLine("{0} Accumulated time planning paths (High-Level): {1}", this, this.accTimePlanningPaths);
Console.WriteLine("{0} Accumulated time building MDDs (High-Level): {1}", this, this.accTimeBuildingMdds);
output.Write(this.accHLExpanded + Run.RESULTS_DELIMITER);
output.Write(this.accHLGenerated + Run.RESULTS_DELIMITER);
output.Write(this.accClosedListHits + Run.RESULTS_DELIMITER);
output.Write(this.accPartialExpansions + Run.RESULTS_DELIMITER);
output.Write(this.accBypasses + Run.RESULTS_DELIMITER);
output.Write(this.accNodesExpandedWithGoalCost + Run.RESULTS_DELIMITER);
output.Write(this.accBypassLookAheadNodesCreated + Run.RESULTS_DELIMITER);
output.Write(this.accCardinalLookAheadNodesCreated + Run.RESULTS_DELIMITER);
output.Write(this.accConflictsBypassed + Run.RESULTS_DELIMITER);
output.Write(this.accCardinalConflictSplits + Run.RESULTS_DELIMITER);
output.Write(this.accSemiCardinalConflictSplits + Run.RESULTS_DELIMITER);
output.Write(this.accNonCardinalConflictSplits + Run.RESULTS_DELIMITER);
output.Write(this.accMddsBuilt + Run.RESULTS_DELIMITER);
output.Write(this.accMddsAdapted + Run.RESULTS_DELIMITER);
output.Write(this.accRestarts + Run.RESULTS_DELIMITER);
output.Write(this.accPathMaxBoosts + Run.RESULTS_DELIMITER);
output.Write(this.accReversePathMaxBoosts + Run.RESULTS_DELIMITER);
output.Write(this.accPathMaxPlusBoosts + Run.RESULTS_DELIMITER);
output.Write(this.accMaxSizeGroup + Run.RESULTS_DELIMITER);
output.Write(this.accSurplusNodesAvoided + Run.RESULTS_DELIMITER);
output.Write(this.accMddCacheHits + Run.RESULTS_DELIMITER);
output.Write(this.accTimePlanningPaths + Run.RESULTS_DELIMITER);
output.Write(this.accTimeBuildingMdds + Run.RESULTS_DELIMITER);
this.solver.OutputAccumulatedStatistics(output);
if (Object.ReferenceEquals(this.singleAgentSolver, this.solver) == false)
this.singleAgentSolver.OutputAccumulatedStatistics(output);
this.openList.OutputAccumulatedStatistics(output);
}
public bool debug = false;
private bool equivalenceWasOn;
/// <summary>
///
/// </summary>
/// <returns></returns>
protected void SetGlobals()
{
this.equivalenceWasOn = AgentState.EquivalenceOverDifferentTimes;
AgentState.EquivalenceOverDifferentTimes = false;
}
protected void CleanGlobals()
{
AgentState.EquivalenceOverDifferentTimes = this.equivalenceWasOn;
}
public bool Solve()
{
//this.SetGlobals(); // Again, because we might be resuming a search that was stopped.
int initialEstimate = 0;
if (openList.Count > 0)
initialEstimate = openList.Peek().f;
int maxExpandedNodeF = -1;
int currentCost = -1;
while (openList.Count > 0)
{
// Check if max time has been exceeded
if (this.runner.ElapsedMilliseconds() > Constants.MAX_TIME)
{
this.solutionCost = (int) Constants.SpecialCosts.TIMEOUT_COST;
Console.WriteLine("Out of time");
this.solutionDepth = maxExpandedNodeF - initialEstimate; // A minimum estimate.
// Can't use top of OPEN's f-value instead of openList.Peek().f because we may have
// timed out while expanding and before generating nodes that would have led to the
// optimal solution, and the remaining nodes in OPEN are junk
this.Clear(); // Total search time exceeded - we're not going to resume this search.
this.CleanGlobals();
return false;
}
Debug.WriteLine("Getting the next node from OPEN");
CbsNode currentNode = openList.Remove();
if (currentNode.f > this.maxSolutionCost) // A late heuristic application may have increased the node's cost
{
continue;
// Don't expand the node.
// This will exhaust the open list, assuming Fs of nodes chosen for expansions
// are monotonically increasing.
// TODO: Pass maxSolutionCost to the DynamicLazyOpenList so it can inform the
// heuristic not to try to improve its estimate to make the node's f more
// than 1 + maxSolutionCost.
// OTOH, DynamicLazyOpenList only tries to increase the cost by 1 over the
// current minimum, and it would never reach maxSolutionCost + 1 to try to
// go above it.
}
currentNode.ChooseConflict(); // Does nothing if this node has already been partially expanded before
// Notice that even though we may discover cardinal conflicts in hindsight later,
// there would be no point in pushing their node back at that point,
// as we would've already made the split by then.
Debug.WriteLine("Expanding node: (or returning its solution, if it's a goal node)");
currentNode.DebugPrint();
// Update nodesExpandedWithGoalCost statistic
if (currentNode.g > currentCost) // Needs to be here because the goal may have a cost unseen before
{
currentCost = currentNode.g;
this.nodesExpandedWithGoalCost = 0;
}
else if (currentNode.g == currentCost) // check needed because macbs node cost isn't exactly monotonous
{
this.nodesExpandedWithGoalCost++;
}
// Check if node is the goal
if (currentNode.GoalTest())
{
Trace.Assert(currentNode.g >= maxExpandedNodeF,
$"CBS goal node found with lower cost than the max cost node ever expanded ({currentNode.g} < {maxExpandedNodeF})");
// This is subtle, but MA-CBS may expand nodes in a non non-decreasing order:
// If a non-optimal constraint is expanded upon and we decide to merge the agents,
// the resulting node can have a lower cost than before, since we ignore the non-optimal constraint
// because the conflict it addresses is between merged nodes.
// The resulting lower-cost node will have other constraints, that will raise the cost of its children back to at least its original cost,
// since the node with the non-optimal constraint was only expanded because its competitors that had an optimal
// constraint to deal with the same conflict apparently found the other conflict that I promise will be found,
// and so their cost was not smaller than this sub-optimal node.
// To make MA-CBS costs non-decreasing, we can choose not to ignore constraints that deal with conflicts between merged nodes.
// That way, the sub-optimal node will find a sub-optimal merged solution and get a high cost that will push it deep into the open list.
// But the cost would be to create a possibly sub-optimal merged solution where an optimal solution could be found instead, and faster,
// since constraints make the low-level heuristic perform worse.
// For an example for this subtle case happening, see problem instance 63 of the random grid with 4 agents,
// 55 grid cells and 9 obstacles.
Debug.WriteLine("-----------------");
this.solutionCost = currentNode.g;
this.solutionDepth = this.solutionCost - initialEstimate;
this.goalNode = currentNode; // Saves the single agent plans and costs
// The joint plan is calculated on demand.
this.Clear(); // Goal found - we're not going to resume this search
this.CleanGlobals();
return true;
}
if (maxExpandedNodeF < currentNode.f)
{
maxExpandedNodeF = currentNode.f;
Debug.WriteLine("New max F: {0}", maxExpandedNodeF);
}
// Check conditions that stop the search before a goal is found
if (currentNode.f >= this.targetF || // Node is good enough
this.singleAgentSolver.GetAccumulatedGenerated() + this.solver.GetAccumulatedGenerated() >
this.lowLevelGeneratedCap || // Stop because this is taking too long.
// We're looking at _generated_ low level nodes since that's an indication to the amount of work done,
// while expanded nodes is an indication of the amount of good work done.
(this.milliCap != int.MaxValue && // (This check is much cheaper than the method call)
this.runner.ElapsedMilliseconds() > this.milliCap)) // Search is taking too long.
{
Debug.WriteLine("-----------------");
this.solutionCost = maxExpandedNodeF; // This is the min possible cost so far.
this.openList.Add(currentNode); // To be able to continue the search later
this.CleanGlobals();
return false;
}
// Expand
bool wasUnexpandedNode = (currentNode.agentAExpansion == CbsNode.ExpansionState.NOT_EXPANDED &&
currentNode.agentBExpansion == CbsNode.ExpansionState.NOT_EXPANDED);
Expand(currentNode);
if (wasUnexpandedNode)
highLevelExpanded++;
// Consider moving the following into Expand()
if (currentNode.agentAExpansion == CbsNode.ExpansionState.EXPANDED &&
currentNode.agentBExpansion == CbsNode.ExpansionState.EXPANDED) // Fully expanded
currentNode.Clear();
}
// Check if max time has been exceeded
if (this.runner.ElapsedMilliseconds() > Constants.MAX_TIME)
{
this.solutionCost = (int)Constants.SpecialCosts.TIMEOUT_COST;
Console.WriteLine("Out of time");
this.solutionDepth = maxExpandedNodeF - initialEstimate; // A minimum estimate
}
else
this.solutionCost = (int) Constants.SpecialCosts.NO_SOLUTION_COST;
this.Clear(); // we're not going to resume this search - it either timed out or the problem is unsolvable
this.CleanGlobals();
return false;
}
protected virtual bool ShouldMerge(CbsNode node)
{
return node.ShouldMerge(mergeThreshold, node.conflict.agentAIndex, node.conflict.agentBIndex); //TODO: Add an option to use the old merge criterion
}
public virtual void Reset()
{
this.restarts++;
this.openList.Clear();
this.closedList.Clear();
}
/// <summary>
///
/// </summary>
/// <param name="node"></param>
/// <param name="adopt"></param>
/// <param name="children"></param>
/// <param name="reinsertParent">If it was only partially expanded</param>
/// <param name="adoptBy">If not given, adoption is done by expanded node</param>
/// <returns>true if adopted - need to rerun this method, ignoring the returned children from this call, bacause adoption was performed</returns>
protected (bool adopted, IList<CbsNode> children, bool reinsertParent) ExpandImpl(CbsNode node, bool adopt, CbsNode adoptBy = null)
{
CbsConflict conflict = node.GetConflict();
var children = new List<CbsNode>();
CbsNode child;
int closedListHitChildCost;
if (adoptBy == null)
adoptBy = node;
int adoptByH = adoptBy.h;
bool leftSameCost = false; // To quiet the compiler
bool rightSameCost = false;
if (this.mergeThreshold != -1 && ShouldMerge(node))
{
if (this.mergeCausesRestart == false)
{
(child, closedListHitChildCost) = this.MergeExpand(node);
if (child == null)
return (adopted: false, children, reinsertParent: false); // A timeout occured,
// or the child was already in the closed list,
// or there were just too many constraints
// (happens with ID, which adds whole paths as constraints)
}
else
{
// TODO: What if planning a path for the merged agents finds a path with the same
// cost as the sum of their current paths and no other conflicts exist? Should just
// adopt this solution and get a goal node.
// TODO: Save the cost of the group in a table, and use it as a heuristic in the future!
child = new CbsNode(this.instance.agents.Length, this.solver,
this.singleAgentSolver, this, node.agentsGroupAssignment); // This will be the new root node
child.MergeGroups(node.agentsGroupAssignment[conflict.agentAIndex], node.agentsGroupAssignment[conflict.agentBIndex],
fixCounts: false // This is a new root node, it doesn't have conflict counts yet
);
this.maxSizeGroup = Math.Max(this.maxSizeGroup, child.GetGroupSize(conflict.agentAIndex));
bool solved = child.Solve(this.minSolutionTimeStep);
child.h = node.f - child.g;
//if (this.debug)
Debug.WriteLine($"Restarting the search with agents {node.agentsGroupAssignment[conflict.agentAIndex]} and" +
$" {node.agentsGroupAssignment[conflict.agentBIndex]} merged.");
this.Reset();
if (solved == false) // Likely due to a time-out
return (adopted: false, children, reinsertParent: false);
}
// No need to try to adopt the child - there's only one so we're not branching.
children.Add(child);
return (adopted: false, children, reinsertParent: false);
}
bool reinsertParent = false;
// Generate left child:
(child, closedListHitChildCost) = ConstraintExpand(node, doLeftChild: true);
if (child != null)
{
if (child == node) // Expansion deferred
reinsertParent = true;
else // New child
{
// First fit adoption: Greedily adopt the first child that's better than the parent