]> git.sesse.net Git - stockfish/blob - src/material.cpp
Define Score as an enum
[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 namespace std;
32
33
34 ////
35 //// Local definitions
36 ////
37
38 namespace {
39
40   // Polynomial material balance parameters
41   const Value RedundantQueenPenalty = Value(320);
42   const Value RedundantRookPenalty  = Value(554);
43   const int LinearCoefficients[6]   = { 1617, -162, -1172, -190, 105, 26 };
44
45   const int QuadraticCoefficientsSameColor[][6] = {
46   { 7, 7, 7, 7, 7, 7 }, { 39, 2, 7, 7, 7, 7 }, { 35, 271, -4, 7, 7, 7 },
47   { 7, 25, 4, 7, 7, 7 }, { -27, -2, 46, 100, 56, 7 }, { 58, 29, 83, 148, -3, -25 } };
48
49   const int QuadraticCoefficientsOppositeColor[][6] = {
50   { 41, 41, 41, 41, 41, 41 }, { 37, 41, 41, 41, 41, 41 }, { 10, 62, 41, 41, 41, 41 },
51   { 57, 64, 39, 41, 41, 41 }, { 50, 40, 23, -22, 41, 41 }, { 106, 101, 3, 151, 171, 41 } };
52
53   // Named endgame evaluation and scaling functions, these
54   // are accessed direcly and not through the function maps.
55   EvaluationFunction<KmmKm> EvaluateKmmKm(WHITE);
56   EvaluationFunction<KXK>   EvaluateKXK(WHITE), EvaluateKKX(BLACK);
57   ScalingFunction<KBPsK>    ScaleKBPsK(WHITE),  ScaleKKBPs(BLACK);
58   ScalingFunction<KQKRPs>   ScaleKQKRPs(WHITE), ScaleKRPsKQ(BLACK);
59   ScalingFunction<KPsK>     ScaleKPsK(WHITE),   ScaleKKPs(BLACK);
60   ScalingFunction<KPKP>     ScaleKPKPw(WHITE),  ScaleKPKPb(BLACK);
61
62   typedef EndgameEvaluationFunctionBase EF;
63   typedef EndgameScalingFunctionBase SF;
64 }
65
66
67 ////
68 //// Classes
69 ////
70
71 /// EndgameFunctions class stores endgame evaluation and scaling functions
72 /// in two std::map. Because STL library is not guaranteed to be thread
73 /// safe even for read access, the maps, although with identical content,
74 /// are replicated for each thread. This is faster then using locks.
75
76 class EndgameFunctions {
77 public:
78   EndgameFunctions();
79   ~EndgameFunctions();
80   template<class T> T* get(Key key) const;
81
82 private:
83   template<class T> void add(const string& keyCode);
84
85   static Key buildKey(const string& keyCode);
86   static const string swapColors(const string& keyCode);
87
88   // Here we store two maps, for evaluate and scaling functions
89   pair<map<Key, EF*>, map<Key, SF*> > maps;
90
91   // Maps accessing functions returning const and non-const references
92   template<typename T> const map<Key, T*>& get() const { return maps.first; }
93   template<typename T> map<Key, T*>& get() { return maps.first; }
94 };
95
96 // Explicit specializations of a member function shall be declared in
97 // the namespace of which the class template is a member.
98 template<> const map<Key, SF*>&
99 EndgameFunctions::get<SF>() const { return maps.second; }
100
101 template<> map<Key, SF*>&
102 EndgameFunctions::get<SF>() { return maps.second; }
103
104
105 ////
106 //// Functions
107 ////
108
109 /// MaterialInfoTable c'tor and d'tor, called once by each thread
110
111 MaterialInfoTable::MaterialInfoTable(unsigned int numOfEntries) {
112
113   size = numOfEntries;
114   entries = new MaterialInfo[size];
115   funcs = new EndgameFunctions();
116
117   if (!entries || !funcs)
118   {
119       cerr << "Failed to allocate " << numOfEntries * sizeof(MaterialInfo)
120            << " bytes for material hash table." << endl;
121       Application::exit_with_failure();
122   }
123 }
124
125 MaterialInfoTable::~MaterialInfoTable() {
126
127   delete funcs;
128   delete [] entries;
129 }
130
131
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.
137
138 MaterialInfo* MaterialInfoTable::get_material_info(const Position& pos) {
139
140   Key key = pos.get_material_key();
141   int index = key & (size - 1);
142   MaterialInfo* mi = entries + index;
143
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.
147   if (mi->key == key)
148       return mi;
149
150   // Clear the MaterialInfo object, and set its key
151   mi->clear();
152   mi->key = key;
153
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)
158       return mi;
159
160   else if (   pos.non_pawn_material(BLACK) == Value(0)
161            && pos.piece_count(BLACK, PAWN) == 0
162            && pos.non_pawn_material(WHITE) >= RookValueMidgame)
163   {
164       mi->evaluationFunction = &EvaluateKXK;
165       return mi;
166   }
167   else if (   pos.non_pawn_material(WHITE) == Value(0)
168            && pos.piece_count(WHITE, PAWN) == 0
169            && pos.non_pawn_material(BLACK) >= RookValueMidgame)
170   {
171       mi->evaluationFunction = &EvaluateKKX;
172       return mi;
173   }
174   else if (   pos.pieces(PAWN) == EmptyBoardBB
175            && pos.pieces(ROOK) == EmptyBoardBB
176            && pos.pieces(QUEEN) == EmptyBoardBB)
177   {
178       // Minor piece endgame with at least one minor piece per side and
179       // no pawns. Note that the case KmmK is already handled by KXK.
180       assert((pos.pieces(KNIGHT, WHITE) | pos.pieces(BISHOP, WHITE)));
181       assert((pos.pieces(KNIGHT, BLACK) | pos.pieces(BISHOP, BLACK)));
182
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)
185       {
186           mi->evaluationFunction = &EvaluateKmmKm;
187           return mi;
188       }
189   }
190
191   // OK, we didn't find any special evaluation function for the current
192   // material configuration. Is there a suitable scaling function?
193   //
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.
198   SF* sf;
199
200   if ((sf = funcs->get<SF>(key)) != NULL)
201   {
202       mi->scalingFunction[sf->color()] = sf;
203       return mi;
204   }
205
206   // Generic scaling functions that refer to more then one material
207   // distribution. Should be probed after the specialized ones.
208   // Note that these ones don't return after setting the function.
209   if (   pos.non_pawn_material(WHITE) == BishopValueMidgame
210       && pos.piece_count(WHITE, BISHOP) == 1
211       && pos.piece_count(WHITE, PAWN) >= 1)
212       mi->scalingFunction[WHITE] = &ScaleKBPsK;
213
214   if (   pos.non_pawn_material(BLACK) == BishopValueMidgame
215       && pos.piece_count(BLACK, BISHOP) == 1
216       && pos.piece_count(BLACK, PAWN) >= 1)
217       mi->scalingFunction[BLACK] = &ScaleKKBPs;
218
219   if (   pos.piece_count(WHITE, PAWN) == 0
220       && pos.non_pawn_material(WHITE) == QueenValueMidgame
221       && pos.piece_count(WHITE, QUEEN) == 1
222       && pos.piece_count(BLACK, ROOK) == 1
223       && pos.piece_count(BLACK, PAWN) >= 1)
224       mi->scalingFunction[WHITE] = &ScaleKQKRPs;
225
226   else if (   pos.piece_count(BLACK, PAWN) == 0
227            && pos.non_pawn_material(BLACK) == QueenValueMidgame
228            && pos.piece_count(BLACK, QUEEN) == 1
229            && pos.piece_count(WHITE, ROOK) == 1
230            && pos.piece_count(WHITE, PAWN) >= 1)
231       mi->scalingFunction[BLACK] = &ScaleKRPsKQ;
232
233   if (pos.non_pawn_material(WHITE) + pos.non_pawn_material(BLACK) == Value(0))
234   {
235       if (pos.piece_count(BLACK, PAWN) == 0)
236       {
237           assert(pos.piece_count(WHITE, PAWN) >= 2);
238           mi->scalingFunction[WHITE] = &ScaleKPsK;
239       }
240       else if (pos.piece_count(WHITE, PAWN) == 0)
241       {
242           assert(pos.piece_count(BLACK, PAWN) >= 2);
243           mi->scalingFunction[BLACK] = &ScaleKKPs;
244       }
245       else if (pos.piece_count(WHITE, PAWN) == 1 && pos.piece_count(BLACK, PAWN) == 1)
246       {
247           // This is a special case because we set scaling functions
248           // for both colors instead of only one.
249           mi->scalingFunction[WHITE] = &ScaleKPKPw;
250           mi->scalingFunction[BLACK] = &ScaleKPKPb;
251       }
252   }
253
254   // Compute the space weight
255   if (pos.non_pawn_material(WHITE) + pos.non_pawn_material(BLACK) >=
256       2*QueenValueMidgame + 4*RookValueMidgame + 2*KnightValueMidgame)
257   {
258       int minorPieceCount =  pos.piece_count(WHITE, KNIGHT)
259                            + pos.piece_count(BLACK, KNIGHT)
260                            + pos.piece_count(WHITE, BISHOP)
261                            + pos.piece_count(BLACK, BISHOP);
262
263       mi->spaceWeight = minorPieceCount * minorPieceCount;
264   }
265
266   // Evaluate the material balance
267   const int pieceCount[2][6] = { { pos.piece_count(WHITE, BISHOP) > 1, pos.piece_count(WHITE, PAWN), pos.piece_count(WHITE, KNIGHT),
268                                    pos.piece_count(WHITE, BISHOP), pos.piece_count(WHITE, ROOK), pos.piece_count(WHITE, QUEEN) },
269                                  { pos.piece_count(BLACK, BISHOP) > 1, pos.piece_count(BLACK, PAWN), pos.piece_count(BLACK, KNIGHT),
270                                    pos.piece_count(BLACK, BISHOP), pos.piece_count(BLACK, ROOK), pos.piece_count(BLACK, QUEEN) } };
271   Color c, them;
272   int sign;
273   int matValue = 0;
274
275   for (c = WHITE, sign = 1; c <= BLACK; c++, sign = -sign)
276   {
277     // No pawns makes it difficult to win, even with a material advantage
278     if (   pos.piece_count(c, PAWN) == 0
279         && pos.non_pawn_material(c) - pos.non_pawn_material(opposite_color(c)) <= BishopValueMidgame)
280     {
281         if (   pos.non_pawn_material(c) == pos.non_pawn_material(opposite_color(c))
282             || pos.non_pawn_material(c) < RookValueMidgame)
283             mi->factor[c] = 0;
284         else
285         {
286             switch (pos.piece_count(c, BISHOP)) {
287             case 2:
288                 mi->factor[c] = 32;
289                 break;
290             case 1:
291                 mi->factor[c] = 12;
292                 break;
293             case 0:
294                 mi->factor[c] = 6;
295                 break;
296             }
297         }
298     }
299
300     // Redundancy of major pieces, formula based on Kaufman's paper
301     // "The Evaluation of Material Imbalances in Chess"
302     // http://mywebpages.comcast.net/danheisman/Articles/evaluation_of_material_imbalance.htm
303     if (pieceCount[c][ROOK] >= 1)
304         matValue -= sign * ((pieceCount[c][ROOK] - 1) * RedundantRookPenalty + pieceCount[c][QUEEN] * RedundantQueenPenalty);
305
306     them = opposite_color(c);
307
308     // Second-degree polynomial material imbalance by Tord Romstad
309     //
310     // We use NO_PIECE_TYPE as a place holder for the bishop pair "extended piece",
311     // this allow us to be more flexible in defining bishop pair bonuses.
312     for (int pt1 = NO_PIECE_TYPE; pt1 <= QUEEN; pt1++)
313     {
314         int c1 = sign * pieceCount[c][pt1];
315         if (!c1)
316             continue;
317
318         matValue += c1 * LinearCoefficients[pt1];
319
320         for (int pt2 = NO_PIECE_TYPE; pt2 <= pt1; pt2++)
321         {
322             matValue += c1 * pieceCount[c][pt2] * QuadraticCoefficientsSameColor[pt1][pt2];
323             matValue += c1 * pieceCount[them][pt2] * QuadraticCoefficientsOppositeColor[pt1][pt2];
324         }
325     }
326   }
327   mi->value = int16_t(matValue / 16);
328   return mi;
329 }
330
331
332 /// EndgameFunctions member definitions.
333
334 EndgameFunctions::EndgameFunctions() {
335
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");
344
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");
352 }
353
354 EndgameFunctions::~EndgameFunctions() {
355
356     for (map<Key, EF*>::iterator it = maps.first.begin(); it != maps.first.end(); ++it)
357         delete (*it).second;
358
359     for (map<Key, SF*>::iterator it = maps.second.begin(); it != maps.second.end(); ++it)
360         delete (*it).second;
361 }
362
363 Key EndgameFunctions::buildKey(const string& keyCode) {
364
365     assert(keyCode.length() > 0 && keyCode[0] == 'K');
366     assert(keyCode.length() < 8);
367
368     stringstream s;
369     bool upcase = false;
370
371     // Build up a fen string with the given pieces, note that
372     // the fen string could be of an illegal position.
373     for (size_t i = 0; i < keyCode.length(); i++)
374     {
375         if (keyCode[i] == 'K')
376             upcase = !upcase;
377
378         s << char(upcase? toupper(keyCode[i]) : tolower(keyCode[i]));
379     }
380     s << 8 - keyCode.length() << "/8/8/8/8/8/8/8 w -";
381     return Position(s.str()).get_material_key();
382 }
383
384 const string EndgameFunctions::swapColors(const string& keyCode) {
385
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);
389 }
390
391 template<class T>
392 void EndgameFunctions::add(const string& keyCode) {
393
394   typedef typename T::Base F;
395
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)));
398 }
399
400 template<class T>
401 T* EndgameFunctions::get(Key key) const {
402
403   typename map<Key, T*>::const_iterator it(get<T>().find(key));
404   return (it != get<T>().end() ? it->second : NULL);
405 }