-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.cc
More file actions
466 lines (380 loc) · 14 KB
/
main.cc
File metadata and controls
466 lines (380 loc) · 14 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
// Copyright (C) 2016 Tetsui Ohkubo.
#include <gflags/gflags.h>
#include <cstdlib>
#include <iostream>
#include <memory>
#include "./perft.h"
#include "./search.h"
#include "./trax.h"
DEFINE_bool(client, false, "Run as contest client.");
DEFINE_bool(self, false, "Run self play.");
DEFINE_bool(use_log, false, "Load human game log.");
DEFINE_bool(perft, false, "Run perft.");
DEFINE_bool(prediction, false,
"Measure prediction rate against human game log.");
DEFINE_bool(factors_csv, false, "Output factors to stdout (self/use_log.)");
DEFINE_bool(stats_csv, false,
"Output game statistics to stdout (self/use_log.)");
DEFINE_bool(tournament, false, "Run tournament.");
DEFINE_bool(best_move, false,
"Get the current board configuration from stdin"
" and return the best move in trax notation."
" Expected to be used for trax-daemon.");
DEFINE_bool(show_position, false,
"Ad hoc solution not to implement game rules inside trax-daemon.");
DEFINE_int32(seed, 0, "Random seed.");
DEFINE_int32(perft_depth, 6, "Perft depth.");
DEFINE_int32(num_games, 100, "How many times to self play.");
DEFINE_string(white, "simple-la", "Searcher name of white player (first)");
DEFINE_string(red, "negamax1-la", "Searcher name of red player (second)");
DEFINE_string(searcher, "itersmp-fe", "Searcher name of contest client player");
DEFINE_bool(verbose, true, "Verbose output on self play.");
DEFINE_string(commented_games,
"vendor/commented/Comment.txt",
"File name of commented game data");
DEFINE_bool(
interpolate,
false,
"Finish resigned games in human game log by using searcher.");
namespace {
Searcher *GetSearcherFromName(const std::string& name) {
if (name == "random") {
return new RandomSearcher();
} else if (name == "simple-la") {
return new SimpleSearcher<LeafAverageEvaluator>();
} else if (name == "simple-mc") {
return new SimpleSearcher<MonteCarloEvaluator>();
} else if (name == "simple-fe") {
return new SimpleSearcher<FactorEvaluator>();
} else if (name == "simple-afe") {
return new SimpleSearcher<AdvancedFactorEvaluator>();
} else if (name == "simple-lfe") {
return new SimpleSearcher<LoopFactorEvaluator>();
} else if (name == "negamax0-la") {
return new NegaMaxSearcher<LeafAverageEvaluator>(0);
} else if (name == "negamax1-la") {
return new NegaMaxSearcher<LeafAverageEvaluator>(1);
} else if (name == "negamax1wb-la") {
return new NegaMaxSearcher<LeafAverageEvaluator>(1, false, false);
} else if (name == "iter1-la") {
return new NegaMaxSearcher<LeafAverageEvaluator>(1, true);
} else if (name == "negamax2-la") {
return new NegaMaxSearcher<LeafAverageEvaluator>(2);
} else if (name == "iter10-la") {
return new NegaMaxSearcher<LeafAverageEvaluator>(10, true);
} else if (name == "negamax1-mc") {
return new NegaMaxSearcher<MonteCarloEvaluator>(1);
} else if (name == "negamax2-mc") {
return new NegaMaxSearcher<MonteCarloEvaluator>(2);
} else if (name == "negamax0-na") {
return new NegaMaxSearcher<NoneEvaluator>(0);
} else if (name == "negamax1-na") {
return new NegaMaxSearcher<NoneEvaluator>(1);
} else if (name == "negamax2-na") {
return new NegaMaxSearcher<NoneEvaluator>(2);
} else if (name == "negamax3-na") {
return new NegaMaxSearcher<NoneEvaluator>(3);
} else if (name == "negamax4-na") {
return new NegaMaxSearcher<NoneEvaluator>(4);
} else if (name == "iter10-na") {
return new NegaMaxSearcher<NoneEvaluator>(10, true);
} else if (name == "negamax0-fe") {
return new NegaMaxSearcher<FactorEvaluator>(0);
} else if (name == "negamax1-fe") {
return new NegaMaxSearcher<FactorEvaluator>(1);
} else if (name == "iter1-fe") {
return new NegaMaxSearcher<FactorEvaluator>(1, true);
} else if (name == "iter10-fe") {
return new NegaMaxSearcher<FactorEvaluator>(10, true);
} else if (name == "iter10wb-fe") {
return new NegaMaxSearcher<FactorEvaluator>(10, true, false);
} else if (name == "negamax2-fe") {
return new NegaMaxSearcher<FactorEvaluator>(2);
} else if (name == "negamax3-fe") {
return new NegaMaxSearcher<FactorEvaluator>(3);
} else if (name == "negamax4-fe") {
return new NegaMaxSearcher<FactorEvaluator>(4);
} else if (name == "iter10-afe") {
return new NegaMaxSearcher<AdvancedFactorEvaluator>(10, true);
} else if (name == "iter10-lfe") {
return new NegaMaxSearcher<LoopFactorEvaluator>(10, true);
} else if (name == "itersmp-fe") {
return new ThreadedIterativeSearcher<FactorEvaluator>();
} else if (name == "itersmp-la") {
return new ThreadedIterativeSearcher<LeafAverageEvaluator>();
} else {
std::cerr << "cannot find searcher with name " << name << std::endl;
exit(EXIT_FAILURE);
return nullptr;
}
}
void DumpGamesStatistics(const std::vector<Game>& games) {
int loop_count = 0;
int victory_line_count = 0;
int resigns_count = 0;
int red_win = 0;
int white_win = 0;
double average_moves = 0;
double average_search_depths[2] = {0.0};
double average_nps[2] = {0.0};
for (const Game& game : games) {
average_moves += game.num_moves();
if (game.winning_reason == WINNING_REASON_LOOP) {
++loop_count;
} else if (game.winning_reason == WINNING_REASON_LINE) {
++victory_line_count;
} else if (game.winning_reason == WINNING_REASON_RESIGN) {
++resigns_count;
}
if (game.winner == 1) {
++red_win;
} else if (game.winner == -1) {
++white_win;
}
for (int i = 0; i < 2; ++i) {
average_search_depths[i] += game.average_search_depths[i];
average_nps[i] += game.average_nps[i];
}
}
average_moves /= games.size();
for (int i = 0; i < 2; ++i) {
average_search_depths[i] /= games.size();
average_nps[i] /= games.size();
}
std::cerr << "Total: " << games.size() << std::endl;
std::cerr << " Resigns: " << resigns_count << std::endl;
std::cerr << " Loop: " << loop_count << std::endl;
std::cerr << " Victory Line: " << victory_line_count << std::endl;
std::cerr << "Average moves: " << average_moves << std::endl;
std::cerr << "White win: " << white_win << std::endl;
std::cerr << "Red win: " << red_win << std::endl;
std::cerr << "Average search depth: "
<< average_search_depths[0] << "(white) "
<< average_search_depths[1] << "(red)" << std::endl;
std::cerr << "Average nps: "
<< average_nps[0] << "(white) "
<< average_nps[1] << "(red)" << std::endl;
}
void DumpGamesStatisticsCSV(const std::vector<Game>& games) {
std::cout << "total_step,winner,winning_reason" << std::endl;
for (const Game& game : games) {
std::cout
<< game.num_moves() << ","
<< game.winner << ",";
switch (game.winning_reason) {
case WINNING_REASON_UNKNOWN:
std::cout << "UNKNOWN";
break;
case WINNING_REASON_LOOP:
std::cout << "LOOP";
break;
case WINNING_REASON_LINE:
std::cout << "LINE";
break;
case WINNING_REASON_FULL:
std::cout << "FULL";
break;
case WINNING_REASON_RESIGN:
std::cout << "RESIGN";
break;
}
std::cout << std::endl;
}
}
void DumpFactors(const std::vector<Game>& games) {
std::string first_line = "step,winner,field";
bool first = true;
for (const Game& game : games) {
if (game.winner == 0) {
continue;
}
Position position;
for (int i = 0; i < game.num_moves(); ++i) {
Position next_position;
Move move = game.moves[i];
bool success = position.DoMove(move, &next_position);
if (!success) {
std::cerr << "something went wrong!" << std::endl;
exit(EXIT_FAILURE);
}
position.Swap(&next_position);
if (position.finished()) {
continue;
}
std::vector<std::pair<std::string, double>> factors;
GenerateFactors(position, &factors);
if (first) {
for (std::pair<std::string, double>& factor : factors) {
first_line += "," + factor.first;
}
std::cout << first_line << std::endl;
first = false;
}
std::cout << i << "," << game.winner << "," << position.ToString64x64();
for (std::pair<std::string, double>& factor : factors) {
std::cout << "," << factor.second;
}
std::cout << std::endl;
}
}
}
// Ranks searchers by simplified version of Elo rating.
// https://en.wikipedia.org/wiki/Elo_rating_system
//
// The method is based on that of Shogi Club 24 or floodgate's one.
void RunTournament() {
Searcher *searchers[] = {
new RandomSearcher(),
new SimpleSearcher<LeafAverageEvaluator>(),
new SimpleSearcher<FactorEvaluator>(),
new NegaMaxSearcher<LeafAverageEvaluator>(1),
new NegaMaxSearcher<LeafAverageEvaluator>(10, true),
new NegaMaxSearcher<FactorEvaluator>(10, true),
new NegaMaxSearcher<AdvancedFactorEvaluator>(10, true)
};
const int num_searchers = sizeof(searchers) / sizeof(searchers[0]);
std::vector<double> rates(num_searchers, 1500.0);
for (int i = 0; i < FLAGS_num_games; ++i) {
std::cerr << "Game " << i << ": ";
int white_index = Random() % num_searchers;
int red_index = white_index;
while (white_index == red_index) {
red_index = Random() % num_searchers;
}
Game game;
StartSelfGame(searchers[white_index],
searchers[red_index], &game, FLAGS_verbose);
if (game.winner > 0) {
std::cerr << "[LOSE]white: " << searchers[white_index]->name() <<
" [WIN]red: " << searchers[red_index]->name() << std::endl;
double delta_r =
16 + (rates[white_index] - rates[red_index]) * 0.04;
delta_r = std::min(31.0, std::max(1.0, delta_r));
rates[red_index] += delta_r;
rates[white_index] -= delta_r;
} else if (game.winner < 0) {
std::cerr << "[WIN]white: " << searchers[white_index]->name() <<
" [LOSE]red: " << searchers[red_index]->name() << std::endl;
double delta_r =
16 + (rates[red_index] - rates[white_index]) * 0.04;
delta_r = std::min(31.0, std::max(1.0, delta_r));
rates[white_index] += delta_r;
rates[red_index] -= delta_r;
} else {
std::cerr << "[DRAW]white: " << searchers[white_index]->name() <<
" [DRAW]red: " << searchers[red_index]->name() << std::endl;
}
std::vector<std::pair<double, std::string>> ranking;
for (int i = 0; i < num_searchers; ++i) {
ranking.emplace_back(rates[i], searchers[i]->name());
}
std::sort(ranking.rbegin(), ranking.rend());
for (auto& ranked : ranking) {
std::cerr << ranked.first << "\t" << ranked.second << std::endl;
}
std::cerr << std::endl;
std::cerr << std::endl;
}
}
} // namespace
int main(int argc, char *argv[]) {
google::SetUsageMessage(
"Trax artificial intelligence.\n\n"
"usage: ./trax (--client|--perft|--prediction|--self|--use_log|"
"--tournament)");
google::ParseCommandLineFlags(&argc, &argv, true);
// Otherwise Position::GetPossiblePieces() doesn't work.
GeneratePossiblePiecesTable();
// Otherwise Position::TraceVictoryLineOrLoop() doesn't work.
GenerateTrackDirectionTable();
// Otherwise Position::FillForcedPieces() doesn't work.
GenerateForcedPlayTable();
// Initialize random seed.
for (int i = 0; i < FLAGS_seed; ++i) {
Random();
}
//// Realtime playing facilities.
// These modes are for trax-daemon (Trax playing online frontend) and
// the interface is private and subject to change.
if (FLAGS_best_move) {
std::unique_ptr<Searcher> searcher;
searcher.reset(GetSearcherFromName(FLAGS_searcher));
ReadAndFindBestMove(searcher.get());
return 0;
}
if (FLAGS_show_position) {
ShowPosition();
return 0;
}
// Official contest client.
if (FLAGS_client) {
std::unique_ptr<Searcher> searcher;
searcher.reset(GetSearcherFromName(FLAGS_searcher));
StartTraxClient(searcher.get());
return 0;
}
//// Benchmarking utilities.
// Benchmark its performance by counting all the possible moves within
// the given depth.
if (FLAGS_perft) {
ShowPerft(FLAGS_perft_depth);
return 0;
}
// Measure prediction accuracy of the evaluation function against
// human game log.
if (FLAGS_prediction) {
std::unique_ptr<Searcher> searcher;
searcher.reset(GetSearcherFromName(FLAGS_searcher));
std::vector<Game> games;
ParseCommentedGames(FLAGS_commented_games, &games);
int numerator = 0;
int denominator = 0;
for (Game& game : games) {
numerator += game.CountMatchingMoves(searcher.get());
denominator += game.num_moves();
}
DumpGamesStatistics(games);
const double prediction = numerator * 100.0 / denominator;
std::cerr << "Prediction: " << prediction << "% "
<< "(" << numerator << "/" << denominator << ")" << std::endl;
return 0;
}
//// Strategy evaluation and improvement tools.
if (FLAGS_self || FLAGS_use_log) {
std::vector<Game> games;
if (FLAGS_self) {
// Perform self play.
std::unique_ptr<Searcher> white_player;
std::unique_ptr<Searcher> red_player;
white_player.reset(GetSearcherFromName(FLAGS_white));
red_player.reset(GetSearcherFromName(FLAGS_red));
StartMultipleSelfGames(white_player.get(), red_player.get(),
FLAGS_num_games, &games, FLAGS_verbose);
} else {
// Parse human played game logs.
ParseCommentedGames(FLAGS_commented_games, &games);
if (FLAGS_interpolate) {
std::unique_ptr<Searcher> searcher;
searcher.reset(GetSearcherFromName(FLAGS_searcher));
for (Game& game : games) {
game.ContinueBySearcher(searcher.get());
}
}
}
if (FLAGS_factors_csv) {
DumpFactors(games);
} else if (FLAGS_stats_csv) {
DumpGamesStatisticsCSV(games);
}
DumpGamesStatistics(games);
return 0;
}
if (FLAGS_tournament) {
RunTournament();
return 0;
}
google::ShowUsageWithFlags(argv[0]);
std::cerr << std::endl;
std::cerr << "Move struct size: " << sizeof(Move) << std::endl;
return EXIT_FAILURE;
}