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