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