-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathBook.cpp
1575 lines (1350 loc) · 44.2 KB
/
Book.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright Chris Welty
// All Rights Reserved
// This file is distributed subject to GNU GPL version 2. See the files
// Copying.txt and GPL.txt for details.
#include "PreCompile.h"
#include "Book.h"
#include "Debug.h"
#include "options.h"
#include "QPosition.h"
#include "Player.h"
#include "Pos2.h"
#include "Games.h"
#include "GDK/OsObjects.h"
#include "Variation.h"
#include <boost/static_assert.hpp>
#include <algorithm>
#include <strstream>
#include <numeric>
#include <limits>
#include <stdio.h>
#include <string.h>
#include <time.h>
#include <errno.h>
bool fPrintCorrections=true;
namespace
{
//////////////////////////////////////////////
// Routines for picking move at random
//////////////////////////////////////////////
class CMVPS : public CMoveValue {
public:
int pass;
const CBookData* sbd;
void Out(ostream& os, int iLevel) const;
};
void CMVPS::Out(ostream& os, int iLevel) const {
CMoveValue::Out(os);
if (iLevel>1) {
os << "\t";
sbd->Out(os, pass!=1);
os << '\n';
}
}
// move-finding routines
// Pick a move at random
u4 LeftShift(u4 x, int n) {
if (n>0)
return x<<n;
else
return x>>-n;
}
const u4 nullProb=1<<10;
// probability of picking a node (probs do not sum to 1)
u4 Probability(u4 loss, int randomShift) {
u4 ekt; // energy loss / k*temperature
ekt=LeftShift(loss,-randomShift);
// bug in Pentium? 1024>>32 = 1024.
if (ekt>=32)
return 0;
else
return nullProb >> ekt;
}
void PickRandomMove(vector<CMVPS>& mvs, int randomShift, CMoveValue& chosen, bool fPrintRandomInfo) {
int nChoices;
QSSERT(!mvs.empty());
// First get cutoff value
sort(mvs.begin(), mvs.end());
vector<int> possible_moves;
int best_score = std::numeric_limits<int>::min();
for (std::size_t i=0; i<mvs.size(); i++) {
if( best_score<mvs[i].value
|| (best_score==mvs[i].value && (mvs[i].sbd->GameCount()==0 || mvs[i].sbd->IsPrivate())) ) {
best_score = mvs[i].value;
possible_moves.clear();
possible_moves.push_back(i);
}
else if( best_score==mvs[i].value )
possible_moves.push_back(i);
if( mvs[i].sbd->GameCount()==0 )
break;
}
nChoices = possible_moves.size();
int i = rand()%nChoices;
if (fPrintRandomInfo) {
cout << "\n" << nChoices << " move" << (nChoices>1?"s":"") << " considered:";
cout << "\nChoosing move " << possible_moves[i]+1 << "/" << mvs.size() << " - " << mvs[possible_moves[i]] << "\n";
}
chosen = mvs[i];
}
}
////////////////////////////////////////////////////////////
// CBookValue
////////////////////////////////////////////////////////////
BOOST_STATIC_ASSERT(sizeof(CValue)==2);
BOOST_STATIC_ASSERT(sizeof(CBookValue)==10);
BOOST_STATIC_ASSERT(sizeof(CHeightInfo)==12);
BOOST_STATIC_ASSERT(sizeof(CBookData)==36);
CBookValue::CBookValue()
: fSet(false),
fAssigned(false),
fWLDSolved(false)
{}
void CBookValue::Clear() {
//epb = epo = 0;
vHeuristic = vBlack = vWhite = 0;
fWLDSolved=fSet=fAssigned=false;
}
void CBookValue::SetLeaf(CValue av, bool afWLDSolved) {
vHeuristic=av;
fWLDSolved=afWLDSolved;
fSet=true;
}
void CBookValue::SetBranch(const CBookValue& valueNew) {
vHeuristic=valueNew.vHeuristic;
vBlack=valueNew.vBlack;
vWhite=valueNew.vWhite;
fSet=true;
}
// Assign - assign a value to a leaf book node
// inputs:
// boni - winning bonuses
void CBookValue::AssignLeaf(const CBoni& boni) {
//QSSERT(fSet);;
vBlack=vHeuristic;
vWhite=vHeuristic;
if (Win()) {
vBlack+=boni.blackBonus;
vWhite-=boni.whiteBonus;
}
else if (Draw()) {
vBlack+=boni.drawBonus;
vWhite-=boni.drawBonus;
}
else if (Loss()) {
vBlack+=boni.whiteBonus;
vWhite-=boni.blackBonus;
}
fAssigned=true;
}
void CBookValue::AssignBranch() {
QSSERT(fSet);
fAssigned=true;
}
void CBookValue::Deassign() {
fAssigned=false;
}
const char solvedText[5] = "?LDW";
char CBookValue::SolvedChar() const {
if (!fWLDSolved)
return '?';
else if (vHeuristic==0)
return 'D';
else return vHeuristic>0?'W':'L';
}
void CBookValue::Out(ostream& os, bool fReverse) const {
if (fSet) {
if (fReverse) {
os << std::setw(5) << -vHeuristic << SolvedChar() << " <";
if (fAssigned)
os << std::setw(5) << -vWhite << ":" << std::setw(5) << -vBlack;
else
os << "Unassigned";
os << ">";
}
else {
os << std::setw(5) << vHeuristic << SolvedChar() << " <";
if (fAssigned)
os << std::setw(5) << vBlack << ":" << std::setw(5) << vWhite;
else
os << "Unassigned";
os << ">";
}
}
else
os << "No values";
}
CValue CBookValue::VMover(bool fBlackMove) const {
return fBlackMove?vBlack:vWhite;
}
CValue CBookValue::VMover(bool fBlackMove, int vContempt, int nPass) const {
CValue vUpperBound, vLowerBound;
// calculate upper and lower possible values for draw
if (vBlack<vWhite) {
vUpperBound=vWhite;
vLowerBound=vBlack;
}
else {
vUpperBound=vBlack;
vLowerBound=vWhite;
}
// adjust contempt factor for passes
if (nPass)
vContempt=-vContempt;
// calculate value given contempt factor
if (vContempt>vUpperBound)
return vUpperBound;
else if (vContempt<vLowerBound)
return vLowerBound;
else
return vContempt;
}
// Merge - combine two CValues
// inputs:
// maxval - the maximum so far
// newval - the new value to be combined
// outputs:
// maxval - the greater of maxval and newval
inline void ValueMerge(CValue& maxval, CValue newval) {
if (maxval<newval)
maxval=newval;
}
// Merge - updates a node's values given a subnode value
// inputs:
// sub - the value of the subnode
// pass - nonzero if the subnode had a pass
void CBookValue::Merge(const CBookValue& sbd, int pass) {
if (pass) {
ValueMerge(vBlack, sbd.vBlack);
ValueMerge(vWhite, sbd.vWhite);
ValueMerge(vHeuristic, sbd.vHeuristic);
}
else {
ValueMerge(vBlack, -sbd.vWhite);
ValueMerge(vWhite, -sbd.vBlack);
ValueMerge(vHeuristic, -sbd.vHeuristic);
}
}
// MergeTerminalValue - updates a node's margins given a subnode's terminal value
// It is assumed that there was a pass before calculating vTerminal
// inputs:
// terminalValue - the child value of the terminal subnode
void CBookValue::MergeTerminalValue(CValue vTerminal, const CBoni& boni) {
CBookValue bv;
bv.vHeuristic=vTerminal;
bv.fWLDSolved=true;
bv.AssignLeaf(boni);
Merge(bv, 1);
}
////////////////////////////////////////////////////////////
// CBookData
////////////////////////////////////////////////////////////
CBookData::CBookData() {
hi.Clear();
nGames[0]=nGames[1]=0;
cutoff=kInfinity;
fRoot=false;
values.Clear();
}
// Increase the height if needed. Return true if we have increased the height
bool CBookData::IncreaseHeight(const CHeightInfo& hiNew, int nEmpty) {
bool fIncrease=hiNew>hi;
if (fIncrease) {
hi=hiNew;
values.Clear();
values.SetWLDSolved(hiNew.WLDSolved(nEmpty));
cutoff=kInfinity;
}
return fIncrease;
}
// Update book data with the result of a search. If the height is at least the old height,
// set the v value and the height.
// If the height is greater than the old height, set cutoff = value
// If height == old height, set cutoff = Min(old cutoff, value)
// If rootNode, clear minimal flag
void CBookData::StoreLeaf(CHeightInfo hiNew, int nEmpty, CValue v, const CBoni& boni) {
// update the node if the new value is more important
if (hiNew>=hi) {
IncreaseHeight(hiNew, nEmpty);
if (IsLeaf()) {
values.SetLeaf(v, hiNew.WLDSolved(nEmpty));
values.AssignLeaf(boni);
}
}
}
void CBookData::StoreRoot(CHeightInfo hiNew,
int nEmpty,
CValue v,
CValue vCutoff,
bool fFull,
const CBoni& boni)
{
// update the node if the new value is more important
fRoot=true;
if (hiNew>=hi) {
bool fIncrease=IncreaseHeight(hiNew, nEmpty);
if (IsBranch()) {
if (fIncrease || vCutoff<cutoff)
cutoff=vCutoff;
}
else if (fFull) {
values.SetLeaf(v, hiNew.WLDSolved(nEmpty));
values.AssignLeaf(boni);
}
}
}
void CBookData::AllSubnodesInBook() {
cutoff=-kInfinity;
}
void CBookData::AssignBranchValues(const CBookValue& valuesNew) {
values.SetBranch(valuesNew);
values.AssignBranch();
}
void CBookData::IncrementGameCount(int iGameType) {
nGames[iGameType]++;
}
void CBookData::CorrectBranchness() {
if (nGames[0] || nGames[1])
UpgradeToBranch();
}
void CBookData::UpgradeToBranch() {
fRoot=true;
}
void CBookData::Out(ostream& os, bool fReverse) const {
static char cLeafness[3]= { 'u','b','s' };
os << cLeafness[Leafness()] << ' ' << hi << " in "
<< std::setw(4) << nGames[0] << " + "
<< std::setw(4) << nGames[1] << " games: ";
values.Out(os, fReverse);
if (IsBranch())
os << "; cutoff " << (fReverse?-cutoff:cutoff);
}
CBookData::TLeafness CBookData::Leafness() const {
if (IsSolved())
return kSolved;
else if (IsBranch())
return kBranch;
else
return kULeaf;
}
bool CBookData::IsMoreImportantThan(const CBookData& bd2) const {
if (Leafness()>bd2.Leafness())
return true;
if (Leafness() < bd2.Leafness())
return false;
return hi > bd2.hi;
}
////////////////////////////////////////////////////////////
// CBook
////////////////////////////////////////////////////////////
map<CBookType, CBookPtr> CBook::bookList;
CBookPtr CBook::FindBook(char evalType, char coeffSet, CCalcParamsPtr pcp) {
CBookType bookType;
CBookPtr result;
map<CBookType, CBookPtr>::iterator ptr;
ostrstream os(bookType.bookName, sizeof(bookType.bookName));
os << fnBaseDir << "coefficients/" << evalType << coeffSet << "_" << *pcp << ".book" << '\0';
ptr=bookList.find(bookType);
if (ptr==bookList.end()) {
result.reset(new CBook(bookType.bookName));
bookList[bookType]=result;
QSSERT(result);
}
else {
result=(*ptr).second;
}
return result;
}
void CBook::Clean() {
bookList.clear();
}
// hash stuff for double-checking
u4 hash_a,hash_b,hash_c,hash_n;
void HashInit() {
hash_a=hash_b=hash_c=hash_n=0;
}
void HashLong(u4 x) {
switch(hash_n++) {
case 0:
hash_a+=x;
break;
case 1:
hash_b+=x;
break;
case 2:
hash_c+=x;
bobMix(hash_a,hash_b,hash_c);
hash_n=0;
break;
default:
_ASSERT(0);
}
}
void HashChunk(const void* p, int size) {
const u4* p4 = (u4*)p;
while (size>=4) {
HashLong(*p4);
p4++;
size-=4;
}
const u2* p2 = (u2*)p4;
if (size>=2) {
HashLong(*p2);
p2++;
}
const u1* p1 = (u1*)p2;
if (size>=1) {
HashLong(*p1);
p1++;
}
}
void CBook::ReadErr() {
cerr << "WARNING: BOOK " << bookname << " is damaged, restore a backup.\n";
_ASSERT(0);
_exit(-3);
}
CBook::CBook(const char* filename)
: tLastWrite(time(0)),
nHashErr(0),
save_when_closing(true)
{
Init(filename);
}
CBook::CBook(const char* filename, no_save_type)
: tLastWrite(time(0)),
nHashErr(0),
save_when_closing(false)
{
Init(filename);
}
void CBook::Init(const char* filename)
{
CBookData bd;
CBitBoard board;
FILE* fp;
int nVersion;
if (filename) {
fp=fopen(filename,"rb");
if (!fp) {
switch(errno) {
case ENOENT:
fprintf(stderr, "WARNING: book %s doesn't exist, will be created when saving book\n",filename);
break;
default:
fprintf(stderr, "WARNING: Book %s unavailable, book will start out empty and will not be saved. (errno %d)\n",filename, errno);
filename=0;
}
}
else {
fprintf(stderr, "Loading book %s...",filename);
if (fread(&nVersion, sizeof(nVersion), 1, fp)==0) {
cerr << "WARNING: Book " << filename << " is empty, either restore a backup or delete the file\n";
_exit(-3);
}
else {
if (nVersion!=1)
ReadVersion0(fp);
else
ReadVersion1(fp);
}
fclose(fp);
fprintf(stderr, "Done\n");
}
}
if (filename) {
bookname=filename;
}
else
bookname.erase(0,-1);
}
CBook::~CBook() {
if( save_when_closing ) {
std::cerr << "Closing book " << bookname << "..." << std::flush;
Write();
std::cerr << "Done\n";
}
}
int CBook::NEmptyMin() const {
return hSolverStart+1;
}
// Mirror the book to disk - Write it every so often
void CBook::Mirror() {
Mirror(0);
}
void CBook::Mirror(int pruneHeight) {
if (time(0)>=tLastWrite+25*60) {
std::cout << "Writing book " << bookname << "..." << std::flush;
Write(pruneHeight);
std::cout << "Done" << std::endl;
}
}
int CBook::GetPruneHeight() const
{
int pruneHeight = 0;
if( pComputer ) {
pruneHeight = pComputer->book_pcp ? pComputer->book_pcp->PerfectSolve() : 0;
}
// three perfect solved nodes, or a maximum at 24 empty
return (std::min)(24, (std::max)(pruneHeight-2, 0));
}
void CBook::Prune(int pruneHeight)
{
for (int nEmpties=0; nEmpties<pruneHeight; nEmpties++)
entries[nEmpties].clear();
}
void CBook::Prune()
{
Prune(GetPruneHeight());
}
void CBook::Write() {
Write(GetPruneHeight());
}
void CBook::Write(int pruneHeight) {
WriteVersion1(pruneHeight);
}
void CBook::WriteErr() {
cerr << "WARNING: Error writing to book file " << bookname << " (errno " << errno << ")\n";
}
void CBook::ReadVersion0(FILE* fp) {
CBitBoard board;
CBookData bd;
rewind(fp);
while (fread(&board, sizeof(board), 1, fp) && fread(&bd, sizeof(bd), 1, fp)) {
int nEmpty=CountBits(board.empty);
if (nEmpty<nEmptyBookMax)
entries[nEmpty][board]=bd;
else {
cerr << "RED ALERT: BOOK MAY BE CORRUPT\nEntry with " << nEmpty << " empties was ignored\n";
cout << "RED ALERT: BOOK MAY BE CORRUPT\nEntry with " << nEmpty << " empties was ignored\n";
}
}
}
void CBook::WriteVersion1(int pruneHeight) {
BookType::const_iterator i;
FILE* fp;
int nEmpties;
int nSize, nVersion=1;
if (bookname.empty())
return;
fp=fopen(bookname.c_str(),"wb");
if (!fp) {
cerr << "WARNING: Error opening book file " << bookname << " for writing (errno " << errno << ")\n";
return;
}
// calculate nSize - number of book entries
nSize=0;
for (nEmpties=pruneHeight; nEmpties<nEmptyBookMax; nEmpties++)
nSize+=entries[nEmpties].size();
if (!fwrite(&nVersion, sizeof(nVersion), 1, fp) || !fwrite(&nSize, sizeof(nSize), 1, fp)) {
WriteErr();
}
else {
HashInit();
for (nEmpties=nEmptyBookMax-1; nEmpties>=pruneHeight; nEmpties--) {
const BookType& bookType = entries[nEmpties];
for (i=bookType.begin(); i!=bookType.end(); i++) {
const CBitBoard& bitboard = i->first;
const CBookData& bookData = i->second;
if (!(fwrite(&bitboard, sizeof(CBitBoard), 1, fp)
&& fwrite(&bookData, sizeof(CBookData), 1, fp)))
{
WriteErr();
fclose(fp);
return;
}
HashChunk(&((*i).first), sizeof(CBitBoard));
HashChunk(&((*i).second), sizeof(CBookData));
}
}
}
hash_a+=nHashErr;
fwrite(&hash_a, sizeof(hash_a), 1, fp);
fclose(fp);
tLastWrite=time(0);
}
void CBook::ReadVersion1(FILE* fp) {
CBitBoard board;
CBookData bd;
int nSize, nRead, nHashCheck;
if (!fread(&nSize, sizeof(nSize), 1, fp))
ReadErr();
HashInit(); // init hash table for detection of corrupt book
for (nRead=0; nRead<nSize && fread(&board, sizeof(board), 1, fp) && fread(&bd, sizeof(bd), 1, fp); nRead++) {
HashChunk(&board, sizeof(board));
HashChunk(&bd, sizeof(bd));
int nEmpty=CountBits(board.empty);
if (nEmpty<nEmptyBookMax)
entries[nEmpty][board]=bd;
else
ReadErr();
}
if (nRead!=nSize)
ReadErr();
if (!fread(&nHashCheck, sizeof(nHashCheck), 1, fp))
ReadErr();
nHashErr=nHashCheck-hash_a;
_ASSERT(nHashErr==0);
}
void CBook::WriteVersion0() {
BookType::const_iterator i;
FILE* fp;
int nEmpties;
if (!bookname.empty()) {
fp=fopen(bookname.c_str(),"wb");
if (!fp)
printf("Error opening book file %s for writing (errno %d)\n",bookname.c_str(), errno);
else {
for (nEmpties=nEmptyBookMax-1; nEmpties>=0; nEmpties--) {
for (i=entries[nEmpties].begin(); i!=entries[nEmpties].end(); i++)
if (!(fwrite(&((*i).first), sizeof(CBitBoard), 1, fp) &&
fwrite(&((*i).second), sizeof(CBookData), 1, fp)))
fprintf(stderr, "WARNING: Error writing to book file %s (errno %d)\n", bookname.c_str(), errno);
}
fclose(fp);
tLastWrite=time(0);
}
}
}
const CBookData* CBook::FindMinimal(const CBitBoard& board) const {
return FindMinimal(board, CountBits(board.empty));
}
CBookData* CBook::FindMinimal(const CBitBoard& board) {
return FindMinimal(board, CountBits(board.empty));
}
const CBookData* CBook::FindMinimal(const CBitBoard& board, int nEmpty) const {
BookType::const_iterator i;
if (nEmpty>=nEmptyBookMax)
return 0;
i=entries[nEmpty].find(board);
if (i==entries[nEmpty].end())
return 0;
else {
QSSERT((*i).second.Hi().height<=nEmpty);
return &((*i).second);
}
}
CBookData* CBook::FindMinimal(const CBitBoard& board, int nEmpty) {
BookType::iterator i;
if (nEmpty>=nEmptyBookMax)
return 0;
i=entries[nEmpty].find(board);
if (i==entries[nEmpty].end())
return 0;
else {
QSSERT((*i).second.Hi().height<=nEmpty);
return &((*i).second);
}
}
const CBookData* CBook::FindAnyReflection(const CBitBoard& board) const {
return FindMinimal(board.MinimalReflection());
}
CBookData* CBook::FindAnyReflection(const CBitBoard& board) {
return FindMinimal(board.MinimalReflection());
}
const CBookData* CBook::FindAnyReflection(const CBitBoard& board, int nEmpty) const {
return FindMinimal(board.MinimalReflection(), nEmpty);
}
CBookData* CBook::FindAnyReflection(const CBitBoard& board, int nEmpty) {
return FindMinimal(board.MinimalReflection(), nEmpty);
}
// read a value from the book
bool CBook::Load(const CBitBoard& board, CHeightInfo hi, CValue alpha, CValue beta, CValue& value) {
return Load(board, hi, alpha, beta, value, CountBits(board.empty));
}
bool CBook::Load(const CBitBoard& board, CHeightInfo hi, CValue alpha, CValue beta, CValue& value, int nEmpty) {
CBookData* bd;
bd=FindAnyReflection(board, nEmpty);
// no data, return false
if (bd==NULL)
return false;
// data of height >= full-width search? return value
if (bd->Hi() >= hi) {
value=bd->Values().vHeuristic;
return true;
}
// data of proper height but WLD only? See if we can return it
hi.fWLD=true;
if (bd->Hi() >= hi) {
CValue vtmp = bd->Values().vHeuristic;
if (beta<=kStoneValue && kStoneValue<=vtmp) {
value=kStoneValue;
return true;
}
else if (vtmp<=-kStoneValue && -kStoneValue<=alpha) {
value=-kStoneValue;
return true;
}
else if (vtmp==0) {
value=0;
return true;
}
}
return false;
}
bool CBook::GetRandomMove(const CQPosition& pos, const CSearchInfo& si, CMVK& mvk) const {
vector<CMVPS> mvs;
CMVPS mv;
CMove move;
CMoves moves, submoves;
int pass;
const CBookData *bd, *sbd;
CQPosition subpos;
u4 fPrintLevel=si.PrintBookLevel();
pos.CalcMoves(moves);
// Find the book data. Return false if unusable.
bd=FindAnyReflection(pos.BitBoard());
if (!bd || bd->IsUleaf())
return false;
bool fSolved=bd->IsLeaf();
QSSERT(fSolved ? bd->Values().IsSolved() : true);
int vContempt=fSolved?0:si.vContempt;
// Check subnodes in turn to see if they're in book
for (move.Set(-1); moves.GetNext(move);) {
subpos=pos;
subpos.MakeMove(move);
pass=subpos.CalcMovesAndPass(submoves);
sbd=FindAnyReflection(subpos.BitBoard());
// If subnode is in book, add it to the list.
if (sbd) {
mv.move=move;
mv.value=sbd->Values().VMover(subpos.BlackMove(), vContempt, pass);
if (!pass)
mv.value=-mv.value;
mv.pass=pass;
mv.sbd=sbd;
mvs.push_back(mv);
// correctness checks when debugging
if(!sbd->Values().IsAssigned()) {
cout << "============= RED ALERT: BOOK BUG ==========\n";
pos.Print();
cout << mv << "\n";
subpos.Print();
cout << (*sbd);
cout << "\n=========== End book bug ==================\n";
}
}
}
// check for error condition and return false if we have one
if (mvs.empty()) {
if (!fSolved) {
pos.Print();
QSSERT(0);
printf("RED ALERT: BOOK HAS NO MOVES\n");
}
// restore board
Initialize(pos.BitBoard(), pos.BlackMove());
return false;
}
// sort the moves, and print them if we're debugging
sort(mvs.begin(), mvs.end());
if (fPrintLevel) {
cout << "BOOK: " << *bd << "\n";
cout << "Contempt: " << si.vContempt << "; Randomness: " << si.rs << "\n";
if (fPrintLevel>1) {
vector<CMVPS>::iterator i;
for (i=mvs.begin(); i!=mvs.end(); i++)
i->Out(cout, fPrintLevel);
if (fPrintLevel==2)
cout << '\n';
}
}
// choose a move
// assertion fails when we have uncorrected transpositions
//QSSERT(mvs[0].value==bd->Values().VMover(fBlackMove) || bd->IsSolved());
bool fUsable=!fSolved;
int rs = si.rs;
if (fSolved) {
rs = 0;
if (bd->Values().Loss()) {
if (mvs[0].value>=0) {
cout << "RED ALERT: Book error, Loss has a possible win or draw\n";
fUsable = true;
}
}
else if (bd->Values().Draw()) {
if (mvs[0].value>0)
cout << "RED ALERT: Book error, Draw has a possible win\n";
if (mvs[0].value>=0)
fUsable=true;
}
else {
if (mvs[0].value>0)
fUsable=true;
}
}
if (fUsable) {
PickRandomMove(mvs, rs, mvk, si.PrintBookRandomInfo()!=0);
// really the only info from the book is the height, although we could go to the
// subnode to get the ply of the chosen move. But I'm too lazy to implement this
mvk.hiFull=mvk.hiBest=bd->Hi();
}
Initialize(pos.BitBoard(), pos.BlackMove());
return fUsable;
}
bool CBook::GetEdmundMove(const CBitBoard& board, bool fBlackMove, CMoveValue& mv, bool fPrintEdmund, bool timeOut1, bool timeOut2) const {
vector<CMoveValue> mvs;
CMove move;
CMoves submoves;
int pass;
const CBookData *bd, *sbd;
CQPosition pos(board, fBlackMove), subpos;
CMoveValue mvBestPlayed;
CMoves moves;
// Find the book data. Return false if unusable.
bd=FindAnyReflection(board);
if (!bd || bd->IsUleaf() || bd->IsSolved() || /*bd->Hi().height+hSolverStart!=board.NEmpty() || */bd->GameCount()==0)
return false;
// Check subnodes in turn to see if they're in book
mvBestPlayed.value=-kInfinity;
pos.CalcMoves(moves);
for (move.Set(-1); moves.GetNext(move);) {
subpos=pos;
subpos.MakeMove(move);
pass=subpos.CalcMovesAndPass(submoves);
sbd=FindAnyReflection(subpos.BitBoard());
// If subnode is in book, add it to the list.
if (sbd) {
mv.move=move;
mv.value=sbd->Values().vHeuristic;
if (!pass)
mv.value=-mv.value;
if (sbd->GameCount() ) {
if( mvBestPlayed.value<mv.value)
mvBestPlayed=mv;
}
else
mvs.push_back(mv);
// correctness checks when debugging
if(!sbd->Values().IsAssigned()) {
cout << "============= RED ALERT: BOOK BUG ==========\n";
pos.Print();
cout << mv << "\n";
subpos.Print();
cout << (*sbd);
cout << "\n=========== End book bug ==================\n";
}
}
}
// restore board
Initialize(board, fBlackMove);
// check for error condition and return false if we have one
if (mvs.empty()) {
//board.Print(fBlackMove);
//QSSERT(0);
//printf("RED ALERT: BOOK HAS NO MOVES\n");
return false;
}
// sort the moves, and print them if we're debugging
sort(mvs.begin(), mvs.end());
mv=mvs[0];
bool best_draw_or_worse = mvBestPlayed.value<=0 || mvBestPlayed.value==10000;
bool fEdmund = (mv.move != mvBestPlayed.move)
&& ((mv.value>(timeOut1?(timeOut2?-1:-100):-200) && best_draw_or_worse) || (!timeOut1 && abs(mvBestPlayed.value)<=200 && abs(mv.value)<=200 && mv.value>mvBestPlayed.value));
//CValue v = pComputer->cd.vContempts[pos.BlackMove()];
//bool fEdmund= ((mv.value>v && mvBestPlayed.value<=v) || (mv.value==v && mvBestPlayed.value<v));
if (fEdmund && fPrintEdmund) {
cout << "--- Found an edmund position ---\n";
cout << "Best played : " << mvBestPlayed << ". Best deviation: " << mv << ".\n";
board.Print(fBlackMove);
cout << "--------------------------------\n";
}
return fEdmund;
}