Fuzzy.cpp 9.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298
  1. #include "StdInc.h"
  2. #include "Fuzzy.h"
  3. #include <limits>
  4. #include "../../lib/CObjectHandler.h"
  5. #include "../../lib/CCreatureHandler.h"
  6. #include "../../lib/VCMI_Lib.h"
  7. //#include "Goals.cpp"
  8. //#include "VCAI.h"
  9. /*
  10. * Fuzzy.cpp, part of VCMI engine
  11. *
  12. * Authors: listed in file AUTHORS in main folder
  13. *
  14. * License: GNU General Public License v2.0 or later
  15. * Full text of license available in license.txt file, in main folder
  16. *
  17. */
  18. #define MIN_AI_STRENGHT (0.5f) //lower when combat AI gets smarter
  19. struct BankConfig;
  20. class FuzzyEngine;
  21. class InputLVar;
  22. class CGTownInstance;
  23. using namespace boost::assign;
  24. using namespace vstd;
  25. //using namespace Goals;
  26. FuzzyHelper *fh;
  27. struct armyStructure
  28. {
  29. float walkers, shooters, flyers;
  30. ui32 maxSpeed;
  31. };
  32. ui64 evaluateBankConfig (BankConfig * bc)
  33. {
  34. ui64 danger = 0;
  35. for (auto opt : bc->guards)
  36. {
  37. danger += VLC->creh->creatures[opt.first]->fightValue * opt.second;
  38. }
  39. return danger;
  40. }
  41. armyStructure evaluateArmyStructure (const CArmedInstance * army)
  42. {
  43. ui64 totalStrenght = army->getArmyStrength();
  44. double walkersStrenght = 0;
  45. double flyersStrenght = 0;
  46. double shootersStrenght = 0;
  47. ui32 maxSpeed = 0;
  48. for(auto s : army->Slots())
  49. {
  50. bool walker = true;
  51. if (s.second->type->hasBonusOfType(Bonus::SHOOTER))
  52. {
  53. shootersStrenght += s.second->getPower();
  54. walker = false;
  55. }
  56. if (s.second->type->hasBonusOfType(Bonus::FLYING))
  57. {
  58. flyersStrenght += s.second->getPower();
  59. walker = false;
  60. }
  61. if (walker)
  62. walkersStrenght += s.second->getPower();
  63. amax (maxSpeed, s.second->type->valOfBonuses(Bonus::STACKS_SPEED));
  64. }
  65. armyStructure as;
  66. as.walkers = walkersStrenght / totalStrenght;
  67. as.shooters = shootersStrenght / totalStrenght;
  68. as.flyers = flyersStrenght / totalStrenght;
  69. as.maxSpeed = maxSpeed;
  70. return as;
  71. }
  72. FuzzyHelper::FuzzyHelper()
  73. {
  74. initBank();
  75. initTacticalAdvantage();
  76. }
  77. void FuzzyHelper::initBank()
  78. {
  79. try
  80. {
  81. //Trivial bank estimation
  82. bankInput = new fl::InputLVar("BankInput");
  83. bankDanger = new fl::OutputLVar("BankDanger");
  84. bankInput->addTerm(new fl::SingletonTerm ("SET"));
  85. engine.addRuleBlock (&bankBlock); //have to be added before the rules are parsed
  86. engine.addInputLVar (bankInput);
  87. engine.addOutputLVar (bankDanger);
  88. for (int i = 0; i < 4; ++i)
  89. {
  90. bankDanger->addTerm(new fl::TriangularTerm ("Bank" + boost::lexical_cast<std::string>(i), 0, 1));
  91. bankBlock.addRule(new fl::MamdaniRule("if BankInput is SET then BankDanger is Bank" + boost::lexical_cast<std::string>(i), engine));
  92. }
  93. }
  94. catch (fl::FuzzyException & fe)
  95. {
  96. logAi->errorStream() << "initBank " << fe.name() << ": " << fe.message();
  97. }
  98. }
  99. void FuzzyHelper::initTacticalAdvantage()
  100. {
  101. try
  102. {
  103. //Tactical advantage calculation
  104. std::vector<fl::InputLVar*> helper;
  105. ourShooters = new fl::InputLVar("OurShooters");
  106. ourWalkers = new fl::InputLVar("OurWalkers");
  107. ourFlyers = new fl::InputLVar("OurFlyers");
  108. enemyShooters = new fl::InputLVar("EnemyShooters");
  109. enemyWalkers = new fl::InputLVar("EnemyWalkers");
  110. enemyFlyers = new fl::InputLVar("EnemyFlyers");
  111. helper += ourShooters, ourWalkers, ourFlyers, enemyShooters, enemyWalkers, enemyFlyers;
  112. for (auto val : helper)
  113. {
  114. val->addTerm (new fl::ShoulderTerm("FEW", 0, 0.75, true));
  115. val->addTerm (new fl::ShoulderTerm("MANY", 0.25, 1, false));
  116. engine.addInputLVar(val);
  117. }
  118. helper.clear();
  119. ourSpeed = new fl::InputLVar("OurSpeed");
  120. enemySpeed = new fl::InputLVar("EnemySpeed");
  121. helper += ourSpeed, enemySpeed;
  122. for (auto val : helper)
  123. {
  124. val->addTerm (new fl::ShoulderTerm("LOW", 3, 8.1, true));
  125. val->addTerm (new fl::TriangularTerm("MEDIUM", 6.9, 13.1));
  126. val->addTerm (new fl::ShoulderTerm("HIGH", 10.5, 16, false));
  127. engine.addInputLVar(val);
  128. }
  129. castleWalls = new fl::InputLVar("CastleWalls");
  130. castleWalls->addTerm(new fl::SingletonTerm("NONE", CGTownInstance::NONE));
  131. castleWalls->addTerm(new fl::TrapezoidalTerm("MEDIUM", CGTownInstance::FORT, 2.5));
  132. castleWalls->addTerm(new fl::ShoulderTerm("HIGH", CGTownInstance::CITADEL - 0.1, CGTownInstance::CASTLE));
  133. engine.addInputLVar(castleWalls);
  134. bankPresent = new fl::InputLVar("Bank");
  135. bankPresent->addTerm(new fl::SingletonTerm("FALSE", 0));
  136. bankPresent->addTerm(new fl::SingletonTerm("TRUE", 1));
  137. engine.addInputLVar(bankPresent);
  138. threat = new fl::OutputLVar("Threat");
  139. threat->addTerm (new fl::TriangularTerm("LOW", MIN_AI_STRENGHT, 1));
  140. threat->addTerm (new fl::TriangularTerm("MEDIUM", 0.8, 1.2));
  141. threat->addTerm (new fl::ShoulderTerm("HIGH", 1, 1.5, false));
  142. engine.addOutputLVar(threat);
  143. engine.hedgeSet().add(new fl::HedgeSomewhat());
  144. engine.hedgeSet().add(new fl::HedgeVery());
  145. tacticalAdvantage.addRule(new fl::MamdaniRule("if OurShooters is MANY and EnemySpeed is LOW then Threat is very LOW", engine));
  146. tacticalAdvantage.addRule(new fl::MamdaniRule("if OurSpeed is LOW and OurShooters is FEW and EnemyShooters is MANY then Threat is very HIGH", engine));
  147. tacticalAdvantage.addRule(new fl::MamdaniRule("if (OurShooters is MANY and OurFlyers is MANY) and EnemyShooters is MANY then Threat is LOW", engine));
  148. tacticalAdvantage.addRule(new fl::MamdaniRule("if OurShooters is MANY and EnemySpeed is HIGH then Threat is somewhat HIGH", engine));
  149. //tacticalAdvantage.addRule(new fl::MamdaniRule("if OurShooters is MANY and EnemyShooters is MANY then Threat is MEDIUM", engine));
  150. tacticalAdvantage.addRule(new fl::MamdaniRule("if Bank is TRUE and OurShooters is MANY then Threat is somewhat HIGH", engine));
  151. tacticalAdvantage.addRule(new fl::MamdaniRule("if Bank is TRUE and EnemyShooters is MANY then Threat is LOW", engine));
  152. tacticalAdvantage.addRule(new fl::MamdaniRule("if CastleWalls is HIGH and OurWalkers is MANY then Threat is very HIGH", engine));
  153. tacticalAdvantage.addRule(new fl::MamdaniRule("if CastleWalls is HIGH and OurFlyers is MANY and OurShooters is MANY then Threat is MEDIUM", engine));
  154. tacticalAdvantage.addRule(new fl::MamdaniRule("if CastleWalls is MEDIUM and OurShooters is MANY and EnemyWalkers is MANY then Threat is LOW", engine));
  155. engine.addRuleBlock (&tacticalAdvantage);
  156. }
  157. catch(fl::ParsingException & pe)
  158. {
  159. logAi->errorStream() << "initTacticalAdvantage " << pe.name() << ": " << pe.message();
  160. }
  161. catch (fl::FuzzyException & fe)
  162. {
  163. logAi->errorStream() << "initTacticalAdvantage " << fe.name() << ": " << fe.message();
  164. }
  165. }
  166. ui64 FuzzyHelper::estimateBankDanger (int ID)
  167. {
  168. std::vector <ConstTransitivePtr<BankConfig>> & configs = VLC->objh->banksInfo[ID];
  169. ui64 val = std::numeric_limits<ui64>::max();
  170. try
  171. {
  172. switch (configs.size())
  173. {
  174. case 4:
  175. try
  176. {
  177. for (int i = 0; i < 4; ++i)
  178. {
  179. int bankVal = evaluateBankConfig (VLC->objh->banksInfo[ID][i]);
  180. bankDanger->term("Bank" + boost::lexical_cast<std::string>(i))->setMinimum(bankVal * 0.5f);
  181. bankDanger->term("Bank" + boost::lexical_cast<std::string>(i))->setMaximum(bankVal * 1.5f);
  182. }
  183. //comparison purposes
  184. //int averageValue = (evaluateBankConfig (VLC->objh->banksInfo[ID][0]) + evaluateBankConfig (VLC->objh->banksInfo[ID][3])) * 0.5;
  185. dynamic_cast<fl::SingletonTerm*>(bankInput->term("SET"))->setValue(0.5);
  186. bankInput->setInput (0.5);
  187. engine.process (BANK_DANGER);
  188. val = bankDanger->output().defuzzify(); //some expected value of this bank
  189. }
  190. catch (fl::FuzzyException & fe)
  191. {
  192. logAi->errorStream() << fe.name() << ": " << fe.message();
  193. }
  194. break;
  195. case 1: //rare case - Pyramid
  196. val = evaluateBankConfig (VLC->objh->banksInfo[ID][0]);
  197. break;
  198. default:
  199. logAi->warnStream() << ("Uhnandled bank config!");
  200. }
  201. }
  202. catch (fl::FuzzyException & fe)
  203. {
  204. logAi->errorStream() << "estimateBankDanger " << fe.name() << ": " << fe.message();
  205. }
  206. return val;
  207. }
  208. float FuzzyHelper::getTacticalAdvantage (const CArmedInstance *we, const CArmedInstance *enemy)
  209. {
  210. float output = 1;
  211. try
  212. {
  213. armyStructure ourStructure = evaluateArmyStructure(we);
  214. armyStructure enemyStructure = evaluateArmyStructure(enemy);
  215. ourWalkers->setInput(ourStructure.walkers);
  216. ourShooters->setInput(ourStructure.shooters);
  217. ourFlyers->setInput(ourStructure.flyers);
  218. ourSpeed->setInput(ourStructure.maxSpeed);
  219. enemyWalkers->setInput(enemyStructure.walkers);
  220. enemyShooters->setInput(enemyStructure.shooters);
  221. enemyFlyers->setInput(enemyStructure.flyers);
  222. enemySpeed->setInput(enemyStructure.maxSpeed);
  223. bool bank = dynamic_cast<const CBank*>(enemy);
  224. if (bank)
  225. bankPresent->setInput(1);
  226. else
  227. bankPresent->setInput(0);
  228. const CGTownInstance * fort = dynamic_cast<const CGTownInstance*>(enemy);
  229. if (fort)
  230. {
  231. castleWalls->setInput (fort->fortLevel());
  232. }
  233. else
  234. castleWalls->setInput(0);
  235. engine.process (TACTICAL_ADVANTAGE);
  236. output = threat->output().defuzzify();
  237. }
  238. catch (fl::FuzzyException & fe)
  239. {
  240. logAi->errorStream() << "getTacticalAdvantage " << fe.name() << ": " << fe.message();
  241. }
  242. return output;
  243. }
  244. //shared_ptr<AbstractGoal> chooseSolution (std::vector<shared_ptr<AbstractGoal>> & vec)
  245. Goals::TSubgoal chooseSolution (Goals::TGoalVec & vec)
  246. {
  247. typedef std::pair<Goals::TSubgoal, float> goalValue;
  248. std::vector <goalValue> values;
  249. for (auto g : vec)
  250. {
  251. values.push_back (std::make_pair(g, 66.6f));
  252. }
  253. auto compareGoals = [&](const goalValue & lhs, const goalValue & rhs) -> bool
  254. {
  255. return lhs.second < rhs.second;
  256. };
  257. boost::sort (values, compareGoals);
  258. return values.end()->first;
  259. }