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
|
/*
Sjeng - a chess variants playing program
Copyright (C) 2000 Gian-Carlo Pascutto
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
File: newbook.c
Purpose: general function concerning the binary hashed book
*/
#include "sjeng.h"
#include "protos.h"
#include "extvars.h"
#include "gdbm.h"
#include <sys/stat.h>
#include <math.h>
#define BUILDTHRESHOLD 2
#define PLAYTHRESHOLD 3
#ifndef HAVE_LIBGDBM
#error You need the GNU DBM library (GDBM). Go to ftp.gnu.org
#endif
typedef struct
{
unsigned long hashkey;
} hashkey_t;
typedef struct
{
unsigned long played;
long int score;
} posinfo_t;
typedef struct
{
int result; /* 0: 1-0 1:1/2 2:0-1 3:? */
} pgn_header_t;
unsigned long kksize;
unsigned char *keycache;
unsigned long bookpos[400], booktomove[400], bookidx;
int gamenum;
void get_header(FILE *pgnbook, pgn_header_t *pgn_header)
{
int ch;
char buff[STR_BUFF];
int b;
int terminate = FALSE;
memset(pgn_header, 0, sizeof(pgn_header_t));
while(!terminate)
{
ch = getc(pgnbook);
if (ch == EOF)
break;
/* beginning of a header field */
if (ch == '[')
{
b = 0;
memset(buff, 0, sizeof(buff));
while(((buff[b++] = getc(pgnbook)) != ']') && (b < STR_BUFF));
buff[--b] = '\0';
/* buff now contains the field, minus the [] */
/* file position is just after ] */
//printf ("Read header: -%s-\n", buff);
if (!strncmp("Result", buff, 6))
{
if (strstr(buff+6, "1-0"))
pgn_header->result = 0;
else if (strstr(buff+6, "1/2-1/2"))
pgn_header->result = 1;
else if (strstr(buff+6, "0-1"))
pgn_header->result = 2;
else if (strstr(buff+6, "*"))
pgn_header->result = 3;
}
}
/* space or newlines between headers */
else if (ch == ' ' || ch == '\n' || ch == '\r');
else /* no more headers, put back last char */
{
//printf("End of header: -%c-\n", ch);
terminate = TRUE;
ungetc(ch, pgnbook);
}
}
}
void add_current(GDBM_FILE binbook, pgn_header_t pgn_header)
{
hashkey_t key;
posinfo_t posinfo;
posinfo_t *pst;
datum index;
datum data;
int ret;
/* fill in the key field */
key.hashkey = (hash ^ ToMove);
if (keycache[key.hashkey % kksize] >= BUILDTHRESHOLD)
{
index.dptr = (char*) &key;
index.dsize = sizeof(key);
posinfo.played = 2;
posinfo.score = 0;
data.dptr = (char*) &posinfo;
data.dsize = sizeof(posinfo);
ret = gdbm_store(binbook, index, data, GDBM_INSERT);
if (ret == 1)
{
data = gdbm_fetch(binbook, index);
pst = (posinfo_t *) data.dptr;
pst->played++;
gdbm_store(binbook, index, data, GDBM_REPLACE);
free(data.dptr);
}
}
else
keycache[key.hashkey % kksize]++;
}
void replay_game(FILE *pgnbook, GDBM_FILE binbook, pgn_header_t pgn_header)
{
int ch, xch;
char movebuff[STR_BUFF], sjmove[STR_BUFF];
int ms;
int brackets = 0, braces = 0;
int gameend = FALSE;
move_s moves[MOVE_BUFF];
int match, num_moves, i;
int limit = 0;
int ic;
/* reset board */
init_game();
initialize_hash();
putchar('.');
while (!gameend)
{
ch = getc(pgnbook);
if (ch == EOF)
return;
if (ch == ' ' || ch == '\n')
{
/* just skip and go on */
}
else if (ch == '{')
{
brackets++;
/* we want to skip everything till we get brackets
* and braces back to 0 */
while (brackets > 0 || braces > 0)
{
xch = getc(pgnbook);
if (xch == '}')
brackets--;
else if (xch == '{')
brackets++;
else if (xch == '[')
braces++;
else if (xch == ']')
braces--;
else if (xch == EOF)
break;
}
}
else if (ch == '[')
{
braces++;
while (brackets > 0 || braces > 0)
{
xch = getc(pgnbook);
if (xch == '}')
brackets--;
else if (xch == '{')
brackets++;
else if (xch == '[')
braces++;
else if (xch == ']')
braces--;
else if (xch == EOF)
break;
}
}
else if (ch == '*')
{
/* result string: unfinished game */
/* seek next header */
while (((ch = getc(pgnbook)) != '[') && !feof(pgnbook));
ungetc(ch, pgnbook);
gameend = TRUE;
}
else if (isdigit(ch))
{
xch = getc(pgnbook);
if (xch == EOF)
{
return;
}
/* either a move number or a result string */
else if (isdigit(xch)) /* 2 digits...must be move number */
{
while(((ch = getc(pgnbook)) != '.') && !feof(pgnbook));
}
else if (xch != '.')
{
/* not a move numer, must be result */
/* seek to next header */
while (((ch = getc(pgnbook)) != '[') && !feof(pgnbook));
ungetc(ch, pgnbook);
gameend = TRUE;
}
}
else if (isalpha(ch))
{
/* parse one move */
ms = 0;
movebuff[ms++] = ch;
while(movebuff[ms-1] != ' ' && movebuff[ms-1] != '\n')
{
movebuff[ms++] = getc(pgnbook);
}
movebuff[--ms] = '\0'; /* scratch last bogus char */
/* movebuff now contains -hopefully- the move in SAN */
// printf("Read move: -%s- ", &movebuff);
/* now, generate all moves from the current pos and try
* to get a match */
match = FALSE;
num_moves = 0;
// 21-3
ply = 0;
gen (&moves[0]);
num_moves = numb_moves;
ic = in_check();
for (i = 0; i < num_moves; i++)
{
comp_to_san(moves[i], sjmove);
if (!strcmp(movebuff, sjmove))
{
/* moves matched !*/
make(&moves[0], i);
match = TRUE;
if (check_legal(&moves[0], i, ic))
{
break;
}
else
{
printf("Illegal move from PGN!\n");
printf("Game: %d Move: %s\n", gamenum, movebuff);
break;
}
}
}
limit++;
if (match == FALSE || limit > 40)
{
if (match == FALSE)
printf("No move match! -%s-\n", movebuff);
/* skip junk game */
while (((ch = getc(pgnbook)) != '[') && !feof(pgnbook));
ungetc(ch, pgnbook);
gameend = TRUE;
}
else
{
add_current(binbook, pgn_header);
}
}
}
}
void weed_book(GDBM_FILE binbook)
{
datum data;
datum index;
datum nextkey;
posinfo_t *ps;
int weeds;
int positions;
do
{
weeds = 0;
positions = 0;
index = gdbm_firstkey(binbook);
while (index.dptr)
{
positions++;
nextkey = gdbm_nextkey (binbook, index);
data = gdbm_fetch(binbook, index);
ps = (posinfo_t *) data.dptr;
if ((ps->played) < PLAYTHRESHOLD)
{
gdbm_delete(binbook, index);
free(index.dptr);
weeds++;
}
free(data.dptr);
index = nextkey;
}
printf("Weeded %d moves.\n", weeds);
}
while (weeds > 0);
printf("%d unique positions.\n", positions);
printf("Reorganizing BinBook.\n");
gdbm_reorganize(binbook);
printf("Done.\n");
}
void build_book (void)
{
FILE *pgnbook;
GDBM_FILE binbook;
pgn_header_t pgn_header;
char bookname[FILENAME_MAX], kks[STR_BUFF];
printf("\nName of PGN book: ");
rinput(bookname, STR_BUFF, stdin);
pgnbook = fopen(bookname, "r");
if (pgnbook == NULL)
{
printf("PGN book not found!\n");
exit(EXIT_FAILURE);
}
if (Variant == Normal)
binbook = gdbm_open("nbook.bin", 16384, GDBM_NEWDB | GDBM_FAST, 00664, NULL);
else if (Variant == Suicide)
binbook = gdbm_open("sbook.bin", 16384, GDBM_NEWDB | GDBM_FAST, 00664, NULL);
else if (Variant == Losers)
binbook = gdbm_open("lbook.bin", 16384, GDBM_NEWDB | GDBM_FAST, 00664, NULL);
else
binbook = gdbm_open("zbook.bin", 16384, GDBM_NEWDB | GDBM_FAST, 00664, NULL);
if (binbook == NULL)
{
printf("Error opening binbook.\n");
exit(EXIT_FAILURE);
}
printf("\nSize of KeyCache (bytes): ");
rinput(kks, STR_BUFF, stdin);
kksize = atol(kks);
printf("Freeing hash and eval cache\n");
free_hash();
free_ecache();
printf("Allocating keycache\n");
keycache = (unsigned char *) calloc(kksize, sizeof(unsigned char));
if (keycache == NULL)
{
printf("Not enough RAM!\n");
exit(EXIT_FAILURE);
}
printf("Building");
gamenum = 0;
while (!feof(pgnbook))
{
gamenum++;
get_header(pgnbook, &pgn_header);
replay_game(pgnbook, binbook, pgn_header);
};
free(keycache);
printf("\nWeeding book moves.\n");
weed_book(binbook);
fclose(pgnbook);
gdbm_close(binbook);
alloc_hash();
alloc_ecache();
}
move_s choose_binary_book_move (void)
{
GDBM_FILE binbook;
hashkey_t key;
posinfo_t *ps;
datum index;
datum data;
move_s moves[MOVE_BUFF], bestmove;
move_s bookmoves[MOVE_BUFF];
int num_bookmoves;
int raw;
int num_moves, i;
char output[6];
long int scores[MOVE_BUFF], best_score = 0;
srand(time(0));
if (Variant == Normal)
binbook = gdbm_open("nbook.bin", 16384, GDBM_READER, 0, NULL);
else if (Variant == Suicide)
binbook = gdbm_open("sbook.bin", 16384, GDBM_READER, 0, NULL);
else if (Variant == Losers)
binbook = gdbm_open("lbook.bin", 16384, GDBM_READER, 0, NULL);
else
binbook = gdbm_open("zbook.bin", 16384, GDBM_READER, 0, NULL);
if (binbook == NULL)
{
printf("No BinBook found.\n");
return dummy;
}
num_moves = 0;
raw = 0;
num_bookmoves = 0;
gen(&moves[0]);
num_moves = numb_moves;
for (i = 0; i < num_moves; i++)
{
make(&moves[0], i);
if (check_legal(&moves[0], i, TRUE))
{
if (is_draw())
{
/* ok this is fishy: we can get a draw-by-rep
* while still in book. let the search take over.
* this prevents a trick where the player simply
* retreats his knights and Sjeng does the same */
book_ply = 50;
printf("Anti-book-rep-trick...\n");
unmake(&moves[0], i);
gdbm_close(binbook);
return dummy;
}
key.hashkey = (hash ^ ToMove);
index.dptr = (char*) &key;
index.dsize = sizeof(key);
data = gdbm_fetch(binbook, index);
if (data.dptr != NULL)
{
ps = (posinfo_t *) data.dptr;
raw++;
comp_to_coord(moves[i], output);
printf("Move %s: %ld times played, %ld learned\n", output,
ps->played, ps->score);
if ((ps->played + ps->score) >= PLAYTHRESHOLD)
{
scores[num_bookmoves] = ps->played + ps->score;
bookmoves[num_bookmoves] = moves[i];
num_bookmoves++;
}
free(data.dptr);
}
}
unmake(&moves[0], i);
}
gdbm_close(binbook);
printf("Book moves: raw: %d cut : %d\n", raw, num_bookmoves);
if (!num_bookmoves)
return dummy;
/* find the top frequency: */
for (i = 0; i < num_bookmoves; i++) {
if (scores[i] > best_score) {
best_score = scores[i];
}
}
/* add some randomness to each frequency: */
for (i = 0; i < num_bookmoves; i++) {
/* weed out very rare lines */
if (scores[i] * 15 > best_score)
{
scores[i] += (int) ((float)(((float)(rand())/RAND_MAX)) * ((float)best_score*1.35));
}
else
{
scores[i] = 0;
}
}
/* now pick our best move: */
best_score = 0;
for (i = 0; i < num_bookmoves; i++) {
if (scores[i] > best_score) {
best_score = scores[i];
bestmove = bookmoves[i];
}
}
/* we need to find the hash here so learning will
* be correct */
make(&bestmove, 0);
bookpos[bookidx] = hash;
booktomove[bookidx++] = ToMove;
unmake(&bestmove, 0);
return bestmove;
}
void book_learning(int result)
{
GDBM_FILE binbook = NULL;
hashkey_t key;
posinfo_t *ps;
datum index;
datum data;
float playinc;
float factor;
int pi;
int iters;
static const float factortable[] = {1.0, 0.5, 0.25, 0.12, 0.08, 0.05, 0.03};
if (bookidx == 0) return;
if (Variant == Normal)
binbook = gdbm_open("nbook.bin", 16384, GDBM_WRITER, 0, NULL);
else if (Variant == Suicide)
binbook = gdbm_open("sbook.bin", 16384, GDBM_WRITER, 0, NULL);
else if (Variant == Losers)
binbook = gdbm_open("lbook.bin", 16384, GDBM_WRITER, 0, NULL);
else if (Variant == Crazyhouse)
binbook = gdbm_open("zbook.bin", 16384, GDBM_WRITER, 0, NULL);
else if (Variant == Bughouse)
return;
if (binbook == NULL)
{
printf("No BinBook found, not learning.\n");
return;
}
iters = 0;
while ((iters < 7) && ((bookidx - iters) > 0))
{
iters++;
factor = factortable[iters-1];
key.hashkey = (bookpos[bookidx-iters] ^ booktomove[bookidx-iters]);
index.dptr = (char*) &key;
index.dsize = sizeof(key);
data = gdbm_fetch(binbook, index);
if (data.dptr != NULL)
{
ps = (posinfo_t *) data.dptr;
playinc = 0;
if (result == WIN)
{
if (my_rating <= opp_rating)
playinc = 0.5 * factor;
else
playinc = 0.25 * factor;
}
else if (result == LOSS)
{
if (my_rating >= opp_rating)
playinc = -0.5 * factor;
else
playinc = -0.25 * factor;
}
else
{
if (my_rating >= opp_rating)
playinc = -0.3 * factor;
else
playinc = 0.3 * factor;
}
if (fabs((double)((ps->played + ps->score)) * playinc) < 1.0)
{
pi = (int)(playinc * 10.0);
}
else
{
pi = (int)((float)(ps->played + ps->score)*(float)playinc);
}
/* don't 'overlearn' */
if ((unsigned long)labs((ps->score)+pi) < (ps->played*5))
{
printf("Learning opening %lu, played %lu, old score %ld, new score %ld\n",
bookpos[bookidx-iters], ps->played, ps->score, (ps->score)+pi);
ps->score += pi;
gdbm_store(binbook, index, data, GDBM_REPLACE);
}
free(data.dptr);
}
else
{
printf("No hit in hashed book, not learning.\n");
}
}
gdbm_close(binbook);
return;
};
|