]> git.sesse.net Git - stockfish/blob - src/material.cpp
Add TT prefetching support
[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 namespace std;
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   // Polynomial material balance parameters
44   const Value RedundantQueenPenalty = Value(320);
45   const Value RedundantRookPenalty  = Value(554);
46   const int LinearCoefficients[6]   = { 1709, -137, -1185, -166, 141, 59 };
47
48   const int QuadraticCoefficientsSameColor[][6] = {
49   { 0, 0, 0, 0, 0, 0 }, { 33, -6, 0, 0, 0, 0 }, { 29, 269, -12, 0, 0, 0 },
50   { 0, 19, -4, 0, 0, 0 }, { -35, -10, 40, 95, 50, 0 }, { 52, 23, 78, 144, -11, -33 } };
51
52   const int QuadraticCoefficientsOppositeColor[][6] = {
53   { 0, 0, 0, 0, 0, 0 }, { -5, 0, 0, 0, 0, 0 }, { -33, 23, 0, 0, 0, 0 },
54   { 17, 25, -3, 0, 0, 0 }, { 10, -2, -19, -67, 0, 0 }, { 69, 64, -41, 116, 137, 0 } };
55
56   // Unmapped endgame evaluation and scaling functions, these
57   // are accessed direcly and not through the function maps.
58   EvaluationFunction<KmmKm> EvaluateKmmKm(WHITE);
59   EvaluationFunction<KXK>   EvaluateKXK(WHITE), EvaluateKKX(BLACK);
60   ScalingFunction<KBPK>     ScaleKBPK(WHITE),   ScaleKKBP(BLACK);
61   ScalingFunction<KQKRP>    ScaleKQKRP(WHITE),  ScaleKRPKQ(BLACK);
62   ScalingFunction<KPsK>     ScaleKPsK(WHITE),   ScaleKKPs(BLACK);
63   ScalingFunction<KPKP>     ScaleKPKPw(WHITE),  ScaleKPKPb(BLACK);
64 }
65
66
67 ////
68 //// Classes
69 ////
70
71 typedef EndgameEvaluationFunctionBase EF;
72 typedef EndgameScalingFunctionBase SF;
73
74 /// See header for a class description. It is declared here to avoid
75 /// to include <map> in the header file.
76
77 class EndgameFunctions {
78 public:
79   EndgameFunctions();
80   ~EndgameFunctions();
81   template<class T> T* get(Key key) const;
82
83 private:
84   template<class T> void add(const string& keyCode);
85
86   static Key buildKey(const string& keyCode);
87   static const string swapColors(const string& keyCode);
88
89   // Here we store two maps, one for evaluate and one for scaling
90   pair<map<Key, EF*>, map<Key, SF*> > maps;
91
92   // Maps accessing functions for const and non-const references
93   template<typename T> const map<Key, T*>& get() const { return maps.first; }
94   template<typename T> map<Key, T*>& get() { return maps.first; }
95 };
96
97 // Explicit specializations of a member function shall be declared in
98 // the namespace of which the class template is a member.
99 template<> const map<Key, SF*>&
100 EndgameFunctions::get<SF>() const { return maps.second; }
101
102 template<> map<Key, SF*>&
103 EndgameFunctions::get<SF>() { return maps.second; }
104
105
106 ////
107 //// Functions
108 ////
109
110
111 /// Constructor for the MaterialInfoTable class
112
113 MaterialInfoTable::MaterialInfoTable(unsigned int numOfEntries) {
114
115   size = numOfEntries;
116   entries = new MaterialInfo[size];
117   funcs = new EndgameFunctions();
118   if (!entries || !funcs)
119   {
120       cerr << "Failed to allocate " << (numOfEntries * sizeof(MaterialInfo))
121            << " bytes for material hash table." << endl;
122       Application::exit_with_failure();
123   }
124 }
125
126
127 /// Destructor for the MaterialInfoTable class
128
129 MaterialInfoTable::~MaterialInfoTable() {
130
131   delete funcs;
132   delete [] entries;
133 }
134
135
136 /// MaterialInfoTable::get_material_info() takes a position object as input,
137 /// computes or looks up a MaterialInfo object, and returns a pointer to it.
138 /// If the material configuration is not already present in the table, it
139 /// is stored there, so we don't have to recompute everything when the
140 /// same material configuration occurs again.
141
142 MaterialInfo* MaterialInfoTable::get_material_info(const Position& pos) {
143
144   Key key = pos.get_material_key();
145   int index = key & (size - 1);
146   MaterialInfo* mi = entries + index;
147
148   // If mi->key matches the position's material hash key, it means that we
149   // have analysed this material configuration before, and we can simply
150   // return the information we found the last time instead of recomputing it.
151   if (mi->key == key)
152       return mi;
153
154   // Clear the MaterialInfo object, and set its key
155   mi->clear();
156   mi->key = key;
157
158   // Let's look if we have a specialized evaluation function for this
159   // particular material configuration. First we look for a fixed
160   // configuration one, then a generic one if previous search failed.
161   if ((mi->evaluationFunction = funcs->get<EF>(key)) != NULL)
162       return mi;
163
164   else if (   pos.non_pawn_material(BLACK) == Value(0)
165            && pos.piece_count(BLACK, PAWN) == 0
166            && pos.non_pawn_material(WHITE) >= RookValueMidgame)
167   {
168       mi->evaluationFunction = &EvaluateKXK;
169       return mi;
170   }
171   else if (   pos.non_pawn_material(WHITE) == Value(0)
172            && pos.piece_count(WHITE, PAWN) == 0
173            && pos.non_pawn_material(BLACK) >= RookValueMidgame)
174   {
175       mi->evaluationFunction = &EvaluateKKX;
176       return mi;
177   }
178   else if (   pos.pawns() == EmptyBoardBB
179            && pos.rooks() == EmptyBoardBB
180            && pos.queens() == EmptyBoardBB)
181   {
182       // Minor piece endgame with at least one minor piece per side,
183       // and no pawns.
184       assert(pos.knights(WHITE) | pos.bishops(WHITE));
185       assert(pos.knights(BLACK) | pos.bishops(BLACK));
186
187       if (   pos.piece_count(WHITE, BISHOP) + pos.piece_count(WHITE, KNIGHT) <= 2
188           && pos.piece_count(BLACK, BISHOP) + pos.piece_count(BLACK, KNIGHT) <= 2)
189       {
190           mi->evaluationFunction = &EvaluateKmmKm;
191           return mi;
192       }
193   }
194
195   // OK, we didn't find any special evaluation function for the current
196   // material configuration. Is there a suitable scaling function?
197   //
198   // The code below is rather messy, and it could easily get worse later,
199   // if we decide to add more special cases. We face problems when there
200   // are several conflicting applicable scaling functions and we need to
201   // decide which one to use.
202   SF* sf;
203
204   if ((sf = funcs->get<SF>(key)) != NULL)
205   {
206       mi->scalingFunction[sf->color()] = sf;
207       return mi;
208   }
209
210   if (   pos.non_pawn_material(WHITE) == BishopValueMidgame
211       && pos.piece_count(WHITE, BISHOP) == 1
212       && pos.piece_count(WHITE, PAWN) >= 1)
213       mi->scalingFunction[WHITE] = &ScaleKBPK;
214
215   if (   pos.non_pawn_material(BLACK) == BishopValueMidgame
216       && pos.piece_count(BLACK, BISHOP) == 1
217       && pos.piece_count(BLACK, PAWN) >= 1)
218       mi->scalingFunction[BLACK] = &ScaleKKBP;
219
220   if (   pos.piece_count(WHITE, PAWN) == 0
221       && pos.non_pawn_material(WHITE) == QueenValueMidgame
222       && pos.piece_count(WHITE, QUEEN) == 1
223       && pos.piece_count(BLACK, ROOK) == 1
224       && pos.piece_count(BLACK, PAWN) >= 1)
225       mi->scalingFunction[WHITE] = &ScaleKQKRP;
226
227   else if (   pos.piece_count(BLACK, PAWN) == 0
228            && pos.non_pawn_material(BLACK) == QueenValueMidgame
229            && pos.piece_count(BLACK, QUEEN) == 1
230            && pos.piece_count(WHITE, ROOK) == 1
231            && pos.piece_count(WHITE, PAWN) >= 1)
232       mi->scalingFunction[BLACK] = &ScaleKRPKQ;
233
234   if (pos.non_pawn_material(WHITE) + pos.non_pawn_material(BLACK) == Value(0))
235   {
236       if (pos.piece_count(BLACK, PAWN) == 0)
237       {
238           assert(pos.piece_count(WHITE, PAWN) >= 2);
239           mi->scalingFunction[WHITE] = &ScaleKPsK;
240       }
241       else if (pos.piece_count(WHITE, PAWN) == 0)
242       {
243           assert(pos.piece_count(BLACK, PAWN) >= 2);
244           mi->scalingFunction[BLACK] = &ScaleKKPs;
245       }
246       else if (pos.piece_count(WHITE, PAWN) == 1 && pos.piece_count(BLACK, PAWN) == 1)
247       {
248           mi->scalingFunction[WHITE] = &ScaleKPKPw;
249           mi->scalingFunction[BLACK] = &ScaleKPKPb;
250       }
251   }
252
253   // Compute the space weight
254   if (pos.non_pawn_material(WHITE) + pos.non_pawn_material(BLACK) >=
255       2*QueenValueMidgame + 4*RookValueMidgame + 2*KnightValueMidgame)
256   {
257       int minorPieceCount =  pos.piece_count(WHITE, KNIGHT)
258                            + pos.piece_count(BLACK, KNIGHT)
259                            + pos.piece_count(WHITE, BISHOP)
260                            + pos.piece_count(BLACK, BISHOP);
261
262       mi->spaceWeight = minorPieceCount * minorPieceCount;
263   }
264
265   // Evaluate the material balance
266   const int pieceCount[2][6] = { { pos.piece_count(WHITE, BISHOP) > 1, pos.piece_count(WHITE, PAWN), pos.piece_count(WHITE, KNIGHT),
267                                    pos.piece_count(WHITE, BISHOP), pos.piece_count(WHITE, ROOK), pos.piece_count(WHITE, QUEEN) },
268                                  { pos.piece_count(BLACK, BISHOP) > 1, pos.piece_count(BLACK, PAWN), pos.piece_count(BLACK, KNIGHT),
269                                    pos.piece_count(BLACK, BISHOP), pos.piece_count(BLACK, ROOK), pos.piece_count(BLACK, QUEEN) } };
270   Color c, them;
271   int sign;
272   int matValue = 0;
273
274   for (c = WHITE, sign = 1; c <= BLACK; c++, sign = -sign)
275   {
276     // No pawns makes it difficult to win, even with a material advantage
277     if (   pos.piece_count(c, PAWN) == 0
278         && pos.non_pawn_material(c) - pos.non_pawn_material(opposite_color(c)) <= BishopValueMidgame)
279     {
280         if (   pos.non_pawn_material(c) == pos.non_pawn_material(opposite_color(c))
281             || pos.non_pawn_material(c) < RookValueMidgame)
282             mi->factor[c] = 0;
283         else
284         {
285             switch (pos.piece_count(c, BISHOP)) {
286             case 2:
287                 mi->factor[c] = 32;
288                 break;
289             case 1:
290                 mi->factor[c] = 12;
291                 break;
292             case 0:
293                 mi->factor[c] = 6;
294                 break;
295             }
296         }
297     }
298
299     // Redundancy of major pieces, formula based on Kaufman's paper
300     // "The Evaluation of Material Imbalances in Chess"
301     // http://mywebpages.comcast.net/danheisman/Articles/evaluation_of_material_imbalance.htm
302     if (pieceCount[c][ROOK] >= 1)
303         matValue -= sign * ((pieceCount[c][ROOK] - 1) * RedundantRookPenalty + pieceCount[c][QUEEN] * RedundantQueenPenalty);
304
305     // Second-degree polynomial material imbalance by Tord Romstad
306     //
307     // We use NO_PIECE_TYPE as a place holder for the bishop pair "extended piece",
308     // this allow us to be more flexible in defining bishop pair bonuses.
309     them = opposite_color(c);
310     for (int pt1 = NO_PIECE_TYPE; pt1 <= QUEEN; pt1++)
311     {
312         int c1 = sign * pieceCount[c][pt1];
313         if (!c1)
314             continue;
315
316         matValue += c1 * LinearCoefficients[pt1];
317
318         for (int pt2 = NO_PIECE_TYPE; pt2 <= pt1; pt2++)
319         {
320             matValue += c1 * pieceCount[c][pt2] * QuadraticCoefficientsSameColor[pt1][pt2];
321             matValue += c1 * pieceCount[them][pt2] * QuadraticCoefficientsOppositeColor[pt1][pt2];
322         }
323     }
324   }
325
326   mi->value = int16_t(matValue / 16);
327   return mi;
328 }
329
330
331 /// EndgameFunctions member definitions. This class is used to store the maps
332 /// of end game and scaling functions that MaterialInfoTable will query for
333 /// each key. The maps are constant and are populated only at construction,
334 /// but are per-thread instead of globals to avoid expensive locks needed
335 /// because std::map is not guaranteed to be thread-safe even if accessed
336 /// only for a lookup.
337
338 EndgameFunctions::EndgameFunctions() {
339
340   add<EvaluationFunction<KNNK>  >("KNNK");
341   add<EvaluationFunction<KPK>   >("KPK");
342   add<EvaluationFunction<KBNK>  >("KBNK");
343   add<EvaluationFunction<KRKP>  >("KRKP");
344   add<EvaluationFunction<KRKB>  >("KRKB");
345   add<EvaluationFunction<KRKN>  >("KRKN");
346   add<EvaluationFunction<KQKR>  >("KQKR");
347   add<EvaluationFunction<KBBKN> >("KBBKN");
348
349   add<ScalingFunction<KNPK>    >("KNPK");
350   add<ScalingFunction<KRPKR>   >("KRPKR");
351   add<ScalingFunction<KBPKB>   >("KBPKB");
352   add<ScalingFunction<KBPPKB>  >("KBPPKB");
353   add<ScalingFunction<KBPKN>   >("KBPKN");
354   add<ScalingFunction<KRPPKRP> >("KRPPKRP");
355   add<ScalingFunction<KRPPKRP> >("KRPPKRP");
356 }
357
358 EndgameFunctions::~EndgameFunctions() {
359
360     for (map<Key, EF*>::iterator it = maps.first.begin(); it != maps.first.end(); ++it)
361         delete (*it).second;
362
363     for (map<Key, SF*>::iterator it = maps.second.begin(); it != maps.second.end(); ++it)
364         delete (*it).second;
365 }
366
367 Key EndgameFunctions::buildKey(const string& keyCode) {
368
369     assert(keyCode.length() > 0 && keyCode[0] == 'K');
370     assert(keyCode.length() < 8);
371
372     stringstream s;
373     bool upcase = false;
374
375     // Build up a fen substring with the given pieces, note
376     // that the fen string could be of an illegal position.
377     for (size_t i = 0; i < keyCode.length(); i++)
378     {
379         if (keyCode[i] == 'K')
380             upcase = !upcase;
381
382         s << char(upcase? toupper(keyCode[i]) : tolower(keyCode[i]));
383     }
384     s << 8 - keyCode.length() << "/8/8/8/8/8/8/8 w -";
385     return Position(s.str()).get_material_key();
386 }
387
388 const string EndgameFunctions::swapColors(const string& keyCode) {
389
390     // Build corresponding key for the opposite color: "KBPKN" -> "KNKBP"
391     size_t idx = keyCode.find("K", 1);
392     return keyCode.substr(idx) + keyCode.substr(0, idx);
393 }
394
395 template<class T>
396 void EndgameFunctions::add(const string& keyCode) {
397
398   typedef typename T::Base F;
399
400   get<F>().insert(pair<Key, F*>(buildKey(keyCode), new T(WHITE)));
401   get<F>().insert(pair<Key, F*>(buildKey(swapColors(keyCode)), new T(BLACK)));
402 }
403
404 template<class T>
405 T* EndgameFunctions::get(Key key) const {
406
407   typename map<Key, T*>::const_iterator it(get<T>().find(key));
408   return (it != get<T>().end() ? it->second : NULL);
409 }