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 // Values modified by Joona Kiiski
40 const Value BishopPairMidgameBonus = Value(109);
41 const Value BishopPairEndgameBonus = Value(97);
43 // Polynomial material balance parameters
44 const Value RedundantQueenPenalty = Value(358);
45 const Value RedundantRookPenalty = Value(536);
46 const int LinearCoefficients[6] = { 1740, -146, -1246, -197, 206, -7 };
48 const int QuadraticCoefficientsSameColor[][6] = {
49 { 0, 0, 0, 0, 0, 0 }, { 31, -4, 0, 0, 0, 0 }, { 14, 267, -21, 0, 0, 0 },
50 { 0, 7, -26, 0, 0, 0 }, { -3, -1, 69, 162, 80, 0 }, { 40, 27, 119, 174, -64, -49 } };
52 const int QuadraticCoefficientsOppositeColor[][6] = {
53 { 0, 0, 0, 0, 0, 0 }, { -9, 0, 0, 0, 0, 0 }, { 49, 32, 0, 0, 0, 0 },
54 { -25, 19, -5, 0, 0, 0 }, { 97, -6, 39, -88, 0, 0 }, { 77, 69, -42, 104, 116, 0 } };
56 // Unmapped endgame evaluation and scaling functions, these
57 // are accessed direcly and not through the function maps.
58 EvaluationFunction<KmmKm> EvaluateKmmKm(WHITE);
59 EvaluationFunction<KXK> EvaluateKXK(WHITE), EvaluateKKX(BLACK);
60 ScalingFunction<KBPK> ScaleKBPK(WHITE), ScaleKKBP(BLACK);
61 ScalingFunction<KQKRP> ScaleKQKRP(WHITE), ScaleKRPKQ(BLACK);
62 ScalingFunction<KPsK> ScaleKPsK(WHITE), ScaleKKPs(BLACK);
63 ScalingFunction<KPKP> ScaleKPKPw(WHITE), ScaleKPKPb(BLACK);
65 Key KNNKMaterialKey, KKNNMaterialKey;
73 typedef EndgameEvaluationFunctionBase EF;
74 typedef EndgameScalingFunctionBase SF;
76 /// See header for a class description. It is declared here to avoid
77 /// to include <map> in the header file.
79 class EndgameFunctions {
83 template<class T> T* get(Key key) const;
86 template<class T> void add(const string& keyCode);
88 static Key buildKey(const string& keyCode);
89 static const string swapColors(const string& keyCode);
91 std::map<Key, EF*> EEFmap;
92 std::map<Key, SF*> ESFmap;
94 // Maps accessing functions for const and non-const references
95 template<typename T> const std::map<Key, T*>& map() const { return EEFmap; }
96 template<typename T> std::map<Key, T*>& map() { return EEFmap; }
99 // Explicit specializations of a member function shall be declared in
100 // the namespace of which the class template is a member.
101 template<> const std::map<Key, SF*>&
102 EndgameFunctions::map<SF>() const { return ESFmap; }
104 template<> std::map<Key, SF*>&
105 EndgameFunctions::map<SF>() { return ESFmap; }
113 /// Constructor for the MaterialInfoTable class
115 MaterialInfoTable::MaterialInfoTable(unsigned int numOfEntries) {
118 entries = new MaterialInfo[size];
119 funcs = new EndgameFunctions();
120 if (!entries || !funcs)
122 std::cerr << "Failed to allocate " << (numOfEntries * sizeof(MaterialInfo))
123 << " bytes for material hash table." << std::endl;
124 Application::exit_with_failure();
129 /// Destructor for the MaterialInfoTable class
131 MaterialInfoTable::~MaterialInfoTable() {
138 /// MaterialInfoTable::get_material_info() takes a position object as input,
139 /// computes or looks up a MaterialInfo object, and returns a pointer to it.
140 /// If the material configuration is not already present in the table, it
141 /// is stored there, so we don't have to recompute everything when the
142 /// same material configuration occurs again.
144 MaterialInfo* MaterialInfoTable::get_material_info(const Position& pos) {
146 Key key = pos.get_material_key();
147 int index = key & (size - 1);
148 MaterialInfo* mi = entries + index;
150 // If mi->key matches the position's material hash key, it means that we
151 // have analysed this material configuration before, and we can simply
152 // return the information we found the last time instead of recomputing it.
156 // Clear the MaterialInfo object, and set its key
160 // A special case before looking for a specialized evaluation function
161 // KNN vs K is a draw.
162 if (key == KNNKMaterialKey || key == KKNNMaterialKey)
164 mi->factor[WHITE] = mi->factor[BLACK] = 0;
168 // Let's look if we have a specialized evaluation function for this
169 // particular material configuration. First we look for a fixed
170 // configuration one, then a generic one if previous search failed.
171 if ((mi->evaluationFunction = funcs->get<EF>(key)) != NULL)
174 else if ( pos.non_pawn_material(BLACK) == Value(0)
175 && pos.piece_count(BLACK, PAWN) == 0
176 && pos.non_pawn_material(WHITE) >= RookValueMidgame)
178 mi->evaluationFunction = &EvaluateKXK;
181 else if ( pos.non_pawn_material(WHITE) == Value(0)
182 && pos.piece_count(WHITE, PAWN) == 0
183 && pos.non_pawn_material(BLACK) >= RookValueMidgame)
185 mi->evaluationFunction = &EvaluateKKX;
188 else if ( pos.pawns() == EmptyBoardBB
189 && pos.rooks() == EmptyBoardBB
190 && pos.queens() == EmptyBoardBB)
192 // Minor piece endgame with at least one minor piece per side,
194 assert(pos.knights(WHITE) | pos.bishops(WHITE));
195 assert(pos.knights(BLACK) | pos.bishops(BLACK));
197 if ( pos.piece_count(WHITE, BISHOP) + pos.piece_count(WHITE, KNIGHT) <= 2
198 && pos.piece_count(BLACK, BISHOP) + pos.piece_count(BLACK, KNIGHT) <= 2)
200 mi->evaluationFunction = &EvaluateKmmKm;
205 // OK, we didn't find any special evaluation function for the current
206 // material configuration. Is there a suitable scaling function?
208 // The code below is rather messy, and it could easily get worse later,
209 // if we decide to add more special cases. We face problems when there
210 // are several conflicting applicable scaling functions and we need to
211 // decide which one to use.
214 if ((sf = funcs->get<SF>(key)) != NULL)
216 mi->scalingFunction[sf->color()] = sf;
220 if ( pos.non_pawn_material(WHITE) == BishopValueMidgame
221 && pos.piece_count(WHITE, BISHOP) == 1
222 && pos.piece_count(WHITE, PAWN) >= 1)
223 mi->scalingFunction[WHITE] = &ScaleKBPK;
225 if ( pos.non_pawn_material(BLACK) == BishopValueMidgame
226 && pos.piece_count(BLACK, BISHOP) == 1
227 && pos.piece_count(BLACK, PAWN) >= 1)
228 mi->scalingFunction[BLACK] = &ScaleKKBP;
230 if ( pos.piece_count(WHITE, PAWN) == 0
231 && pos.non_pawn_material(WHITE) == QueenValueMidgame
232 && pos.piece_count(WHITE, QUEEN) == 1
233 && pos.piece_count(BLACK, ROOK) == 1
234 && pos.piece_count(BLACK, PAWN) >= 1)
235 mi->scalingFunction[WHITE] = &ScaleKQKRP;
237 else if ( pos.piece_count(BLACK, PAWN) == 0
238 && pos.non_pawn_material(BLACK) == QueenValueMidgame
239 && pos.piece_count(BLACK, QUEEN) == 1
240 && pos.piece_count(WHITE, ROOK) == 1
241 && pos.piece_count(WHITE, PAWN) >= 1)
242 mi->scalingFunction[BLACK] = &ScaleKRPKQ;
244 if (pos.non_pawn_material(WHITE) + pos.non_pawn_material(BLACK) == Value(0))
246 if (pos.piece_count(BLACK, PAWN) == 0)
248 assert(pos.piece_count(WHITE, PAWN) >= 2);
249 mi->scalingFunction[WHITE] = &ScaleKPsK;
251 else if (pos.piece_count(WHITE, PAWN) == 0)
253 assert(pos.piece_count(BLACK, PAWN) >= 2);
254 mi->scalingFunction[BLACK] = &ScaleKKPs;
256 else if (pos.piece_count(WHITE, PAWN) == 1 && pos.piece_count(BLACK, PAWN) == 1)
258 mi->scalingFunction[WHITE] = &ScaleKPKPw;
259 mi->scalingFunction[BLACK] = &ScaleKPKPb;
263 // Compute the space weight
264 if (pos.non_pawn_material(WHITE) + pos.non_pawn_material(BLACK) >=
265 2*QueenValueMidgame + 4*RookValueMidgame + 2*KnightValueMidgame)
267 int minorPieceCount = pos.piece_count(WHITE, KNIGHT)
268 + pos.piece_count(BLACK, KNIGHT)
269 + pos.piece_count(WHITE, BISHOP)
270 + pos.piece_count(BLACK, BISHOP);
272 mi->spaceWeight = minorPieceCount * minorPieceCount;
275 // Evaluate the material balance
277 const int bishopsPair_count[2] = { pos.piece_count(WHITE, BISHOP) > 1, pos.piece_count(BLACK, BISHOP) > 1 };
282 for (c = WHITE, sign = 1; c <= BLACK; c++, sign = -sign)
284 // No pawns makes it difficult to win, even with a material advantage
285 if ( pos.piece_count(c, PAWN) == 0
286 && pos.non_pawn_material(c) - pos.non_pawn_material(opposite_color(c)) <= BishopValueMidgame)
288 if ( pos.non_pawn_material(c) == pos.non_pawn_material(opposite_color(c))
289 || pos.non_pawn_material(c) < RookValueMidgame)
293 switch (pos.piece_count(c, BISHOP)) {
307 // Redundancy of major pieces, formula based on Kaufman's paper
308 // "The Evaluation of Material Imbalances in Chess"
309 // http://mywebpages.comcast.net/danheisman/Articles/evaluation_of_material_imbalance.htm
310 if (pos.piece_count(c, ROOK) >= 1)
311 matValue -= sign * ((pos.piece_count(c, ROOK) - 1) * RedundantRookPenalty + pos.piece_count(c, QUEEN) * RedundantQueenPenalty);
313 // Second-degree polynomial material imbalance by Tord Romstad
315 // We use NO_PIECE_TYPE as a place holder for the bishop pair "extended piece",
316 // this allow us to be more flexible in defining bishop pair bonuses.
317 them = opposite_color(c);
318 for (PieceType pt1 = NO_PIECE_TYPE; pt1 <= QUEEN; pt1++)
321 c1 = sign * (pt1 != NO_PIECE_TYPE ? pos.piece_count(c, pt1) : bishopsPair_count[c]);
325 matValue += c1 * LinearCoefficients[pt1];
327 for (PieceType pt2 = NO_PIECE_TYPE; pt2 <= pt1; pt2++)
329 c2 = (pt2 != NO_PIECE_TYPE ? pos.piece_count(c, pt2) : bishopsPair_count[c]);
330 c3 = (pt2 != NO_PIECE_TYPE ? pos.piece_count(them, pt2) : bishopsPair_count[them]);
331 matValue += c1 * c2 * QuadraticCoefficientsSameColor[pt1][pt2];
332 matValue += c1 * c3 * QuadraticCoefficientsOppositeColor[pt1][pt2];
337 mi->value = int16_t(matValue / 16);
342 /// EndgameFunctions member definitions. This class is used to store the maps
343 /// of end game and scaling functions that MaterialInfoTable will query for
344 /// each key. The maps are constant and are populated only at construction,
345 /// but are per-thread instead of globals to avoid expensive locks needed
346 /// because std::map is not guaranteed to be thread-safe even if accessed
347 /// only for a lookup.
349 EndgameFunctions::EndgameFunctions() {
351 KNNKMaterialKey = buildKey("KNNK");
352 KKNNMaterialKey = buildKey("KKNN");
354 add<EvaluationFunction<KPK> >("KPK");
355 add<EvaluationFunction<KBNK> >("KBNK");
356 add<EvaluationFunction<KRKP> >("KRKP");
357 add<EvaluationFunction<KRKB> >("KRKB");
358 add<EvaluationFunction<KRKN> >("KRKN");
359 add<EvaluationFunction<KQKR> >("KQKR");
360 add<EvaluationFunction<KBBKN> >("KBBKN");
362 add<ScalingFunction<KNPK> >("KNPK");
363 add<ScalingFunction<KRPKR> >("KRPKR");
364 add<ScalingFunction<KBPKB> >("KBPKB");
365 add<ScalingFunction<KBPPKB> >("KBPPKB");
366 add<ScalingFunction<KBPKN> >("KBPKN");
367 add<ScalingFunction<KRPPKRP> >("KRPPKRP");
368 add<ScalingFunction<KRPPKRP> >("KRPPKRP");
371 EndgameFunctions::~EndgameFunctions() {
373 for (std::map<Key, EF*>::iterator it = EEFmap.begin(); it != EEFmap.end(); ++it)
376 for (std::map<Key, SF*>::iterator it = ESFmap.begin(); it != ESFmap.end(); ++it)
380 Key EndgameFunctions::buildKey(const string& keyCode) {
382 assert(keyCode.length() > 0 && keyCode[0] == 'K');
383 assert(keyCode.length() < 8);
388 // Build up a fen substring with the given pieces, note
389 // that the fen string could be of an illegal position.
390 for (size_t i = 0; i < keyCode.length(); i++)
392 if (keyCode[i] == 'K')
395 s << char(upcase? toupper(keyCode[i]) : tolower(keyCode[i]));
397 s << 8 - keyCode.length() << "/8/8/8/8/8/8/8 w -";
398 return Position(s.str()).get_material_key();
401 const string EndgameFunctions::swapColors(const string& keyCode) {
403 // Build corresponding key for the opposite color: "KBPKN" -> "KNKBP"
404 size_t idx = keyCode.find("K", 1);
405 return keyCode.substr(idx) + keyCode.substr(0, idx);
409 void EndgameFunctions::add(const string& keyCode) {
411 typedef typename T::Base F;
413 map<F>().insert(std::pair<Key, F*>(buildKey(keyCode), new T(WHITE)));
414 map<F>().insert(std::pair<Key, F*>(buildKey(swapColors(keyCode)), new T(BLACK)));
418 T* EndgameFunctions::get(Key key) const {
420 typename std::map<Key, T*>::const_iterator it(map<T>().find(key));
421 return (it != map<T>().end() ? it->second : NULL);