]> git.sesse.net Git - stockfish/blob - src/material.cpp
Correctly set mateThreat in search()
[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   Key KNNKMaterialKey, KKNNMaterialKey;
44
45   // Unmapped endgame evaluation and scaling functions, these
46   // are accessed direcly and not through the function maps.
47   EvaluationFunction<KmmKm> EvaluateKmmKm(WHITE);
48   EvaluationFunction<KXK>   EvaluateKXK(WHITE), EvaluateKKX(BLACK);
49   ScalingFunction<KBPK>     ScaleKBPK(WHITE),   ScaleKKBP(BLACK);
50   ScalingFunction<KQKRP>    ScaleKQKRP(WHITE),  ScaleKRPKQ(BLACK);
51   ScalingFunction<KPsK>     ScaleKPsK(WHITE),   ScaleKKPs(BLACK);
52   ScalingFunction<KPKP>     ScaleKPKPw(WHITE),  ScaleKPKPb(BLACK);
53 }
54
55
56 ////
57 //// Classes
58 ////
59
60 typedef EndgameEvaluationFunctionBase EF;
61 typedef EndgameScalingFunctionBase SF;
62
63 /// See header for a class description. It is declared here to avoid
64 /// to include <map> in the header file.
65
66 class EndgameFunctions {
67 public:
68   EndgameFunctions();
69   ~EndgameFunctions();
70   template<class T> T* get(Key key) const;
71
72 private:
73   template<class T> void add(const string& keyCode);
74
75   static Key buildKey(const string& keyCode);
76   static const string swapColors(const string& keyCode);
77
78   std::map<Key, EF*> EEFmap;
79   std::map<Key, SF*> ESFmap;
80
81   // Maps accessing functions for const and non-const references
82   template<typename T> const std::map<Key, T*>& map() const { return EEFmap; }
83   template<typename T> std::map<Key, T*>& map() { return EEFmap; }
84 };
85
86 // Explicit specializations of a member function shall be declared in
87 // the namespace of which the class template is a member.
88 template<> const std::map<Key, SF*>&
89 EndgameFunctions::map<SF>() const { return ESFmap; }
90
91 template<> std::map<Key, SF*>&
92 EndgameFunctions::map<SF>() { return ESFmap; }
93
94
95 ////
96 //// Functions
97 ////
98
99
100 /// Constructor for the MaterialInfoTable class
101
102 MaterialInfoTable::MaterialInfoTable(unsigned int numOfEntries) {
103
104   size = numOfEntries;
105   entries = new MaterialInfo[size];
106   funcs = new EndgameFunctions();
107   if (!entries || !funcs)
108   {
109       std::cerr << "Failed to allocate " << (numOfEntries * sizeof(MaterialInfo))
110                 << " bytes for material hash table." << std::endl;
111       Application::exit_with_failure();
112   }
113 }
114
115
116 /// Destructor for the MaterialInfoTable class
117
118 MaterialInfoTable::~MaterialInfoTable() {
119
120   delete funcs;
121   delete [] entries;
122 }
123
124
125 /// MaterialInfoTable::get_material_info() takes a position object as input,
126 /// computes or looks up a MaterialInfo object, and returns a pointer to it.
127 /// If the material configuration is not already present in the table, it
128 /// is stored there, so we don't have to recompute everything when the
129 /// same material configuration occurs again.
130
131 MaterialInfo* MaterialInfoTable::get_material_info(const Position& pos) {
132
133   Key key = pos.get_material_key();
134   int index = key & (size - 1);
135   MaterialInfo* mi = entries + index;
136
137   // If mi->key matches the position's material hash key, it means that we
138   // have analysed this material configuration before, and we can simply
139   // return the information we found the last time instead of recomputing it.
140   if (mi->key == key)
141       return mi;
142
143   // Clear the MaterialInfo object, and set its key
144   mi->clear();
145   mi->key = key;
146
147   // A special case before looking for a specialized evaluation function
148   // KNN vs K is a draw.
149   if (key == KNNKMaterialKey || key == KKNNMaterialKey)
150   {
151       mi->factor[WHITE] = mi->factor[BLACK] = 0;
152       return mi;
153   }
154
155   // Let's look if we have a specialized evaluation function for this
156   // particular material configuration. First we look for a fixed
157   // configuration one, then a generic one if previous search failed.
158   if ((mi->evaluationFunction = funcs->get<EF>(key)) != NULL)
159       return mi;
160
161   else if (   pos.non_pawn_material(BLACK) == Value(0)
162            && pos.piece_count(BLACK, PAWN) == 0
163            && pos.non_pawn_material(WHITE) >= RookValueMidgame)
164   {
165       mi->evaluationFunction = &EvaluateKXK;
166       return mi;
167   }
168   else if (   pos.non_pawn_material(WHITE) == Value(0)
169            && pos.piece_count(WHITE, PAWN) == 0
170            && pos.non_pawn_material(BLACK) >= RookValueMidgame)
171   {
172       mi->evaluationFunction = &EvaluateKKX;
173       return mi;
174   }
175   else if (   pos.pawns() == EmptyBoardBB
176            && pos.rooks() == EmptyBoardBB
177            && pos.queens() == EmptyBoardBB)
178   {
179       // Minor piece endgame with at least one minor piece per side,
180       // and no pawns.
181       assert(pos.knights(WHITE) | pos.bishops(WHITE));
182       assert(pos.knights(BLACK) | pos.bishops(BLACK));
183
184       if (   pos.piece_count(WHITE, BISHOP) + pos.piece_count(WHITE, KNIGHT) <= 2
185           && pos.piece_count(BLACK, BISHOP) + pos.piece_count(BLACK, KNIGHT) <= 2)
186       {
187           mi->evaluationFunction = &EvaluateKmmKm;
188           return mi;
189       }
190   }
191
192   // OK, we didn't find any special evaluation function for the current
193   // material configuration. Is there a suitable scaling function?
194   //
195   // The code below is rather messy, and it could easily get worse later,
196   // if we decide to add more special cases. We face problems when there
197   // are several conflicting applicable scaling functions and we need to
198   // decide which one to use.
199   SF* sf;
200
201   if ((sf = funcs->get<SF>(key)) != NULL)
202   {
203       mi->scalingFunction[sf->color()] = sf;
204       return mi;
205   }
206
207   if (   pos.non_pawn_material(WHITE) == BishopValueMidgame
208       && pos.piece_count(WHITE, BISHOP) == 1
209       && pos.piece_count(WHITE, PAWN) >= 1)
210       mi->scalingFunction[WHITE] = &ScaleKBPK;
211
212   if (   pos.non_pawn_material(BLACK) == BishopValueMidgame
213       && pos.piece_count(BLACK, BISHOP) == 1
214       && pos.piece_count(BLACK, PAWN) >= 1)
215       mi->scalingFunction[BLACK] = &ScaleKKBP;
216
217   if (   pos.piece_count(WHITE, PAWN) == 0
218       && pos.non_pawn_material(WHITE) == QueenValueMidgame
219       && pos.piece_count(WHITE, QUEEN) == 1
220       && pos.piece_count(BLACK, ROOK) == 1
221       && pos.piece_count(BLACK, PAWN) >= 1)
222       mi->scalingFunction[WHITE] = &ScaleKQKRP;
223
224   else if (   pos.piece_count(BLACK, PAWN) == 0
225            && pos.non_pawn_material(BLACK) == QueenValueMidgame
226            && pos.piece_count(BLACK, QUEEN) == 1
227            && pos.piece_count(WHITE, ROOK) == 1
228            && pos.piece_count(WHITE, PAWN) >= 1)
229       mi->scalingFunction[BLACK] = &ScaleKRPKQ;
230
231   if (pos.non_pawn_material(WHITE) + pos.non_pawn_material(BLACK) == Value(0))
232   {
233       if (pos.piece_count(BLACK, PAWN) == 0)
234       {
235           assert(pos.piece_count(WHITE, PAWN) >= 2);
236           mi->scalingFunction[WHITE] = &ScaleKPsK;
237       }
238       else if (pos.piece_count(WHITE, PAWN) == 0)
239       {
240           assert(pos.piece_count(BLACK, PAWN) >= 2);
241           mi->scalingFunction[BLACK] = &ScaleKKPs;
242       }
243       else if (pos.piece_count(WHITE, PAWN) == 1 && pos.piece_count(BLACK, PAWN) == 1)
244       {
245           mi->scalingFunction[WHITE] = &ScaleKPKPw;
246           mi->scalingFunction[BLACK] = &ScaleKPKPb;
247       }
248   }
249
250   // Compute the space weight
251   if (pos.non_pawn_material(WHITE) + pos.non_pawn_material(BLACK) >=
252       2*QueenValueMidgame + 4*RookValueMidgame + 2*KnightValueMidgame)
253   {
254       int minorPieceCount =  pos.piece_count(WHITE, KNIGHT)
255                            + pos.piece_count(BLACK, KNIGHT)
256                            + pos.piece_count(WHITE, BISHOP)
257                            + pos.piece_count(BLACK, BISHOP);
258
259       mi->spaceWeight = minorPieceCount * minorPieceCount;
260   }
261
262   // Evaluate the material balance
263
264   Color c;
265   int sign;
266   Value egValue = Value(0);
267   Value mgValue = Value(0);
268
269   for (c = WHITE, sign = 1; c <= BLACK; c++, sign = -sign)
270   {
271     // No pawns makes it difficult to win, even with a material advantage
272     if (   pos.piece_count(c, PAWN) == 0
273         && pos.non_pawn_material(c) - pos.non_pawn_material(opposite_color(c)) <= BishopValueMidgame)
274     {
275         if (   pos.non_pawn_material(c) == pos.non_pawn_material(opposite_color(c))
276             || pos.non_pawn_material(c) < RookValueMidgame)
277             mi->factor[c] = 0;
278         else
279         {
280             switch (pos.piece_count(c, BISHOP)) {
281             case 2:
282                 mi->factor[c] = 32;
283                 break;
284             case 1:
285                 mi->factor[c] = 12;
286                 break;
287             case 0:
288                 mi->factor[c] = 6;
289                 break;
290             }
291         }
292     }
293
294     // Bishop pair
295     if (pos.piece_count(c, BISHOP) >= 2)
296     {
297         mgValue += sign * BishopPairMidgameBonus;
298         egValue += sign * BishopPairEndgameBonus;
299     }
300
301     // Knights are stronger when there are many pawns on the board.  The
302     // formula is taken from Larry Kaufman's paper "The Evaluation of Material
303     // Imbalances in Chess":
304     // http://mywebpages.comcast.net/danheisman/Articles/evaluation_of_material_imbalance.htm
305     mgValue += sign * Value(pos.piece_count(c, KNIGHT)*(pos.piece_count(c, PAWN)-5)*16);
306     egValue += sign * Value(pos.piece_count(c, KNIGHT)*(pos.piece_count(c, PAWN)-5)*16);
307
308     // Redundancy of major pieces, again based on Kaufman's paper:
309     if (pos.piece_count(c, ROOK) >= 1)
310     {
311         Value v = Value((pos.piece_count(c, ROOK) - 1) * 32 + pos.piece_count(c, QUEEN) * 16);
312         mgValue -= sign * v;
313         egValue -= sign * v;
314     }
315   }
316   mi->mgValue = int16_t(mgValue);
317   mi->egValue = int16_t(egValue);
318   return mi;
319 }
320
321
322 /// EndgameFunctions member definitions. This class is used to store the maps
323 /// of end game and scaling functions that MaterialInfoTable will query for
324 /// each key. The maps are constant and are populated only at construction,
325 /// but are per-thread instead of globals to avoid expensive locks needed
326 /// because std::map is not guaranteed to be thread-safe even if accessed
327 /// only for a lookup.
328
329 EndgameFunctions::EndgameFunctions() {
330
331   KNNKMaterialKey = buildKey("KNNK");
332   KKNNMaterialKey = buildKey("KKNN");
333
334   add<EvaluationFunction<KPK>   >("KPK");
335   add<EvaluationFunction<KBNK>  >("KBNK");
336   add<EvaluationFunction<KRKP>  >("KRKP");
337   add<EvaluationFunction<KRKB>  >("KRKB");
338   add<EvaluationFunction<KRKN>  >("KRKN");
339   add<EvaluationFunction<KQKR>  >("KQKR");
340   add<EvaluationFunction<KBBKN> >("KBBKN");
341
342   add<ScalingFunction<KNPK>    >("KNPK");
343   add<ScalingFunction<KRPKR>   >("KRPKR");
344   add<ScalingFunction<KBPKB>   >("KBPKB");
345   add<ScalingFunction<KBPPKB>  >("KBPPKB");
346   add<ScalingFunction<KBPKN>   >("KBPKN");
347   add<ScalingFunction<KRPPKRP> >("KRPPKRP");
348   add<ScalingFunction<KRPPKRP> >("KRPPKRP");
349 }
350
351 EndgameFunctions::~EndgameFunctions() {
352
353     for (std::map<Key, EF*>::iterator it = EEFmap.begin(); it != EEFmap.end(); ++it)
354         delete (*it).second;
355
356     for (std::map<Key, SF*>::iterator it = ESFmap.begin(); it != ESFmap.end(); ++it)
357         delete (*it).second;
358 }
359
360 Key EndgameFunctions::buildKey(const string& keyCode) {
361
362     assert(keyCode.length() > 0 && keyCode[0] == 'K');
363     assert(keyCode.length() < 8);
364
365     std::stringstream s;
366     bool upcase = false;
367
368     // Build up a fen substring with the given pieces, note
369     // that the fen string could be of an illegal position.
370     for (size_t i = 0; i < keyCode.length(); i++)
371     {
372         if (keyCode[i] == 'K')
373             upcase = !upcase;
374
375         s << char(upcase? toupper(keyCode[i]) : tolower(keyCode[i]));
376     }
377     s << 8 - keyCode.length() << "/8/8/8/8/8/8/8 w -";
378     return Position(s.str()).get_material_key();
379 }
380
381 const string EndgameFunctions::swapColors(const string& keyCode) {
382
383     // Build corresponding key for the opposite color: "KBPKN" -> "KNKBP"
384     size_t idx = keyCode.find("K", 1);
385     return keyCode.substr(idx) + keyCode.substr(0, idx);
386 }
387
388 template<class T>
389 void EndgameFunctions::add(const string& keyCode) {
390
391   typedef typename T::Base F;
392
393   map<F>().insert(std::pair<Key, F*>(buildKey(keyCode), new T(WHITE)));
394   map<F>().insert(std::pair<Key, F*>(buildKey(swapColors(keyCode)), new T(BLACK)));
395 }
396
397 template<class T>
398 T* EndgameFunctions::get(Key key) const {
399
400   typename std::map<Key, T*>::const_iterator it(map<T>().find(key));
401   return (it != map<T>().end() ? it->second : NULL);
402 }