-
Notifications
You must be signed in to change notification settings - Fork 11
Expand file tree
/
Copy pathplay.cpp
More file actions
280 lines (234 loc) · 9.46 KB
/
Copy pathplay.cpp
File metadata and controls
280 lines (234 loc) · 9.46 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
#include "../core/global.h"
#include "../search/asyncbot.h"
#include "../program/play.h"
static double nextGaussianTruncated(Rand& rand) {
double d = rand.nextGaussian();
//Truncated refers to the probability distribution, not the sample
//So on falling outside the range, we redraw, rather than capping.
while(d < -2.0 || d > 2.0)
d = rand.nextGaussian();
return d;
}
static int getMaxExtraBlack(int bSize) {
if(bSize <= 10)
return 0;
if(bSize <= 14)
return 1;
if(bSize <= 18)
return 2;
return 3;
}
static pair<int,float> chooseExtraBlackAndKomi(
float base, float stdev, double allowIntegerProb, double handicapProb, float handicapStoneValue, double bigStdevProb, float bigStdev, int bSize, Rand& rand
) {
int extraBlack = 0;
float komi = base;
if(stdev > 0.0f)
komi += stdev * (float)nextGaussianTruncated(rand);
if(bigStdev > 0.0f && rand.nextDouble() < bigStdevProb)
komi += bigStdev * (float)nextGaussianTruncated(rand);
//Adjust for bSize, so that we don't give the same massive komis on smaller boards
komi = base + (komi - base) * (float)bSize / 19.0f;
//Add handicap stones compensated with komi
int maxExtraBlack = getMaxExtraBlack(bSize);
if(maxExtraBlack > 0 && rand.nextDouble() < handicapProb) {
extraBlack += 1+rand.nextUInt(maxExtraBlack);
komi += extraBlack * handicapStoneValue;
}
//Discretize komi
float lower;
float upper;
if(rand.nextDouble() < allowIntegerProb) {
lower = floor(komi*2.0f) / 2.0f;
upper = ceil(komi*2.0f) / 2.0f;
}
else {
lower = floor(komi+ 0.5f)-0.5f;
upper = ceil(komi+0.5f)-0.5f;
}
if(lower == upper)
komi = lower;
else {
assert(upper > lower);
if(rand.nextDouble() < (komi - lower) / (upper - lower))
komi = upper;
else
komi = lower;
}
assert((float)((int)(komi * 2)) == komi * 2);
return make_pair(extraBlack,komi);
}
//------------------------------------------------------------------------------------------------
GameInitializer::GameInitializer(ConfigParser& cfg)
:createGameMutex(),rand()
{
allowedKoRuleStrs = cfg.getStrings("koRules", Rules::koRuleStrings());
allowedScoringRuleStrs = cfg.getStrings("scoringRules", Rules::scoringRuleStrings());
allowedMultiStoneSuicideLegals = cfg.getBools("multiStoneSuicideLegals");
for(size_t i = 0; i < allowedKoRuleStrs.size(); i++)
allowedKoRules.push_back(Rules::parseKoRule(allowedKoRuleStrs[i]));
for(size_t i = 0; i < allowedScoringRuleStrs.size(); i++)
allowedScoringRules.push_back(Rules::parseScoringRule(allowedScoringRuleStrs[i]));
if(allowedKoRules.size() <= 0)
throw IOError("koRules must have at least one value in " + cfg.getFileName());
if(allowedScoringRules.size() <= 0)
throw IOError("scoringRules must have at least one value in " + cfg.getFileName());
if(allowedMultiStoneSuicideLegals.size() <= 0)
throw IOError("multiStoneSuicideLegals must have at least one value in " + cfg.getFileName());
allowedBSizes = cfg.getInts("bSizes", 9, 19);
allowedBSizeRelProbs = cfg.getDoubles("bSizeRelProbs",0.0,1e100);
komiMean = cfg.getFloat("komiMean",-60.0f,60.0f);
komiStdev = cfg.getFloat("komiStdev",-60.0f,60.0f);
komiAllowIntegerProb = cfg.getDouble("komiAllowIntegerProb",0.0,1.0);
handicapProb = cfg.getDouble("handicapProb",0.0,1.0);
handicapStoneValue = cfg.getFloat("handicapStoneValue",0.0f,30.0f);
komiBigStdevProb = cfg.getDouble("komiBigStdevProb",0.0,1.0);
komiBigStdev = cfg.getFloat("komiBigStdev",-60.0f,60.0f);
if(allowedBSizes.size() <= 0)
throw IOError("bSizes must have at least one value in " + cfg.getFileName());
if(allowedBSizes.size() != allowedBSizeRelProbs.size())
throw IOError("bSizes and bSizeRelProbs must have same number of values in " + cfg.getFileName());
}
GameInitializer::~GameInitializer()
{}
void GameInitializer::createGame(Board& board, Player& pla, BoardHistory& hist, int& numExtraBlack) {
//Multiple threads will be calling this, and we have some mutable state such as rand.
unique_lock<std::mutex> lock(createGameMutex);
int bSize = allowedBSizes[rand.nextUInt(allowedBSizeRelProbs.data(),allowedBSizeRelProbs.size())];
board = Board(bSize,bSize);
Rules rules;
rules.koRule = allowedKoRules[rand.nextUInt(allowedKoRules.size())];
rules.scoringRule = allowedScoringRules[rand.nextUInt(allowedScoringRules.size())];
rules.multiStoneSuicideLegal = allowedMultiStoneSuicideLegals[rand.nextUInt(allowedMultiStoneSuicideLegals.size())];
pair<int,float> extraBlackAndKomi = chooseExtraBlackAndKomi(
komiMean, komiStdev, komiAllowIntegerProb, handicapProb, handicapStoneValue,
komiBigStdevProb, komiBigStdev, bSize, rand
);
rules.komi = extraBlackAndKomi.second;
pla = P_BLACK;
hist.clear(board,pla,rules);
numExtraBlack = extraBlackAndKomi.first;
}
//----------------------------------------------------------------------------------------------------------
MatchPairer::MatchPairer(int nBots, const vector<int>& secBots)
:numBots(nBots),secondaryBots(secBots),nextMatchups(),rand()
{}
MatchPairer::~MatchPairer()
{}
pair<int,int> MatchPairer::getMatchup() {
if(nextMatchups.size() <= 0) {
if(numBots == 1)
return make_pair(0,0);
for(int i = 0; i<numBots; i++) {
for(int j = 0; j<numBots; j++) {
if(i != j && !(contains(secondaryBots,i) && contains(secondaryBots,j))) {
nextMatchups.push_back(make_pair(i,j));
}
}
}
//Shuffle
for(int i = nextMatchups.size()-1; i >= 1; i--) {
int j = (int)rand.nextUInt(i+1);
pair<int,int> tmp = nextMatchups[i];
nextMatchups[i] = nextMatchups[j];
nextMatchups[j] = tmp;
}
}
pair<int,int> matchup = nextMatchups.back();
nextMatchups.pop_back();
return matchup;
}
//----------------------------------------------------------------------------------------------------------
static void failIllegalMove(AsyncBot* bot, Logger& logger, Board board, Loc loc) {
ostringstream sout;
sout << "Bot returned null location or illegal move!?!" << "\n";
sout << board << "\n";
sout << bot->getRootBoard() << "\n";
sout << "Pla: " << playerToString(bot->getRootPla()) << "\n";
sout << "Loc: " << Location::toString(loc,bot->getRootBoard()) << "\n";
logger.write(sout.str());
bot->getRootBoard().checkConsistency();
assert(false);
}
static void logSearch(AsyncBot* bot, Logger& logger, Loc loc) {
Search* search = bot->getSearch();
ostringstream sout;
Board::printBoard(sout, bot->getRootBoard(), loc, &(bot->getRootHist().moveHistory));
sout << "\n";
sout << "Root visits: " << search->numRootVisits() << "\n";
sout << "PV: ";
search->printPV(sout, search->rootNode, 25);
sout << "\n";
sout << "Tree:\n";
search->printTree(sout, search->rootNode, PrintTreeOptions().maxDepth(1).maxChildrenToShow(10));
logger.write(sout.str());
}
//Place black handicap stones, free placement
static void playExtraBlack(AsyncBot* bot, Logger& logger, int numExtraBlack, Board& board, BoardHistory& hist) {
SearchParams oldParams = bot->getSearch()->searchParams;
SearchParams tempParams = oldParams;
tempParams.rootNoiseEnabled = false;
tempParams.chosenMoveSubtract = 0.0;
tempParams.chosenMoveTemperature = 1.0;
tempParams.numThreads = 1;
tempParams.maxVisits = 1;
Player pla = P_BLACK;
bot->setPosition(pla,board,hist);
bot->setParams(tempParams);
bot->setRootPassLegal(false);
for(int i = 0; i<numExtraBlack; i++) {
Loc loc = bot->genMoveSynchronous(pla);
if(loc == Board::NULL_LOC || !bot->isLegal(loc,pla))
failIllegalMove(bot,logger,board,loc);
assert(hist.isLegal(board,loc,pla));
hist.makeBoardMoveAssumeLegal(board,loc,pla,NULL);
hist.clear(board,pla,hist.rules);
bot->setPosition(pla,board,hist);
}
bot->setParams(oldParams);
bot->setRootPassLegal(true);
}
//Run a game between two bots. It is OK if both bots are the same bot.
//Mutates the given board and history
void Play::runGame(
Board& board, Player pla, BoardHistory& hist, int numExtraBlack, AsyncBot* botB, AsyncBot* botW,
bool doEndGameIfAllPassAlive, bool clearBotAfterSearch,
Logger& logger, bool logSearchInfo, bool logMoves,
int maxMovesPerGame, std::atomic<bool>& stopSignalReceived
) {
if(numExtraBlack > 0)
playExtraBlack(botB,logger,numExtraBlack,board,hist);
botB->setPosition(pla,board,hist);
if(botB != botW)
botW->setPosition(pla,board,hist);
for(int i = 0; i<maxMovesPerGame; i++) {
if(doEndGameIfAllPassAlive)
hist.endGameIfAllPassAlive(board);
if(hist.isGameFinished)
break;
if(stopSignalReceived.load())
break;
AsyncBot* toMoveBot = pla == P_BLACK ? botB : botW;
Loc loc = toMoveBot->genMoveSynchronous(pla);
if(loc == Board::NULL_LOC || !toMoveBot->isLegal(loc,pla))
failIllegalMove(toMoveBot,logger,board,loc);
if(logSearchInfo)
logSearch(toMoveBot,logger,loc);
if(logMoves)
logger.write("Move " + Global::intToString(hist.moveHistory.size()) + " made: " + Location::toString(loc,board));
//In many cases, we are using root-level noise, so we want to clear the search each time so that we don't
//bias the next search with the result of the previous... and also to make each color's search independent of the other's.
if(clearBotAfterSearch)
toMoveBot->clearSearch();
bool suc;
suc = botB->makeMove(loc,pla);
assert(suc);
if(botB != botW) {
suc = botW->makeMove(loc,pla);
assert(suc);
}
assert(hist.isLegal(board,loc,pla));
hist.makeBoardMoveAssumeLegal(board,loc,pla,NULL);
pla = getOpp(pla);
}
}