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