Fuzzy.cpp 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469
  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 "../../CCallback.h"
  8. //#include "Goals.cpp"
  9. #include "VCAI.h"
  10. /*
  11. * Fuzzy.cpp, part of VCMI engine
  12. *
  13. * Authors: listed in file AUTHORS in main folder
  14. *
  15. * License: GNU General Public License v2.0 or later
  16. * Full text of license available in license.txt file, in main folder
  17. *
  18. */
  19. #define MIN_AI_STRENGHT (0.5f) //lower when combat AI gets smarter
  20. struct BankConfig;
  21. class FuzzyEngine;
  22. class InputLVar;
  23. class CGTownInstance;
  24. using namespace boost::assign;
  25. using namespace vstd;
  26. //using namespace Goals;
  27. FuzzyHelper *fh;
  28. extern boost::thread_specific_ptr<CCallback> cb;
  29. extern boost::thread_specific_ptr<VCAI> ai;
  30. struct armyStructure
  31. {
  32. float walkers, shooters, flyers;
  33. ui32 maxSpeed;
  34. };
  35. ui64 evaluateBankConfig (BankConfig * bc)
  36. {
  37. ui64 danger = 0;
  38. for (auto opt : bc->guards)
  39. {
  40. danger += VLC->creh->creatures[opt.first]->fightValue * opt.second;
  41. }
  42. return danger;
  43. }
  44. armyStructure evaluateArmyStructure (const CArmedInstance * army)
  45. {
  46. ui64 totalStrenght = army->getArmyStrength();
  47. double walkersStrenght = 0;
  48. double flyersStrenght = 0;
  49. double shootersStrenght = 0;
  50. ui32 maxSpeed = 0;
  51. for(auto s : army->Slots())
  52. {
  53. bool walker = true;
  54. if (s.second->type->hasBonusOfType(Bonus::SHOOTER))
  55. {
  56. shootersStrenght += s.second->getPower();
  57. walker = false;
  58. }
  59. if (s.second->type->hasBonusOfType(Bonus::FLYING))
  60. {
  61. flyersStrenght += s.second->getPower();
  62. walker = false;
  63. }
  64. if (walker)
  65. walkersStrenght += s.second->getPower();
  66. amax (maxSpeed, s.second->type->valOfBonuses(Bonus::STACKS_SPEED));
  67. }
  68. armyStructure as;
  69. as.walkers = walkersStrenght / totalStrenght;
  70. as.shooters = shootersStrenght / totalStrenght;
  71. as.flyers = flyersStrenght / totalStrenght;
  72. as.maxSpeed = maxSpeed;
  73. return as;
  74. }
  75. FuzzyHelper::FuzzyHelper()
  76. {
  77. engine.hedgeSet().add(new fl::HedgeSomewhat());
  78. engine.hedgeSet().add(new fl::HedgeVery());
  79. initBank();
  80. initTacticalAdvantage();
  81. initVisitTile();
  82. }
  83. void FuzzyHelper::initBank()
  84. {
  85. try
  86. {
  87. //Trivial bank estimation
  88. bankInput = new fl::InputLVar("BankInput");
  89. bankDanger = new fl::OutputLVar("BankDanger");
  90. bankInput->addTerm(new fl::SingletonTerm ("SET"));
  91. engine.addRuleBlock (&bankBlock); //have to be added before the rules are parsed
  92. engine.addInputLVar (bankInput);
  93. engine.addOutputLVar (bankDanger);
  94. for (int i = 0; i < 4; ++i)
  95. {
  96. bankDanger->addTerm(new fl::TriangularTerm ("Bank" + boost::lexical_cast<std::string>(i), 0, 1));
  97. bankBlock.addRule(new fl::MamdaniRule("if BankInput is SET then BankDanger is Bank" + boost::lexical_cast<std::string>(i), engine));
  98. }
  99. }
  100. catch (fl::FuzzyException & fe)
  101. {
  102. logAi->errorStream() << "initBank " << fe.name() << ": " << fe.message();
  103. }
  104. }
  105. void FuzzyHelper::initTacticalAdvantage()
  106. {
  107. try
  108. {
  109. //Tactical advantage calculation
  110. std::vector<fl::InputLVar*> helper;
  111. //TODO: delete all that stuff upon destruction
  112. ta.ourShooters = new fl::InputLVar("OurShooters");
  113. ta.ourWalkers = new fl::InputLVar("OurWalkers");
  114. ta.ourFlyers = new fl::InputLVar("OurFlyers");
  115. ta.enemyShooters = new fl::InputLVar("EnemyShooters");
  116. ta.enemyWalkers = new fl::InputLVar("EnemyWalkers");
  117. ta.enemyFlyers = new fl::InputLVar("EnemyFlyers");
  118. helper += ta.ourShooters, ta.ourWalkers, ta.ourFlyers, ta.enemyShooters, ta.enemyWalkers, ta.enemyFlyers;
  119. for (auto val : helper)
  120. {
  121. val->addTerm (new fl::ShoulderTerm("FEW", 0, 0.75, true));
  122. val->addTerm (new fl::ShoulderTerm("MANY", 0.25, 1, false));
  123. engine.addInputLVar(val);
  124. }
  125. helper.clear();
  126. ta.ourSpeed = new fl::InputLVar("OurSpeed");
  127. ta.enemySpeed = new fl::InputLVar("EnemySpeed");
  128. helper += ta.ourSpeed, ta.enemySpeed;
  129. for (auto val : helper)
  130. {
  131. val->addTerm (new fl::ShoulderTerm("LOW", 3, 8.1, true));
  132. val->addTerm (new fl::TriangularTerm("MEDIUM", 6.9, 13.1));
  133. val->addTerm (new fl::ShoulderTerm("HIGH", 10.5, 16, false));
  134. engine.addInputLVar(val);
  135. }
  136. ta.castleWalls = new fl::InputLVar("CastleWalls");
  137. ta.castleWalls->addTerm(new fl::SingletonTerm("NONE", CGTownInstance::NONE));
  138. ta.castleWalls->addTerm(new fl::TrapezoidalTerm("MEDIUM", CGTownInstance::FORT, 2.5));
  139. ta.castleWalls->addTerm(new fl::ShoulderTerm("HIGH", CGTownInstance::CITADEL - 0.1, CGTownInstance::CASTLE, false));
  140. engine.addInputLVar(ta.castleWalls);
  141. ta.bankPresent = new fl::InputLVar("Bank");
  142. ta.bankPresent->addTerm(new fl::SingletonTerm("FALSE", 0));
  143. ta.bankPresent->addTerm(new fl::SingletonTerm("TRUE", 1));
  144. engine.addInputLVar(ta.bankPresent);
  145. ta.threat = new fl::OutputLVar("Threat");
  146. ta.threat->addTerm (new fl::TriangularTerm("LOW", MIN_AI_STRENGHT, 1));
  147. ta.threat->addTerm (new fl::TriangularTerm("MEDIUM", 0.8, 1.2));
  148. ta.threat->addTerm (new fl::ShoulderTerm("HIGH", 1, 1.5, false));
  149. engine.addOutputLVar(ta.threat);
  150. ta.tacticalAdvantage.addRule(new fl::MamdaniRule("if OurShooters is MANY and EnemySpeed is LOW then Threat is very LOW", engine));
  151. ta.tacticalAdvantage.addRule(new fl::MamdaniRule("if OurSpeed is LOW and OurShooters is FEW and EnemyShooters is MANY then Threat is very HIGH", engine));
  152. ta.tacticalAdvantage.addRule(new fl::MamdaniRule("if (OurShooters is MANY and OurFlyers is MANY) and EnemyShooters is MANY then Threat is LOW", engine));
  153. ta.tacticalAdvantage.addRule(new fl::MamdaniRule("if OurShooters is MANY and EnemySpeed is HIGH then Threat is somewhat HIGH", engine));
  154. //tacticalAdvantage.addRule(new fl::MamdaniRule("if OurShooters is MANY and EnemyShooters is MANY then Threat is MEDIUM", engine));
  155. ta.tacticalAdvantage.addRule(new fl::MamdaniRule("if Bank is TRUE and OurShooters is MANY then Threat is somewhat HIGH", engine));
  156. ta.tacticalAdvantage.addRule(new fl::MamdaniRule("if Bank is TRUE and EnemyShooters is MANY then Threat is LOW", engine));
  157. ta.tacticalAdvantage.addRule(new fl::MamdaniRule("if CastleWalls is HIGH and OurWalkers is MANY then Threat is very HIGH", engine));
  158. ta.tacticalAdvantage.addRule(new fl::MamdaniRule("if CastleWalls is HIGH and OurFlyers is MANY and OurShooters is MANY then Threat is MEDIUM", engine));
  159. ta.tacticalAdvantage.addRule(new fl::MamdaniRule("if CastleWalls is MEDIUM and OurShooters is MANY and EnemyWalkers is MANY then Threat is LOW", engine));
  160. engine.addRuleBlock (&ta.tacticalAdvantage);
  161. }
  162. catch(fl::ParsingException & pe)
  163. {
  164. logAi->errorStream() << "initTacticalAdvantage " << pe.name() << ": " << pe.message();
  165. }
  166. catch (fl::FuzzyException & fe)
  167. {
  168. logAi->errorStream() << "initTacticalAdvantage " << fe.name() << ": " << fe.message();
  169. }
  170. }
  171. ui64 FuzzyHelper::estimateBankDanger (int ID)
  172. {
  173. std::vector <ConstTransitivePtr<BankConfig>> & configs = VLC->objh->banksInfo[ID];
  174. ui64 val = std::numeric_limits<ui64>::max();
  175. try
  176. {
  177. switch (configs.size())
  178. {
  179. case 4:
  180. try
  181. {
  182. for (int i = 0; i < 4; ++i)
  183. {
  184. int bankVal = evaluateBankConfig (VLC->objh->banksInfo[ID][i]);
  185. bankDanger->term("Bank" + boost::lexical_cast<std::string>(i))->setMinimum(bankVal * 0.5f);
  186. bankDanger->term("Bank" + boost::lexical_cast<std::string>(i))->setMaximum(bankVal * 1.5f);
  187. }
  188. //comparison purposes
  189. //int averageValue = (evaluateBankConfig (VLC->objh->banksInfo[ID][0]) + evaluateBankConfig (VLC->objh->banksInfo[ID][3])) * 0.5;
  190. dynamic_cast<fl::SingletonTerm*>(bankInput->term("SET"))->setValue(0.5);
  191. bankInput->setInput (0.5);
  192. engine.process (BANK_DANGER);
  193. val = bankDanger->output().defuzzify(); //some expected value of this bank
  194. }
  195. catch (fl::FuzzyException & fe)
  196. {
  197. logAi->errorStream() << fe.name() << ": " << fe.message();
  198. }
  199. break;
  200. case 1: //rare case - Pyramid
  201. val = evaluateBankConfig (VLC->objh->banksInfo[ID][0]);
  202. break;
  203. default:
  204. logAi->warnStream() << ("Uhnandled bank config!");
  205. }
  206. }
  207. catch (fl::FuzzyException & fe)
  208. {
  209. logAi->errorStream() << "estimateBankDanger " << fe.name() << ": " << fe.message();
  210. }
  211. return val;
  212. }
  213. float FuzzyHelper::getTacticalAdvantage (const CArmedInstance *we, const CArmedInstance *enemy)
  214. {
  215. float output = 1;
  216. try
  217. {
  218. armyStructure ourStructure = evaluateArmyStructure(we);
  219. armyStructure enemyStructure = evaluateArmyStructure(enemy);
  220. ta.ourWalkers->setInput(ourStructure.walkers);
  221. ta.ourShooters->setInput(ourStructure.shooters);
  222. ta.ourFlyers->setInput(ourStructure.flyers);
  223. ta.ourSpeed->setInput(ourStructure.maxSpeed);
  224. ta.enemyWalkers->setInput(enemyStructure.walkers);
  225. ta.enemyShooters->setInput(enemyStructure.shooters);
  226. ta.enemyFlyers->setInput(enemyStructure.flyers);
  227. ta.enemySpeed->setInput(enemyStructure.maxSpeed);
  228. bool bank = dynamic_cast<const CBank*>(enemy);
  229. if (bank)
  230. ta.bankPresent->setInput(1);
  231. else
  232. ta.bankPresent->setInput(0);
  233. const CGTownInstance * fort = dynamic_cast<const CGTownInstance*>(enemy);
  234. if (fort)
  235. {
  236. ta.castleWalls->setInput (fort->fortLevel());
  237. }
  238. else
  239. ta.castleWalls->setInput(0);
  240. engine.process (TACTICAL_ADVANTAGE);
  241. output = ta.threat->output().defuzzify();
  242. }
  243. catch (fl::FuzzyException & fe)
  244. {
  245. logAi->errorStream() << "getTacticalAdvantage " << fe.name() << ": " << fe.message();
  246. }
  247. return output;
  248. }
  249. FuzzyHelper::TacticalAdvantage::~TacticalAdvantage()
  250. {
  251. //TODO: smart pointers?
  252. delete ourWalkers;
  253. delete ourShooters;
  254. delete ourFlyers;
  255. delete enemyWalkers;
  256. delete enemyShooters;
  257. delete enemyFlyers;
  258. delete ourSpeed;
  259. delete enemySpeed;
  260. delete bankPresent;
  261. delete castleWalls;
  262. delete threat;
  263. }
  264. //shared_ptr<AbstractGoal> chooseSolution (std::vector<shared_ptr<AbstractGoal>> & vec)
  265. Goals::TSubgoal FuzzyHelper::chooseSolution (Goals::TGoalVec vec)
  266. {
  267. if (vec.empty()) //no possibilities found
  268. return sptr(Goals::Invalid());
  269. typedef std::pair<Goals::TSubgoal, float> goalValue;
  270. std::vector <goalValue> values;
  271. for (auto g : vec)
  272. {
  273. values.push_back (std::make_pair(g, g->accept(this)));
  274. }
  275. auto compareGoals = [&](const goalValue & lhs, const goalValue & rhs) -> bool
  276. {
  277. return lhs.second < rhs.second;
  278. };
  279. boost::sort (values, compareGoals);
  280. return values.back().first;
  281. }
  282. float FuzzyHelper::evaluate (Goals::Explore & g)
  283. {
  284. return 1;
  285. }
  286. float FuzzyHelper::evaluate (Goals::RecruitHero & g)
  287. {
  288. return 1; //just try to recruit hero as one of options
  289. }
  290. FuzzyHelper::EvalVisitTile::~EvalVisitTile()
  291. {
  292. delete strengthRatio;
  293. delete heroStrength;
  294. delete tileDistance;
  295. delete missionImportance;
  296. delete movement;
  297. }
  298. void FuzzyHelper::initVisitTile()
  299. {
  300. std::vector<fl::InputLVar*> helper;
  301. vt.strengthRatio = new fl::InputLVar("strengthRatio"); //hero must be strong enough to defeat guards
  302. vt.heroStrength = new fl::InputLVar("heroStrength"); //we want to use weakest possible hero
  303. vt.tileDistance = new fl::InputLVar("tileDistance"); //we want to use hero who is near
  304. vt.missionImportance = new fl::InputLVar("lockedMissionImportance"); //we may want to preempt hero with low-priority mission
  305. vt.movement = new fl::InputLVar("movement");
  306. vt.value = new fl::OutputLVar("Value");
  307. helper += vt.strengthRatio, vt.heroStrength, vt.tileDistance, vt.missionImportance, vt.movement;
  308. vt.strengthRatio->addTerm (new fl::ShoulderTerm("LOW", 0.9, SAFE_ATTACK_CONSTANT, true));
  309. vt.strengthRatio->addTerm (new fl::ShoulderTerm("HIGH", SAFE_ATTACK_CONSTANT, SAFE_ATTACK_CONSTANT * 3, false));
  310. vt.heroStrength->addTerm (new fl::ShoulderTerm("LOW", 1, 2500, true)); //assumed strength of new hero from tavern
  311. vt.heroStrength->addTerm (new fl::TriangularTerm("MEDIUM", 2500, 40000)); //assumed strength of hero able to defeat bank
  312. vt.heroStrength->addTerm (new fl::ShoulderTerm("HIGH", 40000, 1e5, false)); //assumed strength of hero able to clear utopia
  313. vt.tileDistance->addTerm (new fl::ShoulderTerm("SMALL", 0, 3.5, true));
  314. vt.tileDistance->addTerm (new fl::TriangularTerm("MEDIUM", 3, 10.5));
  315. vt.tileDistance->addTerm (new fl::ShoulderTerm("LONG", 10, 50, false));
  316. vt.missionImportance->addTerm (new fl::ShoulderTerm("LOW", 0, 3.1, true));
  317. vt.missionImportance->addTerm (new fl::TriangularTerm("MEDIUM", 2, 9.5));
  318. vt.missionImportance->addTerm (new fl::ShoulderTerm("HIGH", 4.5, 10, false));
  319. vt.value->addTerm (new fl::ShoulderTerm("LOW", 0, 1.1, true));
  320. vt.value->addTerm (new fl::ShoulderTerm("HIGH", 1, 5, false));
  321. vt.movement->addTerm (new fl::ShoulderTerm("LOW", 1, 200, true));
  322. vt.movement->addTerm (new fl::ShoulderTerm("HIGH", 1000, 2000, false));
  323. for (auto val : helper)
  324. {
  325. engine.addInputLVar(val);
  326. }
  327. engine.addOutputLVar (vt.value);
  328. //vt.rules.addRule (new fl::MamdaniRule("if OurShooters is MANY and EnemySpeed is LOW then Threat is very LOW", engine));
  329. //use unarmed scouts if possible
  330. vt.rules.addRule (new fl::MamdaniRule("if strengthRatio is HIGH and heroStrength is LOW then Value is very HIGH", engine));
  331. //don't assign targets to heroes who are too weak
  332. vt.rules.addRule (new fl::MamdaniRule("if strengthRatio is very LOW then Value is very LOW", engine));
  333. //if medium heroes can't scratch enemy, don't try to arm them
  334. vt.rules.addRule (new fl::MamdaniRule("if strengthRatio is LOW and heroStrength is MEDIUM then Value is LOW", engine));
  335. //do not cancel important goals
  336. vt.rules.addRule (new fl::MamdaniRule("if lockedMissionImportance is HIGH then Value is very LOW", engine));
  337. //pick nearby objects if it's easy, avoid long walks
  338. vt.rules.addRule (new fl::MamdaniRule("if tileDistance is SMALL then Value is HIGH", engine));
  339. vt.rules.addRule (new fl::MamdaniRule("if tileDistance is LONG then Value is LOW", engine));
  340. //use heroes with movement points first
  341. vt.rules.addRule (new fl::MamdaniRule("if movement is LOW then Value is somewhat LOW", engine));
  342. vt.rules.addRule (new fl::MamdaniRule("if movement is HIGH then Value is somewhat HIGH", engine));
  343. engine.addRuleBlock (&vt.rules);
  344. }
  345. float FuzzyHelper::evaluate (Goals::VisitTile & g)
  346. {
  347. //we assume that hero is already set and we want to choose most suitable one for the mission
  348. if (!g.hero)
  349. return 0;
  350. float output = 0;
  351. cb->setSelection (g.hero.h);
  352. int distance = cb->getDistance(g.tile); //at this point we already assume tile is reachable
  353. float missionImportance = 0;
  354. if (vstd::contains(ai->lockedHeroes, g.hero))
  355. missionImportance = ai->lockedHeroes[g.hero]->importanceWhenLocked();
  356. float strengthRatio = 100; //we are much stronger than enemy
  357. ui64 danger = evaluateDanger (g.tile, g.hero.h);
  358. if (danger)
  359. strengthRatio = g.hero.h->getTotalStrength() / danger;
  360. try
  361. {
  362. vt.strengthRatio->setInput (strengthRatio);
  363. vt.heroStrength->setInput (g.hero->getTotalStrength());
  364. vt.tileDistance->setInput (distance);
  365. vt.missionImportance->setInput (missionImportance);
  366. vt.movement->setInput(g.hero->movement);
  367. engine.process (VISIT_TILE);
  368. output = vt.value->output().defuzzify();
  369. }
  370. catch (fl::FuzzyException & fe)
  371. {
  372. logAi->errorStream() << "evaluate VisitTile " << fe.name() << ": " << fe.message();
  373. }
  374. return output;
  375. }
  376. float FuzzyHelper::evaluate (Goals::VisitHero & g)
  377. {
  378. auto obj = cb->getObj(ObjectInstanceID(g.objid)); //we assume for now that these goals are similiar
  379. return Goals::VisitTile(obj->pos).sethero(g.hero).setisAbstract(g.isAbstract).accept(this);
  380. //TODO: consider direct copy (constructor?)
  381. }
  382. float FuzzyHelper::evaluate (Goals::BuildThis & g)
  383. {
  384. return 1;
  385. }
  386. float FuzzyHelper::evaluate (Goals::DigAtTile & g)
  387. {
  388. return 0;
  389. }
  390. float FuzzyHelper::evaluate (Goals::CollectRes & g)
  391. {
  392. return 0;
  393. }
  394. float FuzzyHelper::evaluate (Goals::Build & g)
  395. {
  396. return 0;
  397. }
  398. float FuzzyHelper::evaluate (Goals::Invalid & g)
  399. {
  400. return -1e10;
  401. }
  402. float FuzzyHelper::evaluate (Goals::AbstractGoal & g)
  403. {
  404. logAi->debugStream() << boost::format("Cannot evaluate goal %s") % g.name();
  405. return -1e10;
  406. }