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