]> git.sesse.net Git - stockfish/blob - src/evaluate.cpp
Simplify move_importance()
[stockfish] / src / evaluate.cpp
1 /*
2   Stockfish, a UCI chess playing engine derived from Glaurung 2.1
3   Copyright (C) 2004-2008 Tord Romstad (Glaurung author)
4   Copyright (C) 2008-2013 Marco Costalba, Joona Kiiski, Tord Romstad
5
6   Stockfish is free software: you can redistribute it and/or modify
7   it under the terms of the GNU General Public License as published by
8   the Free Software Foundation, either version 3 of the License, or
9   (at your option) any later version.
10
11   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 <iomanip>
22 #include <sstream>
23 #include <algorithm>
24
25 #include "bitcount.h"
26 #include "evaluate.h"
27 #include "material.h"
28 #include "pawns.h"
29 #include "thread.h"
30 #include "ucioption.h"
31
32 namespace {
33
34   enum ExtendedPieceType { // Used for tracing
35     PST = 8, IMBALANCE, MOBILITY, THREAT, PASSED, SPACE, TOTAL
36   };
37
38   namespace Tracing {
39
40     Score scores[COLOR_NB][TOTAL + 1];
41     std::stringstream stream;
42
43     void add(int idx, Score term_w, Score term_b = SCORE_ZERO);
44     void row(const char* name, int idx);
45     std::string do_trace(const Position& pos);
46   }
47
48   // Struct EvalInfo contains various information computed and collected
49   // by the evaluation functions.
50   struct EvalInfo {
51
52     // Pointers to material and pawn hash table entries
53     Material::Entry* mi;
54     Pawns::Entry* pi;
55
56     // attackedBy[color][piece type] is a bitboard representing all squares
57     // attacked by a given color and piece type, attackedBy[color][ALL_PIECES]
58     // contains all squares attacked by the given color.
59     Bitboard attackedBy[COLOR_NB][PIECE_TYPE_NB];
60
61     // kingRing[color] is the zone around the king which is considered
62     // by the king safety evaluation. This consists of the squares directly
63     // adjacent to the king, and the three (or two, for a king on an edge file)
64     // squares two ranks in front of the king. For instance, if black's king
65     // is on g8, kingRing[BLACK] is a bitboard containing the squares f8, h8,
66     // f7, g7, h7, f6, g6 and h6.
67     Bitboard kingRing[COLOR_NB];
68
69     // kingAttackersCount[color] is the number of pieces of the given color
70     // which attack a square in the kingRing of the enemy king.
71     int kingAttackersCount[COLOR_NB];
72
73     // kingAttackersWeight[color] is the sum of the "weight" of the pieces of the
74     // given color which attack a square in the kingRing of the enemy king. The
75     // weights of the individual piece types are given by the variables
76     // QueenAttackWeight, RookAttackWeight, BishopAttackWeight and
77     // KnightAttackWeight in evaluate.cpp
78     int kingAttackersWeight[COLOR_NB];
79
80     // kingAdjacentZoneAttacksCount[color] is the number of attacks to squares
81     // directly adjacent to the king of the given color. Pieces which attack
82     // more than one square are counted multiple times. For instance, if black's
83     // king is on g8 and there's a white knight on g5, this knight adds
84     // 2 to kingAdjacentZoneAttacksCount[BLACK].
85     int kingAdjacentZoneAttacksCount[COLOR_NB];
86
87     Bitboard pinnedPieces[COLOR_NB];
88   };
89
90   // Evaluation grain size, must be a power of 2
91   const int GrainSize = 4;
92
93   // Evaluation weights, initialized from UCI options
94   enum { Mobility, PawnStructure, PassedPawns, Space, KingDangerUs, KingDangerThem };
95   Score Weights[6];
96
97   typedef Value V;
98   #define S(mg, eg) make_score(mg, eg)
99
100   // Internal evaluation weights. These are applied on top of the evaluation
101   // weights read from UCI parameters. The purpose is to be able to change
102   // the evaluation weights while keeping the default values of the UCI
103   // parameters at 100, which looks prettier.
104   //
105   // Values modified by Joona Kiiski
106   const Score WeightsInternal[] = {
107       S(289, 344), S(233, 201), S(221, 273), S(46, 0), S(271, 0), S(307, 0)
108   };
109
110   // MobilityBonus[PieceType][attacked] contains bonuses for middle and end
111   // game, indexed by piece type and number of attacked squares not occupied by
112   // friendly pieces.
113   const Score MobilityBonus[][32] = {
114      {}, {},
115      { S(-35,-30), S(-22,-20), S(-9,-10), S( 3,  0), S(15, 10), S(27, 20), // Knights
116        S( 37, 28), S( 42, 31), S(44, 33) },
117      { S(-22,-27), S( -8,-13), S( 6,  1), S(20, 15), S(34, 29), S(48, 43), // Bishops
118        S( 60, 55), S( 68, 63), S(74, 68), S(77, 72), S(80, 75), S(82, 77),
119        S( 84, 79), S( 86, 81) },
120      { S(-17,-33), S(-11,-16), S(-5,  0), S( 1, 16), S( 7, 32), S(13, 48), // Rooks
121        S( 18, 64), S( 22, 80), S(26, 96), S(29,109), S(31,115), S(33,119),
122        S( 35,122), S( 36,123), S(37,124) },
123      { S(-12,-20), S( -8,-13), S(-5, -7), S(-2, -1), S( 1,  5), S( 4, 11), // Queens
124        S(  7, 17), S( 10, 23), S(13, 29), S(16, 34), S(18, 38), S(20, 40),
125        S( 22, 41), S( 23, 41), S(24, 41), S(25, 41), S(25, 41), S(25, 41),
126        S( 25, 41), S( 25, 41), S(25, 41), S(25, 41), S(25, 41), S(25, 41),
127        S( 25, 41), S( 25, 41), S(25, 41), S(25, 41) }
128   };
129
130   // Outpost[PieceType][Square] contains bonuses for knights and bishops outposts,
131   // indexed by piece type and square (from white's point of view).
132   const Value Outpost[][SQUARE_NB] = {
133   {
134   //  A     B     C     D     E     F     G     H
135     V(0), V(0), V(0), V(0), V(0), V(0), V(0), V(0), // Knights
136     V(0), V(0), V(0), V(0), V(0), V(0), V(0), V(0),
137     V(0), V(0), V(4), V(8), V(8), V(4), V(0), V(0),
138     V(0), V(4),V(17),V(26),V(26),V(17), V(4), V(0),
139     V(0), V(8),V(26),V(35),V(35),V(26), V(8), V(0),
140     V(0), V(4),V(17),V(17),V(17),V(17), V(4), V(0) },
141   {
142     V(0), V(0), V(0), V(0), V(0), V(0), V(0), V(0), // Bishops
143     V(0), V(0), V(0), V(0), V(0), V(0), V(0), V(0),
144     V(0), V(0), V(5), V(5), V(5), V(5), V(0), V(0),
145     V(0), V(5),V(10),V(10),V(10),V(10), V(5), V(0),
146     V(0),V(10),V(21),V(21),V(21),V(21),V(10), V(0),
147     V(0), V(5), V(8), V(8), V(8), V(8), V(5), V(0) }
148   };
149
150   // Threat[attacking][attacked] contains bonuses according to which piece
151   // type attacks which one.
152   const Score Threat[][PIECE_TYPE_NB] = {
153     { S(0, 0), S( 7, 39), S(24, 49), S(24, 49), S(41,100), S(41,100) }, // Minor
154     { S(0, 0), S(15, 39), S(15, 45), S(15, 45), S(15, 45), S(24, 49) }, // Major
155   };
156
157   // ThreatenedByPawn[PieceType] contains a penalty according to which piece
158   // type is attacked by an enemy pawn.
159   const Score ThreatenedByPawn[] = {
160     S(0, 0), S(0, 0), S(56, 70), S(56, 70), S(76, 99), S(86, 118)
161   };
162
163   #undef S
164
165   const Score Tempo            = make_score(24, 11);
166   const Score RookOn7th        = make_score(11, 20);
167   const Score QueenOn7th       = make_score( 3,  8);
168   const Score RookOnPawn       = make_score(10, 28);
169   const Score QueenOnPawn      = make_score( 4, 20);
170   const Score RookOpenFile     = make_score(43, 21);
171   const Score RookSemiopenFile = make_score(19, 10);
172   const Score BishopPawns      = make_score( 8, 12);
173   const Score KnightPawns      = make_score( 8,  4);
174   const Score MinorBehindPawn  = make_score(16,  0);
175   const Score UndefendedMinor  = make_score(25, 10);
176   const Score TrappedRook      = make_score(90,  0);
177   const Score Unstoppable      = make_score( 0, 20);
178
179   // Penalty for a bishop on a1/h1 (a8/h8 for black) which is trapped by
180   // a friendly pawn on b2/g2 (b7/g7 for black). This can obviously only
181   // happen in Chess960 games.
182   const Score TrappedBishopA1H1 = make_score(50, 50);
183
184   // SpaceMask[Color] contains the area of the board which is considered
185   // by the space evaluation. In the middlegame, each side is given a bonus
186   // based on how many squares inside this area are safe and available for
187   // friendly minor pieces.
188   const Bitboard SpaceMask[] = {
189     (FileCBB | FileDBB | FileEBB | FileFBB) & (Rank2BB | Rank3BB | Rank4BB),
190     (FileCBB | FileDBB | FileEBB | FileFBB) & (Rank7BB | Rank6BB | Rank5BB)
191   };
192
193   // King danger constants and variables. The king danger scores are taken
194   // from KingDanger[]. Various little "meta-bonuses" measuring the strength
195   // of the enemy attack are added up into an integer, which is used as an
196   // index to KingDanger[].
197   //
198   // KingAttackWeights[PieceType] contains king attack weights by piece type
199   const int KingAttackWeights[] = { 0, 0, 2, 2, 3, 5 };
200
201   // Bonuses for enemy's safe checks
202   const int QueenContactCheck = 24;
203   const int RookContactCheck  = 16;
204   const int QueenCheck        = 12;
205   const int RookCheck         = 8;
206   const int BishopCheck       = 2;
207   const int KnightCheck       = 3;
208
209   // KingDanger[Color][attackUnits] contains the actual king danger weighted
210   // scores, indexed by color and by a calculated integer number.
211   Score KingDanger[COLOR_NB][128];
212
213   // Function prototypes
214   template<bool Trace>
215   Value do_evaluate(const Position& pos);
216
217   template<Color Us>
218   void init_eval_info(const Position& pos, EvalInfo& ei);
219
220   template<Color Us, bool Trace>
221   Score evaluate_pieces_of_color(const Position& pos, EvalInfo& ei, Score* mobility);
222
223   template<Color Us, bool Trace>
224   Score evaluate_king(const Position& pos, const EvalInfo& ei);
225
226   template<Color Us, bool Trace>
227   Score evaluate_threats(const Position& pos, const EvalInfo& ei);
228
229   template<Color Us, bool Trace>
230   Score evaluate_passed_pawns(const Position& pos, const EvalInfo& ei);
231
232   template<Color Us>
233   int evaluate_space(const Position& pos, const EvalInfo& ei);
234
235   Score evaluate_unstoppable_pawns(const Position& pos, Color us, const EvalInfo& ei);
236
237   Value interpolate(const Score& v, Phase ph, ScaleFactor sf);
238   Score apply_weight(Score v, Score w);
239   Score weight_option(const std::string& mgOpt, const std::string& egOpt, Score internalWeight);
240   double to_cp(Value v);
241 }
242
243
244 namespace Eval {
245
246   /// evaluate() is the main evaluation function. It always computes two
247   /// values, an endgame score and a middlegame score, and interpolates
248   /// between them based on the remaining material.
249
250   Value evaluate(const Position& pos) {
251     return do_evaluate<false>(pos);
252   }
253
254
255   /// trace() is like evaluate(), but instead of returning a value, it returns
256   /// a string (suitable for outputting to stdout) that contains the detailed
257   /// descriptions and values of each evaluation term. It's mainly used for
258   /// debugging.
259   std::string trace(const Position& pos) {
260     return Tracing::do_trace(pos);
261   }
262
263
264   /// init() computes evaluation weights from the corresponding UCI parameters
265   /// and setup king tables.
266
267   void init() {
268
269     Weights[Mobility]       = weight_option("Mobility (Midgame)", "Mobility (Endgame)", WeightsInternal[Mobility]);
270     Weights[PawnStructure]  = weight_option("Pawn Structure (Midgame)", "Pawn Structure (Endgame)", WeightsInternal[PawnStructure]);
271     Weights[PassedPawns]    = weight_option("Passed Pawns (Midgame)", "Passed Pawns (Endgame)", WeightsInternal[PassedPawns]);
272     Weights[Space]          = weight_option("Space", "Space", WeightsInternal[Space]);
273     Weights[KingDangerUs]   = weight_option("Cowardice", "Cowardice", WeightsInternal[KingDangerUs]);
274     Weights[KingDangerThem] = weight_option("Aggressiveness", "Aggressiveness", WeightsInternal[KingDangerThem]);
275
276     const int MaxSlope = 30;
277     const int Peak = 1280;
278
279     for (int t = 0, i = 1; i < 100; ++i)
280     {
281         t = std::min(Peak, std::min(int(0.4 * i * i), t + MaxSlope));
282
283         KingDanger[1][i] = apply_weight(make_score(t, 0), Weights[KingDangerUs]);
284         KingDanger[0][i] = apply_weight(make_score(t, 0), Weights[KingDangerThem]);
285     }
286   }
287
288 } // namespace Eval
289
290
291 namespace {
292
293 template<bool Trace>
294 Value do_evaluate(const Position& pos) {
295
296   assert(!pos.checkers());
297
298   EvalInfo ei;
299   Score score, mobility[2] = { SCORE_ZERO, SCORE_ZERO };
300   Thread* th = pos.this_thread();
301
302   // Initialize score by reading the incrementally updated scores included
303   // in the position object (material + piece square tables) and adding a
304   // Tempo bonus. Score is computed from the point of view of white.
305   score = pos.psq_score() + (pos.side_to_move() == WHITE ? Tempo : -Tempo);
306
307   // Probe the material hash table
308   ei.mi = Material::probe(pos, th->materialTable, th->endgames);
309   score += ei.mi->material_value();
310
311   // If we have a specialized evaluation function for the current material
312   // configuration, call it and return.
313   if (ei.mi->specialized_eval_exists())
314       return ei.mi->evaluate(pos);
315
316   // Probe the pawn hash table
317   ei.pi = Pawns::probe(pos, th->pawnsTable);
318   score += apply_weight(ei.pi->pawns_value(), Weights[PawnStructure]);
319
320   // Initialize attack and king safety bitboards
321   init_eval_info<WHITE>(pos, ei);
322   init_eval_info<BLACK>(pos, ei);
323
324   // Evaluate pieces and mobility
325   score +=  evaluate_pieces_of_color<WHITE, Trace>(pos, ei, mobility)
326           - evaluate_pieces_of_color<BLACK, Trace>(pos, ei, mobility);
327
328   score += apply_weight(mobility[WHITE] - mobility[BLACK], Weights[Mobility]);
329
330   // Evaluate kings after all other pieces because we need complete attack
331   // information when computing the king safety evaluation.
332   score +=  evaluate_king<WHITE, Trace>(pos, ei)
333           - evaluate_king<BLACK, Trace>(pos, ei);
334
335   // Evaluate tactical threats, we need full attack information including king
336   score +=  evaluate_threats<WHITE, Trace>(pos, ei)
337           - evaluate_threats<BLACK, Trace>(pos, ei);
338
339   // Evaluate passed pawns, we need full attack information including king
340   score +=  evaluate_passed_pawns<WHITE, Trace>(pos, ei)
341           - evaluate_passed_pawns<BLACK, Trace>(pos, ei);
342
343   // If one side has only a king, score for potential unstoppable pawns
344   if (!pos.non_pawn_material(WHITE) || !pos.non_pawn_material(BLACK))
345       score +=  evaluate_unstoppable_pawns(pos, WHITE, ei)
346               - evaluate_unstoppable_pawns(pos, BLACK, ei);
347
348   // Evaluate space for both sides, only in middlegame
349   if (ei.mi->space_weight())
350   {
351       int s = evaluate_space<WHITE>(pos, ei) - evaluate_space<BLACK>(pos, ei);
352       score += apply_weight(s * ei.mi->space_weight(), Weights[Space]);
353   }
354
355   // Scale winning side if position is more drawish than it appears
356   ScaleFactor sf = eg_value(score) > VALUE_DRAW ? ei.mi->scale_factor(pos, WHITE)
357                                                 : ei.mi->scale_factor(pos, BLACK);
358
359   // If we don't already have an unusual scale factor, check for opposite
360   // colored bishop endgames, and use a lower scale for those.
361   if (   ei.mi->game_phase() < PHASE_MIDGAME
362       && pos.opposite_bishops()
363       && sf == SCALE_FACTOR_NORMAL)
364   {
365       // Ignoring any pawns, do both sides only have a single bishop and no
366       // other pieces?
367       if (   pos.non_pawn_material(WHITE) == BishopValueMg
368           && pos.non_pawn_material(BLACK) == BishopValueMg)
369       {
370           // Check for KBP vs KB with only a single pawn that is almost
371           // certainly a draw or at least two pawns.
372           bool one_pawn = (pos.count<PAWN>(WHITE) + pos.count<PAWN>(BLACK) == 1);
373           sf = one_pawn ? ScaleFactor(8) : ScaleFactor(32);
374       }
375       else
376           // Endgame with opposite-colored bishops, but also other pieces. Still
377           // a bit drawish, but not as drawish as with only the two bishops.
378            sf = ScaleFactor(50);
379   }
380
381   Value v = interpolate(score, ei.mi->game_phase(), sf);
382
383   // In case of tracing add all single evaluation contributions for both white and black
384   if (Trace)
385   {
386       Tracing::add(PST, pos.psq_score());
387       Tracing::add(IMBALANCE, ei.mi->material_value());
388       Tracing::add(PAWN, ei.pi->pawns_value());
389       Score w = ei.mi->space_weight() * evaluate_space<WHITE>(pos, ei);
390       Score b = ei.mi->space_weight() * evaluate_space<BLACK>(pos, ei);
391       Tracing::add(SPACE, apply_weight(w, Weights[Space]), apply_weight(b, Weights[Space]));
392       Tracing::add(TOTAL, score);
393       Tracing::stream << "\nScaling: " << std::noshowpos
394                       << std::setw(6) << 100.0 * ei.mi->game_phase() / 128.0 << "% MG, "
395                       << std::setw(6) << 100.0 * (1.0 - ei.mi->game_phase() / 128.0) << "% * "
396                       << std::setw(6) << (100.0 * sf) / SCALE_FACTOR_NORMAL << "% EG.\n"
397                       << "Total evaluation: " << to_cp(v);
398   }
399
400   return pos.side_to_move() == WHITE ? v : -v;
401 }
402
403
404   // init_eval_info() initializes king bitboards for given color adding
405   // pawn attacks. To be done at the beginning of the evaluation.
406
407   template<Color Us>
408   void init_eval_info(const Position& pos, EvalInfo& ei) {
409
410     const Color  Them = (Us == WHITE ? BLACK : WHITE);
411     const Square Down = (Us == WHITE ? DELTA_S : DELTA_N);
412
413     ei.pinnedPieces[Us] = pos.pinned_pieces(Us);
414
415     Bitboard b = ei.attackedBy[Them][KING] = pos.attacks_from<KING>(pos.king_square(Them));
416     ei.attackedBy[Us][PAWN] = ei.pi->pawn_attacks(Us);
417
418     // Init king safety tables only if we are going to use them
419     if (pos.count<QUEEN>(Us) && pos.non_pawn_material(Us) > QueenValueMg + PawnValueMg)
420     {
421         ei.kingRing[Them] = b | shift_bb<Down>(b);
422         b &= ei.attackedBy[Us][PAWN];
423         ei.kingAttackersCount[Us] = b ? popcount<Max15>(b) : 0;
424         ei.kingAdjacentZoneAttacksCount[Us] = ei.kingAttackersWeight[Us] = 0;
425     }
426     else
427         ei.kingRing[Them] = ei.kingAttackersCount[Us] = 0;
428   }
429
430
431   // evaluate_outposts() evaluates bishop and knight outpost squares
432
433   template<PieceType Piece, Color Us>
434   Score evaluate_outposts(const Position& pos, EvalInfo& ei, Square s) {
435
436     const Color Them = (Us == WHITE ? BLACK : WHITE);
437
438     assert (Piece == BISHOP || Piece == KNIGHT);
439
440     // Initial bonus based on square
441     Value bonus = Outpost[Piece == BISHOP][relative_square(Us, s)];
442
443     // Increase bonus if supported by pawn, especially if the opponent has
444     // no minor piece which can trade with the outpost piece.
445     if (bonus && (ei.attackedBy[Us][PAWN] & s))
446     {
447         if (   !pos.pieces(Them, KNIGHT)
448             && !(squares_of_color(s) & pos.pieces(Them, BISHOP)))
449             bonus += bonus + bonus / 2;
450         else
451             bonus += bonus / 2;
452     }
453
454     return make_score(bonus, bonus);
455   }
456
457
458   // evaluate_pieces() assigns bonuses and penalties to the pieces of a given color
459
460   template<PieceType Piece, Color Us, bool Trace>
461   Score evaluate_pieces(const Position& pos, EvalInfo& ei, Score* mobility, Bitboard mobilityArea) {
462
463     Bitboard b;
464     Square s;
465     Score score = SCORE_ZERO;
466
467     const Color Them = (Us == WHITE ? BLACK : WHITE);
468     const Square* pl = pos.list<Piece>(Us);
469
470     ei.attackedBy[Us][Piece] = 0;
471
472     while ((s = *pl++) != SQ_NONE)
473     {
474         // Find attacked squares, including x-ray attacks for bishops and rooks
475         b = Piece == BISHOP ? attacks_bb<BISHOP>(s, pos.pieces() ^ pos.pieces(Us, QUEEN))
476           : Piece ==   ROOK ? attacks_bb<  ROOK>(s, pos.pieces() ^ pos.pieces(Us, ROOK, QUEEN))
477                             : pos.attacks_from<Piece>(s);
478
479         if (ei.pinnedPieces[Us] & s)
480             b &= LineBB[pos.king_square(Us)][s];
481
482         ei.attackedBy[Us][Piece] |= b;
483
484         if (b & ei.kingRing[Them])
485         {
486             ei.kingAttackersCount[Us]++;
487             ei.kingAttackersWeight[Us] += KingAttackWeights[Piece];
488             Bitboard bb = b & ei.attackedBy[Them][KING];
489             if (bb)
490                 ei.kingAdjacentZoneAttacksCount[Us] += popcount<Max15>(bb);
491         }
492
493         int mob = Piece != QUEEN ? popcount<Max15>(b & mobilityArea)
494                                  : popcount<Full >(b & mobilityArea);
495
496         mobility[Us] += MobilityBonus[Piece][mob];
497
498         // Decrease score if we are attacked by an enemy pawn. The remaining part
499         // of threat evaluation must be done later when we have full attack info.
500         if (ei.attackedBy[Them][PAWN] & s)
501             score -= ThreatenedByPawn[Piece];
502
503         // Penalty for bishop with same coloured pawns
504         if (Piece == BISHOP)
505             score -= BishopPawns * ei.pi->pawns_on_same_color_squares(Us, s);
506
507         // Penalty for knight when there are few enemy pawns
508         if (Piece == KNIGHT)
509             score -= KnightPawns * std::max(5 - pos.count<PAWN>(Them), 0);
510
511         if (Piece == BISHOP || Piece == KNIGHT)
512         {
513             // Bishop and knight outposts squares
514             if (!(pos.pieces(Them, PAWN) & pawn_attack_span(Us, s)))
515                 score += evaluate_outposts<Piece, Us>(pos, ei, s);
516
517             // Bishop or knight behind a pawn
518             if (    relative_rank(Us, s) < RANK_5
519                 && (pos.pieces(PAWN) & (s + pawn_push(Us))))
520                 score += MinorBehindPawn;
521         }
522
523         if (  (Piece == ROOK || Piece == QUEEN)
524             && relative_rank(Us, s) >= RANK_5)
525         {
526             // Major piece on 7th rank and enemy king trapped on 8th
527             if (   relative_rank(Us, s) == RANK_7
528                 && relative_rank(Us, pos.king_square(Them)) == RANK_8)
529                 score += Piece == ROOK ? RookOn7th : QueenOn7th;
530
531             // Major piece attacking enemy pawns on the same rank/file
532             Bitboard pawns = pos.pieces(Them, PAWN) & PseudoAttacks[ROOK][s];
533             if (pawns)
534                 score += popcount<Max15>(pawns) * (Piece == ROOK ? RookOnPawn : QueenOnPawn);
535         }
536
537         // Special extra evaluation for rooks
538         if (Piece == ROOK)
539         {
540             // Give a bonus for a rook on a open or semi-open file
541             if (ei.pi->semiopen(Us, file_of(s)))
542                 score += ei.pi->semiopen(Them, file_of(s)) ? RookOpenFile : RookSemiopenFile;
543
544             if (mob > 3 || ei.pi->semiopen(Us, file_of(s)))
545                 continue;
546
547             Square ksq = pos.king_square(Us);
548
549             // Penalize rooks which are trapped by a king. Penalize more if the
550             // king has lost its castling capability.
551             if (   ((file_of(ksq) < FILE_E) == (file_of(s) < file_of(ksq)))
552                 && (rank_of(ksq) == rank_of(s) || relative_rank(Us, ksq) == RANK_1)
553                 && !ei.pi->semiopen_on_side(Us, file_of(ksq), file_of(ksq) < FILE_E))
554                 score -= (TrappedRook - make_score(mob * 8, 0)) * (pos.can_castle(Us) ? 1 : 2);
555         }
556
557         // An important Chess960 pattern: A cornered bishop blocked by a friendly
558         // pawn diagonally in front of it is a very serious problem, especially
559         // when that pawn is also blocked.
560         if (   Piece == BISHOP
561             && pos.is_chess960()
562             && (s == relative_square(Us, SQ_A1) || s == relative_square(Us, SQ_H1)))
563         {
564             const enum Piece P = make_piece(Us, PAWN);
565             Square d = pawn_push(Us) + (file_of(s) == FILE_A ? DELTA_E : DELTA_W);
566             if (pos.piece_on(s + d) == P)
567                 score -= !pos.empty(s + d + pawn_push(Us)) ? TrappedBishopA1H1 * 4
568                         : pos.piece_on(s + d + d) == P     ? TrappedBishopA1H1 * 2
569                                                            : TrappedBishopA1H1;
570         }
571     }
572
573     if (Trace)
574         Tracing::scores[Us][Piece] = score;
575
576     return score;
577   }
578
579
580   // evaluate_pieces_of_color() assigns bonuses and penalties to all the
581   // pieces of a given color.
582
583   template<Color Us, bool Trace>
584   Score evaluate_pieces_of_color(const Position& pos, EvalInfo& ei, Score* mobility) {
585
586     const Color Them = (Us == WHITE ? BLACK : WHITE);
587
588     // Do not include in mobility squares protected by enemy pawns or occupied by our pieces
589     const Bitboard mobilityArea = ~(ei.attackedBy[Them][PAWN] | pos.pieces(Us, PAWN, KING));
590
591     Score score =  evaluate_pieces<KNIGHT, Us, Trace>(pos, ei, mobility, mobilityArea)
592                  + evaluate_pieces<BISHOP, Us, Trace>(pos, ei, mobility, mobilityArea)
593                  + evaluate_pieces<ROOK,   Us, Trace>(pos, ei, mobility, mobilityArea)
594                  + evaluate_pieces<QUEEN,  Us, Trace>(pos, ei, mobility, mobilityArea);
595
596     // Sum up all attacked squares (updated in evaluate_pieces)
597     ei.attackedBy[Us][ALL_PIECES] =  ei.attackedBy[Us][PAWN]   | ei.attackedBy[Us][KNIGHT]
598                                    | ei.attackedBy[Us][BISHOP] | ei.attackedBy[Us][ROOK]
599                                    | ei.attackedBy[Us][QUEEN]  | ei.attackedBy[Us][KING];
600     if (Trace)
601         Tracing::scores[Us][MOBILITY] = apply_weight(mobility[Us], Weights[Mobility]);
602
603     return score;
604   }
605
606
607   // evaluate_king() assigns bonuses and penalties to a king of a given color
608
609   template<Color Us, bool Trace>
610   Score evaluate_king(const Position& pos, const EvalInfo& ei) {
611
612     const Color Them = (Us == WHITE ? BLACK : WHITE);
613
614     Bitboard undefended, b, b1, b2, safe;
615     int attackUnits;
616     const Square ksq = pos.king_square(Us);
617
618     // King shelter and enemy pawns storm
619     Score score = ei.pi->king_safety<Us>(pos, ksq);
620
621     // Main king safety evaluation
622     if (ei.kingAttackersCount[Them])
623     {
624         // Find the attacked squares around the king which have no defenders
625         // apart from the king itself
626         undefended =  ei.attackedBy[Them][ALL_PIECES]
627                     & ei.attackedBy[Us][KING]
628                     & ~(  ei.attackedBy[Us][PAWN]   | ei.attackedBy[Us][KNIGHT]
629                         | ei.attackedBy[Us][BISHOP] | ei.attackedBy[Us][ROOK]
630                         | ei.attackedBy[Us][QUEEN]);
631
632         // Initialize the 'attackUnits' variable, which is used later on as an
633         // index to the KingDanger[] array. The initial value is based on the
634         // number and types of the enemy's attacking pieces, the number of
635         // attacked and undefended squares around our king and the quality of
636         // the pawn shelter (current 'score' value).
637         attackUnits =  std::min(20, (ei.kingAttackersCount[Them] * ei.kingAttackersWeight[Them]) / 2)
638                      + 3 * (ei.kingAdjacentZoneAttacksCount[Them] + popcount<Max15>(undefended))
639                      - mg_value(score) / 32;
640
641         // Analyse the enemy's safe queen contact checks. Firstly, find the
642         // undefended squares around the king that are attacked by the enemy's
643         // queen...
644         b = undefended & ei.attackedBy[Them][QUEEN] & ~pos.pieces(Them);
645         if (b)
646         {
647             // ...and then remove squares not supported by another enemy piece
648             b &= (  ei.attackedBy[Them][PAWN]   | ei.attackedBy[Them][KNIGHT]
649                   | ei.attackedBy[Them][BISHOP] | ei.attackedBy[Them][ROOK]);
650             if (b)
651                 attackUnits +=  QueenContactCheck
652                               * popcount<Max15>(b)
653                               * (Them == pos.side_to_move() ? 2 : 1);
654         }
655
656         // Analyse the enemy's safe rook contact checks. Firstly, find the
657         // undefended squares around the king that are attacked by the enemy's
658         // rooks...
659         b = undefended & ei.attackedBy[Them][ROOK] & ~pos.pieces(Them);
660
661         // Consider only squares where the enemy's rook gives check
662         b &= PseudoAttacks[ROOK][ksq];
663
664         if (b)
665         {
666             // ...and then remove squares not supported by another enemy piece
667             b &= (  ei.attackedBy[Them][PAWN]   | ei.attackedBy[Them][KNIGHT]
668                   | ei.attackedBy[Them][BISHOP] | ei.attackedBy[Them][QUEEN]);
669             if (b)
670                 attackUnits +=  RookContactCheck
671                               * popcount<Max15>(b)
672                               * (Them == pos.side_to_move() ? 2 : 1);
673         }
674
675         // Analyse the enemy's safe distance checks for sliders and knights
676         safe = ~(pos.pieces(Them) | ei.attackedBy[Us][ALL_PIECES]);
677
678         b1 = pos.attacks_from<ROOK>(ksq) & safe;
679         b2 = pos.attacks_from<BISHOP>(ksq) & safe;
680
681         // Enemy queen safe checks
682         b = (b1 | b2) & ei.attackedBy[Them][QUEEN];
683         if (b)
684             attackUnits += QueenCheck * popcount<Max15>(b);
685
686         // Enemy rooks safe checks
687         b = b1 & ei.attackedBy[Them][ROOK];
688         if (b)
689             attackUnits += RookCheck * popcount<Max15>(b);
690
691         // Enemy bishops safe checks
692         b = b2 & ei.attackedBy[Them][BISHOP];
693         if (b)
694             attackUnits += BishopCheck * popcount<Max15>(b);
695
696         // Enemy knights safe checks
697         b = pos.attacks_from<KNIGHT>(ksq) & ei.attackedBy[Them][KNIGHT] & safe;
698         if (b)
699             attackUnits += KnightCheck * popcount<Max15>(b);
700
701         // To index KingDanger[] attackUnits must be in [0, 99] range
702         attackUnits = std::min(99, std::max(0, attackUnits));
703
704         // Finally, extract the king danger score from the KingDanger[]
705         // array and subtract the score from evaluation.
706         score -= KingDanger[Us == Search::RootColor][attackUnits];
707     }
708
709     if (Trace)
710         Tracing::scores[Us][KING] = score;
711
712     return score;
713   }
714
715
716   // evaluate_threats() assigns bonuses according to the type of attacking piece
717   // and the type of attacked one.
718
719   template<Color Us, bool Trace>
720   Score evaluate_threats(const Position& pos, const EvalInfo& ei) {
721
722     const Color Them = (Us == WHITE ? BLACK : WHITE);
723
724     Bitboard b, undefendedMinors, weakEnemies;
725     Score score = SCORE_ZERO;
726
727     // Undefended minors get penalized even if they are not under attack
728     undefendedMinors =  pos.pieces(Them, BISHOP, KNIGHT)
729                       & ~ei.attackedBy[Them][ALL_PIECES];
730
731     if (undefendedMinors)
732         score += UndefendedMinor;
733
734     // Enemy pieces not defended by a pawn and under our attack
735     weakEnemies =  pos.pieces(Them)
736                  & ~ei.attackedBy[Them][PAWN]
737                  & ei.attackedBy[Us][ALL_PIECES];
738
739     // Add a bonus according if the attacking pieces are minor or major
740     if (weakEnemies)
741     {
742         b = weakEnemies & (ei.attackedBy[Us][KNIGHT] | ei.attackedBy[Us][BISHOP]);
743         if (b)
744             score += Threat[0][type_of(pos.piece_on(lsb(b)))];
745
746         b = weakEnemies & (ei.attackedBy[Us][ROOK] | ei.attackedBy[Us][QUEEN]);
747         if (b)
748             score += Threat[1][type_of(pos.piece_on(lsb(b)))];
749     }
750
751     if (Trace)
752         Tracing::scores[Us][THREAT] = score;
753
754     return score;
755   }
756
757
758   // evaluate_passed_pawns() evaluates the passed pawns of the given color
759
760   template<Color Us, bool Trace>
761   Score evaluate_passed_pawns(const Position& pos, const EvalInfo& ei) {
762
763     const Color Them = (Us == WHITE ? BLACK : WHITE);
764
765     Bitboard b, squaresToQueen, defendedSquares, unsafeSquares, supportingPawns;
766     Score score = SCORE_ZERO;
767
768     b = ei.pi->passed_pawns(Us);
769
770     while (b)
771     {
772         Square s = pop_lsb(&b);
773
774         assert(pos.pawn_passed(Us, s));
775
776         int r = int(relative_rank(Us, s) - RANK_2);
777         int rr = r * (r - 1);
778
779         // Base bonus based on rank
780         Value mbonus = Value(17 * rr);
781         Value ebonus = Value(7 * (rr + r + 1));
782
783         if (rr)
784         {
785             Square blockSq = s + pawn_push(Us);
786
787             // Adjust bonus based on the king's proximity
788             ebonus +=  Value(square_distance(pos.king_square(Them), blockSq) * 5 * rr)
789                      - Value(square_distance(pos.king_square(Us  ), blockSq) * 2 * rr);
790
791             // If blockSq is not the queening square then consider also a second push
792             if (relative_rank(Us, blockSq) != RANK_8)
793                 ebonus -= Value(square_distance(pos.king_square(Us), blockSq + pawn_push(Us)) * rr);
794
795             // If the pawn is free to advance, then increase the bonus
796             if (pos.empty(blockSq))
797             {
798                 squaresToQueen = forward_bb(Us, s);
799
800                 // If there is an enemy rook or queen attacking the pawn from behind,
801                 // add all X-ray attacks by the rook or queen. Otherwise consider only
802                 // the squares in the pawn's path attacked or occupied by the enemy.
803                 if (    unlikely(forward_bb(Them, s) & pos.pieces(Them, ROOK, QUEEN))
804                     && (forward_bb(Them, s) & pos.pieces(Them, ROOK, QUEEN) & pos.attacks_from<ROOK>(s)))
805                     unsafeSquares = squaresToQueen;
806                 else
807                     unsafeSquares = squaresToQueen & (ei.attackedBy[Them][ALL_PIECES] | pos.pieces(Them));
808
809                 if (    unlikely(forward_bb(Them, s) & pos.pieces(Us, ROOK, QUEEN))
810                     && (forward_bb(Them, s) & pos.pieces(Us, ROOK, QUEEN) & pos.attacks_from<ROOK>(s)))
811                     defendedSquares = squaresToQueen;
812                 else
813                     defendedSquares = squaresToQueen & ei.attackedBy[Us][ALL_PIECES];
814
815                 // If there aren't any enemy attacks, then assign a huge bonus.
816                 // The bonus will be a bit smaller if at least the block square
817                 // isn't attacked, otherwise assign the smallest possible bonus.
818                 int k = !unsafeSquares ? 15 : !(unsafeSquares & blockSq) ? 9 : 3;
819
820                 // Assign a big bonus if the path to the queen is fully defended,
821                 // otherwise assign a bit less of a bonus if at least the block
822                 // square is defended.
823                 if (defendedSquares == squaresToQueen)
824                     k += 6;
825
826                 else if (defendedSquares & blockSq)
827                     k += (unsafeSquares & defendedSquares) == unsafeSquares ? 4 : 2;
828
829                 mbonus += Value(k * rr), ebonus += Value(k * rr);
830             }
831         } // rr != 0
832
833         // Increase the bonus if the passed pawn is supported by a friendly pawn
834         // on the same rank and a bit smaller if it's on the previous rank.
835         supportingPawns = pos.pieces(Us, PAWN) & adjacent_files_bb(file_of(s));
836         if (supportingPawns & rank_bb(s))
837             ebonus += Value(r * 20);
838
839         else if (supportingPawns & rank_bb(s - pawn_push(Us)))
840             ebonus += Value(r * 12);
841
842         // Rook pawns are a special case: They are sometimes worse, and
843         // sometimes better than other passed pawns. It is difficult to find
844         // good rules for determining whether they are good or bad. For now,
845         // we try the following: Increase the value for rook pawns if the
846         // other side has no pieces apart from a knight, and decrease the
847         // value if the other side has a rook or queen.
848         if (file_of(s) == FILE_A || file_of(s) == FILE_H)
849         {
850             if (pos.non_pawn_material(Them) <= KnightValueMg)
851                 ebonus += ebonus / 4;
852
853             else if (pos.pieces(Them, ROOK, QUEEN))
854                 ebonus -= ebonus / 4;
855         }
856
857         if (pos.count<PAWN>(Us) < pos.count<PAWN>(Them))
858             ebonus += ebonus / 4;
859
860         score += make_score(mbonus, ebonus);
861
862     }
863
864     if (Trace)
865         Tracing::scores[Us][PASSED] = apply_weight(score, Weights[PassedPawns]);
866
867     // Add the scores to the middlegame and endgame eval
868     return apply_weight(score, Weights[PassedPawns]);
869   }
870
871
872   // evaluate_unstoppable_pawns() scores the most advanced among the passed and
873   // candidate pawns. In case opponent has no pieces but pawns, this is somewhat
874   // related to the possibility that pawns are unstoppable.
875
876   Score evaluate_unstoppable_pawns(const Position& pos, Color us, const EvalInfo& ei) {
877
878     Bitboard b = ei.pi->passed_pawns(us) | ei.pi->candidate_pawns(us);
879
880     if (!b || pos.non_pawn_material(~us))
881         return SCORE_ZERO;
882
883     return Unstoppable * int(relative_rank(us, frontmost_sq(us, b)));
884   }
885
886
887   // evaluate_space() computes the space evaluation for a given side. The
888   // space evaluation is a simple bonus based on the number of safe squares
889   // available for minor pieces on the central four files on ranks 2--4. Safe
890   // squares one, two or three squares behind a friendly pawn are counted
891   // twice. Finally, the space bonus is scaled by a weight taken from the
892   // material hash table. The aim is to improve play on game opening.
893   template<Color Us>
894   int evaluate_space(const Position& pos, const EvalInfo& ei) {
895
896     const Color Them = (Us == WHITE ? BLACK : WHITE);
897
898     // Find the safe squares for our pieces inside the area defined by
899     // SpaceMask[]. A square is unsafe if it is attacked by an enemy
900     // pawn, or if it is undefended and attacked by an enemy piece.
901     Bitboard safe =   SpaceMask[Us]
902                    & ~pos.pieces(Us, PAWN)
903                    & ~ei.attackedBy[Them][PAWN]
904                    & (ei.attackedBy[Us][ALL_PIECES] | ~ei.attackedBy[Them][ALL_PIECES]);
905
906     // Find all squares which are at most three squares behind some friendly pawn
907     Bitboard behind = pos.pieces(Us, PAWN);
908     behind |= (Us == WHITE ? behind >>  8 : behind <<  8);
909     behind |= (Us == WHITE ? behind >> 16 : behind << 16);
910
911     // Since SpaceMask[Us] is fully on our half of the board
912     assert(unsigned(safe >> (Us == WHITE ? 32 : 0)) == 0);
913
914     // Count safe + (behind & safe) with a single popcount
915     return popcount<Full>((Us == WHITE ? safe << 32 : safe >> 32) | (behind & safe));
916   }
917
918
919   // interpolate() interpolates between a middlegame and an endgame score,
920   // based on game phase. It also scales the return value by a ScaleFactor array.
921
922   Value interpolate(const Score& v, Phase ph, ScaleFactor sf) {
923
924     assert(mg_value(v) > -VALUE_INFINITE && mg_value(v) < VALUE_INFINITE);
925     assert(eg_value(v) > -VALUE_INFINITE && eg_value(v) < VALUE_INFINITE);
926     assert(ph >= PHASE_ENDGAME && ph <= PHASE_MIDGAME);
927
928     int e = (eg_value(v) * int(sf)) / SCALE_FACTOR_NORMAL;
929     int r = (mg_value(v) * int(ph) + e * int(PHASE_MIDGAME - ph)) / PHASE_MIDGAME;
930     return Value((r / GrainSize) * GrainSize); // Sign independent
931   }
932
933   // apply_weight() weights score v by score w trying to prevent overflow
934   Score apply_weight(Score v, Score w) {
935     return make_score((int(mg_value(v)) * mg_value(w)) / 0x100,
936                       (int(eg_value(v)) * eg_value(w)) / 0x100);
937   }
938
939   // weight_option() computes the value of an evaluation weight, by combining
940   // two UCI-configurable weights (midgame and endgame) with an internal weight.
941
942   Score weight_option(const std::string& mgOpt, const std::string& egOpt, Score internalWeight) {
943
944     // Scale option value from 100 to 256
945     int mg = Options[mgOpt] * 256 / 100;
946     int eg = Options[egOpt] * 256 / 100;
947
948     return apply_weight(make_score(mg, eg), internalWeight);
949   }
950
951
952   // Tracing functions definitions
953
954   double to_cp(Value v) { return double(v) / double(PawnValueMg); }
955
956   void Tracing::add(int idx, Score wScore, Score bScore) {
957
958     scores[WHITE][idx] = wScore;
959     scores[BLACK][idx] = bScore;
960   }
961
962   void Tracing::row(const char* name, int idx) {
963
964     Score wScore = scores[WHITE][idx];
965     Score bScore = scores[BLACK][idx];
966
967     switch (idx) {
968     case PST: case IMBALANCE: case PAWN: case TOTAL:
969         stream << std::setw(20) << name << " |   ---   --- |   ---   --- | "
970                << std::setw(6)  << to_cp(mg_value(wScore)) << " "
971                << std::setw(6)  << to_cp(eg_value(wScore)) << " \n";
972         break;
973     default:
974         stream << std::setw(20) << name << " | " << std::noshowpos
975                << std::setw(5)  << to_cp(mg_value(wScore)) << " "
976                << std::setw(5)  << to_cp(eg_value(wScore)) << " | "
977                << std::setw(5)  << to_cp(mg_value(bScore)) << " "
978                << std::setw(5)  << to_cp(eg_value(bScore)) << " | "
979                << std::showpos
980                << std::setw(6)  << to_cp(mg_value(wScore - bScore)) << " "
981                << std::setw(6)  << to_cp(eg_value(wScore - bScore)) << " \n";
982     }
983   }
984
985   std::string Tracing::do_trace(const Position& pos) {
986
987     stream.str("");
988     stream << std::showpoint << std::showpos << std::fixed << std::setprecision(2);
989     std::memset(scores, 0, 2 * (TOTAL + 1) * sizeof(Score));
990
991     do_evaluate<true>(pos);
992
993     std::string totals = stream.str();
994     stream.str("");
995
996     stream << std::setw(21) << "Eval term " << "|    White    |    Black    |     Total     \n"
997                     <<             "                     |   MG    EG  |   MG    EG  |   MG     EG   \n"
998                     <<             "---------------------+-------------+-------------+---------------\n";
999
1000     row("Material, PST, Tempo", PST);
1001     row("Material imbalance", IMBALANCE);
1002     row("Pawns", PAWN);
1003     row("Knights", KNIGHT);
1004     row("Bishops", BISHOP);
1005     row("Rooks", ROOK);
1006     row("Queens", QUEEN);
1007     row("Mobility", MOBILITY);
1008     row("King safety", KING);
1009     row("Threats", THREAT);
1010     row("Passed pawns", PASSED);
1011     row("Space", SPACE);
1012
1013     stream <<             "---------------------+-------------+-------------+---------------\n";
1014     row("Total", TOTAL);
1015     stream << totals;
1016
1017     return stream.str();
1018   }
1019 }