2 Stockfish, a UCI chess playing engine derived from Glaurung 2.1
3 Copyright (C) 2004-2008 Tord Romstad (Glaurung author)
4 Copyright (C) 2008-2009 Marco Costalba
6 Stockfish is free software: you can redistribute it and/or modify
7 it under the terms of the GNU General Public License as published by
8 the Free Software Foundation, either version 3 of the License, or
9 (at your option) any later version.
11 Stockfish is distributed in the hope that it will be useful,
12 but WITHOUT ANY WARRANTY; without even the implied warranty of
13 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 GNU General Public License for more details.
16 You should have received a copy of the GNU General Public License
17 along with this program. If not, see <http://www.gnu.org/licenses/>.
34 //// Local definitions
39 // Polynomial material balance parameters
40 const Value RedundantQueenPenalty = Value(320);
41 const Value RedundantRookPenalty = Value(554);
42 const int LinearCoefficients[6] = { 1709, -137, -1185, -166, 141, 59 };
44 const int QuadraticCoefficientsSameColor[][6] = {
45 { 0, 0, 0, 0, 0, 0 }, { 33, -6, 0, 0, 0, 0 }, { 29, 269, -12, 0, 0, 0 },
46 { 0, 19, -4, 0, 0, 0 }, { -35, -10, 40, 95, 50, 0 }, { 52, 23, 78, 144, -11, -33 } };
48 const int QuadraticCoefficientsOppositeColor[][6] = {
49 { 0, 0, 0, 0, 0, 0 }, { -5, 0, 0, 0, 0, 0 }, { -33, 23, 0, 0, 0, 0 },
50 { 17, 25, -3, 0, 0, 0 }, { 10, -2, -19, -67, 0, 0 }, { 69, 64, -41, 116, 137, 0 } };
52 // Unmapped endgame evaluation and scaling functions, these
53 // are accessed direcly and not through the function maps.
54 EvaluationFunction<KmmKm> EvaluateKmmKm(WHITE);
55 EvaluationFunction<KXK> EvaluateKXK(WHITE), EvaluateKKX(BLACK);
56 ScalingFunction<KBPK> ScaleKBPK(WHITE), ScaleKKBP(BLACK);
57 ScalingFunction<KQKRP> ScaleKQKRP(WHITE), ScaleKRPKQ(BLACK);
58 ScalingFunction<KPsK> ScaleKPsK(WHITE), ScaleKKPs(BLACK);
59 ScalingFunction<KPKP> ScaleKPKPw(WHITE), ScaleKPKPb(BLACK);
67 typedef EndgameEvaluationFunctionBase EF;
68 typedef EndgameScalingFunctionBase SF;
70 /// See header for a class description. It is declared here to avoid
71 /// to include <map> in the header file.
73 class EndgameFunctions {
77 template<class T> T* get(Key key) const;
80 template<class T> void add(const string& keyCode);
82 static Key buildKey(const string& keyCode);
83 static const string swapColors(const string& keyCode);
85 // Here we store two maps, one for evaluate and one for scaling
86 pair<map<Key, EF*>, map<Key, SF*> > maps;
88 // Maps accessing functions for const and non-const references
89 template<typename T> const map<Key, T*>& get() const { return maps.first; }
90 template<typename T> map<Key, T*>& get() { return maps.first; }
93 // Explicit specializations of a member function shall be declared in
94 // the namespace of which the class template is a member.
95 template<> const map<Key, SF*>&
96 EndgameFunctions::get<SF>() const { return maps.second; }
98 template<> map<Key, SF*>&
99 EndgameFunctions::get<SF>() { return maps.second; }
107 /// Constructor for the MaterialInfoTable class
109 MaterialInfoTable::MaterialInfoTable(unsigned int numOfEntries) {
112 entries = new MaterialInfo[size];
113 funcs = new EndgameFunctions();
114 if (!entries || !funcs)
116 cerr << "Failed to allocate " << (numOfEntries * sizeof(MaterialInfo))
117 << " bytes for material hash table." << endl;
118 Application::exit_with_failure();
123 /// Destructor for the MaterialInfoTable class
125 MaterialInfoTable::~MaterialInfoTable() {
132 /// MaterialInfoTable::get_material_info() takes a position object as input,
133 /// computes or looks up a MaterialInfo object, and returns a pointer to it.
134 /// If the material configuration is not already present in the table, it
135 /// is stored there, so we don't have to recompute everything when the
136 /// same material configuration occurs again.
138 MaterialInfo* MaterialInfoTable::get_material_info(const Position& pos) {
140 Key key = pos.get_material_key();
141 int index = key & (size - 1);
142 MaterialInfo* mi = entries + index;
144 // If mi->key matches the position's material hash key, it means that we
145 // have analysed this material configuration before, and we can simply
146 // return the information we found the last time instead of recomputing it.
150 // Clear the MaterialInfo object, and set its key
154 // Let's look if we have a specialized evaluation function for this
155 // particular material configuration. First we look for a fixed
156 // configuration one, then a generic one if previous search failed.
157 if ((mi->evaluationFunction = funcs->get<EF>(key)) != NULL)
160 else if ( pos.non_pawn_material(BLACK) == Value(0)
161 && pos.piece_count(BLACK, PAWN) == 0
162 && pos.non_pawn_material(WHITE) >= RookValueMidgame)
164 mi->evaluationFunction = &EvaluateKXK;
167 else if ( pos.non_pawn_material(WHITE) == Value(0)
168 && pos.piece_count(WHITE, PAWN) == 0
169 && pos.non_pawn_material(BLACK) >= RookValueMidgame)
171 mi->evaluationFunction = &EvaluateKKX;
174 else if ( pos.pawns() == EmptyBoardBB
175 && pos.rooks() == EmptyBoardBB
176 && pos.queens() == EmptyBoardBB)
178 // Minor piece endgame with at least one minor piece per side,
180 assert(pos.knights(WHITE) | pos.bishops(WHITE));
181 assert(pos.knights(BLACK) | pos.bishops(BLACK));
183 if ( pos.piece_count(WHITE, BISHOP) + pos.piece_count(WHITE, KNIGHT) <= 2
184 && pos.piece_count(BLACK, BISHOP) + pos.piece_count(BLACK, KNIGHT) <= 2)
186 mi->evaluationFunction = &EvaluateKmmKm;
191 // OK, we didn't find any special evaluation function for the current
192 // material configuration. Is there a suitable scaling function?
194 // The code below is rather messy, and it could easily get worse later,
195 // if we decide to add more special cases. We face problems when there
196 // are several conflicting applicable scaling functions and we need to
197 // decide which one to use.
200 if ((sf = funcs->get<SF>(key)) != NULL)
202 mi->scalingFunction[sf->color()] = sf;
206 if ( pos.non_pawn_material(WHITE) == BishopValueMidgame
207 && pos.piece_count(WHITE, BISHOP) == 1
208 && pos.piece_count(WHITE, PAWN) >= 1)
209 mi->scalingFunction[WHITE] = &ScaleKBPK;
211 if ( pos.non_pawn_material(BLACK) == BishopValueMidgame
212 && pos.piece_count(BLACK, BISHOP) == 1
213 && pos.piece_count(BLACK, PAWN) >= 1)
214 mi->scalingFunction[BLACK] = &ScaleKKBP;
216 if ( pos.piece_count(WHITE, PAWN) == 0
217 && pos.non_pawn_material(WHITE) == QueenValueMidgame
218 && pos.piece_count(WHITE, QUEEN) == 1
219 && pos.piece_count(BLACK, ROOK) == 1
220 && pos.piece_count(BLACK, PAWN) >= 1)
221 mi->scalingFunction[WHITE] = &ScaleKQKRP;
223 else if ( pos.piece_count(BLACK, PAWN) == 0
224 && pos.non_pawn_material(BLACK) == QueenValueMidgame
225 && pos.piece_count(BLACK, QUEEN) == 1
226 && pos.piece_count(WHITE, ROOK) == 1
227 && pos.piece_count(WHITE, PAWN) >= 1)
228 mi->scalingFunction[BLACK] = &ScaleKRPKQ;
230 if (pos.non_pawn_material(WHITE) + pos.non_pawn_material(BLACK) == Value(0))
232 if (pos.piece_count(BLACK, PAWN) == 0)
234 assert(pos.piece_count(WHITE, PAWN) >= 2);
235 mi->scalingFunction[WHITE] = &ScaleKPsK;
237 else if (pos.piece_count(WHITE, PAWN) == 0)
239 assert(pos.piece_count(BLACK, PAWN) >= 2);
240 mi->scalingFunction[BLACK] = &ScaleKKPs;
242 else if (pos.piece_count(WHITE, PAWN) == 1 && pos.piece_count(BLACK, PAWN) == 1)
244 mi->scalingFunction[WHITE] = &ScaleKPKPw;
245 mi->scalingFunction[BLACK] = &ScaleKPKPb;
249 // Compute the space weight
250 if (pos.non_pawn_material(WHITE) + pos.non_pawn_material(BLACK) >=
251 2*QueenValueMidgame + 4*RookValueMidgame + 2*KnightValueMidgame)
253 int minorPieceCount = pos.piece_count(WHITE, KNIGHT)
254 + pos.piece_count(BLACK, KNIGHT)
255 + pos.piece_count(WHITE, BISHOP)
256 + pos.piece_count(BLACK, BISHOP);
258 mi->spaceWeight = minorPieceCount * minorPieceCount;
261 // Evaluate the material balance
262 const int pieceCount[2][6] = { { pos.piece_count(WHITE, BISHOP) > 1, pos.piece_count(WHITE, PAWN), pos.piece_count(WHITE, KNIGHT),
263 pos.piece_count(WHITE, BISHOP), pos.piece_count(WHITE, ROOK), pos.piece_count(WHITE, QUEEN) },
264 { pos.piece_count(BLACK, BISHOP) > 1, pos.piece_count(BLACK, PAWN), pos.piece_count(BLACK, KNIGHT),
265 pos.piece_count(BLACK, BISHOP), pos.piece_count(BLACK, ROOK), pos.piece_count(BLACK, QUEEN) } };
270 for (c = WHITE, sign = 1; c <= BLACK; c++, sign = -sign)
272 // No pawns makes it difficult to win, even with a material advantage
273 if ( pos.piece_count(c, PAWN) == 0
274 && pos.non_pawn_material(c) - pos.non_pawn_material(opposite_color(c)) <= BishopValueMidgame)
276 if ( pos.non_pawn_material(c) == pos.non_pawn_material(opposite_color(c))
277 || pos.non_pawn_material(c) < RookValueMidgame)
281 switch (pos.piece_count(c, BISHOP)) {
295 // Redundancy of major pieces, formula based on Kaufman's paper
296 // "The Evaluation of Material Imbalances in Chess"
297 // http://mywebpages.comcast.net/danheisman/Articles/evaluation_of_material_imbalance.htm
298 if (pieceCount[c][ROOK] >= 1)
299 matValue -= sign * ((pieceCount[c][ROOK] - 1) * RedundantRookPenalty + pieceCount[c][QUEEN] * RedundantQueenPenalty);
301 // Second-degree polynomial material imbalance by Tord Romstad
303 // We use NO_PIECE_TYPE as a place holder for the bishop pair "extended piece",
304 // this allow us to be more flexible in defining bishop pair bonuses.
305 them = opposite_color(c);
306 for (int pt1 = NO_PIECE_TYPE; pt1 <= QUEEN; pt1++)
308 int c1 = sign * pieceCount[c][pt1];
312 matValue += c1 * LinearCoefficients[pt1];
314 for (int pt2 = NO_PIECE_TYPE; pt2 <= pt1; pt2++)
316 matValue += c1 * pieceCount[c][pt2] * QuadraticCoefficientsSameColor[pt1][pt2];
317 matValue += c1 * pieceCount[them][pt2] * QuadraticCoefficientsOppositeColor[pt1][pt2];
322 mi->value = int16_t(matValue / 16);
327 /// EndgameFunctions member definitions. This class is used to store the maps
328 /// of end game and scaling functions that MaterialInfoTable will query for
329 /// each key. The maps are constant and are populated only at construction,
330 /// but are per-thread instead of globals to avoid expensive locks needed
331 /// because std::map is not guaranteed to be thread-safe even if accessed
332 /// only for a lookup.
334 EndgameFunctions::EndgameFunctions() {
336 add<EvaluationFunction<KNNK> >("KNNK");
337 add<EvaluationFunction<KPK> >("KPK");
338 add<EvaluationFunction<KBNK> >("KBNK");
339 add<EvaluationFunction<KRKP> >("KRKP");
340 add<EvaluationFunction<KRKB> >("KRKB");
341 add<EvaluationFunction<KRKN> >("KRKN");
342 add<EvaluationFunction<KQKR> >("KQKR");
343 add<EvaluationFunction<KBBKN> >("KBBKN");
345 add<ScalingFunction<KNPK> >("KNPK");
346 add<ScalingFunction<KRPKR> >("KRPKR");
347 add<ScalingFunction<KBPKB> >("KBPKB");
348 add<ScalingFunction<KBPPKB> >("KBPPKB");
349 add<ScalingFunction<KBPKN> >("KBPKN");
350 add<ScalingFunction<KRPPKRP> >("KRPPKRP");
351 add<ScalingFunction<KRPPKRP> >("KRPPKRP");
354 EndgameFunctions::~EndgameFunctions() {
356 for (map<Key, EF*>::iterator it = maps.first.begin(); it != maps.first.end(); ++it)
359 for (map<Key, SF*>::iterator it = maps.second.begin(); it != maps.second.end(); ++it)
363 Key EndgameFunctions::buildKey(const string& keyCode) {
365 assert(keyCode.length() > 0 && keyCode[0] == 'K');
366 assert(keyCode.length() < 8);
371 // Build up a fen substring with the given pieces, note
372 // that the fen string could be of an illegal position.
373 for (size_t i = 0; i < keyCode.length(); i++)
375 if (keyCode[i] == 'K')
378 s << char(upcase? toupper(keyCode[i]) : tolower(keyCode[i]));
380 s << 8 - keyCode.length() << "/8/8/8/8/8/8/8 w -";
381 return Position(s.str()).get_material_key();
384 const string EndgameFunctions::swapColors(const string& keyCode) {
386 // Build corresponding key for the opposite color: "KBPKN" -> "KNKBP"
387 size_t idx = keyCode.find("K", 1);
388 return keyCode.substr(idx) + keyCode.substr(0, idx);
392 void EndgameFunctions::add(const string& keyCode) {
394 typedef typename T::Base F;
396 get<F>().insert(pair<Key, F*>(buildKey(keyCode), new T(WHITE)));
397 get<F>().insert(pair<Key, F*>(buildKey(swapColors(keyCode)), new T(BLACK)));
401 T* EndgameFunctions::get(Key key) const {
403 typename map<Key, T*>::const_iterator it(get<T>().find(key));
404 return (it != get<T>().end() ? it->second : NULL);