-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathSimpleParameterOptimizer.cpp
More file actions
729 lines (614 loc) · 26 KB
/
Copy pathSimpleParameterOptimizer.cpp
File metadata and controls
729 lines (614 loc) · 26 KB
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
// SimpleParameterOptimizer_GA.cpp
// シンプルさを保ったまま遺伝的アルゴリズム(GA)へ置き換える実装
// ファイル丸ごと置換用。ヘッダ SimpleParameterOptimizer.h は既に存在する前提。
// コンパイラ: C++17
#if defined(OPTIMIZE_MODE)
#include "SimpleParameterOptimizer.h"
#include "ActionOptimizer.h"
#include "BattleEmulator.h"
#include "Player.h"
#include "Genome.h"
#include <array>
#include <vector>
#include <iostream>
#include <sstream>
#include <cmath>
#include <algorithm>
#include <random>
#include <chrono>
#include <future>
#include <limits>
#include <string>
#include <cstdint>
static void appendUniqueTuneId(std::vector<int> &values, int id) {
if (std::find(values.begin(), values.end(), id) == values.end()) {
values.push_back(id);
}
}
static const std::vector<int>& getTuneIds() {
static const std::vector<int> tuneIds = [] {
std::vector<int> values;
values.reserve(64);
const int allyAndEventIds[] = {
BattleEmulator::SPECIAL_MEDICINE,
BattleEmulator::SPECIAL_ANTIDOTE,
BattleEmulator::FLEE_ALLY,
BattleEmulator::DRAGON_SLASH,
BattleEmulator::HEAL,
BattleEmulator::CRACK_ALLY,
BattleEmulator::WOOSH_ALLY,
BattleEmulator::ATTACK_ALLY,
BattleEmulator::DEFENCE,
BattleEmulator::ACROBATIC_STAR,
BattleEmulator::ACROBATSTAR_KAIHI,
BattleEmulator::COUNTER,
};
for (int id : allyAndEventIds) {
appendUniqueTuneId(values, id);
}
for (int id : BattleEmulator::EnemyActionCandidates) {
appendUniqueTuneId(values, id);
}
const int parameterIds[] = {
SimpleParameterOptimizerNode::turnHeignt,
SimpleParameterOptimizerNode::enemyHpWeight,
SimpleParameterOptimizerNode::playerHpWeight,
SimpleParameterOptimizerNode::resourceWeight,
SimpleParameterOptimizerNode::StatusEffectWeight,
SimpleParameterOptimizerNode::paralysisWeight,
SimpleParameterOptimizerNode::sleepWeight,
SimpleParameterOptimizerNode::poisonWeight,
SimpleParameterOptimizerNode::inactiveWeight,
SimpleParameterOptimizerNode::SpHeight,
SimpleParameterOptimizerNode::ActHeight,
SimpleParameterOptimizerNode::ResourceHPCost,
SimpleParameterOptimizerNode::SpecialMedicineCost,
SimpleParameterOptimizerNode::NoResourceCost,
SimpleParameterOptimizerNode::SpecialAntiCost,
SimpleParameterOptimizerNode::speedLevelWeight,
SimpleParameterOptimizerNode::BuffWeight,
};
for (int id : parameterIds) {
appendUniqueTuneId(values, id);
}
return values;
}();
return tuneIds;
}
// action cost テーブル(一次真実源)
static thread_local std::array<double, MAX_ACTION_ID> s_actionCosts;
// --- 安定性チェック用: actions をコピーしてランダム挿入する(本体 actions は汚さない) ---
template <size_t N>
static int buildActionsWithRandomInserts(
const int srcActions[350],
int dstActions[350],
std::mt19937 &rng,
const std::array<int, N> &pool,
int maxInserts,
double insertProb,
std::string *outInsertedSummary // nullptr 可
) {
// src をコピー & 長さ測定
int len = 0;
for (; len < 350; ++len) {
dstActions[len] = srcActions[len];
if (srcActions[len] == -1) break;
}
if (len == 350) {
// 念のため終端を保証
dstActions[349] = -1;
len = 349;
}
if (maxInserts <= 0 || N == 0 || insertProb <= 0.0) {
if (outInsertedSummary) *outInsertedSummary = "";
return len;
}
std::uniform_real_distribution<double> uni01(0.0, 1.0);
std::uniform_int_distribution<int> pickAction(0, static_cast<int>(N) - 1);
std::ostringstream oss;
int inserted = 0;
// 「-1」を含まない実データ長(挿入位置計算に使う)
int dataLen = 0;
while (dataLen < 350 && dstActions[dataLen] != -1) ++dataLen;
for (int k = 0; k < maxInserts; ++k) {
if (uni01(rng) > insertProb) continue;
if (dataLen >= 349) break; // これ以上挿入すると -1 が置けない
const int actionToInsert = pool[pickAction(rng)];
std::uniform_int_distribution<int> pickPos(0, dataLen);
const int pos = pickPos(rng);
// 右に1つずらして挿入
for (int i = std::min(349, dataLen); i > pos; --i) {
dstActions[i] = dstActions[i - 1];
}
dstActions[pos] = actionToInsert;
++dataLen;
dstActions[dataLen] = -1;
if (inserted > 0) oss << ", ";
oss << BattleEmulator::getActionName(actionToInsert) << "@idx" << pos;
++inserted;
}
if (outInsertedSummary) *outInsertedSummary = oss.str();
return dataLen;
}
// --- ヘルパ関数 ---
static void initActionCostsIfNeeded() {
thread_local static bool inited = false;
if (inited) return;
for (int i = 0; i < MAX_ACTION_ID; ++i) s_actionCosts[i] = DEFAULT_ACTION_COST;
inited = true;
}
static inline double clampDouble(double v, double lo, double hi) {
if (v < lo) return lo;
if (v > hi) return hi;
return v;
}
static inline void applyActionCostsToCostParams() {
// ユーザ環境に依存するため、ここで s_actionCosts の各 index を
// CostParams の静的メンバへ割り当てる実装を追加してください。
// 例: CostParams::someWeight = s_actionCosts[SomeId];
}
double SimpleParameterOptimizer::getActionCost(int action) {
if (action < 0 || action >= MAX_ACTION_ID) {
throw std::invalid_argument("Invalid action ID");
}
return s_actionCosts[action];
}
// --- 新: evaluateGenome を uint64_t にして最小値を採用 ---
// 戻り値: fitness (小さいほど良い)
// fitness のフォーマット: turns * 1_000_000 + ms_int
// measuredTurns/outMs は best(最小 fitness)だった時の値を返す
static uint64_t evaluateGenome(
GAGenome &g,
const Player players[2],
const std::array<uint64_t, GA_EVAL_SEEDS> &evalSeeds,
const int actions[350],
int turnsLimit,
std::mt19937 &rng,
int &outTurns,
double &outMs
) {
// genes を s_actionCosts に適用(評価時のみ)
auto backup = s_actionCosts;
const auto &tuneIds = getTuneIds();
for (size_t i = 0; i < g.genes.size(); ++i) {
int aid = tuneIds[i];
if (aid >= 0 && aid < MAX_ACTION_ID) s_actionCosts[aid] = g.genes[i];
}
long long totalTurns = 0;
double totalMs = 0.0;
uint64_t totalFitness = 0.0;
for (int i = 0; i < GA_EVAL_SEEDS; ++i) {
const uint64_t seedToUse = evalSeeds[i];
auto t0 = std::chrono::high_resolution_clock::now();
int measuredTurn = SimpleParameterOptimizer::testParameters(players, seedToUse, actions, turnsLimit);
auto t1 = std::chrono::high_resolution_clock::now();
std::chrono::duration<double, std::milli> elapsed = t1 - t0;
totalTurns += measuredTurn;
totalMs += elapsed.count();
// fitness の作り方(既存ロジックを seed ごとに適用して足し算)
totalFitness += static_cast<uint64_t>(measuredTurn) * 1000ull + static_cast<uint64_t>(elapsed.count() * 1000);
}
outTurns = static_cast<int>(totalTurns);
outMs = totalMs;
// restore
s_actionCosts = backup;
return totalFitness;
}
// --- 遺伝子ダンプ: improvement 時に呼ぶ ---
static void dumpGenome(const GAGenome &g, uint64_t bestTurn) {
constexpr int MAX_ID = 200;
std::vector<double> tmp(MAX_ID + 1, 0.0);
const auto &tuneIds = getTuneIds();
for (size_t i = 0; i < g.genes.size(); ++i) {
int id = tuneIds[i];
if (id >= 0 && id <= MAX_ID) tmp[id] = g.genes[i];
}
std::cout << "[GA] improvement bestTurn=" << bestTurn << " -> genome dump:\n";
std::cout << "constexpr std::array<double, " << (MAX_ID + 1) << "> GENOME = {\n";
bool prevWasNonZero = false;
bool needIndent = false;
for (int id = 0; id <= MAX_ID; ++id) {
if (tmp[id] != 0.0 && prevWasNonZero) {
std::cout << "\n";
needIndent = true;
}
if (tmp[id] != 0.0) {
std::cout << " /* " << id << " */ " << tmp[id];
} else {
if (needIndent) {
std::cout << " ";
needIndent = false;
}
std::cout << "0.0";
}
if (id != MAX_ID) std::cout << ",";
if (tmp[id] != 0.0) {
std::cout << "\n";
prevWasNonZero = false;
needIndent = true;
} else {
prevWasNonZero = true;
}
}
std::cout << "\n};\n" << std::endl;
}
OptimResult SimpleParameterOptimizer::optimize(const Player players[2], uint64_t seed,
const int actions[350], int maxTests, int turns)
{
initActionCostsIfNeeded();
OptimResult result;
result.bestTurn = 9999999;
result.testCount = 0;
result.found = false;
// snapshot
std::vector<double> originalCosts(MAX_ACTION_ID);
for (int i = 0; i < MAX_ACTION_ID; ++i) originalCosts[i] = s_actionCosts[i];
applyActionCostsToCostParams();
std::cout << "[SimpleParameterOptimizer GA] initial turn " << std::endl;
// GA 初期化
std::random_device rd;
std::mt19937 rng(static_cast<uint32_t>(seed ^ rd()));
const auto &tuneIds = getTuneIds();
const size_t geneCount = tuneIds.size();
// // ★ 追加:評価用 seed 生成関数(世代内で固定に使う)
// auto makeEvalSeeds = [&](uint64_t base) {
// std::array<uint64_t, GA_EVAL_SEEDS> s{};
// s[0] = base;
// s[1] = 0x1022ULL; // 波動2連パターンを必ず含める
// s[2] = 0x1094ull; // 波動2連パターンを必ず含める
// s[3] = 0x1040ull; // 波動2連パターンを必ず含める
// s[4] = 0x1045ull; // 波動2連パターンを必ず含める
// s[5] = 0x1069ull; // 波動2連パターンを必ず含める
// s[6] = 0x11029ull; // 波動2連パターンを必ず含める
//
// for (int i = 7; i < GA_EVAL_SEEDS; ++i) {
// uint64_t r1 = static_cast<uint64_t>(rng());
// uint64_t r2 = static_cast<uint64_t>(rng());
// s[i] = base ^ (r1 << 32) ^ r2 ^ (0x9E3779B97F4A7C15ULL * static_cast<uint64_t>(i));
// }
//
// return s;
// };
// ★ 追加:評価用 seed 生成関数(世代内で固定に使う)
auto makeEvalSeeds = [&](uint64_t base) {
std::array<uint64_t, GA_EVAL_SEEDS> s{};
s[0] = base;
for (int i = 1; i < GA_EVAL_SEEDS; ++i) {
uint64_t r1 = static_cast<uint64_t>(rng());
uint64_t r2 = static_cast<uint64_t>(rng());
s[i] = base ^ (r1 << 32) ^ r2 ^ (0x9E3779B97F4A7C15ULL * static_cast<uint64_t>(i));
}
return s;
};
std::array<uint64_t, GA_EVAL_SEEDS> evalSeeds = makeEvalSeeds(seed);
// population 初期化: 現状値を中心にランダム化
std::vector<GAGenome> population;
population.reserve(GA_POPULATION);
// get current start values
// ===== 変更後 =====
// GENOME 配列を初期値として使用
std::vector<double> startVals(geneCount);
for (size_t i = 0; i < geneCount; ++i) {
int aid = tuneIds[i];
startVals[i] = (aid >= 0 && aid < MAX_ACTION_ID) ? s_actionCosts[aid] : DEFAULT_ACTION_COST;
}
std::normal_distribution<double> normDist(0.0, DEFAULT_STEP * 5.0);
std::uniform_real_distribution<double> uni01(0.0, 1.0);
for (int p = 0; p < GA_POPULATION; ++p) {
GAGenome g;
g.genes.resize(geneCount);
for (size_t i = 0; i < geneCount; ++i) {
// small random perturbation around start
double v = startVals[i] + normDist(rng);
// if (v < 0.0) v = 0.0;
g.genes[i] = v;
}
g.fitness = std::numeric_limits<uint64_t>::max();
population.push_back(std::move(g));
}
uint64_t evaluations = 1; // 基本評価1回消費済み
const uint64_t maxEvaluations = std::max(1, maxTests);
while (evaluations < maxEvaluations) {
// 世代内で evalSeeds を確率的に変える処理は GA の収束特性を壊すので無効化します。
// 必要であれば外側ループで GA を複数回回す(各回で seed を変える)方針を推奨します。
/*
std::uniform_real_distribution<double> ud(0.0, 1.0);
if (ud(rng) < GA_SEED_CHANGE_PROB) {
seed = seed ^ (static_cast<uint64_t>(rng()) << 32) ^ rng();
evalSeeds = makeEvalSeeds(seed);
std::cout << "[GA] evalSeeds changed" << std::endl;
}
*/
// --- ここから並列評価ブロック ---
// 未評価 index を収集(予算も考慮)
std::vector<int> pending;
pending.reserve(population.size());
const auto budget = maxEvaluations - evaluations;
if (budget > 0) {
for (int i = 0; i < static_cast<int>(population.size()) && static_cast<int>(pending.size()) < budget; ++i) {
if (population[i].fitness == std::numeric_limits<uint64_t>::max()) {
pending.push_back(i);
}
}
}
if (!pending.empty()) {
const auto numThreads = std::min(kNumThreads, pending.size());
const auto chunkSize = (static_cast<uint64_t>(pending.size()) + numThreads - 1) / numThreads;
std::vector<std::future<std::vector<EvalResult>>> futures;
futures.reserve(numThreads);
for (int t = 0; t < numThreads; ++t) {
const auto start = t * chunkSize;
const auto end = std::min(static_cast<uint64_t>(pending.size()), start + chunkSize);
if (start >= end) break;
const uint64_t threadSeed = seed ^ (0x9E3779B97F4A7C15ULL * static_cast<uint64_t>(t + 1));
futures.push_back(std::async(
std::launch::async,
evaluateGenomeRange,
&population,
&pending,
start,
end,
players,
std::cref(evalSeeds),
actions,
turns,
threadSeed
));
}
for (auto &fut : futures) {
auto results = fut.get();
for (const auto &r : results) {
auto &ind = population[r.index];
// r.fitness は uint64_t。population[].fitness も uint64_t。
ind.fitness = r.fitness;
ind.measuredTurns = r.measuredTurns;
ind.measuredMs = r.measuredMs;
++evaluations;
++result.testCount;
//std::cout << "[GA] eval=" << evaluations << " turn=" << r.measuredTurns
// << " ms=" << r.measuredMs << " fitness=" << r.fitness << std::endl;
if (r.measuredTurns < result.bestTurn) {
result.bestTurn = r.measuredTurns;
result.found = true;
dumpGenome(population[r.index], result.bestTurn);
}
if (evaluations >= maxEvaluations) break;
}
if (evaluations >= maxEvaluations) break;
}
}
// sort by fitness (小さい方が良い)
std::sort(population.begin(), population.end(), [](const GAGenome &a, const GAGenome &b){
return a.fitness < b.fitness;
});
// ---------- Stability feedback ----------
if (!population.empty()) {
GAGenome bestGenomeCopy = population.front();
auto baselineTurn = bestGenomeCopy.measuredTurns;
if (baselineTurn == 0 || baselineTurn >= 9999) {
int mTurn;
double mMs;
uint64_t baseFit = evaluateGenome(bestGenomeCopy, players, evalSeeds, actions, turns, rng, mTurn, mMs);
baselineTurn = mTurn;
++evaluations;
++result.testCount;
}
auto availableChecks = std::min(STABILITY_CHECKS, maxEvaluations - evaluations);
if (availableChecks > 0) {
const auto numThreads = std::min(kNumThreads, availableChecks);
const auto chunkSize = (availableChecks + numThreads - 1) / numThreads;
std::vector<std::future<StabilityChunkResult>> futures;
futures.reserve(numThreads);
for (int t = 0; t < numThreads; ++t) {
const auto beginIdx = t * chunkSize;
const auto endIdx = std::min(availableChecks, beginIdx + chunkSize);
if (beginIdx >= endIdx) break;
futures.push_back(std::async(
std::launch::async,
stabilityCheckRange,
&bestGenomeCopy,
baselineTurn,
beginIdx,
endIdx,
seed,
players,
actions,
turns
));
}
uint64_t instabilitySum = 0;
uint64_t performedChecks = 0;
for (auto &f : futures) {
auto r = f.get();
instabilitySum += r.instabilitySum;
performedChecks += r.performed;
//std::cout << "[GA] stability check=" << r.performed << " instability=" << r.instabilitySum << " turns=" << r.turns << std::endl;
}
evaluations += performedChecks;
result.testCount += performedChecks;
if (performedChecks > 0) {
uint64_t instabilityPenalty = (instabilitySum / static_cast<uint64_t>(performedChecks));
uint64_t penaltyToApply = GA_INSTABILITY_WEIGHT * instabilityPenalty;
population.front().fitness += penaltyToApply;
//std::cout << "[GA] stability checks(performed)=" << performedChecks
// << " baseline=" << baselineTurn
// << " applied penalty=" << penaltyToApply
// << " (mean diff=" << (instabilitySum / static_cast<uint64_t>(performedChecks)) << ")\n";
std::sort(population.begin(), population.end(), [](const GAGenome &a, const GAGenome &b){
return a.fitness < b.fitness;
});
}
}
}
// ---------- end stability feedback ----------
// エリート保存
int eliteCount = std::max(1, GA_POPULATION / 10);
std::vector<GAGenome> nextGen;
nextGen.reserve(GA_POPULATION);
for (int e = 0; e < eliteCount; ++e) nextGen.push_back(population[e]);
// ルーレット/トーナメント: シンプルにトーナメント選択
auto tournamentSelect = [&](int k)->const GAGenome& {
int best = static_cast<int>(rng() % GA_POPULATION);
for (int i = 1; i < k; ++i) {
int cand = static_cast<int>(rng() % GA_POPULATION);
if (population[cand].fitness < population[best].fitness) best = cand;
}
return population[best];
};
// 子生成
while ((int)nextGen.size() < GA_POPULATION && evaluations < maxEvaluations) {
// 選択
const GAGenome &parentA = tournamentSelect(3);
const GAGenome &parentB = tournamentSelect(3);
GAGenome child;
child.genes.resize(geneCount);
// 交叉
if (uni01(rng) < GA_CROSSOVER_PROB) {
// arithmetic crossover (平均)
for (size_t i = 0; i < geneCount; ++i) {
child.genes[i] = 0.5 * (parentA.genes[i] + parentB.genes[i]);
}
} else {
// クローン
child.genes = parentA.genes;
}
// 変異
for (size_t i = 0; i < geneCount; ++i) {
if (uni01(rng) < GA_MUTATION_PROB) {
double delta = normDist(rng);
child.genes[i] = clampDouble(child.genes[i] + delta, -1e6-1, 1e6);
}
}
child.fitness = std::numeric_limits<uint64_t>::max();
nextGen.push_back(std::move(child));
// 評価は次ループで一括して行うことで評価回数制御をシンプルにしている
}
// 次世代へ
population.swap(nextGen);
}
// 最終的な best を決定
// population が評価済みであることを仮定するが、保険として評価されていないものは評価する
for (auto &ind : population) {
if (ind.fitness == std::numeric_limits<uint64_t>::max() && evaluations < maxEvaluations) {
int measuredTurn;
double measuredMs;
uint64_t fit = evaluateGenome(ind, players, evalSeeds, actions, turns, rng, measuredTurn, measuredMs);
ind.fitness = fit;
ind.measuredTurns = measuredTurn;
ind.measuredMs = measuredMs;
++evaluations;
++result.testCount;
}
}
std::sort(population.begin(), population.end(), [](const GAGenome &a, const GAGenome &b){
return a.fitness < b.fitness;
});
if (!population.empty()) {
const GAGenome &best = population.front();
// best を s_actionCosts に反映
for (size_t i = 0; i < best.genes.size(); ++i) {
int aid = tuneIds[i];
if (aid >= 0 && aid < MAX_ACTION_ID) s_actionCosts[aid] = best.genes[i];
}
applyActionCostsToCostParams();
result.bestTurn = std::min(result.bestTurn, best.measuredTurns);
}
result.testCount = evaluations;
std::cout << "[SimpleParameterOptimizer GA] done. bestTurn=" << result.bestTurn
<< " evaluations=" << evaluations << std::endl;
return result;
}
// --- testParameters の定義 ---
int SimpleParameterOptimizer::testParameters(
const Player players[2],
uint64_t seed,
const int actions[350],
int turns)
{
applyActionCostsToCostParams();
Player copiedPlayers[2] = { players[0], players[1] };
int gene[350];
for (int i = 0; i < 350; ++i) {
gene[i] = actions[i];
if (actions[i] == -1) { gene[i] = -1; break; }
}
auto genome = ActionOptimizer::RunAlgorithm(copiedPlayers, seed, turns, 5000, gene, 0);
if (genome.EnemyPlayer.hp <= 0) {
return genome.turn - 1;
} else {
return 9999;
}
}
// --- evaluateGenomeRange: EvalResult::fitness は uint64_t に準拠 ---
std::vector<EvalResult> SimpleParameterOptimizer::evaluateGenomeRange(std::vector<GAGenome> *population,
const std::vector<int> *pendingIndices, int start, int end, const Player players[2],
const std::array<uint64_t, GA_EVAL_SEEDS> &evalSeeds, const int actions[350], int turnsLimit,
uint64_t seedForThread) {
std::mt19937 localRng(static_cast<uint32_t>(seedForThread));
std::vector<EvalResult> out;
out.reserve(static_cast<size_t>(std::max(0, end - start)));
for (int k = start; k < end; ++k) {
const int idx = (*pendingIndices)[k];
auto &ind = (*population)[idx];
int measuredTurn = 0;
double measuredMs = 0.0;
uint64_t fit = evaluateGenome(ind, players, evalSeeds, actions, turnsLimit, localRng, measuredTurn, measuredMs);
EvalResult r;
r.index = idx;
r.fitness = fit; // uint64_t
r.measuredTurns = measuredTurn;
r.measuredMs = measuredMs;
out.push_back(r);
}
return out;
}
// --- 追加: stability check 用の決定的 seed 生成(スレッドセーフ) ---
static inline uint64_t splitmix64(uint64_t &x) {
uint64_t z = (x += 0x9E3779B97F4A7C15ULL);
z = (z ^ (z >> 30)) * 0xBF58476D1CE4E5B9ULL;
z = (z ^ (z >> 27)) * 0x94D049BB133111EBULL;
return z ^ (z >> 31);
}
static std::array<uint64_t, GA_EVAL_SEEDS> makeEvalSeedsDeterministic(uint64_t base) {
std::array<uint64_t, GA_EVAL_SEEDS> s{};
uint64_t x = base;
for (int i = 0; i < GA_EVAL_SEEDS; ++i) {
s[i] = splitmix64(x);
}
return s;
}
StabilityChunkResult SimpleParameterOptimizer::stabilityCheckRange(const GAGenome *bestGenomeCopy, int baselineTurn,
int beginIdx, int endIdx, uint64_t baseSeed, const Player players[2], const int actions[350], int turnsLimit) {
StabilityChunkResult out{};
auto turns = 0;
for (int i = beginIdx; i < endIdx; ++i) {
uint64_t altBase = baseSeed ^ (0x9E3779B97F4A7C15ULL * static_cast<uint64_t>(i + 1));
auto altEvalSeeds = makeEvalSeedsDeterministic(altBase);
auto localSeed32 = static_cast<uint32_t>((altBase >> 32) ^ (altBase & 0xFFFFFFFFu));
std::mt19937 localRng(localSeed32);
int mutatedActions[350];
std::string insertedSummary;
buildActionsWithRandomInserts(
actions,
mutatedActions,
localRng,
STABILITY_RANDOM_ACTION_POOL,
STABILITY_EXTRA_ACTIONS_MAX,
STABILITY_EXTRA_ACTION_INSERT_PROB,
&insertedSummary
);
GAGenome copyForCheck = *bestGenomeCopy;
int mTurn = 0;
double mMs = 0.0;
// NOTE: mutatedActions を使う(安定性チェックの意図どおり)
(void)evaluateGenome(copyForCheck, players, altEvalSeeds, mutatedActions, turnsLimit, localRng, mTurn, mMs);
turns += mTurn;
if (mTurn > baselineTurn) {
out.instabilitySum += static_cast<uint64_t>(mTurn - baselineTurn);
}
++out.performed;
}
out.turns = turns;
return out;
}
#endif // OPTIMIZE_MODE