diff --git a/.clang-format b/.clang-format index 2d9fcadd..06838e03 100644 --- a/.clang-format +++ b/.clang-format @@ -6,16 +6,19 @@ AlignEscapedNewlines: LeftWithLastLine AlignOperands: AlignAfterOperator AlignTrailingComments: true AllowAllParametersOfDeclarationOnNextLine: true +AllowAllArgumentsOnNextLine: true AllowShortCaseLabelsOnASingleLine: false AllowShortEnumsOnASingleLine: false AllowShortIfStatementsOnASingleLine: Never AllowShortLoopsOnASingleLine: false -AllowShortFunctionsOnASingleLine: None -AllowShortLambdasOnASingleLine: None +AllowShortFunctionsOnASingleLine: Inline +AllowShortLambdasOnASingleLine: All AlwaysBreakTemplateDeclarations: Yes + BasedOnStyle: WebKit BitFieldColonSpacing: After -BinPackParameters: false +BinPackParameters: true +BinPackArguments: true BreakBeforeBinaryOperators: NonAssignment BreakBeforeBraces: Custom BraceWrapping: @@ -31,19 +34,24 @@ BraceWrapping: BreakBeforeTernaryOperators: true BreakConstructorInitializers: AfterColon BreakStringLiterals: false -ColumnLimit: 100 + +ColumnLimit: 120 ContinuationIndentWidth: 2 Cpp11BracedListStyle: true + IndentAccessModifiers: false IndentGotoLabels: false IndentPPDirectives: BeforeHash IndentWidth: 4 InsertBraces: true InsertTrailingCommas: None +InsertNewlineAtEOF: true + MaxEmptyLinesToKeep: 2 NamespaceIndentation: None PackConstructorInitializers: Never ReflowComments: false + SortIncludes: CaseInsensitive SortUsingDeclarations: false SpaceAfterTemplateKeyword: false @@ -52,4 +60,3 @@ SpaceBeforeCpp11BracedList: false SpaceBeforeInheritanceColon: true SpaceInEmptyBlock: false SpacesBeforeTrailingComments: 2 -InsertNewlineAtEOF: true diff --git a/src/bench.cpp b/src/bench.cpp index 6992da7a..266616ff 100644 --- a/src/bench.cpp +++ b/src/bench.cpp @@ -87,7 +87,6 @@ void benchmark(Search::Searcher& searcher, Depth depth) { dbg_print(); - std::cout << nodes << " nodes " << time::nps(nodes, end_time - start_time) << " nps" - << std::endl; + std::cout << nodes << " nodes " << time::nps(nodes, end_time - start_time) << " nps" << std::endl; } } // namespace Clockwork::Bench diff --git a/src/bitboard.hpp b/src/bitboard.hpp index 9c7da0b9..2be252dc 100644 --- a/src/bitboard.hpp +++ b/src/bitboard.hpp @@ -26,12 +26,9 @@ struct Bitboard { constexpr Bitboard() = default; constexpr explicit Bitboard(u64 raw) : - m_raw(raw) { - } + m_raw(raw) {} - static constexpr Bitboard from_square(Square sq) { - return Bitboard{static_cast(1) << sq.raw}; - } + static constexpr Bitboard from_square(Square sq) { return Bitboard{static_cast(1) << sq.raw}; } static constexpr Bitboard squares_of_color(Color c) { return c == Color::White ? Bitboard{0x55AA55AA55AA55AA} : Bitboard{0xAA55AA55AA55AA55}; @@ -47,9 +44,7 @@ struct Bitboard { return Bitboard{static_cast(0xFF) << (8 * rank)}; } - static constexpr Bitboard central_files() { - return file_mask(2) | file_mask(3) | file_mask(4) | file_mask(5); - } + static constexpr Bitboard central_files() { return file_mask(2) | file_mask(3) | file_mask(4) | file_mask(5); } [[nodiscard]] static Bitboard fill_verticals(const Bitboard mask) { Bitboard result = mask | (mask >> 8); @@ -58,25 +53,15 @@ struct Bitboard { return (result & Bitboard::rank_mask(0)) * Bitboard::file_mask(0); } - [[nodiscard]] bool empty() const { - return m_raw == 0; - } + [[nodiscard]] bool empty() const { return m_raw == 0; } - [[nodiscard]] usize popcount() const { - return static_cast(std::popcount(m_raw)); - } + [[nodiscard]] usize popcount() const { return static_cast(std::popcount(m_raw)); } - [[nodiscard]] i32 ipopcount() const { - return static_cast(std::popcount(m_raw)); - } + [[nodiscard]] i32 ipopcount() const { return static_cast(std::popcount(m_raw)); } - [[nodiscard]] Square msb() const { - return Square{static_cast(std::countl_zero(m_raw))}; - } + [[nodiscard]] Square msb() const { return Square{static_cast(std::countl_zero(m_raw))}; } - [[nodiscard]] Square lsb() const { - return Square{static_cast(std::countr_zero(m_raw))}; - } + [[nodiscard]] Square lsb() const { return Square{static_cast(std::countr_zero(m_raw))}; } // Rank closest to player [[nodiscard]] u8 front_rank(Color color) const { @@ -125,21 +110,13 @@ struct Bitboard { return result; } - [[nodiscard]] u64 value() const { - return m_raw; - } + [[nodiscard]] u64 value() const { return m_raw; } - [[nodiscard]] bool is_set(Square sq) const { - return (m_raw >> sq.raw) & 1; - } + [[nodiscard]] bool is_set(Square sq) const { return (m_raw >> sq.raw) & 1; } - void clear(Square sq) { - m_raw &= ~from_square(sq).m_raw; - } + void clear(Square sq) { m_raw &= ~from_square(sq).m_raw; } - void set(Square sq) { - m_raw |= from_square(sq).m_raw; - } + void set(Square sq) { m_raw |= from_square(sq).m_raw; } void set(Square sq, bool value) { if (value) { @@ -156,9 +133,7 @@ struct Bitboard { return *this; } - Square operator*() const { - return Square{static_cast(std::countr_zero(m_bb))}; - } + Square operator*() const { return Square{static_cast(std::countr_zero(m_bb))}; } bool operator==(const Iterator&) const = default; @@ -166,49 +141,28 @@ struct Bitboard { friend struct Bitboard; explicit constexpr Iterator(u64 bb) : - m_bb(bb) { - } + m_bb(bb) {} u64 m_bb; }; - [[nodiscard]] Iterator begin() const { - return Iterator{m_raw}; - } + [[nodiscard]] Iterator begin() const { return Iterator{m_raw}; } - [[nodiscard]] Iterator end() const { - return Iterator{0}; - } + [[nodiscard]] Iterator end() const { return Iterator{0}; } bool operator==(const Bitboard&) const = default; - friend constexpr Bitboard operator~(Bitboard a) { - return Bitboard{~a.m_raw}; - } - friend constexpr Bitboard operator&(Bitboard a, Bitboard b) { - return Bitboard{a.m_raw & b.m_raw}; - } - friend constexpr Bitboard operator|(Bitboard a, Bitboard b) { - return Bitboard{a.m_raw | b.m_raw}; - } + friend constexpr Bitboard operator~(Bitboard a) { return Bitboard{~a.m_raw}; } + friend constexpr Bitboard operator&(Bitboard a, Bitboard b) { return Bitboard{a.m_raw & b.m_raw}; } + friend constexpr Bitboard operator|(Bitboard a, Bitboard b) { return Bitboard{a.m_raw | b.m_raw}; } - friend constexpr Bitboard operator*(Bitboard a, Bitboard b) { - return Bitboard{a.m_raw * b.m_raw}; - } + friend constexpr Bitboard operator*(Bitboard a, Bitboard b) { return Bitboard{a.m_raw * b.m_raw}; } - friend constexpr Bitboard operator>>(Bitboard a, i32 shift) { - return Bitboard{a.m_raw >> shift}; - } - friend constexpr Bitboard operator<<(Bitboard a, i32 shift) { - return Bitboard{a.m_raw << shift}; - } + friend constexpr Bitboard operator>>(Bitboard a, i32 shift) { return Bitboard{a.m_raw >> shift}; } + friend constexpr Bitboard operator<<(Bitboard a, i32 shift) { return Bitboard{a.m_raw << shift}; } - friend constexpr Bitboard& operator&=(Bitboard& a, Bitboard b) { - return a = a & b; - } - friend constexpr Bitboard& operator|=(Bitboard& a, Bitboard b) { - return a = a | b; - } + friend constexpr Bitboard& operator&=(Bitboard& a, Bitboard b) { return a = a & b; } + friend constexpr Bitboard& operator|=(Bitboard& a, Bitboard b) { return a = a | b; } private: u64 m_raw = 0; diff --git a/src/board.hpp b/src/board.hpp index 727e35c0..34518cda 100644 --- a/src/board.hpp +++ b/src/board.hpp @@ -22,9 +22,7 @@ struct PieceId { assert(raw < 0x10); } - constexpr static PieceId king() { - return {0}; - } + constexpr static PieceId king() { return {0}; } [[nodiscard]] constexpr PieceMask to_piece_mask() const; }; @@ -34,49 +32,31 @@ static_assert(sizeof(PieceId) == sizeof(u8)); struct PieceMask { public: constexpr PieceMask() : - m_raw(0) { - } + m_raw(0) {} constexpr explicit PieceMask(u16 raw) : - m_raw(raw) { - } + m_raw(raw) {} constexpr static PieceMask king() { // The king always has a PieceId of 0. return PieceMask{0x0001}; } - [[nodiscard]] bool empty() const { - return m_raw == 0; - } + [[nodiscard]] bool empty() const { return m_raw == 0; } - [[nodiscard]] usize popcount() const { - return static_cast(std::popcount(m_raw)); - } + [[nodiscard]] usize popcount() const { return static_cast(std::popcount(m_raw)); } - [[nodiscard]] PieceId msb() const { - return PieceId{static_cast(std::countl_zero(m_raw))}; - } + [[nodiscard]] PieceId msb() const { return PieceId{static_cast(std::countl_zero(m_raw))}; } - [[nodiscard]] PieceId lsb() const { - return PieceId{static_cast(std::countr_zero(m_raw))}; - } + [[nodiscard]] PieceId lsb() const { return PieceId{static_cast(std::countr_zero(m_raw))}; } - [[nodiscard]] u16 value() const { - return m_raw; - } + [[nodiscard]] u16 value() const { return m_raw; } - [[nodiscard]] bool is_set(PieceId id) const { - return (m_raw >> id.raw) & 1; - } + [[nodiscard]] bool is_set(PieceId id) const { return (m_raw >> id.raw) & 1; } - void clear(PieceId id) { - m_raw &= ~id.to_piece_mask().m_raw; - } + void clear(PieceId id) { m_raw &= ~id.to_piece_mask().m_raw; } - void set(PieceId id) { - m_raw |= id.to_piece_mask().m_raw; - } + void set(PieceId id) { m_raw |= id.to_piece_mask().m_raw; } void set(PieceId id, bool value) { if (value) { @@ -93,9 +73,7 @@ struct PieceMask { return *this; } - PieceId operator*() const { - return PieceId{static_cast(std::countr_zero(m_raw))}; - } + PieceId operator*() const { return PieceId{static_cast(std::countr_zero(m_raw))}; } bool operator==(const Iterator&) const = default; @@ -103,25 +81,18 @@ struct PieceMask { friend struct PieceMask; explicit constexpr Iterator(u16 raw) : - m_raw(raw) { - } + m_raw(raw) {} u16 m_raw; }; - [[nodiscard]] Iterator begin() const { - return Iterator{m_raw}; - } + [[nodiscard]] Iterator begin() const { return Iterator{m_raw}; } - [[nodiscard]] Iterator end() const { - return Iterator{0}; - } + [[nodiscard]] Iterator end() const { return Iterator{0}; } bool operator==(const PieceMask&) const = default; - friend constexpr PieceMask operator~(PieceMask a) { - return PieceMask{static_cast(~a.m_raw)}; - } + friend constexpr PieceMask operator~(PieceMask a) { return PieceMask{static_cast(~a.m_raw)}; } friend constexpr PieceMask operator&(PieceMask a, PieceMask b) { return PieceMask{static_cast(a.m_raw & b.m_raw)}; } @@ -129,12 +100,8 @@ struct PieceMask { return PieceMask{static_cast(a.m_raw | b.m_raw)}; } - friend constexpr PieceMask& operator&=(PieceMask& a, PieceMask b) { - return a = a & b; - } - friend constexpr PieceMask& operator|=(PieceMask& a, PieceMask b) { - return a = a | b; - } + friend constexpr PieceMask& operator&=(PieceMask& a, PieceMask b) { return a = a & b; } + friend constexpr PieceMask& operator|=(PieceMask& a, PieceMask b) { return a = a | b; } private: u16 m_raw = 0; @@ -149,9 +116,7 @@ static_assert(sizeof(PieceMask) == sizeof(u16)); struct Place { u8 raw = 0; - static constexpr Place empty() { - return {}; - } + static constexpr Place empty() { return {}; } static constexpr i32 PTYPE_SHIFT = 5; static constexpr u8 PTYPE_MASK = 0xE0; @@ -162,22 +127,16 @@ struct Place { constexpr Place() = default; constexpr Place(Color color, PieceType pt, PieceId id) { - raw = static_cast((static_cast(color) << COLOR_SHIFT) - | (static_cast(pt) << PTYPE_SHIFT) | id.raw); + raw = + static_cast((static_cast(color) << COLOR_SHIFT) | (static_cast(pt) << PTYPE_SHIFT) | id.raw); } - [[nodiscard]] constexpr bool is_empty() const { - return raw == 0; - } - [[nodiscard]] constexpr Color color() const { - return static_cast((raw & COLOR_MASK) != 0); - } + [[nodiscard]] constexpr bool is_empty() const { return raw == 0; } + [[nodiscard]] constexpr Color color() const { return static_cast((raw & COLOR_MASK) != 0); } [[nodiscard]] constexpr PieceType ptype() const { return static_cast((raw & PTYPE_MASK) >> PTYPE_SHIFT); } - [[nodiscard]] constexpr PieceId id() const { - return PieceId{static_cast(raw & ID_MASK)}; - } + [[nodiscard]] constexpr PieceId id() const { return PieceId{static_cast(raw & ID_MASK)}; } [[nodiscard]] constexpr char to_char() const { constexpr std::array STR{{".PNBRQK", ".pnbrqk"}}; @@ -192,23 +151,16 @@ static_assert(sizeof(Place) == sizeof(u8)); struct Byteboard { std::array mailbox; - [[nodiscard]] u8x64 to_vector() const { - return std::bit_cast(mailbox); - } + [[nodiscard]] u8x64 to_vector() const { return std::bit_cast(mailbox); } - [[nodiscard]] Bitboard get_empty_bitboard() const { - return Bitboard{to_vector().zeros().to_bits()}; - } + [[nodiscard]] Bitboard get_empty_bitboard() const { return Bitboard{to_vector().zeros().to_bits()}; } - [[nodiscard]] Bitboard get_occupied_bitboard() const { - return Bitboard{to_vector().nonzeros().to_bits()}; - } + [[nodiscard]] Bitboard get_occupied_bitboard() const { return Bitboard{to_vector().nonzeros().to_bits()}; } [[nodiscard]] Bitboard get_color_bitboard(Color color) const { u64 color_bb = static_cast(0) - static_cast(color); auto vec = to_vector(); - return Bitboard{~vec.test(u8x64::splat(0x10)).to_bits() ^ color_bb} - & get_occupied_bitboard(); + return Bitboard{~vec.test(u8x64::splat(0x10)).to_bits() ^ color_bb} & get_occupied_bitboard(); } [[nodiscard]] Bitboard bitboard_for(Color color, PieceType ptype) const { @@ -218,17 +170,12 @@ struct Byteboard { [[nodiscard]] Bitboard bitboard_for(PieceType ptype) const { Place p{Color::White, ptype, PieceId{0}}; - return Bitboard{ - (to_vector() & u8x64::splat(Place::PTYPE_MASK)).eq(u8x64::splat(p.raw)).to_bits()}; + return Bitboard{(to_vector() & u8x64::splat(Place::PTYPE_MASK)).eq(u8x64::splat(p.raw)).to_bits()}; } - constexpr Place& operator[](Square sq) { - return mailbox[sq.raw]; - } + constexpr Place& operator[](Square sq) { return mailbox[sq.raw]; } - constexpr Place operator[](Square sq) const { - return mailbox[sq.raw]; - } + constexpr Place operator[](Square sq) const { return mailbox[sq.raw]; } bool operator==(const Byteboard& other) const = default; }; @@ -238,13 +185,9 @@ static_assert(sizeof(Byteboard) == 64); struct Wordboard { u16x64 raw = u16x64::zero(); - [[nodiscard]] std::array to_mailbox() const { - return std::bit_cast>(raw); - } + [[nodiscard]] std::array to_mailbox() const { return std::bit_cast>(raw); } - [[nodiscard]] Bitboard get_attacked_bitboard() const { - return Bitboard{raw.nonzeros().to_bits()}; - } + [[nodiscard]] Bitboard get_attacked_bitboard() const { return Bitboard{raw.nonzeros().to_bits()}; } [[nodiscard]] Bitboard get_piece_mask_bitboard(PieceMask piece_mask) const { u16x64 pm = u16x64::splat(piece_mask.value()); @@ -258,8 +201,7 @@ struct Wordboard { [[nodiscard]] PieceMask read(Square sq) const { PieceMask value; - std::memcpy(&value, reinterpret_cast(&raw) + sq.raw * sizeof(PieceMask), - sizeof(PieceMask)); + std::memcpy(&value, reinterpret_cast(&raw) + sq.raw * sizeof(PieceMask), sizeof(PieceMask)); return value; } @@ -271,9 +213,7 @@ struct Wordboard { return count; } - friend inline Wordboard operator&(const Wordboard& a, const Wordboard& b) { - return Wordboard{a.raw & b.raw}; - } + friend inline Wordboard operator&(const Wordboard& a, const Wordboard& b) { return Wordboard{a.raw & b.raw}; } bool operator==(const Wordboard& other) const = default; friend std::ostream& operator<<(std::ostream& os, const Wordboard& at); diff --git a/src/dbg_tools.cpp b/src/dbg_tools.cpp index ed041319..69e2fa75 100644 --- a/src/dbg_tools.cpp +++ b/src/dbg_tools.cpp @@ -68,12 +68,10 @@ void dbg_extremes_of(int64_t value, size_t slot) { ++extremes.at(slot)[0]; int64_t current_max = extremes.at(slot)[1].load(); - while (current_max < value && !extremes.at(slot)[1].compare_exchange_weak(current_max, value)) { - } + while (current_max < value && !extremes.at(slot)[1].compare_exchange_weak(current_max, value)) {} int64_t current_min = extremes.at(slot)[2].load(); - while (current_min > value && !extremes.at(slot)[2].compare_exchange_weak(current_min, value)) { - } + while (current_min > value && !extremes.at(slot)[2].compare_exchange_weak(current_min, value)) {} } void dbg_correl_of(int64_t value1, int64_t value2, size_t slot) { @@ -89,17 +87,13 @@ void dbg_correl_of(int64_t value1, int64_t value2, size_t slot) { void dbg_print() { int64_t n; - auto e = [&n](int64_t x) { - return static_cast(x) / static_cast(n); - }; - auto sqr = [](double x) { - return x * x; - }; + auto e = [&n](int64_t x) { return static_cast(x) / static_cast(n); }; + auto sqr = [](double x) { return x * x; }; for (size_t i = 0; i < MAX_DEBUG_SLOTS; ++i) { if ((n = hit[i][0])) { - std::cerr << "Hit #" << i << ": Total " << n << " Hits " << hit[i][1] - << " Hit Rate (%) " << 100.0 * e(hit[i][1]) << std::endl; + std::cerr << "Hit #" << i << ": Total " << n << " Hits " << hit[i][1] << " Hit Rate (%) " + << 100.0 * e(hit[i][1]) << std::endl; } } @@ -118,16 +112,15 @@ void dbg_print() { for (size_t i = 0; i < MAX_DEBUG_SLOTS; ++i) { if ((n = extremes[i][0])) { - std::cerr << "Extremity #" << i << ": Total " << n << " Min " << extremes[i][2] - << " Max " << extremes[i][1] << std::endl; + std::cerr << "Extremity #" << i << ": Total " << n << " Min " << extremes[i][2] << " Max " << extremes[i][1] + << std::endl; } } for (size_t i = 0; i < MAX_DEBUG_SLOTS; ++i) { if ((n = correl[i][0])) { double r = (e(correl[i][5]) - e(correl[i][1]) * e(correl[i][3])) - / (sqrt(e(correl[i][2]) - sqr(e(correl[i][1]))) - * sqrt(e(correl[i][4]) - sqr(e(correl[i][3])))); + / (sqrt(e(correl[i][2]) - sqr(e(correl[i][1]))) * sqrt(e(correl[i][4]) - sqr(e(correl[i][3])))); std::cerr << "Correl. #" << i << ": Total " << n << " Coefficient " << r << std::endl; } } diff --git a/src/eval_types.hpp b/src/eval_types.hpp index 8262a951..a8c1b8d2 100644 --- a/src/eval_types.hpp +++ b/src/eval_types.hpp @@ -21,20 +21,16 @@ class PScore { private: i32 m_score; explicit constexpr PScore(i32 score) : - m_score{score} { - } + m_score{score} {} public: constexpr PScore() : - m_score{} { - } + m_score{} {} constexpr PScore(Score midgame, Score endgame) : m_score{static_cast(static_cast(endgame) << 16) + midgame} { - assert(std::numeric_limits::min() <= midgame - && std::numeric_limits::max() >= midgame); - assert(std::numeric_limits::min() <= endgame - && std::numeric_limits::max() >= endgame); + assert(std::numeric_limits::min() <= midgame && std::numeric_limits::max() >= midgame); + assert(std::numeric_limits::min() <= endgame && std::numeric_limits::max() >= endgame); } [[nodiscard]] inline auto mg() const { @@ -55,42 +51,32 @@ class PScore { return static_cast(v); } - [[nodiscard]] constexpr auto operator+(const PScore& other) const { - return PScore{m_score + other.m_score}; - } + [[nodiscard]] constexpr auto operator+(const PScore& other) const { return PScore{m_score + other.m_score}; } constexpr auto operator+=(const PScore& other) -> auto& { m_score += other.m_score; return *this; } - [[nodiscard]] constexpr auto operator-(const PScore& other) const { - return PScore{m_score - other.m_score}; - } + [[nodiscard]] constexpr auto operator-(const PScore& other) const { return PScore{m_score - other.m_score}; } constexpr auto operator-=(const PScore& other) -> auto& { m_score -= other.m_score; return *this; } - [[nodiscard]] constexpr auto operator*(i32 v) const { - return PScore{m_score * v}; - } + [[nodiscard]] constexpr auto operator*(i32 v) const { return PScore{m_score * v}; } constexpr auto operator*=(i32 v) -> auto& { m_score *= v; return *this; } - [[nodiscard]] constexpr auto operator-() const { - return PScore{-m_score}; - } + [[nodiscard]] constexpr auto operator-() const { return PScore{-m_score}; } [[nodiscard]] constexpr bool operator==(const PScore& other) const = default; - [[nodiscard]] constexpr const PScore* operator->() const { - return this; - } + [[nodiscard]] constexpr const PScore* operator->() const { return this; } // Phasing between two scores template diff --git a/src/evaltune_main.cpp b/src/evaltune_main.cpp index 0568a660..fb49b256 100644 --- a/src/evaltune_main.cpp +++ b/src/evaltune_main.cpp @@ -55,8 +55,7 @@ int main() { if (parsed) { positions.push_back(*parsed); } else { - std::cerr << "Failed to parse FEN in file " << filename << ": " << fen - << std::endl; + std::cerr << "Failed to parse FEN in file " << filename << ": " << fen << std::endl; continue; } @@ -70,8 +69,8 @@ int main() { } else if (result == "b") { results.push_back(0.0); } else { - std::cerr << "Invalid result in file " << filename << " line: " << line - << " (result is '" << result << "')" << std::endl; + std::cerr << "Invalid result in file " << filename << " line: " << line << " (result is '" << result + << "')" << std::endl; } } else { std::cerr << "Invalid line format in " << filename << ": " << line << std::endl; @@ -82,8 +81,7 @@ int main() { } // Print the number of positions loaded - std::cout << "Loaded " << positions.size() << " FENs from " << fenFiles.size() << " files." - << std::endl; + std::cout << "Loaded " << positions.size() << " FENs from " << fenFiles.size() << " files." << std::endl; if (positions.size() == 0) { std::cerr << "No positions loaded!" << std::endl; @@ -127,15 +125,14 @@ int main() { epoch_barrier.arrive_and_wait(); - for (size_t batch_start = 0; batch_start < positions.size(); - batch_start += batch_size) { + for (size_t batch_start = 0; batch_start < positions.size(); batch_start += batch_size) { - size_t batch_end = std::min(batch_start + batch_size, positions.size()); + size_t batch_end = std::min(batch_start + batch_size, positions.size()); size_t current_batch_size = batch_end - batch_start; - size_t subbatch_size = (current_batch_size + thread_count - 1) / thread_count; + size_t subbatch_size = (current_batch_size + thread_count - 1) / thread_count; - size_t subbatch_start = batch_start + subbatch_size * thread_idx; - size_t subbatch_end = std::min(subbatch_start + subbatch_size, batch_end); + size_t subbatch_start = batch_start + subbatch_size * thread_idx; + size_t subbatch_end = std::min(subbatch_start + subbatch_size, batch_end); size_t current_subbatch_size = subbatch_end - subbatch_start; subbatch_outputs.clear(); @@ -154,10 +151,9 @@ int main() { subbatch_outputs.push_back(result); subbatch_targets.push_back(y); if (++i == 1024) { - i = 0; - auto subbatch_loss = - mse(subbatch_outputs, subbatch_targets) - * Autograd::Value::create(1.0 / static_cast(current_batch_size)); + i = 0; + auto subbatch_loss = mse(subbatch_outputs, subbatch_targets) + * Autograd::Value::create(1.0 / static_cast(current_batch_size)); Graph::get().backward(); Graph::get().clear_backwardables(); subbatch_outputs.clear(); @@ -165,9 +161,8 @@ int main() { } } - auto subbatch_loss = - mse(subbatch_outputs, subbatch_targets) - * Autograd::Value::create(1.0 / static_cast(current_batch_size)); + auto subbatch_loss = mse(subbatch_outputs, subbatch_targets) + * Autograd::Value::create(1.0 / static_cast(current_batch_size)); Graph::get().backward(); Parameters subbatch_gradients = Graph::get().get_all_parameter_gradients(); @@ -219,40 +214,28 @@ int main() { std::cout << "inline const PParam TEMPO_VAL = " << TEMPO_VAL << ";" << std::endl; std::cout << std::endl; - std::cout << "inline const PParam BISHOP_PAIR_VAL = " << BISHOP_PAIR_VAL << ";" - << std::endl; - std::cout << "inline const PParam ROOK_OPEN_VAL = " << ROOK_OPEN_VAL << ";" - << std::endl; - std::cout << "inline const PParam ROOK_SEMIOPEN_VAL = " << ROOK_SEMIOPEN_VAL << ";" - << std::endl; + std::cout << "inline const PParam BISHOP_PAIR_VAL = " << BISHOP_PAIR_VAL << ";" << std::endl; + std::cout << "inline const PParam ROOK_OPEN_VAL = " << ROOK_OPEN_VAL << ";" << std::endl; + std::cout << "inline const PParam ROOK_SEMIOPEN_VAL = " << ROOK_SEMIOPEN_VAL << ";" << std::endl; std::cout << std::endl; - std::cout << "inline const PParam DOUBLED_PAWN_VAL = " << DOUBLED_PAWN_VAL << ";" - << std::endl; + std::cout << "inline const PParam DOUBLED_PAWN_VAL = " << DOUBLED_PAWN_VAL << ";" << std::endl; std::cout << std::endl; - std::cout << "inline const PParam POTENTIAL_CHECKER_VAL = " << POTENTIAL_CHECKER_VAL << ";" - << std::endl; + std::cout << "inline const PParam POTENTIAL_CHECKER_VAL = " << POTENTIAL_CHECKER_VAL << ";" << std::endl; - std::cout << "inline const PParam OUTPOST_KNIGHT_VAL = " << OUTPOST_KNIGHT_VAL << ";" - << std::endl; - std::cout << "inline const PParam OUTPOST_BISHOP_VAL = " << OUTPOST_BISHOP_VAL << ";" - << std::endl; + std::cout << "inline const PParam OUTPOST_KNIGHT_VAL = " << OUTPOST_KNIGHT_VAL << ";" << std::endl; + std::cout << "inline const PParam OUTPOST_BISHOP_VAL = " << OUTPOST_BISHOP_VAL << ";" << std::endl; std::cout << std::endl; - std::cout << "inline const PParam PAWN_PUSH_THREAT_KNIGHT = " << PAWN_PUSH_THREAT_KNIGHT - << ";" << std::endl; - std::cout << "inline const PParam PAWN_PUSH_THREAT_BISHOP = " << PAWN_PUSH_THREAT_BISHOP - << ";" << std::endl; - std::cout << "inline const PParam PAWN_PUSH_THREAT_ROOK = " << PAWN_PUSH_THREAT_ROOK - << ";" << std::endl; - std::cout << "inline const PParam PAWN_PUSH_THREAT_QUEEN = " << PAWN_PUSH_THREAT_QUEEN - << ";" << std::endl; + std::cout << "inline const PParam PAWN_PUSH_THREAT_KNIGHT = " << PAWN_PUSH_THREAT_KNIGHT << ";" << std::endl; + std::cout << "inline const PParam PAWN_PUSH_THREAT_BISHOP = " << PAWN_PUSH_THREAT_BISHOP << ";" << std::endl; + std::cout << "inline const PParam PAWN_PUSH_THREAT_ROOK = " << PAWN_PUSH_THREAT_ROOK << ";" << std::endl; + std::cout << "inline const PParam PAWN_PUSH_THREAT_QUEEN = " << PAWN_PUSH_THREAT_QUEEN << ";" << std::endl; std::cout << std::endl; auto print_table = [](const std::string& name, const auto& table) { - std::cout << "inline const std::array " << name - << " = {" << std::endl + std::cout << "inline const std::array " << name << " = {" << std::endl << " "; for (const auto& val : table) { std::cout << " " << val << ","; @@ -284,38 +267,27 @@ int main() { print_table("QUEEN_KING_RING", QUEEN_KING_RING); std::cout << std::endl; - std::cout << "inline const PParam PAWN_THREAT_KNIGHT = " << PAWN_THREAT_KNIGHT << ";" - << std::endl; - std::cout << "inline const PParam PAWN_THREAT_BISHOP = " << PAWN_THREAT_BISHOP << ";" - << std::endl; - std::cout << "inline const PParam PAWN_THREAT_ROOK = " << PAWN_THREAT_ROOK << ";" - << std::endl; - std::cout << "inline const PParam PAWN_THREAT_QUEEN = " << PAWN_THREAT_QUEEN << ";" - << std::endl; + std::cout << "inline const PParam PAWN_THREAT_KNIGHT = " << PAWN_THREAT_KNIGHT << ";" << std::endl; + std::cout << "inline const PParam PAWN_THREAT_BISHOP = " << PAWN_THREAT_BISHOP << ";" << std::endl; + std::cout << "inline const PParam PAWN_THREAT_ROOK = " << PAWN_THREAT_ROOK << ";" << std::endl; + std::cout << "inline const PParam PAWN_THREAT_QUEEN = " << PAWN_THREAT_QUEEN << ";" << std::endl; std::cout << std::endl; - std::cout << "inline const PParam KNIGHT_THREAT_BISHOP = " << KNIGHT_THREAT_BISHOP << ";" - << std::endl; - std::cout << "inline const PParam KNIGHT_THREAT_ROOK = " << KNIGHT_THREAT_ROOK << ";" - << std::endl; - std::cout << "inline const PParam KNIGHT_THREAT_QUEEN = " << KNIGHT_THREAT_QUEEN << ";" - << std::endl; + std::cout << "inline const PParam KNIGHT_THREAT_BISHOP = " << KNIGHT_THREAT_BISHOP << ";" << std::endl; + std::cout << "inline const PParam KNIGHT_THREAT_ROOK = " << KNIGHT_THREAT_ROOK << ";" << std::endl; + std::cout << "inline const PParam KNIGHT_THREAT_QUEEN = " << KNIGHT_THREAT_QUEEN << ";" << std::endl; std::cout << std::endl; - std::cout << "inline const PParam BISHOP_THREAT_KNIGHT = " << BISHOP_THREAT_KNIGHT << ";" - << std::endl; - std::cout << "inline const PParam BISHOP_THREAT_ROOK = " << BISHOP_THREAT_ROOK << ";" - << std::endl; - std::cout << "inline const PParam BISHOP_THREAT_QUEEN = " << BISHOP_THREAT_QUEEN << ";" - << std::endl; + std::cout << "inline const PParam BISHOP_THREAT_KNIGHT = " << BISHOP_THREAT_KNIGHT << ";" << std::endl; + std::cout << "inline const PParam BISHOP_THREAT_ROOK = " << BISHOP_THREAT_ROOK << ";" << std::endl; + std::cout << "inline const PParam BISHOP_THREAT_QUEEN = " << BISHOP_THREAT_QUEEN << ";" << std::endl; std::cout << std::endl; print_table("BISHOP_PAWNS", BISHOP_PAWNS); std::cout << std::endl; auto printPsqtArray = [](const std::string& name, const auto& arr) { - std::cout << "inline const std::array " << name << " = {" - << std::endl; + std::cout << "inline const std::array " << name << " = {" << std::endl; for (std::size_t i = 0; i < arr.size(); ++i) { if ((i & 7) == 0) { std::cout << " "; @@ -337,8 +309,7 @@ int main() { printPsqtArray("QUEEN_PSQT", QUEEN_PSQT); printPsqtArray("KING_PSQT", KING_PSQT); - std::cout << "// Epoch duration: " - << time::cast(epoch_end_time - epoch_start_time).count() + std::cout << "// Epoch duration: " << time::cast(epoch_end_time - epoch_start_time).count() << "s" << std::endl; if (epoch > 5) { diff --git a/src/evaluation.cpp b/src/evaluation.cpp index 9ac677a1..8db591c4 100644 --- a/src/evaluation.cpp +++ b/src/evaluation.cpp @@ -32,8 +32,8 @@ Bitboard pawn_spans(const Bitboard pawns) { template Bitboard static_pawn_attacks(const Bitboard pawns) { - Bitboard attacks = pawns.shift_relative(color, Direction::NorthEast) - | pawns.shift_relative(color, Direction::NorthWest); + Bitboard attacks = + pawns.shift_relative(color, Direction::NorthEast) | pawns.shift_relative(color, Direction::NorthWest); return attacks; } @@ -105,14 +105,11 @@ PScore evaluate_pawns(const Position& pos) { Bitboard stoppers = opp_pawns & passed_pawn_spans[static_cast(color)][sq.raw]; if (stoppers.empty()) { eval += PASSED_PAWN[static_cast(sq.relative_sq(color).rank() - RANK_2)]; - if (pos.attack_table(color).read(push).popcount() - > pos.attack_table(them).read(push).popcount()) { - eval += - DEFENDED_PASSED_PUSH[static_cast(sq.relative_sq(color).rank() - RANK_2)]; + if (pos.attack_table(color).read(push).popcount() > pos.attack_table(them).read(push).popcount()) { + eval += DEFENDED_PASSED_PUSH[static_cast(sq.relative_sq(color).rank() - RANK_2)]; } if (pos.piece_at(push) != PieceType::None) { - eval += - BLOCKED_PASSED_PAWN[static_cast(sq.relative_sq(color).rank() - RANK_2)]; + eval += BLOCKED_PASSED_PAWN[static_cast(sq.relative_sq(color).rank() - RANK_2)]; } i32 our_king_dist = chebyshev_distance(our_king, sq); @@ -148,17 +145,12 @@ PScore evaluate_pawn_push_threats(const Position& pos) { Bitboard push_attacks = pushable.shift_relative(color, Direction::North).shift_relative(color, Direction::NorthEast) - | pushable.shift_relative(color, Direction::North) - .shift_relative(color, Direction::NorthWest); + | pushable.shift_relative(color, Direction::North).shift_relative(color, Direction::NorthWest); - eval += PAWN_PUSH_THREAT_KNIGHT - * (push_attacks & pos.bitboard_for(opp, PieceType::Knight)).ipopcount(); - eval += PAWN_PUSH_THREAT_BISHOP - * (push_attacks & pos.bitboard_for(opp, PieceType::Bishop)).ipopcount(); - eval += - PAWN_PUSH_THREAT_ROOK * (push_attacks & pos.bitboard_for(opp, PieceType::Rook)).ipopcount(); - eval += - PAWN_PUSH_THREAT_QUEEN * (push_attacks & pos.bitboard_for(opp, PieceType::Queen)).ipopcount(); + eval += PAWN_PUSH_THREAT_KNIGHT * (push_attacks & pos.bitboard_for(opp, PieceType::Knight)).ipopcount(); + eval += PAWN_PUSH_THREAT_BISHOP * (push_attacks & pos.bitboard_for(opp, PieceType::Bishop)).ipopcount(); + eval += PAWN_PUSH_THREAT_ROOK * (push_attacks & pos.bitboard_for(opp, PieceType::Rook)).ipopcount(); + eval += PAWN_PUSH_THREAT_QUEEN * (push_attacks & pos.bitboard_for(opp, PieceType::Queen)).ipopcount(); return eval; } @@ -168,14 +160,12 @@ PScore evaluate_pieces(const Position& pos) { constexpr Color opp = ~color; PScore eval = PSCORE_ZERO; Bitboard own_pawns = pos.bitboard_for(color, PieceType::Pawn); - Bitboard blocked_pawns = - own_pawns & pos.board().get_occupied_bitboard().shift_relative(color, Direction::South); - constexpr Bitboard early_ranks = color == Color::White - ? Bitboard::rank_mask(1) | Bitboard::rank_mask(2) - : Bitboard::rank_mask(5) | Bitboard::rank_mask(6); + Bitboard blocked_pawns = own_pawns & pos.board().get_occupied_bitboard().shift_relative(color, Direction::South); + constexpr Bitboard early_ranks = color == Color::White ? Bitboard::rank_mask(1) | Bitboard::rank_mask(2) + : Bitboard::rank_mask(5) | Bitboard::rank_mask(6); Bitboard own_early_pawns = own_pawns & early_ranks; - Bitboard bb = (blocked_pawns | own_early_pawns) | pos.attacked_by(opp, PieceType::Pawn); - Bitboard opp_king_ring = king_ring_table[pos.king_sq(opp).raw]; + Bitboard bb = (blocked_pawns | own_early_pawns) | pos.attacked_by(opp, PieceType::Pawn); + Bitboard opp_king_ring = king_ring_table[pos.king_sq(opp).raw]; for (PieceId id : pos.get_piece_mask(color, PieceType::Knight)) { eval += KNIGHT_MOBILITY[pos.mobility_of(color, id, ~bb)]; eval += KNIGHT_KING_RING[pos.mobility_of(color, id, opp_king_ring)]; @@ -184,10 +174,9 @@ PScore evaluate_pieces(const Position& pos) { eval += BISHOP_MOBILITY[pos.mobility_of(color, id, ~bb)]; eval += BISHOP_KING_RING[pos.mobility_of(color, id, opp_king_ring)]; Square sq = pos.piece_list_sq(color)[id]; - eval += BISHOP_PAWNS[std::min( - static_cast(8), - (own_pawns & Bitboard::squares_of_color(sq.color())) - .popcount()) // Weird non standard positions which can have more than 8 pawns + eval += BISHOP_PAWNS[std::min(static_cast(8), + (own_pawns & Bitboard::squares_of_color(sq.color())) + .popcount()) // Weird non standard positions which can have more than 8 pawns ] * (1 + (blocked_pawns & Bitboard::central_files()).ipopcount()); } for (PieceId id : pos.get_piece_mask(color, PieceType::Rook)) { @@ -216,25 +205,21 @@ PScore evaluate_outposts(const Position& pos) { // - additional conditions will be added as we go constexpr Color opp = ~color; constexpr Bitboard viable_outposts_ranks = - color == Color::White - ? Bitboard::rank_mask(3) | Bitboard::rank_mask(4) | Bitboard::rank_mask(5) - : Bitboard::rank_mask(2) | Bitboard::rank_mask(3) | Bitboard::rank_mask(4); + color == Color::White ? Bitboard::rank_mask(3) | Bitboard::rank_mask(4) | Bitboard::rank_mask(5) + : Bitboard::rank_mask(2) | Bitboard::rank_mask(3) | Bitboard::rank_mask(4); // Get enemy pawns to calculate the attacks and attack spans Bitboard opp_pawns = pos.bitboard_for(opp, PieceType::Pawn); Bitboard opp_pawn_span = pawn_spans(opp_pawns); Bitboard opp_pawn_span_attacks = static_pawn_attacks( opp_pawns); // Note, this does NOT consider pins! Might need to test this more thoroughly. Bitboard pawn_defended_squares = pos.attacked_by(color, PieceType::Pawn); - Bitboard viable_outposts = - viable_outposts_ranks & pawn_defended_squares & ~opp_pawn_span_attacks; + Bitboard viable_outposts = viable_outposts_ranks & pawn_defended_squares & ~opp_pawn_span_attacks; // Check for minor pieces on outposts PScore eval = PSCORE_ZERO; eval += - OUTPOST_KNIGHT_VAL - * static_cast((pos.bitboard_for(color, PieceType::Knight) & viable_outposts).popcount()); + OUTPOST_KNIGHT_VAL * static_cast((pos.bitboard_for(color, PieceType::Knight) & viable_outposts).popcount()); eval += - OUTPOST_BISHOP_VAL - * static_cast((pos.bitboard_for(color, PieceType::Bishop) & viable_outposts).popcount()); + OUTPOST_BISHOP_VAL * static_cast((pos.bitboard_for(color, PieceType::Bishop) & viable_outposts).popcount()); return eval; } @@ -266,71 +251,54 @@ PScore evaluate_threats(const Position& pos) { PScore eval = PSCORE_ZERO; Bitboard pawn_attacks = pos.attacked_by(color, PieceType::Pawn); - eval += - PAWN_THREAT_KNIGHT * (pos.bitboard_for(opp, PieceType::Knight) & pawn_attacks).ipopcount(); - eval += - PAWN_THREAT_BISHOP * (pos.bitboard_for(opp, PieceType::Bishop) & pawn_attacks).ipopcount(); + eval += PAWN_THREAT_KNIGHT * (pos.bitboard_for(opp, PieceType::Knight) & pawn_attacks).ipopcount(); + eval += PAWN_THREAT_BISHOP * (pos.bitboard_for(opp, PieceType::Bishop) & pawn_attacks).ipopcount(); eval += PAWN_THREAT_ROOK * (pos.bitboard_for(opp, PieceType::Rook) & pawn_attacks).ipopcount(); - eval += - PAWN_THREAT_QUEEN * (pos.bitboard_for(opp, PieceType::Queen) & pawn_attacks).ipopcount(); + eval += PAWN_THREAT_QUEEN * (pos.bitboard_for(opp, PieceType::Queen) & pawn_attacks).ipopcount(); Bitboard knight_attacks = pos.attacked_by(color, PieceType::Knight); - eval += KNIGHT_THREAT_BISHOP - * (pos.bitboard_for(opp, PieceType::Bishop) & knight_attacks).ipopcount(); - eval += - KNIGHT_THREAT_ROOK * (pos.bitboard_for(opp, PieceType::Rook) & knight_attacks).ipopcount(); - eval += - KNIGHT_THREAT_QUEEN * (pos.bitboard_for(opp, PieceType::Queen) & knight_attacks).ipopcount(); + eval += KNIGHT_THREAT_BISHOP * (pos.bitboard_for(opp, PieceType::Bishop) & knight_attacks).ipopcount(); + eval += KNIGHT_THREAT_ROOK * (pos.bitboard_for(opp, PieceType::Rook) & knight_attacks).ipopcount(); + eval += KNIGHT_THREAT_QUEEN * (pos.bitboard_for(opp, PieceType::Queen) & knight_attacks).ipopcount(); Bitboard bishop_attacks = pos.attacked_by(color, PieceType::Bishop); - eval += BISHOP_THREAT_KNIGHT - * (pos.bitboard_for(opp, PieceType::Knight) & bishop_attacks).ipopcount(); - eval += - BISHOP_THREAT_ROOK * (pos.bitboard_for(opp, PieceType::Rook) & bishop_attacks).ipopcount(); - eval += - BISHOP_THREAT_QUEEN * (pos.bitboard_for(opp, PieceType::Queen) & bishop_attacks).ipopcount(); + eval += BISHOP_THREAT_KNIGHT * (pos.bitboard_for(opp, PieceType::Knight) & bishop_attacks).ipopcount(); + eval += BISHOP_THREAT_ROOK * (pos.bitboard_for(opp, PieceType::Rook) & bishop_attacks).ipopcount(); + eval += BISHOP_THREAT_QUEEN * (pos.bitboard_for(opp, PieceType::Queen) & bishop_attacks).ipopcount(); return eval; } template PScore evaluate_space(const Position& pos) { - PScore eval = PSCORE_ZERO; - constexpr Color them = color == Color::White ? Color::Black : Color::White; - Bitboard ourfiles = Bitboard::fill_verticals(pos.bitboard_for(color, PieceType::Pawn)); - Bitboard theirfiles = Bitboard::fill_verticals(pos.bitboard_for(them, PieceType::Pawn)); - Bitboard openfiles = ~(ourfiles | theirfiles); + PScore eval = PSCORE_ZERO; + constexpr Color them = color == Color::White ? Color::Black : Color::White; + Bitboard ourfiles = Bitboard::fill_verticals(pos.bitboard_for(color, PieceType::Pawn)); + Bitboard theirfiles = Bitboard::fill_verticals(pos.bitboard_for(them, PieceType::Pawn)); + Bitboard openfiles = ~(ourfiles | theirfiles); Bitboard half_open_files = (~ourfiles) & theirfiles; eval += ROOK_OPEN_VAL * (openfiles & pos.bitboard_for(color, PieceType::Rook)).ipopcount(); - eval += - ROOK_SEMIOPEN_VAL * (half_open_files & pos.bitboard_for(color, PieceType::Rook)).ipopcount(); + eval += ROOK_SEMIOPEN_VAL * (half_open_files & pos.bitboard_for(color, PieceType::Rook)).ipopcount(); return eval; } Score evaluate_white_pov(const Position& pos, const PsqtState& psqt_state) { - const Color us = pos.active_color(); - usize phase = pos.piece_count(Color::White, PieceType::Knight) - + pos.piece_count(Color::Black, PieceType::Knight) - + pos.piece_count(Color::White, PieceType::Bishop) - + pos.piece_count(Color::Black, PieceType::Bishop) - + 2 - * (pos.piece_count(Color::White, PieceType::Rook) - + pos.piece_count(Color::Black, PieceType::Rook)) - + 4 - * (pos.piece_count(Color::White, PieceType::Queen) - + pos.piece_count(Color::Black, PieceType::Queen)); + const Color us = pos.active_color(); + usize phase = + pos.piece_count(Color::White, PieceType::Knight) + pos.piece_count(Color::Black, PieceType::Knight) + + pos.piece_count(Color::White, PieceType::Bishop) + pos.piece_count(Color::Black, PieceType::Bishop) + + 2 * (pos.piece_count(Color::White, PieceType::Rook) + pos.piece_count(Color::Black, PieceType::Rook)) + + 4 * (pos.piece_count(Color::White, PieceType::Queen) + pos.piece_count(Color::Black, PieceType::Queen)); phase = std::min(phase, 24); PScore eval = psqt_state.score(); eval += evaluate_pieces(pos) - evaluate_pieces(pos); eval += evaluate_pawns(pos) - evaluate_pawns(pos); - eval += - evaluate_pawn_push_threats(pos) - evaluate_pawn_push_threats(pos); - eval += evaluate_potential_checkers(pos) - - evaluate_potential_checkers(pos); + eval += evaluate_pawn_push_threats(pos) - evaluate_pawn_push_threats(pos); + eval += evaluate_potential_checkers(pos) - evaluate_potential_checkers(pos); eval += evaluate_threats(pos) - evaluate_threats(pos); eval += evaluate_space(pos) - evaluate_space(pos); eval += evaluate_outposts(pos) - evaluate_outposts(pos); diff --git a/src/history.cpp b/src/history.cpp index e6c83bed..1445da52 100644 --- a/src/history.cpp +++ b/src/history.cpp @@ -28,39 +28,32 @@ i32 History::get_conthist(const Position& pos, Move move, i32 ply, Search::Stack i32 History::get_quiet_stats(const Position& pos, Move move, i32 ply, Search::Stack* ss) const { auto to_attacked = pos.is_square_attacked_by(move.to(), ~pos.active_color()); auto from_attacked = pos.is_square_attacked_by(move.from(), ~pos.active_color()); - i32 stats = m_main_hist[static_cast(pos.active_color())][move.from_to()] - [from_attacked * 2 + to_attacked]; + i32 stats = m_main_hist[static_cast(pos.active_color())][move.from_to()][from_attacked * 2 + to_attacked]; stats += 2 * get_conthist(pos, move, ply, ss); return stats; } -void History::update_cont_hist( - const Position& pos, Move move, i32 ply, Search::Stack* ss, i32 bonus) { +void History::update_cont_hist(const Position& pos, Move move, i32 ply, Search::Stack* ss, i32 bonus) { i32 conthist = get_conthist(pos, move, ply, ss); PieceType pt = pos.piece_at(move.from()); usize pt_idx = static_cast(pt) - static_cast(PieceType::Pawn); usize stm_idx = static_cast(pos.active_color()); if (ply >= 1 && (ss - 1)->cont_hist_entry != nullptr) { - update_hist_entry_banger((*(ss - 1)->cont_hist_entry)[stm_idx][pt_idx][move.to().raw], - conthist, bonus); + update_hist_entry_banger((*(ss - 1)->cont_hist_entry)[stm_idx][pt_idx][move.to().raw], conthist, bonus); } if (ply >= 2 && (ss - 2)->cont_hist_entry != nullptr) { - update_hist_entry_banger((*(ss - 2)->cont_hist_entry)[stm_idx][pt_idx][move.to().raw], - conthist, bonus); + update_hist_entry_banger((*(ss - 2)->cont_hist_entry)[stm_idx][pt_idx][move.to().raw], conthist, bonus); } if (ply >= 4 && (ss - 4)->cont_hist_entry != nullptr) { - update_hist_entry_banger((*(ss - 4)->cont_hist_entry)[stm_idx][pt_idx][move.to().raw], - conthist, bonus); + update_hist_entry_banger((*(ss - 4)->cont_hist_entry)[stm_idx][pt_idx][move.to().raw], conthist, bonus); } if (ply >= 6 && (ss - 6)->cont_hist_entry != nullptr) { - update_hist_entry_banger((*(ss - 6)->cont_hist_entry)[stm_idx][pt_idx][move.to().raw], - conthist, bonus); + update_hist_entry_banger((*(ss - 6)->cont_hist_entry)[stm_idx][pt_idx][move.to().raw], conthist, bonus); } } -void History::update_quiet_stats( - const Position& pos, Move move, i32 ply, Search::Stack* ss, i32 bonus) { +void History::update_quiet_stats(const Position& pos, Move move, i32 ply, Search::Stack* ss, i32 bonus) { auto to_attacked = pos.is_square_attacked_by(move.to(), ~pos.active_color()); auto from_attacked = pos.is_square_attacked_by(move.from(), ~pos.active_color()); usize stm_idx = static_cast(pos.active_color()); @@ -81,34 +74,29 @@ void History::update_noisy_stats(const Position& pos, Move move, i32 bonus) { PieceType pt = pos.piece_at(move.from()); usize pt_idx = static_cast(pt) - static_cast(PieceType::Pawn); PieceType captured = move.is_en_passant() ? PieceType::Pawn : pos.piece_at(move.to()); - update_hist_entry(m_capt_hist[stm_idx][pt_idx][static_cast(captured)][move.to().raw], - bonus); + update_hist_entry(m_capt_hist[stm_idx][pt_idx][static_cast(captured)][move.to().raw], bonus); } void History::update_correction_history(const Position& pos, i32 depth, i32 diff) { - usize side_index = static_cast(pos.active_color()); - u64 pawn_key = pos.get_pawn_key(); - u64 white_non_pawn_key = pos.get_non_pawn_key(Color::White); - u64 black_non_pawn_key = pos.get_non_pawn_key(Color::Black); - u64 major_key = pos.get_major_key(); - u64 minor_key = pos.get_minor_key(); - usize pawn_index = static_cast(pawn_key % CORRECTION_HISTORY_ENTRY_NB); - usize white_non_pawn_index = - static_cast(white_non_pawn_key % CORRECTION_HISTORY_ENTRY_NB); - usize black_non_pawn_index = - static_cast(black_non_pawn_key % CORRECTION_HISTORY_ENTRY_NB); - usize major_index = static_cast(major_key % CORRECTION_HISTORY_ENTRY_NB); - usize minor_index = static_cast(minor_key % CORRECTION_HISTORY_ENTRY_NB); + usize side_index = static_cast(pos.active_color()); + u64 pawn_key = pos.get_pawn_key(); + u64 white_non_pawn_key = pos.get_non_pawn_key(Color::White); + u64 black_non_pawn_key = pos.get_non_pawn_key(Color::Black); + u64 major_key = pos.get_major_key(); + u64 minor_key = pos.get_minor_key(); + usize pawn_index = static_cast(pawn_key % CORRECTION_HISTORY_ENTRY_NB); + usize white_non_pawn_index = static_cast(white_non_pawn_key % CORRECTION_HISTORY_ENTRY_NB); + usize black_non_pawn_index = static_cast(black_non_pawn_key % CORRECTION_HISTORY_ENTRY_NB); + usize major_index = static_cast(major_key % CORRECTION_HISTORY_ENTRY_NB); + usize minor_index = static_cast(minor_key % CORRECTION_HISTORY_ENTRY_NB); i32 new_weight = std::min(16, 1 + depth); i32 scaled_diff = diff * CORRECTION_HISTORY_GRAIN; auto update_entry = [=](i32& entry) { - i32 update = - entry * (CORRECTION_HISTORY_WEIGHT_SCALE - new_weight) + scaled_diff * new_weight; + i32 update = entry * (CORRECTION_HISTORY_WEIGHT_SCALE - new_weight) + scaled_diff * new_weight; - entry = std::clamp(update / CORRECTION_HISTORY_WEIGHT_SCALE, -CORRECTION_HISTORY_MAX, - CORRECTION_HISTORY_MAX); + entry = std::clamp(update / CORRECTION_HISTORY_WEIGHT_SCALE, -CORRECTION_HISTORY_MAX, CORRECTION_HISTORY_MAX); }; update_entry(m_pawn_corr_hist[side_index][pawn_index]); @@ -119,19 +107,17 @@ void History::update_correction_history(const Position& pos, i32 depth, i32 diff } i32 History::get_correction(const Position& pos) { - usize side_index = static_cast(pos.active_color()); - u64 pawn_key = pos.get_pawn_key(); - u64 white_non_pawn_key = pos.get_non_pawn_key(Color::White); - u64 black_non_pawn_key = pos.get_non_pawn_key(Color::Black); - u64 major_key = pos.get_major_key(); - u64 minor_key = pos.get_minor_key(); - usize pawn_index = static_cast(pawn_key % CORRECTION_HISTORY_ENTRY_NB); - usize white_non_pawn_index = - static_cast(white_non_pawn_key % CORRECTION_HISTORY_ENTRY_NB); - usize black_non_pawn_index = - static_cast(black_non_pawn_key % CORRECTION_HISTORY_ENTRY_NB); - usize major_index = static_cast(major_key % CORRECTION_HISTORY_ENTRY_NB); - usize minor_index = static_cast(minor_key % CORRECTION_HISTORY_ENTRY_NB); + usize side_index = static_cast(pos.active_color()); + u64 pawn_key = pos.get_pawn_key(); + u64 white_non_pawn_key = pos.get_non_pawn_key(Color::White); + u64 black_non_pawn_key = pos.get_non_pawn_key(Color::Black); + u64 major_key = pos.get_major_key(); + u64 minor_key = pos.get_minor_key(); + usize pawn_index = static_cast(pawn_key % CORRECTION_HISTORY_ENTRY_NB); + usize white_non_pawn_index = static_cast(white_non_pawn_key % CORRECTION_HISTORY_ENTRY_NB); + usize black_non_pawn_index = static_cast(black_non_pawn_key % CORRECTION_HISTORY_ENTRY_NB); + usize major_index = static_cast(major_key % CORRECTION_HISTORY_ENTRY_NB); + usize minor_index = static_cast(minor_key % CORRECTION_HISTORY_ENTRY_NB); i32 correction = 0; correction += m_pawn_corr_hist[side_index][pawn_index]; diff --git a/src/history.hpp b/src/history.hpp index 04c04618..1f9dc16e 100644 --- a/src/history.hpp +++ b/src/history.hpp @@ -48,9 +48,7 @@ class History { void clear(); private: - static void update_hist_entry(i32& entry, i32 bonus) { - entry += bonus - entry * std::abs(bonus) / HISTORY_MAX; - } + static void update_hist_entry(i32& entry, i32 bonus) { entry += bonus - entry * std::abs(bonus) / HISTORY_MAX; } static void update_hist_entry_banger(i32& entry, i32 base, i32 bonus) { entry += bonus - base * std::abs(bonus) / HISTORY_MAX; diff --git a/src/move.hpp b/src/move.hpp index da914dd1..4d9f93a1 100644 --- a/src/move.hpp +++ b/src/move.hpp @@ -37,41 +37,23 @@ struct Move { raw = static_cast(from.raw | (to.raw << 6) | static_cast(flags)); } - static constexpr Move none() { - return {}; - } + static constexpr Move none() { return {}; } - [[nodiscard]] constexpr Square from() const { - return Square{static_cast(raw & 0x3F)}; - } + [[nodiscard]] constexpr Square from() const { return Square{static_cast(raw & 0x3F)}; } - [[nodiscard]] constexpr Square to() const { - return Square{static_cast((raw >> 6) & 0x3F)}; - } + [[nodiscard]] constexpr Square to() const { return Square{static_cast((raw >> 6) & 0x3F)}; } - [[nodiscard]] constexpr u16 from_to() const { - return raw & 0xFFF; - } + [[nodiscard]] constexpr u16 from_to() const { return raw & 0xFFF; } - [[nodiscard]] constexpr MoveFlags flags() const { - return MoveFlags{static_cast(raw & (0xF << 12))}; - } + [[nodiscard]] constexpr MoveFlags flags() const { return MoveFlags{static_cast(raw & (0xF << 12))}; } - [[nodiscard]] constexpr bool is_capture() const { - return raw & static_cast(MoveFlags::CaptureBit); - } + [[nodiscard]] constexpr bool is_capture() const { return raw & static_cast(MoveFlags::CaptureBit); } - [[nodiscard]] constexpr bool is_promotion() const { - return raw & static_cast(MoveFlags::PromotionBit); - } + [[nodiscard]] constexpr bool is_promotion() const { return raw & static_cast(MoveFlags::PromotionBit); } - [[nodiscard]] constexpr bool is_castle() const { - return flags() == MoveFlags::Castle; - } + [[nodiscard]] constexpr bool is_castle() const { return flags() == MoveFlags::Castle; } - [[nodiscard]] constexpr bool is_en_passant() const { - return flags() == MoveFlags::EnPassant; - } + [[nodiscard]] constexpr bool is_en_passant() const { return flags() == MoveFlags::EnPassant; } [[nodiscard]] constexpr std::optional promo() const { if (!is_promotion()) { diff --git a/src/movegen.cpp b/src/movegen.cpp index 1e3c89ec..3d4ae98c 100644 --- a/src/movegen.cpp +++ b/src/movegen.cpp @@ -13,8 +13,8 @@ namespace Clockwork { -static std::tuple -valid_pawns(Color color, Bitboard bb, Bitboard empty, Bitboard valid_dests) { +static std::tuple valid_pawns(Color color, Bitboard bb, Bitboard empty, + Bitboard valid_dests) { switch (color) { case Color::White: { Bitboard single = bb & ((empty & valid_dests) >> 8); @@ -56,8 +56,7 @@ void MoveGen::generate_moves(MoveList& noisy, MoveList& quiet) { } } -std::tuple -MoveGen::valid_destinations_one_checker(PieceMask checker) const { +std::tuple MoveGen::valid_destinations_one_checker(PieceMask checker) const { Color active_color = m_position.active_color(); Square king_sq = m_position.king_sq(active_color); @@ -66,8 +65,7 @@ MoveGen::valid_destinations_one_checker(PieceMask checker) const { PieceType checker_ptype = m_position.piece_list(invert(active_color))[checker_id]; Bitboard valid_dests = rays::inclusive(king_sq, checker_sq); - Bitboard checker_ray = - is_slider(checker_ptype) ? rays::infinite_exclusive(king_sq, checker_sq) : Bitboard{}; + Bitboard checker_ray = is_slider(checker_ptype) ? rays::infinite_exclusive(king_sq, checker_sq) : Bitboard{}; return {valid_dests, ~checker_ray, checker_ptype == PieceType::Pawn}; } @@ -102,9 +100,8 @@ bool MoveGen::is_legal_no_checkers(Move m, Bitboard valid_dests, bool can_ep) co bool enemy_dest = !empty_dest && m_position.board()[m.to()].color() != active_color; // valid_attack implies valid from square in the move! (exception: quiet pawn moves) - PieceMask at_dest = - m_position.attack_table(active_color).read(m.to()) & m_pin_mask.read(m.to()); - bool valid_attack = at_dest.is_set(src.id()); + PieceMask at_dest = m_position.attack_table(active_color).read(m.to()) & m_pin_mask.read(m.to()); + bool valid_attack = at_dest.is_set(src.id()); // There are positions where enpassant is legal but is not set in valid_dests if (src.ptype() == PieceType::Pawn && m.flags() == MoveFlags::EnPassant) { @@ -136,8 +133,7 @@ bool MoveGen::is_legal_no_checkers(Move m, Bitboard valid_dests, bool can_ep) co if (m.flags() == MoveFlags::Normal || m.is_promotion()) { Bitboard empty = m_position.board().get_empty_bitboard(); Bitboard pinned_pawns = m_pinned & ~Bitboard::file_mask(king_sq.file()); - Bitboard bb = - m_position.board().bitboard_for(active_color, PieceType::Pawn) & ~pinned_pawns; + Bitboard bb = m_position.board().bitboard_for(active_color, PieceType::Pawn) & ~pinned_pawns; auto [single_push, double_push, promo, single_shift, double_shift] = valid_pawns(active_color, bb, empty, valid_dests); @@ -239,26 +235,20 @@ bool MoveGen::is_legal_two_checkers(Move m, PieceMask checkers) const { } template -void MoveGen::generate_moves_to(MoveList& noisy, - MoveList& quiet, - Bitboard valid_dests, - bool can_ep) { +void MoveGen::generate_moves_to(MoveList& noisy, MoveList& quiet, Bitboard valid_dests, bool can_ep) { Color active_color = m_position.active_color(); Bitboard empty = m_position.board().get_empty_bitboard(); Bitboard enemy = m_position.board().get_color_bitboard(invert(active_color)); - std::array at = - (m_position.attack_table(active_color) & m_pin_mask).to_mailbox(); + std::array at = (m_position.attack_table(active_color) & m_pin_mask).to_mailbox(); PieceMask king_mask = PieceMask::king(); PieceMask pawn_mask = m_position.piece_list(active_color).mask_eq(PieceType::Pawn); - Bitboard pawn_active = - m_position.attack_table(active_color).get_piece_mask_bitboard(pawn_mask) & valid_dests; - Bitboard nonpawn_active = - m_position.attack_table(active_color).get_piece_mask_bitboard(~pawn_mask) & valid_dests; - Bitboard danger = m_position.attack_table(invert(active_color)).get_attacked_bitboard(); + Bitboard pawn_active = m_position.attack_table(active_color).get_piece_mask_bitboard(pawn_mask) & valid_dests; + Bitboard nonpawn_active = m_position.attack_table(active_color).get_piece_mask_bitboard(~pawn_mask) & valid_dests; + Bitboard danger = m_position.attack_table(invert(active_color)).get_attacked_bitboard(); PieceMask valid_plist = m_position.piece_list(active_color).mask_valid(); if constexpr (!king_moves) { @@ -276,8 +266,7 @@ void MoveGen::generate_moves_to(MoveList& noisy, // Undefended non-pawn captures write(noisy, at, nonpawn_active & enemy & ~danger, non_pawn_mask, MoveFlags::CaptureBit); // Defended non-pawn captures - write(noisy, at, nonpawn_active & enemy & danger, non_pawn_mask & ~king_mask, - MoveFlags::CaptureBit); + write(noisy, at, nonpawn_active & enemy & danger, non_pawn_mask & ~king_mask, MoveFlags::CaptureBit); Bitboard promo_zone{static_cast(0xFF) << (active_color == Color::White ? 56 : 0)}; // Capture-with-promotion @@ -304,16 +293,14 @@ void MoveGen::generate_moves_to(MoveList& noisy, write(quiet, at, nonpawn_active & empty & ~danger, non_pawn_mask, MoveFlags::Normal); // Defended non-pawn quiets - write(quiet, at, nonpawn_active & empty & danger, non_pawn_mask & ~king_mask, - MoveFlags::Normal); + write(quiet, at, nonpawn_active & empty & danger, non_pawn_mask & ~king_mask, MoveFlags::Normal); // Pawn quiets { Square king_sq = m_position.king_sq(active_color); Bitboard pinned_pawns = m_pinned & ~Bitboard::file_mask(king_sq.file()); - Bitboard bb = - m_position.board().bitboard_for(active_color, PieceType::Pawn) & ~pinned_pawns; + Bitboard bb = m_position.board().bitboard_for(active_color, PieceType::Pawn) & ~pinned_pawns; auto [single_push, double_push, promo, single_shift, double_shift] = valid_pawns(active_color, bb, empty, valid_dests); @@ -338,8 +325,7 @@ void MoveGen::generate_king_moves_to(MoveList& noisy, MoveList& quiet, Bitboard PieceMask king_mask = PieceMask::king(); - Bitboard active = - m_position.attack_table(active_color).get_piece_mask_bitboard(king_mask) & valid_dests; + Bitboard active = m_position.attack_table(active_color).get_piece_mask_bitboard(king_mask) & valid_dests; Bitboard danger = m_position.attack_table(invert(active_color)).get_attacked_bitboard(); // Undefended captures @@ -378,13 +364,10 @@ bool MoveGen::is_aside_castling_legal(Bitboard empty, Bitboard danger) const { if (m_pinned.is_set(aside)) { return false; } - u8 king_ray = rays::inclusive(king_sq, Square::from_file_and_rank(2, king_sq.rank())) - .front_rank(active_color); - u8 rook_ray = rays::inclusive(aside, Square::from_file_and_rank(3, aside.rank())) - .front_rank(active_color); + u8 king_ray = rays::inclusive(king_sq, Square::from_file_and_rank(2, king_sq.rank())).front_rank(active_color); + u8 rook_ray = rays::inclusive(aside, Square::from_file_and_rank(3, aside.rank())).front_rank(active_color); u8 should_be_empty = king_ray | rook_ray; - return (rank_empty & should_be_empty) == should_be_empty - && (rank_safe & king_ray) == king_ray; + return (rank_empty & should_be_empty) == should_be_empty && (rank_safe & king_ray) == king_ray; } else { return (rank_empty & 0x1F) == 0x1F && (rank_safe & 0x1C) == 0x1C; } @@ -407,13 +390,10 @@ bool MoveGen::is_hside_castling_legal(Bitboard empty, Bitboard danger) const { if (m_pinned.is_set(hside)) { return false; } - u8 king_ray = rays::inclusive(king_sq, Square::from_file_and_rank(6, king_sq.rank())) - .front_rank(active_color); - u8 rook_ray = rays::inclusive(hside, Square::from_file_and_rank(5, hside.rank())) - .front_rank(active_color); + u8 king_ray = rays::inclusive(king_sq, Square::from_file_and_rank(6, king_sq.rank())).front_rank(active_color); + u8 rook_ray = rays::inclusive(hside, Square::from_file_and_rank(5, hside.rank())).front_rank(active_color); u8 should_be_empty = king_ray | rook_ray; - return (rank_empty & should_be_empty) == should_be_empty - && (rank_safe & king_ray) == king_ray; + return (rank_empty & should_be_empty) == should_be_empty && (rank_safe & king_ray) == king_ray; } else { return (rank_empty & 0xF0) == 0xF0 && (rank_safe & 0x70) == 0x70; } @@ -426,11 +406,8 @@ void MoveGen::write(MoveList& moves, Square dest, PieceMask piecemask, MoveFlags } } -void MoveGen::write(MoveList& moves, - const std::array& at, - Bitboard dest_bb, - PieceMask piecemask, - MoveFlags mf) { +void MoveGen::write(MoveList& moves, const std::array& at, Bitboard dest_bb, PieceMask piecemask, + MoveFlags mf) { for (Square dest : dest_bb) { write(moves, dest, piecemask & at[dest.raw], mf); } diff --git a/src/movegen.hpp b/src/movegen.hpp index bdc2ee5f..0ff0547f 100644 --- a/src/movegen.hpp +++ b/src/movegen.hpp @@ -25,9 +25,8 @@ class MoveGen { void generate_moves(MoveList& noisy, MoveList& quiet); private: - [[nodiscard]] std::tuple - valid_destinations_one_checker(PieceMask checker) const; - [[nodiscard]] Bitboard valid_destinations_two_checkers(PieceMask checker) const; + [[nodiscard]] std::tuple valid_destinations_one_checker(PieceMask checker) const; + [[nodiscard]] Bitboard valid_destinations_two_checkers(PieceMask checker) const; [[nodiscard]] bool is_legal_no_checkers(Move m, Bitboard valid_dests, bool can_ep) const; [[nodiscard]] bool is_legal_king_move(Move m, Bitboard valid_dests) const; @@ -48,11 +47,8 @@ class MoveGen { void write(MoveList& moves, Square dest, PieceMask piecemask, MoveFlags mf); // Write moves that go to all squares in dest_bb. Possible sources are pieces in piecemask, masked as appropriate by attack_table. - void write(MoveList& moves, - const std::array& attack_table, - Bitboard dest_bb, - PieceMask piecemask, - MoveFlags mf); + void write(MoveList& moves, const std::array& attack_table, Bitboard dest_bb, PieceMask piecemask, + MoveFlags mf); // Write quiet pawn moves that start from src_bb, moved by shift. void write_pawn(MoveList& moves, Bitboard src_bb, i32 shift, MoveFlags mf); diff --git a/src/movepick.hpp b/src/movepick.hpp index 6a5f9abb..8ee85a52 100644 --- a/src/movepick.hpp +++ b/src/movepick.hpp @@ -13,16 +13,14 @@ bool quiet_move(Move move); class MovePicker { public: - explicit MovePicker( - const Position& pos, const History& history, Move tt_move, i32 ply, Search::Stack* ss) : + explicit MovePicker(const Position& pos, const History& history, Move tt_move, i32 ply, Search::Stack* ss) : m_pos(pos), m_history(history), m_movegen(pos), m_tt_move(tt_move), m_killer(ss->killer), m_ply(ply), - m_stack(ss) { - } + m_stack(ss) {} enum class Stage { EmitTTMove, @@ -40,13 +38,9 @@ class MovePicker { Move next(); - [[nodiscard]] Stage stage() const { - return m_stage; - } + [[nodiscard]] Stage stage() const { return m_stage; } - [[nodiscard]] bool is_legal(Move m) const { - return m_movegen.is_legal(m); - } + [[nodiscard]] bool is_legal(Move m) const { return m_movegen.is_legal(m); } private: void generate_moves(); diff --git a/src/perft.cpp b/src/perft.cpp index b807ddb6..8160cf55 100644 --- a/src/perft.cpp +++ b/src/perft.cpp @@ -57,8 +57,7 @@ void split_perft(const Position& position, usize depth) { f64 mnps = static_cast(total) / elapsed.count() / 1000000.0; std::cout << std::setprecision(1) << std::fixed; - std::cout << "perft to depth " << depth << " complete in " << elapsed_ms << "ms (" << mnps - << " Mnps)" << std::endl; + std::cout << "perft to depth " << depth << " complete in " << elapsed_ms << "ms (" << mnps << " Mnps)" << std::endl; } } // namespace Clockwork diff --git a/src/position.cpp b/src/position.cpp index e7f6384d..ce7b51a7 100644 --- a/src/position.cpp +++ b/src/position.cpp @@ -14,18 +14,14 @@ namespace Clockwork { -void Position::incrementally_remove_piece(bool color, - PieceId id, - Square from, - PsqtUpdates& updates) { +void Position::incrementally_remove_piece(bool color, PieceId id, Square from, PsqtUpdates& updates) { remove_attacks(color, id); toggle_rays(from); // TODO: check if some speed left on the table for zobrist here - Color pcolor = m_board[from].color(); - PieceType ptype = m_board[from].ptype(); - u64 piece_key = Zobrist::piece_square_zobrist[static_cast(pcolor)] - [static_cast(ptype)][from.raw]; + Color pcolor = m_board[from].color(); + PieceType ptype = m_board[from].ptype(); + u64 piece_key = Zobrist::piece_square_zobrist[static_cast(pcolor)][static_cast(ptype)][from.raw]; m_hash_key ^= piece_key; if (ptype == PieceType::Pawn) { m_pawn_key ^= piece_key; @@ -44,11 +40,10 @@ void Position::incrementally_remove_piece(bool color, void Position::incrementally_add_piece(bool color, Place p, Square to, PsqtUpdates& updates) { // TODO: check if some speed left on the table for zobrist here - m_board[to] = p; - Color pcolor = p.color(); - PieceType ptype = p.ptype(); - u64 piece_key = - Zobrist::piece_square_zobrist[static_cast(pcolor)][static_cast(ptype)][to.raw]; + m_board[to] = p; + Color pcolor = p.color(); + PieceType ptype = p.ptype(); + u64 piece_key = Zobrist::piece_square_zobrist[static_cast(pcolor)][static_cast(ptype)][to.raw]; m_hash_key ^= piece_key; if (ptype == PieceType::Pawn) { m_pawn_key ^= piece_key; @@ -67,13 +62,13 @@ void Position::incrementally_add_piece(bool color, Place p, Square to, PsqtUpdat add_attacks(color, p.id(), to, p.ptype(), m); } -void Position::incrementally_mutate_piece( - bool old_color, PieceId old_id, Square sq, bool new_color, Place p, PsqtUpdates& updates) { +void Position::incrementally_mutate_piece(bool old_color, PieceId old_id, Square sq, bool new_color, Place p, + PsqtUpdates& updates) { PieceType ptype = m_board[sq].ptype(); // TODO: check if some speed left on the table for zobrist here - u64 rem_piece_key = Zobrist::piece_square_zobrist[static_cast(m_board[sq].color())] - [static_cast(ptype)][sq.raw]; + u64 rem_piece_key = + Zobrist::piece_square_zobrist[static_cast(m_board[sq].color())][static_cast(ptype)][sq.raw]; m_hash_key ^= rem_piece_key; if (ptype == PieceType::Pawn) { m_pawn_key ^= rem_piece_key; @@ -87,10 +82,10 @@ void Position::incrementally_mutate_piece( } } updates.removes.push_back({m_board[sq].color(), ptype, sq}); - m_board[sq] = p; - ptype = m_board[sq].ptype(); - u64 add_piece_key = Zobrist::piece_square_zobrist[static_cast(m_board[sq].color())] - [static_cast(ptype)][sq.raw]; + m_board[sq] = p; + ptype = m_board[sq].ptype(); + u64 add_piece_key = + Zobrist::piece_square_zobrist[static_cast(m_board[sq].color())][static_cast(ptype)][sq.raw]; m_hash_key ^= add_piece_key; if (ptype == PieceType::Pawn) { m_pawn_key ^= add_piece_key; @@ -109,8 +104,7 @@ void Position::incrementally_mutate_piece( add_attacks(new_color, p.id(), sq, p.ptype()); } -void Position::incrementally_move_piece( - bool color, Square from, Square to, Place p, PsqtUpdates& updates) { +void Position::incrementally_move_piece(bool color, Square from, Square to, Place p, PsqtUpdates& updates) { remove_attacks(color, p.id()); auto [src_ray_coords, src_ray_valid] = geometry::superpiece_rays(from); @@ -120,8 +114,8 @@ void Position::incrementally_move_piece( PieceType ptype = m_board[from].ptype(); // TODO: check if some speed left on the table for zobrist here - u64 rem_piece_key = Zobrist::piece_square_zobrist[static_cast(m_board[from].color())] - [static_cast(ptype)][from.raw]; + u64 rem_piece_key = + Zobrist::piece_square_zobrist[static_cast(m_board[from].color())][static_cast(ptype)][from.raw]; m_hash_key ^= rem_piece_key; if (ptype == PieceType::Pawn) { m_pawn_key ^= rem_piece_key; @@ -135,10 +129,10 @@ void Position::incrementally_move_piece( } } updates.removes.push_back({m_board[from].color(), ptype, from}); - m_board[from] = Place::empty(); - m_board[to] = p; - u64 add_piece_key = Zobrist::piece_square_zobrist[static_cast(m_board[to].color())] - [static_cast(ptype)][to.raw]; + m_board[from] = Place::empty(); + m_board[to] = p; + u64 add_piece_key = + Zobrist::piece_square_zobrist[static_cast(m_board[to].color())][static_cast(ptype)][to.raw]; m_hash_key ^= add_piece_key; if (ptype == PieceType::Pawn) { m_pawn_key ^= add_piece_key; @@ -167,7 +161,7 @@ void Position::incrementally_move_piece( src_slider_ids = src_raymask.mask(geometry::flip_rays(src_slider_ids)); // flip rays dst_slider_ids = dst_raymask.mask(geometry::flip_rays(dst_slider_ids)); // flip rays - dst_slider_ids |= dst_raymask.mask(u8x64::splat(0x20)); // pack information for efficiency + dst_slider_ids |= dst_raymask.mask(u8x64::splat(0x20)); // pack information for efficiency u8x64 src_inv_perm = geometry::superpiece_inverse_rays_avx2(from); u8x64 dst_inv_perm = geometry::superpiece_inverse_rays_avx2(to); @@ -328,8 +322,7 @@ Position Position::move(Move m, PsqtState* psqtState) const { } // Compute old castle index for zobrist indexing and remove it - usize old_castle_index = - new_pos.m_rook_info[0].as_index() | (new_pos.m_rook_info[1].as_index() << 2); + usize old_castle_index = new_pos.m_rook_info[0].as_index() | (new_pos.m_rook_info[1].as_index() << 2); new_pos.m_hash_key ^= Zobrist::castling_zobrist[old_castle_index]; const auto CHECK_SRC_CASTLING_RIGHTS = [&] { @@ -452,8 +445,7 @@ Position Position::move(Move m, PsqtState* psqtState) const { } // Calculate the new castling index for zobrist indexing and add it back in - usize new_castle_index = - new_pos.m_rook_info[0].as_index() | (new_pos.m_rook_info[1].as_index() << 2); + usize new_castle_index = new_pos.m_rook_info[0].as_index() | (new_pos.m_rook_info[1].as_index() << 2); new_pos.m_hash_key ^= Zobrist::castling_zobrist[new_castle_index]; new_pos.m_active_color = invert(m_active_color); @@ -517,24 +509,19 @@ std::tuple Position::calc_pin_mask() const { // Does this ray have a pinner? #if LPS_AVX512 - m8x64 no_pinner_mask{ - std::bit_cast(std::bit_cast(pinner.to_vector()).zeros().to_vector()) - .to_bits()}; + m8x64 no_pinner_mask{std::bit_cast(std::bit_cast(pinner.to_vector()).zeros().to_vector()).to_bits()}; #else m8x64 no_pinner_mask = std::bit_cast(std::bit_cast(pinner).to_vector().zeros()); #endif m8x64 pinned = maybe_pinned.andnot(no_pinner_mask); - u8x64 nonmasked_pinned_ids = - geometry::lane_broadcast(pinned.mask(ray_places & u8x64::splat(0xF))); - u8x64 pinned_ids = pin_raymask.mask(nonmasked_pinned_ids); + u8x64 nonmasked_pinned_ids = geometry::lane_broadcast(pinned.mask(ray_places & u8x64::splat(0xF))); + u8x64 pinned_ids = pin_raymask.mask(nonmasked_pinned_ids); // Transform into board layout pinned_ids = inverse_perm.swizzle(pinned_ids); u16 nonpinned_piece_mask = static_cast( - ~((u64x8::splat(1) << (std::bit_cast(nonmasked_pinned_ids) & u64x8::splat(0xF))) - .reduce_or()) - | 1); + ~((u64x8::splat(1) << (std::bit_cast(nonmasked_pinned_ids) & u64x8::splat(0xF))).reduce_or()) | 1); // AVX2 doesn't have a variable word shift, so were're doing it this way. // Index zero is invalid here (the king is never pinned), so 0 converts to 0. @@ -547,8 +534,8 @@ std::tuple Position::calc_pin_mask() const { u16x64 nppm = u16x64::splat(nonpinned_piece_mask); - u16x64 at = std::bit_cast( - std::array{at_lo.zip_low_128lanes(at_hi), at_lo.zip_high_128lanes(at_hi)}); + u16x64 at = + std::bit_cast(std::array{at_lo.zip_low_128lanes(at_hi), at_lo.zip_high_128lanes(at_hi)}); at |= nppm; u64 pinned_bb = at.neq(nppm).to_bits(); @@ -583,15 +570,12 @@ const std::array Position::calc_attacks_slow(Square sq) { u8x16 white_attackers_coord = white_attackers.compress(ray_coords).extract_aligned(); u8x16 black_attackers_coord = black_attackers.compress(ray_coords).extract_aligned(); return { - PieceMask{geometry::find_set(white_attackers_coord, white_attackers_count, - m_piece_list_sq[0].to_vector())}, - PieceMask{geometry::find_set(black_attackers_coord, black_attackers_count, - m_piece_list_sq[1].to_vector())}, + PieceMask{geometry::find_set(white_attackers_coord, white_attackers_count, m_piece_list_sq[0].to_vector())}, + PieceMask{geometry::find_set(black_attackers_coord, black_attackers_count, m_piece_list_sq[1].to_vector())}, }; } -Wordboard Position::create_attack_table_superpiece_mask(Square sq, - CreateSuperpieceMaskInfo cmi_arg) const { +Wordboard Position::create_attack_table_superpiece_mask(Square sq, CreateSuperpieceMaskInfo cmi_arg) const { auto [ray_coords, ray_valid] = geometry::superpiece_rays(sq); u8x64 ray_places = ray_coords.swizzle(m_board.to_vector()); u8x64 inverse_perm = geometry::superpiece_inverse_rays_avx2(sq); @@ -643,11 +627,8 @@ std::optional Position::parse(std::string_view str) { return parse(board, color, castle, enpassant, irreversible_clock, ply); } -std::optional Position::parse(std::string_view board, - std::string_view color, - std::string_view castle, - std::string_view enpassant, - std::string_view irreversible_clock, +std::optional Position::parse(std::string_view board, std::string_view color, std::string_view castle, + std::string_view enpassant, std::string_view irreversible_clock, std::string_view ply) { Position result{}; @@ -876,8 +857,7 @@ HashKey Position::calc_hash_key_slow() const { if (p.is_empty()) { continue; } - key ^= Zobrist::piece_square_zobrist[static_cast(p.color())] - [static_cast(p.ptype())][sq_idx]; + key ^= Zobrist::piece_square_zobrist[static_cast(p.color())][static_cast(p.ptype())][sq_idx]; } // Add ep if available @@ -905,8 +885,8 @@ HashKey Position::calc_pawn_key_slow() const { if (p.is_empty() || p.ptype() != PieceType::Pawn) { continue; } - key ^= Zobrist::piece_square_zobrist[static_cast(p.color())] - [static_cast(PieceType::Pawn)][sq_idx]; + key ^= + Zobrist::piece_square_zobrist[static_cast(p.color())][static_cast(PieceType::Pawn)][sq_idx]; } return key; } @@ -919,8 +899,7 @@ std::array Position::calc_non_pawn_key_slow() const { continue; } key[static_cast(p.color())] ^= - Zobrist::piece_square_zobrist[static_cast(p.color())] - [static_cast(p.ptype())][sq_idx]; + Zobrist::piece_square_zobrist[static_cast(p.color())][static_cast(p.ptype())][sq_idx]; } return key; } @@ -933,8 +912,7 @@ HashKey Position::calc_major_key_slow() const { || p.ptype() == PieceType::Bishop || p.ptype() == PieceType::King) { continue; } - key ^= Zobrist::piece_square_zobrist[static_cast(p.color())] - [static_cast(p.ptype())][sq_idx]; + key ^= Zobrist::piece_square_zobrist[static_cast(p.color())][static_cast(p.ptype())][sq_idx]; } return key; } @@ -944,12 +922,10 @@ HashKey Position::calc_minor_key_slow() const { for (usize sq_idx = 0; sq_idx < 64; sq_idx++) { Place p = m_board.mailbox[sq_idx]; if (p.is_empty() - || (p.ptype() != PieceType::Knight && p.ptype() != PieceType::Bishop - && p.ptype() != PieceType::King)) { + || (p.ptype() != PieceType::Knight && p.ptype() != PieceType::Bishop && p.ptype() != PieceType::King)) { continue; } - key ^= Zobrist::piece_square_zobrist[static_cast(p.color())] - [static_cast(p.ptype())][sq_idx]; + key ^= Zobrist::piece_square_zobrist[static_cast(p.color())][static_cast(p.ptype())][sq_idx]; } return key; } diff --git a/src/position.hpp b/src/position.hpp index 5118a786..cd14192c 100644 --- a/src/position.hpp +++ b/src/position.hpp @@ -19,20 +19,12 @@ template struct alignas(16) PieceList { std::array array{}; - constexpr T& operator[](PieceId id) { - return array[id.raw]; - } - constexpr T operator[](PieceId id) const { - return array[id.raw]; - } + constexpr T& operator[](PieceId id) { return array[id.raw]; } + constexpr T operator[](PieceId id) const { return array[id.raw]; } - [[nodiscard]] u8x16 to_vector() const { - return std::bit_cast(array); - } + [[nodiscard]] u8x16 to_vector() const { return std::bit_cast(array); } - [[nodiscard]] PieceMask mask_valid() const { - return PieceMask{to_vector().nonzeros().to_bits()}; - } + [[nodiscard]] PieceMask mask_valid() const { return PieceMask{to_vector().nonzeros().to_bits()}; } [[nodiscard]] PieceMask mask_eq(PieceType ptype) const { return PieceMask{to_vector().eq(u8x16::splat(static_cast(ptype))).to_bits()}; @@ -50,9 +42,7 @@ struct alignas(16) PieceList { return PieceMask{(to_vector().swizzle(to_bits) & u8x16::splat(bits)).nonzeros().to_bits()}; } - constexpr bool operator==(const PieceList& other) const { - return array == other.array; - } + constexpr bool operator==(const PieceList& other) const { return array == other.array; } }; struct RookInfo { @@ -69,9 +59,7 @@ struct RookInfo { hside = hside == sq ? Square::invalid() : hside; } - [[nodiscard]] constexpr bool is_clear() const { - return !aside.is_valid() && !hside.is_valid(); - } + [[nodiscard]] constexpr bool is_clear() const { return !aside.is_valid() && !hside.is_valid(); } [[nodiscard]] constexpr size_t as_index() const { return static_cast(aside.is_valid()) | (static_cast(hside.is_valid()) << 1); @@ -96,54 +84,28 @@ struct Position { public: constexpr Position() = default; - [[nodiscard]] const Byteboard& board() const { - return m_board; - } - [[nodiscard]] const Wordboard& attack_table(Color color) const { - return m_attack_table[static_cast(color)]; - } + [[nodiscard]] const Byteboard& board() const { return m_board; } + [[nodiscard]] const Wordboard& attack_table(Color color) const { return m_attack_table[static_cast(color)]; } [[nodiscard]] const PieceList& piece_list(Color color) const { return m_piece_list[static_cast(color)]; } [[nodiscard]] const PieceList& piece_list_sq(Color color) const { return m_piece_list_sq[static_cast(color)]; } - [[nodiscard]] Color active_color() const { - return m_active_color; - } - [[nodiscard]] Square en_passant() const { - return m_enpassant; - } - [[nodiscard]] RookInfo rook_info(Color color) const { - return m_rook_info[static_cast(color)]; - } - [[nodiscard]] HashKey get_hash_key() const { - return m_hash_key; - } - [[nodiscard]] HashKey get_pawn_key() const { - return m_pawn_key; - } - [[nodiscard]] HashKey get_non_pawn_key(Color color) const { - return m_non_pawn_key[static_cast(color)]; - } - [[nodiscard]] HashKey get_major_key() const { - return m_major_key; - } - [[nodiscard]] HashKey get_minor_key() const { - return m_minor_key; - } + [[nodiscard]] Color active_color() const { return m_active_color; } + [[nodiscard]] Square en_passant() const { return m_enpassant; } + [[nodiscard]] RookInfo rook_info(Color color) const { return m_rook_info[static_cast(color)]; } + [[nodiscard]] HashKey get_hash_key() const { return m_hash_key; } + [[nodiscard]] HashKey get_pawn_key() const { return m_pawn_key; } + [[nodiscard]] HashKey get_non_pawn_key(Color color) const { return m_non_pawn_key[static_cast(color)]; } + [[nodiscard]] HashKey get_major_key() const { return m_major_key; } + [[nodiscard]] HashKey get_minor_key() const { return m_minor_key; } - [[nodiscard]] Square king_sq(Color color) const { - return piece_list_sq(color)[PieceId{0}]; - } + [[nodiscard]] Square king_sq(Color color) const { return piece_list_sq(color)[PieceId{0}]; } - [[nodiscard]] size_t king_side(Color color) const { - return king_sq(color).file() >= 4; - } + [[nodiscard]] size_t king_side(Color color) const { return king_sq(color).file() >= 4; } - [[nodiscard]] PieceType piece_at(Square sq) const { - return m_board[sq].ptype(); - } + [[nodiscard]] PieceType piece_at(Square sq) const { return m_board[sq].ptype(); } [[nodiscard]] bool is_valid() const { return attack_table(m_active_color).read(king_sq(invert(m_active_color))).empty(); @@ -153,9 +115,7 @@ struct Position { return attack_table(invert(m_active_color)).read(king_sq(m_active_color)); } - [[nodiscard]] bool is_in_check() const { - return !checker_mask().empty(); - } + [[nodiscard]] bool is_in_check() const { return !checker_mask().empty(); } [[nodiscard]] Bitboard bitboard_for(Color color, PieceType ptype) const { return m_board.bitboard_for(color, ptype); @@ -170,9 +130,7 @@ struct Position { return piece_list(color).mask_eq().popcount(); } - [[nodiscard]] PieceMask get_piece_mask(Color color) const { - return piece_list(color).mask_valid(); - } + [[nodiscard]] PieceMask get_piece_mask(Color color) const { return piece_list(color).mask_valid(); } [[nodiscard]] PieceMask get_piece_mask(Color color, PieceType ptype) const { return piece_list(color).mask_eq(ptype); @@ -207,16 +165,11 @@ struct Position { return (attack_table(color).get_piece_mask_bitboard(id.to_piece_mask()) & mask).popcount(); } - [[nodiscard]] Wordboard create_attack_table_superpiece_mask(Square sq, - CreateSuperpieceMaskInfo cmi) const; + [[nodiscard]] Wordboard create_attack_table_superpiece_mask(Square sq, CreateSuperpieceMaskInfo cmi) const; - [[nodiscard]] PieceType pt_of(Color color, PieceId id) const { - return piece_list(color)[id]; - } + [[nodiscard]] PieceType pt_of(Color color, PieceId id) const { return piece_list(color)[id]; } - [[nodiscard]] usize piece_count(Color color) const { - return 16 - piece_count(color, PieceType::None); - } + [[nodiscard]] usize piece_count(Color color) const { return 16 - piece_count(color, PieceType::None); } [[nodiscard]] isize ipiece_count(Color color, PieceType ptype) const { return static_cast(piece_count(color, ptype)); @@ -258,12 +211,8 @@ struct Position { [[nodiscard]] Position move(Move m, PsqtState* psqt_state) const; [[nodiscard]] Position null_move() const; - [[nodiscard]] Position move(Move m) const { - return move(m, nullptr); - } - [[nodiscard]] Position move(Move m, PsqtState& psqt_state) const { - return move(m, &psqt_state); - } + [[nodiscard]] Position move(Move m) const { return move(m, nullptr); } + [[nodiscard]] Position move(Move m, PsqtState& psqt_state) const { return move(m, &psqt_state); } [[nodiscard]] std::tuple calc_pin_mask() const; @@ -283,11 +232,8 @@ struct Position { [[nodiscard]] HashKey calc_minor_key_slow() const; static std::optional parse(std::string_view str); - static std::optional parse(std::string_view board, - std::string_view color, - std::string_view castle, - std::string_view enpassant, - std::string_view irreversible_clock, + static std::optional parse(std::string_view board, std::string_view color, std::string_view castle, + std::string_view enpassant, std::string_view irreversible_clock, std::string_view ply); bool operator==(const Position&) const = default; @@ -312,10 +258,9 @@ struct Position { void incrementally_remove_piece(bool color, PieceId id, Square sq, PsqtUpdates& updates); void incrementally_add_piece(bool color, Place p, Square sq, PsqtUpdates& updates); - void incrementally_mutate_piece( - bool old_color, PieceId old_id, Square sq, bool new_color, Place p, PsqtUpdates& updates); - void - incrementally_move_piece(bool color, Square from, Square to, Place p, PsqtUpdates& updates); + void incrementally_mutate_piece(bool old_color, PieceId old_id, Square sq, bool new_color, Place p, + PsqtUpdates& updates); + void incrementally_move_piece(bool color, Square from, Square to, Place p, PsqtUpdates& updates); void remove_attacks(bool color, PieceId id); m8x64 toggle_rays(Square sq); diff --git a/src/psqt_state.hpp b/src/psqt_state.hpp index a39a54a3..9e23d0d2 100644 --- a/src/psqt_state.hpp +++ b/src/psqt_state.hpp @@ -69,8 +69,7 @@ struct PsqtState { } PScore score() const { - return m_accumulators[static_cast(Color::White)] - - m_accumulators[static_cast(Color::Black)]; + return m_accumulators[static_cast(Color::White)] - m_accumulators[static_cast(Color::Black)]; } bool operator==(const PsqtState& other) const noexcept = default; diff --git a/src/rays.hpp b/src/rays.hpp index 6db831fe..24631ba5 100644 --- a/src/rays.hpp +++ b/src/rays.hpp @@ -36,8 +36,7 @@ template int file_diff = b_file - a_file; int rank_diff = b_rank - a_rank; - if (file_diff == 0 || rank_diff == 0 || file_diff == rank_diff - || file_diff == -rank_diff) { + if (file_diff == 0 || rank_diff == 0 || file_diff == rank_diff || file_diff == -rank_diff) { int file_delta = sign(file_diff); int rank_delta = sign(rank_diff); @@ -51,8 +50,8 @@ template return result; } -inline constexpr Table INCLUSIVE_TABLE = generate_rays( - [](Bitboard& bb, int a_file, int a_rank, int b_file, int b_rank, int rank_delta, int file_delta) { +inline constexpr Table INCLUSIVE_TABLE = + generate_rays([](Bitboard& bb, int a_file, int a_rank, int b_file, int b_rank, int rank_delta, int file_delta) { int file = a_file; int rank = a_rank; for (; file != b_file || rank != b_rank; file += file_delta, rank += rank_delta) { @@ -64,18 +63,16 @@ inline constexpr Table INCLUSIVE_TABLE = generate_rays( return INCLUSIVE_TABLE[a.raw][b.raw]; } -inline constexpr Table INFINITE_EXCLUSIVE_TABLE = generate_rays( - [](Bitboard& bb, int a_file, int a_rank, int b_file, int b_rank, int rank_delta, int file_delta) { +inline constexpr Table INFINITE_EXCLUSIVE_TABLE = + generate_rays([](Bitboard& bb, int a_file, int a_rank, int b_file, int b_rank, int rank_delta, int file_delta) { int file = a_file; int rank = a_rank; - for (; file >= 0 && file <= 7 && rank >= 0 && rank <= 7; - file += file_delta, rank += rank_delta) { + for (; file >= 0 && file <= 7 && rank >= 0 && rank <= 7; file += file_delta, rank += rank_delta) { bb |= Bitboard::from_square(Square::from_file_and_rank(file, rank)); } file = a_file; rank = a_rank; - for (; file >= 0 && file <= 7 && rank >= 0 && rank <= 7; - file -= file_delta, rank -= rank_delta) { + for (; file >= 0 && file <= 7 && rank >= 0 && rank <= 7; file -= file_delta, rank -= rank_delta) { bb |= Bitboard::from_square(Square::from_file_and_rank(file, rank)); } bb &= ~Bitboard::from_square(Square::from_file_and_rank(a_file, a_rank)); diff --git a/src/search.cpp b/src/search.cpp index a8b14982..c23b4215 100644 --- a/src/search.cpp +++ b/src/search.cpp @@ -40,8 +40,7 @@ std::ostream& operator<<(std::ostream& os, const PV& pv) { Searcher::Searcher() : idle_barrier(std::make_unique>(1)), - started_barrier(std::make_unique>(1)) { -} + started_barrier(std::make_unique>(1)) {} Searcher::~Searcher() { exit(); @@ -188,15 +187,14 @@ void Worker::start_searching() { m_search_start = time::Clock::now(); m_search_limits = { - .hard_time_limit = TM::compute_hard_limit(m_search_start, m_searcher.settings, - root_position.active_color()), - .soft_time_limit = TM::compute_soft_limit(m_search_start, m_searcher.settings, - root_position.active_color(), 0.0, 0.0), - .soft_node_limit = m_searcher.settings.soft_nodes > 0 ? m_searcher.settings.soft_nodes - : std::numeric_limits::max(), - .hard_node_limit = m_searcher.settings.hard_nodes > 0 ? m_searcher.settings.hard_nodes - : std::numeric_limits::max(), - .depth_limit = m_searcher.settings.depth > 0 ? m_searcher.settings.depth : MAX_PLY}; + .hard_time_limit = TM::compute_hard_limit(m_search_start, m_searcher.settings, root_position.active_color()), + .soft_time_limit = + TM::compute_soft_limit(m_search_start, m_searcher.settings, root_position.active_color(), 0.0, 0.0), + .soft_node_limit = + m_searcher.settings.soft_nodes > 0 ? m_searcher.settings.soft_nodes : std::numeric_limits::max(), + .hard_node_limit = + m_searcher.settings.hard_nodes > 0 ? m_searcher.settings.hard_nodes : std::numeric_limits::max(), + .depth_limit = m_searcher.settings.depth > 0 ? m_searcher.settings.depth : MAX_PLY}; Move best_move = iterative_deepening(root_position); @@ -238,12 +236,11 @@ Move Worker::iterative_deepening(const Position& root_position) { // Get current time auto curr_time = time::Clock::now(); - std::cout << std::dec << "info depth " << last_search_depth << " seldepth " << last_seldepth - << " score " << format_score(last_search_score) << " nodes " - << m_searcher.node_count() << " nps " + std::cout << std::dec << "info depth " << last_search_depth << " seldepth " << last_seldepth << " score " + << format_score(last_search_score) << " nodes " << m_searcher.node_count() << " nps " << time::nps(m_searcher.node_count(), curr_time - m_search_start) << " time " - << time::cast(curr_time - m_search_start).count() << " pv " - << last_pv << std::endl; + << time::cast(curr_time - m_search_start).count() << " pv " << last_pv + << std::endl; }; m_node_counts.fill(0); @@ -266,8 +263,7 @@ Move Worker::iterative_deepening(const Position& root_position) { alpha = std::max(-VALUE_INF, alpha); beta = std::min(VALUE_INF, beta); - score = search(root_position, &ss[SS_PADDING], alpha, beta, - asp_window_depth, 0, false); + score = search(root_position, &ss[SS_PADDING], alpha, beta, asp_window_depth, 0, false); if (m_stopped) { break; @@ -306,10 +302,9 @@ Move Worker::iterative_deepening(const Position& root_position) { break; } - const auto total_nodes = std::reduce(std::begin(m_node_counts), std::end(m_node_counts), 0); - const auto best_move_nodes = m_node_counts[last_best_move.from_to()]; - const auto nodes_tm_fraction = - static_cast(best_move_nodes) / static_cast(total_nodes); + const auto total_nodes = std::reduce(std::begin(m_node_counts), std::end(m_node_counts), 0); + const auto best_move_nodes = m_node_counts[last_best_move.from_to()]; + const auto nodes_tm_fraction = static_cast(best_move_nodes) / static_cast(total_nodes); // Check soft node limit if (IS_MAIN && search_nodes() >= m_search_limits.soft_node_limit) { @@ -326,8 +321,7 @@ Move Worker::iterative_deepening(const Position& root_position) { complexity = 0.6 * abs(base_search_score - score) * std::log(search_depth); } m_search_limits.soft_time_limit = TM::compute_soft_limit( - m_search_start, m_searcher.settings, root_position.active_color(), nodes_tm_fraction, - complexity); + m_search_start, m_searcher.settings, root_position.active_color(), nodes_tm_fraction, complexity); } // check soft time limit @@ -350,8 +344,7 @@ Move Worker::iterative_deepening(const Position& root_position) { } template -Value Worker::search( - const Position& pos, Stack* ss, Value alpha, Value beta, Depth depth, i32 ply, bool cutnode) { +Value Worker::search(const Position& pos, Stack* ss, Value alpha, Value beta, Depth depth, i32 ply, bool cutnode) { ss->pv.clear(); if (m_stopped) { @@ -416,8 +409,7 @@ Value Worker::search( if (!PV_NODE && tt_data) { if (tt_data->depth >= depth - && (tt_data->bound() == Bound::Exact - || (tt_data->bound() == Bound::Lower && tt_data->score >= beta) + && (tt_data->bound() == Bound::Exact || (tt_data->bound() == Bound::Lower && tt_data->score >= beta) || (tt_data->bound() == Bound::Upper && tt_data->score <= alpha))) { return tt_data->score; } @@ -435,7 +427,7 @@ Value Worker::search( correction = m_td.history.get_correction(pos); raw_eval = tt_data && !is_mate_score(tt_data->eval) ? tt_data->eval : evaluate(pos); ss->static_eval = raw_eval + correction; - improving = (ss - 2)->static_eval != -VALUE_INF && ss->static_eval > (ss - 2)->static_eval; + improving = (ss - 2)->static_eval != -VALUE_INF && ss->static_eval > (ss - 2)->static_eval; if (!tt_data) { m_searcher.tt.store(pos, ply, raw_eval, Move::none(), -VALUE_INF, 0, ttpv, Bound::None); @@ -461,14 +453,12 @@ Value Worker::search( if (!PV_NODE && !is_in_check && !pos.is_kp_endgame() && depth >= tuned::nmp_depth && !excluded && tt_adjusted_eval >= beta + 30 && !is_being_mated_score(beta) && !m_in_nmp_verification) { - int R = - tuned::nmp_base_r + depth / 4 + std::min(3, (tt_adjusted_eval - beta) / 400) + improving; + int R = tuned::nmp_base_r + depth / 4 + std::min(3, (tt_adjusted_eval - beta) / 400) + improving; Position pos_after = pos.null_move(); repetition_info.push(pos_after.get_hash_key(), true); - Value null_score = -search(pos_after, ss + 1, -beta, -beta + 1, depth - R, - ply + 1, !cutnode); + Value null_score = -search(pos_after, ss + 1, -beta, -beta + 1, depth - R, ply + 1, !cutnode); repetition_info.pop(); @@ -482,8 +472,7 @@ Value Worker::search( } m_in_nmp_verification = true; - Value verification = - search(pos, ss, beta - 1, beta, depth - R, ply, false); + Value verification = search(pos, ss, beta - 1, beta, depth - R, ply, false); m_in_nmp_verification = false; if (verification >= beta) { @@ -493,8 +482,7 @@ Value Worker::search( } // Razoring - if (!PV_NODE && !excluded && !is_in_check && depth <= 7 - && ss->static_eval + 707 * depth < alpha) { + if (!PV_NODE && !excluded && !is_in_check && depth <= 7 && ss->static_eval + 707 * depth < alpha) { const Value razor_score = quiesce(pos, ss, alpha, beta, ply); if (razor_score <= alpha) { return razor_score; @@ -558,10 +546,10 @@ Value Worker::search( Value singular_beta = tt_data->score - depth * 5; int singular_depth = depth / 2; - ss->excluded_move = m; - Value singular_value = search(pos, ss, singular_beta - 1, singular_beta, - singular_depth, ply, cutnode); - ss->excluded_move = Move::none(); + ss->excluded_move = m; + Value singular_value = + search(pos, ss, singular_beta - 1, singular_beta, singular_depth, ply, cutnode); + ss->excluded_move = Move::none(); if (singular_value < singular_beta) { extension = 1; @@ -594,22 +582,18 @@ Value Worker::search( if (SEE::value(captured) > SEE::value(PieceType::Pawn)) { if (non_pawn_material < 0) { - non_pawn_material = - static_cast(pos.ipiece_count(Color::White, PieceType::Queen) - + pos.ipiece_count(Color::Black, PieceType::Queen)) - * SEE::value(PieceType::Queen); - non_pawn_material += - static_cast(pos.ipiece_count(Color::White, PieceType::Rook) - + pos.ipiece_count(Color::Black, PieceType::Rook)) - * SEE::value(PieceType::Rook); - non_pawn_material += - static_cast(pos.ipiece_count(Color::White, PieceType::Bishop) - + pos.ipiece_count(Color::Black, PieceType::Bishop)) - * SEE::value(PieceType::Bishop); - non_pawn_material += - static_cast(pos.ipiece_count(Color::White, PieceType::Knight) - + pos.ipiece_count(Color::Black, PieceType::Knight)) - * SEE::value(PieceType::Knight); + non_pawn_material = static_cast(pos.ipiece_count(Color::White, PieceType::Queen) + + pos.ipiece_count(Color::Black, PieceType::Queen)) + * SEE::value(PieceType::Queen); + non_pawn_material += static_cast(pos.ipiece_count(Color::White, PieceType::Rook) + + pos.ipiece_count(Color::Black, PieceType::Rook)) + * SEE::value(PieceType::Rook); + non_pawn_material += static_cast(pos.ipiece_count(Color::White, PieceType::Bishop) + + pos.ipiece_count(Color::Black, PieceType::Bishop)) + * SEE::value(PieceType::Bishop); + non_pawn_material += static_cast(pos.ipiece_count(Color::White, PieceType::Knight) + + pos.ipiece_count(Color::Black, PieceType::Knight)) + * SEE::value(PieceType::Knight); } if (non_pawn_material <= 2 * SEE::value(PieceType::Rook)) { @@ -634,11 +618,9 @@ Value Worker::search( i32 reduction; if (quiet) { - reduction = - static_cast(788 + 208 * log2i(depth) * log2i(moves_played) / (1024 * 1024)); + reduction = static_cast(788 + 208 * log2i(depth) * log2i(moves_played) / (1024 * 1024)); } else { - reduction = - static_cast(256 + 197 * log2i(depth) * log2i(moves_played) / (1024 * 1024)); + reduction = static_cast(256 + 197 * log2i(depth) * log2i(moves_played) / (1024 * 1024)); } reduction -= 1024 * PV_NODE; @@ -685,25 +667,20 @@ Value Worker::search( reduction /= 1024; Depth reduced_depth = std::clamp(new_depth - reduction, 1, new_depth); - value = -search(pos_after, ss + 1, -alpha - 1, -alpha, reduced_depth, - ply + 1, true); + value = -search(pos_after, ss + 1, -alpha - 1, -alpha, reduced_depth, ply + 1, true); if (value > alpha && reduced_depth < new_depth) { - value = -search(pos_after, ss + 1, -alpha - 1, -alpha, new_depth, - ply + 1, !cutnode); + value = -search(pos_after, ss + 1, -alpha - 1, -alpha, new_depth, ply + 1, !cutnode); if (quiet && (value <= alpha || value >= beta)) { m_td.history.update_cont_hist(pos, m, ply, ss, - value <= alpha ? -stat_bonus(new_depth) - : stat_bonus(new_depth)); + value <= alpha ? -stat_bonus(new_depth) : stat_bonus(new_depth)); } } } else if (!PV_NODE || moves_played > 1) { - value = -search(pos_after, ss + 1, -alpha - 1, -alpha, new_depth, - ply + 1, !cutnode); + value = -search(pos_after, ss + 1, -alpha - 1, -alpha, new_depth, ply + 1, !cutnode); } if (PV_NODE && (moves_played == 1 || value > alpha)) { - value = - -search(pos_after, ss + 1, -beta, -alpha, new_depth, ply + 1, false); + value = -search(pos_after, ss + 1, -beta, -alpha, new_depth, ply + 1, false); } const auto nodes_after = m_search_nodes.load(std::memory_order::relaxed); if (ROOT_NODE) { @@ -778,17 +755,12 @@ Value Worker::search( } if (!excluded) { - Bound bound = best_value >= beta ? Bound::Lower - : best_move != Move::none() ? Bound::Exact - : Bound::Upper; - Move tt_move = best_move != Move::none() ? best_move - : tt_data ? tt_data->move - : Move::none(); + Bound bound = best_value >= beta ? Bound::Lower : best_move != Move::none() ? Bound::Exact : Bound::Upper; + Move tt_move = best_move != Move::none() ? best_move : tt_data ? tt_data->move : Move::none(); m_searcher.tt.store(pos, ply, raw_eval, tt_move, best_value, depth, ttpv, bound); // Update to correction history. - if (!is_in_check - && !(best_move != Move::none() && (best_move.is_capture() || best_move.is_promotion())) + if (!is_in_check && !(best_move != Move::none() && (best_move.is_capture() || best_move.is_promotion())) && !((bound == Bound::Lower && best_value <= ss->static_eval) || (bound == Bound::Upper && best_value >= ss->static_eval))) { m_td.history.update_correction_history(pos, depth, best_value - raw_eval); @@ -833,8 +805,7 @@ Value Worker::quiesce(const Position& pos, Stack* ss, Value alpha, Value beta, i // TT Probing auto tt_data = m_searcher.tt.probe(pos, ply); if (tt_data - && (tt_data->bound() == Bound::Exact - || (tt_data->bound() == Bound::Lower && tt_data->score >= beta) + && (tt_data->bound() == Bound::Exact || (tt_data->bound() == Bound::Lower && tt_data->score >= beta) || (tt_data->bound() == Bound::Upper && tt_data->score <= alpha))) { return tt_data->score; } @@ -936,9 +907,8 @@ Value Worker::quiesce(const Position& pos, Stack* ss, Value alpha, Value beta, i Value Worker::evaluate(const Position& pos) { #ifndef EVAL_TUNING - return std::clamp( - static_cast(Clockwork::evaluate_stm_pov(pos, m_td.psqt_states.back())), -VALUE_WIN + 1, - VALUE_WIN - 1); + return std::clamp(static_cast(Clockwork::evaluate_stm_pov(pos, m_td.psqt_states.back())), + -VALUE_WIN + 1, VALUE_WIN - 1); #else return -VALUE_INF; // Not implemented in tune mode #endif diff --git a/src/search.hpp b/src/search.hpp index 53a8f07c..fc1635b6 100644 --- a/src/search.hpp +++ b/src/search.hpp @@ -40,9 +40,7 @@ enum class ThreadType { struct PV { public: - void clear() { - m_pv.clear(); - } + void clear() { m_pv.clear(); } void set(Move move, const PV& child_pv_line) { m_pv.clear(); @@ -50,9 +48,7 @@ struct PV { m_pv.append(child_pv_line.m_pv); } - Move first_move() const { - return m_pv.empty() ? Move::none() : m_pv[0]; - } + Move first_move() const { return m_pv.empty() ? Move::none() : m_pv[0]; } friend std::ostream& operator<<(std::ostream& os, const PV& pv); @@ -86,9 +82,7 @@ struct ThreadData { return psqt_states.back(); } - void pop_psqt_state() { - psqt_states.pop_back(); - } + void pop_psqt_state() { psqt_states.pop_back(); } }; class Searcher { @@ -118,9 +112,7 @@ class Searcher { u64 node_count(); void reset(); - void resize_tt(size_t mb) { - tt.resize(mb); - } + void resize_tt(size_t mb) { tt.resize(mb); } private: std::vector> m_workers; @@ -139,19 +131,11 @@ class alignas(128) Worker { void prepare(); void start_searching(); - void set_stopped() { - m_stopped = true; - } - void reset_thread_data() { - m_td = {}; - } + void set_stopped() { m_stopped = true; } + void reset_thread_data() { m_td = {}; } - [[nodiscard]] ThreadType thread_type() const { - return m_thread_type; - } - [[nodiscard]] u64 search_nodes() const { - return m_search_nodes.load(std::memory_order_relaxed); - } + [[nodiscard]] ThreadType thread_type() const { return m_thread_type; } + [[nodiscard]] u64 search_nodes() const { return m_search_nodes.load(std::memory_order_relaxed); } [[nodiscard]] Value get_draw_score() const { return (search_nodes() & 3) - 2; // Randomize between -2 and +2 @@ -160,9 +144,7 @@ class alignas(128) Worker { private: void thread_main(); - void increment_search_nodes() { - m_search_nodes.fetch_add(1, std::memory_order_relaxed); - } + void increment_search_nodes() { m_search_nodes.fetch_add(1, std::memory_order_relaxed); } std::atomic m_search_nodes; time::TimePoint m_search_start; @@ -181,8 +163,7 @@ class alignas(128) Worker { template Move iterative_deepening(const Position& root_position); template - Value search( - const Position& pos, Stack* ss, Value alpha, Value beta, Depth depth, i32 ply, bool cutnode); + Value search(const Position& pos, Stack* ss, Value alpha, Value beta, Depth depth, i32 ply, bool cutnode); template Value quiesce(const Position& pos, Stack* ss, Value alpha, Value beta, i32 ply); Value evaluate(const Position& pos); diff --git a/src/speedtest.cpp b/src/speedtest.cpp index 84d21355..8e7bace8 100644 --- a/src/speedtest.cpp +++ b/src/speedtest.cpp @@ -371,9 +371,8 @@ void speedtest(Search::Searcher& searcher) { } const int bar_width = 50; - float progress = - static_cast(positions_processed) / static_cast(total_positions); - int bar_pos = static_cast(bar_width * progress); + float progress = static_cast(positions_processed) / static_cast(total_positions); + int bar_pos = static_cast(bar_width * progress); std::cout << "["; for (int i = 0; i < bar_width; ++i) { @@ -389,9 +388,7 @@ void speedtest(Search::Searcher& searcher) { auto end_time = time::Clock::now(); auto duration_ms = time::cast(end_time - start_time).count(); - f64 nps = (duration_ms > 0) - ? (static_cast(total_nodes) * 1000.0 / static_cast(duration_ms)) - : 0.0; + f64 nps = (duration_ms > 0) ? (static_cast(total_nodes) * 1000.0 / static_cast(duration_ms)) : 0.0; std::cout << std::endl; std::cout << "Speedtest finished." << std::endl; diff --git a/src/square.hpp b/src/square.hpp index ea59f5c7..47c7330a 100644 --- a/src/square.hpp +++ b/src/square.hpp @@ -13,9 +13,7 @@ namespace Clockwork { struct Square { u8 raw = 0x80; - static constexpr Square invalid() { - return {0x80}; - } + static constexpr Square invalid() { return {0x80}; } static constexpr Square from_file_and_rank(i32 file, i32 rank) { assert(file >= 0 && file < 8); @@ -38,37 +36,21 @@ struct Square { return from_file_and_rank(file, rank); } - [[nodiscard]] constexpr i32 file() const { - return raw % 8; - } + [[nodiscard]] constexpr i32 file() const { return raw % 8; } - [[nodiscard]] constexpr i32 rank() const { - return raw / 8; - } + [[nodiscard]] constexpr i32 rank() const { return raw / 8; } - [[nodiscard]] constexpr Color color() const { - return ((file() + rank()) & 1) ? Color::White : Color::Black; - } + [[nodiscard]] constexpr Color color() const { return ((file() + rank()) & 1) ? Color::White : Color::Black; } - [[nodiscard]] constexpr Square relative_sq(Color c) const { - return c == Color::White ? *this : flip_vertical(); - } + [[nodiscard]] constexpr Square relative_sq(Color c) const { return c == Color::White ? *this : flip_vertical(); } - [[nodiscard]] constexpr std::tuple to_file_and_rank() const { - return {file(), rank()}; - } + [[nodiscard]] constexpr std::tuple to_file_and_rank() const { return {file(), rank()}; } - [[nodiscard]] constexpr bool is_valid() const { - return (raw & 0x80) == 0; - } + [[nodiscard]] constexpr bool is_valid() const { return (raw & 0x80) == 0; } - constexpr Square flip_horizontal() const { - return Square{static_cast(raw ^ 7)}; - } + constexpr Square flip_horizontal() const { return Square{static_cast(raw ^ 7)}; } - constexpr Square flip_vertical() const { - return Square{static_cast(raw ^ 56)}; - } + constexpr Square flip_vertical() const { return Square{static_cast(raw ^ 56)}; } template constexpr Square push() const { diff --git a/src/tm.cpp b/src/tm.cpp index f7730805..2c38709a 100644 --- a/src/tm.cpp +++ b/src/tm.cpp @@ -4,9 +4,8 @@ #include namespace Clockwork::TM { -time::TimePoint compute_hard_limit(time::TimePoint search_start, - const Search::SearchSettings& settings, - const Color stm) { +time::TimePoint compute_hard_limit(time::TimePoint search_start, const Search::SearchSettings& settings, + const Color stm) { using namespace std; using namespace time; @@ -31,11 +30,8 @@ time::TimePoint compute_hard_limit(time::TimePoint search_start, } template -time::TimePoint compute_soft_limit(time::TimePoint search_start, - const Search::SearchSettings& settings, - const Color stm, - const f64 nodes_tm_fraction, - const f64 complexity) { +time::TimePoint compute_soft_limit(time::TimePoint search_start, const Search::SearchSettings& settings, + const Color stm, const f64 nodes_tm_fraction, const f64 complexity) { using namespace std; using namespace time; @@ -66,20 +62,18 @@ time::TimePoint compute_soft_limit(time::TimePoint search_start, return std::max(0.77 + std::clamp(complexity, 0.0, 200.0) / 386.0, 1.0); }; - soft_limit = - min(soft_limit, - search_start - + Milliseconds(static_cast(compute_buffer_time() * compute_nodestm_factor() - * compute_complexitytm_factor()))); + soft_limit = min(soft_limit, search_start + + Milliseconds(static_cast(compute_buffer_time() * compute_nodestm_factor() + * compute_complexitytm_factor()))); } return soft_limit; } // Explicit instantiations -template time::TimePoint compute_soft_limit( - time::TimePoint, const Search::SearchSettings&, const Color, const f64, const f64); +template time::TimePoint compute_soft_limit(time::TimePoint, const Search::SearchSettings&, const Color, + const f64, const f64); -template time::TimePoint compute_soft_limit( - time::TimePoint, const Search::SearchSettings&, const Color, const f64, const f64); +template time::TimePoint compute_soft_limit(time::TimePoint, const Search::SearchSettings&, const Color, + const f64, const f64); } // namespace Clockwork::TM diff --git a/src/tm.hpp b/src/tm.hpp index 5901095f..3e1da8ea 100644 --- a/src/tm.hpp +++ b/src/tm.hpp @@ -6,14 +6,10 @@ namespace Clockwork::TM { constexpr time::Milliseconds UCI_LATENCY(50); -time::TimePoint compute_hard_limit(time::TimePoint search_start, - const Search::SearchSettings& settings, - const Color stm); +time::TimePoint compute_hard_limit(time::TimePoint search_start, const Search::SearchSettings& settings, + const Color stm); template -time::TimePoint compute_soft_limit(time::TimePoint search_start, - const Search::SearchSettings& settings, - const Color stm, - const f64 nodes_tm_fraction, - const f64 complexity); +time::TimePoint compute_soft_limit(time::TimePoint search_start, const Search::SearchSettings& settings, + const Color stm, const f64 nodes_tm_fraction, const f64 complexity); // Will add soft tm and other helper functions here } // namespace Clockwork::TM diff --git a/src/tt.cpp b/src/tt.cpp index 751131e4..2943595c 100644 --- a/src/tt.cpp +++ b/src/tt.cpp @@ -31,8 +31,7 @@ void aligned_free(void* ptr) { } [[nodiscard]] static u8 make_tt_info(bool is_tt_pv, Bound bound, u8 age) { - return static_cast(bound) | (static_cast(static_cast(is_tt_pv) << 2)) - | static_cast(age << 3); + return static_cast(bound) | (static_cast(static_cast(is_tt_pv) << 2)) | static_cast(age << 3); } i16 score_to_tt(Value score, i32 ply) { @@ -88,14 +87,7 @@ std::optional TT::probe(const Position& pos, i32 ply) const { return {}; } -void TT::store(const Position& pos, - i32 ply, - Value eval, - Move move, - Value score, - Depth depth, - bool ttpv, - Bound bound) { +void TT::store(const Position& pos, i32 ply, Value eval, Move move, Value score, Depth depth, bool ttpv, Bound bound) { size_t cluster_index = mulhi64(pos.get_hash_key(), m_size); auto cluster = this->m_clusters[cluster_index].load(); const auto key = shrink_key(pos.get_hash_key()); @@ -129,10 +121,7 @@ void TT::store(const Position& pos, // give entries a bonus for type: // exact = 3, lower = 2, upper = 1 - i32 insert_flag_bonus = bound == Bound::Exact ? 3 - : bound == Bound::Lower ? 2 - : bound == Bound::Upper ? 1 - : 0; + i32 insert_flag_bonus = bound == Bound::Exact ? 3 : bound == Bound::Lower ? 2 : bound == Bound::Upper ? 1 : 0; i32 record_flag_bonus = tte.bound() == Bound::Exact ? 3 : tte.bound() == Bound::Lower ? 2 : tte.bound() == Bound::Upper ? 1 @@ -140,9 +129,8 @@ void TT::store(const Position& pos, i32 age_differential = (MAX_AGE + m_age - tte.age()) & AGE_MASK; - i32 insert_priority = - depth + insert_flag_bonus + (age_differential * age_differential) / 4; //+ i32::from(pv); - i32 record_prority = tte.depth + record_flag_bonus; + i32 insert_priority = depth + insert_flag_bonus + (age_differential * age_differential) / 4; //+ i32::from(pv); + i32 record_prority = tte.depth + record_flag_bonus; if (tte.key16 != key || (bound == Bound::Exact && tte.bound() != Bound::Exact) || insert_priority * 3 >= record_prority * 2) { diff --git a/src/tt.hpp b/src/tt.hpp index 5d720f92..5e4dec4d 100644 --- a/src/tt.hpp +++ b/src/tt.hpp @@ -22,15 +22,9 @@ struct TTEntry { u8 depth; u8 info; - [[nodiscard]] Bound bound() const { - return static_cast(info & 0b011); - } - [[nodiscard]] bool ttpv() const { - return static_cast(info & 0b100); - } - [[nodiscard]] u8 age() const { - return info >> 3; - } + [[nodiscard]] Bound bound() const { return static_cast(info & 0b011); } + [[nodiscard]] bool ttpv() const { return static_cast(info & 0b100); } + [[nodiscard]] u8 age() const { return info >> 3; } }; struct TTCluster { @@ -70,15 +64,9 @@ struct TTData { Depth depth; u8 info; - [[nodiscard]] Bound bound() const { - return static_cast(info & 0b011); - } - [[nodiscard]] bool ttpv() const { - return static_cast(info & 0b100); - } - [[nodiscard]] u8 age() const { - return info >> 3; - } + [[nodiscard]] Bound bound() const { return static_cast(info & 0b011); } + [[nodiscard]] bool ttpv() const { return static_cast(info & 0b100); } + [[nodiscard]] u8 age() const { return info >> 3; } }; class TT { @@ -93,17 +81,11 @@ class TT { ~TT(); std::optional probe(const Position& position, i32 ply) const; - void store(const Position& position, - i32 ply, - Value eval, - Move move, - Value score, - Depth depth, - bool ttpv, - Bound bound); - void resize(size_t mb); - void clear(); - void increment_age(); + void store(const Position& position, i32 ply, Value eval, Move move, Value score, Depth depth, bool ttpv, + Bound bound); + void resize(size_t mb); + void clear(); + void increment_age(); private: TTClusterMemory* m_clusters; diff --git a/src/tuned.cpp b/src/tuned.cpp index 250c71ed..81e20571 100644 --- a/src/tuned.cpp +++ b/src/tuned.cpp @@ -8,9 +8,8 @@ namespace Clockwork::tuned { void uci_print_tunable_options() { #if CLOCKWORK_IS_TUNING - #define TUNE(NAME, DEFAULTVAL, MINVAL, MAXVAL, ...) \ - std::cout << "option name tune_" #NAME " type spin default " #DEFAULTVAL " min " #MINVAL \ - " max " #MAXVAL \ + #define TUNE(NAME, DEFAULTVAL, MINVAL, MAXVAL, ...) \ + std::cout << "option name tune_" #NAME " type spin default " #DEFAULTVAL " min " #MINVAL " max " #MAXVAL \ << std::endl; #define NO_TUNE(...) /* do nothing */ CLOCKWORK_TUNABLES(TUNE, NO_TUNE) @@ -20,18 +19,15 @@ void uci_print_tunable_options() { } void uci_print_tunable_values() { -#define TUNE(NAME, DEFAULTVAL, MINVAL, MAXVAL, CEND, REND) \ - std::cout << "tune_" #NAME ", int, " #DEFAULTVAL ", " #MINVAL ", " #MAXVAL ", " #CEND \ - ", " #REND \ - << std::endl; +#define TUNE(NAME, DEFAULTVAL, MINVAL, MAXVAL, CEND, REND) \ + std::cout << "tune_" #NAME ", int, " #DEFAULTVAL ", " #MINVAL ", " #MAXVAL ", " #CEND ", " #REND << std::endl; #define NO_TUNE(...) /* do nothing */ CLOCKWORK_TUNABLES(TUNE, NO_TUNE) #undef TUNE #undef NO_TUNE } -bool uci_parse_tunable([[maybe_unused]] std::string_view name, - [[maybe_unused]] std::string_view value_str) { +bool uci_parse_tunable([[maybe_unused]] std::string_view name, [[maybe_unused]] std::string_view value_str) { #if CLOCKWORK_IS_TUNING #define TUNE(NAME, DEFAULTVAL, MINVAL, MAXVAL, ...) \ if (name == "tune_" #NAME) { \ diff --git a/src/tuning/dataset.hpp b/src/tuning/dataset.hpp index 5d4291e7..fce345fc 100644 --- a/src/tuning/dataset.hpp +++ b/src/tuning/dataset.hpp @@ -28,12 +28,8 @@ class Dataset { Dataset(const std::string& file_path); ~Dataset(); - const std::vector& lines() const { - return m_lines; - } - size_t size() const { - return m_lines.size(); - } + const std::vector& lines() const { return m_lines; } + size_t size() const { return m_lines.size(); } }; class DataLoader { diff --git a/src/tuning/globals.hpp b/src/tuning/globals.hpp index e573930f..aa877f88 100644 --- a/src/tuning/globals.hpp +++ b/src/tuning/globals.hpp @@ -24,8 +24,7 @@ class Globals { usize register_param(ValuePlaceholder* param) { if (m_locked) { - std::cerr << "Attempted to register new global parameter after Globals has been locked" - << std::endl; + std::cerr << "Attempted to register new global parameter after Globals has been locked" << std::endl; std::terminate(); } usize index = m_parameters.size(); @@ -35,8 +34,7 @@ class Globals { usize register_param(PairPlaceholder* param) { if (m_locked) { - std::cerr << "Attempted to register new global parameter after Globals has been locked" - << std::endl; + std::cerr << "Attempted to register new global parameter after Globals has been locked" << std::endl; std::terminate(); } usize index = m_pair_parameters.size(); @@ -64,9 +62,7 @@ class Globals { bool is_pair_parameter_constant(usize i) const; private: - void lock() const { - m_locked = true; - } + void lock() const { m_locked = true; } mutable std::atomic m_locked = false; std::vector m_parameters; @@ -78,32 +74,19 @@ class ValuePlaceholder { explicit ValuePlaceholder(f64 default_value, bool constant) : m_index(Globals::get().register_param(this)), m_default_value(default_value), - m_constant(constant) { - } + m_constant(constant) {} - static ValuePlaceholder create_tunable(f64 a) { - return ValuePlaceholder(a, false); - } + static ValuePlaceholder create_tunable(f64 a) { return ValuePlaceholder(a, false); } - static ValuePlaceholder create(f64 a) { - return ValuePlaceholder(a, true); - } + static ValuePlaceholder create(f64 a) { return ValuePlaceholder(a, true); } - operator ValuePtr() const { - return Graph::get().get_parameter(m_index); - } + operator ValuePtr() const { return Graph::get().get_parameter(m_index); } - usize index() const { - return m_index; - } + usize index() const { return m_index; } - f64 default_value() const { - return m_default_value; - } + f64 default_value() const { return m_default_value; } - bool constant() const { - return m_constant; - } + bool constant() const { return m_constant; } private: usize m_index; @@ -145,32 +128,19 @@ class PairPlaceholder { explicit PairPlaceholder(f128 default_value, bool constant) : m_index(Globals::get().register_param(this)), m_default_value(default_value), - m_constant(constant) { - } + m_constant(constant) {} - static PairPlaceholder create_tunable(f64 a, f64 b) { - return PairPlaceholder(f128::make(a, b), false); - } + static PairPlaceholder create_tunable(f64 a, f64 b) { return PairPlaceholder(f128::make(a, b), false); } - static PairPlaceholder create(f64 a, f64 b) { - return PairPlaceholder(f128::make(a, b), true); - } + static PairPlaceholder create(f64 a, f64 b) { return PairPlaceholder(f128::make(a, b), true); } - operator PairPtr() const { - return Graph::get().get_pair_parameter(m_index); - } + operator PairPtr() const { return Graph::get().get_pair_parameter(m_index); } - usize index() const { - return m_index; - } + usize index() const { return m_index; } - f128 default_value() const { - return m_default_value; - } + f128 default_value() const { return m_default_value; } - bool constant() const { - return m_constant; - } + bool constant() const { return m_constant; } private: usize m_index; diff --git a/src/tuning/graph.cpp b/src/tuning/graph.cpp index 706ee5c9..dd6ff12f 100644 --- a/src/tuning/graph.cpp +++ b/src/tuning/graph.cpp @@ -8,8 +8,7 @@ Graph::Graph() { register_param(std::make_shared(placeholder->default_value())); } for (PairPlaceholder* placeholder : Globals::get().get_pair_parameters()) { - register_param( - std::make_shared(placeholder->default_value(), placeholder->constant())); + register_param(std::make_shared(placeholder->default_value(), placeholder->constant())); } } diff --git a/src/tuning/graph.hpp b/src/tuning/graph.hpp index 5f029677..677affb1 100644 --- a/src/tuning/graph.hpp +++ b/src/tuning/graph.hpp @@ -34,13 +34,9 @@ class Graph { Graph(); - void register_param(const ValuePtr& param) { - m_parameters.push_back(param); - } + void register_param(const ValuePtr& param) { m_parameters.push_back(param); } - void register_param(const PairPtr& param) { - m_pair_parameters.push_back(param); - } + void register_param(const PairPtr& param) { m_pair_parameters.push_back(param); } public: static Graph& get() { @@ -49,9 +45,7 @@ class Graph { } // ------------------ Registration ------------------ - void register_value(const BackwardablePtr& node) { - m_backwardables.push_back(node); - } + void register_value(const BackwardablePtr& node) { m_backwardables.push_back(node); } void register_value(const ValuePtr& node) { m_backwardables.push_back(std::static_pointer_cast(node)); @@ -119,9 +113,7 @@ class Graph { } } - void clear_backwardables() { - m_backwardables.clear(); - } + void clear_backwardables() { m_backwardables.clear(); } // ------------------ Cleanup ------------------ void cleanup() { @@ -147,18 +139,10 @@ class Graph { } // ------------------ Accessors ------------------ - const std::vector& get_parameters() const { - return m_parameters; - } - const std::vector& get_pair_parameters() const { - return m_pair_parameters; - } - ValuePtr get_parameter(usize index) const { - return m_parameters[index]; - } - PairPtr get_pair_parameter(usize index) const { - return m_pair_parameters[index]; - } + const std::vector& get_parameters() const { return m_parameters; } + const std::vector& get_pair_parameters() const { return m_pair_parameters; } + ValuePtr get_parameter(usize index) const { return m_parameters[index]; } + PairPtr get_pair_parameter(usize index) const { return m_pair_parameters[index]; } }; } // namespace Clockwork::Autograd diff --git a/src/tuning/info.hpp b/src/tuning/info.hpp index ce6d01e4..e7b1d086 100644 --- a/src/tuning/info.hpp +++ b/src/tuning/info.hpp @@ -41,8 +41,7 @@ struct Parameters { parameters[i] += weight * b.parameters[i]; } for (usize i = 0; i < pair_parameters.size(); i++) { - pair_parameters[i] = - f128::madd(pair_parameters[i], f128::broadcast(weight), b.pair_parameters[i]); + pair_parameters[i] = f128::madd(pair_parameters[i], f128::broadcast(weight), b.pair_parameters[i]); } } }; diff --git a/src/tuning/optim.hpp b/src/tuning/optim.hpp index 037e0598..1b9d2376 100644 --- a/src/tuning/optim.hpp +++ b/src/tuning/optim.hpp @@ -66,12 +66,8 @@ class SGD { } } - void set_lr(f64 lr) { - m_lr = lr; - } - f64 get_lr() const { - return m_lr; - } + void set_lr(f64 lr) { m_lr = lr; } + f64 get_lr() const { return m_lr; } }; @@ -92,12 +88,8 @@ class AdamW { std::vector m_pair_v; public: - explicit AdamW(ParameterCountInfo counts, - f64 lr = 1e-3, - f64 beta1 = 0.9, - f64 beta2 = 0.999, - f64 eps = 1e-8, - f64 weight_decay = 0.01) : + explicit AdamW(ParameterCountInfo counts, f64 lr = 1e-3, f64 beta1 = 0.9, f64 beta2 = 0.999, f64 eps = 1e-8, + f64 weight_decay = 0.01) : m_counts(counts), m_lr(lr), m_beta1(beta1), @@ -182,12 +174,8 @@ class AdamW { } } - void set_lr(f64 lr) { - m_lr = lr; - } - f64 get_lr() const { - return m_lr; - } + void set_lr(f64 lr) { m_lr = lr; } + f64 get_lr() const { return m_lr; } }; } // namespace Clockwork::Autograd diff --git a/src/tuning/value.hpp b/src/tuning/value.hpp index 73c23015..5e92f7d8 100644 --- a/src/tuning/value.hpp +++ b/src/tuning/value.hpp @@ -56,22 +56,12 @@ class Value : public SmartBackwardable { explicit Value(f64 data) : m_value(data) {}; - inline f64 get_value() const { - return m_value; - } - inline void change_value(f64 amount) { - m_value += amount; - } - inline void set_value(f64 value) { - m_value = value; - } - inline f64 get_gradient() const { - return m_gradient; - } + inline f64 get_value() const { return m_value; } + inline void change_value(f64 amount) { m_value += amount; } + inline void set_value(f64 value) { m_value = value; } + inline f64 get_gradient() const { return m_gradient; } - inline void zero_grad() { - m_gradient = 0.0; - } + inline void zero_grad() { m_gradient = 0.0; } static ValuePtr create(f64 data); ValuePtr exp() { @@ -98,8 +88,7 @@ class Value : public SmartBackwardable { auto this_value = this->shared_from_this(); ValuePtr result = Value::create(1 / (1 + std::exp(-this_value->m_value))); result->m_backward_func = [this_value](ValuePtr out) { - f64 grad = out->m_value - * (1 - out->m_value); // Same trick as before, avoid recomputing sigmoid(x) + f64 grad = out->m_value * (1 - out->m_value); // Same trick as before, avoid recomputing sigmoid(x) this_value->m_gradient += grad * out->m_gradient; }; return result; @@ -109,9 +98,8 @@ class Value : public SmartBackwardable { auto this_value = this->shared_from_this(); ValuePtr result = Value::create(std::pow(this_value->m_value, exponent->m_value)); result->m_backward_func = [this_value, exponent](ValuePtr out) { - this_value->m_gradient += exponent->m_value - * std::pow(this_value->m_value, exponent->m_value - 1) - * out->m_gradient; + this_value->m_gradient += + exponent->m_value * std::pow(this_value->m_value, exponent->m_value - 1) * out->m_gradient; exponent->m_gradient += out->m_value * std::log(this_value->m_value) * out->m_gradient; }; return result; @@ -121,15 +109,12 @@ class Value : public SmartBackwardable { auto this_value = this->shared_from_this(); ValuePtr result = Value::create(std::pow(this_value->m_value, exponent)); result->m_backward_func = [this_value, exponent](ValuePtr out) { - this_value->m_gradient += - exponent * std::pow(this_value->m_value, exponent - 1) * out->m_gradient; + this_value->m_gradient += exponent * std::pow(this_value->m_value, exponent - 1) * out->m_gradient; }; return result; } - void add_gradient(f64 rhs) { - m_gradient += rhs; - } + void add_gradient(f64 rhs) { m_gradient += rhs; } friend ValuePtr operator-(ValuePtr a) { ValuePtr result = Value::create(-a->m_value); @@ -180,52 +165,38 @@ class Value : public SmartBackwardable { friend ValuePtr operator+(ValuePtr a, f64 b) { ValuePtr result = Value::create(a->m_value + b); - result->m_backward_func = [a](ValuePtr out) { - a->m_gradient += out->m_gradient; - }; + result->m_backward_func = [a](ValuePtr out) { a->m_gradient += out->m_gradient; }; return result; } friend ValuePtr operator-(ValuePtr a, f64 b) { ValuePtr result = Value::create(a->m_value - b); - result->m_backward_func = [a](ValuePtr out) { - a->m_gradient += out->m_gradient; - }; + result->m_backward_func = [a](ValuePtr out) { a->m_gradient += out->m_gradient; }; return result; } friend ValuePtr operator*(ValuePtr a, f64 b) { ValuePtr result = Value::create(a->m_value * b); - result->m_backward_func = [a, b](ValuePtr out) { - a->m_gradient += b * out->m_gradient; - }; + result->m_backward_func = [a, b](ValuePtr out) { a->m_gradient += b * out->m_gradient; }; return result; } friend ValuePtr operator/(ValuePtr a, f64 b) { // We are NOT cheaping out with a * (std::pow(b,-1)) ValuePtr result = Value::create(a->m_value / b); - result->m_backward_func = [a, b](ValuePtr out) { - a->m_gradient += 1.0 / b * out->m_gradient; - }; + result->m_backward_func = [a, b](ValuePtr out) { a->m_gradient += 1.0 / b * out->m_gradient; }; return result; } - friend ValuePtr operator+(f64 a, ValuePtr b) { - return b + a; - } + friend ValuePtr operator+(f64 a, ValuePtr b) { return b + a; } friend ValuePtr operator-(f64 a, ValuePtr b) { ValuePtr result = Value::create(a - b->m_value); - result->m_backward_func = [b](ValuePtr out) { - b->m_gradient -= out->m_gradient; - }; + result->m_backward_func = [b](ValuePtr out) { b->m_gradient -= out->m_gradient; }; return result; } - friend ValuePtr operator*(f64 a, ValuePtr b) { - return b * a; - } + friend ValuePtr operator*(f64 a, ValuePtr b) { return b * a; } friend ValuePtr operator/(f64 a, ValuePtr b) { ValuePtr result = Value::create(a / b->m_value); @@ -262,29 +233,17 @@ class Value : public SmartBackwardable { } - friend bool operator==(ValuePtr a, ValuePtr b) { - return a->m_value == b->m_value; - } + friend bool operator==(ValuePtr a, ValuePtr b) { return a->m_value == b->m_value; } - friend bool operator!=(ValuePtr a, ValuePtr b) { - return a->m_value != b->m_value; - } + friend bool operator!=(ValuePtr a, ValuePtr b) { return a->m_value != b->m_value; } - friend bool operator<(ValuePtr a, ValuePtr b) { - return a->m_value < b->m_value; - } + friend bool operator<(ValuePtr a, ValuePtr b) { return a->m_value < b->m_value; } - friend bool operator<=(ValuePtr a, ValuePtr b) { - return a->m_value <= b->m_value; - } + friend bool operator<=(ValuePtr a, ValuePtr b) { return a->m_value <= b->m_value; } - friend bool operator>(ValuePtr a, ValuePtr b) { - return a->m_value > b->m_value; - } + friend bool operator>(ValuePtr a, ValuePtr b) { return a->m_value > b->m_value; } - friend bool operator>=(ValuePtr a, ValuePtr b) { - return a->m_value >= b->m_value; - } + friend bool operator>=(ValuePtr a, ValuePtr b) { return a->m_value >= b->m_value; } friend std::ostream& operator<<(std::ostream& os, const ValuePtr& value) { os << "Value(data=" << value->get_value() << ", grad=" << value->get_gradient() << ")"; @@ -314,53 +273,33 @@ class Pair : public SmartBackwardable { explicit Pair(f64 first, f64 second, bool constant = false) : m_constant(constant), m_values(f128::make(first, second)), - m_gradients(f128::zero()) { - } + m_gradients(f128::zero()) {} explicit Pair(const f128& values, bool constant = false) : m_constant(constant), m_values(values), - m_gradients(f128::zero()) { - } + m_gradients(f128::zero()) {} static PairPtr create(f64 first, f64 second); static PairPtr create(const f128& values); - inline f64 first() const { - return m_values.first(); - } + inline f64 first() const { return m_values.first(); } - inline f64 second() const { - return m_values.second(); - } + inline f64 second() const { return m_values.second(); } - inline f128 get_values() const { - return m_values; - } + inline f128 get_values() const { return m_values; } - inline f64 grad_first() const { - return m_gradients.first(); - } + inline f64 grad_first() const { return m_gradients.first(); } - inline f64 grad_second() const { - return m_gradients.second(); - } + inline f64 grad_second() const { return m_gradients.second(); } - inline f128 get_graidents() const { - return m_gradients; - } + inline f128 get_graidents() const { return m_gradients; } - inline void zero_grad() { - m_gradients = f128::zero(); - } + inline void zero_grad() { m_gradients = f128::zero(); } - inline void set_values(const f128& values) { - m_values = values; - } - inline void set_values(f64 first, f64 second) { - m_values = f128::make(first, second); - } + inline void set_values(const f128& values) { m_values = values; } + inline void set_values(f64 first, f64 second) { m_values = f128::make(first, second); } // ------------------- Backward ------------------- void backward() override { @@ -405,9 +344,7 @@ class Pair : public SmartBackwardable { return result; } - friend PairPtr operator*(f64 scalar, const PairPtr& a) { - return a * scalar; - } + friend PairPtr operator*(f64 scalar, const PairPtr& a) { return a * scalar; } // ------------------- Pair * Value ------------------- friend PairPtr operator*(const PairPtr& a, const ValuePtr& v) { @@ -426,9 +363,7 @@ class Pair : public SmartBackwardable { return result; } - friend PairPtr operator*(const ValuePtr& v, const PairPtr& a) { - return a * v; - } + friend PairPtr operator*(const ValuePtr& v, const PairPtr& a) { return a * v; } // ------------------- Pair / scalar ------------------- friend PairPtr operator/(const PairPtr& a, f64 scalar) { @@ -498,9 +433,7 @@ class Pair : public SmartBackwardable { f128 result_values = f128::neg(a->m_values); PairPtr result = Pair::create(result_values); - result->m_backward_func = [a](PairPtr out) { - a->m_gradients = f128::sub(a->m_gradients, out->m_gradients); - }; + result->m_backward_func = [a](PairPtr out) { a->m_gradients = f128::sub(a->m_gradients, out->m_gradients); }; return result; } @@ -528,12 +461,11 @@ class Pair : public SmartBackwardable { // ------------------- Print ------------------- friend std::ostream& operator<<(std::ostream& os, const PairPtr& p) { #ifdef VERBOSE_AUTOGRAD - os << "Pair(first=" << p->first() << ", second=" << p->second() - << ", grad_first=" << p->grad_first() << ", grad_second=" << p->grad_second() << ")"; + os << "Pair(first=" << p->first() << ", second=" << p->second() << ", grad_first=" << p->grad_first() + << ", grad_second=" << p->grad_second() << ")"; #else os << (p->m_constant ? "CS" : "S"); - os << "(" << static_cast(p->first() + 0.5) << ", " - << static_cast(p->second() + 0.5) << ")"; + os << "(" << static_cast(p->first() + 0.5) << ", " << static_cast(p->second() + 0.5) << ")"; #endif return os; } diff --git a/src/uci.cpp b/src/uci.cpp index 9804908f..8d5dcd79 100644 --- a/src/uci.cpp +++ b/src/uci.cpp @@ -213,8 +213,7 @@ void UCIHandler::handle_d(std::istringstream&) { std::cout << " a b c d e f g h " << std::endl; std::cout << std::endl; std::cout << "fen: " << m_position << std::endl; - std::cout << "key: " << std::hex << std::setw(16) << std::setfill('0') - << m_position.get_hash_key() << std::endl; + std::cout << "key: " << std::hex << std::setw(16) << std::setfill('0') << m_position.get_hash_key() << std::endl; } void UCIHandler::handle_setoption(std::istringstream& is) { @@ -369,8 +368,7 @@ void UCIHandler::handle_genfens(std::istringstream& is) { } if (N > static_cast(lines.size())) { - std::cout << "Requested " << N << " positions, but only " << lines.size() << " available." - << std::endl; + std::cout << "Requested " << N << " positions, but only " << lines.size() << " available." << std::endl; return; } diff --git a/src/util/ios_fmt_guard.hpp b/src/util/ios_fmt_guard.hpp index c0d879e8..1e5b35e6 100644 --- a/src/util/ios_fmt_guard.hpp +++ b/src/util/ios_fmt_guard.hpp @@ -11,9 +11,7 @@ class IosFmtGuard { m_state.copyfmt(m_stream); } - ~IosFmtGuard() { - m_stream.copyfmt(m_state); - } + ~IosFmtGuard() { m_stream.copyfmt(m_state); } private: std::ostream& m_stream; diff --git a/src/util/pretty.hpp b/src/util/pretty.hpp index 92f2a1f6..2fc90028 100644 --- a/src/util/pretty.hpp +++ b/src/util/pretty.hpp @@ -28,8 +28,7 @@ inline void print_progress(size_t current, size_t total, size_t bar_width = 40) } } - std::cout << "] " << static_cast(progress * 100.0f) << "% (" << current << "/" << total - << ")" << std::flush; + std::cout << "] " << static_cast(progress * 100.0f) << "% (" << current << "/" << total << ")" << std::flush; } } // namespace Clockwork diff --git a/src/util/static_vector.hpp b/src/util/static_vector.hpp index 3d039d0c..72d5f1f8 100644 --- a/src/util/static_vector.hpp +++ b/src/util/static_vector.hpp @@ -28,9 +28,7 @@ class StaticVector { m_len(0) { // don't zero `m_storage` } - ~StaticVector() { - clear(); - } + ~StaticVector() { clear(); } StaticVector(std::initializer_list list) : m_len(list.size()) { @@ -105,9 +103,7 @@ class StaticVector { return res; } - iterator push_back(T&& value) { - return emplace_back(std::move(value)); - } + iterator push_back(T&& value) { return emplace_back(std::move(value)); } void append(StaticVector&& other) { assert(m_len + other.m_len <= cap); @@ -129,15 +125,9 @@ class StaticVector { m_len = 0; } - [[nodiscard]] usize size() const { - return m_len; - } - [[nodiscard]] usize capacity() const { - return cap; - } - [[nodiscard]] bool empty() const { - return m_len == 0; - } + [[nodiscard]] usize size() const { return m_len; } + [[nodiscard]] usize capacity() const { return cap; } + [[nodiscard]] bool empty() const { return m_len == 0; } /// This value initializes elements, that is, it zeros primitive types like `int`. void resize(usize new_size) { @@ -172,33 +162,17 @@ class StaticVector { // We never access the raw bytes directly except to immediately call `std::construct_at`. // This means we don't need to call `std::launder`. // Unfortunately, the reinterpret_cast means this can't be constexpr. - [[nodiscard]] T* data() { - return reinterpret_cast(m_storage.data()); - } + [[nodiscard]] T* data() { return reinterpret_cast(m_storage.data()); } - [[nodiscard]] const T* data() const { - return reinterpret_cast(m_storage.data()); - } + [[nodiscard]] const T* data() const { return reinterpret_cast(m_storage.data()); } - [[nodiscard]] iterator begin() { - return data(); - } - [[nodiscard]] const_iterator begin() const { - return data(); - } - [[nodiscard]] const_iterator cbegin() const { - return begin(); - } + [[nodiscard]] iterator begin() { return data(); } + [[nodiscard]] const_iterator begin() const { return data(); } + [[nodiscard]] const_iterator cbegin() const { return begin(); } - [[nodiscard]] iterator end() { - return begin() + m_len; - } - [[nodiscard]] const_iterator end() const { - return begin() + m_len; - } - [[nodiscard]] const_iterator cend() const { - return end(); - } + [[nodiscard]] iterator end() { return begin() + m_len; } + [[nodiscard]] const_iterator end() const { return begin() + m_len; } + [[nodiscard]] const_iterator cend() const { return end(); } T& back() { assert(m_len > 0); @@ -210,8 +184,7 @@ class StaticVector { } friend auto operator<=>(const StaticVector& lhs, const StaticVector& rhs) { - return std::lexicographical_compare_three_way(lhs.begin(), lhs.end(), rhs.begin(), - rhs.end()); + return std::lexicographical_compare_three_way(lhs.begin(), lhs.end(), rhs.begin(), rhs.end()); } friend auto operator==(const StaticVector& lhs, const StaticVector& rhs) { diff --git a/src/util/vec/sse2.hpp b/src/util/vec/sse2.hpp index 0b212b68..949f4213 100644 --- a/src/util/vec/sse2.hpp +++ b/src/util/vec/sse2.hpp @@ -124,21 +124,13 @@ struct f128 { } // ---- Scalar ops ---- - static inline f128 add_scalar(const f128& a, double s) { - return add(a, broadcast(s)); - } + static inline f128 add_scalar(const f128& a, double s) { return add(a, broadcast(s)); } - static inline f128 sub_scalar(const f128& a, double s) { - return sub(a, broadcast(s)); - } + static inline f128 sub_scalar(const f128& a, double s) { return sub(a, broadcast(s)); } - static inline f128 mul_scalar(const f128& a, double s) { - return mul(a, broadcast(s)); - } + static inline f128 mul_scalar(const f128& a, double s) { return mul(a, broadcast(s)); } - static inline f128 div_scalar(const f128& a, double s) { - return div(a, broadcast(s)); - } + static inline f128 div_scalar(const f128& a, double s) { return div(a, broadcast(s)); } static inline f128 scalar_div(double s, const f128& a) { #if F128_USE_SSE2 diff --git a/tests/test.hpp b/tests/test.hpp index 5e48a46d..ef9efd9b 100644 --- a/tests/test.hpp +++ b/tests/test.hpp @@ -4,11 +4,10 @@ #include #include -#define REQUIRE(x) \ - do { \ - if (!(x)) { \ - std::cout << "Assertion failed at line " << std::source_location::current().line() \ - << ": " #x; \ - std::exit(1); \ - } \ +#define REQUIRE(x) \ + do { \ + if (!(x)) { \ + std::cout << "Assertion failed at line " << std::source_location::current().line() << ": " #x; \ + std::exit(1); \ + } \ } while (false) diff --git a/tests/test_piece_count.cpp b/tests/test_piece_count.cpp index ae491e06..75ebb0c2 100644 --- a/tests/test_piece_count.cpp +++ b/tests/test_piece_count.cpp @@ -34,10 +34,8 @@ int main() { REQUIRE(pos.piece_count(Color::White) == 1); REQUIRE(pos.piece_count(Color::Black) == 1); - REQUIRE( - (pos.piece_count(Color::White) == 1)); - REQUIRE( - (pos.piece_count(Color::Black) == 1)); + REQUIRE((pos.piece_count(Color::White) == 1)); + REQUIRE((pos.piece_count(Color::Black) == 1)); return 0; } diff --git a/tests/test_repetition.cpp b/tests/test_repetition.cpp index 140a7865..0485f8e6 100644 --- a/tests/test_repetition.cpp +++ b/tests/test_repetition.cpp @@ -15,18 +15,15 @@ void move(std::string_view movestr) { Move move = Move::parse(movestr, g_position).value(); g_position = g_position.move(move); g_repetition_info.push(g_position.get_hash_key(), g_position.is_reversible(move)); - std::cout << "move: " << movestr << " " << std::hex << std::setw(16) - << g_position.get_hash_key() << std::endl; + std::cout << "move: " << movestr << " " << std::hex << std::setw(16) << g_position.get_hash_key() << std::endl; } void repeat_in_history() { std::cout << "repeat_in_history" << std::endl; - g_position = - Position::parse("rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1").value(); + g_position = Position::parse("rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1").value(); g_repetition_info.reset(); g_repetition_info.push(g_position.get_hash_key(), false); - std::cout << "startpos: " << std::hex << std::setw(16) << g_position.get_hash_key() - << std::endl; + std::cout << "startpos: " << std::hex << std::setw(16) << g_position.get_hash_key() << std::endl; REQUIRE(g_repetition_info.detect_repetition(0) == false); move("g1f3"); REQUIRE(g_repetition_info.detect_repetition(0) == false); @@ -48,12 +45,10 @@ void repeat_in_history() { void repeat_in_search() { std::cout << "repeat_in_search" << std::endl; - g_position = - Position::parse("rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1").value(); + g_position = Position::parse("rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1").value(); g_repetition_info.reset(); g_repetition_info.push(g_position.get_hash_key(), false); - std::cout << "startpos: " << std::hex << std::setw(16) << g_position.get_hash_key() - << std::endl; + std::cout << "startpos: " << std::hex << std::setw(16) << g_position.get_hash_key() << std::endl; REQUIRE(g_repetition_info.detect_repetition(0) == false); move("g1f3"); REQUIRE(g_repetition_info.detect_repetition(1) == false); diff --git a/tests/test_static_vector.cpp b/tests/test_static_vector.cpp index 5b5850d4..76cf8ebf 100644 --- a/tests/test_static_vector.cpp +++ b/tests/test_static_vector.cpp @@ -23,9 +23,7 @@ struct TestType { x(other.x) { ctr += 1; } - ~TestType() { - ctr -= 1; - } + ~TestType() { ctr -= 1; } explicit TestType(isize x) : x(x) {