forked from voxnav/tyrant_optimize
-
Notifications
You must be signed in to change notification settings - Fork 30
/
tyrant_optimize.cpp
2076 lines (2029 loc) · 80.5 KB
/
tyrant_optimize.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
//------------------------------------------------------------------------------
//#define NDEBUG
#define BOOST_THREAD_USE_LIB
#include <cassert>
#include <chrono>
#include <cstring>
#include <ctime>
#include <functional>
#include <iostream>
#include <map>
#include <set>
#include <stack>
#include <string>
#include <tuple>
#include <vector>
#include <boost/algorithm/string.hpp>
#include <boost/filesystem.hpp>
#include <boost/lexical_cast.hpp>
#include <boost/math/distributions/binomial.hpp>
#include <boost/optional.hpp>
#include <boost/range/join.hpp>
#include <boost/thread/barrier.hpp>
#include <boost/thread/mutex.hpp>
#include <boost/thread/thread.hpp>
#include "card.h"
#include "cards.h"
#include "deck.h"
#include "read.h"
#include "sim.h"
#include "tyrant.h"
#include "xml.h"
struct Requirement
{
std::unordered_map<const Card*, unsigned> num_cards;
};
namespace {
gamemode_t gamemode{fight};
OptimizationMode optimization_mode{OptimizationMode::notset};
std::map<unsigned, unsigned> owned_cards;
bool use_owned_cards{true};
unsigned min_deck_len{1};
unsigned max_deck_len{10};
unsigned freezed_cards{0};
unsigned fund{0};
long double target_score{100};
long double min_increment_of_score{0};
long double confidence_level{0.99};
bool use_top_level_card{false};
unsigned use_fused_card_level{0};
bool show_ci{false};
bool use_harmonic_mean{false};
unsigned sim_seed{0};
Requirement requirement;
Quest quest;
}
using namespace std::placeholders;
//------------------------------------------------------------------------------
std::string card_id_name(const Card* card)
{
std::stringstream ios;
if(card)
{
ios << "[" << card->m_id << "] " << card->m_name;
}
else
{
ios << "-void-";
}
return ios.str();
}
std::string card_slot_id_names(const std::vector<std::pair<signed, const Card *>> card_list)
{
if (card_list.empty())
{
return "-void-";
}
std::stringstream ios;
std::string separator = "";
for (const auto & card_it : card_list)
{
ios << separator;
separator = ", ";
if (card_it.first >= 0)
{ ios << card_it.first << " "; }
ios << "[" << card_it.second->m_id << "] " << card_it.second->m_name;
}
return ios.str();
}
//------------------------------------------------------------------------------
Deck* find_deck(Decks& decks, const Cards& all_cards, std::string deck_name)
{
Deck* deck = decks.find_deck_by_name(deck_name);
if (deck != nullptr)
{
deck->resolve();
return(deck);
}
decks.decks.emplace_back(Deck{all_cards});
deck = &decks.decks.back();
deck->set(deck_name);
deck->resolve();
return(deck);
}
//---------------------- $80 deck optimization ---------------------------------
unsigned get_required_cards_before_upgrade(const std::vector<const Card *> & card_list, std::map<const Card*, unsigned> & num_cards)
{
unsigned deck_cost = 0;
std::set<const Card*> unresolved_cards;
for (const Card * card : card_list)
{
++ num_cards[card];
unresolved_cards.insert(card);
}
// un-upgrade only if fund is used
while (fund > 0 && !unresolved_cards.empty())
{
auto card_it = unresolved_cards.end();
auto card = *(-- card_it);
unresolved_cards.erase(card_it);
if ((use_fused_card_level > 0 && card->m_set == 1000 && card->m_rarity <= 2 && card->m_level == 1) || // assume unlimited common/rare level-1 cards (standard set) under endgame 1|2
(owned_cards[card->m_id] < num_cards[card] && !card->m_recipe_cards.empty()))
{
unsigned num_under = num_cards[card] - owned_cards[card->m_id];
num_cards[card] = owned_cards[card->m_id];
// std::cout << "-" << num_under << " " << card->m_name << "\n"; // XXX
deck_cost += num_under * card->m_recipe_cost;
for (auto recipe_it : card->m_recipe_cards)
{
num_cards[recipe_it.first] += num_under * recipe_it.second;
// std::cout << "+" << num_under * recipe_it.second << " " << recipe_it.first->m_name << "\n"; // XXX
unresolved_cards.insert(recipe_it.first);
}
}
}
// std::cout << "\n"; // XXX
return deck_cost;
}
unsigned get_deck_cost(const Deck * deck)
{
if (!use_owned_cards)
{ return 0; }
std::map<const Card *, unsigned> num_in_deck;
unsigned deck_cost = get_required_cards_before_upgrade({deck->commander}, num_in_deck);
deck_cost += get_required_cards_before_upgrade(deck->cards, num_in_deck);
for(auto it: num_in_deck)
{
unsigned card_id = it.first->m_id;
if (it.second > owned_cards[card_id])
{
return UINT_MAX;
}
}
return deck_cost;
}
// remove val from oppo if found, otherwise append val to self
template <typename C>
void append_unless_remove(C & self, C & oppo, typename C::const_reference val)
{
for (auto it = oppo.begin(); it != oppo.end(); ++ it)
{
if (*it == val)
{
oppo.erase(it);
return;
}
}
self.push_back(val);
}
// insert card at to_slot into deck limited by fund; store deck_cost
// return true if affordable
bool adjust_deck(Deck * deck, const signed from_slot, const signed to_slot, const Card * card, unsigned fund, std::mt19937 & re, unsigned & deck_cost,
std::vector<std::pair<signed, const Card *>> & cards_out, std::vector<std::pair<signed, const Card *>> & cards_in)
{
cards_in.clear();
if (card == nullptr)
{ // change commander or remove card
if (to_slot < 0)
{ // change commander
cards_in.emplace_back(-1, deck->commander);
}
deck_cost = get_deck_cost(deck);
return (deck_cost <= fund);
}
bool is_random = deck->strategy == DeckStrategy::random;
std::vector<const Card *> cards = deck->cards;
card = card->m_top_level_card;
{
// try to add new card into the deck, unfuse/downgrade it if necessary
std::stack<const Card *> candidate_cards;
candidate_cards.emplace(card);
while (! candidate_cards.empty())
{
const Card* card_in = candidate_cards.top();
candidate_cards.pop();
deck->cards.clear();
deck->cards.emplace_back(card_in);
deck_cost = get_deck_cost(deck);
if (use_top_level_card || deck_cost <= fund)
{ break; }
for (auto recipe_it : card_in->m_recipe_cards)
{ candidate_cards.emplace(recipe_it.first); }
}
if (deck_cost > fund)
{
return false;
}
cards_in.emplace_back(is_random ? -1 : to_slot, deck->cards[0]);
}
{
// try to add commander into the deck, unfuse/downgrade it if necessary
std::stack<const Card *> candidate_cards;
const Card * old_commander = deck->commander;
candidate_cards.emplace(deck->commander);
while (! candidate_cards.empty())
{
const Card* card_in = candidate_cards.top();
candidate_cards.pop();
deck->commander = card_in;
deck_cost = get_deck_cost(deck);
if (deck_cost <= fund)
{ break; }
for (auto recipe_it : card_in->m_recipe_cards)
{ candidate_cards.emplace(recipe_it.first); }
}
if (deck_cost > fund)
{
deck->commander = old_commander;
return false;
}
else if (deck->commander != old_commander)
{
append_unless_remove(cards_out, cards_in, {-1, old_commander});
append_unless_remove(cards_in, cards_out, {-1, deck->commander});
}
}
if (is_random)
{ std::shuffle(cards.begin(), cards.end(), re); }
for (signed i = 0; i < (signed)cards.size(); ++ i)
{
// try to add cards[i] into the deck, unfuse/downgrade it if necessary
auto saved_cards = deck->cards;
auto in_it = deck->cards.end() - (i < to_slot);
in_it = deck->cards.insert(in_it, nullptr);
std::stack<const Card *> candidate_cards;
candidate_cards.emplace(cards[i]);
while (! candidate_cards.empty())
{
const Card* card_in = candidate_cards.top();
candidate_cards.pop();
*in_it = card_in;
deck_cost = get_deck_cost(deck);
if (use_top_level_card || deck_cost <= fund)
{ break; }
if (i < (signed)freezed_cards)
{ return false; }
for (auto recipe_it : card_in->m_recipe_cards)
{ candidate_cards.emplace(recipe_it.first); }
}
if (deck_cost > fund)
{
append_unless_remove(cards_out, cards_in, {is_random ? -1 : i + (i >= to_slot), cards[i]});
deck->cards = saved_cards;
}
else if (*in_it != cards[i])
{
append_unless_remove(cards_out, cards_in, {is_random ? -1 : i + (i >= from_slot), cards[i]});
append_unless_remove(cards_in, cards_out, {is_random ? -1 : i + (i >= to_slot), *in_it});
}
}
deck_cost = get_deck_cost(deck);
return !cards_in.empty() || !cards_out.empty();
}
unsigned check_requirement(const Deck* deck, const Requirement & requirement, const Quest & quest)
{
unsigned gap = 0;
if (!requirement.num_cards.empty())
{
std::unordered_map<const Card*, unsigned> num_cards;
num_cards[deck->commander] = 1;
for (auto card: deck->cards)
{
++ num_cards[card];
}
for (auto it: requirement.num_cards)
{
gap += safe_minus(it.second, num_cards[it.first]);
}
}
if (quest.quest_type != QuestType::none)
{
unsigned potential_value = 0;
switch (quest.quest_type)
{
case QuestType::skill_use:
case QuestType::skill_damage:
for (const auto & ss: deck->commander->m_skills)
{
if (quest.quest_key == ss.id)
{
potential_value = quest.quest_value;
break;
}
}
break;
case QuestType::faction_assault_card_kill:
case QuestType::type_card_kill:
potential_value = quest.quest_value;
break;
default:
break;
}
for (auto card: deck->cards)
{
switch (quest.quest_type)
{
case QuestType::skill_use:
case QuestType::skill_damage:
for (const auto & ss: card->m_skills)
{
if (quest.quest_key == ss.id)
{
potential_value = quest.quest_value;
break;
}
}
break;
case QuestType::faction_assault_card_use:
potential_value += (quest.quest_key == card->m_faction);
break;
case QuestType::type_card_use:
potential_value += (quest.quest_key == card->m_type);
break;
default:
break;
}
if (potential_value >= (quest.must_fulfill ? quest.quest_value : 1))
{
break;
}
}
gap += safe_minus(quest.must_fulfill ? quest.quest_value : 1, potential_value);
}
return gap;
}
void claim_cards(const std::vector<const Card*> & card_list)
{
std::map<const Card *, unsigned> num_cards;
get_required_cards_before_upgrade(card_list, num_cards);
for(const auto & it: num_cards)
{
const Card * card = it.first;
unsigned num_to_claim = safe_minus(it.second, owned_cards[card->m_id]);
if(num_to_claim > 0)
{
owned_cards[card->m_id] += num_to_claim;
if (debug_print >= 0)
{
std::cerr << "WARNING: Need extra " << num_to_claim << " " << card->m_name << " to build your initial deck: adding to owned card list.\n";
}
}
}
}
//------------------------------------------------------------------------------
FinalResults<long double> compute_score(const EvaluatedResults& results, std::vector<long double>& factors)
{
FinalResults<long double> final{0, 0, 0, 0, 0, 0, results.second};
long double max_possible = max_possible_score[(size_t)optimization_mode];
for (unsigned index(0); index < results.first.size(); ++index)
{
final.wins += results.first[index].wins * factors[index];
final.draws += results.first[index].draws * factors[index];
final.losses += results.first[index].losses * factors[index];
auto lower_bound = boost::math::binomial_distribution<>::find_lower_bound_on_p(results.second, results.first[index].points / max_possible, 1 - confidence_level) * max_possible;
auto upper_bound = boost::math::binomial_distribution<>::find_upper_bound_on_p(results.second, results.first[index].points / max_possible, 1 - confidence_level) * max_possible;
if (use_harmonic_mean)
{
final.points += factors[index] / results.first[index].points;
final.points_lower_bound += factors[index] / lower_bound;
final.points_upper_bound += factors[index] / upper_bound;
}
else
{
final.points += results.first[index].points * factors[index];
final.points_lower_bound += lower_bound * factors[index];
final.points_upper_bound += upper_bound * factors[index];
}
}
long double factor_sum = std::accumulate(factors.begin(), factors.end(), 0.);
final.wins /= factor_sum * (long double)results.second;
final.draws /= factor_sum * (long double)results.second;
final.losses /= factor_sum * (long double)results.second;
if (use_harmonic_mean)
{
final.points = factor_sum / ((long double)results.second * final.points);
final.points_lower_bound = factor_sum / final.points_lower_bound;
final.points_upper_bound = factor_sum / final.points_upper_bound;
}
else
{
final.points /= factor_sum * (long double)results.second;
final.points_lower_bound /= factor_sum;
final.points_upper_bound /= factor_sum;
}
return final;
}
//------------------------------------------------------------------------------
volatile unsigned thread_num_iterations{0}; // written by threads
EvaluatedResults *thread_results{nullptr}; // written by threads
volatile const FinalResults<long double> *thread_best_results{nullptr};
volatile bool thread_compare{false};
volatile bool thread_compare_stop{false}; // written by threads
volatile bool destroy_threads;
//------------------------------------------------------------------------------
// Per thread data.
// seed should be unique for each thread.
// d1 and d2 are intended to point to read-only process-wide data.
struct SimulationData
{
std::mt19937 re;
const Cards& cards;
const Decks& decks;
std::shared_ptr<Deck> your_deck;
Hand your_hand;
std::vector<std::shared_ptr<Deck>> enemy_decks;
std::vector<Hand*> enemy_hands;
std::vector<long double> factors;
gamemode_t gamemode;
Quest quest;
std::unordered_map<unsigned, unsigned> bg_effects;
std::vector<SkillSpec> your_bg_skills, enemy_bg_skills;
SimulationData(unsigned seed, const Cards& cards_, const Decks& decks_, unsigned num_enemy_decks_, std::vector<long double> factors_, gamemode_t gamemode_, Quest & quest_,
std::unordered_map<unsigned, unsigned>& bg_effects_, std::vector<SkillSpec>& your_bg_skills_, std::vector<SkillSpec>& enemy_bg_skills_) :
re(seed),
cards(cards_),
decks(decks_),
your_deck(),
your_hand(nullptr),
enemy_decks(num_enemy_decks_),
factors(factors_),
gamemode(gamemode_),
quest(quest_),
bg_effects(bg_effects_),
your_bg_skills(your_bg_skills_),
enemy_bg_skills(enemy_bg_skills_)
{
for (size_t i = 0; i < num_enemy_decks_; ++i)
{
enemy_hands.emplace_back(new Hand(nullptr));
}
}
~SimulationData()
{
for(auto hand: enemy_hands) { delete(hand); }
}
void set_decks(const Deck* const your_deck_, std::vector<Deck*> const & enemy_decks_)
{
your_deck.reset(your_deck_->clone());
your_hand.deck = your_deck.get();
for(unsigned i(0); i < enemy_decks_.size(); ++i)
{
enemy_decks[i].reset(enemy_decks_[i]->clone());
enemy_hands[i]->deck = enemy_decks[i].get();
}
}
inline std::vector<Results<uint64_t>> evaluate()
{
std::vector<Results<uint64_t>> res;
for(Hand* enemy_hand: enemy_hands)
{
your_hand.reset(re);
enemy_hand->reset(re);
Field fd(re, cards, your_hand, *enemy_hand, gamemode, optimization_mode, quest, bg_effects, your_bg_skills, enemy_bg_skills);
Results<uint64_t> result(play(&fd));
res.emplace_back(result);
}
return(res);
}
};
//------------------------------------------------------------------------------
class Process;
void thread_evaluate(boost::barrier& main_barrier,
boost::mutex& shared_mutex,
SimulationData& sim,
const Process& p,
unsigned thread_id);
//------------------------------------------------------------------------------
class Process
{
public:
unsigned num_threads;
std::vector<boost::thread*> threads;
std::vector<SimulationData*> threads_data;
boost::barrier main_barrier;
boost::mutex shared_mutex;
const Cards& cards;
const Decks& decks;
Deck* your_deck;
const std::vector<Deck*> enemy_decks;
std::vector<long double> factors;
gamemode_t gamemode;
Quest quest;
std::unordered_map<unsigned, unsigned> bg_effects;
std::vector<SkillSpec> your_bg_skills, enemy_bg_skills;
Process(unsigned num_threads_, const Cards& cards_, const Decks& decks_, Deck* your_deck_, std::vector<Deck*> enemy_decks_, std::vector<long double> factors_, gamemode_t gamemode_, Quest & quest_,
std::unordered_map<unsigned, unsigned>& bg_effects_, std::vector<SkillSpec>& your_bg_skills_, std::vector<SkillSpec>& enemy_bg_skills_) :
num_threads(num_threads_),
main_barrier(num_threads+1),
cards(cards_),
decks(decks_),
your_deck(your_deck_),
enemy_decks(enemy_decks_),
factors(factors_),
gamemode(gamemode_),
quest(quest_),
bg_effects(bg_effects_),
your_bg_skills(your_bg_skills_),
enemy_bg_skills(enemy_bg_skills_)
{
destroy_threads = false;
unsigned seed(sim_seed ? sim_seed : std::chrono::system_clock::now().time_since_epoch().count() * 2654435761); // Knuth multiplicative hash
if (num_threads_ == 1)
{
std::cout << "RNG seed " << seed << std::endl;
}
for(unsigned i(0); i < num_threads; ++i)
{
threads_data.push_back(new SimulationData(seed + i, cards, decks, enemy_decks.size(), factors, gamemode, quest, bg_effects, your_bg_skills, enemy_bg_skills));
threads.push_back(new boost::thread(thread_evaluate, std::ref(main_barrier), std::ref(shared_mutex), std::ref(*threads_data.back()), std::ref(*this), i));
}
}
~Process()
{
destroy_threads = true;
main_barrier.wait();
for(auto thread: threads) { thread->join(); }
for(auto data: threads_data) { delete(data); }
}
EvaluatedResults & evaluate(unsigned num_iterations, EvaluatedResults & evaluated_results)
{
if (num_iterations <= evaluated_results.second)
{
return evaluated_results;
}
thread_num_iterations = num_iterations - evaluated_results.second;
thread_results = &evaluated_results;
thread_compare = false;
// unlock all the threads
main_barrier.wait();
// wait for the threads
main_barrier.wait();
return evaluated_results;
}
EvaluatedResults & compare(unsigned num_iterations, EvaluatedResults & evaluated_results, const FinalResults<long double> & best_results)
{
if (num_iterations <= evaluated_results.second)
{
return evaluated_results;
}
thread_num_iterations = num_iterations - evaluated_results.second;
thread_results = &evaluated_results;
thread_best_results = &best_results;
thread_compare = true;
thread_compare_stop = false;
// unlock all the threads
main_barrier.wait();
// wait for the threads
main_barrier.wait();
return evaluated_results;
}
};
//------------------------------------------------------------------------------
void thread_evaluate(boost::barrier& main_barrier,
boost::mutex& shared_mutex,
SimulationData& sim,
const Process& p,
unsigned thread_id)
{
while(true)
{
main_barrier.wait();
sim.set_decks(p.your_deck, p.enemy_decks);
if(destroy_threads)
{ return; }
while(true)
{
shared_mutex.lock(); //<<<<
if(thread_num_iterations == 0 || (thread_compare && thread_compare_stop)) //!
{
shared_mutex.unlock(); //>>>>
main_barrier.wait();
break;
}
else
{
--thread_num_iterations; //!
shared_mutex.unlock(); //>>>>
std::vector<Results<uint64_t>> result{sim.evaluate()};
shared_mutex.lock(); //<<<<
std::vector<uint64_t> thread_score_local(thread_results->first.size(), 0u); //!
for(unsigned index(0); index < result.size(); ++index)
{
thread_results->first[index] += result[index]; //!
thread_score_local[index] = thread_results->first[index].points; //!
}
++thread_results->second; //!
unsigned thread_total_local{thread_results->second}; //!
shared_mutex.unlock(); //>>>>
if(thread_compare && thread_id == 0 && thread_total_local > 1)
{
unsigned score_accum = 0;
// Multiple defense decks case: scaling by factors and approximation of a "discrete" number of events.
if(result.size() > 1)
{
long double score_accum_d = 0.0;
for(unsigned i = 0; i < thread_score_local.size(); ++i)
{
score_accum_d += thread_score_local[i] * sim.factors[i];
}
score_accum_d /= std::accumulate(sim.factors.begin(), sim.factors.end(), .0);
score_accum = score_accum_d;
}
else
{
score_accum = thread_score_local[0];
}
bool compare_stop(false);
long double max_possible = max_possible_score[(size_t)optimization_mode];
// Get a loose (better than no) upper bound. TODO: Improve it.
compare_stop = (boost::math::binomial_distribution<>::find_upper_bound_on_p(thread_total_local, score_accum / max_possible, 1 - confidence_level) * max_possible <
thread_best_results->points + min_increment_of_score);
if(compare_stop)
{
shared_mutex.lock(); //<<<<
//std::cout << thread_total_local << "\n";
thread_compare_stop = true; //!
shared_mutex.unlock(); //>>>>
}
}
}
}
}
}
//------------------------------------------------------------------------------
void print_score_info(const EvaluatedResults& results, std::vector<long double>& factors)
{
auto final = compute_score(results, factors);
std::cout << final.points << " (";
if (show_ci)
{
std::cout << final.points_lower_bound << "-" << final.points_upper_bound << ", ";
}
for(const auto & val: results.first)
{
switch(optimization_mode)
{
case OptimizationMode::raid:
case OptimizationMode::campaign:
case OptimizationMode::brawl:
case OptimizationMode::war:
case OptimizationMode::quest:
std::cout << val.points << " ";
break;
default:
std::cout << val.points / 100 << " ";
break;
}
}
std::cout << "/ " << results.second << ")" << std::endl;
}
//------------------------------------------------------------------------------
void print_results(const EvaluatedResults& results, std::vector<long double>& factors)
{
auto final = compute_score(results, factors);
std::cout << "win%: " << final.wins * 100.0 << " (";
for (const auto & val : results.first)
{
std::cout << val.wins << " ";
}
std::cout << "/ " << results.second << ")" << std::endl;
std::cout << "stall%: " << final.draws * 100.0 << " (";
for (const auto & val : results.first)
{
std::cout << val.draws << " ";
}
std::cout << "/ " << results.second << ")" << std::endl;
std::cout << "loss%: " << final.losses * 100.0 << " (";
for (const auto & val : results.first)
{
std::cout << val.losses << " ";
}
std::cout << "/ " << results.second << ")" << std::endl;
if (optimization_mode == OptimizationMode::quest)
{
// points = win% * win_score + (must_win ? win% : 100%) * quest% * quest_score
// quest% = (points - win% * win_score) / (must_win ? win% : 100%) / quest_score
std::cout << "quest%: " << (final.points - final.wins * quest.win_score) / (quest.must_win ? final.wins : 1) / quest.quest_score * 100 << std::endl;
}
switch(optimization_mode)
{
case OptimizationMode::raid:
case OptimizationMode::campaign:
case OptimizationMode::brawl:
case OptimizationMode::war:
case OptimizationMode::quest:
std::cout << "score: " << final.points << " (";
for(const auto & val: results.first)
{
std::cout << val.points << " ";
}
std::cout << "/ " << results.second << ")" << std::endl;
if (show_ci)
{
std::cout << "ci: " << final.points_lower_bound << " - " << final.points_upper_bound << std::endl;
}
break;
default:
break;
}
}
//------------------------------------------------------------------------------
void print_deck_inline(const unsigned deck_cost, const FinalResults<long double> score, Deck * deck)
{
std::cout << deck->cards.size() << " units: ";
if(fund > 0)
{
std::cout << "$" << deck_cost << " ";
}
switch(optimization_mode)
{
case OptimizationMode::raid:
case OptimizationMode::campaign:
case OptimizationMode::brawl:
case OptimizationMode::war:
case OptimizationMode::quest:
std::cout << "(" << score.wins * 100 << "% win";
if (optimization_mode == OptimizationMode::quest)
{
std::cout << ", " << (score.points - score.wins * quest.win_score) / (quest.must_win ? score.wins : 1) / quest.quest_score * 100 << "% quest";
}
if (show_ci)
{
std::cout << ", " << score.points_lower_bound << "-" << score.points_upper_bound;
}
std::cout << ") ";
break;
case OptimizationMode::defense:
std::cout << "(" << score.draws * 100.0 << "% stall) ";
break;
default:
break;
}
std::cout << score.points << ": " << deck->commander->m_name;
if (deck->strategy == DeckStrategy::random)
{
std::sort(deck->cards.begin(), deck->cards.end(), [](const Card* a, const Card* b) { return a->m_id < b->m_id; });
}
std::string last_name;
unsigned num_repeat(0);
for(const Card* card: deck->cards)
{
if(card->m_name == last_name)
{
++ num_repeat;
}
else
{
if(num_repeat > 1)
{
std::cout << " #" << num_repeat;
}
std::cout << ", " << card->m_name;
last_name = card->m_name;
num_repeat = 1;
}
}
if(num_repeat > 1)
{
std::cout << " #" << num_repeat;
}
std::cout << std::endl;
}
//------------------------------------------------------------------------------
void hill_climbing(unsigned num_min_iterations, unsigned num_iterations, Deck* d1, Process& proc, Requirement & requirement, Quest & quest)
{
EvaluatedResults zero_results = { EvaluatedResults::first_type(proc.enemy_decks.size()), 0 };
auto best_deck = d1->hash();
std::map<std::string, EvaluatedResults> evaluated_decks{{best_deck, zero_results}};
EvaluatedResults & results = proc.evaluate(num_min_iterations, evaluated_decks.begin()->second);
print_score_info(results, proc.factors);
auto current_score = compute_score(results, proc.factors);
auto best_score = current_score;
// Non-commander cards
auto non_commander_cards = proc.cards.player_assaults;
non_commander_cards.insert(non_commander_cards.end(), proc.cards.player_structures.begin(), proc.cards.player_structures.end());
non_commander_cards.insert(non_commander_cards.end(), std::initializer_list<Card*>{NULL,});
const Card* best_commander = d1->commander;
std::vector<const Card*> best_cards = d1->cards;
unsigned deck_cost = get_deck_cost(d1);
fund = std::max(fund, deck_cost);
print_deck_inline(deck_cost, best_score, d1);
std::mt19937 & re = proc.threads_data[0]->re;
unsigned best_gap = check_requirement(d1, requirement, quest);
bool deck_has_been_improved = true;
unsigned long skipped_simulations = 0;
std::vector<std::pair<signed, const Card *>> cards_out, cards_in;
for(unsigned slot_i(0), dead_slot(0); ; slot_i = (slot_i + 1) % std::min<unsigned>(max_deck_len, best_cards.size() + 1))
{
if (deck_has_been_improved)
{
dead_slot = slot_i;
deck_has_been_improved = false;
}
else if (slot_i == dead_slot || best_score.points - target_score > -1e-9)
{
if (best_score.n_sims >= num_iterations || best_gap > 0)
{
break;
}
auto & prev_results = evaluated_decks[best_deck];
skipped_simulations += prev_results.second;
// Re-evaluate the best deck
auto evaluate_result = proc.evaluate(std::min(prev_results.second * 10, num_iterations), prev_results);
best_score = compute_score(evaluate_result, proc.factors);
std::cout << "Results refined: ";
print_score_info(evaluate_result, proc.factors);
dead_slot = slot_i;
}
if (best_score.points - target_score > -1e-9)
{
continue;
}
if (requirement.num_cards.count(best_commander) == 0)
{
for(const Card* commander_candidate: proc.cards.player_commanders)
{
// Various checks to check if the card is accepted
assert(commander_candidate->m_type == CardType::commander);
if (commander_candidate->m_name == best_commander->m_name)
{ continue; }
d1->cards = best_cards;
// Place it in the deck and restore other cards
cards_out.clear();
cards_out.emplace_back(-1, best_commander);
cards_out = {{-1, best_commander}};
d1->commander = commander_candidate;
if (! adjust_deck(d1, -1, -1, nullptr, fund, re, deck_cost, cards_out, cards_in))
{ continue; }
unsigned new_gap = check_requirement(d1, requirement, quest);
if (new_gap > 0 && new_gap >= best_gap)
{ continue; }
auto && cur_deck = d1->hash();
auto && emplace_rv = evaluated_decks.insert({cur_deck, zero_results});
auto & prev_results = emplace_rv.first->second;
if (!emplace_rv.second)
{
skipped_simulations += prev_results.second;
}
// Evaluate new deck
auto compare_results = proc.compare(best_score.n_sims, prev_results, best_score);
current_score = compute_score(compare_results, proc.factors);
// Is it better ?
if (new_gap < best_gap || current_score.points > best_score.points + min_increment_of_score)
{
// Then update best score/commander, print stuff
std::cout << "Deck improved: " << d1->hash() << ": " << card_slot_id_names(cards_out) << " -> " << card_slot_id_names(cards_in) << ": ";
best_gap = new_gap;
best_score = current_score;
best_deck = cur_deck;
best_commander = d1->commander;
best_cards = d1->cards;
deck_has_been_improved = true;
print_score_info(compare_results, proc.factors);
print_deck_inline(deck_cost, best_score, d1);
}
}
// Now that all commanders are evaluated, take the best one
d1->commander = best_commander;
d1->cards = best_cards;
}
std::shuffle(non_commander_cards.begin(), non_commander_cards.end(), re);
for(const Card* card_candidate: non_commander_cards)
{
if (card_candidate && (card_candidate->m_fusion_level < use_fused_card_level || (use_top_level_card && card_candidate->m_level < card_candidate->m_top_level_card->m_level)))
{ continue; }
d1->commander = best_commander;
d1->cards = best_cards;
if (card_candidate ?
(slot_i < best_cards.size() && card_candidate->m_name == best_cards[slot_i]->m_name) // Omega -> Omega
:
(slot_i == best_cards.size())) // void -> void
{ continue; }
cards_out.clear();
if (slot_i < d1->cards.size())
{
cards_out.emplace_back(-1, d1->cards[slot_i]);
d1->cards.erase(d1->cards.begin() + slot_i);
}
if (! adjust_deck(d1, slot_i, slot_i, card_candidate, fund, re, deck_cost, cards_out, cards_in) ||
d1->cards.size() < min_deck_len)
{ continue; }
unsigned new_gap = check_requirement(d1, requirement, quest);
if (new_gap > 0 && new_gap >= best_gap)
{ continue; }
auto && cur_deck = d1->hash();
auto && emplace_rv = evaluated_decks.insert({cur_deck, zero_results});
auto & prev_results = emplace_rv.first->second;
if (!emplace_rv.second)
{
skipped_simulations += prev_results.second;
}
// Evaluate new deck
auto compare_results = proc.compare(best_score.n_sims, prev_results, best_score);
current_score = compute_score(compare_results, proc.factors);
// Is it better ?
if (new_gap < best_gap || current_score.points > best_score.points + min_increment_of_score)
{
// Then update best score/slot, print stuff
std::cout << "Deck improved: " << d1->hash() << ": " << card_slot_id_names(cards_out) << " -> " << card_slot_id_names(cards_in) << ": ";
best_gap = new_gap;
best_score = current_score;
best_deck = cur_deck;
best_commander = d1->commander;
best_cards = d1->cards;
deck_has_been_improved = true;
print_score_info(compare_results, proc.factors);
print_deck_inline(deck_cost, best_score, d1);
}
if(best_score.points - target_score > -1e-9)
{ break; }
}
d1->commander = best_commander;
d1->cards = best_cards;
}
unsigned simulations = 0;
for(auto evaluation: evaluated_decks)
{ simulations += evaluation.second.second; }
std::cout << "Evaluated " << evaluated_decks.size() << " decks (" << simulations << " + " << skipped_simulations << " simulations)." << std::endl;
std::cout << "Optimized Deck: ";
print_deck_inline(get_deck_cost(d1), best_score, d1);
}
//------------------------------------------------------------------------------
void hill_climbing_ordered(unsigned num_min_iterations, unsigned num_iterations, Deck* d1, Process& proc, Requirement & requirement, Quest & quest)
{
EvaluatedResults zero_results = { EvaluatedResults::first_type(proc.enemy_decks.size()), 0 };
auto best_deck = d1->hash();
std::map<std::string, EvaluatedResults> evaluated_decks{{best_deck, zero_results}};
EvaluatedResults & results = proc.evaluate(num_min_iterations, evaluated_decks.begin()->second);
print_score_info(results, proc.factors);
auto current_score = compute_score(results, proc.factors);
auto best_score = current_score;
// Non-commander cards
auto non_commander_cards = proc.cards.player_assaults;
non_commander_cards.insert(non_commander_cards.end(), proc.cards.player_structures.begin(), proc.cards.player_structures.end());
non_commander_cards.insert(non_commander_cards.end(), std::initializer_list<Card*>{NULL,});
const Card* best_commander = d1->commander;
std::vector<const Card*> best_cards = d1->cards;
unsigned deck_cost = get_deck_cost(d1);
fund = std::max(fund, deck_cost);
print_deck_inline(deck_cost, best_score, d1);
std::mt19937 & re = proc.threads_data[0]->re;
unsigned best_gap = check_requirement(d1, requirement, quest);
bool deck_has_been_improved = true;
unsigned long skipped_simulations = 0;
std::vector<std::pair<signed, const Card *>> cards_out, cards_in;
for(unsigned from_slot(freezed_cards), dead_slot(freezed_cards); ; from_slot = (from_slot + 1) % std::min<unsigned>(max_deck_len, d1->cards.size() + 1))
{
if (from_slot < freezed_cards)