You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

320 lines
16 KiB

10 months ago
  1. #include "Grid.h"
  2. #include <boost/algorithm/string/find.hpp>
  3. #include <algorithm>
  4. prism::ModelType GridOptions::getModelType() const
  5. {
  6. if (agentsWithView.size() > 1) {
  7. return prism::ModelType::SMG;
  8. }
  9. return prism::ModelType::MDP;
  10. }
  11. Grid::Grid(cells gridCells, cells background, const GridOptions &gridOptions, const std::map<coordinates, float> &stateRewards, const double faultyProbability)
  12. : allGridCells(gridCells), background(background), gridOptions(gridOptions), stateRewards(stateRewards), faultyProbability(faultyProbability)
  13. {
  14. cell max = allGridCells.at(allGridCells.size() - 1);
  15. maxBoundaries = std::make_pair(max.row - 1, max.column - 1);
  16. std::copy_if(gridCells.begin(), gridCells.end(), std::back_inserter(walls), [](cell c) { return c.type == Type::Wall; });
  17. std::copy_if(gridCells.begin(), gridCells.end(), std::back_inserter(lava), [](cell c) { return c.type == Type::Lava; });
  18. std::copy_if(gridCells.begin(), gridCells.end(), std::back_inserter(floor), [](cell c) { return c.type == Type::Floor; }); // TODO Add agent cells to floor
  19. std::copy_if(background.begin(), background.end(), std::back_inserter(slipperyNorth), [](cell c) { return c.type == Type::SlipperyNorth; });
  20. std::copy_if(background.begin(), background.end(), std::back_inserter(slipperyEast), [](cell c) { return c.type == Type::SlipperyEast; });
  21. std::copy_if(background.begin(), background.end(), std::back_inserter(slipperySouth), [](cell c) { return c.type == Type::SlipperySouth; });
  22. std::copy_if(background.begin(), background.end(), std::back_inserter(slipperyWest), [](cell c) { return c.type == Type::SlipperyWest; });
  23. std::copy_if(gridCells.begin(), gridCells.end(), std::back_inserter(lockedDoors), [](cell c) { return c.type == Type::LockedDoor; });
  24. std::copy_if(gridCells.begin(), gridCells.end(), std::back_inserter(unlockedDoors), [](cell c) { return c.type == Type::Door; });
  25. std::copy_if(gridCells.begin(), gridCells.end(), std::back_inserter(goals), [](cell c) { return c.type == Type::Goal; });
  26. std::copy_if(gridCells.begin(), gridCells.end(), std::back_inserter(keys), [](cell c) { return c.type == Type::Key; });
  27. std::copy_if(gridCells.begin(), gridCells.end(), std::back_inserter(boxes), [](cell c) { return c.type == Type::Box; });
  28. std::copy_if(gridCells.begin(), gridCells.end(), std::back_inserter(balls), [](cell c) { return c.type == Type::Ball; });
  29. std::copy_if(gridCells.begin(), gridCells.end(), std::back_inserter(adversaries), [](cell c) { return c.type == Type::Adversary; });
  30. agent = *std::find_if(gridCells.begin(), gridCells.end(), [](cell c) { return c.type == Type::Agent; });
  31. floor.push_back(agent);
  32. agentNameAndPositionMap.insert({ "Agent", agent.getCoordinates() });
  33. for(auto const& adversary : adversaries) {
  34. std::string color = adversary.getColor();
  35. color.at(0) = std::toupper(color.at(0));
  36. try {
  37. if(gridOptions.agentsToBeConsidered.size() != 0 && std::find(gridOptions.agentsToBeConsidered.begin(), gridOptions.agentsToBeConsidered.end(), color) == gridOptions.agentsToBeConsidered.end()) continue;
  38. auto success = agentNameAndPositionMap.insert({ color, adversary.getCoordinates() });
  39. floor.push_back(adversary);
  40. if(!success.second) {
  41. throw std::logic_error("Agent with " + color + " already present\n");
  42. }
  43. } catch(const std::logic_error& e) {
  44. std::cerr << "Expected agents colors to be different. Agent with color : '" << color << "' already present." << std::endl;
  45. throw;
  46. }
  47. }
  48. for(auto const& key : keys) {
  49. std::string color = key.getColor();
  50. try {
  51. auto success = keyNameAndPositionMap.insert({color, key.getCoordinates() });
  52. if (!success.second) {
  53. throw std::logic_error("Multiple keys with same color not supported " + color + "\n");
  54. }
  55. } catch(const std::logic_error& e) {
  56. std::cerr << "Expected key colors to be different. Key with color : '" << color << "' already present." << std::endl;
  57. throw;
  58. }
  59. }
  60. for(auto const& color : allColors) {
  61. cells cellsOfColor;
  62. std::copy_if(background.begin(), background.end(), std::back_inserter(cellsOfColor), [&color](cell c) {
  63. return c.type == Type::Floor && c.color == color;
  64. });
  65. if(cellsOfColor.size() > 0) {
  66. backgroundTiles.emplace(color, cellsOfColor);
  67. }
  68. }
  69. }
  70. std::ostream& operator<<(std::ostream& os, const Grid& grid) {
  71. int lastRow = 1;
  72. for(auto const& cell : grid.allGridCells) {
  73. if(lastRow != cell.row)
  74. os << std::endl;
  75. os << static_cast<char>(cell.type) << static_cast<char>(cell.color);
  76. lastRow = cell.row;
  77. }
  78. return os;
  79. }
  80. cells Grid::getGridCells() {
  81. return allGridCells;
  82. }
  83. bool Grid::isBlocked(coordinates p) {
  84. return isWall(p); //|| isLockedDoor(p) || isKey(p);
  85. }
  86. bool Grid::isWall(coordinates p) {
  87. return std::find_if(walls.begin(), walls.end(),
  88. [p](cell cell) {
  89. return cell.row == p.first && cell.column == p.second;
  90. }) != walls.end();
  91. }
  92. bool Grid::isLockedDoor(coordinates p) {
  93. return std::find_if(lockedDoors.begin(), lockedDoors.end(),
  94. [p](cell cell) {
  95. return cell.row == p.first && cell.column == p.second;
  96. }) != lockedDoors.end();
  97. }
  98. bool Grid::isUnlockedDoor(coordinates p) {
  99. return std::find_if(unlockedDoors.begin(), unlockedDoors.end(),
  100. [p](cell cell) {
  101. return cell.row == p.first && cell.column == p.second;
  102. }) != unlockedDoors.end();
  103. }
  104. bool Grid::isKey(coordinates p) {
  105. return std::find_if(keys.begin(), keys.end(),
  106. [p](cell cell) {
  107. return cell.row == p.first && cell.column == p.second;
  108. }) != keys.end();
  109. }
  110. bool Grid::isBox(coordinates p) {
  111. return std::find_if(boxes.begin(), boxes.end(),
  112. [p](cell cell) {
  113. return cell.row == p.first && cell.column == p.second;
  114. }) != boxes.end();
  115. }
  116. void Grid::applyOverwrites(std::string& str, std::vector<Configuration>& configuration) {
  117. for (auto& config : configuration) {
  118. if (!config.overwrite_) {
  119. continue;
  120. }
  121. size_t start_pos;
  122. if (config.type_ == ConfigType::Formula) {
  123. start_pos = str.find("formula " + config.identifier_);
  124. } else if (config.type_ == ConfigType::Label) {
  125. start_pos = str.find("label " + config.identifier_);
  126. } else if (config.type_ == ConfigType::Module) {
  127. auto iter = boost::find_nth(str, config.identifier_, config.index_);
  128. start_pos = std::distance(str.begin(), iter.begin());
  129. }
  130. else if (config.type_ == ConfigType::Constant) {
  131. start_pos = str.find(config.identifier_);
  132. if (start_pos == std::string::npos) {
  133. std::cout << "Couldn't find overwrite:" << config.expression_ << std::endl;
  134. }
  135. }
  136. size_t end_pos = str.find(';', start_pos) + 1;
  137. std::string expression = config.expression_;
  138. str.replace(start_pos, end_pos - start_pos , expression);
  139. }
  140. }
  141. void Grid::printToPrism(std::ostream& os, std::vector<Configuration>& configuration ,const prism::ModelType& modelType) {
  142. cells northRestriction;
  143. cells eastRestriction;
  144. cells southRestriction;
  145. cells westRestriction;
  146. cells walkable = floor;
  147. cells conditionallyWalkable;
  148. walkable.insert(walkable.end(), goals.begin(), goals.end());
  149. walkable.insert(walkable.end(), boxes.begin(), boxes.end());
  150. walkable.push_back(agent);
  151. walkable.insert(walkable.end(), adversaries.begin(), adversaries.end());
  152. walkable.insert(walkable.end(), lava.begin(), lava.end());
  153. conditionallyWalkable.insert(conditionallyWalkable.end(), keys.begin(), keys.end());
  154. conditionallyWalkable.insert(conditionallyWalkable.end(), lockedDoors.begin(), lockedDoors.end());
  155. conditionallyWalkable.insert(conditionallyWalkable.end(), unlockedDoors.begin(), unlockedDoors.end());
  156. for(auto const& c : walkable) {
  157. if(isBlocked(c.getNorth())) northRestriction.push_back(c);
  158. if(isBlocked(c.getEast())) eastRestriction.push_back(c);
  159. if(isBlocked(c.getSouth())) southRestriction.push_back(c);
  160. if(isBlocked(c.getWest())) westRestriction.push_back(c);
  161. }
  162. // TODO Add doors here (list of doors keys etc)
  163. // walkable.insert(walkable.end(), lockedDoors.begin(), lockedDoors.end());
  164. // walkable.insert(walkable.end(), unlockedDoors.begin(), unlockedDoors.end());
  165. for(auto const& c : conditionallyWalkable) {
  166. if(isBlocked(c.getNorth())) northRestriction.push_back(c);
  167. if(isBlocked(c.getEast())) eastRestriction.push_back(c);
  168. if(isBlocked(c.getSouth())) southRestriction.push_back(c);
  169. if(isBlocked(c.getWest())) westRestriction.push_back(c);
  170. }
  171. prism::PrismModulesPrinter printer(modelType, agentNameAndPositionMap.size(), configuration, gridOptions.enforceOneWays);
  172. printer.printModel(os, modelType);
  173. if(modelType == prism::ModelType::SMG) {
  174. printer.printGlobalMoveVariable(os, agentNameAndPositionMap.size());
  175. }
  176. for(auto const &backgroundTilesOfColor : backgroundTiles) {
  177. for(auto agentNameAndPosition = agentNameAndPositionMap.begin(); agentNameAndPosition != agentNameAndPositionMap.end(); ++agentNameAndPosition) {
  178. printer.printBackgroundLabels(os, agentNameAndPosition->first, backgroundTilesOfColor);
  179. }
  180. }
  181. cells noTurnFloor;
  182. if(gridOptions.enforceOneWays) {
  183. for(auto const& c : floor) {
  184. cell east = c.getEast(allGridCells);
  185. cell south = c.getSouth(allGridCells);
  186. cell west = c.getWest(allGridCells);
  187. cell north = c.getNorth(allGridCells);
  188. if( (east.type == Type::Wall && west.type == Type::Wall) or
  189. (north.type == Type::Wall && south.type == Type::Wall) ) {
  190. noTurnFloor.push_back(c);
  191. }
  192. }
  193. }
  194. cells doors;
  195. doors.insert(doors.end(), lockedDoors.begin(), lockedDoors.end());
  196. doors.insert(doors.end(), unlockedDoors.begin(), unlockedDoors.end());
  197. for(auto agentNameAndPosition = agentNameAndPositionMap.begin(); agentNameAndPosition != agentNameAndPositionMap.end(); ++agentNameAndPosition) {
  198. printer.printFormulas(os, agentNameAndPosition->first, northRestriction, eastRestriction, southRestriction, westRestriction, { slipperyNorth, slipperyEast, slipperySouth, slipperyWest }, lava, walls, noTurnFloor, slipperyNorth, slipperyEast, slipperySouth, slipperyWest, keys, doors);
  199. printer.printGoalLabel(os, agentNameAndPosition->first, goals);
  200. printer.printKeysLabels(os, agentNameAndPosition->first, keys);
  201. }
  202. std::vector<std::string> constants {"const double prop_zero = 0/9;",
  203. "const double prop_intended = 6/9;",
  204. "const double prop_turn_intended = 6/9;",
  205. "const double prop_displacement = 3/9;",
  206. "const double prop_turn_displacement = 3/9;",
  207. "const int width = " + std::to_string(maxBoundaries.first) + ";",
  208. "const int height = " + std::to_string(maxBoundaries.second) + ";"
  209. };
  210. printer.printConstants(os, constants);
  211. std::vector<AgentName> agentNames;
  212. std::transform(agentNameAndPositionMap.begin(),
  213. agentNameAndPositionMap.end(),
  214. std::back_inserter(agentNames),
  215. [](const std::map<AgentNameAndPosition::first_type,AgentNameAndPosition::second_type>::value_type &pair){return pair.first;});
  216. if(modelType == prism::ModelType::SMG) {
  217. printer.printCrashLabel(os, agentNames);
  218. }
  219. size_t agentIndex = 0;
  220. printer.printInitStruct(os, agentNameAndPositionMap, keyNameAndPositionMap, lockedDoors, unlockedDoors, modelType);
  221. for(auto agentNameAndPosition = agentNameAndPositionMap.begin(); agentNameAndPosition != agentNameAndPositionMap.end(); ++agentNameAndPosition, agentIndex++) {
  222. AgentName agentName = agentNameAndPosition->first;
  223. //std::cout << "Agent Name: " << agentName << std::endl;
  224. bool agentWithView = std::find(gridOptions.agentsWithView.begin(), gridOptions.agentsWithView.end(), agentName) != gridOptions.agentsWithView.end();
  225. bool agentWithProbabilisticBehaviour = std::find(gridOptions.agentsWithProbabilisticBehaviour.begin(), gridOptions.agentsWithProbabilisticBehaviour.end(), agentName) != gridOptions.agentsWithProbabilisticBehaviour.end();
  226. std::set<std::string> slipperyActions; // TODO AGENT POSITION INITIALIZATIN
  227. if(agentWithProbabilisticBehaviour) printer.printModule(os, agentName, agentIndex, maxBoundaries, agentNameAndPosition->second, keys, backgroundTiles, agentWithView, gridOptions.probabilitiesForActions);
  228. else printer.printModule(os, agentName, agentIndex, maxBoundaries, agentNameAndPosition->second, keys, backgroundTiles, agentWithView, {} ,faultyProbability);
  229. for(auto const& c : slipperyNorth) {
  230. printer.printSlipperyMove(os, agentName, agentIndex, c.getCoordinates(), slipperyActions, getWalkableDirOf8Neighborhood(c), prism::PrismModulesPrinter::SlipperyType::North);
  231. if(!gridOptions.enforceOneWays) printer.printSlipperyTurn(os, agentName, agentIndex, c.getCoordinates(), slipperyActions, getWalkableDirOf8Neighborhood(c), prism::PrismModulesPrinter::SlipperyType::North);
  232. }
  233. for(auto const& c : slipperyEast) {
  234. printer.printSlipperyMove(os, agentName, agentIndex, c.getCoordinates(), slipperyActions, getWalkableDirOf8Neighborhood(c), prism::PrismModulesPrinter::SlipperyType::East);
  235. if(!gridOptions.enforceOneWays) printer.printSlipperyTurn(os, agentName, agentIndex, c.getCoordinates(), slipperyActions, getWalkableDirOf8Neighborhood(c), prism::PrismModulesPrinter::SlipperyType::East);
  236. }
  237. for(auto const& c : slipperySouth) {
  238. printer.printSlipperyMove(os, agentName, agentIndex, c.getCoordinates(), slipperyActions, getWalkableDirOf8Neighborhood(c), prism::PrismModulesPrinter::SlipperyType::South);
  239. if(!gridOptions.enforceOneWays) printer.printSlipperyTurn(os, agentName, agentIndex, c.getCoordinates(), slipperyActions, getWalkableDirOf8Neighborhood(c), prism::PrismModulesPrinter::SlipperyType::South);
  240. }
  241. for(auto const& c : slipperyWest) {
  242. printer.printSlipperyMove(os, agentName, agentIndex, c.getCoordinates(), slipperyActions, getWalkableDirOf8Neighborhood(c), prism::PrismModulesPrinter::SlipperyType::West);
  243. if(!gridOptions.enforceOneWays) printer.printSlipperyTurn(os, agentName, agentIndex, c.getCoordinates(), slipperyActions, getWalkableDirOf8Neighborhood(c), prism::PrismModulesPrinter::SlipperyType::West);
  244. }
  245. printer.printEndmodule(os);
  246. if(modelType == prism::ModelType::SMG) {
  247. if(agentWithProbabilisticBehaviour) printer.printPlayerStruct(os, agentNameAndPosition->first, agentWithView, gridOptions.probabilitiesForActions, slipperyActions);
  248. else printer.printPlayerStruct(os, agentNameAndPosition->first, agentWithView, {}, slipperyActions);
  249. }
  250. //if(!stateRewards.empty()) {
  251. printer.printRewards(os, agentName, stateRewards, lava, goals, backgroundTiles);
  252. //}
  253. }
  254. if (!configuration.empty()) {
  255. printer.printConfiguration(os, configuration);
  256. }
  257. // TODO CHANGE HANDLING
  258. std::string agentName = agentNames.at(0);
  259. for (auto const & key : keys) {
  260. os << "\n";
  261. printer.printKeyModule(os, key, maxBoundaries, agentName);
  262. printer.printEndmodule(os);
  263. }
  264. for (auto const& door : lockedDoors) {
  265. os << "\n";
  266. printer.printDoorModule(os, door, maxBoundaries, agentName);
  267. printer.printEndmodule(os);
  268. }
  269. }
  270. std::array<bool, 8> Grid::getWalkableDirOf8Neighborhood(cell c) /* const */ {
  271. return (std::array<bool, 8>)
  272. {
  273. !isBlocked(c.getNorth()),
  274. !isBlocked(c.getNorth(allGridCells).getEast()),
  275. !isBlocked(c.getEast()),
  276. !isBlocked(c.getSouth(allGridCells).getEast()),
  277. !isBlocked(c.getSouth()),
  278. !isBlocked(c.getSouth(allGridCells).getWest()),
  279. !isBlocked(c.getWest()),
  280. !isBlocked(c.getNorth(allGridCells).getWest())
  281. };
  282. }