From d4350a16f32eaedf0e5bd207a4e1293a7a4e1f2c Mon Sep 17 00:00:00 2001 From: Tomasz Sobczyk Date: Mon, 16 Nov 2020 11:32:42 +0100 Subject: [PATCH] Add representation of an opening book. --- src/Makefile | 1 + src/learn/opening_book.cpp | 43 +++++++++++++++++++++++++++++ src/learn/opening_book.h | 56 ++++++++++++++++++++++++++++++++++++++ 3 files changed, 100 insertions(+) create mode 100644 src/learn/opening_book.cpp create mode 100644 src/learn/opening_book.h diff --git a/src/Makefile b/src/Makefile index cba4e351..51a9654a 100644 --- a/src/Makefile +++ b/src/Makefile @@ -63,6 +63,7 @@ SRCS = benchmark.cpp bitbase.cpp bitboard.cpp endgame.cpp evaluate.cpp main.cpp learn/sfen_packer.cpp \ learn/learn.cpp \ learn/gensfen.cpp \ + learn/opening_book.cpp \ learn/convert.cpp OBJS = $(notdir $(SRCS:.cpp=.o)) diff --git a/src/learn/opening_book.cpp b/src/learn/opening_book.cpp new file mode 100644 index 00000000..fb569bda --- /dev/null +++ b/src/learn/opening_book.cpp @@ -0,0 +1,43 @@ +#include "opening_book.h" + +#include + +namespace Learner { + + EpdOpeningBook::EpdOpeningBook(const std::string& file, PRNG& prng) : + OpeningBook(file) + { + std::ifstream in(file); + if (!in) + { + return; + } + + std::string line; + while (std::getline(in, line)) + { + if (line.empty()) + continue; + + fens.emplace_back(line); + } + + Algo::shuffle(fens, prng); + } + + static bool ends_with(const std::string& lhs, const std::string& end) + { + if (end.size() > lhs.size()) return false; + + return std::equal(end.rbegin(), end.rend(), lhs.rbegin()); + } + + std::unique_ptr open_opening_book(const std::string& filename, PRNG& prng) + { + if (ends_with(filename, ".epd")) + return std::make_unique(filename, prng); + + return nullptr; + } + +} diff --git a/src/learn/opening_book.h b/src/learn/opening_book.h new file mode 100644 index 00000000..16207f13 --- /dev/null +++ b/src/learn/opening_book.h @@ -0,0 +1,56 @@ +#ifndef LEARN_OPENING_BOOK_H +#define LEARN_OPENING_BOOK_H + +#include "misc.h" +#include "position.h" +#include "thread.h" + +#include +#include +#include +#include +#include +#include + +namespace Learner { + + struct OpeningBook { + + const std::string& next_fen() + { + assert(fens.size() > 0); + + auto& fen = fens[current_index++]; + if (current_index >= fens.size()) + current_index = 0; + + return fen; + } + + std::size_t size() const { return fens.size(); } + + const std::string& get_filename() const { return filename; } + + protected: + OpeningBook(const std::string& file) : + filename(file), + current_index(0) + { + } + + + std::string filename; + std::vector fens; + std::size_t current_index; + }; + + struct EpdOpeningBook : OpeningBook { + + EpdOpeningBook(const std::string& file, PRNG& prng); + }; + + std::unique_ptr open_opening_book(const std::string& filename, PRNG& prng); + +} + +#endif