]> git.sesse.net Git - stockfish/blob - src/movepick.cpp
Simple always overwrite Refutation table
[stockfish] / src / movepick.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-2013 Marco Costalba, Joona Kiiski, Tord Romstad
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
12   Stockfish is distributed in the hope that it will be useful,
13   but WITHOUT ANY WARRANTY; without even the implied warranty of
14   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15   GNU General Public License for more details.
16
17   You should have received a copy of the GNU General Public License
18   along with this program.  If not, see <http://www.gnu.org/licenses/>.
19 */
20
21 #include <cassert>
22
23 #include "movepick.h"
24 #include "thread.h"
25
26 namespace {
27
28   enum Sequencer {
29     MAIN_SEARCH, CAPTURES_S1, KILLERS_S1, QUIETS_1_S1, QUIETS_2_S1, BAD_CAPTURES_S1,
30     EVASION,     EVASIONS_S2,
31     QSEARCH_0,   CAPTURES_S3, QUIET_CHECKS_S3,
32     QSEARCH_1,   CAPTURES_S4,
33     PROBCUT,     CAPTURES_S5,
34     RECAPTURE,   CAPTURES_S6,
35     STOP
36   };
37
38   // Our insertion sort, guaranteed to be stable, as is needed
39   void insertion_sort(MoveStack* begin, MoveStack* end)
40   {
41     MoveStack tmp, *p, *q;
42
43     for (p = begin + 1; p < end; ++p)
44     {
45         tmp = *p;
46         for (q = p; q != begin && *(q-1) < tmp; --q)
47             *q = *(q-1);
48         *q = tmp;
49     }
50   }
51
52   // Unary predicate used by std::partition to split positive scores from remaining
53   // ones so to sort separately the two sets, and with the second sort delayed.
54   inline bool has_positive_score(const MoveStack& ms) { return ms.score > 0; }
55
56   // Picks and moves to the front the best move in the range [begin, end),
57   // it is faster than sorting all the moves in advance when moves are few, as
58   // normally are the possible captures.
59   inline MoveStack* pick_best(MoveStack* begin, MoveStack* end)
60   {
61       std::swap(*begin, *std::max_element(begin, end));
62       return begin;
63   }
64 }
65
66
67 /// Constructors of the MovePicker class. As arguments we pass information
68 /// to help it to return the presumably good moves first, to decide which
69 /// moves to return (in the quiescence search, for instance, we only want to
70 /// search captures, promotions and some checks) and about how important good
71 /// move ordering is at the current node.
72
73 MovePicker::MovePicker(const Position& p, Move ttm, Depth d, const History& h,
74                        Search::Stack* s, Move refutationMove, Value beta) : pos(p), Hist(h), depth(d) {
75
76   assert(d > DEPTH_ZERO);
77
78   captureThreshold = 0;
79   cur = end = moves;
80   endBadCaptures = moves + MAX_MOVES - 1;
81   ss = s;
82
83   if (p.checkers())
84       phase = EVASION;
85
86   else
87   {
88       phase = MAIN_SEARCH;
89
90       killers[0].move = ss->killers[0];
91       killers[1].move = ss->killers[1];
92       killers[2].move = refutationMove;
93
94       // Consider sligtly negative captures as good if at low depth and far from beta
95       if (ss && ss->staticEval < beta - PawnValueMg && d < 3 * ONE_PLY)
96           captureThreshold = -PawnValueMg;
97
98       // Consider negative captures as good if still enough to reach beta
99       else if (ss && ss->staticEval > beta)
100           captureThreshold = beta - ss->staticEval;
101   }
102
103   ttMove = (ttm && pos.is_pseudo_legal(ttm) ? ttm : MOVE_NONE);
104   end += (ttMove != MOVE_NONE);
105 }
106
107 MovePicker::MovePicker(const Position& p, Move ttm, Depth d, const History& h,
108                        Square sq) : pos(p), Hist(h), cur(moves), end(moves) {
109
110   assert(d <= DEPTH_ZERO);
111
112   if (p.checkers())
113       phase = EVASION;
114
115   else if (d > DEPTH_QS_NO_CHECKS)
116       phase = QSEARCH_0;
117
118   else if (d > DEPTH_QS_RECAPTURES)
119   {
120       phase = QSEARCH_1;
121
122       // Skip TT move if is not a capture or a promotion, this avoids qsearch
123       // tree explosion due to a possible perpetual check or similar rare cases
124       // when TT table is full.
125       if (ttm && !pos.is_capture_or_promotion(ttm))
126           ttm = MOVE_NONE;
127   }
128   else
129   {
130       phase = RECAPTURE;
131       recaptureSquare = sq;
132       ttm = MOVE_NONE;
133   }
134
135   ttMove = (ttm && pos.is_pseudo_legal(ttm) ? ttm : MOVE_NONE);
136   end += (ttMove != MOVE_NONE);
137 }
138
139 MovePicker::MovePicker(const Position& p, Move ttm, const History& h, PieceType pt)
140                        : pos(p), Hist(h), cur(moves), end(moves) {
141
142   assert(!pos.checkers());
143
144   phase = PROBCUT;
145
146   // In ProbCut we generate only captures better than parent's captured piece
147   captureThreshold = PieceValue[MG][pt];
148   ttMove = (ttm && pos.is_pseudo_legal(ttm) ? ttm : MOVE_NONE);
149
150   if (ttMove && (!pos.is_capture(ttMove) ||  pos.see(ttMove) <= captureThreshold))
151       ttMove = MOVE_NONE;
152
153   end += (ttMove != MOVE_NONE);
154 }
155
156
157 /// score() assign a numerical move ordering score to each move in a move list.
158 /// The moves with highest scores will be picked first.
159 template<>
160 void MovePicker::score<CAPTURES>() {
161   // Winning and equal captures in the main search are ordered by MVV/LVA.
162   // Suprisingly, this appears to perform slightly better than SEE based
163   // move ordering. The reason is probably that in a position with a winning
164   // capture, capturing a more valuable (but sufficiently defended) piece
165   // first usually doesn't hurt. The opponent will have to recapture, and
166   // the hanging piece will still be hanging (except in the unusual cases
167   // where it is possible to recapture with the hanging piece). Exchanging
168   // big pieces before capturing a hanging piece probably helps to reduce
169   // the subtree size.
170   // In main search we want to push captures with negative SEE values to
171   // badCaptures[] array, but instead of doing it now we delay till when
172   // the move has been picked up in pick_move_from_list(), this way we save
173   // some SEE calls in case we get a cutoff (idea from Pablo Vazquez).
174   Move m;
175
176   for (MoveStack* it = moves; it != end; ++it)
177   {
178       m = it->move;
179       it->score =  PieceValue[MG][pos.piece_on(to_sq(m))]
180                  - type_of(pos.piece_moved(m));
181
182       if (type_of(m) == PROMOTION)
183           it->score += PieceValue[MG][promotion_type(m)] - PieceValue[MG][PAWN];
184
185       else if (type_of(m) == ENPASSANT)
186           it->score += PieceValue[MG][PAWN];
187   }
188 }
189
190 template<>
191 void MovePicker::score<QUIETS>() {
192
193   Move m;
194
195   for (MoveStack* it = moves; it != end; ++it)
196   {
197       m = it->move;
198       it->score = Hist[pos.piece_moved(m)][to_sq(m)];
199   }
200 }
201
202 template<>
203 void MovePicker::score<EVASIONS>() {
204   // Try good captures ordered by MVV/LVA, then non-captures if destination square
205   // is not under attack, ordered by history value, then bad-captures and quiet
206   // moves with a negative SEE. This last group is ordered by the SEE score.
207   Move m;
208   int seeScore;
209
210   for (MoveStack* it = moves; it != end; ++it)
211   {
212       m = it->move;
213       if ((seeScore = pos.see_sign(m)) < 0)
214           it->score = seeScore - History::Max; // At the bottom
215
216       else if (pos.is_capture(m))
217           it->score =  PieceValue[MG][pos.piece_on(to_sq(m))]
218                      - type_of(pos.piece_moved(m)) + History::Max;
219       else
220           it->score = Hist[pos.piece_moved(m)][to_sq(m)];
221   }
222 }
223
224
225 /// generate_next() generates, scores and sorts the next bunch of moves, when
226 /// there are no more moves to try for the current phase.
227
228 void MovePicker::generate_next() {
229
230   cur = moves;
231
232   switch (++phase) {
233
234   case CAPTURES_S1: case CAPTURES_S3: case CAPTURES_S4: case CAPTURES_S5: case CAPTURES_S6:
235       end = generate<CAPTURES>(pos, moves);
236       score<CAPTURES>();
237       return;
238
239   case KILLERS_S1:
240       cur = killers;
241       end = cur + 3;
242       return;
243
244   case QUIETS_1_S1:
245       endQuiets = end = generate<QUIETS>(pos, moves);
246       score<QUIETS>();
247       end = std::partition(cur, end, has_positive_score);
248       insertion_sort(cur, end);
249       return;
250
251   case QUIETS_2_S1:
252       cur = end;
253       end = endQuiets;
254       if (depth >= 3 * ONE_PLY)
255           insertion_sort(cur, end);
256       return;
257
258   case BAD_CAPTURES_S1:
259       // Just pick them in reverse order to get MVV/LVA ordering
260       cur = moves + MAX_MOVES - 1;
261       end = endBadCaptures;
262       return;
263
264   case EVASIONS_S2:
265       end = generate<EVASIONS>(pos, moves);
266       if (end > moves + 1)
267           score<EVASIONS>();
268       return;
269
270   case QUIET_CHECKS_S3:
271       end = generate<QUIET_CHECKS>(pos, moves);
272       return;
273
274   case EVASION: case QSEARCH_0: case QSEARCH_1: case PROBCUT: case RECAPTURE:
275       phase = STOP;
276   case STOP:
277       end = cur + 1; // Avoid another next_phase() call
278       return;
279
280   default:
281       assert(false);
282   }
283 }
284
285
286 /// next_move() is the most important method of the MovePicker class. It returns
287 /// a new pseudo legal move every time is called, until there are no more moves
288 /// left. It picks the move with the biggest score from a list of generated moves
289 /// taking care not returning the ttMove if has already been searched previously.
290 template<>
291 Move MovePicker::next_move<false>() {
292
293   Move move;
294
295   while (true)
296   {
297       while (cur == end)
298           generate_next();
299
300       switch (phase) {
301
302       case MAIN_SEARCH: case EVASION: case QSEARCH_0: case QSEARCH_1: case PROBCUT:
303           cur++;
304           return ttMove;
305
306       case CAPTURES_S1:
307           move = pick_best(cur++, end)->move;
308           if (move != ttMove)
309           {
310               assert(captureThreshold <= 0); // Otherwise we cannot use see_sign()
311
312               if (pos.see_sign(move) >= captureThreshold)
313                   return move;
314
315               // Losing capture, move it to the tail of the array
316               (endBadCaptures--)->move = move;
317           }
318           break;
319
320       case KILLERS_S1:
321           move = (cur++)->move;
322           if (    move != MOVE_NONE
323               &&  pos.is_pseudo_legal(move)
324               &&  move != ttMove
325               && !pos.is_capture(move))
326               return move;
327           break;
328
329       case QUIETS_1_S1: case QUIETS_2_S1:
330           move = (cur++)->move;
331           if (   move != ttMove
332               && move != killers[0].move
333               && move != killers[1].move
334               && move != killers[2].move)
335               return move;
336           break;
337
338       case BAD_CAPTURES_S1:
339           return (cur--)->move;
340
341       case EVASIONS_S2: case CAPTURES_S3: case CAPTURES_S4:
342           move = pick_best(cur++, end)->move;
343           if (move != ttMove)
344               return move;
345           break;
346
347       case CAPTURES_S5:
348            move = pick_best(cur++, end)->move;
349            if (move != ttMove && pos.see(move) > captureThreshold)
350                return move;
351            break;
352
353       case CAPTURES_S6:
354           move = pick_best(cur++, end)->move;
355           if (to_sq(move) == recaptureSquare)
356               return move;
357           break;
358
359       case QUIET_CHECKS_S3:
360           move = (cur++)->move;
361           if (move != ttMove)
362               return move;
363           break;
364
365       case STOP:
366           return MOVE_NONE;
367
368       default:
369           assert(false);
370       }
371   }
372 }
373
374
375 /// Version of next_move() to use at split point nodes where the move is grabbed
376 /// from the split point's shared MovePicker object. This function is not thread
377 /// safe so must be lock protected by the caller.
378 template<>
379 Move MovePicker::next_move<true>() { return ss->splitPoint->movePicker->next_move<false>(); }