]> git.sesse.net Git - stockfish/blob - src/material.cpp
Add Tord's polynomial material balance
[stockfish] / src / material.cpp
1 /*
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
5
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.
10
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.
15
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/>.
18 */
19
20
21 ////
22 //// Includes
23 ////
24
25 #include <cassert>
26 #include <sstream>
27 #include <map>
28
29 #include "material.h"
30
31 using std::string;
32
33 ////
34 //// Local definitions
35 ////
36
37 namespace {
38
39   // Values modified by Joona Kiiski
40   const Value BishopPairMidgameBonus = Value(109);
41   const Value BishopPairEndgameBonus = Value(97);
42
43   // Polynomial material balance parameters
44   const Value RedundantQueenPenalty = Value(320);
45   const Value RedundantRookPenalty  = Value(554);
46   const int LinearCoefficients[6]   = { 1709, -137, -1185, -166, 141, 59 };
47
48   const int QuadraticCoefficientsSameColor[][6] = {
49   { 0, 0, 0, 0, 0, 0 }, { 33, -6, 0, 0, 0, 0 }, { 29, 269, -12, 0, 0, 0 },
50   { 0, 19, -4, 0, 0, 0 }, { -35, -10, 40, 95, 50, 0 }, { 52, 23, 78, 144, -11, -33 } };
51
52   const int QuadraticCoefficientsOppositeColor[][6] = {
53   { 0, 0, 0, 0, 0, 0 }, { -5, 0, 0, 0, 0, 0 }, { -33, 23, 0, 0, 0, 0 },
54   { 17, 25, -3, 0, 0, 0 }, { 10, -2, -19, -67, 0, 0 }, { 69, 64, -41, 116, 137, 0 } };
55
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);
64
65   Key KNNKMaterialKey, KKNNMaterialKey;
66 }
67
68
69 ////
70 //// Classes
71 ////
72
73 typedef EndgameEvaluationFunctionBase EF;
74 typedef EndgameScalingFunctionBase SF;
75
76 /// See header for a class description. It is declared here to avoid
77 /// to include <map> in the header file.
78
79 class EndgameFunctions {
80 public:
81   EndgameFunctions();
82   ~EndgameFunctions();
83   template<class T> T* get(Key key) const;
84
85 private:
86   template<class T> void add(const string& keyCode);
87
88   static Key buildKey(const string& keyCode);
89   static const string swapColors(const string& keyCode);
90
91   std::map<Key, EF*> EEFmap;
92   std::map<Key, SF*> ESFmap;
93
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; }
97 };
98
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; }
103
104 template<> std::map<Key, SF*>&
105 EndgameFunctions::map<SF>() { return ESFmap; }
106
107
108 ////
109 //// Functions
110 ////
111
112
113 /// Constructor for the MaterialInfoTable class
114
115 MaterialInfoTable::MaterialInfoTable(unsigned int numOfEntries) {
116
117   size = numOfEntries;
118   entries = new MaterialInfo[size];
119   funcs = new EndgameFunctions();
120   if (!entries || !funcs)
121   {
122       std::cerr << "Failed to allocate " << (numOfEntries * sizeof(MaterialInfo))
123                 << " bytes for material hash table." << std::endl;
124       Application::exit_with_failure();
125   }
126 }
127
128
129 /// Destructor for the MaterialInfoTable class
130
131 MaterialInfoTable::~MaterialInfoTable() {
132
133   delete funcs;
134   delete [] entries;
135 }
136
137
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.
143
144 MaterialInfo* MaterialInfoTable::get_material_info(const Position& pos) {
145
146   Key key = pos.get_material_key();
147   int index = key & (size - 1);
148   MaterialInfo* mi = entries + index;
149
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.
153   if (mi->key == key)
154       return mi;
155
156   // Clear the MaterialInfo object, and set its key
157   mi->clear();
158   mi->key = key;
159
160   // A special case before looking for a specialized evaluation function
161   // KNN vs K is a draw.
162   if (key == KNNKMaterialKey || key == KKNNMaterialKey)
163   {
164       mi->factor[WHITE] = mi->factor[BLACK] = 0;
165       return mi;
166   }
167
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)
172       return mi;
173
174   else if (   pos.non_pawn_material(BLACK) == Value(0)
175            && pos.piece_count(BLACK, PAWN) == 0
176            && pos.non_pawn_material(WHITE) >= RookValueMidgame)
177   {
178       mi->evaluationFunction = &EvaluateKXK;
179       return mi;
180   }
181   else if (   pos.non_pawn_material(WHITE) == Value(0)
182            && pos.piece_count(WHITE, PAWN) == 0
183            && pos.non_pawn_material(BLACK) >= RookValueMidgame)
184   {
185       mi->evaluationFunction = &EvaluateKKX;
186       return mi;
187   }
188   else if (   pos.pawns() == EmptyBoardBB
189            && pos.rooks() == EmptyBoardBB
190            && pos.queens() == EmptyBoardBB)
191   {
192       // Minor piece endgame with at least one minor piece per side,
193       // and no pawns.
194       assert(pos.knights(WHITE) | pos.bishops(WHITE));
195       assert(pos.knights(BLACK) | pos.bishops(BLACK));
196
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)
199       {
200           mi->evaluationFunction = &EvaluateKmmKm;
201           return mi;
202       }
203   }
204
205   // OK, we didn't find any special evaluation function for the current
206   // material configuration. Is there a suitable scaling function?
207   //
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.
212   SF* sf;
213
214   if ((sf = funcs->get<SF>(key)) != NULL)
215   {
216       mi->scalingFunction[sf->color()] = sf;
217       return mi;
218   }
219
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;
224
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;
229
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;
236
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;
243
244   if (pos.non_pawn_material(WHITE) + pos.non_pawn_material(BLACK) == Value(0))
245   {
246       if (pos.piece_count(BLACK, PAWN) == 0)
247       {
248           assert(pos.piece_count(WHITE, PAWN) >= 2);
249           mi->scalingFunction[WHITE] = &ScaleKPsK;
250       }
251       else if (pos.piece_count(WHITE, PAWN) == 0)
252       {
253           assert(pos.piece_count(BLACK, PAWN) >= 2);
254           mi->scalingFunction[BLACK] = &ScaleKKPs;
255       }
256       else if (pos.piece_count(WHITE, PAWN) == 1 && pos.piece_count(BLACK, PAWN) == 1)
257       {
258           mi->scalingFunction[WHITE] = &ScaleKPKPw;
259           mi->scalingFunction[BLACK] = &ScaleKPKPb;
260       }
261   }
262
263   // Compute the space weight
264   if (pos.non_pawn_material(WHITE) + pos.non_pawn_material(BLACK) >=
265       2*QueenValueMidgame + 4*RookValueMidgame + 2*KnightValueMidgame)
266   {
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);
271
272       mi->spaceWeight = minorPieceCount * minorPieceCount;
273   }
274
275   // Evaluate the material balance
276
277   const int bishopsPair_count[2] = { pos.piece_count(WHITE, BISHOP) > 1, pos.piece_count(BLACK, BISHOP) > 1 };
278   Color c, them;
279   int sign;
280   int matValue = 0;
281
282   for (c = WHITE, sign = 1; c <= BLACK; c++, sign = -sign)
283   {
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)
287     {
288         if (   pos.non_pawn_material(c) == pos.non_pawn_material(opposite_color(c))
289             || pos.non_pawn_material(c) < RookValueMidgame)
290             mi->factor[c] = 0;
291         else
292         {
293             switch (pos.piece_count(c, BISHOP)) {
294             case 2:
295                 mi->factor[c] = 32;
296                 break;
297             case 1:
298                 mi->factor[c] = 12;
299                 break;
300             case 0:
301                 mi->factor[c] = 6;
302                 break;
303             }
304         }
305     }
306
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);
312
313     // Second-degree polynomial material imbalance by Tord Romstad
314     //
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++)
319     {
320         int c1, c2, c3;
321         c1 = sign * (pt1 != NO_PIECE_TYPE ? pos.piece_count(c, pt1) : bishopsPair_count[c]);
322         if (!c1)
323             continue;
324
325         matValue += c1 * LinearCoefficients[pt1];
326
327         for (PieceType pt2 = NO_PIECE_TYPE; pt2 <= pt1; pt2++)
328         {
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];
333         }
334     }
335   }
336
337   mi->value = int16_t(matValue / 16);
338   return mi;
339 }
340
341
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.
348
349 EndgameFunctions::EndgameFunctions() {
350
351   KNNKMaterialKey = buildKey("KNNK");
352   KKNNMaterialKey = buildKey("KKNN");
353
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");
361
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");
369 }
370
371 EndgameFunctions::~EndgameFunctions() {
372
373     for (std::map<Key, EF*>::iterator it = EEFmap.begin(); it != EEFmap.end(); ++it)
374         delete (*it).second;
375
376     for (std::map<Key, SF*>::iterator it = ESFmap.begin(); it != ESFmap.end(); ++it)
377         delete (*it).second;
378 }
379
380 Key EndgameFunctions::buildKey(const string& keyCode) {
381
382     assert(keyCode.length() > 0 && keyCode[0] == 'K');
383     assert(keyCode.length() < 8);
384
385     std::stringstream s;
386     bool upcase = false;
387
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++)
391     {
392         if (keyCode[i] == 'K')
393             upcase = !upcase;
394
395         s << char(upcase? toupper(keyCode[i]) : tolower(keyCode[i]));
396     }
397     s << 8 - keyCode.length() << "/8/8/8/8/8/8/8 w -";
398     return Position(s.str()).get_material_key();
399 }
400
401 const string EndgameFunctions::swapColors(const string& keyCode) {
402
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);
406 }
407
408 template<class T>
409 void EndgameFunctions::add(const string& keyCode) {
410
411   typedef typename T::Base F;
412
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)));
415 }
416
417 template<class T>
418 T* EndgameFunctions::get(Key key) const {
419
420   typename std::map<Key, T*>::const_iterator it(map<T>().find(key));
421   return (it != map<T>().end() ? it->second : NULL);
422 }