]> git.sesse.net Git - stockfish/blob - src/syzygy/tbprobe.cpp
7-pieces Syzygy tablebase support
[stockfish] / src / syzygy / tbprobe.cpp
1 /*
2   Stockfish, a UCI chess playing engine derived from Glaurung 2.1
3   Copyright (c) 2013 Ronald de Man
4   Copyright (C) 2016-2018 Marco Costalba, Lucas Braesch
5
6   Stockfish is free software: you can redistribute it and/or modify
7   it under the terms of the GNU General Public License as published by
8   the Free Software Foundation, either version 3 of the License, or
9   (at your option) any later version.
10
11   Stockfish is distributed in the hope that it will be useful,
12   but WITHOUT ANY WARRANTY; without even the implied warranty of
13   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14   GNU General Public License for more details.
15
16   You should have received a copy of the GNU General Public License
17   along with this program.  If not, see <http://www.gnu.org/licenses/>.
18 */
19
20 #include <algorithm>
21 #include <atomic>
22 #include <cstdint>
23 #include <cstring>   // For std::memset and std::memcpy
24 #include <deque>
25 #include <fstream>
26 #include <iostream>
27 #include <list>
28 #include <sstream>
29 #include <type_traits>
30
31 #include "../bitboard.h"
32 #include "../movegen.h"
33 #include "../position.h"
34 #include "../search.h"
35 #include "../thread_win32.h"
36 #include "../types.h"
37 #include "../uci.h"
38
39 #include "tbprobe.h"
40
41 #ifndef _WIN32
42 #include <fcntl.h>
43 #include <unistd.h>
44 #include <sys/mman.h>
45 #include <sys/stat.h>
46 #else
47 #define WIN32_LEAN_AND_MEAN
48 #define NOMINMAX
49 #include <windows.h>
50 #endif
51
52 using namespace Tablebases;
53
54 int Tablebases::MaxCardinality;
55
56 namespace {
57
58 constexpr int TBPIECES = 7; // Max number of supported pieces
59
60 enum { BigEndian, LittleEndian };
61 enum TBType { KEY, WDL, DTZ }; // Used as template parameter
62
63 // Each table has a set of flags: all of them refer to DTZ tables, the last one to WDL tables
64 enum TBFlag { STM = 1, Mapped = 2, WinPlies = 4, LossPlies = 8, Wide = 16, SingleValue = 128 };
65
66 inline WDLScore operator-(WDLScore d) { return WDLScore(-int(d)); }
67 inline Square operator^=(Square& s, int i) { return s = Square(int(s) ^ i); }
68 inline Square operator^(Square s, int i) { return Square(int(s) ^ i); }
69
70 const std::string PieceToChar = " PNBRQK  pnbrqk";
71
72 int MapPawns[SQUARE_NB];
73 int MapB1H1H7[SQUARE_NB];
74 int MapA1D1D4[SQUARE_NB];
75 int MapKK[10][SQUARE_NB]; // [MapA1D1D4][SQUARE_NB]
76
77 int Binomial[6][SQUARE_NB];    // [k][n] k elements from a set of n elements
78 int LeadPawnIdx[6][SQUARE_NB]; // [leadPawnsCnt][SQUARE_NB]
79 int LeadPawnsSize[6][4];       // [leadPawnsCnt][FILE_A..FILE_D]
80
81 // Comparison function to sort leading pawns in ascending MapPawns[] order
82 bool pawns_comp(Square i, Square j) { return MapPawns[i] < MapPawns[j]; }
83 int off_A1H8(Square sq) { return int(rank_of(sq)) - file_of(sq); }
84
85 constexpr Value WDL_to_value[] = {
86    -VALUE_MATE + MAX_PLY + 1,
87     VALUE_DRAW - 2,
88     VALUE_DRAW,
89     VALUE_DRAW + 2,
90     VALUE_MATE - MAX_PLY - 1
91 };
92
93 template<typename T, int Half = sizeof(T) / 2, int End = sizeof(T) - 1>
94 inline void swap_endian(T& x)
95 {
96     static_assert(std::is_unsigned<T>::value, "Argument of swap_endian not unsigned");
97
98     uint8_t tmp, *c = (uint8_t*)&x;
99     for (int i = 0; i < Half; ++i)
100         tmp = c[i], c[i] = c[End - i], c[End - i] = tmp;
101 }
102 template<> inline void swap_endian<uint8_t>(uint8_t&) {}
103
104 template<typename T, int LE> T number(void* addr)
105 {
106     static const union { uint32_t i; char c[4]; } Le = { 0x01020304 };
107     static const bool IsLittleEndian = (Le.c[0] == 4);
108
109     T v;
110
111     if ((uintptr_t)addr & (alignof(T) - 1)) // Unaligned pointer (very rare)
112         std::memcpy(&v, addr, sizeof(T));
113     else
114         v = *((T*)addr);
115
116     if (LE != IsLittleEndian)
117         swap_endian(v);
118     return v;
119 }
120
121 // DTZ tables don't store valid scores for moves that reset the rule50 counter
122 // like captures and pawn moves but we can easily recover the correct dtz of the
123 // previous move if we know the position's WDL score.
124 int dtz_before_zeroing(WDLScore wdl) {
125     return wdl == WDLWin         ?  1   :
126            wdl == WDLCursedWin   ?  101 :
127            wdl == WDLBlessedLoss ? -101 :
128            wdl == WDLLoss        ? -1   : 0;
129 }
130
131 // Return the sign of a number (-1, 0, 1)
132 template <typename T> int sign_of(T val) {
133     return (T(0) < val) - (val < T(0));
134 }
135
136 // Numbers in little endian used by sparseIndex[] to point into blockLength[]
137 struct SparseEntry {
138     char block[4];   // Number of block
139     char offset[2];  // Offset within the block
140 };
141
142 static_assert(sizeof(SparseEntry) == 6, "SparseEntry must be 6 bytes");
143
144 typedef uint16_t Sym; // Huffman symbol
145
146 struct LR {
147     enum Side { Left, Right };
148
149     uint8_t lr[3]; // The first 12 bits is the left-hand symbol, the second 12
150                    // bits is the right-hand symbol. If symbol has length 1,
151                    // then the left-hand symbol is the stored value.
152     template<Side S>
153     Sym get() {
154         return S == Left  ? ((lr[1] & 0xF) << 8) | lr[0] :
155                S == Right ?  (lr[2] << 4) | (lr[1] >> 4) : (assert(false), Sym(-1));
156     }
157 };
158
159 static_assert(sizeof(LR) == 3, "LR tree entry must be 3 bytes");
160
161 // Tablebases data layout is structured as following:
162 //
163 //  TBFile:   memory maps/unmaps the physical .rtbw and .rtbz files
164 //  TBTable:  one object for each file with corresponding indexing information
165 //  TBTables: has ownership of TBTable objects, keeping a list and a hash
166
167 // class TBFile memory maps/unmaps the single .rtbw and .rtbz files. Files are
168 // memory mapped for best performance. Files are mapped at first access: at init
169 // time only existence of the file is checked.
170 class TBFile : public std::ifstream {
171
172     std::string fname;
173
174 public:
175     // Look for and open the file among the Paths directories where the .rtbw
176     // and .rtbz files can be found. Multiple directories are separated by ";"
177     // on Windows and by ":" on Unix-based operating systems.
178     //
179     // Example:
180     // C:\tb\wdl345;C:\tb\wdl6;D:\tb\dtz345;D:\tb\dtz6
181     static std::string Paths;
182
183     TBFile(const std::string& f) {
184
185 #ifndef _WIN32
186         constexpr char SepChar = ':';
187 #else
188         constexpr char SepChar = ';';
189 #endif
190         std::stringstream ss(Paths);
191         std::string path;
192
193         while (std::getline(ss, path, SepChar)) {
194             fname = path + "/" + f;
195             std::ifstream::open(fname);
196             if (is_open())
197                 return;
198         }
199     }
200
201     // Memory map the file and check it. File should be already open and will be
202     // closed after mapping.
203     uint8_t* map(void** baseAddress, uint64_t* mapping, TBType type) {
204
205         assert(is_open());
206
207         close(); // Need to re-open to get native file descriptor
208
209 #ifndef _WIN32
210         struct stat statbuf;
211         int fd = ::open(fname.c_str(), O_RDONLY);
212
213         if (fd == -1)
214             return *baseAddress = nullptr, nullptr;
215
216         fstat(fd, &statbuf);
217         *mapping = statbuf.st_size;
218         *baseAddress = mmap(nullptr, statbuf.st_size, PROT_READ, MAP_SHARED, fd, 0);
219         ::close(fd);
220
221         if (*baseAddress == MAP_FAILED) {
222             std::cerr << "Could not mmap() " << fname << std::endl;
223             exit(1);
224         }
225 #else
226         HANDLE fd = CreateFile(fname.c_str(), GENERIC_READ, FILE_SHARE_READ, nullptr,
227                                OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, nullptr);
228
229         if (fd == INVALID_HANDLE_VALUE)
230             return *baseAddress = nullptr, nullptr;
231
232         DWORD size_high;
233         DWORD size_low = GetFileSize(fd, &size_high);
234         HANDLE mmap = CreateFileMapping(fd, nullptr, PAGE_READONLY, size_high, size_low, nullptr);
235         CloseHandle(fd);
236
237         if (!mmap) {
238             std::cerr << "CreateFileMapping() failed" << std::endl;
239             exit(1);
240         }
241
242         *mapping = (uint64_t)mmap;
243         *baseAddress = MapViewOfFile(mmap, FILE_MAP_READ, 0, 0, 0);
244
245         if (!*baseAddress) {
246             std::cerr << "MapViewOfFile() failed, name = " << fname
247                       << ", error = " << GetLastError() << std::endl;
248             exit(1);
249         }
250 #endif
251         uint8_t* data = (uint8_t*)*baseAddress;
252
253         constexpr uint8_t Magics[][4] = { { 0xD7, 0x66, 0x0C, 0xA5 },
254                                           { 0x71, 0xE8, 0x23, 0x5D } };
255
256         if (memcmp(data, Magics[type == WDL], 4)) {
257             std::cerr << "Corrupted table in file " << fname << std::endl;
258             unmap(*baseAddress, *mapping);
259             return *baseAddress = nullptr, nullptr;
260         }
261
262         return data + 4; // Skip Magics's header
263     }
264
265     static void unmap(void* baseAddress, uint64_t mapping) {
266
267 #ifndef _WIN32
268         munmap(baseAddress, mapping);
269 #else
270         UnmapViewOfFile(baseAddress);
271         CloseHandle((HANDLE)mapping);
272 #endif
273     }
274 };
275
276 std::string TBFile::Paths;
277
278 // struct PairsData contains low level indexing information to access TB data.
279 // There are 8, 4 or 2 PairsData records for each TBTable, according to type of
280 // table and if positions have pawns or not. It is populated at first access.
281 struct PairsData {
282     uint8_t flags;                 // Table flags, see enum TBFlag
283     uint8_t maxSymLen;             // Maximum length in bits of the Huffman symbols
284     uint8_t minSymLen;             // Minimum length in bits of the Huffman symbols
285     uint32_t blocksNum;            // Number of blocks in the TB file
286     size_t sizeofBlock;            // Block size in bytes
287     size_t span;                   // About every span values there is a SparseIndex[] entry
288     Sym* lowestSym;                // lowestSym[l] is the symbol of length l with the lowest value
289     LR* btree;                     // btree[sym] stores the left and right symbols that expand sym
290     uint16_t* blockLength;         // Number of stored positions (minus one) for each block: 1..65536
291     uint32_t blockLengthSize;      // Size of blockLength[] table: padded so it's bigger than blocksNum
292     SparseEntry* sparseIndex;      // Partial indices into blockLength[]
293     size_t sparseIndexSize;        // Size of SparseIndex[] table
294     uint8_t* data;                 // Start of Huffman compressed data
295     std::vector<uint64_t> base64;  // base64[l - min_sym_len] is the 64bit-padded lowest symbol of length l
296     std::vector<uint8_t> symlen;   // Number of values (-1) represented by a given Huffman symbol: 1..256
297     Piece pieces[TBPIECES];        // Position pieces: the order of pieces defines the groups
298     uint64_t groupIdx[TBPIECES+1]; // Start index used for the encoding of the group's pieces
299     int groupLen[TBPIECES+1];      // Number of pieces in a given group: KRKN -> (3, 1)
300     uint16_t map_idx[4];           // WDLWin, WDLLoss, WDLCursedWin, WDLBlessedLoss (used in DTZ)
301 };
302
303 // struct TBTable contains indexing information to access the corresponding TBFile.
304 // There are 2 types of TBTable, corresponding to a WDL or a DTZ file. TBTable
305 // is populated at init time but the nested PairsData records are populated at
306 // first access, when the corresponding file is memory mapped.
307 template<TBType Type>
308 struct TBTable {
309     typedef typename std::conditional<Type == WDL, WDLScore, int>::type Ret;
310
311     static constexpr int Sides = Type == WDL ? 2 : 1;
312
313     std::atomic_bool ready;
314     void* baseAddress;
315     uint8_t* map;
316     uint64_t mapping;
317     Key key;
318     Key key2;
319     int pieceCount;
320     bool hasPawns;
321     bool hasUniquePieces;
322     uint8_t pawnCount[2]; // [Lead color / other color]
323     PairsData items[Sides][4]; // [wtm / btm][FILE_A..FILE_D or 0]
324
325     PairsData* get(int stm, int f) {
326         return &items[stm % Sides][hasPawns ? f : 0];
327     }
328
329     TBTable() : ready(false), baseAddress(nullptr) {}
330     explicit TBTable(const std::string& code);
331     explicit TBTable(const TBTable<WDL>& wdl);
332
333     ~TBTable() {
334         if (baseAddress)
335             TBFile::unmap(baseAddress, mapping);
336     }
337 };
338
339 template<>
340 TBTable<WDL>::TBTable(const std::string& code) : TBTable() {
341
342     StateInfo st;
343     Position pos;
344
345     key = pos.set(code, WHITE, &st).material_key();
346     pieceCount = pos.count<ALL_PIECES>();
347     hasPawns = pos.pieces(PAWN);
348
349     hasUniquePieces = false;
350     for (Color c = WHITE; c <= BLACK; ++c)
351         for (PieceType pt = PAWN; pt < KING; ++pt)
352             if (popcount(pos.pieces(c, pt)) == 1)
353                 hasUniquePieces = true;
354
355     // Set the leading color. In case both sides have pawns the leading color
356     // is the side with less pawns because this leads to better compression.
357     bool c =   !pos.count<PAWN>(BLACK)
358             || (   pos.count<PAWN>(WHITE)
359                 && pos.count<PAWN>(BLACK) >= pos.count<PAWN>(WHITE));
360
361     pawnCount[0] = pos.count<PAWN>(c ? WHITE : BLACK);
362     pawnCount[1] = pos.count<PAWN>(c ? BLACK : WHITE);
363
364     key2 = pos.set(code, BLACK, &st).material_key();
365 }
366
367 template<>
368 TBTable<DTZ>::TBTable(const TBTable<WDL>& wdl) : TBTable() {
369
370     // Use the corresponding WDL table to avoid recalculating all from scratch
371     key = wdl.key;
372     key2 = wdl.key2;
373     pieceCount = wdl.pieceCount;
374     hasPawns = wdl.hasPawns;
375     hasUniquePieces = wdl.hasUniquePieces;
376     pawnCount[0] = wdl.pawnCount[0];
377     pawnCount[1] = wdl.pawnCount[1];
378 }
379
380 // class TBTables creates and keeps ownership of the TBTable objects, one for
381 // each TB file found. It supports a fast, hash based, table lookup. Populated
382 // at init time, accessed at probe time.
383 class TBTables {
384
385     typedef std::tuple<Key, TBTable<WDL>*, TBTable<DTZ>*> Entry;
386
387     static const int Size = 1 << 16; // 64K table, indexed by key's 16 lsb
388
389     Entry hashTable[Size];
390
391     std::deque<TBTable<WDL>> wdlTable;
392     std::deque<TBTable<DTZ>> dtzTable;
393
394     void insert(Key key, TBTable<WDL>* wdl, TBTable<DTZ>* dtz) {
395         Entry* entry = &hashTable[(uint32_t)key & (Size - 1)];
396
397         // Ensure last element is empty to avoid overflow when looking up
398         for ( ; entry - hashTable < Size - 1; ++entry)
399             if (std::get<KEY>(*entry) == key || !std::get<WDL>(*entry)) {
400                 *entry = std::make_tuple(key, wdl, dtz);
401                 return;
402             }
403         std::cerr << "TB hash table size too low!" << std::endl;
404         exit(1);
405     }
406
407 public:
408     template<TBType Type>
409     TBTable<Type>* get(Key key) {
410         for (const Entry* entry = &hashTable[(uint32_t)key & (Size - 1)]; ; ++entry) {
411             if (std::get<KEY>(*entry) == key || !std::get<Type>(*entry))
412                 return std::get<Type>(*entry);
413         }
414     }
415
416     void clear() {
417         memset(hashTable, 0, sizeof(hashTable));
418         wdlTable.clear();
419         dtzTable.clear();
420     }
421     size_t size() const { return wdlTable.size(); }
422     void add(const std::vector<PieceType>& pieces);
423 };
424
425 TBTables TBTables;
426
427 // If the corresponding file exists two new objects TBTable<WDL> and TBTable<DTZ>
428 // are created and added to the lists and hash table. Called at init time.
429 void TBTables::add(const std::vector<PieceType>& pieces) {
430
431     std::string code;
432
433     for (PieceType pt : pieces)
434         code += PieceToChar[pt];
435
436     TBFile file(code.insert(code.find('K', 1), "v") + ".rtbw"); // KRK -> KRvK
437
438     if (!file.is_open()) // Only WDL file is checked
439         return;
440
441     file.close();
442
443     MaxCardinality = std::max((int)pieces.size(), MaxCardinality);
444
445     wdlTable.emplace_back(code);
446     dtzTable.emplace_back(wdlTable.back());
447
448     // Insert into the hash keys for both colors: KRvK with KR white and black
449     insert(wdlTable.back().key , &wdlTable.back(), &dtzTable.back());
450     insert(wdlTable.back().key2, &wdlTable.back(), &dtzTable.back());
451 }
452
453 // TB tables are compressed with canonical Huffman code. The compressed data is divided into
454 // blocks of size d->sizeofBlock, and each block stores a variable number of symbols.
455 // Each symbol represents either a WDL or a (remapped) DTZ value, or a pair of other symbols
456 // (recursively). If you keep expanding the symbols in a block, you end up with up to 65536
457 // WDL or DTZ values. Each symbol represents up to 256 values and will correspond after
458 // Huffman coding to at least 1 bit. So a block of 32 bytes corresponds to at most
459 // 32 x 8 x 256 = 65536 values. This maximum is only reached for tables that consist mostly
460 // of draws or mostly of wins, but such tables are actually quite common. In principle, the
461 // blocks in WDL tables are 64 bytes long (and will be aligned on cache lines). But for
462 // mostly-draw or mostly-win tables this can leave many 64-byte blocks only half-filled, so
463 // in such cases blocks are 32 bytes long. The blocks of DTZ tables are up to 1024 bytes long.
464 // The generator picks the size that leads to the smallest table. The "book" of symbols and
465 // Huffman codes is the same for all blocks in the table. A non-symmetric pawnless TB file
466 // will have one table for wtm and one for btm, a TB file with pawns will have tables per
467 // file a,b,c,d also in this case one set for wtm and one for btm.
468 int decompress_pairs(PairsData* d, uint64_t idx) {
469
470     // Special case where all table positions store the same value
471     if (d->flags & TBFlag::SingleValue)
472         return d->minSymLen;
473
474     // First we need to locate the right block that stores the value at index "idx".
475     // Because each block n stores blockLength[n] + 1 values, the index i of the block
476     // that contains the value at position idx is:
477     //
478     //                    for (i = -1, sum = 0; sum <= idx; i++)
479     //                        sum += blockLength[i + 1] + 1;
480     //
481     // This can be slow, so we use SparseIndex[] populated with a set of SparseEntry that
482     // point to known indices into blockLength[]. Namely SparseIndex[k] is a SparseEntry
483     // that stores the blockLength[] index and the offset within that block of the value
484     // with index I(k), where:
485     //
486     //       I(k) = k * d->span + d->span / 2      (1)
487
488     // First step is to get the 'k' of the I(k) nearest to our idx, using definition (1)
489     uint32_t k = idx / d->span;
490
491     // Then we read the corresponding SparseIndex[] entry
492     uint32_t block = number<uint32_t, LittleEndian>(&d->sparseIndex[k].block);
493     int offset     = number<uint16_t, LittleEndian>(&d->sparseIndex[k].offset);
494
495     // Now compute the difference idx - I(k). From definition of k we know that
496     //
497     //       idx = k * d->span + idx % d->span    (2)
498     //
499     // So from (1) and (2) we can compute idx - I(K):
500     int diff = idx % d->span - d->span / 2;
501
502     // Sum the above to offset to find the offset corresponding to our idx
503     offset += diff;
504
505     // Move to previous/next block, until we reach the correct block that contains idx,
506     // that is when 0 <= offset <= d->blockLength[block]
507     while (offset < 0)
508         offset += d->blockLength[--block] + 1;
509
510     while (offset > d->blockLength[block])
511         offset -= d->blockLength[block++] + 1;
512
513     // Finally, we find the start address of our block of canonical Huffman symbols
514     uint32_t* ptr = (uint32_t*)(d->data + ((uint64_t)block * d->sizeofBlock));
515
516     // Read the first 64 bits in our block, this is a (truncated) sequence of
517     // unknown number of symbols of unknown length but we know the first one
518     // is at the beginning of this 64 bits sequence.
519     uint64_t buf64 = number<uint64_t, BigEndian>(ptr); ptr += 2;
520     int buf64Size = 64;
521     Sym sym;
522
523     while (true) {
524         int len = 0; // This is the symbol length - d->min_sym_len
525
526         // Now get the symbol length. For any symbol s64 of length l right-padded
527         // to 64 bits we know that d->base64[l-1] >= s64 >= d->base64[l] so we
528         // can find the symbol length iterating through base64[].
529         while (buf64 < d->base64[len])
530             ++len;
531
532         // All the symbols of a given length are consecutive integers (numerical
533         // sequence property), so we can compute the offset of our symbol of
534         // length len, stored at the beginning of buf64.
535         sym = (buf64 - d->base64[len]) >> (64 - len - d->minSymLen);
536
537         // Now add the value of the lowest symbol of length len to get our symbol
538         sym += number<Sym, LittleEndian>(&d->lowestSym[len]);
539
540         // If our offset is within the number of values represented by symbol sym
541         // we are done...
542         if (offset < d->symlen[sym] + 1)
543             break;
544
545         // ...otherwise update the offset and continue to iterate
546         offset -= d->symlen[sym] + 1;
547         len += d->minSymLen; // Get the real length
548         buf64 <<= len;       // Consume the just processed symbol
549         buf64Size -= len;
550
551         if (buf64Size <= 32) { // Refill the buffer
552             buf64Size += 32;
553             buf64 |= (uint64_t)number<uint32_t, BigEndian>(ptr++) << (64 - buf64Size);
554         }
555     }
556
557     // Ok, now we have our symbol that expands into d->symlen[sym] + 1 symbols.
558     // We binary-search for our value recursively expanding into the left and
559     // right child symbols until we reach a leaf node where symlen[sym] + 1 == 1
560     // that will store the value we need.
561     while (d->symlen[sym]) {
562
563         Sym left = d->btree[sym].get<LR::Left>();
564
565         // If a symbol contains 36 sub-symbols (d->symlen[sym] + 1 = 36) and
566         // expands in a pair (d->symlen[left] = 23, d->symlen[right] = 11), then
567         // we know that, for instance the ten-th value (offset = 10) will be on
568         // the left side because in Recursive Pairing child symbols are adjacent.
569         if (offset < d->symlen[left] + 1)
570             sym = left;
571         else {
572             offset -= d->symlen[left] + 1;
573             sym = d->btree[sym].get<LR::Right>();
574         }
575     }
576
577     return d->btree[sym].get<LR::Left>();
578 }
579
580 bool check_dtz_stm(TBTable<WDL>*, int, File) { return true; }
581
582 bool check_dtz_stm(TBTable<DTZ>* entry, int stm, File f) {
583
584     auto flags = entry->get(stm, f)->flags;
585     return   (flags & TBFlag::STM) == stm
586           || ((entry->key == entry->key2) && !entry->hasPawns);
587 }
588
589 // DTZ scores are sorted by frequency of occurrence and then assigned the
590 // values 0, 1, 2, ... in order of decreasing frequency. This is done for each
591 // of the four WDLScore values. The mapping information necessary to reconstruct
592 // the original values is stored in the TB file and read during map[] init.
593 WDLScore map_score(TBTable<WDL>*, File, int value, WDLScore) { return WDLScore(value - 2); }
594
595 int map_score(TBTable<DTZ>* entry, File f, int value, WDLScore wdl) {
596
597     constexpr int WDLMap[] = { 1, 3, 0, 2, 0 };
598
599     auto flags = entry->get(0, f)->flags;
600
601     uint8_t* map = entry->map;
602     uint16_t* idx = entry->get(0, f)->map_idx;
603     if (flags & TBFlag::Mapped) {
604         if (flags & TBFlag::Wide)
605             value = ((uint16_t *)map)[idx[WDLMap[wdl + 2]] + value];
606         else
607             value = map[idx[WDLMap[wdl + 2]] + value];
608     }
609
610     // DTZ tables store distance to zero in number of moves or plies. We
611     // want to return plies, so we have convert to plies when needed.
612     if (   (wdl == WDLWin  && !(flags & TBFlag::WinPlies))
613         || (wdl == WDLLoss && !(flags & TBFlag::LossPlies))
614         ||  wdl == WDLCursedWin
615         ||  wdl == WDLBlessedLoss)
616         value *= 2;
617
618     return value + 1;
619 }
620
621 // Compute a unique index out of a position and use it to probe the TB file. To
622 // encode k pieces of same type and color, first sort the pieces by square in
623 // ascending order s1 <= s2 <= ... <= sk then compute the unique index as:
624 //
625 //      idx = Binomial[1][s1] + Binomial[2][s2] + ... + Binomial[k][sk]
626 //
627 template<typename T, typename Ret = typename T::Ret>
628 Ret do_probe_table(const Position& pos, T* entry, WDLScore wdl, ProbeState* result) {
629
630     Square squares[TBPIECES];
631     Piece pieces[TBPIECES];
632     uint64_t idx;
633     int next = 0, size = 0, leadPawnsCnt = 0;
634     PairsData* d;
635     Bitboard b, leadPawns = 0;
636     File tbFile = FILE_A;
637
638     // A given TB entry like KRK has associated two material keys: KRvk and Kvkr.
639     // If both sides have the same pieces keys are equal. In this case TB tables
640     // only store the 'white to move' case, so if the position to lookup has black
641     // to move, we need to switch the color and flip the squares before to lookup.
642     bool symmetricBlackToMove = (entry->key == entry->key2 && pos.side_to_move());
643
644     // TB files are calculated for white as stronger side. For instance we have
645     // KRvK, not KvKR. A position where stronger side is white will have its
646     // material key == entry->key, otherwise we have to switch the color and
647     // flip the squares before to lookup.
648     bool blackStronger = (pos.material_key() != entry->key);
649
650     int flipColor   = (symmetricBlackToMove || blackStronger) * 8;
651     int flipSquares = (symmetricBlackToMove || blackStronger) * 070;
652     int stm         = (symmetricBlackToMove || blackStronger) ^ pos.side_to_move();
653
654     // For pawns, TB files store 4 separate tables according if leading pawn is on
655     // file a, b, c or d after reordering. The leading pawn is the one with maximum
656     // MapPawns[] value, that is the one most toward the edges and with lowest rank.
657     if (entry->hasPawns) {
658
659         // In all the 4 tables, pawns are at the beginning of the piece sequence and
660         // their color is the reference one. So we just pick the first one.
661         Piece pc = Piece(entry->get(0, 0)->pieces[0] ^ flipColor);
662
663         assert(type_of(pc) == PAWN);
664
665         leadPawns = b = pos.pieces(color_of(pc), PAWN);
666         do
667             squares[size++] = pop_lsb(&b) ^ flipSquares;
668         while (b);
669
670         leadPawnsCnt = size;
671
672         std::swap(squares[0], *std::max_element(squares, squares + leadPawnsCnt, pawns_comp));
673
674         tbFile = file_of(squares[0]);
675         if (tbFile > FILE_D)
676             tbFile = file_of(squares[0] ^ 7); // Horizontal flip: SQ_H1 -> SQ_A1
677     }
678
679     // DTZ tables are one-sided, i.e. they store positions only for white to
680     // move or only for black to move, so check for side to move to be stm,
681     // early exit otherwise.
682     if (!check_dtz_stm(entry, stm, tbFile))
683         return *result = CHANGE_STM, Ret();
684
685     // Now we are ready to get all the position pieces (but the lead pawns) and
686     // directly map them to the correct color and square.
687     b = pos.pieces() ^ leadPawns;
688     do {
689         Square s = pop_lsb(&b);
690         squares[size] = s ^ flipSquares;
691         pieces[size++] = Piece(pos.piece_on(s) ^ flipColor);
692     } while (b);
693
694     assert(size >= 2);
695
696     d = entry->get(stm, tbFile);
697
698     // Then we reorder the pieces to have the same sequence as the one stored
699     // in pieces[i]: the sequence that ensures the best compression.
700     for (int i = leadPawnsCnt; i < size; ++i)
701         for (int j = i; j < size; ++j)
702             if (d->pieces[i] == pieces[j])
703             {
704                 std::swap(pieces[i], pieces[j]);
705                 std::swap(squares[i], squares[j]);
706                 break;
707             }
708
709     // Now we map again the squares so that the square of the lead piece is in
710     // the triangle A1-D1-D4.
711     if (file_of(squares[0]) > FILE_D)
712         for (int i = 0; i < size; ++i)
713             squares[i] ^= 7; // Horizontal flip: SQ_H1 -> SQ_A1
714
715     // Encode leading pawns starting with the one with minimum MapPawns[] and
716     // proceeding in ascending order.
717     if (entry->hasPawns) {
718         idx = LeadPawnIdx[leadPawnsCnt][squares[0]];
719
720         std::sort(squares + 1, squares + leadPawnsCnt, pawns_comp);
721
722         for (int i = 1; i < leadPawnsCnt; ++i)
723             idx += Binomial[i][MapPawns[squares[i]]];
724
725         goto encode_remaining; // With pawns we have finished special treatments
726     }
727
728     // In positions withouth pawns, we further flip the squares to ensure leading
729     // piece is below RANK_5.
730     if (rank_of(squares[0]) > RANK_4)
731         for (int i = 0; i < size; ++i)
732             squares[i] ^= 070; // Vertical flip: SQ_A8 -> SQ_A1
733
734     // Look for the first piece of the leading group not on the A1-D4 diagonal
735     // and ensure it is mapped below the diagonal.
736     for (int i = 0; i < d->groupLen[0]; ++i) {
737         if (!off_A1H8(squares[i]))
738             continue;
739
740         if (off_A1H8(squares[i]) > 0) // A1-H8 diagonal flip: SQ_A3 -> SQ_C3
741             for (int j = i; j < size; ++j)
742                 squares[j] = Square(((squares[j] >> 3) | (squares[j] << 3)) & 63);
743         break;
744     }
745
746     // Encode the leading group.
747     //
748     // Suppose we have KRvK. Let's say the pieces are on square numbers wK, wR
749     // and bK (each 0...63). The simplest way to map this position to an index
750     // is like this:
751     //
752     //   index = wK * 64 * 64 + wR * 64 + bK;
753     //
754     // But this way the TB is going to have 64*64*64 = 262144 positions, with
755     // lots of positions being equivalent (because they are mirrors of each
756     // other) and lots of positions being invalid (two pieces on one square,
757     // adjacent kings, etc.).
758     // Usually the first step is to take the wK and bK together. There are just
759     // 462 ways legal and not-mirrored ways to place the wK and bK on the board.
760     // Once we have placed the wK and bK, there are 62 squares left for the wR
761     // Mapping its square from 0..63 to available squares 0..61 can be done like:
762     //
763     //   wR -= (wR > wK) + (wR > bK);
764     //
765     // In words: if wR "comes later" than wK, we deduct 1, and the same if wR
766     // "comes later" than bK. In case of two same pieces like KRRvK we want to
767     // place the two Rs "together". If we have 62 squares left, we can place two
768     // Rs "together" in 62 * 61 / 2 ways (we divide by 2 because rooks can be
769     // swapped and still get the same position.)
770     //
771     // In case we have at least 3 unique pieces (inlcuded kings) we encode them
772     // together.
773     if (entry->hasUniquePieces) {
774
775         int adjust1 =  squares[1] > squares[0];
776         int adjust2 = (squares[2] > squares[0]) + (squares[2] > squares[1]);
777
778         // First piece is below a1-h8 diagonal. MapA1D1D4[] maps the b1-d1-d3
779         // triangle to 0...5. There are 63 squares for second piece and and 62
780         // (mapped to 0...61) for the third.
781         if (off_A1H8(squares[0]))
782             idx = (   MapA1D1D4[squares[0]]  * 63
783                    + (squares[1] - adjust1)) * 62
784                    +  squares[2] - adjust2;
785
786         // First piece is on a1-h8 diagonal, second below: map this occurence to
787         // 6 to differentiate from the above case, rank_of() maps a1-d4 diagonal
788         // to 0...3 and finally MapB1H1H7[] maps the b1-h1-h7 triangle to 0..27.
789         else if (off_A1H8(squares[1]))
790             idx = (  6 * 63 + rank_of(squares[0]) * 28
791                    + MapB1H1H7[squares[1]])       * 62
792                    + squares[2] - adjust2;
793
794         // First two pieces are on a1-h8 diagonal, third below
795         else if (off_A1H8(squares[2]))
796             idx =  6 * 63 * 62 + 4 * 28 * 62
797                  +  rank_of(squares[0])        * 7 * 28
798                  + (rank_of(squares[1]) - adjust1) * 28
799                  +  MapB1H1H7[squares[2]];
800
801         // All 3 pieces on the diagonal a1-h8
802         else
803             idx = 6 * 63 * 62 + 4 * 28 * 62 + 4 * 7 * 28
804                  +  rank_of(squares[0])         * 7 * 6
805                  + (rank_of(squares[1]) - adjust1)  * 6
806                  + (rank_of(squares[2]) - adjust2);
807     } else
808         // We don't have at least 3 unique pieces, like in KRRvKBB, just map
809         // the kings.
810         idx = MapKK[MapA1D1D4[squares[0]]][squares[1]];
811
812 encode_remaining:
813     idx *= d->groupIdx[0];
814     Square* groupSq = squares + d->groupLen[0];
815
816     // Encode remainig pawns then pieces according to square, in ascending order
817     bool remainingPawns = entry->hasPawns && entry->pawnCount[1];
818
819     while (d->groupLen[++next])
820     {
821         std::sort(groupSq, groupSq + d->groupLen[next]);
822         uint64_t n = 0;
823
824         // Map down a square if "comes later" than a square in the previous
825         // groups (similar to what done earlier for leading group pieces).
826         for (int i = 0; i < d->groupLen[next]; ++i)
827         {
828             auto f = [&](Square s) { return groupSq[i] > s; };
829             auto adjust = std::count_if(squares, groupSq, f);
830             n += Binomial[i + 1][groupSq[i] - adjust - 8 * remainingPawns];
831         }
832
833         remainingPawns = false;
834         idx += n * d->groupIdx[next];
835         groupSq += d->groupLen[next];
836     }
837
838     // Now that we have the index, decompress the pair and get the score
839     return map_score(entry, tbFile, decompress_pairs(d, idx), wdl);
840 }
841
842 // Group together pieces that will be encoded together. The general rule is that
843 // a group contains pieces of same type and color. The exception is the leading
844 // group that, in case of positions withouth pawns, can be formed by 3 different
845 // pieces (default) or by the king pair when there is not a unique piece apart
846 // from the kings. When there are pawns, pawns are always first in pieces[].
847 //
848 // As example KRKN -> KRK + N, KNNK -> KK + NN, KPPKP -> P + PP + K + K
849 //
850 // The actual grouping depends on the TB generator and can be inferred from the
851 // sequence of pieces in piece[] array.
852 template<typename T>
853 void set_groups(T& e, PairsData* d, int order[], File f) {
854
855     int n = 0, firstLen = e.hasPawns ? 0 : e.hasUniquePieces ? 3 : 2;
856     d->groupLen[n] = 1;
857
858     // Number of pieces per group is stored in groupLen[], for instance in KRKN
859     // the encoder will default on '111', so groupLen[] will be (3, 1).
860     for (int i = 1; i < e.pieceCount; ++i)
861         if (--firstLen > 0 || d->pieces[i] == d->pieces[i - 1])
862             d->groupLen[n]++;
863         else
864             d->groupLen[++n] = 1;
865
866     d->groupLen[++n] = 0; // Zero-terminated
867
868     // The sequence in pieces[] defines the groups, but not the order in which
869     // they are encoded. If the pieces in a group g can be combined on the board
870     // in N(g) different ways, then the position encoding will be of the form:
871     //
872     //           g1 * N(g2) * N(g3) + g2 * N(g3) + g3
873     //
874     // This ensures unique encoding for the whole position. The order of the
875     // groups is a per-table parameter and could not follow the canonical leading
876     // pawns/pieces -> remainig pawns -> remaining pieces. In particular the
877     // first group is at order[0] position and the remaining pawns, when present,
878     // are at order[1] position.
879     bool pp = e.hasPawns && e.pawnCount[1]; // Pawns on both sides
880     int next = pp ? 2 : 1;
881     int freeSquares = 64 - d->groupLen[0] - (pp ? d->groupLen[1] : 0);
882     uint64_t idx = 1;
883
884     for (int k = 0; next < n || k == order[0] || k == order[1]; ++k)
885         if (k == order[0]) // Leading pawns or pieces
886         {
887             d->groupIdx[0] = idx;
888             idx *=         e.hasPawns ? LeadPawnsSize[d->groupLen[0]][f]
889                   : e.hasUniquePieces ? 31332 : 462;
890         }
891         else if (k == order[1]) // Remaining pawns
892         {
893             d->groupIdx[1] = idx;
894             idx *= Binomial[d->groupLen[1]][48 - d->groupLen[0]];
895         }
896         else // Remainig pieces
897         {
898             d->groupIdx[next] = idx;
899             idx *= Binomial[d->groupLen[next]][freeSquares];
900             freeSquares -= d->groupLen[next++];
901         }
902
903     d->groupIdx[n] = idx;
904 }
905
906 // In Recursive Pairing each symbol represents a pair of childern symbols. So
907 // read d->btree[] symbols data and expand each one in his left and right child
908 // symbol until reaching the leafs that represent the symbol value.
909 uint8_t set_symlen(PairsData* d, Sym s, std::vector<bool>& visited) {
910
911     visited[s] = true; // We can set it now because tree is acyclic
912     Sym sr = d->btree[s].get<LR::Right>();
913
914     if (sr == 0xFFF)
915         return 0;
916
917     Sym sl = d->btree[s].get<LR::Left>();
918
919     if (!visited[sl])
920         d->symlen[sl] = set_symlen(d, sl, visited);
921
922     if (!visited[sr])
923         d->symlen[sr] = set_symlen(d, sr, visited);
924
925     return d->symlen[sl] + d->symlen[sr] + 1;
926 }
927
928 uint8_t* set_sizes(PairsData* d, uint8_t* data) {
929
930     d->flags = *data++;
931
932     if (d->flags & TBFlag::SingleValue) {
933         d->blocksNum = d->blockLengthSize = 0;
934         d->span = d->sparseIndexSize = 0; // Broken MSVC zero-init
935         d->minSymLen = *data++; // Here we store the single value
936         return data;
937     }
938
939     // groupLen[] is a zero-terminated list of group lengths, the last groupIdx[]
940     // element stores the biggest index that is the tb size.
941     uint64_t tbSize = d->groupIdx[std::find(d->groupLen, d->groupLen + 7, 0) - d->groupLen];
942
943     d->sizeofBlock = 1ULL << *data++;
944     d->span = 1ULL << *data++;
945     d->sparseIndexSize = (tbSize + d->span - 1) / d->span; // Round up
946     auto padding = number<uint8_t, LittleEndian>(data++);
947     d->blocksNum = number<uint32_t, LittleEndian>(data); data += sizeof(uint32_t);
948     d->blockLengthSize = d->blocksNum + padding; // Padded to ensure SparseIndex[]
949                                                  // does not point out of range.
950     d->maxSymLen = *data++;
951     d->minSymLen = *data++;
952     d->lowestSym = (Sym*)data;
953     d->base64.resize(d->maxSymLen - d->minSymLen + 1);
954
955     // The canonical code is ordered such that longer symbols (in terms of
956     // the number of bits of their Huffman code) have lower numeric value,
957     // so that d->lowestSym[i] >= d->lowestSym[i+1] (when read as LittleEndian).
958     // Starting from this we compute a base64[] table indexed by symbol length
959     // and containing 64 bit values so that d->base64[i] >= d->base64[i+1].
960     // See http://www.eecs.harvard.edu/~michaelm/E210/huffman.pdf
961     for (int i = d->base64.size() - 2; i >= 0; --i) {
962         d->base64[i] = (d->base64[i + 1] + number<Sym, LittleEndian>(&d->lowestSym[i])
963                                          - number<Sym, LittleEndian>(&d->lowestSym[i + 1])) / 2;
964
965         assert(d->base64[i] * 2 >= d->base64[i+1]);
966     }
967
968     // Now left-shift by an amount so that d->base64[i] gets shifted 1 bit more
969     // than d->base64[i+1] and given the above assert condition, we ensure that
970     // d->base64[i] >= d->base64[i+1]. Moreover for any symbol s64 of length i
971     // and right-padded to 64 bits holds d->base64[i-1] >= s64 >= d->base64[i].
972     for (size_t i = 0; i < d->base64.size(); ++i)
973         d->base64[i] <<= 64 - i - d->minSymLen; // Right-padding to 64 bits
974
975     data += d->base64.size() * sizeof(Sym);
976     d->symlen.resize(number<uint16_t, LittleEndian>(data)); data += sizeof(uint16_t);
977     d->btree = (LR*)data;
978
979     // The compression scheme used is "Recursive Pairing", that replaces the most
980     // frequent adjacent pair of symbols in the source message by a new symbol,
981     // reevaluating the frequencies of all of the symbol pairs with respect to
982     // the extended alphabet, and then repeating the process.
983     // See http://www.larsson.dogma.net/dcc99.pdf
984     std::vector<bool> visited(d->symlen.size());
985
986     for (Sym sym = 0; sym < d->symlen.size(); ++sym)
987         if (!visited[sym])
988             d->symlen[sym] = set_symlen(d, sym, visited);
989
990     return data + d->symlen.size() * sizeof(LR) + (d->symlen.size() & 1);
991 }
992
993 uint8_t* set_dtz_map(TBTable<WDL>&, uint8_t* data, File) { return data; }
994
995 uint8_t* set_dtz_map(TBTable<DTZ>& e, uint8_t* data, File maxFile) {
996
997     e.map = data;
998
999     for (File f = FILE_A; f <= maxFile; ++f) {
1000         auto flags = e.get(0, f)->flags;
1001         if (flags & TBFlag::Mapped) {
1002             if (flags & TBFlag::Wide) {
1003                 data += (uintptr_t)data & 1;  // Word alignment, we may have a mixed table
1004                 for (int i = 0; i < 4; ++i) { // Sequence like 3,x,x,x,1,x,0,2,x,x
1005                     e.get(0, f)->map_idx[i] = (uint16_t)((uint16_t *)data - (uint16_t *)e.map + 1);
1006                     data += 2 * number<uint16_t, LittleEndian>(data) + 2;
1007                 }
1008             }
1009             else {
1010                 for (int i = 0; i < 4; ++i) {
1011                     e.get(0, f)->map_idx[i] = (uint16_t)(data - e.map + 1);
1012                     data += *data + 1;
1013                 }
1014             }
1015         }
1016     }
1017
1018     return data += (uintptr_t)data & 1; // Word alignment
1019 }
1020
1021 // Populate entry's PairsData records with data from the just memory mapped file.
1022 // Called at first access.
1023 template<typename T>
1024 void set(T& e, uint8_t* data) {
1025
1026     PairsData* d;
1027
1028     enum { Split = 1, HasPawns = 2 };
1029
1030     assert(e.hasPawns        == !!(*data & HasPawns));
1031     assert((e.key != e.key2) == !!(*data & Split));
1032
1033     data++; // First byte stores flags
1034
1035     const int sides = T::Sides == 2 && (e.key != e.key2) ? 2 : 1;
1036     const File maxFile = e.hasPawns ? FILE_D : FILE_A;
1037
1038     bool pp = e.hasPawns && e.pawnCount[1]; // Pawns on both sides
1039
1040     assert(!pp || e.pawnCount[0]);
1041
1042     for (File f = FILE_A; f <= maxFile; ++f) {
1043
1044         for (int i = 0; i < sides; i++)
1045             *e.get(i, f) = PairsData();
1046
1047         int order[][2] = { { *data & 0xF, pp ? *(data + 1) & 0xF : 0xF },
1048                            { *data >>  4, pp ? *(data + 1) >>  4 : 0xF } };
1049         data += 1 + pp;
1050
1051         for (int k = 0; k < e.pieceCount; ++k, ++data)
1052             for (int i = 0; i < sides; i++)
1053                 e.get(i, f)->pieces[k] = Piece(i ? *data >>  4 : *data & 0xF);
1054
1055         for (int i = 0; i < sides; ++i)
1056             set_groups(e, e.get(i, f), order[i], f);
1057     }
1058
1059     data += (uintptr_t)data & 1; // Word alignment
1060
1061     for (File f = FILE_A; f <= maxFile; ++f)
1062         for (int i = 0; i < sides; i++)
1063             data = set_sizes(e.get(i, f), data);
1064
1065     data = set_dtz_map(e, data, maxFile);
1066
1067     for (File f = FILE_A; f <= maxFile; ++f)
1068         for (int i = 0; i < sides; i++) {
1069             (d = e.get(i, f))->sparseIndex = (SparseEntry*)data;
1070             data += d->sparseIndexSize * sizeof(SparseEntry);
1071         }
1072
1073     for (File f = FILE_A; f <= maxFile; ++f)
1074         for (int i = 0; i < sides; i++) {
1075             (d = e.get(i, f))->blockLength = (uint16_t*)data;
1076             data += d->blockLengthSize * sizeof(uint16_t);
1077         }
1078
1079     for (File f = FILE_A; f <= maxFile; ++f)
1080         for (int i = 0; i < sides; i++) {
1081             data = (uint8_t*)(((uintptr_t)data + 0x3F) & ~0x3F); // 64 byte alignment
1082             (d = e.get(i, f))->data = data;
1083             data += d->blocksNum * d->sizeofBlock;
1084         }
1085 }
1086
1087 // If the TB file corresponding to the given position is already memory mapped
1088 // then return its base address, otherwise try to memory map and init it. Called
1089 // at every probe, memory map and init only at first access. Function is thread
1090 // safe and can be called concurrently.
1091 template<TBType Type>
1092 void* mapped(TBTable<Type>& e, const Position& pos) {
1093
1094     static Mutex mutex;
1095
1096     // Use 'aquire' to avoid a thread reads 'ready' == true while another is
1097     // still working, this could happen due to compiler reordering.
1098     if (e.ready.load(std::memory_order_acquire))
1099         return e.baseAddress; // Could be nullptr if file does not exsist
1100
1101     std::unique_lock<Mutex> lk(mutex);
1102
1103     if (e.ready.load(std::memory_order_relaxed)) // Recheck under lock
1104         return e.baseAddress;
1105
1106     // Pieces strings in decreasing order for each color, like ("KPP","KR")
1107     std::string fname, w, b;
1108     for (PieceType pt = KING; pt >= PAWN; --pt) {
1109         w += std::string(popcount(pos.pieces(WHITE, pt)), PieceToChar[pt]);
1110         b += std::string(popcount(pos.pieces(BLACK, pt)), PieceToChar[pt]);
1111     }
1112
1113     fname =  (e.key == pos.material_key() ? w + 'v' + b : b + 'v' + w)
1114            + (Type == WDL ? ".rtbw" : ".rtbz");
1115
1116     uint8_t* data = TBFile(fname).map(&e.baseAddress, &e.mapping, Type);
1117
1118     if (data)
1119         set(e, data);
1120
1121     e.ready.store(true, std::memory_order_release);
1122     return e.baseAddress;
1123 }
1124
1125 template<TBType Type, typename Ret = typename TBTable<Type>::Ret>
1126 Ret probe_table(const Position& pos, ProbeState* result, WDLScore wdl = WDLDraw) {
1127
1128     if (pos.count<ALL_PIECES>() == 2) // KvK
1129         return Ret(WDLDraw);
1130
1131     TBTable<Type>* entry = TBTables.get<Type>(pos.material_key());
1132
1133     if (!entry || !mapped(*entry, pos))
1134         return *result = FAIL, Ret();
1135
1136     return do_probe_table(pos, entry, wdl, result);
1137 }
1138
1139 // For a position where the side to move has a winning capture it is not necessary
1140 // to store a winning value so the generator treats such positions as "don't cares"
1141 // and tries to assign to it a value that improves the compression ratio. Similarly,
1142 // if the side to move has a drawing capture, then the position is at least drawn.
1143 // If the position is won, then the TB needs to store a win value. But if the
1144 // position is drawn, the TB may store a loss value if that is better for compression.
1145 // All of this means that during probing, the engine must look at captures and probe
1146 // their results and must probe the position itself. The "best" result of these
1147 // probes is the correct result for the position.
1148 // DTZ tables do not store values when a following move is a zeroing winning move
1149 // (winning capture or winning pawn move). Also DTZ store wrong values for positions
1150 // where the best move is an ep-move (even if losing). So in all these cases set
1151 // the state to ZEROING_BEST_MOVE.
1152 template<bool CheckZeroingMoves>
1153 WDLScore search(Position& pos, ProbeState* result) {
1154
1155     WDLScore value, bestValue = WDLLoss;
1156     StateInfo st;
1157
1158     auto moveList = MoveList<LEGAL>(pos);
1159     size_t totalCount = moveList.size(), moveCount = 0;
1160
1161     for (const Move& move : moveList)
1162     {
1163         if (   !pos.capture(move)
1164             && (!CheckZeroingMoves || type_of(pos.moved_piece(move)) != PAWN))
1165             continue;
1166
1167         moveCount++;
1168
1169         pos.do_move(move, st);
1170         value = -search<false>(pos, result);
1171         pos.undo_move(move);
1172
1173         if (*result == FAIL)
1174             return WDLDraw;
1175
1176         if (value > bestValue)
1177         {
1178             bestValue = value;
1179
1180             if (value >= WDLWin)
1181             {
1182                 *result = ZEROING_BEST_MOVE; // Winning DTZ-zeroing move
1183                 return value;
1184             }
1185         }
1186     }
1187
1188     // In case we have already searched all the legal moves we don't have to probe
1189     // the TB because the stored score could be wrong. For instance TB tables
1190     // do not contain information on position with ep rights, so in this case
1191     // the result of probe_wdl_table is wrong. Also in case of only capture
1192     // moves, for instance here 4K3/4q3/6p1/2k5/6p1/8/8/8 w - - 0 7, we have to
1193     // return with ZEROING_BEST_MOVE set.
1194     bool noMoreMoves = (moveCount && moveCount == totalCount);
1195
1196     if (noMoreMoves)
1197         value = bestValue;
1198     else
1199     {
1200         value = probe_table<WDL>(pos, result);
1201
1202         if (*result == FAIL)
1203             return WDLDraw;
1204     }
1205
1206     // DTZ stores a "don't care" value if bestValue is a win
1207     if (bestValue >= value)
1208         return *result = (   bestValue > WDLDraw
1209                           || noMoreMoves ? ZEROING_BEST_MOVE : OK), bestValue;
1210
1211     return *result = OK, value;
1212 }
1213
1214 } // namespace
1215
1216
1217 /// Tablebases::init() is called at startup and after every change to
1218 /// "SyzygyPath" UCI option to (re)create the various tables. It is not thread
1219 /// safe, nor it needs to be.
1220 void Tablebases::init(const std::string& paths) {
1221
1222     TBTables.clear();
1223     MaxCardinality = 0;
1224     TBFile::Paths = paths;
1225
1226     if (paths.empty() || paths == "<empty>")
1227         return;
1228
1229     // MapB1H1H7[] encodes a square below a1-h8 diagonal to 0..27
1230     int code = 0;
1231     for (Square s = SQ_A1; s <= SQ_H8; ++s)
1232         if (off_A1H8(s) < 0)
1233             MapB1H1H7[s] = code++;
1234
1235     // MapA1D1D4[] encodes a square in the a1-d1-d4 triangle to 0..9
1236     std::vector<Square> diagonal;
1237     code = 0;
1238     for (Square s = SQ_A1; s <= SQ_D4; ++s)
1239         if (off_A1H8(s) < 0 && file_of(s) <= FILE_D)
1240             MapA1D1D4[s] = code++;
1241
1242         else if (!off_A1H8(s) && file_of(s) <= FILE_D)
1243             diagonal.push_back(s);
1244
1245     // Diagonal squares are encoded as last ones
1246     for (auto s : diagonal)
1247         MapA1D1D4[s] = code++;
1248
1249     // MapKK[] encodes all the 461 possible legal positions of two kings where
1250     // the first is in the a1-d1-d4 triangle. If the first king is on the a1-d4
1251     // diagonal, the other one shall not to be above the a1-h8 diagonal.
1252     std::vector<std::pair<int, Square>> bothOnDiagonal;
1253     code = 0;
1254     for (int idx = 0; idx < 10; idx++)
1255         for (Square s1 = SQ_A1; s1 <= SQ_D4; ++s1)
1256             if (MapA1D1D4[s1] == idx && (idx || s1 == SQ_B1)) // SQ_B1 is mapped to 0
1257             {
1258                 for (Square s2 = SQ_A1; s2 <= SQ_H8; ++s2)
1259                     if ((PseudoAttacks[KING][s1] | s1) & s2)
1260                         continue; // Illegal position
1261
1262                     else if (!off_A1H8(s1) && off_A1H8(s2) > 0)
1263                         continue; // First on diagonal, second above
1264
1265                     else if (!off_A1H8(s1) && !off_A1H8(s2))
1266                         bothOnDiagonal.push_back(std::make_pair(idx, s2));
1267
1268                     else
1269                         MapKK[idx][s2] = code++;
1270             }
1271
1272     // Legal positions with both kings on diagonal are encoded as last ones
1273     for (auto p : bothOnDiagonal)
1274         MapKK[p.first][p.second] = code++;
1275
1276     // Binomial[] stores the Binomial Coefficents using Pascal rule. There
1277     // are Binomial[k][n] ways to choose k elements from a set of n elements.
1278     Binomial[0][0] = 1;
1279
1280     for (int n = 1; n < 64; n++) // Squares
1281         for (int k = 0; k < 6 && k <= n; ++k) // Pieces
1282             Binomial[k][n] =  (k > 0 ? Binomial[k - 1][n - 1] : 0)
1283                             + (k < n ? Binomial[k    ][n - 1] : 0);
1284
1285     // MapPawns[s] encodes squares a2-h7 to 0..47. This is the number of possible
1286     // available squares when the leading one is in 's'. Moreover the pawn with
1287     // highest MapPawns[] is the leading pawn, the one nearest the edge and,
1288     // among pawns with same file, the one with lowest rank.
1289     int availableSquares = 47; // Available squares when lead pawn is in a2
1290
1291     // Init the tables for the encoding of leading pawns group: with 7-men TB we
1292     // can have up to 5 leading pawns (KPPPPPK).
1293     for (int leadPawnsCnt = 1; leadPawnsCnt <= 5; ++leadPawnsCnt)
1294         for (File f = FILE_A; f <= FILE_D; ++f)
1295         {
1296             // Restart the index at every file because TB table is splitted
1297             // by file, so we can reuse the same index for different files.
1298             int idx = 0;
1299
1300             // Sum all possible combinations for a given file, starting with
1301             // the leading pawn on rank 2 and increasing the rank.
1302             for (Rank r = RANK_2; r <= RANK_7; ++r)
1303             {
1304                 Square sq = make_square(f, r);
1305
1306                 // Compute MapPawns[] at first pass.
1307                 // If sq is the leading pawn square, any other pawn cannot be
1308                 // below or more toward the edge of sq. There are 47 available
1309                 // squares when sq = a2 and reduced by 2 for any rank increase
1310                 // due to mirroring: sq == a3 -> no a2, h2, so MapPawns[a3] = 45
1311                 if (leadPawnsCnt == 1)
1312                 {
1313                     MapPawns[sq] = availableSquares--;
1314                     MapPawns[sq ^ 7] = availableSquares--; // Horizontal flip
1315                 }
1316                 LeadPawnIdx[leadPawnsCnt][sq] = idx;
1317                 idx += Binomial[leadPawnsCnt - 1][MapPawns[sq]];
1318             }
1319             // After a file is traversed, store the cumulated per-file index
1320             LeadPawnsSize[leadPawnsCnt][f] = idx;
1321         }
1322
1323     // Add entries in TB tables if the corresponding ".rtbw" file exsists
1324     for (PieceType p1 = PAWN; p1 < KING; ++p1) {
1325         TBTables.add({KING, p1, KING});
1326
1327         for (PieceType p2 = PAWN; p2 <= p1; ++p2) {
1328             TBTables.add({KING, p1, p2, KING});
1329             TBTables.add({KING, p1, KING, p2});
1330
1331             for (PieceType p3 = PAWN; p3 < KING; ++p3)
1332                 TBTables.add({KING, p1, p2, KING, p3});
1333
1334             for (PieceType p3 = PAWN; p3 <= p2; ++p3) {
1335                 TBTables.add({KING, p1, p2, p3, KING});
1336
1337                 for (PieceType p4 = PAWN; p4 <= p3; ++p4) {
1338                     TBTables.add({KING, p1, p2, p3, p4, KING});
1339
1340                     for (PieceType p5 = PAWN; p5 <= p4; ++p5)
1341                         TBTables.add({KING, p1, p2, p3, p4, p5, KING});
1342
1343                     for (PieceType p5 = PAWN; p5 < KING; ++p5)
1344                         TBTables.add({KING, p1, p2, p3, p4, KING, p5});
1345                 }
1346
1347                 for (PieceType p4 = PAWN; p4 < KING; ++p4) {
1348                     TBTables.add({KING, p1, p2, p3, KING, p4});
1349
1350                     for (PieceType p5 = PAWN; p5 <= p4; ++p5)
1351                         TBTables.add({KING, p1, p2, p3, KING, p4, p5});
1352                 }
1353             }
1354
1355             for (PieceType p3 = PAWN; p3 <= p1; ++p3)
1356                 for (PieceType p4 = PAWN; p4 <= (p1 == p3 ? p2 : p3); ++p4)
1357                     TBTables.add({KING, p1, p2, KING, p3, p4});
1358         }
1359     }
1360
1361     sync_cout << "info string Found " << TBTables.size() << " tablebases" << sync_endl;
1362 }
1363
1364 // Probe the WDL table for a particular position.
1365 // If *result != FAIL, the probe was successful.
1366 // The return value is from the point of view of the side to move:
1367 // -2 : loss
1368 // -1 : loss, but draw under 50-move rule
1369 //  0 : draw
1370 //  1 : win, but draw under 50-move rule
1371 //  2 : win
1372 WDLScore Tablebases::probe_wdl(Position& pos, ProbeState* result) {
1373
1374     *result = OK;
1375     return search<false>(pos, result);
1376 }
1377
1378 // Probe the DTZ table for a particular position.
1379 // If *result != FAIL, the probe was successful.
1380 // The return value is from the point of view of the side to move:
1381 //         n < -100 : loss, but draw under 50-move rule
1382 // -100 <= n < -1   : loss in n ply (assuming 50-move counter == 0)
1383 //        -1        : loss, the side to move is mated
1384 //         0        : draw
1385 //     1 < n <= 100 : win in n ply (assuming 50-move counter == 0)
1386 //   100 < n        : win, but draw under 50-move rule
1387 //
1388 // The return value n can be off by 1: a return value -n can mean a loss
1389 // in n+1 ply and a return value +n can mean a win in n+1 ply. This
1390 // cannot happen for tables with positions exactly on the "edge" of
1391 // the 50-move rule.
1392 //
1393 // This implies that if dtz > 0 is returned, the position is certainly
1394 // a win if dtz + 50-move-counter <= 99. Care must be taken that the engine
1395 // picks moves that preserve dtz + 50-move-counter <= 99.
1396 //
1397 // If n = 100 immediately after a capture or pawn move, then the position
1398 // is also certainly a win, and during the whole phase until the next
1399 // capture or pawn move, the inequality to be preserved is
1400 // dtz + 50-movecounter <= 100.
1401 //
1402 // In short, if a move is available resulting in dtz + 50-move-counter <= 99,
1403 // then do not accept moves leading to dtz + 50-move-counter == 100.
1404 int Tablebases::probe_dtz(Position& pos, ProbeState* result) {
1405
1406     *result = OK;
1407     WDLScore wdl = search<true>(pos, result);
1408
1409     if (*result == FAIL || wdl == WDLDraw) // DTZ tables don't store draws
1410         return 0;
1411
1412     // DTZ stores a 'don't care' value in this case, or even a plain wrong
1413     // one as in case the best move is a losing ep, so it cannot be probed.
1414     if (*result == ZEROING_BEST_MOVE)
1415         return dtz_before_zeroing(wdl);
1416
1417     int dtz = probe_table<DTZ>(pos, result, wdl);
1418
1419     if (*result == FAIL)
1420         return 0;
1421
1422     if (*result != CHANGE_STM)
1423         return (dtz + 100 * (wdl == WDLBlessedLoss || wdl == WDLCursedWin)) * sign_of(wdl);
1424
1425     // DTZ stores results for the other side, so we need to do a 1-ply search and
1426     // find the winning move that minimizes DTZ.
1427     StateInfo st;
1428     int minDTZ = 0xFFFF;
1429
1430     for (const Move& move : MoveList<LEGAL>(pos))
1431     {
1432         bool zeroing = pos.capture(move) || type_of(pos.moved_piece(move)) == PAWN;
1433
1434         pos.do_move(move, st);
1435
1436         // For zeroing moves we want the dtz of the move _before_ doing it,
1437         // otherwise we will get the dtz of the next move sequence. Search the
1438         // position after the move to get the score sign (because even in a
1439         // winning position we could make a losing capture or going for a draw).
1440         dtz = zeroing ? -dtz_before_zeroing(search<false>(pos, result))
1441                       : -probe_dtz(pos, result);
1442
1443         // If the move mates, force minDTZ to 1
1444         if (dtz == 1 && pos.checkers() && MoveList<LEGAL>(pos).size() == 0)
1445             minDTZ = 1;
1446
1447         // Convert result from 1-ply search. Zeroing moves are already accounted
1448         // by dtz_before_zeroing() that returns the DTZ of the previous move.
1449         if (!zeroing)
1450             dtz += sign_of(dtz);
1451
1452         // Skip the draws and if we are winning only pick positive dtz
1453         if (dtz < minDTZ && sign_of(dtz) == sign_of(wdl))
1454             minDTZ = dtz;
1455
1456         pos.undo_move(move);
1457
1458         if (*result == FAIL)
1459             return 0;
1460     }
1461
1462     // When there are no legal moves, the position is mate: we return -1
1463     return minDTZ == 0xFFFF ? -1 : minDTZ;
1464 }
1465
1466
1467 // Use the DTZ tables to rank root moves.
1468 //
1469 // A return value false indicates that not all probes were successful.
1470 bool Tablebases::root_probe(Position& pos, Search::RootMoves& rootMoves) {
1471
1472     ProbeState result;
1473     StateInfo st;
1474
1475     // Obtain 50-move counter for the root position
1476     int cnt50 = pos.rule50_count();
1477
1478     // Check whether a position was repeated since the last zeroing move.
1479     bool rep = pos.has_repeated();
1480
1481     int dtz, bound = Options["Syzygy50MoveRule"] ? 900 : 1;
1482
1483     // Probe and rank each move
1484     for (auto& m : rootMoves)
1485     {
1486         pos.do_move(m.pv[0], st);
1487
1488         // Calculate dtz for the current move counting from the root position
1489         if (pos.rule50_count() == 0)
1490         {
1491             // In case of a zeroing move, dtz is one of -101/-1/0/1/101
1492             WDLScore wdl = -probe_wdl(pos, &result);
1493             dtz = dtz_before_zeroing(wdl);
1494         }
1495         else
1496         {
1497             // Otherwise, take dtz for the new position and correct by 1 ply
1498             dtz = -probe_dtz(pos, &result);
1499             dtz =  dtz > 0 ? dtz + 1
1500                  : dtz < 0 ? dtz - 1 : dtz;
1501         }
1502
1503         // Make sure that a mating move is assigned a dtz value of 1
1504         if (   pos.checkers()
1505             && dtz == 2
1506             && MoveList<LEGAL>(pos).size() == 0)
1507             dtz = 1;
1508
1509         pos.undo_move(m.pv[0]);
1510
1511         if (result == FAIL)
1512             return false;
1513
1514         // Better moves are ranked higher. Certain wins are ranked equally.
1515         // Losing moves are ranked equally unless a 50-move draw is in sight.
1516         int r =  dtz > 0 ? (dtz + cnt50 <= 99 && !rep ? 1000 : 1000 - (dtz + cnt50))
1517                : dtz < 0 ? (-dtz * 2 + cnt50 < 100 ? -1000 : -1000 + (-dtz + cnt50))
1518                : 0;
1519         m.tbRank = r;
1520
1521         // Determine the score to be displayed for this move. Assign at least
1522         // 1 cp to cursed wins and let it grow to 49 cp as the positions gets
1523         // closer to a real win.
1524         m.tbScore =  r >= bound ? VALUE_MATE - MAX_PLY - 1
1525                    : r >  0     ? Value((std::max( 3, r - 800) * int(PawnValueEg)) / 200)
1526                    : r == 0     ? VALUE_DRAW
1527                    : r > -bound ? Value((std::min(-3, r + 800) * int(PawnValueEg)) / 200)
1528                    :             -VALUE_MATE + MAX_PLY + 1;
1529     }
1530
1531     return true;
1532 }
1533
1534
1535 // Use the WDL tables to rank root moves.
1536 // This is a fallback for the case that some or all DTZ tables are missing.
1537 //
1538 // A return value false indicates that not all probes were successful.
1539 bool Tablebases::root_probe_wdl(Position& pos, Search::RootMoves& rootMoves) {
1540
1541     static const int WDL_to_rank[] = { -1000, -899, 0, 899, 1000 };
1542
1543     ProbeState result;
1544     StateInfo st;
1545
1546     bool rule50 = Options["Syzygy50MoveRule"];
1547
1548     // Probe and rank each move
1549     for (auto& m : rootMoves)
1550     {
1551         pos.do_move(m.pv[0], st);
1552
1553         WDLScore wdl = -probe_wdl(pos, &result);
1554
1555         pos.undo_move(m.pv[0]);
1556
1557         if (result == FAIL)
1558             return false;
1559
1560         m.tbRank = WDL_to_rank[wdl + 2];
1561
1562         if (!rule50)
1563             wdl =  wdl > WDLDraw ? WDLWin
1564                  : wdl < WDLDraw ? WDLLoss : WDLDraw;
1565         m.tbScore = WDL_to_value[wdl + 2];
1566     }
1567
1568     return true;
1569 }