]> git.sesse.net Git - stockfish/blob - src/movepick.cpp
Restore LSN filtering
[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 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
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
22 ////
23 //// Includes
24 ////
25
26 #include <cassert>
27
28 #include "history.h"
29 #include "movegen.h"
30 #include "movepick.h"
31 #include "search.h"
32 #include "value.h"
33
34
35 ////
36 //// Local definitions
37 ////
38
39 namespace {
40
41   /// Variables
42
43   MovePicker::MovegenPhase PhaseTable[32];
44   int MainSearchPhaseIndex;
45   int EvasionsPhaseIndex;
46   int QsearchWithChecksPhaseIndex;
47   int QsearchWithoutChecksPhaseIndex;
48
49 }
50
51
52
53 ////
54 //// Functions
55 ////
56
57
58 /// Constructor for the MovePicker class.  Apart from the position for which
59 /// it is asked to pick legal moves, MovePicker also wants some information
60 /// to help it to return the presumably good moves first, to decide which
61 /// moves to return (in the quiescence search, for instance, we only want to
62 /// search captures, promotions and some checks) and about how important good
63 /// move ordering is at the current node.
64
65 MovePicker::MovePicker(const Position& p, bool pvnode, Move ttm, Move mk,
66                        Move k1, Move k2, Depth d) : pos(p) {
67   pvNode = pvnode;
68   ttMove = ttm;
69   mateKiller = (mk == ttm)? MOVE_NONE : mk;
70   killer1 = k1;
71   killer2 = k2;
72   depth = d;
73   movesPicked = 0;
74   numOfMoves = 0;
75   numOfBadCaptures = 0;
76   dc = p.discovered_check_candidates(p.side_to_move());
77
78   if (p.is_check())
79     phaseIndex = EvasionsPhaseIndex;
80   else if (depth > Depth(0))
81     phaseIndex = MainSearchPhaseIndex;
82   else if (depth == Depth(0))
83     phaseIndex = QsearchWithChecksPhaseIndex;
84   else
85     phaseIndex = QsearchWithoutChecksPhaseIndex;
86
87   pinned = p.pinned_pieces(p.side_to_move());
88
89   finished = false;
90 }
91
92
93 /// MovePicker::get_next_move() is the most important method of the MovePicker
94 /// class.  It returns a new legal move every time it is called, until there
95 /// are no more moves left of the types we are interested in.
96
97 Move MovePicker::get_next_move() {
98
99   Move move;
100
101   while (true)
102   {
103     // If we already have a list of generated moves, pick the best move from
104     // the list, and return it.
105     move = pick_move_from_list();
106     if (move != MOVE_NONE)
107     {
108         assert(move_is_ok(move));
109         return move;
110     }
111
112     // Next phase
113     phaseIndex++;
114     switch (PhaseTable[phaseIndex]) {
115
116     case PH_TT_MOVE:
117         if (ttMove != MOVE_NONE)
118         {
119             assert(move_is_ok(ttMove));
120             if (move_is_legal(pos, ttMove, pinned))
121                 return ttMove;
122         }
123         break;
124
125     case PH_MATE_KILLER:
126         if (mateKiller != MOVE_NONE)
127         {
128             assert(move_is_ok(mateKiller));
129             if (move_is_legal(pos, mateKiller, pinned))
130                 return mateKiller;
131        }
132        break;
133
134     case PH_GOOD_CAPTURES:
135         numOfMoves = generate_captures(pos, moves);
136         score_captures();
137         movesPicked = 0;
138         break;
139
140     case PH_BAD_CAPTURES:
141         badCapturesPicked = 0;
142         break;
143
144     case PH_NONCAPTURES:
145         numOfMoves = generate_noncaptures(pos, moves);
146         score_noncaptures();
147         movesPicked = 0;
148         break;
149
150     case PH_EVASIONS:
151         assert(pos.is_check());
152         numOfMoves = generate_evasions(pos, moves);
153         score_evasions();
154         movesPicked = 0;
155         break;
156
157     case PH_QCAPTURES:
158         numOfMoves = generate_captures(pos, moves);
159         score_qcaptures();
160         movesPicked = 0;
161         break;
162
163     case PH_QCHECKS:
164         numOfMoves = generate_checks(pos, moves, dc);
165         movesPicked = 0;
166         break;
167
168     case PH_STOP:
169         return MOVE_NONE;
170
171     default:
172         assert(false);
173         return MOVE_NONE;
174     }
175   }
176 }
177
178
179 /// A variant of get_next_move() which takes a lock as a parameter, used to
180 /// prevent multiple threads from picking the same move at a split point.
181
182 Move MovePicker::get_next_move(Lock &lock) {
183
184    lock_grab(&lock);
185    if (finished)
186    {
187        lock_release(&lock);
188        return MOVE_NONE;
189    }
190    Move m = get_next_move();
191    if (m == MOVE_NONE)
192        finished = true;
193
194    lock_release(&lock);
195    return m;
196 }
197
198
199 /// MovePicker::score_captures(), MovePicker::score_noncaptures(),
200 /// MovePicker::score_evasions() and MovePicker::score_qcaptures() assign a
201 /// numerical move ordering score to each move in a move list.  The moves
202 /// with highest scores will be picked first by pick_move_from_list().
203
204 void MovePicker::score_captures() {
205   // Winning and equal captures in the main search are ordered by MVV/LVA.
206   // Suprisingly, this appears to perform slightly better than SEE based
207   // move ordering.  The reason is probably that in a position with a winning
208   // capture, capturing a more valuable (but sufficiently defended) piece
209   // first usually doesn't hurt.  The opponent will have to recapture, and
210   // the hanging piece will still be hanging (except in the unusual cases
211   // where it is possible to recapture with the hanging piece). Exchanging
212   // big pieces before capturing a hanging piece probably helps to reduce
213   // the subtree size.
214   Move m;
215   int seeValue;
216
217   for (int i = 0; i < numOfMoves; i++)
218   {
219       m = moves[i].move;
220       seeValue = pos.see(m);
221       if (seeValue >= 0)
222       {
223           if (move_promotion(m))
224               moves[i].score = QueenValueMidgame;
225           else
226               moves[i].score = int(pos.midgame_value_of_piece_on(move_to(m)))
227                               -int(pos.type_of_piece_on(move_from(m)));
228       } else
229           moves[i].score = seeValue;
230   }
231 }
232
233 void MovePicker::score_noncaptures() {
234   // First score by history, when no history is available then use
235   // piece/square tables values. This seems to be better then a
236   // random choice when we don't have an history for any move.
237   Move m;
238   int hs;
239
240   for (int i = 0; i < numOfMoves; i++)
241   {
242       m = moves[i].move;
243
244       if (m == killer1)
245           hs = HistoryMax + 2;
246       else if (m == killer2)
247           hs = HistoryMax + 1;
248       else
249           hs = H.move_ordering_score(pos.piece_on(move_from(m)), m);
250
251       // Ensure moves in history are always sorted as first
252       if (hs > 0)
253           hs += 1000;
254
255       moves[i].score = hs + pos.mg_pst_delta(m);
256   }
257 }
258
259 void MovePicker::score_evasions() {
260
261   for (int i = 0; i < numOfMoves; i++)
262   {
263       Move m = moves[i].move;
264       if (m == ttMove)
265           moves[i].score = 2*HistoryMax;
266       else if (!pos.square_is_empty(move_to(m)))
267       {
268           int seeScore = pos.see(m);
269           moves[i].score = (seeScore >= 0)? seeScore + HistoryMax : seeScore;
270       } else
271           moves[i].score = H.move_ordering_score(pos.piece_on(move_from(m)), m);
272   }
273   // FIXME try psqt also here
274 }
275
276 void MovePicker::score_qcaptures() {
277
278   // Use MVV/LVA ordering
279   for (int i = 0; i < numOfMoves; i++)
280   {
281       Move m = moves[i].move;
282       if (move_promotion(m))
283           moves[i].score = QueenValueMidgame;
284       else
285           moves[i].score = int(pos.midgame_value_of_piece_on(move_to(m)))
286                           -int(pos.type_of_piece_on(move_from(m)));
287   }
288 }
289
290
291 /// find_best_index() loops across the moves and returns index of
292 /// the highest scored one.
293
294 int MovePicker::find_best_index() {
295
296   int bestScore = -10000000, bestIndex = -1;
297
298   for (int i = movesPicked; i < numOfMoves; i++)
299       if (moves[i].score > bestScore)
300       {
301           bestIndex = i;
302           bestScore = moves[i].score;
303       }
304   return bestIndex;
305 }
306
307
308 /// MovePicker::pick_move_from_list() picks the move with the biggest score
309 /// from a list of generated moves (moves[] or badCaptures[], depending on
310 /// the current move generation phase).  It takes care not to return the
311 /// transposition table move if that has already been serched previously.
312 /// While picking captures in the PH_GOOD_CAPTURES phase (i.e. while picking
313 /// non-losing captures in the main search), it moves all captures with
314 /// negative SEE values to the badCaptures[] array.
315
316 Move MovePicker::pick_move_from_list() {
317
318   int bestIndex;
319   Move move;
320
321   switch (PhaseTable[phaseIndex]) {
322   case PH_GOOD_CAPTURES:
323       assert(!pos.is_check());
324       assert(movesPicked >= 0);
325
326       while (movesPicked < numOfMoves)
327       {
328           int bestScore = -10000000;
329           bestIndex = -1;
330           for (int i = movesPicked; i < numOfMoves; i++)
331           {
332               if (moves[i].score < 0)
333               {
334                   // Losing capture, move it to the badCaptures[] array
335                   assert(numOfBadCaptures < 63);
336                   badCaptures[numOfBadCaptures++] = moves[i];
337                   moves[i--] = moves[--numOfMoves];
338               }
339               else if (moves[i].score > bestScore)
340               {
341                   bestIndex = i;
342                   bestScore = moves[i].score;
343               }
344           }
345           if (bestIndex != -1) // Found a good capture
346           {
347               move = moves[bestIndex].move;
348               moves[bestIndex] = moves[movesPicked++];
349               if (   move != ttMove
350                   && move != mateKiller
351                   && pos.pl_move_is_legal(move, pinned))
352                   return move;
353           }
354       }
355       break;
356
357   case PH_NONCAPTURES:
358       assert(!pos.is_check());
359       assert(movesPicked >= 0);
360
361       while (movesPicked < numOfMoves)
362       {
363           // If this is a PV node or we have only picked a few moves, scan
364           // the entire move list for the best move.  If many moves have already
365           // been searched and it is not a PV node, we are probably failing low
366           // anyway, so we just pick the first move from the list.
367           bestIndex = (pvNode || movesPicked < 12) ? find_best_index() : movesPicked;
368
369           if (bestIndex != -1)
370           {
371               move = moves[bestIndex].move;
372               moves[bestIndex] = moves[movesPicked++];
373               if (   move != ttMove
374                   && move != mateKiller
375                   && pos.pl_move_is_legal(move, pinned))
376                   return move;
377           }
378       }
379       break;
380
381   case PH_EVASIONS:
382       assert(pos.is_check());
383       assert(movesPicked >= 0);
384
385       while (movesPicked < numOfMoves)
386       {
387           bestIndex = find_best_index();
388
389           if (bestIndex != -1)
390           {
391               move = moves[bestIndex].move;
392               moves[bestIndex] = moves[movesPicked++];
393               return move;
394           }
395     }
396     break;
397
398   case PH_BAD_CAPTURES:
399       assert(!pos.is_check());
400       assert(badCapturesPicked >= 0);
401       // It's probably a good idea to use SEE move ordering here, instead
402       // of just picking the first move.  FIXME
403       while (badCapturesPicked < numOfBadCaptures)
404       {
405           move = badCaptures[badCapturesPicked++].move;
406           if (   move != ttMove
407               && move != mateKiller
408               && pos.pl_move_is_legal(move, pinned))
409               return move;
410       }
411       break;
412
413   case PH_QCAPTURES:
414       assert(!pos.is_check());
415       assert(movesPicked >= 0);
416       while (movesPicked < numOfMoves)
417       {
418           bestIndex = (movesPicked < 4 ? find_best_index() : movesPicked);
419
420           if (bestIndex != -1)
421           {
422               move = moves[bestIndex].move;
423               moves[bestIndex] = moves[movesPicked++];
424               // Remember to change the line below if we decide to hash the qsearch!
425               // Maybe also postpone the legality check until after futility pruning?
426               if (/* move != ttMove && */ pos.pl_move_is_legal(move, pinned))
427                   return move;
428           }
429       }
430       break;
431
432   case PH_QCHECKS:
433       assert(!pos.is_check());
434       assert(movesPicked >= 0);
435       // Perhaps we should do something better than just picking the first
436       // move here?  FIXME
437       while (movesPicked < numOfMoves)
438       {
439           move = moves[movesPicked++].move;
440           // Remember to change the line below if we decide to hash the qsearch!
441           if (/* move != ttMove && */ pos.pl_move_is_legal(move, pinned))
442               return move;
443       }
444       break;
445
446   default:
447       break;
448   }
449   return MOVE_NONE;
450 }
451
452
453 /// MovePicker::current_move_type() returns the type of the just
454 /// picked next move. It can be used in search to further differentiate
455 /// according to the current move type: capture, non capture, escape, etc.
456 MovePicker::MovegenPhase MovePicker::current_move_type() const {
457
458   return PhaseTable[phaseIndex];
459 }
460
461
462 /// MovePicker::init_phase_table() initializes the PhaseTable[],
463 /// MainSearchPhaseIndex, EvasionPhaseIndex, QsearchWithChecksPhaseIndex
464 /// and QsearchWithoutChecksPhaseIndex variables. It is only called once
465 /// during program startup, and never again while the program is running.
466
467 void MovePicker::init_phase_table() {
468
469   int i = 0;
470
471   // Main search
472   MainSearchPhaseIndex = i - 1;
473   PhaseTable[i++] = PH_TT_MOVE;
474   PhaseTable[i++] = PH_MATE_KILLER;
475   PhaseTable[i++] = PH_GOOD_CAPTURES;
476   // PH_KILLER_1 and PH_KILLER_2 are not yet used.
477   // PhaseTable[i++] = PH_KILLER_1;
478   // PhaseTable[i++] = PH_KILLER_2;
479   PhaseTable[i++] = PH_NONCAPTURES;
480   PhaseTable[i++] = PH_BAD_CAPTURES;
481   PhaseTable[i++] = PH_STOP;
482
483   // Check evasions
484   EvasionsPhaseIndex = i - 1;
485   PhaseTable[i++] = PH_EVASIONS;
486   PhaseTable[i++] = PH_STOP;
487
488   // Quiescence search with checks
489   QsearchWithChecksPhaseIndex = i - 1;
490   PhaseTable[i++] = PH_QCAPTURES;
491   PhaseTable[i++] = PH_QCHECKS;
492   PhaseTable[i++] = PH_STOP;
493
494   // Quiescence search without checks
495   QsearchWithoutChecksPhaseIndex = i - 1;
496   PhaseTable[i++] = PH_QCAPTURES;
497   PhaseTable[i++] = PH_STOP;
498 }