]> git.sesse.net Git - stockfish/blob - src/search.cpp
Convert init of eval to async option
[stockfish] / src / search.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   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 #include <algorithm>
21 #include <cassert>
22 #include <cmath>
23 #include <cstring>
24 #include <iomanip>
25 #include <iostream>
26 #include <sstream>
27
28 #include "book.h"
29 #include "evaluate.h"
30 #include "history.h"
31 #include "misc.h"
32 #include "movegen.h"
33 #include "movepick.h"
34 #include "search.h"
35 #include "timeman.h"
36 #include "thread.h"
37 #include "tt.h"
38 #include "ucioption.h"
39
40 namespace Search {
41
42   volatile SignalsType Signals;
43   LimitsType Limits;
44   std::vector<RootMove> RootMoves;
45   Position RootPosition;
46 }
47
48 using std::string;
49 using std::cout;
50 using std::endl;
51 using namespace Search;
52
53 namespace {
54
55   // Set to true to force running with one thread. Used for debugging
56   const bool FakeSplit = false;
57
58   // Different node types, used as template parameter
59   enum NodeType { Root, PV, NonPV, SplitPointRoot, SplitPointPV, SplitPointNonPV };
60
61   // Lookup table to check if a Piece is a slider and its access function
62   const bool Slidings[18] = { 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 1, 1, 1 };
63   inline bool piece_is_slider(Piece p) { return Slidings[p]; }
64
65   // Maximum depth for razoring
66   const Depth RazorDepth = 4 * ONE_PLY;
67
68   // Dynamic razoring margin based on depth
69   inline Value razor_margin(Depth d) { return Value(0x200 + 0x10 * int(d)); }
70
71   // Maximum depth for use of dynamic threat detection when null move fails low
72   const Depth ThreatDepth = 5 * ONE_PLY;
73
74   // Minimum depth for use of internal iterative deepening
75   const Depth IIDDepth[] = { 8 * ONE_PLY, 5 * ONE_PLY };
76
77   // At Non-PV nodes we do an internal iterative deepening search
78   // when the static evaluation is bigger then beta - IIDMargin.
79   const Value IIDMargin = Value(0x100);
80
81   // Minimum depth for use of singular extension
82   const Depth SingularExtensionDepth[] = { 8 * ONE_PLY, 6 * ONE_PLY };
83
84   // Futility margin for quiescence search
85   const Value FutilityMarginQS = Value(0x80);
86
87   // Futility lookup tables (initialized at startup) and their access functions
88   Value FutilityMargins[16][64]; // [depth][moveNumber]
89   int FutilityMoveCounts[32];    // [depth]
90
91   inline Value futility_margin(Depth d, int mn) {
92
93     return d < 7 * ONE_PLY ? FutilityMargins[std::max(int(d), 1)][std::min(mn, 63)]
94                            : 2 * VALUE_INFINITE;
95   }
96
97   inline int futility_move_count(Depth d) {
98
99     return d < 16 * ONE_PLY ? FutilityMoveCounts[d] : MAX_MOVES;
100   }
101
102   // Reduction lookup tables (initialized at startup) and their access function
103   int8_t Reductions[2][64][64]; // [pv][depth][moveNumber]
104
105   template <bool PvNode> inline Depth reduction(Depth d, int mn) {
106
107     return (Depth) Reductions[PvNode][std::min(int(d) / ONE_PLY, 63)][std::min(mn, 63)];
108   }
109
110   // Easy move margin. An easy move candidate must be at least this much better
111   // than the second best move.
112   const Value EasyMoveMargin = Value(0x150);
113
114   // This is the minimum interval in msec between two check_time() calls
115   const int TimerResolution = 5;
116
117
118   size_t MultiPV, UCIMultiPV, PVIdx;
119   TimeManager TimeMgr;
120   Time SearchTime;
121   int BestMoveChanges;
122   int SkillLevel;
123   bool SkillLevelEnabled, Chess960;
124   History H;
125
126
127   template <NodeType NT>
128   Value search(Position& pos, Stack* ss, Value alpha, Value beta, Depth depth);
129
130   template <NodeType NT>
131   Value qsearch(Position& pos, Stack* ss, Value alpha, Value beta, Depth depth);
132
133   void id_loop(Position& pos);
134   bool check_is_dangerous(Position &pos, Move move, Value futilityBase, Value beta);
135   bool connected_moves(const Position& pos, Move m1, Move m2);
136   Value value_to_tt(Value v, int ply);
137   Value value_from_tt(Value v, int ply);
138   bool can_return_tt(const TTEntry* tte, Depth depth, Value beta, int ply);
139   bool connected_threat(const Position& pos, Move m, Move threat);
140   Value refine_eval(const TTEntry* tte, Value defaultEval, int ply);
141   Move do_skill_level();
142   string score_to_uci(Value v, Value alpha = -VALUE_INFINITE, Value beta = VALUE_INFINITE);
143   void pv_info_to_log(Position& pos, int depth, Value score, int time, Move pv[]);
144   void pv_info_to_uci(const Position& pos, int depth, Value alpha, Value beta);
145
146   // MovePickerExt class template extends MovePicker and allows to choose at
147   // compile time the proper moves source according to the type of node. In the
148   // default case we simply create and use a standard MovePicker object.
149   template<bool SpNode> struct MovePickerExt : public MovePicker {
150
151     MovePickerExt(const Position& p, Move ttm, Depth d, const History& h, Stack* ss, Value b)
152                   : MovePicker(p, ttm, d, h, ss, b) {}
153   };
154
155   // In case of a SpNode we use split point's shared MovePicker object as moves source
156   template<> struct MovePickerExt<true> : public MovePicker {
157
158     MovePickerExt(const Position& p, Move ttm, Depth d, const History& h, Stack* ss, Value b)
159                   : MovePicker(p, ttm, d, h, ss, b), mp(ss->sp->mp) {}
160
161     Move next_move() { return mp->next_move(); }
162     MovePicker* mp;
163   };
164
165   // is_dangerous() checks whether a move belongs to some classes of known
166   // 'dangerous' moves so that we avoid to prune it.
167   FORCE_INLINE bool is_dangerous(const Position& pos, Move m, bool captureOrPromotion) {
168
169     // Test for a pawn pushed to 7th or a passed pawn move
170     if (type_of(pos.piece_moved(m)) == PAWN)
171     {
172         Color c = pos.side_to_move();
173         if (   relative_rank(c, to_sq(m)) == RANK_7
174             || pos.pawn_is_passed(c, to_sq(m)))
175             return true;
176     }
177
178     // Test for a capture that triggers a pawn endgame
179     if (   captureOrPromotion
180         && type_of(pos.piece_on(to_sq(m))) != PAWN
181         && (  pos.non_pawn_material(WHITE) + pos.non_pawn_material(BLACK)
182             - PieceValueMidgame[pos.piece_on(to_sq(m))] == VALUE_ZERO)
183         && !is_special(m))
184         return true;
185
186     return false;
187   }
188
189 } // namespace
190
191
192 /// Search::init() is called during startup to initialize various lookup tables
193
194 void Search::init() {
195
196   int d;  // depth (ONE_PLY == 2)
197   int hd; // half depth (ONE_PLY == 1)
198   int mc; // moveCount
199
200   // Init reductions array
201   for (hd = 1; hd < 64; hd++) for (mc = 1; mc < 64; mc++)
202   {
203       double    pvRed = log(double(hd)) * log(double(mc)) / 3.0;
204       double nonPVRed = 0.33 + log(double(hd)) * log(double(mc)) / 2.25;
205       Reductions[1][hd][mc] = (int8_t) (   pvRed >= 1.0 ? floor(   pvRed * int(ONE_PLY)) : 0);
206       Reductions[0][hd][mc] = (int8_t) (nonPVRed >= 1.0 ? floor(nonPVRed * int(ONE_PLY)) : 0);
207   }
208
209   // Init futility margins array
210   for (d = 1; d < 16; d++) for (mc = 0; mc < 64; mc++)
211       FutilityMargins[d][mc] = Value(112 * int(log(double(d * d) / 2) / log(2.0) + 1.001) - 8 * mc + 45);
212
213   // Init futility move count array
214   for (d = 0; d < 32; d++)
215       FutilityMoveCounts[d] = int(3.001 + 0.25 * pow(d, 2.0));
216 }
217
218
219 /// Search::perft() is our utility to verify move generation. All the leaf nodes
220 /// up to the given depth are generated and counted and the sum returned.
221
222 int64_t Search::perft(Position& pos, Depth depth) {
223
224   StateInfo st;
225   int64_t cnt = 0;
226
227   MoveList<MV_LEGAL> ml(pos);
228
229   // At the last ply just return the number of moves (leaf nodes)
230   if (depth == ONE_PLY)
231       return ml.size();
232
233   CheckInfo ci(pos);
234   for ( ; !ml.end(); ++ml)
235   {
236       pos.do_move(ml.move(), st, ci, pos.move_gives_check(ml.move(), ci));
237       cnt += perft(pos, depth - ONE_PLY);
238       pos.undo_move(ml.move());
239   }
240   return cnt;
241 }
242
243
244 /// Search::think() is the external interface to Stockfish's search, and is
245 /// called by the main thread when the program receives the UCI 'go' command. It
246 /// searches from RootPosition and at the end prints the "bestmove" to output.
247
248 void Search::think() {
249
250   static Book book; // Defined static to initialize the PRNG only once
251
252   Position& pos = RootPosition;
253   Chess960 = pos.is_chess960();
254   EvalRootColor = pos.side_to_move();
255   SearchTime.restart();
256   TimeMgr.init(Limits, pos.startpos_ply_counter());
257   TT.new_search();
258   H.clear();
259
260   if (RootMoves.empty())
261   {
262       cout << "info depth 0 score "
263            << score_to_uci(pos.in_check() ? -VALUE_MATE : VALUE_DRAW) << endl;
264
265       RootMoves.push_back(MOVE_NONE);
266       goto finalize;
267   }
268
269   if (Options["OwnBook"])
270   {
271       Move bookMove = book.probe(pos, Options["Book File"], Options["Best Book Move"]);
272
273       if (bookMove && count(RootMoves.begin(), RootMoves.end(), bookMove))
274       {
275           std::swap(RootMoves[0], *find(RootMoves.begin(), RootMoves.end(), bookMove));
276           goto finalize;
277       }
278   }
279
280   UCIMultiPV = Options["MultiPV"];
281   SkillLevel = Options["Skill Level"];
282
283   // Do we have to play with skill handicap? In this case enable MultiPV that
284   // we will use behind the scenes to retrieve a set of possible moves.
285   SkillLevelEnabled = (SkillLevel < 20);
286   MultiPV = (SkillLevelEnabled ? std::max(UCIMultiPV, (size_t)4) : UCIMultiPV);
287
288   if (Options["Use Search Log"])
289   {
290       Log log(Options["Search Log Filename"]);
291       log << "\nSearching: "  << pos.to_fen()
292           << "\ninfinite: "   << Limits.infinite
293           << " ponder: "      << Limits.ponder
294           << " time: "        << Limits.time
295           << " increment: "   << Limits.increment
296           << " moves to go: " << Limits.movesToGo
297           << endl;
298   }
299
300   Threads.set_size(Options["Threads"]);
301
302   // Set best timer interval to avoid lagging under time pressure. Timer is
303   // used to check for remaining available thinking time.
304   if (Limits.use_time_management())
305       Threads.set_timer(std::min(100, std::max(TimeMgr.available_time() / 16, TimerResolution)));
306   else
307       Threads.set_timer(100);
308
309   // We're ready to start searching. Call the iterative deepening loop function
310   id_loop(pos);
311
312   // Stop timer and send all the slaves to sleep, if not already sleeping
313   Threads.set_timer(0);
314   Threads.set_size(1);
315
316   if (Options["Use Search Log"])
317   {
318       int e = SearchTime.elapsed();
319
320       Log log(Options["Search Log Filename"]);
321       log << "Nodes: "          << pos.nodes_searched()
322           << "\nNodes/second: " << (e > 0 ? pos.nodes_searched() * 1000 / e : 0)
323           << "\nBest move: "    << move_to_san(pos, RootMoves[0].pv[0]);
324
325       StateInfo st;
326       pos.do_move(RootMoves[0].pv[0], st);
327       log << "\nPonder move: " << move_to_san(pos, RootMoves[0].pv[1]) << endl;
328       pos.undo_move(RootMoves[0].pv[0]);
329   }
330
331 finalize:
332
333   // When we reach max depth we arrive here even without Signals.stop is raised,
334   // but if we are pondering or in infinite search, we shouldn't print the best
335   // move before we are told to do so.
336   if (!Signals.stop && (Limits.ponder || Limits.infinite))
337       Threads[pos.thread()].wait_for_stop_or_ponderhit();
338
339   // Best move could be MOVE_NONE when searching on a stalemate position
340   cout << "bestmove " << move_to_uci(RootMoves[0].pv[0], Chess960)
341        << " ponder "  << move_to_uci(RootMoves[0].pv[1], Chess960) << endl;
342 }
343
344
345 namespace {
346
347   // id_loop() is the main iterative deepening loop. It calls search() repeatedly
348   // with increasing depth until the allocated thinking time has been consumed,
349   // user stops the search, or the maximum search depth is reached.
350
351   void id_loop(Position& pos) {
352
353     Stack ss[MAX_PLY_PLUS_2];
354     int depth, prevBestMoveChanges;
355     Value bestValue, alpha, beta, delta;
356     bool bestMoveNeverChanged = true;
357     Move skillBest = MOVE_NONE;
358
359     memset(ss, 0, 4 * sizeof(Stack));
360     depth = BestMoveChanges = 0;
361     bestValue = delta = -VALUE_INFINITE;
362     ss->currentMove = MOVE_NULL; // Hack to skip update gains
363
364     // Iterative deepening loop until requested to stop or target depth reached
365     while (!Signals.stop && ++depth <= MAX_PLY && (!Limits.maxDepth || depth <= Limits.maxDepth))
366     {
367         // Save last iteration's scores before first PV line is searched and all
368         // the move scores but the (new) PV are set to -VALUE_INFINITE.
369         for (size_t i = 0; i < RootMoves.size(); i++)
370             RootMoves[i].prevScore = RootMoves[i].score;
371
372         prevBestMoveChanges = BestMoveChanges;
373         BestMoveChanges = 0;
374
375         // MultiPV loop. We perform a full root search for each PV line
376         for (PVIdx = 0; PVIdx < std::min(MultiPV, RootMoves.size()); PVIdx++)
377         {
378             // Set aspiration window default width
379             if (depth >= 5 && abs(RootMoves[PVIdx].prevScore) < VALUE_KNOWN_WIN)
380             {
381                 delta = Value(16);
382                 alpha = RootMoves[PVIdx].prevScore - delta;
383                 beta  = RootMoves[PVIdx].prevScore + delta;
384             }
385             else
386             {
387                 alpha = -VALUE_INFINITE;
388                 beta  =  VALUE_INFINITE;
389             }
390
391             // Start with a small aspiration window and, in case of fail high/low,
392             // research with bigger window until not failing high/low anymore.
393             do {
394                 // Search starts from ss+1 to allow referencing (ss-1). This is
395                 // needed by update gains and ss copy when splitting at Root.
396                 bestValue = search<Root>(pos, ss+1, alpha, beta, depth * ONE_PLY);
397
398                 // Bring to front the best move. It is critical that sorting is
399                 // done with a stable algorithm because all the values but the first
400                 // and eventually the new best one are set to -VALUE_INFINITE and
401                 // we want to keep the same order for all the moves but the new
402                 // PV that goes to the front. Note that in case of MultiPV search
403                 // the already searched PV lines are preserved.
404                 sort<RootMove>(RootMoves.begin() + PVIdx, RootMoves.end());
405
406                 // In case we have found an exact score and we are going to leave
407                 // the fail high/low loop then reorder the PV moves, otherwise
408                 // leave the last PV move in its position so to be searched again.
409                 // Of course this is needed only in MultiPV search.
410                 if (PVIdx && bestValue > alpha && bestValue < beta)
411                     sort<RootMove>(RootMoves.begin(), RootMoves.begin() + PVIdx);
412
413                 // Write PV back to transposition table in case the relevant
414                 // entries have been overwritten during the search.
415                 for (size_t i = 0; i <= PVIdx; i++)
416                     RootMoves[i].insert_pv_in_tt(pos);
417
418                 // If search has been stopped exit the aspiration window loop.
419                 // Sorting and writing PV back to TT is safe becuase RootMoves
420                 // is still valid, although refers to previous iteration.
421                 if (Signals.stop)
422                     break;
423
424                 // Send full PV info to GUI if we are going to leave the loop or
425                 // if we have a fail high/low and we are deep in the search.
426                 if ((bestValue > alpha && bestValue < beta) || SearchTime.elapsed() > 2000)
427                     pv_info_to_uci(pos, depth, alpha, beta);
428
429                 // In case of failing high/low increase aspiration window and
430                 // research, otherwise exit the fail high/low loop.
431                 if (bestValue >= beta)
432                 {
433                     beta += delta;
434                     delta += delta / 2;
435                 }
436                 else if (bestValue <= alpha)
437                 {
438                     Signals.failedLowAtRoot = true;
439                     Signals.stopOnPonderhit = false;
440
441                     alpha -= delta;
442                     delta += delta / 2;
443                 }
444                 else
445                     break;
446
447                 assert(alpha >= -VALUE_INFINITE && beta <= VALUE_INFINITE);
448
449             } while (abs(bestValue) < VALUE_KNOWN_WIN);
450         }
451
452         // Skills: Do we need to pick now the best move ?
453         if (SkillLevelEnabled && depth == 1 + SkillLevel)
454             skillBest = do_skill_level();
455
456         if (!Signals.stop && Options["Use Search Log"])
457              pv_info_to_log(pos, depth, bestValue, SearchTime.elapsed(), &RootMoves[0].pv[0]);
458
459         // Filter out startup noise when monitoring best move stability
460         if (depth > 2 && BestMoveChanges)
461             bestMoveNeverChanged = false;
462
463         // Do we have time for the next iteration? Can we stop searching now?
464         if (!Signals.stop && !Signals.stopOnPonderhit && Limits.use_time_management())
465         {
466             bool stop = false; // Local variable, not the volatile Signals.stop
467
468             // Take in account some extra time if the best move has changed
469             if (depth > 4 && depth < 50)
470                 TimeMgr.pv_instability(BestMoveChanges, prevBestMoveChanges);
471
472             // Stop search if most of available time is already consumed. We
473             // probably don't have enough time to search the first move at the
474             // next iteration anyway.
475             if (SearchTime.elapsed() > (TimeMgr.available_time() * 62) / 100)
476                 stop = true;
477
478             // Stop search early if one move seems to be much better than others
479             if (    depth >= 12
480                 && !stop
481                 && (   (bestMoveNeverChanged &&  pos.captured_piece_type())
482                     || SearchTime.elapsed() > (TimeMgr.available_time() * 40) / 100))
483             {
484                 Value rBeta = bestValue - EasyMoveMargin;
485                 (ss+1)->excludedMove = RootMoves[0].pv[0];
486                 (ss+1)->skipNullMove = true;
487                 Value v = search<NonPV>(pos, ss+1, rBeta - 1, rBeta, (depth - 3) * ONE_PLY);
488                 (ss+1)->skipNullMove = false;
489                 (ss+1)->excludedMove = MOVE_NONE;
490
491                 if (v < rBeta)
492                     stop = true;
493             }
494
495             if (stop)
496             {
497                 // If we are allowed to ponder do not stop the search now but
498                 // keep pondering until GUI sends "ponderhit" or "stop".
499                 if (Limits.ponder)
500                     Signals.stopOnPonderhit = true;
501                 else
502                     Signals.stop = true;
503             }
504         }
505     }
506
507     // When using skills swap best PV line with the sub-optimal one
508     if (SkillLevelEnabled)
509     {
510         if (skillBest == MOVE_NONE) // Still unassigned ?
511             skillBest = do_skill_level();
512
513         std::swap(RootMoves[0], *find(RootMoves.begin(), RootMoves.end(), skillBest));
514     }
515   }
516
517
518   // search<>() is the main search function for both PV and non-PV nodes and for
519   // normal and SplitPoint nodes. When called just after a split point the search
520   // is simpler because we have already probed the hash table, done a null move
521   // search, and searched the first move before splitting, we don't have to repeat
522   // all this work again. We also don't need to store anything to the hash table
523   // here: This is taken care of after we return from the split point.
524
525   template <NodeType NT>
526   Value search(Position& pos, Stack* ss, Value alpha, Value beta, Depth depth) {
527
528     const bool PvNode   = (NT == PV || NT == Root || NT == SplitPointPV || NT == SplitPointRoot);
529     const bool SpNode   = (NT == SplitPointPV || NT == SplitPointNonPV || NT == SplitPointRoot);
530     const bool RootNode = (NT == Root || NT == SplitPointRoot);
531
532     assert(alpha >= -VALUE_INFINITE && alpha < beta && beta <= VALUE_INFINITE);
533     assert((alpha == beta - 1) || PvNode);
534     assert(depth > DEPTH_ZERO);
535     assert(pos.thread() >= 0 && pos.thread() < Threads.size());
536
537     Move movesSearched[MAX_MOVES];
538     StateInfo st;
539     const TTEntry *tte;
540     Key posKey;
541     Move ttMove, move, excludedMove, bestMove, threatMove;
542     Depth ext, newDepth;
543     Bound bt;
544     Value bestValue, value, oldAlpha;
545     Value refinedValue, nullValue, futilityBase, futilityValue;
546     bool isPvMove, inCheck, singularExtensionNode, givesCheck;
547     bool captureOrPromotion, dangerous, doFullDepthSearch;
548     int moveCount = 0, playedMoveCount = 0;
549     Thread& thread = Threads[pos.thread()];
550     SplitPoint* sp = NULL;
551
552     refinedValue = bestValue = value = -VALUE_INFINITE;
553     oldAlpha = alpha;
554     inCheck = pos.in_check();
555     ss->ply = (ss-1)->ply + 1;
556
557     // Used to send selDepth info to GUI
558     if (PvNode && thread.maxPly < ss->ply)
559         thread.maxPly = ss->ply;
560
561     // Step 1. Initialize node
562     if (SpNode)
563     {
564         tte = NULL;
565         ttMove = excludedMove = MOVE_NONE;
566         sp = ss->sp;
567         bestMove = sp->bestMove;
568         threatMove = sp->threatMove;
569         bestValue = sp->bestValue;
570         moveCount = sp->moveCount; // Lock must be held here
571
572         assert(bestValue > -VALUE_INFINITE && moveCount > 0);
573
574         goto split_point_start;
575     }
576     else
577     {
578         ss->currentMove = threatMove = (ss+1)->excludedMove = bestMove = MOVE_NONE;
579         (ss+1)->skipNullMove = false; (ss+1)->reduction = DEPTH_ZERO;
580         (ss+2)->killers[0] = (ss+2)->killers[1] = MOVE_NONE;
581
582     }
583
584     // Step 2. Check for aborted search and immediate draw
585     // Enforce node limit here. FIXME: This only works with 1 search thread.
586     if (Limits.maxNodes && pos.nodes_searched() >= Limits.maxNodes)
587         Signals.stop = true;
588
589     if ((   Signals.stop
590          || pos.is_draw<false>()
591          || ss->ply > MAX_PLY) && !RootNode)
592         return VALUE_DRAW;
593
594     // Step 3. Mate distance pruning. Even if we mate at the next move our score
595     // would be at best mate_in(ss->ply+1), but if alpha is already bigger because
596     // a shorter mate was found upward in the tree then there is no need to search
597     // further, we will never beat current alpha. Same logic but with reversed signs
598     // applies also in the opposite condition of being mated instead of giving mate,
599     // in this case return a fail-high score.
600     if (!RootNode)
601     {
602         alpha = std::max(mated_in(ss->ply), alpha);
603         beta = std::min(mate_in(ss->ply+1), beta);
604         if (alpha >= beta)
605             return alpha;
606     }
607
608     // Step 4. Transposition table lookup
609     // We don't want the score of a partial search to overwrite a previous full search
610     // TT value, so we use a different position key in case of an excluded move.
611     excludedMove = ss->excludedMove;
612     posKey = excludedMove ? pos.exclusion_key() : pos.key();
613     tte = TT.probe(posKey);
614     ttMove = RootNode ? RootMoves[PVIdx].pv[0] : tte ? tte->move() : MOVE_NONE;
615
616     // At PV nodes we check for exact scores, while at non-PV nodes we check for
617     // a fail high/low. Biggest advantage at probing at PV nodes is to have a
618     // smooth experience in analysis mode. We don't probe at Root nodes otherwise
619     // we should also update RootMoveList to avoid bogus output.
620     if (!RootNode && tte && (PvNode ? tte->depth() >= depth && tte->type() == BOUND_EXACT
621                                     : can_return_tt(tte, depth, beta, ss->ply)))
622     {
623         TT.refresh(tte);
624         ss->currentMove = ttMove; // Can be MOVE_NONE
625         value = value_from_tt(tte->value(), ss->ply);
626
627         if (   value >= beta
628             && ttMove
629             && !pos.is_capture_or_promotion(ttMove)
630             && ttMove != ss->killers[0])
631         {
632             ss->killers[1] = ss->killers[0];
633             ss->killers[0] = ttMove;
634         }
635         return value;
636     }
637
638     // Step 5. Evaluate the position statically and update parent's gain statistics
639     if (inCheck)
640         ss->eval = ss->evalMargin = VALUE_NONE;
641     else if (tte)
642     {
643         assert(tte->static_value() != VALUE_NONE);
644
645         ss->eval = tte->static_value();
646         ss->evalMargin = tte->static_value_margin();
647         refinedValue = refine_eval(tte, ss->eval, ss->ply);
648     }
649     else
650     {
651         refinedValue = ss->eval = evaluate(pos, ss->evalMargin);
652         TT.store(posKey, VALUE_NONE, BOUND_NONE, DEPTH_NONE, MOVE_NONE, ss->eval, ss->evalMargin);
653     }
654
655     // Update gain for the parent non-capture move given the static position
656     // evaluation before and after the move.
657     if (   (move = (ss-1)->currentMove) != MOVE_NULL
658         && (ss-1)->eval != VALUE_NONE
659         && ss->eval != VALUE_NONE
660         && !pos.captured_piece_type()
661         && !is_special(move))
662     {
663         Square to = to_sq(move);
664         H.update_gain(pos.piece_on(to), to, -(ss-1)->eval - ss->eval);
665     }
666
667     // Step 6. Razoring (is omitted in PV nodes)
668     if (   !PvNode
669         &&  depth < RazorDepth
670         && !inCheck
671         &&  refinedValue + razor_margin(depth) < beta
672         &&  ttMove == MOVE_NONE
673         &&  abs(beta) < VALUE_MATE_IN_MAX_PLY
674         && !pos.has_pawn_on_7th(pos.side_to_move()))
675     {
676         Value rbeta = beta - razor_margin(depth);
677         Value v = qsearch<NonPV>(pos, ss, rbeta-1, rbeta, DEPTH_ZERO);
678         if (v < rbeta)
679             // Logically we should return (v + razor_margin(depth)), but
680             // surprisingly this did slightly weaker in tests.
681             return v;
682     }
683
684     // Step 7. Static null move pruning (is omitted in PV nodes)
685     // We're betting that the opponent doesn't have a move that will reduce
686     // the score by more than futility_margin(depth) if we do a null move.
687     if (   !PvNode
688         && !ss->skipNullMove
689         &&  depth < RazorDepth
690         && !inCheck
691         &&  refinedValue - futility_margin(depth, 0) >= beta
692         &&  abs(beta) < VALUE_MATE_IN_MAX_PLY
693         &&  pos.non_pawn_material(pos.side_to_move()))
694         return refinedValue - futility_margin(depth, 0);
695
696     // Step 8. Null move search with verification search (is omitted in PV nodes)
697     if (   !PvNode
698         && !ss->skipNullMove
699         &&  depth > ONE_PLY
700         && !inCheck
701         &&  refinedValue >= beta
702         &&  abs(beta) < VALUE_MATE_IN_MAX_PLY
703         &&  pos.non_pawn_material(pos.side_to_move()))
704     {
705         ss->currentMove = MOVE_NULL;
706
707         // Null move dynamic reduction based on depth
708         int R = 3 + (depth >= 5 * ONE_PLY ? depth / 8 : 0);
709
710         // Null move dynamic reduction based on value
711         if (refinedValue - PawnValueMidgame > beta)
712             R++;
713
714         pos.do_null_move<true>(st);
715         (ss+1)->skipNullMove = true;
716         nullValue = depth-R*ONE_PLY < ONE_PLY ? -qsearch<NonPV>(pos, ss+1, -beta, -alpha, DEPTH_ZERO)
717                                               : - search<NonPV>(pos, ss+1, -beta, -alpha, depth-R*ONE_PLY);
718         (ss+1)->skipNullMove = false;
719         pos.do_null_move<false>(st);
720
721         if (nullValue >= beta)
722         {
723             // Do not return unproven mate scores
724             if (nullValue >= VALUE_MATE_IN_MAX_PLY)
725                 nullValue = beta;
726
727             if (depth < 6 * ONE_PLY)
728                 return nullValue;
729
730             // Do verification search at high depths
731             ss->skipNullMove = true;
732             Value v = search<NonPV>(pos, ss, alpha, beta, depth-R*ONE_PLY);
733             ss->skipNullMove = false;
734
735             if (v >= beta)
736                 return nullValue;
737         }
738         else
739         {
740             // The null move failed low, which means that we may be faced with
741             // some kind of threat. If the previous move was reduced, check if
742             // the move that refuted the null move was somehow connected to the
743             // move which was reduced. If a connection is found, return a fail
744             // low score (which will cause the reduced move to fail high in the
745             // parent node, which will trigger a re-search with full depth).
746             threatMove = (ss+1)->currentMove;
747
748             if (   depth < ThreatDepth
749                 && (ss-1)->reduction
750                 && threatMove != MOVE_NONE
751                 && connected_moves(pos, (ss-1)->currentMove, threatMove))
752                 return beta - 1;
753         }
754     }
755
756     // Step 9. ProbCut (is omitted in PV nodes)
757     // If we have a very good capture (i.e. SEE > seeValues[captured_piece_type])
758     // and a reduced search returns a value much above beta, we can (almost) safely
759     // prune the previous move.
760     if (   !PvNode
761         &&  depth >= RazorDepth + ONE_PLY
762         && !inCheck
763         && !ss->skipNullMove
764         &&  excludedMove == MOVE_NONE
765         &&  abs(beta) < VALUE_MATE_IN_MAX_PLY)
766     {
767         Value rbeta = beta + 200;
768         Depth rdepth = depth - ONE_PLY - 3 * ONE_PLY;
769
770         assert(rdepth >= ONE_PLY);
771         assert((ss-1)->currentMove != MOVE_NONE);
772         assert((ss-1)->currentMove != MOVE_NULL);
773
774         MovePicker mp(pos, ttMove, H, pos.captured_piece_type());
775         CheckInfo ci(pos);
776
777         while ((move = mp.next_move()) != MOVE_NONE)
778             if (pos.pl_move_is_legal(move, ci.pinned))
779             {
780                 ss->currentMove = move;
781                 pos.do_move(move, st, ci, pos.move_gives_check(move, ci));
782                 value = -search<NonPV>(pos, ss+1, -rbeta, -rbeta+1, rdepth);
783                 pos.undo_move(move);
784                 if (value >= rbeta)
785                     return value;
786             }
787     }
788
789     // Step 10. Internal iterative deepening
790     if (   depth >= IIDDepth[PvNode]
791         && ttMove == MOVE_NONE
792         && (PvNode || (!inCheck && ss->eval + IIDMargin >= beta)))
793     {
794         Depth d = (PvNode ? depth - 2 * ONE_PLY : depth / 2);
795
796         ss->skipNullMove = true;
797         search<PvNode ? PV : NonPV>(pos, ss, alpha, beta, d);
798         ss->skipNullMove = false;
799
800         tte = TT.probe(posKey);
801         ttMove = tte ? tte->move() : MOVE_NONE;
802     }
803
804 split_point_start: // At split points actual search starts from here
805
806     MovePickerExt<SpNode> mp(pos, ttMove, depth, H, ss, PvNode ? -VALUE_INFINITE : beta);
807     CheckInfo ci(pos);
808     futilityBase = ss->eval + ss->evalMargin;
809     singularExtensionNode =   !RootNode
810                            && !SpNode
811                            && depth >= SingularExtensionDepth[PvNode]
812                            && ttMove != MOVE_NONE
813                            && !excludedMove // Recursive singular search is not allowed
814                            && (tte->type() & BOUND_LOWER)
815                            && tte->depth() >= depth - 3 * ONE_PLY;
816
817     // Step 11. Loop through moves
818     // Loop through all pseudo-legal moves until no moves remain or a beta cutoff occurs
819     while (   bestValue < beta
820            && (move = mp.next_move()) != MOVE_NONE
821            && !thread.cutoff_occurred()
822            && !Signals.stop)
823     {
824       assert(is_ok(move));
825
826       if (move == excludedMove)
827           continue;
828
829       // At root obey the "searchmoves" option and skip moves not listed in Root
830       // Move List, as a consequence any illegal move is also skipped. In MultiPV
831       // mode we also skip PV moves which have been already searched.
832       if (RootNode && !count(RootMoves.begin() + PVIdx, RootMoves.end(), move))
833           continue;
834
835       // At PV and SpNode nodes we want all moves to be legal since the beginning
836       if ((PvNode || SpNode) && !pos.pl_move_is_legal(move, ci.pinned))
837           continue;
838
839       if (SpNode)
840       {
841           moveCount = ++sp->moveCount;
842           lock_release(sp->lock);
843       }
844       else
845           moveCount++;
846
847       if (RootNode)
848       {
849           Signals.firstRootMove = (moveCount == 1);
850
851           if (pos.thread() == 0 && SearchTime.elapsed() > 2000)
852               cout << "info depth " << depth / ONE_PLY
853                    << " currmove " << move_to_uci(move, Chess960)
854                    << " currmovenumber " << moveCount + PVIdx << endl;
855       }
856
857       isPvMove = (PvNode && moveCount <= 1);
858       captureOrPromotion = pos.is_capture_or_promotion(move);
859       givesCheck = pos.move_gives_check(move, ci);
860       dangerous = givesCheck || is_dangerous(pos, move, captureOrPromotion);
861       ext = DEPTH_ZERO;
862
863       // Step 12. Extend checks and, in PV nodes, also dangerous moves
864       if (PvNode && dangerous)
865           ext = ONE_PLY;
866
867       else if (givesCheck && pos.see_sign(move) >= 0)
868           ext = PvNode ? ONE_PLY : ONE_PLY / 2;
869
870       // Singular extension search. If all moves but one fail low on a search of
871       // (alpha-s, beta-s), and just one fails high on (alpha, beta), then that move
872       // is singular and should be extended. To verify this we do a reduced search
873       // on all the other moves but the ttMove, if result is lower than ttValue minus
874       // a margin then we extend ttMove.
875       if (   singularExtensionNode
876           && !ext
877           && move == ttMove
878           && pos.pl_move_is_legal(move, ci.pinned))
879       {
880           Value ttValue = value_from_tt(tte->value(), ss->ply);
881
882           if (abs(ttValue) < VALUE_KNOWN_WIN)
883           {
884               Value rBeta = ttValue - int(depth);
885               ss->excludedMove = move;
886               ss->skipNullMove = true;
887               value = search<NonPV>(pos, ss, rBeta - 1, rBeta, depth / 2);
888               ss->skipNullMove = false;
889               ss->excludedMove = MOVE_NONE;
890               if (value < rBeta)
891                   ext = ONE_PLY;
892           }
893       }
894
895       // Update current move (this must be done after singular extension search)
896       newDepth = depth - ONE_PLY + ext;
897
898       // Step 13. Futility pruning (is omitted in PV nodes)
899       if (   !PvNode
900           && !captureOrPromotion
901           && !inCheck
902           && !dangerous
903           &&  move != ttMove
904           && !is_castle(move)
905           && (bestValue > VALUE_MATED_IN_MAX_PLY || bestValue == -VALUE_INFINITE))
906       {
907           // Move count based pruning
908           if (   moveCount >= futility_move_count(depth)
909               && (!threatMove || !connected_threat(pos, move, threatMove)))
910           {
911               if (SpNode)
912                   lock_grab(sp->lock);
913
914               continue;
915           }
916
917           // Value based pruning
918           // We illogically ignore reduction condition depth >= 3*ONE_PLY for predicted depth,
919           // but fixing this made program slightly weaker.
920           Depth predictedDepth = newDepth - reduction<PvNode>(depth, moveCount);
921           futilityValue =  futilityBase + futility_margin(predictedDepth, moveCount)
922                          + H.gain(pos.piece_moved(move), to_sq(move));
923
924           if (futilityValue < beta)
925           {
926               if (SpNode)
927                   lock_grab(sp->lock);
928
929               continue;
930           }
931
932           // Prune moves with negative SEE at low depths
933           if (   predictedDepth < 2 * ONE_PLY
934               && pos.see_sign(move) < 0)
935           {
936               if (SpNode)
937                   lock_grab(sp->lock);
938
939               continue;
940           }
941       }
942
943       // Check for legality only before to do the move
944       if (!pos.pl_move_is_legal(move, ci.pinned))
945       {
946           moveCount--;
947           continue;
948       }
949
950       ss->currentMove = move;
951       if (!SpNode && !captureOrPromotion)
952           movesSearched[playedMoveCount++] = move;
953
954       // Step 14. Make the move
955       pos.do_move(move, st, ci, givesCheck);
956
957       // Step 15. Reduced depth search (LMR). If the move fails high will be
958       // re-searched at full depth.
959       if (   depth > 3 * ONE_PLY
960           && !isPvMove
961           && !captureOrPromotion
962           && !dangerous
963           && !is_castle(move)
964           &&  ss->killers[0] != move
965           &&  ss->killers[1] != move)
966       {
967           ss->reduction = reduction<PvNode>(depth, moveCount);
968           Depth d = std::max(newDepth - ss->reduction, ONE_PLY);
969           alpha = SpNode ? sp->alpha : alpha;
970
971           value = -search<NonPV>(pos, ss+1, -(alpha+1), -alpha, d);
972
973           doFullDepthSearch = (value > alpha && ss->reduction != DEPTH_ZERO);
974           ss->reduction = DEPTH_ZERO;
975       }
976       else
977           doFullDepthSearch = !isPvMove;
978
979       // Step 16. Full depth search, when LMR is skipped or fails high
980       if (doFullDepthSearch)
981       {
982           alpha = SpNode ? sp->alpha : alpha;
983           value = newDepth < ONE_PLY ? -qsearch<NonPV>(pos, ss+1, -(alpha+1), -alpha, DEPTH_ZERO)
984                                      : - search<NonPV>(pos, ss+1, -(alpha+1), -alpha, newDepth);
985       }
986
987       // Only for PV nodes do a full PV search on the first move or after a fail
988       // high, in the latter case search only if value < beta, otherwise let the
989       // parent node to fail low with value <= alpha and to try another move.
990       if (PvNode && (isPvMove || (value > alpha && (RootNode || value < beta))))
991           value = newDepth < ONE_PLY ? -qsearch<PV>(pos, ss+1, -beta, -alpha, DEPTH_ZERO)
992                                      : - search<PV>(pos, ss+1, -beta, -alpha, newDepth);
993
994       // Step 17. Undo move
995       pos.undo_move(move);
996
997       assert(value > -VALUE_INFINITE && value < VALUE_INFINITE);
998
999       // Step 18. Check for new best move
1000       if (SpNode)
1001       {
1002           lock_grab(sp->lock);
1003           bestValue = sp->bestValue;
1004           alpha = sp->alpha;
1005       }
1006
1007       // Finished searching the move. If Signals.stop is true, the search
1008       // was aborted because the user interrupted the search or because we
1009       // ran out of time. In this case, the return value of the search cannot
1010       // be trusted, and we don't update the best move and/or PV.
1011       if (RootNode && !Signals.stop)
1012       {
1013           RootMove& rm = *find(RootMoves.begin(), RootMoves.end(), move);
1014
1015           // PV move or new best move ?
1016           if (isPvMove || value > alpha)
1017           {
1018               rm.score = value;
1019               rm.extract_pv_from_tt(pos);
1020
1021               // We record how often the best move has been changed in each
1022               // iteration. This information is used for time management: When
1023               // the best move changes frequently, we allocate some more time.
1024               if (!isPvMove && MultiPV == 1)
1025                   BestMoveChanges++;
1026           }
1027           else
1028               // All other moves but the PV are set to the lowest value, this
1029               // is not a problem when sorting becuase sort is stable and move
1030               // position in the list is preserved, just the PV is pushed up.
1031               rm.score = -VALUE_INFINITE;
1032
1033       }
1034
1035       if (value > bestValue)
1036       {
1037           bestValue = value;
1038           bestMove = move;
1039
1040           if (   PvNode
1041               && value > alpha
1042               && value < beta) // We want always alpha < beta
1043               alpha = value;
1044
1045           if (SpNode && !thread.cutoff_occurred())
1046           {
1047               sp->bestValue = value;
1048               sp->bestMove = move;
1049               sp->alpha = alpha;
1050
1051               if (value >= beta)
1052                   sp->cutoff = true;
1053           }
1054       }
1055
1056       // Step 19. Check for split
1057       if (   !SpNode
1058           && depth >= Threads.min_split_depth()
1059           && bestValue < beta
1060           && Threads.available_slave_exists(pos.thread())
1061           && !Signals.stop
1062           && !thread.cutoff_occurred())
1063           bestValue = Threads.split<FakeSplit>(pos, ss, alpha, beta, bestValue, &bestMove,
1064                                                depth, threatMove, moveCount, &mp, NT);
1065     }
1066
1067     // Step 20. Check for mate and stalemate
1068     // All legal moves have been searched and if there are no legal moves, it
1069     // must be mate or stalemate. Note that we can have a false positive in
1070     // case of Signals.stop or thread.cutoff_occurred() are set, but this is
1071     // harmless because return value is discarded anyhow in the parent nodes.
1072     // If we are in a singular extension search then return a fail low score.
1073     if (!moveCount)
1074         return excludedMove ? oldAlpha : inCheck ? mated_in(ss->ply) : VALUE_DRAW;
1075
1076     // If we have pruned all the moves without searching return a fail-low score
1077     if (bestValue == -VALUE_INFINITE)
1078     {
1079         assert(!playedMoveCount);
1080
1081         bestValue = oldAlpha;
1082     }
1083
1084     // Step 21. Update tables
1085     // Update transposition table entry, killers and history
1086     if (!SpNode && !Signals.stop && !thread.cutoff_occurred())
1087     {
1088         move = bestValue <= oldAlpha ? MOVE_NONE : bestMove;
1089         bt   = bestValue <= oldAlpha ? BOUND_UPPER
1090              : bestValue >= beta ? BOUND_LOWER : BOUND_EXACT;
1091
1092         TT.store(posKey, value_to_tt(bestValue, ss->ply), bt, depth, move, ss->eval, ss->evalMargin);
1093
1094         // Update killers and history for non capture cut-off moves
1095         if (    bestValue >= beta
1096             && !pos.is_capture_or_promotion(move)
1097             && !inCheck)
1098         {
1099             if (move != ss->killers[0])
1100             {
1101                 ss->killers[1] = ss->killers[0];
1102                 ss->killers[0] = move;
1103             }
1104
1105             // Increase history value of the cut-off move
1106             Value bonus = Value(int(depth) * int(depth));
1107             H.add(pos.piece_moved(move), to_sq(move), bonus);
1108
1109             // Decrease history of all the other played non-capture moves
1110             for (int i = 0; i < playedMoveCount - 1; i++)
1111             {
1112                 Move m = movesSearched[i];
1113                 H.add(pos.piece_moved(m), to_sq(m), -bonus);
1114             }
1115         }
1116     }
1117
1118     assert(bestValue > -VALUE_INFINITE && bestValue < VALUE_INFINITE);
1119
1120     return bestValue;
1121   }
1122
1123
1124   // qsearch() is the quiescence search function, which is called by the main
1125   // search function when the remaining depth is zero (or, to be more precise,
1126   // less than ONE_PLY).
1127
1128   template <NodeType NT>
1129   Value qsearch(Position& pos, Stack* ss, Value alpha, Value beta, Depth depth) {
1130
1131     const bool PvNode = (NT == PV);
1132
1133     assert(NT == PV || NT == NonPV);
1134     assert(alpha >= -VALUE_INFINITE && alpha < beta && beta <= VALUE_INFINITE);
1135     assert((alpha == beta - 1) || PvNode);
1136     assert(depth <= DEPTH_ZERO);
1137     assert(pos.thread() >= 0 && pos.thread() < Threads.size());
1138
1139     StateInfo st;
1140     Move ttMove, move, bestMove;
1141     Value bestValue, value, evalMargin, futilityValue, futilityBase;
1142     bool inCheck, enoughMaterial, givesCheck, evasionPrunable;
1143     const TTEntry* tte;
1144     Depth ttDepth;
1145     Bound bt;
1146     Value oldAlpha = alpha;
1147
1148     ss->currentMove = bestMove = MOVE_NONE;
1149     ss->ply = (ss-1)->ply + 1;
1150
1151     // Check for an instant draw or maximum ply reached
1152     if (pos.is_draw<true>() || ss->ply > MAX_PLY)
1153         return VALUE_DRAW;
1154
1155     // Decide whether or not to include checks, this fixes also the type of
1156     // TT entry depth that we are going to use. Note that in qsearch we use
1157     // only two types of depth in TT: DEPTH_QS_CHECKS or DEPTH_QS_NO_CHECKS.
1158     inCheck = pos.in_check();
1159     ttDepth = (inCheck || depth >= DEPTH_QS_CHECKS ? DEPTH_QS_CHECKS : DEPTH_QS_NO_CHECKS);
1160
1161     // Transposition table lookup. At PV nodes, we don't use the TT for
1162     // pruning, but only for move ordering.
1163     tte = TT.probe(pos.key());
1164     ttMove = (tte ? tte->move() : MOVE_NONE);
1165
1166     if (!PvNode && tte && can_return_tt(tte, ttDepth, beta, ss->ply))
1167     {
1168         ss->currentMove = ttMove; // Can be MOVE_NONE
1169         return value_from_tt(tte->value(), ss->ply);
1170     }
1171
1172     // Evaluate the position statically
1173     if (inCheck)
1174     {
1175         bestValue = futilityBase = -VALUE_INFINITE;
1176         ss->eval = evalMargin = VALUE_NONE;
1177         enoughMaterial = false;
1178     }
1179     else
1180     {
1181         if (tte)
1182         {
1183             assert(tte->static_value() != VALUE_NONE);
1184
1185             evalMargin = tte->static_value_margin();
1186             ss->eval = bestValue = tte->static_value();
1187         }
1188         else
1189             ss->eval = bestValue = evaluate(pos, evalMargin);
1190
1191         // Stand pat. Return immediately if static value is at least beta
1192         if (bestValue >= beta)
1193         {
1194             if (!tte)
1195                 TT.store(pos.key(), value_to_tt(bestValue, ss->ply), BOUND_LOWER, DEPTH_NONE, MOVE_NONE, ss->eval, evalMargin);
1196
1197             return bestValue;
1198         }
1199
1200         if (PvNode && bestValue > alpha)
1201             alpha = bestValue;
1202
1203         futilityBase = ss->eval + evalMargin + FutilityMarginQS;
1204         enoughMaterial = pos.non_pawn_material(pos.side_to_move()) > RookValueMidgame;
1205     }
1206
1207     // Initialize a MovePicker object for the current position, and prepare
1208     // to search the moves. Because the depth is <= 0 here, only captures,
1209     // queen promotions and checks (only if depth >= DEPTH_QS_CHECKS) will
1210     // be generated.
1211     MovePicker mp(pos, ttMove, depth, H, to_sq((ss-1)->currentMove));
1212     CheckInfo ci(pos);
1213
1214     // Loop through the moves until no moves remain or a beta cutoff occurs
1215     while (   bestValue < beta
1216            && (move = mp.next_move()) != MOVE_NONE)
1217     {
1218       assert(is_ok(move));
1219
1220       givesCheck = pos.move_gives_check(move, ci);
1221
1222       // Futility pruning
1223       if (   !PvNode
1224           && !inCheck
1225           && !givesCheck
1226           &&  move != ttMove
1227           &&  enoughMaterial
1228           && !is_promotion(move)
1229           && !pos.is_passed_pawn_push(move))
1230       {
1231           futilityValue =  futilityBase
1232                          + PieceValueEndgame[pos.piece_on(to_sq(move))]
1233                          + (is_enpassant(move) ? PawnValueEndgame : VALUE_ZERO);
1234
1235           if (futilityValue < beta)
1236           {
1237               if (futilityValue > bestValue)
1238                   bestValue = futilityValue;
1239
1240               continue;
1241           }
1242
1243           // Prune moves with negative or equal SEE
1244           if (   futilityBase < beta
1245               && depth < DEPTH_ZERO
1246               && pos.see(move) <= 0)
1247               continue;
1248       }
1249
1250       // Detect non-capture evasions that are candidate to be pruned
1251       evasionPrunable =   !PvNode
1252                        && inCheck
1253                        && bestValue > VALUE_MATED_IN_MAX_PLY
1254                        && !pos.is_capture(move)
1255                        && !pos.can_castle(pos.side_to_move());
1256
1257       // Don't search moves with negative SEE values
1258       if (   !PvNode
1259           && (!inCheck || evasionPrunable)
1260           &&  move != ttMove
1261           && !is_promotion(move)
1262           &&  pos.see_sign(move) < 0)
1263           continue;
1264
1265       // Don't search useless checks
1266       if (   !PvNode
1267           && !inCheck
1268           &&  givesCheck
1269           &&  move != ttMove
1270           && !pos.is_capture_or_promotion(move)
1271           &&  ss->eval + PawnValueMidgame / 4 < beta
1272           && !check_is_dangerous(pos, move, futilityBase, beta))
1273           continue;
1274
1275       // Check for legality only before to do the move
1276       if (!pos.pl_move_is_legal(move, ci.pinned))
1277           continue;
1278
1279       ss->currentMove = move;
1280
1281       // Make and search the move
1282       pos.do_move(move, st, ci, givesCheck);
1283       value = -qsearch<NT>(pos, ss+1, -beta, -alpha, depth-ONE_PLY);
1284       pos.undo_move(move);
1285
1286       assert(value > -VALUE_INFINITE && value < VALUE_INFINITE);
1287
1288       // New best move?
1289       if (value > bestValue)
1290       {
1291           bestValue = value;
1292           bestMove = move;
1293
1294           if (   PvNode
1295               && value > alpha
1296               && value < beta) // We want always alpha < beta
1297               alpha = value;
1298        }
1299     }
1300
1301     // All legal moves have been searched. A special case: If we're in check
1302     // and no legal moves were found, it is checkmate.
1303     if (inCheck && bestValue == -VALUE_INFINITE)
1304         return mated_in(ss->ply); // Plies to mate from the root
1305
1306     // Update transposition table
1307     move = bestValue <= oldAlpha ? MOVE_NONE : bestMove;
1308     bt   = bestValue <= oldAlpha ? BOUND_UPPER
1309          : bestValue >= beta ? BOUND_LOWER : BOUND_EXACT;
1310
1311     TT.store(pos.key(), value_to_tt(bestValue, ss->ply), bt, ttDepth, move, ss->eval, evalMargin);
1312
1313     assert(bestValue > -VALUE_INFINITE && bestValue < VALUE_INFINITE);
1314
1315     return bestValue;
1316   }
1317
1318
1319   // check_is_dangerous() tests if a checking move can be pruned in qsearch().
1320   // bestValue is updated only when returning false because in that case move
1321   // will be pruned.
1322
1323   bool check_is_dangerous(Position &pos, Move move, Value futilityBase, Value beta)
1324   {
1325     Bitboard b, occ, oldAtt, newAtt, kingAtt;
1326     Square from, to, ksq;
1327     Piece pc;
1328     Color them;
1329
1330     from = from_sq(move);
1331     to = to_sq(move);
1332     them = ~pos.side_to_move();
1333     ksq = pos.king_square(them);
1334     kingAtt = pos.attacks_from<KING>(ksq);
1335     pc = pos.piece_moved(move);
1336
1337     occ = pos.occupied_squares() & ~(1ULL << from) & ~(1ULL << ksq);
1338     oldAtt = pos.attacks_from(pc, from, occ);
1339     newAtt = pos.attacks_from(pc,   to, occ);
1340
1341     // Rule 1. Checks which give opponent's king at most one escape square are dangerous
1342     b = kingAtt & ~pos.pieces(them) & ~newAtt & ~(1ULL << to);
1343
1344     if (single_bit(b)) // Catches also !b
1345         return true;
1346
1347     // Rule 2. Queen contact check is very dangerous
1348     if (type_of(pc) == QUEEN && (kingAtt & to))
1349         return true;
1350
1351     // Rule 3. Creating new double threats with checks
1352     b = pos.pieces(them) & newAtt & ~oldAtt & ~(1ULL << ksq);
1353     while (b)
1354     {
1355         // Note that here we generate illegal "double move"!
1356         if (futilityBase + PieceValueEndgame[pos.piece_on(pop_1st_bit(&b))] >= beta)
1357             return true;
1358     }
1359
1360     return false;
1361   }
1362
1363
1364   // connected_moves() tests whether two moves are 'connected' in the sense
1365   // that the first move somehow made the second move possible (for instance
1366   // if the moving piece is the same in both moves). The first move is assumed
1367   // to be the move that was made to reach the current position, while the
1368   // second move is assumed to be a move from the current position.
1369
1370   bool connected_moves(const Position& pos, Move m1, Move m2) {
1371
1372     Square f1, t1, f2, t2;
1373     Piece p1, p2;
1374     Square ksq;
1375
1376     assert(is_ok(m1));
1377     assert(is_ok(m2));
1378
1379     // Case 1: The moving piece is the same in both moves
1380     f2 = from_sq(m2);
1381     t1 = to_sq(m1);
1382     if (f2 == t1)
1383         return true;
1384
1385     // Case 2: The destination square for m2 was vacated by m1
1386     t2 = to_sq(m2);
1387     f1 = from_sq(m1);
1388     if (t2 == f1)
1389         return true;
1390
1391     // Case 3: Moving through the vacated square
1392     p2 = pos.piece_on(f2);
1393     if (piece_is_slider(p2) && (squares_between(f2, t2) & f1))
1394       return true;
1395
1396     // Case 4: The destination square for m2 is defended by the moving piece in m1
1397     p1 = pos.piece_on(t1);
1398     if (pos.attacks_from(p1, t1) & t2)
1399         return true;
1400
1401     // Case 5: Discovered check, checking piece is the piece moved in m1
1402     ksq = pos.king_square(pos.side_to_move());
1403     if (    piece_is_slider(p1)
1404         && (squares_between(t1, ksq) & f2)
1405         && (pos.attacks_from(p1, t1, pos.occupied_squares() ^ f2) & ksq))
1406         return true;
1407
1408     return false;
1409   }
1410
1411
1412   // value_to_tt() adjusts a mate score from "plies to mate from the root" to
1413   // "plies to mate from the current position". Non-mate scores are unchanged.
1414   // The function is called before storing a value to the transposition table.
1415
1416   Value value_to_tt(Value v, int ply) {
1417
1418     if (v >= VALUE_MATE_IN_MAX_PLY)
1419       return v + ply;
1420
1421     if (v <= VALUE_MATED_IN_MAX_PLY)
1422       return v - ply;
1423
1424     return v;
1425   }
1426
1427
1428   // value_from_tt() is the inverse of value_to_tt(): It adjusts a mate score
1429   // from the transposition table (where refers to the plies to mate/be mated
1430   // from current position) to "plies to mate/be mated from the root".
1431
1432   Value value_from_tt(Value v, int ply) {
1433
1434     if (v >= VALUE_MATE_IN_MAX_PLY)
1435       return v - ply;
1436
1437     if (v <= VALUE_MATED_IN_MAX_PLY)
1438       return v + ply;
1439
1440     return v;
1441   }
1442
1443
1444   // connected_threat() tests whether it is safe to forward prune a move or if
1445   // is somehow connected to the threat move returned by null search.
1446
1447   bool connected_threat(const Position& pos, Move m, Move threat) {
1448
1449     assert(is_ok(m));
1450     assert(is_ok(threat));
1451     assert(!pos.is_capture_or_promotion(m));
1452     assert(!pos.is_passed_pawn_push(m));
1453
1454     Square mfrom, mto, tfrom, tto;
1455
1456     mfrom = from_sq(m);
1457     mto = to_sq(m);
1458     tfrom = from_sq(threat);
1459     tto = to_sq(threat);
1460
1461     // Case 1: Don't prune moves which move the threatened piece
1462     if (mfrom == tto)
1463         return true;
1464
1465     // Case 2: If the threatened piece has value less than or equal to the
1466     // value of the threatening piece, don't prune moves which defend it.
1467     if (   pos.is_capture(threat)
1468         && (   PieceValueMidgame[pos.piece_on(tfrom)] >= PieceValueMidgame[pos.piece_on(tto)]
1469             || type_of(pos.piece_on(tfrom)) == KING)
1470         && pos.move_attacks_square(m, tto))
1471         return true;
1472
1473     // Case 3: If the moving piece in the threatened move is a slider, don't
1474     // prune safe moves which block its ray.
1475     if (    piece_is_slider(pos.piece_on(tfrom))
1476         && (squares_between(tfrom, tto) & mto)
1477         &&  pos.see_sign(m) >= 0)
1478         return true;
1479
1480     return false;
1481   }
1482
1483
1484   // can_return_tt() returns true if a transposition table score can be used to
1485   // cut-off at a given point in search.
1486
1487   bool can_return_tt(const TTEntry* tte, Depth depth, Value beta, int ply) {
1488
1489     Value v = value_from_tt(tte->value(), ply);
1490
1491     return   (   tte->depth() >= depth
1492               || v >= std::max(VALUE_MATE_IN_MAX_PLY, beta)
1493               || v < std::min(VALUE_MATED_IN_MAX_PLY, beta))
1494
1495           && (   ((tte->type() & BOUND_LOWER) && v >= beta)
1496               || ((tte->type() & BOUND_UPPER) && v < beta));
1497   }
1498
1499
1500   // refine_eval() returns the transposition table score if possible, otherwise
1501   // falls back on static position evaluation.
1502
1503   Value refine_eval(const TTEntry* tte, Value defaultEval, int ply) {
1504
1505       assert(tte);
1506
1507       Value v = value_from_tt(tte->value(), ply);
1508
1509       if (   ((tte->type() & BOUND_LOWER) && v >= defaultEval)
1510           || ((tte->type() & BOUND_UPPER) && v < defaultEval))
1511           return v;
1512
1513       return defaultEval;
1514   }
1515
1516
1517   // score_to_uci() converts a value to a string suitable for use with the UCI
1518   // protocol specifications:
1519   //
1520   // cp <x>     The score from the engine's point of view in centipawns.
1521   // mate <y>   Mate in y moves, not plies. If the engine is getting mated
1522   //            use negative values for y.
1523
1524   string score_to_uci(Value v, Value alpha, Value beta) {
1525
1526     std::stringstream s;
1527
1528     if (abs(v) < VALUE_MATE_IN_MAX_PLY)
1529         s << "cp " << v * 100 / int(PawnValueMidgame);
1530     else
1531         s << "mate " << (v > 0 ? VALUE_MATE - v + 1 : -VALUE_MATE - v) / 2;
1532
1533     s << (v >= beta ? " lowerbound" : v <= alpha ? " upperbound" : "");
1534
1535     return s.str();
1536   }
1537
1538
1539   // pv_info_to_uci() sends search info to GUI. UCI protocol requires to send all
1540   // the PV lines also if are still to be searched and so refer to the previous
1541   // search score.
1542
1543   void pv_info_to_uci(const Position& pos, int depth, Value alpha, Value beta) {
1544
1545     int t = SearchTime.elapsed();
1546     int selDepth = 0;
1547
1548     for (int i = 0; i < Threads.size(); i++)
1549         if (Threads[i].maxPly > selDepth)
1550             selDepth = Threads[i].maxPly;
1551
1552     for (size_t i = 0; i < std::min(UCIMultiPV, RootMoves.size()); i++)
1553     {
1554         bool updated = (i <= PVIdx);
1555
1556         if (depth == 1 && !updated)
1557             continue;
1558
1559         int d = (updated ? depth : depth - 1);
1560         Value v = (updated ? RootMoves[i].score : RootMoves[i].prevScore);
1561         std::stringstream s;
1562
1563         for (int j = 0; RootMoves[i].pv[j] != MOVE_NONE; j++)
1564             s <<  " " << move_to_uci(RootMoves[i].pv[j], Chess960);
1565
1566         cout << "info depth " << d
1567              << " seldepth " << selDepth
1568              << " score " << (i == PVIdx ? score_to_uci(v, alpha, beta) : score_to_uci(v))
1569              << " nodes " << pos.nodes_searched()
1570              << " nps " << (t > 0 ? pos.nodes_searched() * 1000 / t : 0)
1571              << " time " << t
1572              << " multipv " << i + 1
1573              << " pv" << s.str() << endl;
1574     }
1575   }
1576
1577
1578   // pv_info_to_log() writes human-readable search information to the log file
1579   // (which is created when the UCI parameter "Use Search Log" is "true"). It
1580   // uses the two below helpers to pretty format time and score respectively.
1581
1582   string time_to_string(int millisecs) {
1583
1584     const int MSecMinute = 1000 * 60;
1585     const int MSecHour   = 1000 * 60 * 60;
1586
1587     int hours = millisecs / MSecHour;
1588     int minutes =  (millisecs % MSecHour) / MSecMinute;
1589     int seconds = ((millisecs % MSecHour) % MSecMinute) / 1000;
1590
1591     std::stringstream s;
1592
1593     if (hours)
1594         s << hours << ':';
1595
1596     s << std::setfill('0') << std::setw(2) << minutes << ':'
1597                            << std::setw(2) << seconds;
1598     return s.str();
1599   }
1600
1601   string score_to_string(Value v) {
1602
1603     std::stringstream s;
1604
1605     if (v >= VALUE_MATE_IN_MAX_PLY)
1606         s << "#" << (VALUE_MATE - v + 1) / 2;
1607     else if (v <= VALUE_MATED_IN_MAX_PLY)
1608         s << "-#" << (VALUE_MATE + v) / 2;
1609     else
1610         s << std::setprecision(2) << std::fixed << std::showpos
1611           << float(v) / PawnValueMidgame;
1612
1613     return s.str();
1614   }
1615
1616   void pv_info_to_log(Position& pos, int depth, Value value, int time, Move pv[]) {
1617
1618     const int64_t K = 1000;
1619     const int64_t M = 1000000;
1620
1621     StateInfo state[MAX_PLY_PLUS_2], *st = state;
1622     Move* m = pv;
1623     string san, padding;
1624     size_t length;
1625     std::stringstream s;
1626
1627     s << std::setw(2) << depth
1628       << std::setw(8) << score_to_string(value)
1629       << std::setw(8) << time_to_string(time);
1630
1631     if (pos.nodes_searched() < M)
1632         s << std::setw(8) << pos.nodes_searched() / 1 << "  ";
1633
1634     else if (pos.nodes_searched() < K * M)
1635         s << std::setw(7) << pos.nodes_searched() / K << "K  ";
1636
1637     else
1638         s << std::setw(7) << pos.nodes_searched() / M << "M  ";
1639
1640     padding = string(s.str().length(), ' ');
1641     length = padding.length();
1642
1643     while (*m != MOVE_NONE)
1644     {
1645         san = move_to_san(pos, *m);
1646
1647         if (length + san.length() > 80)
1648         {
1649             s << "\n" + padding;
1650             length = padding.length();
1651         }
1652
1653         s << san << ' ';
1654         length += san.length() + 1;
1655
1656         pos.do_move(*m++, *st++);
1657     }
1658
1659     while (m != pv)
1660         pos.undo_move(*--m);
1661
1662     Log l(Options["Search Log Filename"]);
1663     l << s.str() << endl;
1664   }
1665
1666
1667   // When playing with strength handicap choose best move among the MultiPV set
1668   // using a statistical rule dependent on SkillLevel. Idea by Heinz van Saanen.
1669
1670   Move do_skill_level() {
1671
1672     assert(MultiPV > 1);
1673
1674     static RKISS rk;
1675
1676     // PRNG sequence should be not deterministic
1677     for (int i = Time::current_time().msec() % 50; i > 0; i--)
1678         rk.rand<unsigned>();
1679
1680     // RootMoves are already sorted by score in descending order
1681     size_t size = std::min(MultiPV, RootMoves.size());
1682     int variance = std::min(RootMoves[0].score - RootMoves[size - 1].score, PawnValueMidgame);
1683     int weakness = 120 - 2 * SkillLevel;
1684     int max_s = -VALUE_INFINITE;
1685     Move best = MOVE_NONE;
1686
1687     // Choose best move. For each move score we add two terms both dependent on
1688     // weakness, one deterministic and bigger for weaker moves, and one random,
1689     // then we choose the move with the resulting highest score.
1690     for (size_t i = 0; i < size; i++)
1691     {
1692         int s = RootMoves[i].score;
1693
1694         // Don't allow crazy blunders even at very low skills
1695         if (i > 0 && RootMoves[i-1].score > s + EasyMoveMargin)
1696             break;
1697
1698         // This is our magic formula
1699         s += (  weakness * int(RootMoves[0].score - s)
1700               + variance * (rk.rand<unsigned>() % weakness)) / 128;
1701
1702         if (s > max_s)
1703         {
1704             max_s = s;
1705             best = RootMoves[i].pv[0];
1706         }
1707     }
1708     return best;
1709   }
1710
1711 } // namespace
1712
1713
1714 /// RootMove::extract_pv_from_tt() builds a PV by adding moves from the TT table.
1715 /// We consider also failing high nodes and not only BOUND_EXACT nodes so to
1716 /// allow to always have a ponder move even when we fail high at root, and a
1717 /// long PV to print that is important for position analysis.
1718
1719 void RootMove::extract_pv_from_tt(Position& pos) {
1720
1721   StateInfo state[MAX_PLY_PLUS_2], *st = state;
1722   TTEntry* tte;
1723   int ply = 1;
1724   Move m = pv[0];
1725
1726   assert(m != MOVE_NONE && pos.is_pseudo_legal(m));
1727
1728   pv.clear();
1729   pv.push_back(m);
1730   pos.do_move(m, *st++);
1731
1732   while (   (tte = TT.probe(pos.key())) != NULL
1733          && (m = tte->move()) != MOVE_NONE // Local copy, TT entry could change
1734          && pos.is_pseudo_legal(m)
1735          && pos.pl_move_is_legal(m, pos.pinned_pieces())
1736          && ply < MAX_PLY
1737          && (!pos.is_draw<false>() || ply < 2))
1738   {
1739       pv.push_back(m);
1740       pos.do_move(m, *st++);
1741       ply++;
1742   }
1743   pv.push_back(MOVE_NONE);
1744
1745   do pos.undo_move(pv[--ply]); while (ply);
1746 }
1747
1748
1749 /// RootMove::insert_pv_in_tt() is called at the end of a search iteration, and
1750 /// inserts the PV back into the TT. This makes sure the old PV moves are searched
1751 /// first, even if the old TT entries have been overwritten.
1752
1753 void RootMove::insert_pv_in_tt(Position& pos) {
1754
1755   StateInfo state[MAX_PLY_PLUS_2], *st = state;
1756   TTEntry* tte;
1757   Key k;
1758   Value v, m = VALUE_NONE;
1759   int ply = 0;
1760
1761   assert(pv[ply] != MOVE_NONE && pos.is_pseudo_legal(pv[ply]));
1762
1763   do {
1764       k = pos.key();
1765       tte = TT.probe(k);
1766
1767       // Don't overwrite existing correct entries
1768       if (!tte || tte->move() != pv[ply])
1769       {
1770           v = (pos.in_check() ? VALUE_NONE : evaluate(pos, m));
1771           TT.store(k, VALUE_NONE, BOUND_NONE, DEPTH_NONE, pv[ply], v, m);
1772       }
1773       pos.do_move(pv[ply], *st++);
1774
1775   } while (pv[++ply] != MOVE_NONE);
1776
1777   do pos.undo_move(pv[--ply]); while (ply);
1778 }
1779
1780
1781 /// Thread::idle_loop() is where the thread is parked when it has no work to do.
1782 /// The parameter 'master_sp', if non-NULL, is a pointer to an active SplitPoint
1783 /// object for which the thread is the master.
1784
1785 void Thread::idle_loop(SplitPoint* sp_master) {
1786
1787   // If this thread is the master of a split point and all slaves have
1788   // finished their work at this split point, return from the idle loop.
1789   while (!sp_master || sp_master->slavesMask)
1790   {
1791       // If we are not searching, wait for a condition to be signaled
1792       // instead of wasting CPU time polling for work.
1793       while (   do_sleep
1794              || do_exit
1795              || (!is_searching && Threads.use_sleeping_threads()))
1796       {
1797           if (do_exit)
1798           {
1799               assert(!sp_master);
1800               return;
1801           }
1802
1803           // Grab the lock to avoid races with Thread::wake_up()
1804           lock_grab(sleepLock);
1805
1806           // If we are master and all slaves have finished don't go to sleep
1807           if (sp_master && !sp_master->slavesMask)
1808           {
1809               lock_release(sleepLock);
1810               break;
1811           }
1812
1813           // Do sleep after retesting sleep conditions under lock protection, in
1814           // particular we need to avoid a deadlock in case a master thread has,
1815           // in the meanwhile, allocated us and sent the wake_up() call before we
1816           // had the chance to grab the lock.
1817           if (do_sleep || !is_searching)
1818               cond_wait(sleepCond, sleepLock);
1819
1820           lock_release(sleepLock);
1821       }
1822
1823       // If this thread has been assigned work, launch a search
1824       if (is_searching)
1825       {
1826           assert(!do_sleep && !do_exit);
1827
1828           lock_grab(Threads.splitLock);
1829
1830           assert(is_searching);
1831           SplitPoint* sp = curSplitPoint;
1832
1833           lock_release(Threads.splitLock);
1834
1835           Stack ss[MAX_PLY_PLUS_2];
1836           Position pos(*sp->pos, threadID);
1837           int master = sp->master;
1838
1839           memcpy(ss, sp->ss - 1, 4 * sizeof(Stack));
1840           (ss+1)->sp = sp;
1841
1842           lock_grab(sp->lock);
1843
1844           if (sp->nodeType == Root)
1845               search<SplitPointRoot>(pos, ss+1, sp->alpha, sp->beta, sp->depth);
1846           else if (sp->nodeType == PV)
1847               search<SplitPointPV>(pos, ss+1, sp->alpha, sp->beta, sp->depth);
1848           else if (sp->nodeType == NonPV)
1849               search<SplitPointNonPV>(pos, ss+1, sp->alpha, sp->beta, sp->depth);
1850           else
1851               assert(false);
1852
1853           assert(is_searching);
1854
1855           is_searching = false;
1856           sp->slavesMask &= ~(1ULL << threadID);
1857           sp->nodes += pos.nodes_searched();
1858
1859           // After releasing the lock we cannot access anymore any SplitPoint
1860           // related data in a reliably way becuase it could have been released
1861           // under our feet by the sp master.
1862           lock_release(sp->lock);
1863
1864           // Wake up master thread so to allow it to return from the idle loop in
1865           // case we are the last slave of the split point.
1866           if (   Threads.use_sleeping_threads()
1867               && threadID != master
1868               && !Threads[master].is_searching)
1869               Threads[master].wake_up();
1870       }
1871   }
1872 }
1873
1874
1875 /// check_time() is called by the timer thread when the timer triggers. It is
1876 /// used to print debug info and, more important, to detect when we are out of
1877 /// available time and so stop the search.
1878
1879 void check_time() {
1880
1881   static Time lastInfoTime = Time::current_time();
1882
1883   if (lastInfoTime.elapsed() >= 1000)
1884   {
1885       lastInfoTime.restart();
1886       dbg_print();
1887   }
1888
1889   if (Limits.ponder)
1890       return;
1891
1892   int e = SearchTime.elapsed();
1893   bool stillAtFirstMove =    Signals.firstRootMove
1894                          && !Signals.failedLowAtRoot
1895                          &&  e > TimeMgr.available_time();
1896
1897   bool noMoreTime =   e > TimeMgr.maximum_time() - 2 * TimerResolution
1898                    || stillAtFirstMove;
1899
1900   if (   (Limits.use_time_management() && noMoreTime)
1901       || (Limits.maxTime && e >= Limits.maxTime))
1902       Signals.stop = true;
1903 }