-
Notifications
You must be signed in to change notification settings - Fork 16
/
A_Star.cs
1406 lines (1244 loc) · 63.6 KB
/
A_Star.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.IO;
using System.Diagnostics;
using ExtensionMethods;
namespace mapf;
/// <summary>
/// This is an implementation of the A* algorithm for the MAPF problem.
/// It r
/// </summary>
public class A_Star : ICbsSolver, IMStarSolver, IHeuristicSolver<WorldState>, IIndependenceDetectionSolver
{
protected ProblemInstance instance;
protected IHeuristicCalculator<WorldState> heuristic;
public OpenList<WorldState> openList;
public Dictionary<WorldState, WorldState> closedList;
/// <summary>
/// How much more expensive the solution was than the heuristic's initial estimate
/// </summary>
protected int solutionDepth;
protected Dictionary<int, int> conflictCounts;
protected Dictionary<int, List<int>> conflictTimes;
protected int expanded;
protected int generated;
protected int reopened;
/// <summary>
/// Note we can boost nodes that aren't eventually counted as generated (already in the closed list, too costly, ...)
/// </summary>
protected int bpmxBoosts;
protected int reopenedWithOldH;
protected int noReopenHUpdates;
protected int maxExpansionDelay;
protected int closedListHits;
protected int mstarBackprops;
protected int mstarShuffles;
protected int surplusNodesAvoided;
protected int accExpanded;
protected int accGenerated;
protected int accReopened;
protected int accBpmxBoosts;
protected int accReopenedWithOldH;
protected int accNoReopenHUpdates;
protected int accMaxExpansionDelay;
protected int accClosedListHits;
protected int accMstarBackprops;
protected int accMstarShuffles;
protected int accSurplusNodesAvoided;
/// <summary>
/// Holds the cost of the solution when a solution found
/// </summary>
public int totalCost;
public int numOfAgents;
protected int maxSolutionCost;
protected ConflictAvoidanceTable CAT;
protected ISet<TimedMove> illegalMoves;
protected int costParentGroupA;
protected int costParentGroupB;
protected int sizeParentGroupA;
protected ISet<CbsConstraint> constraints;
/// <summary>
/// An array of dictionaries that map constrained timesteps to must constraints.
/// </summary>
protected Dictionary<int, TimedMove>[] mustConstraints;
protected bool mstar = false;
protected bool doMstarShuffle = false;
//protected Dictionary<WorldState, SinglePlan[]> mstarPlanBasesToTheirPlans;
protected Dictionary<WorldState, HashSet<CbsConstraint>[]> mstarPlanBasesToTheirConstraints; // Most nodes won't have constraints so I don't want to make their memory footprint needlessly large.
protected List<CbsConflict> mstarBackPropagationConflictList;
protected Run runner;
protected Plan solution;
//// <summary>
//// For CBS/A*
//// </summary>
//protected int minDepth;
/// <summary>
/// Default constructor.
/// </summary>
public A_Star(IHeuristicCalculator<WorldState> heuristic = null, bool mStar = false, bool mStarShuffle = false)
{
this.closedList = new Dictionary<WorldState, WorldState>();
this.openList = new OpenList<WorldState>(this);
this.heuristic = heuristic;
this.queryConstraint = new CbsConstraint();
this.queryConstraint.queryInstance = true;
this.mstar = mStar;
this.doMstarShuffle = mStarShuffle;
}
/// <summary>
/// Setup the relevant data structures for a run under CBS.
/// </summary>
public virtual void Setup(ProblemInstance problemInstance, int minDepth, Run runner,
ConflictAvoidanceTable CAT = null,
ISet<CbsConstraint> constraints = null, ISet<CbsConstraint> positiveConstraints = null,
int minCost = -1, int maxCost = int.MaxValue, MDD mdd = null)
{
this.instance = problemInstance;
this.runner = runner;
MDDNode mddRoot = null;
if (mdd != null)
{
Trace.Assert(problemInstance.agents.Length == 1, "Using MDDs to find new paths is currently only supported for single agent search");
mddRoot = mdd.levels[0].First.Value;
}
WorldState root = this.CreateSearchRoot(minDepth, minCost, mddRoot);
root.h = (int)this.heuristic.h(root); // g was already set in the constructor
if (root.f < minCost)
root.h = minCost - root.g; // Will be propagated to children with BPMX as needed
this.openList.Add(root);
this.closedList.Add(root, root);
this.ClearPrivateStatistics();
this.generated++; // The root
root.generated = generated;
this.totalCost = 0;
this.singleCosts = null;
this.solution = null;
this.singlePlans = null;
this.conflictCounts = null;
this.conflictTimes = null;
this.solutionDepth = -1;
this.numOfAgents = problemInstance.agents.Length;
this.maxSolutionCost = maxCost;
this.CAT = CAT;
this.constraints = constraints;
if (positiveConstraints != null)
{
this.mustConstraints = new Dictionary<int, TimedMove>[positiveConstraints.Max(con => con.GetTimeStep()) + 1]; // To have index MAX, array needs MAX + 1 places.
foreach (CbsConstraint con in positiveConstraints)
{
int timeStep = con.GetTimeStep();
if (this.mustConstraints[timeStep] == null)
this.mustConstraints[timeStep] = new Dictionary<int, TimedMove>();
this.mustConstraints[timeStep][con.agentNum] = con.move;
}
}
if (this.mstar)
{
root.backPropagationSet = new HashSet<WorldState>();
root.collisionSets = new DisjointSets<int>();
this.mstarBackPropagationConflictList = new List<CbsConflict>();
}
}
/// <summary>
/// Factory method. Creates the initial state from which the search will start.
/// This will be the first state to be inserted to OPEN.
/// </summary>
/// <returns>The root of the search tree</returns>
protected virtual WorldState CreateSearchRoot(int minDepth = -1, int minCost = -1, MDDNode mddNode = null)
{
return new WorldState(this.instance.agents, minDepth, minCost, mddNode);
}
/// <summary>
/// Clears the relevant data structures and variables to free memory.
/// </summary>
public void Clear()
{
this.openList.Clear();
this.closedList.Clear();
this.mustConstraints = null;
this.illegalMoves = null;
// Set trivial values for subproblem data
this.costParentGroupA = 0;
this.costParentGroupB = 0;
this.sizeParentGroupA = 1;
}
public IHeuristicCalculator<WorldState> GetHeuristic()
{
return this.heuristic;
}
public virtual String GetName()
{
if (this.mstar == false)
return "A*";
else if (this.doMstarShuffle == false)
return "rM*";
else
return "rM*+shuffle";
}
public override string ToString()
{
string ret = $"{this.GetName()}/{this.heuristic}";
if (this.openList.GetType() != typeof(OpenList<WorldState>))
ret += $" with {this.openList}";
return ret;
}
public int GetSolutionCost() { return this.totalCost; }
public Dictionary<int, int> GetExternalConflictCounts()
{
return this.conflictCounts;
}
public Dictionary<int, List<int>> GetConflictTimes()
{
return this.conflictTimes;
}
protected void ClearPrivateStatistics()
{
this.expanded = 0;
this.generated = 0;
this.reopened = 0;
this.bpmxBoosts = 0;
this.reopenedWithOldH = 0;
this.noReopenHUpdates = 0;
this.closedListHits = 0;
this.maxExpansionDelay = -1;
this.surplusNodesAvoided = 0;
this.mstarBackprops = 0;
this.mstarShuffles = 0;
}
public virtual void OutputStatisticsHeader(TextWriter output)
{
output.Write(this.ToString() + " Expanded");
output.Write(Run.RESULTS_DELIMITER);
output.Write(this.ToString() + " Generated");
output.Write(Run.RESULTS_DELIMITER);
output.Write(this.ToString() + " Reopened");
output.Write(Run.RESULTS_DELIMITER);
output.Write(this.ToString() + " BPMX boosts");
output.Write(Run.RESULTS_DELIMITER);
output.Write(this.ToString() + " Closed List Hits");
output.Write(Run.RESULTS_DELIMITER);
output.Write(this.ToString() + " Reopened With Old H");
output.Write(Run.RESULTS_DELIMITER);
output.Write(this.ToString() + " H Updated From Other Area");
output.Write(Run.RESULTS_DELIMITER);
output.Write(this.ToString() + " Max expansion delay");
output.Write(Run.RESULTS_DELIMITER);
output.Write(this.ToString() + " Surplus nodes avoided");
output.Write(Run.RESULTS_DELIMITER);
if (this.mstar)
{
output.Write(this.ToString() + " Backpropagations");
output.Write(Run.RESULTS_DELIMITER);
output.Write(this.ToString() + " Shuffles");
output.Write(Run.RESULTS_DELIMITER);
}
this.heuristic.OutputStatisticsHeader(output);
this.openList.OutputStatisticsHeader(output);
}
/// <summary>
/// Prints statistics of a single run to the given output.
/// </summary>
public virtual void OutputStatistics(TextWriter output)
{
Console.WriteLine("Total Expanded Nodes: {0}", this.GetExpanded());
Console.WriteLine("Total Generated Nodes: {0}", this.GetGenerated());
Console.WriteLine("Total Reopened Nodes: {0}", this.reopened);
Console.WriteLine("Num BPMX boosts: {0}", this.bpmxBoosts);
Console.WriteLine("Closed list hits: {0}", this.closedListHits);
Console.WriteLine("Reopened Nodes With Old H: {0}", this.reopenedWithOldH);
Console.WriteLine("No Reopen H Updates: {0}", this.noReopenHUpdates);
Console.WriteLine("Max expansion delay: {0}", this.maxExpansionDelay);
Console.WriteLine("Surplus nodes avoided: {0}", this.surplusNodesAvoided);
if (this.mstar)
{
Console.WriteLine("Backpropagations: {0}", this.mstarBackprops);
Console.WriteLine("Shuffles: {0}", this.mstarShuffles);
}
output.Write(this.expanded + Run.RESULTS_DELIMITER);
output.Write(this.generated + Run.RESULTS_DELIMITER);
output.Write(this.reopened + Run.RESULTS_DELIMITER);
output.Write(this.bpmxBoosts + Run.RESULTS_DELIMITER);
output.Write(this.closedListHits + Run.RESULTS_DELIMITER);
output.Write(this.reopenedWithOldH + Run.RESULTS_DELIMITER);
output.Write(this.noReopenHUpdates + Run.RESULTS_DELIMITER);
output.Write(this.maxExpansionDelay + Run.RESULTS_DELIMITER);
output.Write(this.surplusNodesAvoided + Run.RESULTS_DELIMITER);
if (this.mstar)
{
output.Write(this.mstarBackprops + Run.RESULTS_DELIMITER);
output.Write(this.mstarShuffles + Run.RESULTS_DELIMITER);
}
this.heuristic.OutputStatistics(output);
this.openList.OutputStatistics(output);
}
public virtual int NumStatsColumns
{
get
{
return (this.mstar? 11 : 9) + this.heuristic.NumStatsColumns + this.openList.NumStatsColumns;
}
}
public virtual void ClearStatistics()
{
this.ClearPrivateStatistics();
this.heuristic.ClearStatistics();
this.openList.ClearStatistics();
}
public virtual void ClearAccumulatedStatistics()
{
this.accExpanded = 0;
this.accGenerated = 0;
this.accReopened = 0;
this.accBpmxBoosts = 0;
this.accClosedListHits = 0;
this.accReopenedWithOldH = 0;
this.accNoReopenHUpdates = 0;
this.accMaxExpansionDelay = 0;
this.accSurplusNodesAvoided = 0;
this.accMstarBackprops = 0;
this.accMstarShuffles = 0;
this.heuristic.ClearAccumulatedStatistics();
this.openList.ClearAccumulatedStatistics();
}
public virtual void AccumulateStatistics()
{
this.accExpanded += this.expanded;
this.accGenerated += this.generated;
this.accReopened += this.reopened;
this.accBpmxBoosts += this.bpmxBoosts;
this.accClosedListHits += this.closedListHits;
this.accReopenedWithOldH += this.reopenedWithOldH;
this.accNoReopenHUpdates += this.noReopenHUpdates;
this.accMaxExpansionDelay = Math.Max(this.accMaxExpansionDelay, this.maxExpansionDelay);
this.accSurplusNodesAvoided += this.surplusNodesAvoided;
this.accMstarBackprops += this.mstarBackprops;
this.accMstarShuffles += this.mstarShuffles;
this.heuristic.AccumulateStatistics();
this.openList.AccumulateStatistics();
}
public virtual void OutputAccumulatedStatistics(TextWriter output)
{
Console.WriteLine("{0} Accumulated Expanded Nodes (Low-Level): {1}", this, this.accExpanded);
Console.WriteLine("{0} Accumulated Generated Nodes (Low-Level): {1}", this, this.accGenerated);
Console.WriteLine("{0} Accumulated Reopened Nodes (Low-Level): {1}", this, this.accReopened);
Console.WriteLine("{0} Accumulated BPMX boosts (Low-Level): {1}", this, this.accBpmxBoosts);
Console.WriteLine("{0} Accumulated Closed list hits (Low-Level): {1}", this, this.accClosedListHits);
Console.WriteLine("{0} Accumulated Reopened Nodes With Old H (Low-Level): {1}", this, this.accReopenedWithOldH);
Console.WriteLine("{0} Accumulated No Reopen H Updates (Low-Level): {1}", this, this.accNoReopenHUpdates);
Console.WriteLine("{0} Accumulated Max expansion delay (Low-Level): {1}", this, this.accMaxExpansionDelay);
Console.WriteLine("{0} Accumulated Surplus nodes avoided (Low-Level): {1}", this, this.accSurplusNodesAvoided);
if (this.mstar)
{
Console.WriteLine("{0} Accumulated Backpropagations (Low-Level): {1}", this, this.accMstarBackprops);
Console.WriteLine("{0} Accumulated Shuffles (Low-Level): {1}", this, this.accMstarShuffles);
}
output.Write(this.accExpanded + Run.RESULTS_DELIMITER);
output.Write(this.accGenerated + Run.RESULTS_DELIMITER);
output.Write(this.accReopened + Run.RESULTS_DELIMITER);
output.Write(this.accBpmxBoosts + Run.RESULTS_DELIMITER);
output.Write(this.accClosedListHits + Run.RESULTS_DELIMITER);
output.Write(this.accReopenedWithOldH + Run.RESULTS_DELIMITER);
output.Write(this.accNoReopenHUpdates + Run.RESULTS_DELIMITER);
output.Write(this.accMaxExpansionDelay + Run.RESULTS_DELIMITER);
output.Write(this.accSurplusNodesAvoided + Run.RESULTS_DELIMITER);
if (this.mstar)
{
output.Write(this.accMstarBackprops + Run.RESULTS_DELIMITER);
output.Write(this.accMstarShuffles + Run.RESULTS_DELIMITER);
}
this.heuristic.OutputAccumulatedStatistics(output);
this.openList.OutputAccumulatedStatistics(output);
}
public bool debug = false;
/// <summary>
/// Runs the algorithm until the problem is solved or memory/time is exhausted
/// </summary>
/// <returns>True if solved</returns>
public virtual bool Solve()
{
int initialEstimate = (int) this.heuristic.h(openList.Peek()); // g=0 initially. Recomputing the heuristic to drop the boost from minCost info.
int lastF = -1;
WorldState lastNode = null;
while (openList.Count > 0)
{
// Check if max time has been exceeded
if (runner.ElapsedMilliseconds() > Constants.MAX_TIME)
{
totalCost = (int) Constants.SpecialCosts.TIMEOUT_COST;
Console.WriteLine("Out of time");
this.solutionDepth = openList.Peek().g + openList.Peek().h - initialEstimate; // A minimum estimate, assuming h is admissible
this.Clear();
return false;
}
WorldState currentNode = openList.Remove();
if (currentNode.f > this.maxSolutionCost) // A late heuristic application may have increased the node's cost
{
continue;
// This will exhaust the open list, assuming Fs of nodes chosen for expansions
// are monotonically increasing.
}
if (debug)
{
Debug.WriteLine($"Expanding node {currentNode}");
}
//if (this.instance.agents.Length > 2)
//{
// int a = 3;
// int b = (a + 2) * 2;
// int x1, x2, x3, y1, y2, y3, x4, y4;
// x1 = 5; y1 = 3;
// x2 = 5; y2 = 4;
// x3 = 6; y3 = 2;
// x4 = 5; y4 = 7;
// if (currentNode.allAgentsState[0].lastMove.x == x1 &&
// currentNode.allAgentsState[0].lastMove.y == y1 &&
// currentNode.allAgentsState[1].lastMove.x == x2 &&
// currentNode.allAgentsState[1].lastMove.y == y2 &&
// currentNode.allAgentsState[2].lastMove.x == x3 &&
// currentNode.allAgentsState[2].lastMove.y == y3 &&
// currentNode.allAgentsState[3].lastMove.x == x4 &&
// currentNode.allAgentsState[3].lastMove.y == y4)
// {
// int c = 3;
// int d = 3 * c;
// }
//}
if (this.mstar == false && // Backpropagation can cause the root to be re-expanded after many more expensive nodes were expanded.
(this.openList is DynamicLazyOpenList<WorldState>) == false && // When the open list has just one node,
// application of the expensive heuristic is skipped altogether.
// This can cause decreasing F values.
(this.openList is DynamicRationalLazyOpenList) == false &&
currentNode.minGoalCost == -1 // If we were given a minGoalCost (by ID, for example), then at some point we're going to use up the boost to the h-value we gave the root
)
if (currentNode.f < lastF)
Trace.Assert(false, $"A* node with decreasing F: {currentNode.f} < {lastF}.");
else
{
// TODO: Record the max F. Assert that the goal's F isn't smaller than it.
}
lastF = currentNode.f;
lastNode = currentNode;
// Calculate expansion delay
int expansionDelay = this.expanded - currentNode.expandedCountWhenGenerated - 1; // -1 to make the delay zero when a node is expanded immediately after being generated.
maxExpansionDelay = Math.Max(maxExpansionDelay, expansionDelay);
// Check if node is the goal, or knows how to get to it
if (currentNode.GoalTest())
{
this.totalCost = currentNode.GetGoalCost();
this.singleCosts = currentNode.GetSingleCosts();
this.solution = currentNode.GetPlan();
this.singlePlans = currentNode.GetSinglePlans();
this.conflictCounts = currentNode.conflictCounts;
this.conflictTimes = currentNode.conflictTimes;
this.solutionDepth = this.totalCost - initialEstimate;
this.Clear();
return true;
}
// Expand
if (this.mstar == false)
{
//Expand(currentNode);
}
else
{
this.mstarBackPropagationConflictList.Clear();
// TODO: Need to clear individual agent planned moves, in case this node was reopened with an updated collision set.
if (this.debug)
{
Console.Write("with collision sets: {0}", currentNode.collisionSets);
}
var sets = currentNode.collisionSets.GetSets();
foreach (var set in sets)
{
if (set.Count != 0)
{
}
// Give each agent in the set a planned move
}
}
Expand(currentNode);
expanded++;
if (this.mstar && this.mstarBackPropagationConflictList.Count != 0)
{
++this.mstarBackprops;
foreach (var conflict in this.mstarBackPropagationConflictList)
{
//currentNode.individualMStarPlans[conflict.agentAIndex] = null;
//currentNode.individualMStarPlans[conflict.agentBIndex] = null;
this.RMStarCollisionBackPropagation(conflict, currentNode);
}
this.mstarBackPropagationConflictList.Clear();
}
}
totalCost = (int) Constants.SpecialCosts.NO_SOLUTION_COST;
this.Clear();
return false;
}
/// <summary>
/// Expand a given node. This includes:
/// - Generating all possible children
/// - Inserting them to OPEN
/// - Insert the generated nodes to the hashtable of nodes, currently implemented together with the closed list.
/// </summary>
/// <param name="node"></param>
public virtual void Expand(WorldState node)
{
var intermediateNodes = new List<WorldState>() { node };
for (int agentIndex = 0; agentIndex < this.instance.agents.Length ; ++agentIndex)
{
if (runner.ElapsedMilliseconds() > Constants.MAX_TIME)
return;
intermediateNodes = ExpandOneAgent(intermediateNodes, agentIndex);
}
var finalGeneratedNodes = intermediateNodes;
foreach (var currentNode in finalGeneratedNodes)
{
if (runner.ElapsedMilliseconds() > Constants.MAX_TIME)
return;
currentNode.makespan++;
currentNode.CalculateG();
currentNode.h = (int)this.heuristic.h(currentNode);
// Boost h based on minGoalCost
if (currentNode.g < currentNode.minGoalCost)
{
if (currentNode.h == 0) // Agent is at the goal, only too early
currentNode.h = 2; // Otherwise waiting at goal would expand to waiting at the goal for the same too low cost,
// which would expand to waiting at the goal, etc.
// +2 because you need a step out of the goal and another step into it.
currentNode.h = Math.Max(currentNode.h, currentNode.minGoalCost - currentNode.g); // Like a Manhattan Distance on the time dimension
// TODO: Add a statistic for when the H was increased thanks to the minGoalCost
}
}
// Path-Max stage:
if ((this.heuristic.GetType() != typeof(SumIndividualCosts) &&
(this.heuristic.GetType() != typeof(MaxIndividualCosts))) || (this.openList.GetType() != typeof(OpenList<WorldState>))) // double CHECK!
// otherwise if we just use SIC and no lazy heuristic in addition to it,
// then our heuristic is consistent and Path-Max isn't necessary
{
// Reverse Path-Max (operators are invertible) - BPMX (Felner et al. 2005)
WorldState parent = node;
var childWithMaxH = finalGeneratedNodes.MaxByKeyFunc(child => child.h);
int maxChildH = childWithMaxH.h;
int deltaGOfChildWithMaxH = childWithMaxH.g - parent.g;
if (parent.h < maxChildH - deltaGOfChildWithMaxH)
{
int newParentH = maxChildH - deltaGOfChildWithMaxH;
parent.hBonus += newParentH - parent.h;
parent.h = newParentH; // Also good for partial expansion algs that reinsert the expanded node into the open list
// (in addition to aiding the forward Path-Max).
++bpmxBoosts;
// FIXME: Code duplication with Forward Path-Max
}
// Forward Path-Max
foreach (var child in finalGeneratedNodes)
{
int deltaG = child.g - parent.g; // == (parent.g + c(parent, current)) - parent.g == c(parent, current)
if (child.h < parent.h - deltaG)
{
int newChildH = parent.h - deltaG;
child.hBonus += newChildH - child.h;
child.h = newChildH;
++bpmxBoosts;
}
}
}
// Enter the generated nodes into the open list
foreach (var child in finalGeneratedNodes)
{
ProcessGeneratedNode(child);
}
if (this.debug)
Debug.WriteLine("");
}
/// <summary>
/// Expands a single agent in the nodes.
/// This includes:
/// - Generating the children
/// - Inserting them into OPEN
/// - Insert node into CLOSED
/// Returns the child nodes
/// </summary>
protected virtual List<WorldState> ExpandOneAgent(List<WorldState> intermediateNodes, int agentIndex)
{
var GeneratedNodes = new List<WorldState>();
foreach (var currentNode in intermediateNodes)
{
if (runner.ElapsedMilliseconds() > Constants.MAX_TIME)
break;
if (currentNode.mddNode == null)
{
// Try all legal moves of the agents
foreach (TimedMove potentialMove in currentNode.allAgentsState[agentIndex].lastMove.GetNextMoves())
{
WorldState origNode = agentIndex == 0 ? currentNode : currentNode.prevStep;
//moveIsValid = this.IsValid(potentialMove, currentNode.currentMoves, currentNode.makespan + 1, agentIndex, origNode, currentNode);
//if (moveIsValid == false)
// continue;
//----------------Begin pasting isValid method
TimedMove possibleMove = potentialMove;
IReadOnlyDictionary<TimedMove, int> currentMoves = currentNode.currentMoves; // When agentIndex == 0, this is null (nullified when generating it was done.
int makespan = currentNode.makespan + 1;
WorldState fromNode = origNode;
WorldState intermediateMode = currentNode;
int agentNum = fromNode.allAgentsState[agentIndex].agent.agentNum;
// Check if the proposed move is reserved in the plan of another agent.
// This is used in IndependenceDetection's ImprovedID.
if (this.illegalMoves != null)
{
if (possibleMove.IsColliding(illegalMoves))
continue;
}
// Check if there's a CBS negative constraint on the proposed move
if (this.constraints != null)
{
queryConstraint.Init(agentNum, possibleMove);
if (this.constraints.Contains(queryConstraint))
continue;
}
// Check if there's a CBS positive constraint on the proposed move
if (this.mustConstraints != null && makespan < this.mustConstraints.Length && // There may be a constraint on the timestep of the generated node
this.mustConstraints[makespan] != null &&
this.mustConstraints[makespan].ContainsKey(agentNum)) // This agent has a must constraint for this time step
{
if (this.mustConstraints[makespan][agentNum].Equals(possibleMove) == false)
continue;
}
// Check if the tile is not free (out of the grid or with an obstacle)
if (this.instance.IsValid(possibleMove) == false)
continue;
// Check against all the agents that have already moved to see if current move collides with their move
bool collision;
if (this.mstar)
{
bool agentInCollisionSet = fromNode.collisionSets.IsSingle(agentIndex);
if (agentInCollisionSet == false) // Only one move allowed
{
bool hasPlan = true;
if (hasPlan)
{
// If this move isn't its individually optimal one according to its planned route, return false.
if (this.instance.GetSingleAgentOptimalMove(fromNode.allAgentsState[agentIndex]).Equals(possibleMove) == false)
continue;
}
}
var collidingWith = possibleMove.GetColliding(currentMoves);
collision = collidingWith.Count != 0;
if (collision)
{
// It is possible that possibleMove collides with two moves from currentMoves,
// even though currentMoves contains no collisions:
// Agent 0: 0,0 -> 1,0
// Agent 1: 0,1 -> 0,0
// Agent 2: 1,0 -> 0,0
// Arbitrarily choosing the first colliding agent:
int collidingAgentIndex = collidingWith[0];
bool otherAgentInColSet = fromNode.collisionSets.IsSingle(collidingAgentIndex);
// Check if one of the colliding agents isn't in the collision set yet
if (agentInCollisionSet == false ||
otherAgentInColSet == false)
{
if (this.debug)
Debug.WriteLine("Agent planned route collides with another move!");
bool success = false;
var conflict = new CbsConflict(
agentIndex, collidingAgentIndex, possibleMove,
intermediateMode.allAgentsState[collidingAgentIndex].lastMove, makespan);
if (this.debug)
Debug.WriteLine(conflict.ToString());
if (success == false)
{
this.mstarBackPropagationConflictList.Add(conflict);
}
}
}
}
else
{
// Check if the proposed move collides with moves already made
collision = possibleMove.IsColliding(currentMoves);
}
if (collision)
continue;
//----------------end paste from isValid
WorldState childNode = CreateSearchNode(currentNode);
childNode.allAgentsState[agentIndex].MoveTo(potentialMove);
if (agentIndex < currentNode.allAgentsState.Length - 1) // More agents need to move
childNode.currentMoves.Add(childNode.allAgentsState[agentIndex].lastMove, agentIndex);
else // Moved the last agent
childNode.currentMoves = null; // To reduce memory load and lookup times
// Set the node's prevStep to its real parent, skipping over the intermediate nodes.
if (agentIndex != 0)
childNode.prevStep = currentNode.prevStep;
GeneratedNodes.Add(childNode);
}
}
else
{
foreach (MDDNode childMddNode in currentNode.mddNode.children)
{
WorldState childNode = CreateSearchNode(currentNode);
childNode.allAgentsState[agentIndex].MoveTo(childMddNode.move);
childNode.mddNode = childMddNode;
// No need to set the node's prevStep because we're dealing with a single agent -
// no intermediate nodes.
// TODO: Add that support
GeneratedNodes.Add(childNode);
}
}
}
return GeneratedNodes;
}
/// <summary>
/// Factory method.
/// </summary>
/// <param name="from"></param>
/// <returns></returns>
protected virtual WorldState CreateSearchNode(WorldState from)
{
return new WorldState(from);
}
/// <summary>
/// Just an optimization
/// </summary>
private CbsConstraint queryConstraint;
/// <summary>
/// Check if the move is valid, i.e. not colliding into walls or other agents.
/// This method is here instead of in ProblemInstance to enable algorithmic tweaks.
/// NOTE: This method is pasted into ExpandOneAgent. Be sure to update anything in both places!
/// </summary>
/// <param name="possibleMove">The move to check if possible</param>
/// <param name="currentMoves"></param>
/// <param name="makespan"></param>
/// <param name="agentIndex"></param>
/// <param name="fromNode">To get the agentNum from the agentIndex. TODO: consider just passing the agentNum</param>
/// <param name="intermediateMode">For M* stuff</param>
/// <returns>true, if the move is possible.</returns>
protected virtual bool IsValid(TimedMove possibleMove,
IReadOnlyDictionary<TimedMove, int> currentMoves, int makespan,
int agentIndex, WorldState fromNode, WorldState intermediateMode)
{
int agentNum = fromNode.allAgentsState[agentIndex].agent.agentNum;
// Check if the proposed move is reserved in the plan of another agent.
// This is used in IndependenceDetection's ImprovedID.
if (this.illegalMoves != null)
{
if (possibleMove.IsColliding(illegalMoves))
return false;
}
// Check if there's a CBS negative constraint on the proposed move
if (this.constraints != null)
{
this.queryConstraint.Init(agentNum, possibleMove);
if (this.constraints.Contains(queryConstraint))
return false;
}
// Check if there's a CBS positive constraint on the proposed move
if (this.mustConstraints != null && makespan < this.mustConstraints.Length && // There may be a constraint on the timestep of the generated node
this.mustConstraints[makespan] != null &&
this.mustConstraints[makespan].ContainsKey(agentNum)) // This agent has a must constraint for this time step
{
if (this.mustConstraints[makespan][agentNum].Equals(possibleMove) == false)
return false;
}
// Check if the tile is not free (out of the grid or with an obstacle)
if (this.instance.IsValid(possibleMove) == false)
return false;
// Check against all the agents that have already moved to see if current move collides with their move
bool collision;
if (this.mstar)
{
bool agentInCollisionSet = fromNode.collisionSets.IsSingle(agentIndex);
//fromNode.currentCollisionSet.Contains(agentIndex);// ||
//(fromNode.individualMStarPlanBases[agentIndex] != null &&
// this.mstarPlanBasesToTheirPlans[fromNode.individualMStarPlanBases[agentIndex]][agentIndex] == null); // Parent plan was abandoned. Imagine a backpropagation happened.
if (agentInCollisionSet == false) // Only one move allowed
{
bool hasPlan = true;
//// if the agent doesn't have a planned route, give it a planned route,
////if (fromNode.individualMStarPlanBases[agentIndex] == null) // No parent plan ever
//if (fromNode.individualMStarPlans[agentIndex] == null) // need to give this agent a plan
//{
// //fromNode.individualMStarPlanBases[agentIndex] = fromNode;
// fromNode.individualMStarBookmarks[agentIndex] = 0;
// //if (this.mstarPlanBasesToTheirPlans.ContainsKey(fromNode) == false)
// // this.mstarPlanBasesToTheirPlans[fromNode] = new SinglePlan[this.instance.GetNumOfAgents()];
// if (fromNode.individualMStarPlans == null)
// fromNode.individualMStarPlans = new SinglePlan[this.instance.GetNumOfAgents()];
// hasPlan = this.solveOneAgentForMstar(fromNode, agentIndex);
// //if (hasPlan == false)
// // this.mstarPlanBasesToTheirPlans[fromNode][agentIndex] = null;
// if (this.debug)
// {
// Debug.WriteLine("Agent {0} plan:", agentIndex);
// //Debug.WriteLine(this.mstarPlanBasesToTheirPlans[fromNode.individualMStarPlanBases[agentIndex]][agentIndex].ToString());
// Debug.WriteLine(fromNode.individualMStarPlans[agentIndex].ToString());
// }
//}
if (hasPlan)
{
// If this move isn't its individually optimal one according to its planned route, return false.
////var planBase = fromNode.individualMStarPlanBases[agentIndex];
////var plan = this.mstarPlanBasesToTheirPlans[planBase][agentIndex];
//var plan = fromNode.individualMStarPlans[agentIndex];
//Move allowed = plan.GetLocationAt(fromNode.individualMStarBookmarks[agentIndex] + 1);
//if (possibleMove.Equals(allowed) == false)
// return false;
if (this.instance.GetSingleAgentOptimalMove(fromNode.allAgentsState[agentIndex]).Equals(possibleMove) == false)
return false;
}
}
var collidingWith = possibleMove.GetColliding(currentMoves);
collision = collidingWith.Count != 0;
if (collision)
{
// It is possible that possibleMove collides with two moves from currentMoves, even though currentMoves contains no collisions:
// Agent 0: 0,0 -> 1,0
// Agent 1: 0,1 -> 0,0
// Agent 2: 1,0 -> 0,0
// Arbitrarily choosing the first colliding agent:
int collidingAgentIndex = collidingWith[0];
bool otherAgentInColSet = fromNode.collisionSets.IsSingle(collidingAgentIndex);
//fromNode.currentCollisionSet.Contains(collidingAgentIndex);// ||
//(fromNode.individualMStarPlanBases[collidingAgentIndex] != null &&
//this.mstarPlanBasesToTheirPlans[fromNode.individualMStarPlanBases[collidingAgentIndex]][collidingAgentIndex] == null); // Parent plan was abandoned;
// Check if one of the colliding agents isn't in the collision set yet
if (agentInCollisionSet == false ||
otherAgentInColSet == false)
{
if (this.debug)
Debug.WriteLine("Agent planned route collides with another move!");
bool success = false;
var conflict = new CbsConflict(
agentIndex, collidingAgentIndex, possibleMove,
intermediateMode.allAgentsState[collidingAgentIndex].lastMove, makespan);
if (this.debug)
Debug.WriteLine(conflict.ToString());
//if (this.doMstarShuffle && agentInCollisionSet == false)
//{
// ++this.mstarShuffles;
// WorldState planStart = fromNode.GetPlanStart(agentIndex);
// success = this.RMStarShuffleIndividualPath(conflict, true, planStart);
// if (success)
// {
// //this.reinsertIntoOpenList(fromNode.individualMStarPlanBases[agentIndex]);
// this.reinsertIntoOpenList(planStart);
// if (this.debug)
// {
// Debug.WriteLine("Agent {0} new plan:", agentIndex);
// //Debug.WriteLine(this.mstarPlanBasesToTheirPlans[fromNode.individualMStarPlanBases[agentIndex]][agentIndex].ToString());
// Debug.WriteLine(fromNode.individualMStarPlans[agentIndex].ToString());
// }
// }
// else
// {
// if (this.debug)
// Debug.WriteLine("Replanning Agent {0} for the same cost failed", agentIndex);
// }
//}
//if (this.doMstarShuffle && success == false && otherAgentInColSet == false)
//{
// ++this.mstarShuffles;
// WorldState planStart = fromNode.GetPlanStart(collidingAgentIndex);
// success = this.RMStarShuffleIndividualPath(conflict, false, planStart);
// if (success)
// {
// //this.reinsertIntoOpenList(fromNode.individualMStarPlanBases[collidingAgentIndex]);
// this.reinsertIntoOpenList(planStart);
// if (this.debug)
// {
// Debug.WriteLine("Agent {0} new plan:", collidingAgentIndex);
// //Debug.WriteLine(this.mstarPlanBasesToTheirPlans[fromNode.individualMStarPlanBases[collidingAgentIndex]][collidingAgentIndex].ToString());
// Debug.WriteLine(fromNode.individualMStarPlans[collidingAgentIndex].ToString());
// }
// }
// else
// {
// if (this.debug)
// Debug.WriteLine("Replanning Agent {0} for the same cost failed", collidingAgentIndex);
// }
//}
if (success == false)
{
this.mstarBackPropagationConflictList.Add(conflict);
}
}
}
}
else
{
// Check if the proposed move collides with moves already made
collision = possibleMove.IsColliding(currentMoves);
}
return collision == false;
}
/// <summary>
/// Returns the found plan, or null if no plan was found.
/// </summary>
/// <returns></returns>
public virtual Plan GetPlan()
{
return this.solution;
}
protected SinglePlan[] singlePlans;
public virtual SinglePlan[] GetSinglePlans()
{
return this.singlePlans;
}
protected int[] singleCosts;
public virtual int[] GetSingleCosts()
{