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