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