Skip to content

Commit

Permalink
Added the option to use AS model in ID
Browse files Browse the repository at this point in the history
  • Loading branch information
OmriKaduri committed Dec 20, 2019
1 parent b574a9d commit e30ca12
Show file tree
Hide file tree
Showing 27 changed files with 319 additions and 33 deletions.
Binary file modified .vs/mapf/v15/.suo
Binary file not shown.
Binary file modified .vs/mapf/v15/Server/sqlite3/storage.ide
Binary file not shown.
Binary file modified .vs/mapf/v15/Server/sqlite3/storage.ide-shm
Binary file not shown.
Binary file modified .vs/mapf/v15/Server/sqlite3/storage.ide-wal
Binary file not shown.
159 changes: 151 additions & 8 deletions IndependenceDetection.cs
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,8 @@
using System.Collections.Generic;
using System.IO;
using System.Diagnostics;
using SharpLearning.XGBoost.Learners;
using SharpLearning.XGBoost.Models;

namespace mapf
{
Expand All @@ -24,6 +26,8 @@ class IndependenceDetection : ISolver
public int totalCost;
protected Run runner;

public Boolean withSelection;

/// <summary>
/// The complete plan for all the agents that was found.
/// </summary>
Expand All @@ -40,10 +44,12 @@ class IndependenceDetection : ISolver
private Dictionary<TimedMove, List<int>> conflictAvoidance;
private int maxSolutionCostFound;

public IndependenceDetection(ISolver singleAgentSolver, ISolver groupSolver)
public IndependenceDetection(ISolver singleAgentSolver, ISolver groupSolver, Boolean withSelection = false)
{
this.singleAgentSolver = singleAgentSolver;
this.groupSolver = groupSolver;
this.withSelection = withSelection;

}

public void Clear()
Expand Down Expand Up @@ -71,7 +77,16 @@ public void Setup(ProblemInstance instance, Run runner)
this.singleAgentSolver, this.groupSolver));
}

public virtual String GetName() { return groupSolver.GetName() + "+ID"; }
public virtual String GetName() {
if (this.withSelection)
{
return groupSolver.GetName() + "+ID+AS";
}
else
{
return groupSolver.GetName() + "+ID";
}
}

/// <summary>
/// Calculate the full plan for all the agents that has been found by the algorithm
Expand Down Expand Up @@ -319,7 +334,7 @@ public bool ImprovedID(Run runner)
conflict.group1.GetPlan().PrintPlan();
}
conflict.group1.removeGroupFromCAT(conflictAvoidance);
bool resolved = conflict.group1.ReplanUnderConstraints(conflict.group2.GetPlan(), runner);
bool resolved = conflict.group1.ReplanUnderConstraints(conflict.group2.GetPlan(), runner, withSelection);
conflict.group1.addGroupToCAT(conflictAvoidance, maxSolutionCostFound);
if (resolved == true)
{
Expand Down Expand Up @@ -348,7 +363,7 @@ public bool ImprovedID(Run runner)
conflict.group2.GetPlan().PrintPlan();
}
conflict.group2.removeGroupFromCAT(conflictAvoidance);
bool resolved = conflict.group2.ReplanUnderConstraints(conflict.group1.GetPlan(), runner);
bool resolved = conflict.group2.ReplanUnderConstraints(conflict.group1.GetPlan(), runner, withSelection);
conflict.group2.addGroupToCAT(conflictAvoidance, maxSolutionCostFound);
if (resolved == true)
{
Expand Down Expand Up @@ -386,7 +401,15 @@ public bool ImprovedID(Run runner)
compositeGroup.instance.parameters[CONFLICT_AVOIDANCE] = conflictAvoidance;

// Solve composite group with the underlying group solver
bool solved = compositeGroup.Solve(runner);
bool solved;
if (this.withSelection)
{
solved = compositeGroup.SolveWithSelection(runner);
}
else
{
solved = compositeGroup.Solve(runner);
}

if (compositeGroup.solutionCost > maxSolutionCostFound)
maxSolutionCostFound = compositeGroup.solutionCost;
Expand Down Expand Up @@ -504,13 +527,22 @@ class IndependenceDetectionAgentsGroup
private ISolver singleAgentSolver;
private ISolver groupSolver;
private Plan plan;

ClassificationXGBoostModel selectionModel;


public IndependenceDetectionAgentsGroup(ProblemInstance instance, AgentState[] allAgentsState, ISolver singleAgentSolver, ISolver groupSolver)
{
this.allAgentsState = allAgentsState;
this.instance = instance.Subproblem(allAgentsState);
this.singleAgentSolver = singleAgentSolver;
this.groupSolver = groupSolver;


var model_path = "C:\\Users\\omri\\Projects\\study\\2019semB\\agentsPlanning\\MAPF\\classification\\testing-clf.xgb";

//selectionModel = new ClassificationXGBoostLearner();
this.selectionModel = ClassificationXGBoostModel.Load(model_path);
}

/// <summary>
Expand All @@ -523,8 +555,110 @@ public bool Solve(Run runner)
ISolver relevantSolver = this.groupSolver;
if (this.allAgentsState.Length == 1)
relevantSolver = this.singleAgentSolver; // TODO: Consider using CBS's root trick to really get single agent paths fast. Though it won't respect illegal moves and such.

relevantSolver.Setup(this.instance, runner);
bool solved = relevantSolver.Solve();
this.solutionCost = relevantSolver.GetSolutionCost();
if (solved == false)
return false;

// Store the plan found by the solver
this.plan = relevantSolver.GetPlan();
this.expanded = relevantSolver.GetExpanded();
this.generated = relevantSolver.GetGenerated();
this.depthOfSolution = relevantSolver.GetSolutionDepth();

// Clear memory
relevantSolver.Clear();
return true;
}


public string solverNameByIndex(double solverIndex)
{
switch (solverIndex)
{
case 0:
return "EPEA";
case 1:
return "MA-CBS";
case 2:
return "ICTS";
case 3:
return "ASTAR";
case 4:
return "CBS";
case 5:
return "CBS-H";
default:
return "WHAT?";
}
}

public ISolver solverByIndex(double solverIndex)
{
var simple = new SumIndividualCosts();
var epea = new EPEA_Star(simple);
var astar = new A_Star(simple);
var macbs = new CBS(astar, epea, 10);
var icts = new CostTreeSearchSolverOldMatching(3);
var cbs = new CBS(astar, epea);
var mvc_for_cbs = new MvcHeuristicForCbs();

var cbsh = new CBS(astar, epea,
mergeThreshold: -1,
CBS.BypassStrategy.FIRST_FIT_LOOKAHEAD,
doMalte: false,
CBS.ConflictChoice.CARDINAL_MDD,
mvc_for_cbs,
disableTieBreakingByMinOpsEstimate: true,
lookaheadMaxExpansions: 1,
mergeCausesRestart: true,
replanSameCostWithMdd: false,
cacheMdds: false,
useOldCost: false,
useCAT: true);

switch (solverIndex)
{
case 0:
return epea;
case 1:
return macbs;
case 2:
return icts;
case 3:
return astar;
case 4:
return cbs;
case 5:
return cbsh;
default:
return null;
}
}

/// <summary>
/// Solve the group of agents together.
/// </summary>
/// <param name="runner"></param>
/// <returns>true if optimal solution for the group of agents were found, false otherwise</returns>
public bool SolveWithSelection(Run runner)
{
ISolver relevantSolver = this.groupSolver;
if (this.allAgentsState.Length == 1)
relevantSolver = this.singleAgentSolver; // TODO: Consider using CBS's root trick to really get single agent paths fast. Though it won't respect illegal moves and such.
var watch = System.Diagnostics.Stopwatch.StartNew();
// the code that you want to measure comes here
var pred = this.selectionModel.Predict(instance.ml_features.ToArray());
watch.Stop();
var elapsedMs = watch.ElapsedMilliseconds;
Console.WriteLine("Selection time: {0}", elapsedMs);

Console.WriteLine(solverNameByIndex(pred));
relevantSolver = solverByIndex(pred);
relevantSolver.Setup(this.instance, runner);
//this.sele
bool solved = relevantSolver.Solve();
this.solutionCost = relevantSolver.GetSolutionCost();
if (solved == false)
Expand All @@ -541,6 +675,7 @@ public bool Solve(Run runner)
return true;
}


/// <summary>
/// Returns the plan for the group of agents. This is a collection of Moves for every time step until all the agents reach their goal.
/// </summary>
Expand Down Expand Up @@ -600,7 +735,7 @@ public override int GetHashCode()
/// <param name="plan"></param>
/// <param name="runner"></param>
/// <returns></returns>
public bool ReplanUnderConstraints(Plan plan, Run runner)
public bool ReplanUnderConstraints(Plan plan, Run runner, Boolean withSelection)
{
int oldCost = this.solutionCost;
Plan oldPlan = this.plan;
Expand All @@ -609,8 +744,16 @@ public bool ReplanUnderConstraints(Plan plan, Run runner)

this.instance.parameters[IndependenceDetection.ILLEGAL_MOVES_KEY] = reserved;
this.instance.parameters[IndependenceDetection.MAXIMUM_COST_KEY] = solutionCost; // TODO: add IIndependenceDetectionSolver to ISolver.cs with a Setup method that takes a maxCost
bool success = this.Solve(runner);
this.instance.parameters.Remove(IndependenceDetection.ILLEGAL_MOVES_KEY);
bool success;
if (withSelection)
{
success = this.SolveWithSelection(runner);
}
else
{
success = this.Solve(runner);
}
this.instance.parameters.Remove(IndependenceDetection.ILLEGAL_MOVES_KEY);
this.instance.parameters.Remove(IndependenceDetection.MAXIMUM_COST_KEY);
if (success == false)
{
Expand Down
33 changes: 26 additions & 7 deletions ProblemInstance.cs
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,15 @@ public class ProblemInstance
/// </summary>
public bool[][] grid;

// ml_features will contain the features to predict according to them.
// The order of ml_features is: GridRows, GridColumns, NumOfAgents, NumOfObstacles,
// BranchingFactor, ObstacleDensity, AvgDistanceToGoal,
// MaxDistanceToGoal, MinDistanceToGoal, AvgStartDistances, AvgGoalDistances
// PointsAtSPRatio, Sparsity


public List<double> ml_features;

/// <summary>
/// We keep a reference to the array of agents in the original problem.
/// This will only change when IndependenceDetection's algorithm determines in another
Expand Down Expand Up @@ -147,7 +156,7 @@ public void Init(AgentState[] agentStartStates, bool[][] grid, int nObstacles=-1
distanceBetweenAgentGoals = new int[agents.Length, agents.Length];
distanceBetweenAgentStartPoints = new int[agents.Length, agents.Length];


ml_features = new List<double>();
}

/// <summary>
Expand Down Expand Up @@ -481,12 +490,12 @@ public static ProblemInstance ImportFromScenFile(string fileName)
line = input.ReadLine();
lineParts = line.Split(' ');
Debug.Assert(lineParts.Length == 2);
Debug.Assert(lineParts[0].Equals("height"));
//Debug.Assert(lineParts[0].Equals("height"));
maxY = int.Parse(lineParts[1]); // The height is the number of rows
line = input.ReadLine();
lineParts = line.Split(' ');
Debug.Assert(lineParts.Length == 2);
Debug.Assert(lineParts[0].Equals("width"));
//Debug.Assert(lineParts[0].Equals("width"));
maxX = int.Parse(lineParts[1]); // The width is the number of columns
grid = new bool[maxY][];

Expand Down Expand Up @@ -599,11 +608,13 @@ public static ProblemInstance ImportFromScenFile(string fileName)
}
Console.WriteLine("Found {0} agents", lines.Count);

for (int i = 2; i < lines.Count; i++)

for (int i = 2; i < lines.Count+1; i++)
{
agentNum = 0;
stateList = new List<AgentState>();
var rand_lines = lines.AsEnumerable().OrderBy(n => Guid.NewGuid()).Take(i).Cast<String>().ToList();
//var rand_lines = lines.AsEnumerable().OrderBy(n => Guid.NewGuid()).Take(i).Cast<String>().ToList();
var rand_lines = lines.Take(i);
if (File.Exists(agents_fileName))
{
bool already_executed = File.ReadLines(agents_fileName)
Expand All @@ -615,7 +626,7 @@ public static ProblemInstance ImportFromScenFile(string fileName)
}

}

var agents_writer = new StreamWriter(agents_fileName, true);

agents_writer.WriteLine("NumAgents: {0}", i);
Expand All @@ -627,7 +638,7 @@ public static ProblemInstance ImportFromScenFile(string fileName)
mapRows = int.Parse(lineParts[2]);
Debug.Assert(mapRows == maxX);
mapCols = int.Parse(lineParts[3]);
Debug.Assert(mapRows == maxY);
Debug.Assert(mapCols == maxY);

startY = int.Parse(lineParts[4]);
startX = int.Parse(lineParts[5]);
Expand All @@ -638,8 +649,11 @@ public static ProblemInstance ImportFromScenFile(string fileName)
state = new AgentState(startX, startY, agent);
stateList.Add(state);
agents_writer.WriteLine("{0},{1},{2},{3}", startX, startY, goalX, goalY);

agentNum++;
}
agents_writer.Close();
agents_writer = new StreamWriter(agents_fileName, true);
bool resultsFileExisted = File.Exists(Program.RESULTS_FILE_NAME);
runner.OpenResultsFile(Program.RESULTS_FILE_NAME);

Expand Down Expand Up @@ -852,6 +866,11 @@ public static ProblemInstance Import(string filePath, string mapFilePath = null)
}
}

public void AddFeature(double feature)
{
ml_features.Append(feature);
}

/// <summary>
/// Exports a problem instance to a file
/// </summary>
Expand Down
Loading

0 comments on commit e30ca12

Please sign in to comment.