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