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