]> git.sesse.net Git - stockfish/blob - src/material.cpp
Material: lockless per-thread maps
[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 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 <map>
27
28 #include "material.h"
29
30
31 ////
32 //// Local definitions
33 ////
34
35 namespace {
36
37   const Value BishopPairMidgameBonus = Value(100);
38   const Value BishopPairEndgameBonus = Value(100);
39
40   Key KNNKMaterialKey, KKNNMaterialKey;
41
42   struct ScalingInfo
43   {
44       Color col;
45       ScalingFunction* fun;
46   };
47
48 }
49
50 ////
51 //// Classes
52 ////
53
54 class EndgameFunctions {
55
56 public:
57   EndgameFunctions();
58   EndgameEvaluationFunction* getEEF(Key key);
59   ScalingInfo getESF(Key key);
60
61 private:
62   void add(Key k, EndgameEvaluationFunction* f);
63   void add(Key k, Color c, ScalingFunction* f);
64
65   std::map<Key, EndgameEvaluationFunction*> EEFmap;
66   std::map<Key, ScalingInfo> ESFmap;
67 };
68
69
70 ////
71 //// Functions
72 ////
73
74 /// MaterialInfo::init() is called during program initialization. It
75 /// precomputes material hash keys for a few basic endgames, in order
76 /// to make it easy to recognize such endgames when they occur.
77
78 void MaterialInfo::init() {
79
80   typedef Key ZM[2][8][16];
81   const ZM& z = Position::zobMaterial;
82
83   KNNKMaterialKey = z[WHITE][KNIGHT][1] ^ z[WHITE][KNIGHT][2];
84   KKNNMaterialKey = z[BLACK][KNIGHT][1] ^ z[BLACK][KNIGHT][2];
85 }
86
87
88 /// Constructor for the MaterialInfoTable class
89
90 MaterialInfoTable::MaterialInfoTable(unsigned int numOfEntries) {
91
92   size = numOfEntries;
93   entries = new MaterialInfo[size];
94   funcs = new EndgameFunctions();
95   if (!entries || !funcs)
96   {
97       std::cerr << "Failed to allocate " << (numOfEntries * sizeof(MaterialInfo))
98                 << " bytes for material hash table." << std::endl;
99       exit(EXIT_FAILURE);
100   }
101   clear();
102 }
103
104
105 /// Destructor for the MaterialInfoTable class
106
107 MaterialInfoTable::~MaterialInfoTable() {
108
109   delete [] entries;
110   delete funcs;
111 }
112
113
114 /// MaterialInfoTable::clear() clears a material hash table by setting
115 /// all entries to 0.
116
117 void MaterialInfoTable::clear() {
118
119   memset(entries, 0, size * sizeof(MaterialInfo));
120 }
121
122
123 /// MaterialInfoTable::get_material_info() takes a position object as input,
124 /// computes or looks up a MaterialInfo object, and returns a pointer to it.
125 /// If the material configuration is not already present in the table, it
126 /// is stored there, so we don't have to recompute everything when the
127 /// same material configuration occurs again.
128
129 MaterialInfo *MaterialInfoTable::get_material_info(const Position& pos) {
130
131   Key key = pos.get_material_key();
132   int index = key & (size - 1);
133   MaterialInfo* mi = entries + index;
134
135   // If mi->key matches the position's material hash key, it means that we
136   // have analysed this material configuration before, and we can simply
137   // return the information we found the last time instead of recomputing it.
138   if (mi->key == key)
139     return mi;
140
141   // Clear the MaterialInfo object, and set its key
142   mi->clear();
143   mi->key = key;
144
145   // A special case before looking for a specialized evaluation function
146   // KNN vs K is a draw.
147   if (key == KNNKMaterialKey || key == KKNNMaterialKey)
148   {
149     mi->factor[WHITE] = mi->factor[BLACK] = 0;
150     return mi;
151   }
152
153   // Let's look if we have a specialized evaluation function for this
154   // particular material configuration.
155   if ((mi->evaluationFunction = funcs->getEEF(key)) != NULL)
156       return mi;
157
158   else if (   pos.non_pawn_material(BLACK) == Value(0)
159            && pos.piece_count(BLACK, PAWN) == 0
160            && pos.non_pawn_material(WHITE) >= RookValueEndgame)
161   {
162       mi->evaluationFunction = &EvaluateKXK;
163       return mi;
164   }
165   else if (   pos.non_pawn_material(WHITE) == Value(0)
166            && pos.piece_count(WHITE, PAWN) == 0
167            && pos.non_pawn_material(BLACK) >= RookValueEndgame)
168   {
169       mi->evaluationFunction = &EvaluateKKX;
170       return mi;
171   }
172
173   // OK, we didn't find any special evaluation function for the current
174   // material configuration. Is there a suitable scaling function?
175   //
176   // The code below is rather messy, and it could easily get worse later,
177   // if we decide to add more special cases.  We face problems when there
178   // are several conflicting applicable scaling functions and we need to
179   // decide which one to use.
180   ScalingInfo si = funcs->getESF(key);
181   if (si.fun != NULL)
182   {
183       mi->scalingFunction[si.col] = si.fun;
184       return mi;
185   }
186
187   if (   pos.non_pawn_material(WHITE) == BishopValueMidgame
188       && pos.piece_count(WHITE, BISHOP) == 1
189       && pos.piece_count(WHITE, PAWN) >= 1)
190       mi->scalingFunction[WHITE] = &ScaleKBPK;
191
192   if (   pos.non_pawn_material(BLACK) == BishopValueMidgame
193       && pos.piece_count(BLACK, BISHOP) == 1
194       && pos.piece_count(BLACK, PAWN) >= 1)
195       mi->scalingFunction[BLACK] = &ScaleKKBP;
196
197   if (   pos.piece_count(WHITE, PAWN) == 0
198       && pos.non_pawn_material(WHITE) == QueenValueMidgame
199       && pos.piece_count(WHITE, QUEEN) == 1
200       && pos.piece_count(BLACK, ROOK) == 1
201       && pos.piece_count(BLACK, PAWN) >= 1)
202       mi->scalingFunction[WHITE] = &ScaleKQKRP;
203
204   else if (   pos.piece_count(BLACK, PAWN) == 0
205            && pos.non_pawn_material(BLACK) == QueenValueMidgame
206            && pos.piece_count(BLACK, QUEEN) == 1
207            && pos.piece_count(WHITE, ROOK) == 1
208            && pos.piece_count(WHITE, PAWN) >= 1)
209       mi->scalingFunction[BLACK] = &ScaleKRPKQ;
210
211   if (pos.non_pawn_material(WHITE) + pos.non_pawn_material(BLACK) == Value(0))
212   {
213       if (pos.piece_count(BLACK, PAWN) == 0)
214       {
215           assert(pos.piece_count(WHITE, PAWN) >= 2);
216           mi->scalingFunction[WHITE] = &ScaleKPsK;
217       }
218       else if (pos.piece_count(WHITE, PAWN) == 0)
219       {
220           assert(pos.piece_count(BLACK, PAWN) >= 2);
221           mi->scalingFunction[BLACK] = &ScaleKKPs;
222       }
223       else if (pos.piece_count(WHITE, PAWN) == 1 && pos.piece_count(BLACK, PAWN) == 1)
224       {
225           mi->scalingFunction[WHITE] = &ScaleKPKPw;
226           mi->scalingFunction[BLACK] = &ScaleKPKPb;
227       }
228   }
229
230   // Evaluate the material balance
231
232   Color c;
233   int sign;
234   Value egValue = Value(0);
235   Value mgValue = Value(0);
236
237   for (c = WHITE, sign = 1; c <= BLACK; c++, sign = -sign)
238   {
239     // No pawns makes it difficult to win, even with a material advantage
240     if (   pos.piece_count(c, PAWN) == 0
241         && pos.non_pawn_material(c) - pos.non_pawn_material(opposite_color(c)) <= BishopValueMidgame)
242     {
243         if (   pos.non_pawn_material(c) == pos.non_pawn_material(opposite_color(c))
244             || pos.non_pawn_material(c) < RookValueMidgame)
245             mi->factor[c] = 0;
246         else
247         {
248             switch (pos.piece_count(c, BISHOP)) {
249             case 2:
250                 mi->factor[c] = 32;
251                 break;
252             case 1:
253                 mi->factor[c] = 12;
254                 break;
255             case 0:
256                 mi->factor[c] = 6;
257                 break;
258             }
259         }
260     }
261
262     // Bishop pair
263     if (pos.piece_count(c, BISHOP) >= 2)
264     {
265         mgValue += sign * BishopPairMidgameBonus;
266         egValue += sign * BishopPairEndgameBonus;
267     }
268
269     // Knights are stronger when there are many pawns on the board.  The
270     // formula is taken from Larry Kaufman's paper "The Evaluation of Material
271     // Imbalances in Chess":
272     // http://mywebpages.comcast.net/danheisman/Articles/evaluation_of_material_imbalance.htm
273     mgValue += sign * Value(pos.piece_count(c, KNIGHT)*(pos.piece_count(c, PAWN)-5)*16);
274     egValue += sign * Value(pos.piece_count(c, KNIGHT)*(pos.piece_count(c, PAWN)-5)*16);
275
276     // Redundancy of major pieces, again based on Kaufman's paper:
277     if (pos.piece_count(c, ROOK) >= 1)
278     {
279         Value v = Value((pos.piece_count(c, ROOK) - 1) * 32 + pos.piece_count(c, QUEEN) * 16);
280         mgValue -= sign * v;
281         egValue -= sign * v;
282     }
283   }
284
285   mi->mgValue = int16_t(mgValue);
286   mi->egValue = int16_t(egValue);
287   return mi;
288 }
289
290
291 /// EndgameFunctions members definition. This helper class is used to
292 /// store the maps of end game and scaling functions that MaterialInfoTable
293 /// will query for each key. The maps are constant, and are populated only
294 /// at construction. Being per thread avoids to use locks to access them.
295
296 EndgameFunctions::EndgameFunctions() {
297
298   typedef Key ZM[2][8][16];
299   const ZM& z = Position::zobMaterial;
300
301   static const Color W = WHITE;
302   static const Color B = BLACK;
303
304   KNNKMaterialKey = z[W][KNIGHT][1] ^ z[W][KNIGHT][2];
305   KKNNMaterialKey = z[B][KNIGHT][1] ^ z[B][KNIGHT][2];
306
307   add(z[W][PAWN][1], &EvaluateKPK);
308   add(z[B][PAWN][1], &EvaluateKKP);
309
310   add(z[W][BISHOP][1] ^ z[W][KNIGHT][1], &EvaluateKBNK);
311   add(z[B][BISHOP][1] ^ z[B][KNIGHT][1], &EvaluateKKBN);
312   add(z[W][ROOK][1]   ^ z[B][PAWN][1],   &EvaluateKRKP);
313   add(z[W][PAWN][1]   ^ z[B][ROOK][1],   &EvaluateKPKR);
314   add(z[W][ROOK][1]   ^ z[B][BISHOP][1], &EvaluateKRKB);
315   add(z[W][BISHOP][1] ^ z[B][ROOK][1],   &EvaluateKBKR);
316   add(z[W][ROOK][1]   ^ z[B][KNIGHT][1], &EvaluateKRKN);
317   add(z[W][KNIGHT][1] ^ z[B][ROOK][1],   &EvaluateKNKR);
318   add(z[W][QUEEN][1]  ^ z[B][ROOK][1],   &EvaluateKQKR);
319   add(z[W][ROOK][1]   ^ z[B][QUEEN][1],  &EvaluateKRKQ);
320
321   add(z[W][KNIGHT][1] ^ z[W][PAWN][1], W, &ScaleKNPK);
322   add(z[B][KNIGHT][1] ^ z[B][PAWN][1], B, &ScaleKKNP);
323
324   add(z[W][ROOK][1]   ^ z[W][PAWN][1]   ^ z[B][ROOK][1]  , W, &ScaleKRPKR);
325   add(z[W][ROOK][1]   ^ z[B][ROOK][1]   ^ z[B][PAWN][1]  , B, &ScaleKRKRP);
326   add(z[W][BISHOP][1] ^ z[W][PAWN][1]   ^ z[B][BISHOP][1], W, &ScaleKBPKB);
327   add(z[W][BISHOP][1] ^ z[B][BISHOP][1] ^ z[B][PAWN][1]  , B, &ScaleKBKBP);
328   add(z[W][BISHOP][1] ^ z[W][PAWN][1]   ^ z[B][KNIGHT][1], W, &ScaleKBPKN);
329   add(z[W][KNIGHT][1] ^ z[B][BISHOP][1] ^ z[B][PAWN][1]  , B, &ScaleKNKBP);
330
331   add(z[W][ROOK][1] ^ z[W][PAWN][1] ^ z[W][PAWN][2] ^ z[B][ROOK][1] ^ z[B][PAWN][1], W, &ScaleKRPPKRP);
332   add(z[W][ROOK][1] ^ z[W][PAWN][1] ^ z[B][ROOK][1] ^ z[B][PAWN][1] ^ z[B][PAWN][2], B, &ScaleKRPKRPP);
333 }
334
335 void EndgameFunctions::add(Key k, EndgameEvaluationFunction* f) {
336
337   EEFmap.insert(std::pair<Key, EndgameEvaluationFunction*>(k, f));
338 }
339
340 void EndgameFunctions::add(Key k, Color c, ScalingFunction* f) {
341
342   ScalingInfo s = {c, f};
343   ESFmap.insert(std::pair<Key, ScalingInfo>(k, s));
344 }
345
346 EndgameEvaluationFunction* EndgameFunctions::getEEF(Key key) {
347
348   EndgameEvaluationFunction* f = NULL;
349   std::map<Key, EndgameEvaluationFunction*>::iterator it(EEFmap.find(key));
350   if (it != EEFmap.end())
351       f = it->second;
352
353   return f;
354 }
355
356 ScalingInfo EndgameFunctions::getESF(Key key) {
357
358   ScalingInfo si = {WHITE, NULL};
359   std::map<Key, ScalingInfo>::iterator it(ESFmap.find(key));
360   if (it != ESFmap.end())
361       si = it->second;
362
363   return si;
364 }