Exemplo n.º 1
0
        public static ProblemInstance ImportFromScenFile(string fileName)
        {
            string fileNameWithoutExtension = Path.GetFileNameWithoutExtension(fileName);
            int    instanceId = int.Parse(fileNameWithoutExtension.Split('-').Last());
            //string scen_type = "";
            string mapfileName = "";
            int    scen_type_seperator_index = 0;

            if (fileNameWithoutExtension.Split('-')[0].Contains("empty")) //empty map
            {
                scen_type_seperator_index = 2;
            }
            else if (fileNameWithoutExtension.Split('-')[0].Contains("maze") || fileNameWithoutExtension.Split('-')[0].Contains("random") ||
                     fileNameWithoutExtension.Split('-')[0].Contains("room"))
            {
                scen_type_seperator_index = 3;
            }
            else if (fileNameWithoutExtension.Split('-')[0].Contains("warehouse"))
            {
                scen_type_seperator_index = 5;
            }
            mapfileName = fileNameWithoutExtension.Substring(0, length: IndexOfNth(fileNameWithoutExtension, "-", scen_type_seperator_index));

            Console.WriteLine(mapfileName);
            string mapFilePath = Path.Combine(Path.GetDirectoryName(fileName), @"..", @"..", "maps", mapfileName + ".map");

            Console.WriteLine("map file path {0} {1}", Path.GetDirectoryName(fileName), mapFilePath);
            bool[][] grid;
            string   line;

            string[] lineParts;
            int      maxX;
            int      maxY;

            using (TextReader input = new StreamReader(mapFilePath))
            {
                // Read grid dimensions
                line = input.ReadLine();
                Debug.Assert(line.StartsWith("type octile"));
                line      = input.ReadLine();
                lineParts = line.Split(' ');
                Trace.Assert(lineParts.Length == 2);
                //Trace.Assert(lineParts[0].Equals("height"));
                maxY      = int.Parse(lineParts[1]); // The height is the number of rows
                line      = input.ReadLine();
                lineParts = line.Split(' ');
                Trace.Assert(lineParts.Length == 2);
                //Trace.Assert(lineParts[0].Equals("width"));
                maxX = int.Parse(lineParts[1]);  // The width is the number of columns
                grid = new bool[maxY][];

                line = input.ReadLine();
                Trace.Assert(line.StartsWith("map"));

                char cell;
                // Read grid
                for (int i = 0; i < maxY; i++)
                {
                    grid[i] = new bool[maxX];
                    line    = input.ReadLine();
                    for (int j = 0; j < maxX; j++)
                    {
                        cell = line[j];
                        if (cell == '@' || cell == 'O' || cell == 'T' || cell == 'W' /* Water isn't traversable from land */)
                        {
                            grid[i][j] = true;
                        }
                        else
                        {
                            grid[i][j] = false;
                        }
                    }
                }
            }

            List <AgentState> stateList = new List <AgentState>();
            Run runner = new Run();

            Console.WriteLine("Starting scen file {0}", fileName);

            var rnd = new Random();
            var filename_without_extension = fileName.Substring(0, fileName.IndexOf(".scen"));
            var agents_fileName            = filename_without_extension + ".agents";
            var plan_fileName = filename_without_extension + ".plans";

            //if (File.Exists(agents_fileName))
            //    File.Delete(agents_fileName);
            using (TextReader input = new StreamReader(fileName))
            {
                // Read the format version number
                line      = input.ReadLine();
                lineParts = line.Split(' ');
                Debug.Assert(lineParts[0].Equals("version"));
                int version = int.Parse(lineParts[1]);
                Debug.Assert(version == 1, "Only version 1 is currently supported");

                // Read the agents' start and goal states
                AgentState      state;
                Agent           agent;
                int             agentNum = 0;
                int             block;
                int             goalX;
                int             goalY;
                int             startX;
                int             startY;
                string          mapFileName;
                int             mapRows;
                int             mapCols;
                double          optimalCost; // Assuming diagonal moves are allowed and cost sqrt(2)
                List <string>   lines    = new List <string>();
                ProblemInstance instance = new ProblemInstance();

                while (true)
                {
                    line = input.ReadLine();
                    if (string.IsNullOrWhiteSpace(line))
                    {
                        break;
                    }
                    lines.Add(line);
                }

                Console.WriteLine("Found {0} agents", lines.Count);

                for (int i = 2; i < lines.Count + 1; i++)
                {
                    agentNum = 0;
                    if (i > 1000)
                    {
                        break;
                    }
                    stateList = new List <AgentState>();
                    //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)
                                                .Any(curr_line => curr_line.Contains("NumAgents: " + i));
                        if (already_executed)
                        {
                            Console.WriteLine("Skipping already solved problem with {0} agents", i);
                            continue;
                        }
                    }

                    var agents_writer = new StreamWriter(agents_fileName, true);

                    agents_writer.WriteLine("NumAgents: {0}", i);
                    foreach (String rand_line in rand_lines)
                    {
                        lineParts   = rand_line.Split('\t');
                        block       = int.Parse(lineParts[0]);
                        mapFileName = lineParts[1];
                        mapRows     = int.Parse(lineParts[2]);
                        Debug.Assert(mapRows == maxX);
                        mapCols = int.Parse(lineParts[3]);
                        Debug.Assert(mapCols == maxY);

                        startY      = int.Parse(lineParts[4]);
                        startX      = int.Parse(lineParts[5]);
                        goalY       = int.Parse(lineParts[6]);
                        goalX       = int.Parse(lineParts[7]);
                        optimalCost = double.Parse(lineParts[8]);
                        agent       = new Agent(goalX, goalY, agentNum);
                        state       = new AgentState(startX, startY, agent);
                        stateList.Add(state);
                        agents_writer.WriteLine("{0},{1},{2},{3}", startX, startY, goalX, goalY);

                        agentNum++;
                    }
                    agents_writer.Close();
                    bool resultsFileExisted = File.Exists(Program.RESULTS_FILE_NAME);
                    runner.OpenResultsFile(Program.RESULTS_FILE_NAME);

                    if (resultsFileExisted == false)
                    {
                        runner.PrintResultsFileHeader();
                    }

                    runner.CloseResultsFile();
                    agents_writer = new StreamWriter(agents_fileName, true);

                    Console.WriteLine("Starting scen with {0} agents", i);
                    // Generate the problem instance
                    /////------------- Generate SAT file from scen+map
                    var scen_files_dir   = Directory.GetParent(filename_without_extension);
                    var sat_mpf_fileName = Path.Combine(scen_files_dir.ToString(), "sat_files", Path.GetFileName(filename_without_extension)
                                                        + String.Format("_a_{0}.mpf", i));

                    /////------------- Generate SAT file from scen+map
                    if (instance.agents == null) //Should init the ProblemInstance
                    {
                        instance.Init(stateList.ToArray(), grid);
                        instance.ComputeSingleAgentShortestPaths();
                    }
                    else
                    {
                        instance.AddSingleAgent(stateList.Last());
                    }
                    var lazyCbsAgentsFileName = Path.Combine(scen_files_dir.ToString(), "lazycbs", Path.GetFileName(filename_without_extension)
                                                             + String.Format("_a_{0}.agents", i));
                    string lazyCbsMapFileName = Path.Combine(Path.GetDirectoryName(fileName), @"..", @"..", "maps", mapfileName + ".map.ecbs");

                    instance.parameters[ProblemInstance.SAT_FILE_NAME] = sat_mpf_fileName;
                    instance.parameters[ProblemInstance.MAP_FILE_PATH] = mapFilePath;
                    instance.parameters[ProblemInstance.SCEN_FILE]     = fileName;

                    instance.parameters[ProblemInstance.LAZY_CBS_AGENTS_FILE_NAME] = lazyCbsAgentsFileName;
                    instance.parameters[ProblemInstance.LAZY_CBS_MAP_FILE_NAME]    = lazyCbsMapFileName;
                    instance.parameters[ProblemInstance.SCEN_DIR] = scen_files_dir;
                    instance.parameters[ProblemInstance.N_AGENTS] = i;
                    instance.instanceId = instanceId;
                    instance.parameters[ProblemInstance.GRID_NAME_KEY]     = mapfileName;
                    instance.parameters[ProblemInstance.INSTANCE_NAME_KEY] = fileNameWithoutExtension + ".scen";
                    runner.OpenResultsFile(Program.RESULTS_FILE_NAME);
                    Boolean solved = runner.SolveGivenProblem(instance, plan_fileName);
                    runner.CloseResultsFile();
                    agents_writer.Close();

                    if (!solved)
                    {
                        break;
                    }
                }
            }
            return(null);
        }
Exemplo n.º 2
0
        /// <summary>
        /// Imports a problem instance from a given file
        /// </summary>
        /// <param name="filePath"></param>
        /// <param name="mapFilePath"></param>
        /// <returns></returns>
        public static ProblemInstance Import(string filePath, string mapFilePath = null)
        {
            if (filePath.EndsWith(".agents"))
            {
                string fileNameWithoutExtension = Path.GetFileNameWithoutExtension(filePath);
                int    instanceId = 0;
                string mapfileNameWithoutExtension;
                if (mapFilePath == null)
                {
                    mapfileNameWithoutExtension = fileNameWithoutExtension.Substring(0, length: fileNameWithoutExtension.LastIndexOf('_')) + ".map";  // Passing a length parameter is like specifying a non-inclusive end index
                    mapFilePath = Path.Combine(Path.GetDirectoryName(filePath), "..", "maps", mapfileNameWithoutExtension);
                    instanceId  = int.Parse(filePath.Split('_').Last());
                }
                else
                {
                    mapfileNameWithoutExtension = Path.GetFileNameWithoutExtension(mapFilePath);
                }

                bool[][] grid;
                string   line;
                string[] lineParts;
                using (TextReader input = new StreamReader(mapFilePath))
                {
                    // Read grid dimensions
                    line      = input.ReadLine();
                    lineParts = line.Split(',');
                    int maxX = int.Parse(lineParts[0]);
                    int maxY = int.Parse(lineParts[1]);
                    grid = new bool[maxX][];
                    char cell;
                    // Read grid
                    for (int i = 0; i < maxX; i++)
                    {
                        grid[i] = new bool[maxY];
                        line    = input.ReadLine();
                        for (int j = 0; j < maxY; j++)
                        {
                            cell = line.ElementAt(j);
                            if (cell == '1')
                            {
                                grid[i][j] = true;
                            }
                            else
                            {
                                grid[i][j] = false;
                            }
                        }
                    }
                }

                AgentState[] states;
                using (TextReader input = new StreamReader(filePath))
                {
                    // Read the number of agents
                    line = input.ReadLine();
                    int numOfAgents = int.Parse(line);

                    // Read the agents' start and goal states
                    states = new AgentState[numOfAgents];
                    AgentState state;
                    Agent      agent;
                    int        goalX;
                    int        goalY;
                    int        startX;
                    int        startY;
                    for (int i = 0; i < numOfAgents; i++)
                    {
                        line      = input.ReadLine();
                        lineParts = line.Split(EXPORT_DELIMITER);
                        goalX     = int.Parse(lineParts[0]);
                        goalY     = int.Parse(lineParts[1]);
                        startX    = int.Parse(lineParts[2]);
                        startY    = int.Parse(lineParts[3]);
                        agent     = new Agent(goalX, goalY, i);
                        state     = new AgentState(startX, startY, agent);
                        states[i] = state;
                    }
                }

                // Generate the problem instance
                ProblemInstance instance = new ProblemInstance();
                instance.Init(states, grid);
                instance.instanceId = instanceId;
                instance.parameters[ProblemInstance.GRID_NAME_KEY]     = mapfileNameWithoutExtension;
                instance.parameters[ProblemInstance.INSTANCE_NAME_KEY] = fileNameWithoutExtension + ".agents";
                instance.ComputeSingleAgentShortestPaths();
                return(instance);
            }
            else if (filePath.EndsWith(".scen"))
            {
                return(ImportFromScenFile(filePath));
            }
            else  // Combined map and scenario, no suffix
            {
                using (TextReader input = new StreamReader(filePath))
                {
                    string[] lineParts;
                    string   line;
                    int      instanceId = 0;
                    string   gridName   = "Random Grid"; // The default

                    line = input.ReadLine();
                    if (line.StartsWith("Grid:") == false)
                    {
                        lineParts  = line.Split(',');
                        instanceId = int.Parse(lineParts[0]);
                        if (lineParts.Length > 1)
                        {
                            gridName = lineParts[1];
                        }
                        line = input.ReadLine();
                    }

                    // First/second line is Grid:
                    Debug.Assert(line.StartsWith("Grid:"));

                    // Read grid dimensions
                    line      = input.ReadLine();
                    lineParts = line.Split(',');
                    int      maxX = int.Parse(lineParts[0]);
                    int      maxY = int.Parse(lineParts[1]);
                    bool[][] grid = new bool[maxX][];
                    // Read grid
                    char cell;
                    for (int i = 0; i < maxX; i++)
                    {
                        grid[i] = new bool[maxY];
                        line    = input.ReadLine();
                        for (int j = 0; j < maxY; j++)
                        {
                            cell = line.ElementAt(j);
                            if (cell == '@' || cell == 'O' || cell == 'T' || cell == 'W' /* Water isn't traversable from land */)
                            {
                                grid[i][j] = true;
                            }
                            else
                            {
                                grid[i][j] = false;
                            }
                        }
                    }

                    // Next line is Agents:
                    line = input.ReadLine();
                    Debug.Assert(line.StartsWith("Agents:"));

                    // Read the number of agents
                    line = input.ReadLine();
                    int numOfAgents = int.Parse(line);

                    // Read the agents' start and goal states
                    AgentState[] states = new AgentState[numOfAgents];
                    AgentState   state;
                    Agent        agent;
                    int          agentNum;
                    int          goalX;
                    int          goalY;
                    int          startX;
                    int          startY;
                    for (int i = 0; i < numOfAgents; i++)
                    {
                        line      = input.ReadLine();
                        lineParts = line.Split(EXPORT_DELIMITER);
                        agentNum  = int.Parse(lineParts[0]);
                        goalX     = int.Parse(lineParts[1]);
                        goalY     = int.Parse(lineParts[2]);
                        startX    = int.Parse(lineParts[3]);
                        startY    = int.Parse(lineParts[4]);
                        agent     = new Agent(goalX, goalY, agentNum);
                        state     = new AgentState(startX, startY, agent);
                        states[i] = state;
                    }

                    // Generate the problem instance
                    ProblemInstance instance = new ProblemInstance();
                    instance.Init(states, grid);
                    instance.instanceId = instanceId;
                    instance.parameters[ProblemInstance.GRID_NAME_KEY]     = gridName;
                    instance.parameters[ProblemInstance.INSTANCE_NAME_KEY] = Path.GetFileName(filePath);
                    instance.ComputeSingleAgentShortestPaths();
                    return(instance);
                }
            }
        }
Exemplo n.º 3
0
        /// <summary>
        /// Imports a problem instance from a given file
        /// </summary>
        /// <param name="filePath"></param>
        /// <param name="mapFilePath"></param>
        /// <returns></returns>
        public static ProblemInstance Import(string filePath, string mapFilePath = null)
        {
            if (filePath.EndsWith(".agents"))
            {
                string fileNameWithoutExtension = Path.GetFileNameWithoutExtension(filePath);
                int    instanceId = 0;
                try
                {
                    instanceId = int.Parse(filePath.Split('_').Last());
                }
                catch (Exception) {}
                string mapfileNameWithoutExtension;
                if (mapFilePath == null)
                {
                    mapfileNameWithoutExtension = fileNameWithoutExtension.Substring(0, length: fileNameWithoutExtension.LastIndexOf('_')) + ".map";  // Passing a length parameter is like specifying a non-inclusive end index
                    mapFilePath = Path.Combine(Path.GetDirectoryName(filePath), "..", "maps", mapfileNameWithoutExtension);
                }
                else
                {
                    mapfileNameWithoutExtension = Path.GetFileNameWithoutExtension(mapFilePath);
                }

                bool[][] grid = readMapFile(mapFilePath);

                string       line;
                string[]     lineParts;
                AgentState[] states;
                using (TextReader input = new StreamReader(filePath))
                {
                    // Read the number of agents
                    line = input.ReadLine();
                    int numOfAgents = int.Parse(line);

                    // Read the agents' start and goal states
                    states = new AgentState[numOfAgents];
                    AgentState state;
                    Agent      agent;
                    int        goalX;
                    int        goalY;
                    int        startX;
                    int        startY;
                    for (int i = 0; i < numOfAgents; i++)
                    {
                        line      = input.ReadLine();
                        lineParts = line.Split(EXPORT_DELIMITER);
                        goalX     = int.Parse(lineParts[0]);
                        goalY     = int.Parse(lineParts[1]);
                        startX    = int.Parse(lineParts[2]);
                        startY    = int.Parse(lineParts[3]);
                        agent     = new Agent(goalX, goalY, i);
                        state     = new AgentState(startX, startY, agent);
                        states[i] = state;
                    }
                }

                // Generate the problem instance
                ProblemInstance instance = new ProblemInstance();
                instance.Init(states, grid);
                instance.instanceId = instanceId;
                instance.parameters[ProblemInstance.GRID_NAME_KEY]     = mapfileNameWithoutExtension;
                instance.parameters[ProblemInstance.INSTANCE_NAME_KEY] = fileNameWithoutExtension + ".agents";
                instance.ComputeSingleAgentShortestPaths();
                return(instance);
            }
            else if (filePath.EndsWith(".scen"))
            {
                string fileNameWithoutExtension = Path.GetFileNameWithoutExtension(filePath);
                int    instanceId  = int.Parse(fileNameWithoutExtension.Split('-').Last());
                string mapfileName = fileNameWithoutExtension.Substring(0, length: fileNameWithoutExtension.LastIndexOf('-'));  // Passing a length parameter is like specifying a non-inclusive end index
                if (mapFilePath == null)
                {
                    mapFilePath = Path.Combine(Path.GetDirectoryName(filePath), "..", "..", "..", "maps", mapfileName);
                }

                bool[][] grid = readMapFile(mapFilePath);

                string            line;
                string[]          lineParts;
                List <AgentState> stateList = new List <AgentState>();
                using (TextReader input = new StreamReader(filePath))
                {
                    // Read the format version number
                    line      = input.ReadLine();
                    lineParts = line.Split(' ');
                    Trace.Assert(lineParts[0].Equals("version"));
                    int version = int.Parse(lineParts[1]);
                    Trace.Assert(version == 1, "Only version 1 is currently supported");

                    // Read the agents' start and goal states
                    AgentState state;
                    Agent      agent;
                    int        agentNum = 0;
                    int        block;
                    int        goalX;
                    int        goalY;
                    int        startX;
                    int        startY;
                    string     mapFileName;
                    int        mapRows;
                    int        mapCols;
                    double     optimalCost; // Assuming diagonal moves are allowed and cost sqrt(2)
                    while (true)
                    {
                        line = input.ReadLine();
                        if (string.IsNullOrWhiteSpace(line))
                        {
                            break;
                        }
                        lineParts   = line.Split('\t');
                        block       = int.Parse(lineParts[0]);
                        mapFileName = lineParts[1];
                        mapRows     = int.Parse(lineParts[2]);
                        Trace.Assert(mapRows == grid.GetLength(0));
                        mapCols = int.Parse(lineParts[3]);
                        Trace.Assert(mapCols == grid.GetLength(1));

                        startY      = int.Parse(lineParts[4]);
                        startX      = int.Parse(lineParts[5]);
                        goalY       = int.Parse(lineParts[6]);
                        goalX       = int.Parse(lineParts[7]);
                        optimalCost = double.Parse(lineParts[8]);
                        agent       = new Agent(goalX, goalY, agentNum);
                        state       = new AgentState(startX, startY, agent);
                        stateList.Add(state);
                        agentNum++;
                    }
                }

                // Generate the problem instance
                ProblemInstance instance = new ProblemInstance();
                instance.Init(stateList.ToArray(), grid);
                instance.instanceId = instanceId;
                instance.parameters[ProblemInstance.GRID_NAME_KEY]     = mapfileName;
                instance.parameters[ProblemInstance.INSTANCE_NAME_KEY] = fileNameWithoutExtension + ".scen";
                instance.ComputeSingleAgentShortestPaths();
                return(instance);
            }
            else  // Combined map and scenario, no suffix
            {
                using (TextReader input = new StreamReader(filePath))
                {
                    string[] lineParts;
                    string   line;
                    int      instanceId = 0;
                    string   gridName   = "Random Grid"; // The default

                    line = input.ReadLine();
                    if (line.StartsWith("Grid:") == false)
                    {
                        lineParts  = line.Split(',');
                        instanceId = int.Parse(lineParts[0]);
                        if (lineParts.Length > 1)
                        {
                            gridName = lineParts[1];
                        }
                        line = input.ReadLine();
                    }

                    // First/second line is Grid:
                    Trace.Assert(line.StartsWith("Grid:"));

                    // Read grid dimensions
                    line      = input.ReadLine();
                    lineParts = line.Split(',');
                    int      maxX = int.Parse(lineParts[0]);
                    int      maxY = int.Parse(lineParts[1]);
                    bool[][] grid = new bool[maxX][];
                    // Read grid
                    char cell;
                    for (int i = 0; i < maxX; i++)
                    {
                        grid[i] = new bool[maxY];
                        line    = input.ReadLine();
                        for (int j = 0; j < maxY; j++)
                        {
                            cell = line[j];
                            if (cell == '@' || cell == 'O' || cell == 'T' || cell == 'W' /* Water isn't traversable from land */)
                            {
                                grid[i][j] = true;
                            }
                            else
                            {
                                grid[i][j] = false;
                            }
                        }
                    }

                    // Next line is Agents:
                    line = input.ReadLine();
                    Trace.Assert(line.StartsWith("Agents:"));

                    // Read the number of agents
                    line = input.ReadLine();
                    int numOfAgents = int.Parse(line);

                    // Read the agents' start and goal states
                    AgentState[] states = new AgentState[numOfAgents];
                    AgentState   state;
                    Agent        agent;
                    int          agentNum;
                    int          goalX;
                    int          goalY;
                    int          startX;
                    int          startY;
                    for (int i = 0; i < numOfAgents; i++)
                    {
                        line      = input.ReadLine();
                        lineParts = line.Split(EXPORT_DELIMITER);
                        agentNum  = int.Parse(lineParts[0]);
                        goalX     = int.Parse(lineParts[1]);
                        goalY     = int.Parse(lineParts[2]);
                        startX    = int.Parse(lineParts[3]);
                        startY    = int.Parse(lineParts[4]);
                        agent     = new Agent(goalX, goalY, agentNum);
                        state     = new AgentState(startX, startY, agent);
                        states[i] = state;
                    }

                    // Generate the problem instance
                    ProblemInstance instance = new ProblemInstance();
                    instance.Init(states, grid);
                    instance.instanceId = instanceId;
                    instance.parameters[ProblemInstance.GRID_NAME_KEY]     = gridName;
                    instance.parameters[ProblemInstance.INSTANCE_NAME_KEY] = Path.GetFileName(filePath);
                    instance.ComputeSingleAgentShortestPaths();
                    return(instance);
                }
            }
        }