christopher commited on
Commit
c4e2793
·
verified ·
1 Parent(s): 7d1726d

Upload 101 files

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. .gitattributes +1 -0
  2. app.py +24 -0
  3. puzzler/LICENSE +7 -0
  4. puzzler/generator/README.md +13 -0
  5. puzzler/generator/generator.py +340 -0
  6. puzzler/generator/model.py +29 -0
  7. puzzler/generator/requirements.txt +3 -0
  8. puzzler/generator/server.py +87 -0
  9. puzzler/generator/test.py +192 -0
  10. puzzler/generator/test_pgn_3fold_uDMCM.pgn +24 -0
  11. puzzler/generator/util.py +94 -0
  12. puzzler/tagger/README.md +5 -0
  13. puzzler/tagger/cook.py +793 -0
  14. puzzler/tagger/model.py +76 -0
  15. puzzler/tagger/requirements.txt +2 -0
  16. puzzler/tagger/tagger.py +147 -0
  17. puzzler/tagger/test.py +235 -0
  18. puzzler/tagger/util.py +134 -0
  19. puzzler/tagger/zugzwang.py +44 -0
  20. requirements.txt +1 -0
  21. stockfish/AUTHORS +255 -0
  22. stockfish/CITATION.cff +23 -0
  23. stockfish/CONTRIBUTING.md +96 -0
  24. stockfish/Copying.txt +674 -0
  25. stockfish/README.md +161 -0
  26. stockfish/Top CPU Contributors.txt +322 -0
  27. stockfish/scripts/get_native_properties.sh +153 -0
  28. stockfish/scripts/net.sh +76 -0
  29. stockfish/src/Makefile +1123 -0
  30. stockfish/src/benchmark.cpp +512 -0
  31. stockfish/src/benchmark.h +42 -0
  32. stockfish/src/bitboard.cpp +228 -0
  33. stockfish/src/bitboard.h +374 -0
  34. stockfish/src/engine.cpp +372 -0
  35. stockfish/src/engine.h +130 -0
  36. stockfish/src/evaluate.cpp +128 -0
  37. stockfish/src/evaluate.h +58 -0
  38. stockfish/src/history.h +171 -0
  39. stockfish/src/incbin/UNLICENCE +26 -0
  40. stockfish/src/incbin/incbin.h +476 -0
  41. stockfish/src/main.cpp +44 -0
  42. stockfish/src/memory.cpp +268 -0
  43. stockfish/src/memory.h +218 -0
  44. stockfish/src/misc.cpp +524 -0
  45. stockfish/src/misc.h +322 -0
  46. stockfish/src/movegen.cpp +256 -0
  47. stockfish/src/movegen.h +73 -0
  48. stockfish/src/movepick.cpp +320 -0
  49. stockfish/src/movepick.h +80 -0
  50. stockfish/src/nnue/features/half_ka_v2_hm.cpp +84 -0
.gitattributes CHANGED
@@ -33,3 +33,4 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
33
  *.zip filter=lfs diff=lfs merge=lfs -text
34
  *.zst filter=lfs diff=lfs merge=lfs -text
35
  *tfevents* filter=lfs diff=lfs merge=lfs -text
 
 
33
  *.zip filter=lfs diff=lfs merge=lfs -text
34
  *.zst filter=lfs diff=lfs merge=lfs -text
35
  *tfevents* filter=lfs diff=lfs merge=lfs -text
36
+ stockfish/stockfish-ubuntu-x86-64-avx2 filter=lfs diff=lfs merge=lfs -text
app.py ADDED
@@ -0,0 +1,24 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+
3
+ import chess
4
+ import chess.engine
5
+
6
+ engine = chess.engine.SimpleEngine.popen_uci(r"./stockfish/stockfish-ubuntu-x86-64-avx2")
7
+
8
+ board = chess.Board()
9
+ while not board.is_game_over():
10
+ result = engine.play(board, chess.engine.Limit(time=0.1))
11
+ board.push(result.move)
12
+
13
+ engine.quit()
14
+
15
+ def greet(name, intensity):
16
+ return "Hello, " + name + "!" * int(intensity)
17
+
18
+ demo = gr.Interface(
19
+ fn=greet,
20
+ inputs=["text", "slider"],
21
+ outputs=["text"],
22
+ )
23
+
24
+ demo.launch()
puzzler/LICENSE ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ Copyright 2020 lichess.org
2
+
3
+ Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
4
+
5
+ The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
6
+
7
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
puzzler/generator/README.md ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Generate puzzles from a PGN file! It will look at all games, and analyse them if needed.
2
+
3
+ ```
4
+ python3 -m venv venv
5
+ source venv/bin/activate
6
+ pip install -r requirements.txt
7
+ python3 generator.py --help
8
+ python3 generator.py -t 6 -v -f my_file.pgn # If stockfish installed globally, otherwise use `--engine PATH_TO_YOUR_UCI_ENGINE`
9
+ ```
10
+
11
+ BOT games are also looked at if any. The ouput file will be a csv with the same name as your input PGN file, and the following headers `white,black,game_id,fen,ply,moves,cp,generator_version`.
12
+
13
+ Important! If something does not work, make sure you version matches [this one](https://github.com/kraktus/lichess-puzzler/blob/WC/generator/generator.py#L21). if you don't see `WC` in the version, you have probably not chosen the right branch.
puzzler/generator/generator.py ADDED
@@ -0,0 +1,340 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import logging
2
+ import argparse
3
+ import chess
4
+ import chess.pgn
5
+ import chess.engine
6
+ import copy
7
+ import sys
8
+ import util
9
+ import zstandard
10
+ from model import Puzzle, NextMovePair
11
+ from io import StringIO
12
+ from chess import Move, Color
13
+ from chess.engine import SimpleEngine, Mate, Cp, Score, PovScore
14
+ from chess.pgn import Game, ChildNode
15
+
16
+ from pathlib import Path
17
+ from typing import List, Optional, Union, Set
18
+ from util import count_mates, get_next_move_pair, material_count, material_diff, is_up_in_material, maximum_castling_rights, win_chances
19
+ from server import Server
20
+
21
+ version = "48WC9" # Was made for the World Championship first
22
+
23
+ logger = logging.getLogger(__name__)
24
+ logging.basicConfig(format='%(asctime)s %(levelname)-4s %(message)s', datefmt='%m/%d %H:%M')
25
+
26
+ eval_limit = chess.engine.Limit(depth = 15, time = 30, nodes = 10_000_000) # when the move isn't analysed
27
+ pair_limit = chess.engine.Limit(depth = 50, time = 30, nodes = 30_000_000)
28
+ mate_defense_limit = chess.engine.Limit(depth = 15, time = 10, nodes = 10_000_000)
29
+
30
+ mate_soon = Mate(15)
31
+
32
+ class Generator:
33
+ def __init__(self, engine: SimpleEngine, server: Server):
34
+ self.engine = engine
35
+ self.server = server
36
+ self.not_analysed_warning = False
37
+
38
+ def is_valid_mate_in_one(self, pair: NextMovePair) -> bool:
39
+ if pair.best.score != Mate(1):
40
+ return False
41
+ non_mate_win_threshold = 0.6
42
+ if not pair.second or win_chances(pair.second.score) <= non_mate_win_threshold:
43
+ return True
44
+ if pair.second.score == Mate(1):
45
+ # if there's more than one mate in one, gotta look if the best non-mating move is bad enough
46
+ logger.debug('Looking for best non-mating move...')
47
+ mates = count_mates(copy.deepcopy(pair.node.board()))
48
+ info = self.engine.analyse(pair.node.board(), multipv = mates + 1, limit = pair_limit)
49
+ scores = [pv["score"].pov(pair.winner) for pv in info]
50
+ # the first non-matein1 move is the last element
51
+ if scores[-1] < Mate(1) and win_chances(scores[-1]) > non_mate_win_threshold:
52
+ return False
53
+ return True
54
+ return False
55
+
56
+ # is pair.best the only continuation?
57
+ def is_valid_attack(self, pair: NextMovePair) -> bool:
58
+ return (
59
+ pair.second is None or
60
+ self.is_valid_mate_in_one(pair) or
61
+ win_chances(pair.best.score) > win_chances(pair.second.score) + 0.7
62
+ )
63
+
64
+ def get_next_pair(self, node: ChildNode, winner: Color) -> Optional[NextMovePair]:
65
+ pair = get_next_move_pair(self.engine, node, winner, pair_limit)
66
+ if node.board().turn == winner and not self.is_valid_attack(pair):
67
+ logger.debug("No valid attack {}".format(pair))
68
+ return None
69
+ return pair
70
+
71
+ def get_next_move(self, node: ChildNode, limit: chess.engine.Limit) -> Optional[Move]:
72
+ result = self.engine.play(node.board(), limit = limit)
73
+ return result.move if result else None
74
+
75
+ def cook_mate(self, node: ChildNode, winner: Color) -> Optional[List[Move]]:
76
+
77
+ board = node.board()
78
+
79
+ if board.is_game_over():
80
+ return []
81
+
82
+ if board.turn == winner:
83
+ pair = self.get_next_pair(node, winner)
84
+ if not pair:
85
+ return None
86
+ if pair.best.score < mate_soon:
87
+ logger.debug("Best move is not a mate, we're probably not searching deep enough")
88
+ return None
89
+ move = pair.best.move
90
+ else:
91
+ next = self.get_next_move(node, mate_defense_limit)
92
+ if not next:
93
+ return None
94
+ move = next
95
+
96
+ follow_up = self.cook_mate(node.add_main_variation(move), winner)
97
+
98
+ if follow_up is None:
99
+ return None
100
+
101
+ return [move] + follow_up
102
+
103
+
104
+ def cook_advantage(self, node: ChildNode, winner: Color) -> Optional[List[NextMovePair]]:
105
+
106
+ board = node.board()
107
+
108
+ if board.is_repetition(2):
109
+ logger.debug("Found repetition, canceling")
110
+ return None
111
+
112
+ pair = self.get_next_pair(node, winner)
113
+ if not pair:
114
+ return []
115
+ if pair.best.score < Cp(200):
116
+ logger.debug("Not winning enough, aborting")
117
+ return None
118
+
119
+ follow_up = self.cook_advantage(node.add_main_variation(pair.best.move), winner)
120
+
121
+ if follow_up is None:
122
+ return None
123
+
124
+ return [pair] + follow_up
125
+
126
+
127
+ def analyze_game(self, game: Game, tier: int) -> Optional[Puzzle]:
128
+
129
+ logger.debug(f'Analyzing tier {tier} {game.headers.get("Site")}...')
130
+
131
+ prev_score: Score = Cp(20)
132
+ seen_epds: Set[str] = set()
133
+ board = game.board()
134
+ skip_until_irreversible = False
135
+
136
+ for node in game.mainline():
137
+ if skip_until_irreversible:
138
+ if board.is_irreversible(node.move):
139
+ skip_until_irreversible = False
140
+ seen_epds.clear()
141
+ else:
142
+ board.push(node.move)
143
+ continue
144
+
145
+ current_eval = node.eval()
146
+
147
+ if not current_eval:
148
+ if not self.not_analysed_warning:
149
+ logger.warning("Game not already analysed by stockfish, will make one but consider using already analysed games from Lichess")
150
+ self.not_analysed_warning = True
151
+ logger.debug("Move without eval on ply {}, computing...".format(node.ply()))
152
+ current_eval = self.engine.analyse(node.board(), eval_limit)["score"]
153
+
154
+ board.push(node.move)
155
+ epd = board.epd()
156
+ if epd in seen_epds:
157
+ skip_until_irreversible = True
158
+ continue
159
+ seen_epds.add(epd)
160
+
161
+ if board.castling_rights != maximum_castling_rights(board):
162
+ continue
163
+
164
+ result = self.analyze_position(node, prev_score, current_eval, tier)
165
+
166
+ if isinstance(result, Puzzle):
167
+ return result
168
+
169
+ prev_score = -result
170
+
171
+ logger.debug("Found nothing from {}".format(game.headers.get("Site")))
172
+
173
+ return None
174
+
175
+
176
+ def analyze_position(self, node: ChildNode, prev_score: Score, current_eval: PovScore, tier: int) -> Union[Puzzle, Score]:
177
+
178
+ board = node.board()
179
+ winner = board.turn
180
+ score = current_eval.pov(winner)
181
+
182
+ if board.legal_moves.count() < 2:
183
+ return score
184
+
185
+ game_url = node.game().headers.get("Site")
186
+
187
+ logger.debug("{} {} to {}".format(node.ply(), node.move.uci() if node.move else None, score))
188
+
189
+ if prev_score > Cp(300) and score < mate_soon:
190
+ logger.debug("{} Too much of a winning position to start with {} -> {}".format(node.ply(), prev_score, score))
191
+ return score
192
+ if is_up_in_material(board, winner):
193
+ logger.debug("{} already up in material {} {} {}".format(node.ply(), winner, material_count(board, winner), material_count(board, not winner)))
194
+ return score
195
+ elif score >= Mate(1) and tier < 3:
196
+ logger.debug("{} mate in one".format(node.ply()))
197
+ return score
198
+ elif score > mate_soon:
199
+ logger.debug("Mate {}#{} Probing...".format(game_url, node.ply()))
200
+ if self.server.is_seen_pos(node):
201
+ logger.debug("Skip duplicate position")
202
+ return score
203
+ mate_solution = self.cook_mate(copy.deepcopy(node), winner)
204
+ if mate_solution is None or (tier == 1 and len(mate_solution) == 3):
205
+ return score
206
+ return Puzzle(node, mate_solution, 999999999)
207
+ elif score >= Cp(200) and win_chances(score) > win_chances(prev_score) + 0.6:
208
+ if score < Cp(400) and material_diff(board, winner) > -1:
209
+ logger.debug("Not clearly winning and not from being down in material, aborting")
210
+ return score
211
+ logger.debug("Advantage {}#{} {} -> {}. Probing...".format(game_url, node.ply(), prev_score, score))
212
+ if self.server.is_seen_pos(node):
213
+ logger.debug("Skip duplicate position")
214
+ return score
215
+ puzzle_node = copy.deepcopy(node)
216
+ solution : Optional[List[NextMovePair]] = self.cook_advantage(puzzle_node, winner)
217
+ self.server.set_seen(node.game())
218
+ if not solution:
219
+ return score
220
+ while len(solution) % 2 == 0 or not solution[-1].second:
221
+ if not solution[-1].second:
222
+ logger.debug("Remove final only-move")
223
+ solution = solution[:-1]
224
+ if not solution or len(solution) == 1 :
225
+ logger.debug("Discard one-mover")
226
+ return score
227
+ if tier < 3 and len(solution) == 3:
228
+ logger.debug("Discard two-mover")
229
+ return score
230
+ cp = solution[len(solution) - 1].best.score.score()
231
+ return Puzzle(node, [p.best.move for p in solution], 999999998 if cp is None else cp)
232
+ else:
233
+ return score
234
+
235
+
236
+ def parse_args() -> argparse.Namespace:
237
+ parser = argparse.ArgumentParser(
238
+ prog='generator.py',
239
+ description='takes a pgn file and produces chess puzzles')
240
+ parser.add_argument("--file", "-f", help="input PGN file", required=True, metavar="FILE.pgn")
241
+ parser.add_argument("--engine", "-e", help="analysis engine", default="stockfish")
242
+ parser.add_argument("--threads", "-t", help="count of cpu threads for engine searches", default="4")
243
+ parser.add_argument("--url", "-u", help="URL where to post puzzles", default="")
244
+ parser.add_argument("--token", help="Server secret token", default="changeme")
245
+ parser.add_argument("--skip", help="How many games to skip from the source", default="0")
246
+ parser.add_argument("--verbose", "-v", help="increase verbosity", action="count")
247
+ parser.add_argument("--players", nargs='+', help="A list of players. If set, only generate games in which one of them played")
248
+
249
+ return parser.parse_args()
250
+
251
+
252
+ def make_engine(executable: str, threads: int) -> SimpleEngine:
253
+ engine = SimpleEngine.popen_uci(executable)
254
+ engine.configure({'Threads': threads})
255
+ return engine
256
+
257
+
258
+ def open_file(file: str):
259
+ if file.endswith(".zst"):
260
+ return zstandard.open(file, "rt")
261
+ return open(file)
262
+
263
+ def main() -> None:
264
+ sys.setrecursionlimit(10000) # else node.deepcopy() sometimes fails?
265
+ args = parse_args()
266
+ if args.verbose >= 2:
267
+ logger.setLevel(logging.DEBUG)
268
+ else:
269
+ logger.setLevel(logging.INFO)
270
+ engine = make_engine(args.engine, args.threads)
271
+ server = Server(logger, args.url, args.token, version)
272
+ generator = Generator(engine, server)
273
+ file = Path(args.file)
274
+ games = 0
275
+ site = "?"
276
+ has_master = False
277
+ tier = 10
278
+ skip = int(args.skip)
279
+ write_h = skip > 0 # Erase the .csv file if not skipping any game (i.e starting over), else add
280
+ logger.info("Skipping first {} games".format(skip))
281
+
282
+ print(f'v{version}')
283
+ players = args.players
284
+
285
+ try:
286
+ i = None
287
+ with open_file(args.file) as pgn:
288
+ filtered_games_offset: List[int] = []
289
+ while "Look for all headers of the file":
290
+ offset = pgn.tell()
291
+ headers = chess.pgn.read_headers(pgn)
292
+ if skip > 0:
293
+ skip -= 1
294
+ continue
295
+ if headers is None:
296
+ break
297
+ games = games + 1
298
+ if games % 1000 == 0:
299
+ logger.info(f"{games} headers parsed")
300
+ variant = headers.get("Variant", "Standard")
301
+ black = headers.get("Black", "?")
302
+ white = headers.get("White", "?")
303
+ white_title = headers.get("WhiteTitle", "?")
304
+ black_title = headers.get("BlackTitle", "?")
305
+ if variant != "Standard" and variant != "Chess960":
306
+ continue
307
+ if players is not None and black not in players and white not in players:
308
+ continue
309
+ filtered_games_offset.append(offset)
310
+ logger.info(f"All headers parsed, {len(filtered_games_offset)}/{games} games that match the criterias.")
311
+
312
+ for i, game_offset in enumerate(filtered_games_offset):
313
+ pgn.seek(game_offset)
314
+ game = chess.pgn.read_game(pgn)
315
+ black = game.headers.get("Black", "?")
316
+ white = game.headers.get("White", "?")
317
+ if game.errors:
318
+ logger.error(f"Illegal move detected in {white} vs {black}, game {i}")
319
+ assert(game)
320
+ game_id = game.headers.get("Site", "?")[20:]
321
+ # logger.info(f'https://lichess.org/{game_id} tier {tier}')
322
+ try:
323
+ puzzle = generator.analyze_game(game, tier)
324
+ if puzzle is not None:
325
+ logger.info(f'v{version} {args.file} {util.avg_knps()} knps, tier {tier}, game {i}')
326
+ print(f"Game: {game_id}")
327
+ server.post(game, puzzle, "_".join(players) if players is not None else file.stem, write_h)
328
+ write_h = False
329
+ except Exception as e:
330
+ logger.error("Exception on {}: {}".format(game_id, e))
331
+ except KeyboardInterrupt:
332
+ print(f'v{version} {args.file} Game {i}')
333
+ sys.exit(1)
334
+
335
+ engine.close()
336
+ print(f'v{version} {args.file} Game {i}')
337
+
338
+ if __name__ == "__main__":
339
+ print('#'*80)
340
+ main()
puzzler/generator/model.py ADDED
@@ -0,0 +1,29 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from chess.pgn import GameNode, ChildNode
2
+ from chess import Move, Color
3
+ from chess.engine import Score
4
+ from dataclasses import dataclass
5
+ from typing import Tuple, List, Optional
6
+
7
+ @dataclass
8
+ class Puzzle:
9
+ node: ChildNode
10
+ moves: List[Move]
11
+ cp: int
12
+
13
+ @dataclass
14
+ class Line:
15
+ nb: Tuple[int, int]
16
+ letter: str
17
+ password: str
18
+
19
+ @dataclass
20
+ class EngineMove:
21
+ move: Move
22
+ score: Score
23
+
24
+ @dataclass
25
+ class NextMovePair:
26
+ node: GameNode
27
+ winner: Color
28
+ best: EngineMove
29
+ second: Optional[EngineMove]
puzzler/generator/requirements.txt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ chess==1.3.0
2
+ requests==2.24.0
3
+ zstandard==0.19.0
puzzler/generator/server.py ADDED
@@ -0,0 +1,87 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import logging
2
+ import csv
3
+ from chess.pgn import Game, GameNode, ChildNode
4
+ from model import Puzzle
5
+ import requests
6
+ import urllib.parse
7
+ from requests.adapters import HTTPAdapter
8
+ from requests.packages.urllib3.util.retry import Retry
9
+
10
+ retry_strategy = Retry(
11
+ total=999999999,
12
+ backoff_factor=0.1,
13
+ status_forcelist=[429, 500, 502, 503, 504],
14
+ method_whitelist=["GET", "POST"]
15
+ )
16
+ adapter = HTTPAdapter(max_retries=retry_strategy)
17
+ http = requests.Session()
18
+ http.mount("https://", adapter)
19
+ http.mount("http://", adapter)
20
+
21
+ TIMEOUT = 5
22
+
23
+ class Server:
24
+
25
+ def __init__(self, logger: logging.Logger, url: str, token: str, version: str) -> None:
26
+ self.logger = logger
27
+ self.url = url
28
+ self.token = token
29
+ self.version = version
30
+
31
+ def is_seen(self, id: str) -> bool:
32
+ if not self.url:
33
+ return False
34
+ try:
35
+ status = http.get(self._seen_url(id), timeout = TIMEOUT).status_code
36
+ return status == 200
37
+ except Exception as e:
38
+ self.logger.error(e)
39
+ return False
40
+
41
+ def set_seen(self, game: Game) -> None:
42
+ try:
43
+ if self.url:
44
+ http.post(self._seen_url(game.headers.get("Site", "?")[20:]), timeout = TIMEOUT)
45
+ except Exception as e:
46
+ self.logger.error(e)
47
+
48
+ def is_seen_pos(self, node: ChildNode) -> bool:
49
+ if not self.url:
50
+ return False
51
+ id = urllib.parse.quote(f"{node.parent.board().fen()}:{node.uci()}")
52
+ try:
53
+ status = http.get(self._seen_url(id), timeout = TIMEOUT).status_code
54
+ return status == 200
55
+ except Exception as e:
56
+ self.logger.error(e)
57
+ return False
58
+
59
+ def _seen_url(self, id: str) -> str:
60
+ return "{}/seen?token={}&id={}".format(self.url, self.token, id)
61
+
62
+ def post(self, game: Game, puzzle: Puzzle, name: str, write_h: bool = False) -> None:
63
+ parent = puzzle.node.parent
64
+ assert parent
65
+ json = {
66
+ 'white': game.headers.get("White", "?"),
67
+ 'black': game.headers.get("Black", "?"),
68
+ 'game_id': game.headers.get("Site", "?")[20:],
69
+ 'fen': parent.board().fen(),
70
+ 'ply': parent.ply(),
71
+ 'moves': [puzzle.node.uci()] + list(map(lambda m : m.uci(), puzzle.moves)),
72
+ 'cp': puzzle.cp,
73
+ 'generator_version': self.version,
74
+ }
75
+ if not self.url:
76
+ print(json)
77
+ with open(f"{name}.csv", "w" if write_h else "a") as csvfile:
78
+ writer = csv.DictWriter(csvfile, fieldnames=json.keys())
79
+ if write_h:
80
+ writer.writeheader()
81
+ writer.writerow(json)
82
+ return None
83
+ try:
84
+ r = http.post("{}/puzzle?token={}".format(self.url, self.token), json=json)
85
+ self.logger.info(r.text if r.ok else "FAILURE {}".format(r.text))
86
+ except Exception as e:
87
+ self.logger.error("Couldn't post puzzle: {}".format(e))
puzzler/generator/test.py ADDED
@@ -0,0 +1,192 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import unittest
2
+ import logging
3
+ import chess
4
+ from model import Puzzle
5
+ from generator import logger
6
+ from server import Server
7
+ from chess.engine import SimpleEngine, Mate, Cp, Score, PovScore
8
+ from chess import Move, Color, Board, WHITE, BLACK
9
+ from chess.pgn import Game, GameNode
10
+ from typing import List, Optional, Tuple, Literal, Union
11
+
12
+ from generator import Generator, Server, make_engine
13
+
14
+ class TestGenerator(unittest.TestCase):
15
+
16
+ @classmethod
17
+ def setUpClass(cls):
18
+ cls.engine = make_engine("stockfish", 6) # don't use more than 6 threads! it fails at finding mates
19
+ cls.server = Server(logger, "", "", 0)
20
+ cls.gen = Generator(cls.engine, cls.server)
21
+ logger.setLevel(logging.DEBUG)
22
+
23
+ def test_puzzle_1(self) -> None:
24
+ # https://lichess.org/analysis/standard/3q1k2/p7/1p2Q2p/5P1K/1P4P1/P7/8/8_w_-_-_5_57#112
25
+ self.get_puzzle("3q1k2/p7/1p2Q2p/5P1K/1P4P1/P7/8/8 w - - 5 57",
26
+ Cp(-1000), "h5g6", Mate(2), "d8g5 g6h7 g5g7")
27
+
28
+ def test_puzzle_3(self) -> None:
29
+ # https://lichess.org/wQptHOX6/white#61
30
+ self.get_puzzle("1r4k1/5p1p/pr1p2p1/q2Bb3/2P5/P1R3PP/KB1R1Q2/8 b - - 1 31",
31
+ Cp(-4), "e5c3", Mate(3), "f2f7 g8h8 f7f6 c3f6 b2f6")
32
+
33
+ def test_puzzle_4(self) -> None:
34
+ # https://lichess.org/eVww5aBo#122
35
+ self.get_puzzle("8/8/3Rpk2/2PpNp2/KP1P4/4r3/P1n5/8 w - - 3 62",
36
+ Cp(0), "d6d7", Cp(580), "e3a3 a4b5 c2d4 b5b6 f6e5")
37
+
38
+ # can't be done because there are 2 possible defensive moves
39
+ def test_puzzle_5(self) -> None:
40
+ # https://lichess.org/2YRgIXwk/black#32
41
+ self.get_puzzle("r1b3k1/pp3p1p/2pp2p1/8/2P2q2/2N1r2P/PP2BPP1/R2Q1K1R w - - 0 17",
42
+ Cp(-520), "d1d2", Cp(410), "e3h3 h1h3 f4d2")
43
+
44
+ def test_puzzle_6(self) -> None:
45
+ self.get_puzzle("4nr1k/2r1qNpp/p3pn2/1b2N2Q/1p6/7P/BP1R1PP1/4R1K1 b - - 0 1",
46
+ Cp(130), "f8f7", Cp(550), "e5g6 h8g8 g6e7")
47
+
48
+ # https://lichess.org/YCjcYuK6#81
49
+ # def test_puzzle_7(self) -> None:
50
+ # self.get_puzzle("7r/1k6/pPp1qp2/2Q3p1/P4p2/5P2/5KP1/1RR4r b - - 5 41",
51
+ # Cp(-1500), "e6a2", Cp(530), "c1c2 a2e6 b1h1 h8h1 c2e2 e6d7 e2e7 d7e7 c5e7")
52
+
53
+ # r1bq3r/pppp1kpp/2n5/2b1P1N1/3p2n1/2P5/P4PPP/RNBQ1RK1 b - - 1 10
54
+ # def test_puzzle_8(self) -> None:
55
+ # self.get_puzzle("r1bq3r/pppp1kpp/2n5/2b1P1N1/3p2n1/2P5/P4PPP/RNBQ1RK1 b - - 1 10",
56
+ # Cp(0), "f7g8", Mate(4), "d1b3 d7d5 e5d6 c8e6 b3e6 g8f8 e6f7")
57
+
58
+ def test_puzzle_9(self) -> None:
59
+ self.get_puzzle("7k/p3r1bP/1p1rp2q/8/2PBB3/4P3/P3KQ2/6R1 b - - 0 38",
60
+ Cp(-110), "e6e5", Mate(2), "f2f8 g7f8 g1g8")
61
+
62
+ # https://lichess.org/ejvEklSH/black#50
63
+ def test_puzzle_10(self) -> None:
64
+ self.get_puzzle("5rk1/pp3p2/1q1R3p/6p1/5pBb/2P4P/PPQ2PP1/3Rr1K1 w - - 6 26",
65
+ Cp(-450), "g1h2", Mate(2), "h4g3 f2g3 b6g1")
66
+
67
+ # https://lichess.org/3GvkmJcw#43
68
+ def test_puzzle_15(self):
69
+ self.get_puzzle("7k/pp1q2pp/1n1p2r1/4p3/P3P3/1Q3N1P/1P3PP1/5RK1 w - - 3 22",
70
+ Cp(-80), "a4a5", Cp(856), "d7h3 g2g3 g6h6 f3h4 h6h4 g3h4 h3b3")
71
+
72
+ def test_puzzle_16(self):
73
+ self.get_puzzle("kr6/p5pp/Q4np1/3p4/6P1/2P1qP2/PK4P1/3R3R w - - 1 26",
74
+ Cp(-30), "b2a1", Mate(1), "e3c3")
75
+
76
+ def test_puzzle_17(self):
77
+ self.get_puzzle("8/8/6k1/5R2/5KP1/5P2/5r2/8 w - - 17 66",
78
+ Cp(-410), "g4g5", Cp(0), "f2f3 f4f3 g6f5")
79
+
80
+ # one mover
81
+ # def test_puzzle_17(self):
82
+ # self.get_puzzle("6k1/Q4pp1/8/6p1/3pr3/4q2P/P1P3P1/3R3K w - - 0 31",
83
+ # Cp(0), "d1d3", Cp(2000), "e3c1")
84
+
85
+ def test_not_puzzle_1(self) -> None:
86
+ # https://lichess.org/LywqL7uc#32
87
+ self.not_puzzle("r2q1rk1/1pp2pp1/p4n1p/b1pP4/4PB2/P3RQ2/1P3PPP/RN4K1 w - - 1 17",
88
+ Cp(-230), "b1c3", Cp(160))
89
+
90
+ def test_not_puzzle_2(self) -> None:
91
+ # https://lichess.org/TIH1K2BQ#51
92
+ self.not_puzzle("5b1r/kpQ2ppp/4p3/4P3/1P4q1/8/P3N3/1nK2B2 b - - 0 26",
93
+ Cp(-1520), "b1a3", Cp(0))
94
+
95
+ # def test_not_puzzle_3(self) -> None:
96
+ # https://lichess.org/StRzB2gY#59
97
+ # self.not_puzzle("7k/p6p/4p1p1/8/1q1p3P/2r1P1P1/P4Q2/5RK1 b - - 1 30",
98
+ # Cp(0), "d4e3", Cp(580))
99
+
100
+ def test_not_puzzle_4(self) -> None:
101
+ self.not_puzzle("r2qk2r/p1p1bppp/1p1ppn2/8/2PP1B2/3Q1N2/PP3PPP/3RR1K1 b kq - 6 12",
102
+ Cp(-110), "h7h6", Cp(150))
103
+
104
+ # https://lichess.org/ynAkXFBr/black#92
105
+ def test_not_puzzle_5(self) -> None:
106
+ self.not_puzzle("4Rb2/N4k1p/8/5pp1/1n2p2P/4P1K1/3P4/8 w - - 1 47",
107
+ Cp(-40), "e8c8", Cp(610))
108
+
109
+ def test_not_puzzle_6(self) -> None:
110
+ self.not_puzzle("5r1k/1Q3p2/5q1p/8/2P4p/1P4P1/P4P2/R4RK1 w - - 0 29",
111
+ Cp(-1020), "g3h4", Cp(0))
112
+
113
+ # https://lichess.org/N99i0nfU#11
114
+ def test_not_puzzle_7(self):
115
+ self.not_puzzle("rnb1k1nr/ppp2p1p/3p1qp1/2b1p3/2B1P3/2NP1Q2/PPP2PPP/R1B1K1NR b KQkq - 1 6",
116
+ Cp(-50), "c8g4", Cp(420))
117
+
118
+ def test_not_puzzle_8(self):
119
+ self.not_puzzle("r1bq1rk1/pp1nbppp/4p3/3pP3/8/1P1B4/PBP2PPP/RN1Q1RK1 w - - 1 11",
120
+ Cp(-40), "d3h7", Cp(380))
121
+
122
+ def test_not_puzzle_9(self):
123
+ self.not_puzzle("5k2/5ppp/2r1p3/1p6/1b1R4/p1n1P1P1/B4PKP/1N6 w - - 2 34",
124
+ Cp(0), "b1c3", Cp(520))
125
+
126
+ def test_not_puzzle_10(self):
127
+ self.not_puzzle("2Qr3k/p2P2p1/2p1n3/4n1p1/8/4q1P1/PP2P2P/R4R1K w - - 0 33",
128
+ Cp(100), "c8d8", Cp(500))
129
+
130
+ def test_not_puzzle_11(self) -> None:
131
+ self.not_puzzle("2kr3r/ppp2pp1/1b6/1P2p3/4P3/P2B2P1/2P2PP1/R4RK1 w - - 0 18",
132
+ Cp(20), "f1d1", Mate(4))
133
+
134
+ def test_not_puzzle_12(self):
135
+ self.not_puzzle("5r1k/1Q3p2/5q1p/8/2P4p/1P4P1/P4P2/R4RK1 w - - 0 29",
136
+ Cp(-1010), "g3h4", Cp(0))
137
+
138
+ # https://lichess.org/oKiQW6Wn/black#86
139
+ def test_not_puzzle_13(self):
140
+ self.not_puzzle("8/5p1k/4p1p1/4Q3/3Pp1Kp/4P2P/5qP1/8 w - - 2 44",
141
+ Cp(-6360), "e5e4", Mate(1))
142
+
143
+ def test_not_puzzle_14(self) -> None:
144
+ # https://lichess.org/nq1x9tln/black#76
145
+ self.not_puzzle("3R4/1Q2nk2/4p2p/4n3/BP3ppP/P7/5PP1/2r3K1 w - - 2 39",
146
+ Cp(-1000), "g1h2", Mate(4))
147
+
148
+ def test_not_puzzle_15(self) -> None:
149
+ # https://lichess.org/nq1x9tln/black#76
150
+ self.not_puzzle("3r4/8/2p2n2/7k/P1P4p/1P6/2K5/6R1 w - - 0 43",
151
+ Cp(-1000), "b3b4", Mate(4))
152
+
153
+ def test_not_puzzle_16(self) -> None:
154
+ self.not_puzzle("8/Pkp3pp/8/4p3/1P2b3/4K3/1P3r1P/R7 b - - 1 30",
155
+ Cp(0), "f2f3", Cp(5000))
156
+
157
+ def test_not_puzzle_17(self) -> None:
158
+ with open("test_pgn_3fold_uDMCM.pgn") as pgn:
159
+ game = chess.pgn.read_game(pgn)
160
+ puzzle = self.gen.analyze_game(game, tier=10)
161
+ self.assertEqual(puzzle, None)
162
+
163
+ def get_puzzle(self, fen: str, prev_score: Score, move: str, current_score: Score, moves: str) -> None:
164
+ board = Board(fen)
165
+ game = Game.from_board(board)
166
+ node = game.add_main_variation(Move.from_uci(move))
167
+ current_eval = PovScore(current_score, not board.turn)
168
+ result = self.gen.analyze_position(node, prev_score, current_eval, tier=10)
169
+ self.assert_is_puzzle_with_moves(result, [Move.from_uci(x) for x in moves.split()])
170
+
171
+
172
+ def not_puzzle(self, fen: str, prev_score: Score, move: str, current_score: Score) -> None:
173
+ board = Board(fen)
174
+ game = Game.from_board(board)
175
+ node = game.add_main_variation(Move.from_uci(move))
176
+ current_eval = PovScore(current_score, not board.turn)
177
+ result = self.gen.analyze_position( node, prev_score, current_eval, tier=10)
178
+ self.assertIsInstance(result, Score)
179
+
180
+
181
+ def assert_is_puzzle_with_moves(self, puzzle: Union[Puzzle, Score], moves: List[Move]) -> None:
182
+ self.assertIsInstance(puzzle, Puzzle)
183
+ if isinstance(puzzle, Puzzle):
184
+ self.assertEqual(puzzle.moves, moves)
185
+
186
+ @classmethod
187
+ def tearDownClass(cls):
188
+ cls.engine.close()
189
+
190
+
191
+ if __name__ == '__main__':
192
+ unittest.main()
puzzler/generator/test_pgn_3fold_uDMCM.pgn ADDED
@@ -0,0 +1,24 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ [Event "Rated Blitz game"]
2
+ [Site "https://lichess.org/ZlCTzfMG"]
3
+ [Date "2021.06.28"]
4
+ [White "genassien"]
5
+ [Black "Freiheitskaempfer"]
6
+ [Result "1-0"]
7
+ [UTCDate "2021.06.28"]
8
+ [UTCTime "18:21:43"]
9
+ [WhiteElo "2370"]
10
+ [BlackElo "2441"]
11
+ [WhiteRatingDiff "+7"]
12
+ [BlackRatingDiff "-7"]
13
+ [WhiteTitle "FM"]
14
+ [BlackTitle "FM"]
15
+ [Variant "Standard"]
16
+ [TimeControl "300+0"]
17
+ [ECO "C24"]
18
+ [Opening "Bishop's Opening: Berlin Defense"]
19
+ [Termination "Time forfeit"]
20
+ [Annotator "lichess.org"]
21
+
22
+ 1. e4 { [%eval 0.24] [%clk 0:05:00] } 1... e5 { [%eval 0.2] [%clk 0:05:00] } 2. Bc4 { [%eval 0.0] [%clk 0:04:58] } 2... Nf6 { [%eval 0.0] [%clk 0:04:59] } { C24 Bishop's Opening: Berlin Defense } 3. d3 { [%eval 0.0] [%clk 0:04:53] } 3... c6 { [%eval 0.0] [%clk 0:04:58] } 4. Nf3 { [%eval 0.0] [%clk 0:04:52] } 4... d5 { [%eval 0.02] [%clk 0:04:58] } 5. Bb3 { [%eval 0.0] [%clk 0:04:51] } 5... Bb4+ { [%eval 0.05] [%clk 0:04:57] } 6. c3 { [%eval 0.05] [%clk 0:04:45] } 6... Bd6 { [%eval 0.09] [%clk 0:04:56] } 7. Nbd2 { [%eval -0.35] [%clk 0:04:33] } 7... Nbd7 { [%eval -0.24] [%clk 0:04:54] } 8. O-O { [%eval -0.14] [%clk 0:04:26] } 8... O-O { [%eval -0.04] [%clk 0:04:50] } 9. Re1 { [%eval -0.33] [%clk 0:04:25] } 9... dxe4 { [%eval -0.19] [%clk 0:04:42] } 10. dxe4 { [%eval -0.01] [%clk 0:04:16] } 10... Qe7 { [%eval 0.0] [%clk 0:04:35] } 11. Nc4 { [%eval -0.08] [%clk 0:04:14] } 11... Bc7 { [%eval 0.0] [%clk 0:04:34] } 12. Ne3? { (0.00 → -1.25) Mistake. a4 was best. } { [%eval -1.25] [%clk 0:04:13] } (12. a4 Rd8 13. Qe2 Nb6 14. Na5 Nbd7) 12... Nc5 { [%eval -1.25] [%clk 0:04:28] } 13. Bc2 { [%eval -1.12] [%clk 0:04:08] } 13... Ncxe4 { [%eval -0.98] [%clk 0:04:23] } 14. Nc4?! { (-0.98 → -1.74) Inaccuracy. Nf1 was best. } { [%eval -1.74] [%clk 0:03:49] } (14. Nf1 Nc5 15. b4 Ncd7 16. Ng3 Re8 17. a4 Nb6 18. h3 Nbd5 19. Bd2 h6 20. b5 Qc5) 14... Qc5?! { (-1.74 → -0.99) Inaccuracy. Bf5 was best. } { [%eval -0.99] [%clk 0:03:42] } (14... Bf5 15. Ng5) 15. Bxe4?! { (-0.99 → -1.80) Inaccuracy. Qe2 was best. } { [%eval -1.8] [%clk 0:03:13] } (15. Qe2 Bf5) 15... Qxc4 { [%eval -1.69] [%clk 0:03:40] } 16. Bc2?! { (-1.69 → -2.37) Inaccuracy. Bd3 was best. } { [%eval -2.37] [%clk 0:03:06] } (16. Bd3) 16... Bg4?! { (-2.37 → -1.36) Inaccuracy. Rd8 was best. } { [%eval -1.36] [%clk 0:03:15] } (16... Rd8 17. Nd2 Qh4 18. Qe2 Nd5 19. Nf3 Qh5 20. a4 a5 21. h3 f6 22. Bd2 Qf7 23. c4) 17. Bg5 { [%eval -1.16] [%clk 0:03:01] } 17... Rad8 { [%eval -0.83] [%clk 0:03:08] } 18. Qb1 { [%eval -1.1] [%clk 0:02:54] } 18... Bxf3 { [%eval -1.38] [%clk 0:02:53] } 19. Bxf6?? { (-1.38 → Mate in 6) Checkmate is now unavoidable. gxf3 was best. } { [%eval #-6] [%clk 0:02:53] } (19. gxf3) 19... gxf6?? { (Mate in 6 → -3.06) Lost forced checkmate sequence. Qg4 was best. } { [%eval -3.06] [%clk 0:02:50] } (19... Qg4 20. Bxh7+ Kh8 21. Qg6 fxg6 22. g3 Qh3 23. Bxg7+ Kxg7 24. a3 Qg2#) 20. Bxh7+? { (-3.06 → -5.75) Mistake. gxf3 was best. } { [%eval -5.75] [%clk 0:02:50] } (20. gxf3 Kh8 21. Re4 Rg8+ 22. Kh1 Qd5 23. Bb3 Qd2 24. Rh4 Rg7 25. Rg4 Rxg4 26. fxg4 Qxf2) 20... Kg7 { [%eval -6.06] [%clk 0:02:47] } 21. gxf3 { [%eval -6.09] [%clk 0:02:42] } 21... Qh4 { [%eval -5.99] [%clk 0:02:34] } 22. Be4?! { (-5.99 → -10.07) Inaccuracy. Qf5 was best. } { [%eval -10.07] [%clk 0:02:38] } (22. Qf5 Qxh7 23. Qxh7+ Kxh7 24. Rad1 Kg6 25. Kf1 Rh8 26. Rxd8 Rxd8 27. h3 f5 28. Ke2 Rh8) 22... Rh8 { [%eval -7.71] [%clk 0:02:29] } 23. Kf1 { [%eval -8.01] [%clk 0:01:43] } 23... Rd2 { [%eval -6.46] [%clk 0:02:25] } 24. Re2 { [%eval -6.29] [%clk 0:01:42] } 24... Rhd8 { [%eval -6.04] [%clk 0:02:13] } 25. Rxd2 { [%eval -6.4] [%clk 0:01:32] } 25... Rxd2 { [%eval -6.33] [%clk 0:02:11] } 26. Qe1 { [%eval -6.46] [%clk 0:01:31] } 26... Rxb2 { [%eval -6.73] [%clk 0:02:07] } 27. Rb1 { [%eval -7.46] [%clk 0:01:27] } 27... Qh3+?? { (-7.46 → -2.67) Blunder. Rxa2 was best. } { [%eval -2.67] [%clk 0:01:56] } (27... Rxa2) 28. Kg1 { [%eval -2.84] [%clk 0:01:25] } 28... Rxb1?? { (-2.84 → -0.88) Blunder. Rxa2 was best. } { [%eval -0.88] [%clk 0:01:42] } (28... Rxa2 29. Qf1 Qxf1+ 30. Kxf1 f5 31. Bxf5 Bb6 32. Kg2 Kf6 33. Bc8 Rxf2+ 34. Kg3 Rc2 35. Bxb7) 29. Qxb1 { [%eval -0.77] [%clk 0:01:24] } 29... Bb6 { [%eval -0.75] [%clk 0:01:37] } 30. Qf1 { [%eval -0.91] [%clk 0:01:10] } 30... Qh6?! { (-0.91 → -0.30) Inaccuracy. Qe6 was best. } { [%eval -0.3] [%clk 0:01:31] } (30... Qe6 31. Qg2+ Kf8 32. Qg4 Ke7 33. c4 Kd8 34. Qf5 Kc7 35. h4 Bc5 36. f4 Qxc4 37. fxe5) 31. Qg2+ { [%eval -0.3] [%clk 0:00:56] } 31... Kf8 { [%eval -0.3] [%clk 0:01:29] } 32. Qg4 { [%eval -0.31] [%clk 0:00:53] } 32... Qc1+ { [%eval -0.12] [%clk 0:00:57] } 33. Kg2 { [%eval -0.17] [%clk 0:00:52] } 33... Qd2 { [%eval -0.01] [%clk 0:00:39] } 34. Qc8+ { [%eval 0.0] [%clk 0:00:48] } 34... Ke7 { [%eval 0.0] [%clk 0:00:38] } 35. Qxb7+ { [%eval 0.0] [%clk 0:00:47] } 35... Kf8 { [%eval 0.0] [%clk 0:00:35] } 36. Qc8+ { [%eval 0.0] [%clk 0:00:45] } 36... Ke7 { [%eval 0.0] [%clk 0:00:33] } 37. Bxc6 { [%eval 0.0] [%clk 0:00:37] } 37... Qxf2+ { [%eval 0.0] [%clk 0:00:32] } 38. Kh3 { [%eval 0.0] [%clk 0:00:35] } 38... Qf1+ { [%eval 0.0] [%clk 0:00:31] } 39. Kg4?? { (0.00 → Mate in 3) Checkmate is now unavoidable. Kh4 was best. } { [%eval #-3] [%clk 0:00:31] } (39. Kh4 Qc4+ 40. Kh5 Qxa2 41. Qd7+ Kf8 42. Qc8+) 39... Qg2+ { [%eval #-2] [%clk 0:00:30] } 40. Kf5 { [%eval #-1] [%clk 0:00:26] } 40... Qg5+ { [%eval #-2] [%clk 0:00:28] } 41. Ke4 { [%eval #-2] [%clk 0:00:25] } 41... Qe3+ { [%eval #-1] [%clk 0:00:27] } 42. Kd5 { [%eval #-1] [%clk 0:00:23] } 42... Qc5+ { [%eval #-2] [%clk 0:00:25] } 43. Ke4 { [%eval #-2] [%clk 0:00:23] } 43... Qe3+ { [%eval #-1] [%clk 0:00:22] } 44. Kd5 { [%eval #-1] [%clk 0:00:22] } 44... Qc5+ { [%eval #-2] [%clk 0:00:21] } 45. Ke4 { [%eval #-2] [%clk 0:00:21] } 45... f5+?? { (Mate in 2 → 0.00) Lost forced checkmate sequence. Qc4+ was best. } { [%eval 0.0] [%clk 0:00:17] } (45... Qc4+ 46. Kf5 Qf4#) 46. Kxf5 { [%eval 0.0] [%clk 0:00:20] } 46... e4+ { [%eval 0.0] [%clk 0:00:16] } 47. Kxe4 { [%eval 0.0] [%clk 0:00:17] } 47... Qe3+ { [%eval 0.0] [%clk 0:00:16] } 48. Kf5 { [%eval 0.0] [%clk 0:00:15] } 48... Qd3+ { [%eval 0.02] [%clk 0:00:09] } 49. Be4 { [%eval 0.0] [%clk 0:00:13] } 49... Qd6 { [%eval 0.03] [%clk 0:00:05] } 50. Qb7+ { [%eval 0.11] [%clk 0:00:09] } 50... Bc7 { [%eval 0.17] [%clk 0:00:04] } 51. Qb4 { [%eval 0.21] [%clk 0:00:07] } 51... Qxb4 { [%eval 0.16] [%clk 0:00:02] } 52. cxb4 { [%eval 0.21] [%clk 0:00:07] } 52... Bxh2 { [%eval 0.13] [%clk 0:00:01] } 53. Kg4 { [%eval 0.21] [%clk 0:00:07] } 53... Bd6 { [%eval 0.09] [%clk 0:00:00] } 54. f4 { [%eval -0.04] [%clk 0:00:07] } 54... Bxb4 { [%eval -0.04] [%clk 0:00:00] } 55. Kf5 { [%eval -0.03] [%clk 0:00:07] } 55... Bd6 { [%eval 0.0] [%clk 0:00:00] } 56. Kg4 { [%eval 0.0] [%clk 0:00:06] } 56... f6 { [%eval 0.0] [%clk 0:00:00] } 57. f5 { [%eval 0.0] [%clk 0:00:04] } 57... Bc5 { [%eval 0.0] [%clk 0:00:00] } 58. a3 { [%eval -0.12] [%clk 0:00:04] } 58... Bd6 { [%eval 0.0] [%clk 0:00:00] } 59. a4 { [%eval 0.0] [%clk 0:00:04] } { White wins on time. } 1-0
23
+
24
+
puzzler/generator/util.py ADDED
@@ -0,0 +1,94 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from dataclasses import dataclass
2
+ import math
3
+ import chess
4
+ import chess.engine
5
+ from model import EngineMove, NextMovePair
6
+ from chess import Color, Board
7
+ from chess.pgn import GameNode
8
+ from chess.engine import SimpleEngine, Score
9
+ from typing import Optional
10
+
11
+ nps = []
12
+
13
+ def material_count(board: Board, side: Color) -> int:
14
+ values = { chess.PAWN: 1, chess.KNIGHT: 3, chess.BISHOP: 3, chess.ROOK: 5, chess.QUEEN: 9 }
15
+ return sum(len(board.pieces(piece_type, side)) * value for piece_type, value in values.items())
16
+
17
+ def material_diff(board: Board, side: Color) -> int:
18
+ return material_count(board, side) - material_count(board, not side)
19
+
20
+ def is_up_in_material(board: Board, side: Color) -> bool:
21
+ return material_diff(board, side) > 0
22
+
23
+ def maximum_castling_rights(board: chess.Board) -> chess.Bitboard:
24
+ return (
25
+ (board.pieces_mask(chess.ROOK, chess.WHITE) & (chess.BB_A1 | chess.BB_H1) if board.king(chess.WHITE) == chess.E1 else chess.BB_EMPTY) |
26
+ (board.pieces_mask(chess.ROOK, chess.BLACK) & (chess.BB_A8 | chess.BB_H8) if board.king(chess.BLACK) == chess.E8 else chess.BB_EMPTY)
27
+ )
28
+
29
+
30
+ def get_next_move_pair(engine: SimpleEngine, node: GameNode, winner: Color, limit: chess.engine.Limit) -> NextMovePair:
31
+ info = engine.analyse(node.board(), multipv = 2, limit = limit)
32
+ global nps
33
+ nps.append(info[0]["nps"] / 1000)
34
+ nps = nps[-10000:]
35
+ # print(info)
36
+ best = EngineMove(info[0]["pv"][0], info[0]["score"].pov(winner))
37
+ second = EngineMove(info[1]["pv"][0], info[1]["score"].pov(winner)) if len(info) > 1 else None
38
+ return NextMovePair(node, winner, best, second)
39
+
40
+ def avg_knps():
41
+ global nps
42
+ return round(sum(nps) / len(nps)) if nps else 0
43
+
44
+ def win_chances(score: Score) -> float:
45
+ """
46
+ winning chances from -1 to 1 https://graphsketch.com/?eqn1_color=1&eqn1_eqn=100+*+%282+%2F+%281+%2B+exp%28-0.004+*+x%29%29+-+1%29&eqn2_color=2&eqn2_eqn=&eqn3_color=3&eqn3_eqn=&eqn4_color=4&eqn4_eqn=&eqn5_color=5&eqn5_eqn=&eqn6_color=6&eqn6_eqn=&x_min=-1000&x_max=1000&y_min=-100&y_max=100&x_tick=100&y_tick=10&x_label_freq=2&y_label_freq=2&do_grid=0&do_grid=1&bold_labeled_lines=0&bold_labeled_lines=1&line_width=4&image_w=850&image_h=525
47
+ """
48
+ mate = score.mate()
49
+ if mate is not None:
50
+ return 1 if mate > 0 else -1
51
+
52
+ cp = score.score()
53
+ MULTIPLIER = -0.00368208 # https://github.com/lichess-org/lila/pull/11148
54
+ return 2 / (1 + math.exp(MULTIPLIER * cp)) - 1 if cp is not None else 0
55
+
56
+ def time_control_tier(line: str) -> Optional[int]:
57
+ if not line.startswith("[TimeControl "):
58
+ return None
59
+ try:
60
+ seconds, increment = line[1:][:-2].split()[1].replace("\"", "").split("+")
61
+ total = int(seconds) + int(increment) * 40
62
+ if total >= 480:
63
+ return 3
64
+ if total >= 180:
65
+ return 2
66
+ if total > 60:
67
+ return 1
68
+ return 0
69
+ except:
70
+ return 0
71
+
72
+ def count_mates(board:chess.Board) -> int:
73
+ mates = 0
74
+ for move in board.legal_moves:
75
+ board.push(move)
76
+ if board.is_checkmate():
77
+ mates += 1
78
+ board.pop()
79
+ return mates
80
+
81
+ def rating_tier(line: str) -> Optional[int]:
82
+ if not line.startswith("[WhiteElo ") and not line.startswith("[BlackElo "):
83
+ return None
84
+ try:
85
+ rating = int(line[11:15])
86
+ if rating > 1750:
87
+ return 3
88
+ if rating > 1600:
89
+ return 2
90
+ if rating > 1500:
91
+ return 1
92
+ return 0
93
+ except:
94
+ return 0
puzzler/tagger/README.md ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+
2
+ ```
3
+ const toMake = id => {p=db.puzzle2.findOne({_id:id}); return `make("${id}", "${p.fen}", "${p.moves.join(' ')}")`}
4
+ const toTest = id => `self.assertTrue(cook.test(${toMake(id)}))`
5
+ ```
puzzler/tagger/cook.py ADDED
@@ -0,0 +1,793 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import logging
2
+
3
+ from typing import List, Optional, Union
4
+ import chess
5
+ from chess import square_rank, square_file, Board, SquareSet, Piece, PieceType, square_distance
6
+ from chess import KING, QUEEN, ROOK, BISHOP, KNIGHT, PAWN
7
+ from chess import WHITE, BLACK
8
+ from chess.pgn import ChildNode
9
+ from model import Puzzle, TagKind
10
+ import util
11
+ from util import material_diff
12
+
13
+ logger = logging.getLogger(__name__)
14
+ logging.basicConfig(format='%(asctime)s %(levelname)-4s %(message)s', datefmt='%m/%d %H:%M')
15
+ logger.setLevel(logging.INFO)
16
+
17
+ def log(puzzle: Puzzle) -> None:
18
+ logger.info("https://lichess.org/training/{}".format(puzzle.id))
19
+
20
+ def cook(puzzle: Puzzle) -> List[TagKind]:
21
+ tags : List[TagKind] = []
22
+
23
+ mate_tag = mate_in(puzzle)
24
+ if mate_tag:
25
+ tags.append(mate_tag)
26
+ tags.append("mate")
27
+ if smothered_mate(puzzle):
28
+ tags.append("smotheredMate")
29
+ elif back_rank_mate(puzzle):
30
+ tags.append("backRankMate")
31
+ elif anastasia_mate(puzzle):
32
+ tags.append("anastasiaMate")
33
+ elif hook_mate(puzzle):
34
+ tags.append("hookMate")
35
+ elif arabian_mate(puzzle):
36
+ tags.append("arabianMate")
37
+ else:
38
+ found = boden_or_double_bishop_mate(puzzle)
39
+ if found:
40
+ tags.append(found)
41
+ elif dovetail_mate(puzzle):
42
+ tags.append("dovetailMate")
43
+ elif puzzle.cp > 600:
44
+ tags.append("crushing")
45
+ elif puzzle.cp > 200:
46
+ tags.append("advantage")
47
+ else:
48
+ tags.append("equality")
49
+
50
+ if attraction(puzzle):
51
+ tags.append("attraction")
52
+
53
+ if deflection(puzzle):
54
+ tags.append("deflection")
55
+ elif overloading(puzzle):
56
+ tags.append("overloading")
57
+
58
+ if advanced_pawn(puzzle):
59
+ tags.append("advancedPawn")
60
+
61
+ if double_check(puzzle):
62
+ tags.append("doubleCheck")
63
+
64
+ if quiet_move(puzzle):
65
+ tags.append("quietMove")
66
+
67
+ if defensive_move(puzzle) or check_escape(puzzle):
68
+ tags.append("defensiveMove")
69
+
70
+ if sacrifice(puzzle):
71
+ tags.append("sacrifice")
72
+
73
+ if x_ray(puzzle):
74
+ tags.append("xRayAttack")
75
+
76
+ if fork(puzzle):
77
+ tags.append("fork")
78
+
79
+ if hanging_piece(puzzle):
80
+ tags.append("hangingPiece")
81
+
82
+ if trapped_piece(puzzle):
83
+ tags.append("trappedPiece")
84
+
85
+ if discovered_attack(puzzle):
86
+ tags.append("discoveredAttack")
87
+
88
+ if exposed_king(puzzle):
89
+ tags.append("exposedKing")
90
+
91
+ if skewer(puzzle):
92
+ tags.append("skewer")
93
+
94
+ if self_interference(puzzle) or interference(puzzle):
95
+ tags.append("interference")
96
+
97
+ if intermezzo(puzzle):
98
+ tags.append("intermezzo")
99
+
100
+ if pin_prevents_attack(puzzle) or pin_prevents_escape(puzzle):
101
+ tags.append("pin")
102
+
103
+ if attacking_f2_f7(puzzle):
104
+ tags.append("attackingF2F7")
105
+
106
+ if clearance(puzzle):
107
+ tags.append("clearance")
108
+
109
+ if en_passant(puzzle):
110
+ tags.append("enPassant")
111
+
112
+ if castling(puzzle):
113
+ tags.append("castling")
114
+
115
+ if promotion(puzzle):
116
+ tags.append("promotion")
117
+
118
+ if under_promotion(puzzle):
119
+ tags.append("underPromotion")
120
+
121
+ if capturing_defender(puzzle):
122
+ tags.append("capturingDefender")
123
+
124
+ if piece_endgame(puzzle, PAWN):
125
+ tags.append("pawnEndgame")
126
+ elif piece_endgame(puzzle, QUEEN):
127
+ tags.append("queenEndgame")
128
+ elif piece_endgame(puzzle, ROOK):
129
+ tags.append("rookEndgame")
130
+ elif piece_endgame(puzzle, BISHOP):
131
+ tags.append("bishopEndgame")
132
+ elif piece_endgame(puzzle, KNIGHT):
133
+ tags.append("knightEndgame")
134
+ elif queen_rook_endgame(puzzle):
135
+ tags.append("queenRookEndgame")
136
+
137
+ if "backRankMate" not in tags and "fork" not in tags:
138
+ if kingside_attack(puzzle):
139
+ tags.append("kingsideAttack")
140
+ elif queenside_attack(puzzle):
141
+ tags.append("queensideAttack")
142
+
143
+ if len(puzzle.mainline) == 2:
144
+ tags.append("oneMove")
145
+ elif len(puzzle.mainline) == 4:
146
+ tags.append("short")
147
+ elif len(puzzle.mainline) >= 8:
148
+ tags.append("veryLong")
149
+ else:
150
+ tags.append("long")
151
+
152
+ return tags
153
+
154
+ def advanced_pawn(puzzle: Puzzle) -> bool:
155
+ for node in puzzle.mainline[1::2]:
156
+ if util.is_very_advanced_pawn_move(node):
157
+ return True
158
+ return False
159
+
160
+ def double_check(puzzle: Puzzle) -> bool:
161
+ for node in puzzle.mainline[1::2]:
162
+ if len(node.board().checkers()) > 1:
163
+ return True
164
+ return False
165
+
166
+ def sacrifice(puzzle: Puzzle) -> bool:
167
+ # down in material compared to initial position, after moving
168
+ diffs = [material_diff(n.board(), puzzle.pov) for n in puzzle.mainline]
169
+ initial = diffs[0]
170
+ for d in diffs[1::2][1:]:
171
+ if d - initial <= -2:
172
+ return not any(n.move.promotion for n in puzzle.mainline[::2][1:])
173
+ return False
174
+
175
+ def x_ray(puzzle: Puzzle) -> bool:
176
+ for node in puzzle.mainline[1::2][1:]:
177
+ if not util.is_capture(node):
178
+ continue
179
+ prev_op_node = node.parent
180
+ assert isinstance(prev_op_node, ChildNode)
181
+ if prev_op_node.move.to_square != node.move.to_square or util.moved_piece_type(prev_op_node) == KING:
182
+ continue
183
+ prev_pl_node = prev_op_node.parent
184
+ assert isinstance(prev_pl_node, ChildNode)
185
+ if prev_pl_node.move.to_square != prev_op_node.move.to_square:
186
+ continue
187
+ if prev_op_node.move.from_square in SquareSet.between(node.move.from_square, node.move.to_square):
188
+ return True
189
+
190
+ return False
191
+
192
+ def fork(puzzle: Puzzle) -> bool:
193
+ for node in puzzle.mainline[1::2][:-1]:
194
+ if util.moved_piece_type(node) is not KING:
195
+ board = node.board()
196
+ if util.is_in_bad_spot(board, node.move.to_square):
197
+ continue
198
+ nb = 0
199
+ for (piece, square) in util.attacked_opponent_squares(board, node.move.to_square, puzzle.pov):
200
+ if piece.piece_type == PAWN:
201
+ continue
202
+ if (
203
+ util.king_values[piece.piece_type] > util.king_values[util.moved_piece_type(node)] or (
204
+ util.is_hanging(board, piece, square) and
205
+ square not in board.attackers(not puzzle.pov, node.move.to_square)
206
+ )
207
+ ):
208
+ nb += 1
209
+ if nb > 1:
210
+ return True
211
+ return False
212
+
213
+ def hanging_piece(puzzle: Puzzle) -> bool:
214
+ to = puzzle.mainline[1].move.to_square
215
+ captured = puzzle.mainline[0].board().piece_at(to)
216
+ if puzzle.mainline[0].board().is_check() and (not captured or captured.piece_type == PAWN):
217
+ return False
218
+ if captured and captured.piece_type != PAWN:
219
+ if util.is_hanging(puzzle.mainline[0].board(), captured, to):
220
+ op_move = puzzle.mainline[0].move
221
+ op_capture = puzzle.game.board().piece_at(op_move.to_square)
222
+ if op_capture and util.values[op_capture.piece_type] >= util.values[captured.piece_type] and op_move.to_square == to:
223
+ return False
224
+ if len(puzzle.mainline) < 4:
225
+ return True
226
+ if material_diff(puzzle.mainline[3].board(), puzzle.pov) >= material_diff(puzzle.mainline[1].board(), puzzle.pov):
227
+ return True
228
+ return False
229
+
230
+ def trapped_piece(puzzle: Puzzle) -> bool:
231
+ for node in puzzle.mainline[1::2][1:]:
232
+ square = node.move.to_square
233
+ captured = node.parent.board().piece_at(square)
234
+ if captured and captured.piece_type != PAWN:
235
+ prev = node.parent
236
+ assert isinstance(prev, ChildNode)
237
+ if prev.move.to_square == square:
238
+ square = prev.move.from_square
239
+ if util.is_trapped(prev.parent.board(), square):
240
+ return True
241
+ return False
242
+
243
+ def overloading(puzzle: Puzzle) -> bool:
244
+ return False
245
+
246
+ def discovered_attack(puzzle: Puzzle) -> bool:
247
+ if discovered_check(puzzle):
248
+ return True
249
+ for node in puzzle.mainline[1::2][1:]:
250
+ if util.is_capture(node):
251
+ between = SquareSet.between(node.move.from_square, node.move.to_square)
252
+ assert isinstance(node.parent, ChildNode)
253
+ if node.parent.move.to_square == node.move.to_square:
254
+ return False
255
+ prev = node.parent.parent
256
+ assert isinstance(prev, ChildNode)
257
+ if (prev.move.from_square in between and
258
+ node.move.to_square != prev.move.to_square and
259
+ node.move.from_square != prev.move.to_square and
260
+ not util.is_castling(prev)
261
+ ):
262
+ return True
263
+ return False
264
+
265
+ def discovered_check(puzzle: Puzzle) -> bool:
266
+ for node in puzzle.mainline[1::2]:
267
+ board = node.board()
268
+ checkers = board.checkers()
269
+ if checkers and not node.move.to_square in checkers:
270
+ return True
271
+ return False
272
+
273
+ def quiet_move(puzzle: Puzzle) -> bool:
274
+ for node in puzzle.mainline:
275
+ if (
276
+ # on player move, not the last move of the puzzle
277
+ node.turn() != puzzle.pov and not node.is_end() and
278
+ # no check given or escaped
279
+ not node.board().is_check() and not node.parent.board().is_check() and
280
+ # no capture made or threatened
281
+ not util.is_capture(node) and not util.attacked_opponent_pieces(node.board(), node.move.to_square, puzzle.pov) and
282
+ # no advanced pawn push
283
+ not util.is_advanced_pawn_move(node) and
284
+ util.moved_piece_type(node) != KING
285
+ ):
286
+ return True
287
+ return False
288
+
289
+ def defensive_move(puzzle: Puzzle) -> bool:
290
+ # like quiet_move, but on last move
291
+ # at least 3 legal moves
292
+ if puzzle.mainline[-2].board().legal_moves.count() < 3:
293
+ return False
294
+ node = puzzle.mainline[-1]
295
+ # no check given, no piece taken
296
+ if node.board().is_check() or util.is_capture(node):
297
+ return False
298
+ # no piece attacked
299
+ if util.attacked_opponent_pieces(node.board(), node.move.to_square, puzzle.pov):
300
+ return False
301
+ # no advanced pawn push
302
+ return not util.is_advanced_pawn_move(node)
303
+
304
+ def check_escape(puzzle: Puzzle) -> bool:
305
+ for node in puzzle.mainline[1::2]:
306
+ if node.board().is_check() or util.is_capture(node):
307
+ return False
308
+ if node.parent.board().legal_moves.count() < 3:
309
+ return False
310
+ if node.parent.board().is_check():
311
+ return True
312
+ return False
313
+
314
+ def attraction(puzzle: Puzzle) -> bool:
315
+ for node in puzzle.mainline[1:]:
316
+ if node.turn() == puzzle.pov:
317
+ continue
318
+ # 1. player moves to a square
319
+ first_move_to = node.move.to_square
320
+ opponent_reply = util.next_node(node)
321
+ # 2. opponent captures on that square
322
+ if opponent_reply and opponent_reply.move.to_square == first_move_to:
323
+ attracted_piece = util.moved_piece_type(opponent_reply)
324
+ if attracted_piece in [KING, QUEEN, ROOK]:
325
+ attracted_to_square = opponent_reply.move.to_square
326
+ next_node = util.next_node(opponent_reply)
327
+ if next_node:
328
+ attackers = next_node.board().attackers(puzzle.pov, attracted_to_square)
329
+ # 3. player attacks that square
330
+ if next_node.move.to_square in attackers:
331
+ # 4. player checks on that square
332
+ if attracted_piece == KING:
333
+ return True
334
+ n3 = util.next_next_node(next_node)
335
+ # 4. or player later captures on that square
336
+ if n3 and n3.move.to_square == attracted_to_square:
337
+ return True
338
+ return False
339
+
340
+ def deflection(puzzle: Puzzle) -> bool:
341
+ for node in puzzle.mainline[1::2][1:]:
342
+ captured_piece = node.parent.board().piece_at(node.move.to_square)
343
+ if captured_piece or node.move.promotion:
344
+ capturing_piece = util.moved_piece_type(node)
345
+ if captured_piece and util.king_values[captured_piece.piece_type] > util.king_values[capturing_piece]:
346
+ continue
347
+ square = node.move.to_square
348
+ prev_op_move = node.parent.move
349
+ assert(prev_op_move)
350
+ grandpa = node.parent.parent
351
+ assert isinstance(grandpa, ChildNode)
352
+ prev_player_move = grandpa.move
353
+ prev_player_capture = grandpa.parent.board().piece_at(prev_player_move.to_square)
354
+ if (
355
+ (not prev_player_capture or util.values[prev_player_capture.piece_type] < util.moved_piece_type(grandpa)) and
356
+ square != prev_op_move.to_square and square != prev_player_move.to_square and
357
+ (prev_op_move.to_square == prev_player_move.to_square or grandpa.board().is_check()) and
358
+ (
359
+ square in grandpa.board().attacks(prev_op_move.from_square) or
360
+ node.move.promotion and
361
+ square_file(node.move.to_square) == square_file(prev_op_move.from_square) and
362
+ node.move.from_square in grandpa.board().attacks(prev_op_move.from_square)
363
+ ) and
364
+ (not square in node.parent.board().attacks(prev_op_move.to_square))
365
+ ):
366
+ return True
367
+ return False
368
+
369
+ def exposed_king(puzzle: Puzzle) -> bool:
370
+ if puzzle.pov:
371
+ pov = puzzle.pov
372
+ board = puzzle.mainline[0].board()
373
+ else:
374
+ pov = not puzzle.pov
375
+ board = puzzle.mainline[0].board().mirror()
376
+ king = board.king(not pov)
377
+ assert king is not None
378
+ if chess.square_rank(king) < 5:
379
+ return False
380
+ squares = SquareSet.from_square(king - 8)
381
+ if chess.square_file(king) > 0:
382
+ squares.add(king - 1)
383
+ squares.add(king - 9)
384
+ if chess.square_file(king) < 7:
385
+ squares.add(king + 1)
386
+ squares.add(king - 7)
387
+ for square in squares:
388
+ if board.piece_at(square) == Piece(PAWN, not pov):
389
+ return False
390
+ for node in puzzle.mainline[1::2][1:-1]:
391
+ if node.board().is_check():
392
+ return True
393
+ return False
394
+
395
+ def skewer(puzzle: Puzzle) -> bool:
396
+ for node in puzzle.mainline[1::2][1:]:
397
+ prev = node.parent
398
+ assert isinstance(prev, ChildNode)
399
+ capture = prev.board().piece_at(node.move.to_square)
400
+ if capture and util.moved_piece_type(node) in util.ray_piece_types and not node.board().is_checkmate():
401
+ between = SquareSet.between(node.move.from_square, node.move.to_square)
402
+ op_move = prev.move
403
+ assert op_move
404
+ if (op_move.to_square == node.move.to_square or not op_move.from_square in between):
405
+ continue
406
+ if (
407
+ util.king_values[util.moved_piece_type(prev)] > util.king_values[capture.piece_type] and
408
+ util.is_in_bad_spot(prev.board(), node.move.to_square)
409
+ ):
410
+ return True
411
+ return False
412
+
413
+ def self_interference(puzzle: Puzzle) -> bool:
414
+ # intereference by opponent piece
415
+ for node in puzzle.mainline[1::2][1:]:
416
+ prev_board = node.parent.board()
417
+ square = node.move.to_square
418
+ capture = prev_board.piece_at(square)
419
+ if capture and util.is_hanging(prev_board, capture, square):
420
+ grandpa = node.parent.parent
421
+ assert grandpa
422
+ init_board = grandpa.board()
423
+ defenders = init_board.attackers(capture.color, square)
424
+ defender = defenders.pop() if defenders else None
425
+ defender_piece = init_board.piece_at(defender) if defender else None
426
+ if defender and defender_piece and defender_piece.piece_type in util.ray_piece_types:
427
+ if node.parent.move and node.parent.move.to_square in SquareSet.between(square, defender):
428
+ return True
429
+ return False
430
+
431
+ def interference(puzzle: Puzzle) -> bool:
432
+ # intereference by player piece
433
+ for node in puzzle.mainline[1::2][1:]:
434
+ prev_board = node.parent.board()
435
+ square = node.move.to_square
436
+ capture = prev_board.piece_at(square)
437
+ assert node.parent.move
438
+ if capture and square != node.parent.move.to_square and util.is_hanging(prev_board, capture, square):
439
+ assert node.parent
440
+ assert node.parent.parent
441
+ assert node.parent.parent.parent
442
+ init_board = node.parent.parent.parent.board()
443
+ defenders = init_board.attackers(capture.color, square)
444
+ defender = defenders.pop() if defenders else None
445
+ defender_piece = init_board.piece_at(defender) if defender else None
446
+ if defender and defender_piece and defender_piece.piece_type in util.ray_piece_types:
447
+ interfering = node.parent.parent
448
+ if interfering.move and interfering.move.to_square in SquareSet.between(square, defender):
449
+ return True
450
+ return False
451
+
452
+ def intermezzo(puzzle: Puzzle) -> bool:
453
+ for node in puzzle.mainline[1::2][1:]:
454
+ if util.is_capture(node):
455
+ capture_move = node.move
456
+ capture_square = node.move.to_square
457
+ op_node = node.parent
458
+ assert isinstance(op_node, ChildNode)
459
+ prev_pov_node = node.parent.parent
460
+ assert isinstance(prev_pov_node, ChildNode)
461
+ if not op_node.move.from_square in prev_pov_node.board().attackers(not puzzle.pov, capture_square):
462
+ if prev_pov_node.move.to_square != capture_square:
463
+ prev_op_node = prev_pov_node.parent
464
+ assert isinstance(prev_op_node, ChildNode)
465
+ return (
466
+ prev_op_node.move.to_square == capture_square and
467
+ util.is_capture(prev_op_node) and
468
+ capture_move in prev_op_node.board().legal_moves
469
+ )
470
+ return False
471
+
472
+ # the pinned piece can't attack a player piece
473
+ def pin_prevents_attack(puzzle: Puzzle) -> bool:
474
+ for node in puzzle.mainline[1::2]:
475
+ board = node.board()
476
+ for square, piece in board.piece_map().items():
477
+ if piece.color == puzzle.pov:
478
+ continue
479
+ pin_dir = board.pin(piece.color, square)
480
+ if pin_dir == chess.BB_ALL:
481
+ continue
482
+ for attack in board.attacks(square):
483
+ attacked = board.piece_at(attack)
484
+ if attacked and attacked.color == puzzle.pov and not attack in pin_dir and (
485
+ util.values[attacked.piece_type] > util.values[piece.piece_type] or
486
+ util.is_hanging(board, attacked, attack)
487
+ ):
488
+ return True
489
+ return False
490
+
491
+ # the pinned piece can't escape the attack
492
+ def pin_prevents_escape(puzzle: Puzzle) -> bool:
493
+ for node in puzzle.mainline[1::2]:
494
+ board = node.board()
495
+ for pinned_square, pinned_piece in board.piece_map().items():
496
+ if pinned_piece.color == puzzle.pov:
497
+ continue
498
+ pin_dir = board.pin(pinned_piece.color, pinned_square)
499
+ if pin_dir == chess.BB_ALL:
500
+ continue
501
+ for attacker_square in board.attackers(puzzle.pov, pinned_square):
502
+ if attacker_square in pin_dir:
503
+ attacker = board.piece_at(attacker_square)
504
+ assert(attacker)
505
+ if util.values[pinned_piece.piece_type] > util.values[attacker.piece_type]:
506
+ return True
507
+ if (util.is_hanging(board, pinned_piece, pinned_square) and
508
+ pinned_square not in board.attackers(not puzzle.pov, attacker_square) and
509
+ [m for m in board.pseudo_legal_moves if m.from_square == pinned_square and m.to_square not in pin_dir]
510
+ ):
511
+ return True
512
+ return False
513
+
514
+ def attacking_f2_f7(puzzle: Puzzle) -> bool:
515
+ for node in puzzle.mainline[1::2]:
516
+ square = node.move.to_square
517
+ if node.parent.board().piece_at(node.move.to_square) and square in [chess.F2, chess.F7]:
518
+ king = node.board().piece_at(chess.E8 if square == chess.F7 else chess.E1)
519
+ return king is not None and king.piece_type == KING and king.color != puzzle.pov
520
+ return False
521
+
522
+ def kingside_attack(puzzle: Puzzle) -> bool:
523
+ return side_attack(puzzle, 7, [6, 7], 20)
524
+
525
+ def queenside_attack(puzzle: Puzzle) -> bool:
526
+ return side_attack(puzzle, 0, [0, 1, 2], 18)
527
+
528
+ def side_attack(puzzle: Puzzle, corner_file: int, king_files: List[int], nb_pieces: int) -> bool:
529
+ back_rank = 7 if puzzle.pov else 0
530
+ init_board = puzzle.mainline[0].board()
531
+ king_square = init_board.king(not puzzle.pov)
532
+ if (
533
+ not king_square or
534
+ square_rank(king_square) != back_rank or
535
+ square_file(king_square) not in king_files or
536
+ len(init_board.piece_map()) < nb_pieces or # no endgames
537
+ not any(node.board().is_check() for node in puzzle.mainline[1::2])
538
+ ):
539
+ return False
540
+ score = 0
541
+ corner = chess.square(corner_file, back_rank)
542
+ for node in puzzle.mainline[1::2]:
543
+ corner_dist = square_distance(corner, node.move.to_square)
544
+ if node.board().is_check():
545
+ score += 1
546
+ if util.is_capture(node) and corner_dist <= 3:
547
+ score += 1
548
+ elif corner_dist >= 5:
549
+ score -= 1
550
+ return score >= 2
551
+
552
+ def clearance(puzzle: Puzzle) -> bool:
553
+ for node in puzzle.mainline[1::2][1:]:
554
+ board = node.board()
555
+ if not node.parent.board().piece_at(node.move.to_square):
556
+ piece = board.piece_at(node.move.to_square)
557
+ if piece and piece.piece_type in util.ray_piece_types:
558
+ prev = node.parent.parent
559
+ assert prev
560
+ prev_move = prev.move
561
+ assert prev_move
562
+ assert isinstance(node.parent, ChildNode)
563
+ if (not prev_move.promotion and
564
+ prev_move.to_square != node.move.from_square and
565
+ prev_move.to_square != node.move.to_square and
566
+ not node.parent.board().is_check() and
567
+ (not board.is_check() or util.moved_piece_type(node.parent) != KING)):
568
+ if (prev_move.from_square == node.move.to_square or
569
+ prev_move.from_square in SquareSet.between(node.move.from_square, node.move.to_square)):
570
+ if prev.parent and not prev.parent.board().piece_at(prev_move.to_square) or util.is_in_bad_spot(prev.board(), prev_move.to_square):
571
+ return True
572
+ return False
573
+
574
+ def en_passant(puzzle: Puzzle) -> bool:
575
+ for node in puzzle.mainline[1::2]:
576
+ if (util.moved_piece_type(node) == PAWN and
577
+ square_file(node.move.from_square) != square_file(node.move.to_square) and
578
+ not node.parent.board().piece_at(node.move.to_square)
579
+ ):
580
+ return True
581
+ return False
582
+
583
+ def castling(puzzle: Puzzle) -> bool:
584
+ for node in puzzle.mainline[1::2]:
585
+ if util.is_castling(node):
586
+ return True
587
+ return False
588
+
589
+ def promotion(puzzle: Puzzle) -> bool:
590
+ for node in puzzle.mainline[1::2]:
591
+ if node.move.promotion:
592
+ return True
593
+ return False
594
+
595
+ def under_promotion(puzzle: Puzzle) -> bool:
596
+ for node in puzzle.mainline[1::2]:
597
+ if node.board().is_checkmate():
598
+ return True if node.move.promotion == KNIGHT else False
599
+ elif node.move.promotion and node.move.promotion != QUEEN:
600
+ return True
601
+ return False
602
+
603
+ def capturing_defender(puzzle: Puzzle) -> bool:
604
+ for node in puzzle.mainline[1::2][1:]:
605
+ board = node.board()
606
+ capture = node.parent.board().piece_at(node.move.to_square)
607
+ assert isinstance(node.parent, ChildNode)
608
+ if board.is_checkmate() or (
609
+ capture and
610
+ util.moved_piece_type(node) != KING and
611
+ util.values[capture.piece_type] <= util.values[util.moved_piece_type(node)] and
612
+ util.is_hanging(node.parent.board(), capture, node.move.to_square) and
613
+ node.parent.move.to_square != node.move.to_square
614
+ ):
615
+ prev = node.parent.parent
616
+ assert isinstance(prev, ChildNode)
617
+ if not prev.board().is_check() and prev.move.to_square != node.move.from_square:
618
+ assert prev.parent
619
+ init_board = prev.parent.board()
620
+ defender_square = prev.move.to_square
621
+ defender = init_board.piece_at(defender_square)
622
+ if (defender and
623
+ defender_square in init_board.attackers(defender.color, node.move.to_square) and
624
+ not init_board.is_check()):
625
+ return True
626
+ return False
627
+
628
+ def back_rank_mate(puzzle: Puzzle) -> bool:
629
+ node = puzzle.game.end()
630
+ board = node.board()
631
+ king = board.king(not puzzle.pov)
632
+ assert king is not None
633
+ assert isinstance(node, ChildNode)
634
+ back_rank = 7 if puzzle.pov else 0
635
+ if board.is_checkmate() and square_rank(king) == back_rank:
636
+ squares = SquareSet.from_square(king + (-8 if puzzle.pov else 8))
637
+ if puzzle.pov:
638
+ if chess.square_file(king) < 7:
639
+ squares.add(king - 7)
640
+ if chess.square_file(king) > 0:
641
+ squares.add(king - 9)
642
+ else:
643
+ if chess.square_file(king) < 7:
644
+ squares.add(king + 9)
645
+ if chess.square_file(king) > 0:
646
+ squares.add(king + 7)
647
+ for square in squares:
648
+ piece = board.piece_at(square)
649
+ if piece is None or piece.color == puzzle.pov or board.attackers(puzzle.pov, square):
650
+ return False
651
+ return any(square_rank(checker) == back_rank for checker in board.checkers())
652
+ return False
653
+
654
+ def anastasia_mate(puzzle: Puzzle) -> bool:
655
+ node = puzzle.game.end()
656
+ board = node.board()
657
+ king = board.king(not puzzle.pov)
658
+ assert king is not None
659
+ assert isinstance(node, ChildNode)
660
+ if square_file(king) in [0, 7] and square_rank(king) not in [0, 7]:
661
+ if square_file(node.move.to_square) == square_file(king) and util.moved_piece_type(node) in [QUEEN, ROOK]:
662
+ if square_file(king) != 0:
663
+ board.apply_transform(chess.flip_horizontal)
664
+ king = board.king(not puzzle.pov)
665
+ assert king is not None
666
+ blocker = board.piece_at(king + 1)
667
+ if blocker is not None and blocker.color != puzzle.pov:
668
+ knight = board.piece_at(king + 3)
669
+ if knight is not None and knight.color == puzzle.pov and knight.piece_type == KNIGHT:
670
+ return True
671
+ return False
672
+
673
+ def hook_mate(puzzle: Puzzle) -> bool:
674
+ node = puzzle.game.end()
675
+ board = node.board()
676
+ king = board.king(not puzzle.pov)
677
+ assert king is not None
678
+ assert isinstance(node, ChildNode)
679
+ if util.moved_piece_type(node) == ROOK and square_distance(node.move.to_square, king) == 1:
680
+ for rook_defender_square in board.attackers(puzzle.pov, node.move.to_square):
681
+ defender = board.piece_at(rook_defender_square)
682
+ if defender and defender.piece_type == KNIGHT and square_distance(rook_defender_square, king) == 1:
683
+ for knight_defender_square in board.attackers(puzzle.pov, rook_defender_square):
684
+ pawn = board.piece_at(knight_defender_square)
685
+ if pawn and pawn.piece_type == PAWN:
686
+ return True
687
+ return False
688
+
689
+ def arabian_mate(puzzle: Puzzle) -> bool:
690
+ node = puzzle.game.end()
691
+ board = node.board()
692
+ king = board.king(not puzzle.pov)
693
+ assert king is not None
694
+ assert isinstance(node, ChildNode)
695
+ if square_file(king) in [0, 7] and square_rank(king) in [0, 7] and util.moved_piece_type(node) == ROOK and square_distance(node.move.to_square, king) == 1:
696
+ for knight_square in board.attackers(puzzle.pov, node.move.to_square):
697
+ knight = board.piece_at(knight_square)
698
+ if knight and knight.piece_type == KNIGHT and (
699
+ abs(square_rank(knight_square) - square_rank(king)) == 2 and
700
+ abs(square_file(knight_square) - square_file(king)) == 2
701
+ ):
702
+ return True
703
+ return False
704
+
705
+ def boden_or_double_bishop_mate(puzzle: Puzzle) -> Optional[TagKind]:
706
+ node = puzzle.game.end()
707
+ board = node.board()
708
+ king = board.king(not puzzle.pov)
709
+ assert king is not None
710
+ assert isinstance(node, ChildNode)
711
+ bishop_squares = list(board.pieces(BISHOP, puzzle.pov))
712
+ if len(bishop_squares) < 2:
713
+ return None
714
+ for square in [s for s in SquareSet(chess.BB_ALL) if square_distance(s, king) < 2]:
715
+ if not all([p.piece_type == BISHOP for p in util.attacker_pieces(board, puzzle.pov, square)]):
716
+ return None
717
+ if (square_file(bishop_squares[0]) < square_file(king)) == (square_file(bishop_squares[1]) > square_file(king)):
718
+ return "bodenMate"
719
+ else:
720
+ return "doubleBishopMate"
721
+
722
+ def dovetail_mate(puzzle: Puzzle) -> bool:
723
+ node = puzzle.game.end()
724
+ board = node.board()
725
+ king = board.king(not puzzle.pov)
726
+ assert king is not None
727
+ assert isinstance(node, ChildNode)
728
+ if square_file(king) in [0, 7] or square_rank(king) in [0, 7]:
729
+ return False
730
+ queen_square = node.move.to_square
731
+ if (util.moved_piece_type(node) != QUEEN or
732
+ square_file(queen_square) == square_file(king) or
733
+ square_rank(queen_square) == square_rank(king) or
734
+ square_distance(queen_square, king) > 1):
735
+ return False
736
+ for square in [s for s in SquareSet(chess.BB_ALL) if square_distance(s, king) == 1]:
737
+ if square == queen_square:
738
+ continue
739
+ attackers = list(board.attackers(puzzle.pov, square))
740
+ if attackers == [queen_square]:
741
+ if board.piece_at(square):
742
+ return False
743
+ elif attackers:
744
+ return False
745
+ return True
746
+
747
+ def piece_endgame(puzzle: Puzzle, piece_type: PieceType) -> bool:
748
+ for board in [puzzle.mainline[i].board() for i in [0, 1]]:
749
+ if not board.pieces(piece_type, WHITE) and not board.pieces(piece_type, BLACK):
750
+ return False
751
+ for piece in board.piece_map().values():
752
+ if not piece.piece_type in [KING, PAWN, piece_type]:
753
+ return False
754
+ return True
755
+
756
+ def queen_rook_endgame(puzzle: Puzzle) -> bool:
757
+ def test(board: Board) -> bool:
758
+ pieces = board.piece_map().values()
759
+ return (
760
+ len([p for p in pieces if p.piece_type == QUEEN]) == 1 and
761
+ any(p.piece_type == ROOK for p in pieces) and
762
+ all(p.piece_type in [QUEEN, ROOK, PAWN, KING] for p in pieces)
763
+ )
764
+ return all(test(puzzle.mainline[i].board()) for i in [0, 1])
765
+
766
+ def smothered_mate(puzzle: Puzzle) -> bool:
767
+ board = puzzle.game.end().board()
768
+ king_square = board.king(not puzzle.pov)
769
+ assert king_square is not None
770
+ for checker_square in board.checkers():
771
+ piece = board.piece_at(checker_square)
772
+ assert piece
773
+ if piece.piece_type == KNIGHT:
774
+ for escape_square in [s for s in chess.SQUARES if square_distance(s, king_square) == 1]:
775
+ blocker = board.piece_at(escape_square)
776
+ if not blocker or blocker.color == puzzle.pov:
777
+ return False
778
+ return True
779
+ return False
780
+
781
+ def mate_in(puzzle: Puzzle) -> Optional[TagKind]:
782
+ if not puzzle.game.end().board().is_checkmate():
783
+ return None
784
+ moves_to_mate = len(puzzle.mainline) // 2
785
+ if moves_to_mate == 1:
786
+ return "mateIn1"
787
+ elif moves_to_mate == 2:
788
+ return "mateIn2"
789
+ elif moves_to_mate == 3:
790
+ return "mateIn3"
791
+ elif moves_to_mate == 4:
792
+ return "mateIn4"
793
+ return "mateIn5"
puzzler/tagger/model.py ADDED
@@ -0,0 +1,76 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from dataclasses import dataclass, field
2
+ from chess.pgn import Game, ChildNode
3
+ from chess import Color
4
+ from typing import List, Literal, Optional
5
+
6
+ TagKind = Literal[
7
+ "advancedPawn",
8
+ "advantage",
9
+ "anastasiaMate",
10
+ "arabianMate",
11
+ "attackingF2F7",
12
+ "attraction",
13
+ "backRankMate",
14
+ "bishopEndgame",
15
+ "bodenMate",
16
+ "capturingDefender",
17
+ "castling",
18
+ "clearance",
19
+ "coercion",
20
+ "crushing",
21
+ "defensiveMove",
22
+ "discoveredAttack",
23
+ "deflection",
24
+ "doubleBishopMate",
25
+ "doubleCheck",
26
+ "dovetailMate",
27
+ "equality",
28
+ "enPassant",
29
+ "exposedKing",
30
+ "fork",
31
+ "hangingPiece",
32
+ "hookMate",
33
+ "interference",
34
+ "intermezzo",
35
+ "kingsideAttack",
36
+ "knightEndgame",
37
+ "long",
38
+ "mate",
39
+ "mateIn5",
40
+ "mateIn4",
41
+ "mateIn3",
42
+ "mateIn2",
43
+ "mateIn1",
44
+ "oneMove",
45
+ "overloading",
46
+ "pawnEndgame",
47
+ "pin",
48
+ "promotion",
49
+ "queenEndgame",
50
+ "queensideAttack",
51
+ "quietMove",
52
+ "rookEndgame",
53
+ "queenRookEndgame",
54
+ "sacrifice",
55
+ "short",
56
+ "simplification",
57
+ "skewer",
58
+ "smotheredMate",
59
+ "trappedPiece",
60
+ "underPromotion",
61
+ "veryLong",
62
+ "xRayAttack",
63
+ "zugzwang"
64
+ ]
65
+
66
+ @dataclass
67
+ class Puzzle:
68
+ id: str
69
+ game: Game
70
+ pov : Color = field(init=False)
71
+ mainline: List[ChildNode] = field(init=False)
72
+ cp: int
73
+
74
+ def __post_init__(self):
75
+ self.pov = not self.game.turn()
76
+ self.mainline = list(self.game.mainline())
puzzler/tagger/requirements.txt ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+ chess==1.3.0
2
+ pymongo==3.11.0
puzzler/tagger/tagger.py ADDED
@@ -0,0 +1,147 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import pymongo
2
+ import logging
3
+ import argparse
4
+ from multiprocessing import Process, Queue, Pool, Manager
5
+ from datetime import datetime
6
+ from chess import Move, Board
7
+ from chess.pgn import Game, GameNode
8
+ from chess.engine import SimpleEngine, Mate, Cp
9
+ from typing import List, Tuple, Dict, Any
10
+ from model import Puzzle, TagKind
11
+ import cook
12
+ import chess.engine
13
+ from zugzwang import zugzwang
14
+
15
+ logger = logging.getLogger(__name__)
16
+ logging.basicConfig(format='%(asctime)s %(levelname)-4s %(message)s', datefmt='%m/%d %H:%M')
17
+ logger.setLevel(logging.INFO)
18
+
19
+ def read(doc) -> Puzzle:
20
+ board = Board(doc["fen"])
21
+ node: GameNode = Game.from_board(board)
22
+ for uci in (doc["line"].split(' ') if "line" in doc else doc["moves"]):
23
+ move = Move.from_uci(uci)
24
+ node = node.add_main_variation(move)
25
+ return Puzzle(doc["_id"], node.game(), int(doc["cp"]))
26
+
27
+ if __name__ == "__main__":
28
+ parser = argparse.ArgumentParser(prog='tagger.py', description='automatically tags lichess puzzles')
29
+ parser.add_argument("--zug", "-z", help="only zugzwang", action="store_true")
30
+ parser.add_argument("--bad_mate", help="find bad mates", action="store_true")
31
+ parser.add_argument("--dry", "-d", help="dry run", action="store_true")
32
+ parser.add_argument("--all", "-a", help="don't skip existing", action="store_true")
33
+ parser.add_argument("--threads", "-t", help="count of cpu threads for engine searches", default="4")
34
+ parser.add_argument("--engine", "-e", help="analysis engine", default="stockfish")
35
+ args = parser.parse_args()
36
+
37
+ if args.zug:
38
+ threads = int(args.threads)
39
+ def cruncher(thread_id: int):
40
+ db = pymongo.MongoClient()['puzzler']
41
+ round_coll = db['puzzle2_round']
42
+ play_coll = db['puzzle2_puzzle']
43
+ engine = SimpleEngine.popen_uci(args.engine)
44
+ engine.configure({'Threads': 2})
45
+ for doc in round_coll.aggregate([
46
+ {"$match":{"_id":{"$regex":"^lichess:"},"t":{"$nin":['+zugzwang','-zugzwang']}}},
47
+ {'$lookup':{'from':'puzzle2_puzzle','as':'puzzle','localField':'p','foreignField':'_id'}},
48
+ {'$unwind':'$puzzle'},{'$replaceRoot':{'newRoot':'$puzzle'}}
49
+ ]):
50
+ try:
51
+ if ord(doc["_id"][4]) % threads != thread_id:
52
+ continue
53
+ puzzle = read(doc)
54
+ round_id = f'lichess:{puzzle.id}'
55
+ zug = zugzwang(engine, puzzle)
56
+ if zug:
57
+ cook.log(puzzle)
58
+ round_coll.update_one(
59
+ { "_id": round_id },
60
+ {"$addToSet": {"t": "+zugzwang" if zug else "-zugzwang"}}
61
+ )
62
+ play_coll.update_one({"_id":puzzle.id},{"$set":{"dirty":True}})
63
+ except Exception as e:
64
+ print(doc)
65
+ logger.error(e)
66
+ engine.close()
67
+ exit(1)
68
+ engine.close()
69
+ with Pool(processes=threads) as pool:
70
+ for i in range(int(args.threads)):
71
+ Process(target=cruncher, args=(i,)).start()
72
+ exit(0)
73
+
74
+ if args.bad_mate:
75
+ threads = int(args.threads)
76
+ def cruncher(thread_id: int):
77
+ db = pymongo.MongoClient()['puzzler']
78
+ bad_coll = db['puzzle2_bad_maybe']
79
+ play_coll = db['puzzle2_puzzle']
80
+ engine = SimpleEngine.popen_uci('./stockfish')
81
+ engine.configure({'Threads': 4})
82
+ for doc in bad_coll.find({"bad": {"$exists":False}}):
83
+ try:
84
+ if ord(doc["_id"][4]) % threads != thread_id:
85
+ continue
86
+ doc = play_coll.find_one({'_id': doc['_id']})
87
+ if not doc:
88
+ continue
89
+ puzzle = read(doc)
90
+ board = puzzle.mainline[len(puzzle.mainline) - 2].board()
91
+ info = engine.analyse(board, multipv = 5, limit = chess.engine.Limit(nodes = 30_000_000))
92
+ bad = False
93
+ for score in [pv["score"].pov(puzzle.pov) for pv in info]:
94
+ if score < Mate(1) and score > Cp(250):
95
+ bad = True
96
+ # logger.info(puzzle.id)
97
+ bad_coll.update_one({"_id":puzzle.id},{"$set":{"bad":bad}})
98
+ except Exception as e:
99
+ logger.error(e)
100
+ with Pool(processes=threads) as pool:
101
+ for i in range(int(args.threads)):
102
+ Process(target=cruncher, args=(i,)).start()
103
+ exit(0)
104
+
105
+ threads = int(args.threads)
106
+
107
+ def cruncher(thread_id: int):
108
+ db = pymongo.MongoClient()['puzzler']
109
+ play_coll = db['puzzle2_puzzle']
110
+ round_coll = db['puzzle2_round']
111
+ total = 0
112
+ computed = 0
113
+ updated = 0
114
+ for doc in play_coll.find({'themes':[]}):
115
+ total += 1
116
+ if not thread_id and total % 1000 == 0:
117
+ logger.info(f'{total} / {computed} / {updated}')
118
+ if ord(doc["_id"][4]) % threads != thread_id:
119
+ continue
120
+ computed += 1
121
+ id = doc["_id"]
122
+ if not args.all and round_coll.count_documents({"_id": f"lichess:{id}", "t.1": {"$exists":True}}):
123
+ continue
124
+ tags = cook.cook(read(doc))
125
+ round_id = f"lichess:{id}"
126
+ if not args.dry:
127
+ existing = round_coll.find_one({"_id": round_id},{"t":True})
128
+ zugs = [t for t in existing["t"] if t in ['+zugzwang', '-zugzwang']] if existing else []
129
+ new_tags = [f"+{t}" for t in tags] + zugs
130
+ if not existing or set(new_tags) != set(existing["t"]):
131
+ updated += 1
132
+ round_coll.update_one({
133
+ "_id": round_id
134
+ }, {
135
+ "$set": {
136
+ "p": id,
137
+ "d": datetime.now(),
138
+ "e": 100,
139
+ "t": new_tags
140
+ }
141
+ }, upsert = True);
142
+ play_coll.update_many({"_id":id},{"$set":{"dirty":True}})
143
+ print(f'{thread_id}/{args.threads} done')
144
+
145
+ with Pool(processes=threads) as pool:
146
+ for i in range(int(args.threads)):
147
+ Process(target=cruncher, args=(i,)).start()
puzzler/tagger/test.py ADDED
@@ -0,0 +1,235 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import unittest
2
+ import logging
3
+ import chess
4
+ import util
5
+ import cook
6
+ from model import Puzzle
7
+ from tagger import logger, read
8
+ from chess import parse_square, ROOK
9
+
10
+ def make(id: str, fen: str, line: str) -> Puzzle:
11
+ return read({ "_id": id, "fen": fen, "line": line, "cp": 999999998 })
12
+
13
+ class TestTagger(unittest.TestCase):
14
+
15
+ logger.setLevel(logging.DEBUG)
16
+
17
+ def test_attraction(self):
18
+ self.assertFalse(cook.attraction(make("yUM8F",
19
+ "r1bq1rk1/ppp1bppp/2n2n2/4p1B1/4N1P1/3P1N1P/PPP2P2/R2QKB1R w KQ - 1 9",
20
+ "d1d2 f6e4 d3e4 c6d4 e1c1 d4f3 d2d8 e7g5 d8g5 f3g5"
21
+ )))
22
+
23
+ self.assertFalse(cook.attraction(make("wFGMa",
24
+ "4r1k1/1R3ppp/1N3n2/1bP5/1P6/3p3P/6P1/3R2K1 w - - 0 28",
25
+ "b6d5 f6d5 b7b5 d5c3 d1d3 c3b5"
26
+ )))
27
+
28
+ self.assertTrue(cook.attraction(make("uf4XN",
29
+ "r4rk1/pp3pp1/7p/b2Pn3/4N3/6RQ/P4PPP/q1B1R1K1 b - - 8 26",
30
+ "a5e1 g3g7 g8g7 h3h6 g7g8 e4f6"
31
+ )))
32
+
33
+ self.assertTrue(cook.attraction(make("wRDRr", "2kr1b1r/1p1b2pp/p1P1p2n/2P3N1/P4q2/5N2/4BKPP/R2Q3R b - - 2 18", "d7c6 d1d8 c8d8 g5e6 d8c8 e6f4")))
34
+
35
+ def test_sacrifice(self):
36
+ self.assertTrue(cook.sacrifice(make("1NHUV", "r1b2rk1/pppp1ppp/2n5/3Q2B1/2B5/2P2N2/P1q3PP/4RK1R b - - 1 14", "d7d6 d5f7 f8f7 e1e8")))
37
+ self.assertFalse(cook.sacrifice(make("1HDGN", "3qr1k1/R4pbp/2p3p1/1p1p4/1P3Q2/2P1P3/3B2P1/7K b - - 0 33", "d8b8 f4f7 g8h8 f7g7")))
38
+ self.assertTrue(cook.sacrifice(make("1PljR", "1R1r2k1/5ppp/p7/3q1P2/2pr1B2/3n2PP/4Q3/5RK1 b - - 4 30", "d3f4 e2e8 d8e8 b8e8")))
39
+ self.assertTrue(cook.sacrifice(make("7frsv", "4r1k1/pb3ppp/1p1b1n2/2pP4/4P1q1/2N5/PBQ2PPP/R4RK1 w - - 0 19", "c2e2 d6h2 g1h2 g4h4 h2g1 f6g4 e2g4 h4g4")))
40
+ self.assertFalse(cook.sacrifice(make("2FSmI", "r2q1rk1/pp3p2/4pn1R/8/3Q4/5N2/PPP2PPb/R5K1 w - - 0 19", "g1h2 d8d4 f3d4 f6g4 h2g3 g4h6")))
41
+ self.assertTrue(cook.sacrifice(make("6UjJO", "r1bqnrk1/pp1n2p1/3bp1N1/3p1p2/2pP1P2/2P1PN1R/PP4PP/R1BQ2K1 b - - 1 15", "f8f6 h3h8 g8f7 f3g5 f7g6 d1h5")))
42
+ self.assertTrue(cook.sacrifice(make("uHVch", "4r3/1b4p1/p7/1p1Pp1kr/4Qp2/1B1R1RP1/PP3P1P/2q3K1 w - - 1 31", "g1g2 h5h2 g2h2 e8h8 e4h7 h8h7 h2g2 c1h1")))
43
+ self.assertFalse(cook.sacrifice(make("51K8X", "r3r1k1/pp1n1pp1/2p3p1/3p4/3PnqPN/2P4P/PPQN1P2/4RRK1 w - - 2 18", "h4g2 f4d2 c2d2 e4d2 e1e8 a8e8")))
44
+ # temporary exchange sac
45
+ self.assertTrue(cook.sacrifice(make("2pqYA", "6k1/p6p/2r2bp1/1pp4r/5P2/3R2P1/P5BP/3R3K b - - 1 29", "c5c4 d3d8 f6d8 d1d8 g8f7 g2c6")))
46
+ self.assertFalse(cook.sacrifice(make("bIcc9", "8/8/2R5/7P/2Pk4/p1r5/6P1/6K1 w - - 0 41", "h5h6 a3a2 c6d6 d4c5 d6d1 c3b3 h6h7 b3b1 h7h8q b1d1 g1h2 a2a1q")))
47
+
48
+ def test_defensive(self):
49
+ self.assertFalse(cook.defensive_move(make("6MVFt", "8/2P5/3K4/8/4pk2/2r3p1/R7/8 b - - 0 50", "f4f3 a2a3 c3a3 c7c8q")))
50
+ self.assertFalse(cook.defensive_move(make("5Winv", "6k1/2Q2pp1/p5rp/3P4/2pn3r/5P1q/P1N2RPP/4R1K1 w - - 0 32", "c2d4 h4d4 c7b8 g8h7")))
51
+
52
+ def test_check_escape(self):
53
+ self.assertTrue(cook.check_escape(make("i6rNU", "1R6/1P4p1/8/6k1/4K3/1r4pP/8/8 w - - 0 39", "h3h4 g5g4")))
54
+
55
+ def test_capturing_defender(self):
56
+ self.assertTrue(cook.capturing_defender(make("P6RR5", "3rk3/1RRn4/3r1p2/3pp3/8/2P1B3/5KP1/8 b - - 3 33", "d8b8 c7d7 d6d7 b7b8")))
57
+ self.assertTrue(cook.capturing_defender(make("gfj87", "2rqk2r/pp2ppbp/1n1p2p1/3P4/2P5/2N1B3/PP2QPPP/R4RK1 b k - 0 14", "c8c4 e3b6 d8b6 e2c4")))
58
+ self.assertFalse(cook.capturing_defender(make("i73wX", "2r3k1/1p4bp/pq2p1p1/3pr3/4nPP1/2N4P/PPPB3K/1R1Q1R2 b - - 2 22", "e4c3 b2c3 b6b1 d1b1")))
59
+
60
+ def test_fork(self):
61
+ self.assertTrue(cook.fork(make("0PQep", "6q1/p6p/6p1/4k3/1P2N3/2B2P2/4K1P1/8 b - - 3 43", "e5d5 e4f6 d5c4 f6g8")))
62
+ self.assertFalse(cook.fork(make("0O5RW", "rnb1k2r/p1B2ppp/4p3/1Bb5/8/4P3/PP1K1PPP/nN4NR b kq - 0 12", "b8d7 b5c6 c8a6 c6a8 c5b4 b1c3")))
63
+ self.assertTrue(cook.fork(make("1NxIN", "r3k2r/p2q1ppp/4pn2/1Qp5/8/4P3/PP1N1PPP/R3K2R w KQkq - 2 16", "b5c5 d7d2 e1d2 f6e4 d2e2 e4c5")))
64
+ self.assertFalse(cook.fork(make("6ppA2", "8/p7/1p6/2p5/P6P/2P2Nk1/1r4P1/4R1K1 w - - 1 39", "f3d2 b2d2 h4h5 d2g2")))
65
+ self.assertFalse(cook.fork(make("bypCs", "rnbq1b1r/p1k1pQp1/2p4p/1p1nP1p1/2pP4/2N3B1/PP3P1P/R3KBNR w KQ - 5 14", "c3d5 d8d5 f7d5 c6d5")))
66
+ self.assertFalse(cook.fork(make("qgSLr", "2r3k1/6p1/p2q1rRp/3pp3/3P1p1R/3Q3P/PP3PP1/6K1 w - - 0 31", "g6f6 d6f6 h4h5 e5e4 d3b3 g7g5 b3d5 f6f7 d5e4 c8c1 g1h2 f7h5")))
67
+ self.assertFalse(cook.fork(make("2eqdQ", "r4rk1/pp2qppp/5p2/1b1p4/1b1Q4/2N1B3/PPP2PPP/2KR3R b - - 7 13", "b4c5 d4c5 e7c5 e3c5")))
68
+ self.assertFalse(cook.fork(make("QNrtc", "r2qr1k1/5p1p/pn3bp1/1p6/3P2bN/1P1B2PP/PB3PQ1/R3R1K1 b - - 0 19", "f6d4 e1e8 d8e8 b2d4")))
69
+ self.assertFalse(cook.fork(make("J72FN", "6k1/7p/3R2p1/8/5p2/P4P2/1P1N2PP/3r1nK1 w - - 0 33", "d2e4 f1d2 g1f2 d2e4")))
70
+ # can't detect ray-defended bishop
71
+ # self.assertTrue(cook.fork(make("q0ot7", "3q1rk1/1p1bbppp/8/1PrQP3/8/5N2/1B3PPP/R4RK1 w - - 1 26", "d5b7 c5b5 b7a6 b5b2")))
72
+
73
+ def test_trapped(self):
74
+ self.assertTrue(cook.trapped_piece(make("nPqjh", "r4rk1/pp1nppbp/3p1n2/q4p2/8/N1P1PP2/PP1BB1PP/2RQ1RK1 b - - 0 13", "b7b6 e2b5 a7a6 c3c4 a5a3 b2a3")))
75
+ self.assertFalse(cook.trapped_piece(make("pjqyb", "r1b1k3/1pp4R/3p4/p2P4/2P5/8/PP2pKPP/8 b - - 1 34", "c8f5 h7h8 e8e7 h8a8 e2e1q f2e1")))
76
+ self.assertTrue(cook.trapped_piece(make("pqkqG", "rnb1k2r/ppppqppp/8/2b4n/4P1N1/2N5/PPPP1PPP/R1BQKB1R w KQkq - 3 6", "f2f3 e7h4 g2g3 h5g3 h2g3 h4h1")))
77
+ self.assertFalse(cook.trapped_piece(make("23J63", "2r2rk1/3bbpp1/p2p1n1p/1p1Pp3/4P3/5QNP/PPq2PPN/R1B1R1K1 w - - 6 19", "e1e2 c2d1 h2f1 c8c1 a1c1 d1c1")))
78
+ self.assertFalse(cook.trapped_piece(make("2NQ68", "3qr1k1/p5pp/1p3n2/3p2P1/2rQ4/5B1P/PBb2P2/2R2RK1 w - - 1 21", "f3d5 d8d5 d4d5 f6d5")))
79
+ # wontfix
80
+ # self.assertFalse(cook.trapped_piece(make("RBAaK", "rnbqkbnr/pp3ppp/2p1p3/1N2N3/1B1P4/5Q2/P1P2PPP/1R2KB1R b Kkq - 3 12", "f7f6 f3h5 g7g6 e5g6 h7g6 h5h8 f8b4 b1b4")))
81
+ self.assertTrue(cook.trapped_piece(make("yKXxP", "2kr4/Qp3ppp/1p1q1n2/4r3/8/8/PPP1B1PP/2K1R2R w - - 0 19", "e2d3 e5a5 a7a5 b6a5")))
82
+ self.assertTrue(cook.trapped_piece(make("ybteL", "1r3rk1/4qppp/p1P1p3/Qp2P3/2n5/1R3BP1/P4P1P/1R4K1 w - - 3 30", "a5a6 b8b6 a6b6 c4b6")))
83
+ self.assertTrue(cook.trapped_piece(make("sXDZi", "r5k1/5Npp/8/3r4/4b3/2R2RP1/P5PP/6K1 w - - 1 28", "f3e3 a8a2 f7h6 g7h6")))
84
+ self.assertTrue(cook.trapped_piece(make("0fuIS", "6k1/pp2rpp1/2p4p/8/1Pr5/PB2PpP1/5PbP/1R2K1R1 b - - 3 28", "c4c3 e1d2 e7e3 f2e3 c3b3 b1b3")))
85
+ self.assertTrue(cook.trapped_piece(make("sBEHV", "r2q1r1k/pbp2pp1/3b1n1p/2p1Q3/8/2NB3P/PPP2PP1/R1B1R1K1 w - - 1 16", "e5f5 g7g6 f5f4 d6f4")))
86
+ # wontfix
87
+ # self.assertFalse(cook.trapped_piece(make("RArZa", "r1b2rk1/3qnpb1/p2pp1p1/1pp3B1/4P3/1PNPR2Q/1PP2PPP/R5K1 b - - 2 16", "e6e5 h3d7 c8d7 g5e7")))
88
+
89
+ def test_discovered_attack(self):
90
+ self.assertFalse(cook.discovered_attack(make("0e7Q3", "5rk1/2pqnrpp/p3p1b1/N3P3/1PRPPp2/P4Q2/3B1RPP/6K1 w - - 3 30", "d2f4 f7f4 f3f4 f8f4")))
91
+ self.assertFalse(cook.discovered_attack(make("0ZSP0", "5rk1/3R4/p1p3pp/1p2b3/2P1n2q/4Q2P/PP3PP1/4R1K1 w - - 4 27", "e3e4 h4f2 g1h1 f2f1 e1f1 f8f1")))
92
+ self.assertTrue(cook.discovered_attack(make("01Y7w", "r2q1rk1/pppb1pbp/2n1pnp1/1BPpB3/3P4/4PN2/PP3PPP/RN1QK2R w KQ - 3 9", "e1g1 c6e5 d4e5 d7b5")))
93
+ self.assertTrue(cook.discovered_attack(make("07jQK", "r4rk1/p1p1qppp/3b4/4n3/Q7/2NP4/PP3PPP/R1B2RK1 w - - 0 16", "f1e1 e5f3 g2f3 e7e1")))
94
+ self.assertTrue(cook.discovered_attack(make("0VlKP", "5r2/6k1/8/p1p1p1p1/Pp1p2P1/1P1PnN1P/2P1KR2/8 w - - 3 38", "f3e5 f8e8 e5c6 e3g4 e2f1 g4f2")))
95
+ self.assertFalse(cook.discovered_attack(make("m3h3k", "2r3k1/1r2pp1p/bqNp2p1/3P4/1p2P3/4bN2/1P4PP/2RQR2K w - - 0 24", "c6e7 b7e7 c1c8 a6c8")))
96
+ self.assertFalse(cook.discovered_attack(make("PsryZ", "4r2k/6pp/1R6/1pq5/8/P4QPP/1P3P1K/8 w - - 3 41", "f3c6 c5f2 c6g2 f2b6")))
97
+
98
+ def test_deflection(self):
99
+ self.assertTrue(cook.deflection(make("25Qpt", "r1bqkbnr/pp3p1p/6p1/2pBp3/4P3/2P1B3/PP3PPP/RN1QK2R b KQkq - 0 9", "g8f6 d5f7 e8f7 d1d8")))
100
+ self.assertFalse(cook.deflection(make("0EgUL", "rnb1k2r/pppp2p1/4p2p/5p2/1q1Pn2P/2NQPN2/PPP2PP1/R3KB1R w KQkq - 1 9", "a2a3 b4b2 a1b1 b2c3 d3c3 e4c3")))
101
+ self.assertFalse(cook.deflection(make("08vBP", "8/1R4p1/p5rp/4bN2/5kP1/2P4K/PP6/8 b - - 0 40", "g6g4 b7b4 f4f5 b4g4")))
102
+ self.assertFalse(cook.deflection(make("0ZSP0", "5rk1/3R4/p1p3pp/1p2b3/2P1n2q/4Q2P/PP3PP1/4R1K1 w - - 4 27", "e3e4 h4f2 g1h1 f2f1 e1f1 f8f1")))
103
+ self.assertFalse(cook.deflection(make("3J2Nl", "r2q2k1/pp4bp/3pnppn/3N4/4Pp1B/7P/PPPQ2P1/R4RK1 w - - 0 19", "d5f4 e6f4 f1f4 g6g5 d2d5 g8h8 f4f2 g5h4")))
104
+ self.assertFalse(cook.deflection(make("3051j", "r2k2r1/1b2nQb1/1p2p2p/p3Pp2/2P4q/P6P/NP2R1PN/2R4K b - - 0 26", "h4d4 a2c3 g8f8 f7g7 f8g8 g7h6")))
105
+ self.assertFalse(cook.deflection(make("0VlKP", "5r2/6k1/8/p1p1p1p1/Pp1p2P1/1P1PnN1P/2P1KR2/8 w - - 3 38", "f3e5 f8e8 e5c6 e3g4 e2f1 g4f2")))
106
+ self.assertTrue(cook.deflection(make("7ycL5", "r1bqkb1r/4pp1p/p1pp1np1/4P3/P1B5/2N5/1PP2PPP/R1BQK2R b KQkq - 0 9", "d6e5 c4f7 e8f7 d1d8")))
107
+ self.assertTrue(cook.deflection(make("oGLtH", "8/8/PR4K1/8/5k1P/r7/4p3/8 w - - 0 52", "b6e6 a3a6 e6a6 e2e1q")))
108
+ self.assertTrue(cook.deflection(make("bZQyl", "8/R4pk1/6p1/P6p/3n3P/5PK1/r4NP1/8 w - - 3 43", "a5a6 d4f5 g3h2 a2f2")))
109
+
110
+ def test_skewer(self):
111
+ self.assertTrue(cook.skewer(make("29HGS", "3r4/6p1/5r1p/7k/3N1P2/3K2P1/3R4/3R4 w - - 1 50", "d2e2 d8d4 d3d4 f6d6 d4e5 d6d1")))
112
+ self.assertFalse(cook.skewer(make("aUuGJ", "5R2/p2rkpKp/1p2p1p1/4P1P1/8/8/P7/8 b - - 9 47", "a7a5 f8f7 e7e8 f7d7 e8d7 g7h7 b6b5 h7g6")))
113
+ self.assertTrue(cook.skewer(make("tipFF", "1rr5/3k4/3bpp2/q5p1/PpRP3p/1P3N1P/1K1Q1PP1/7R w - - 2 25", "h1c1 d6f4 d2d3 f4c1")))
114
+ self.assertTrue(cook.skewer(make("DcZWN", "rn3rk1/p2p3p/1pb1p1pn/4Q3/P1B5/qNP2PP1/3N3P/4RRK1 b - - 2 21", "c6a4 e1a1 a3e7 a1a4")))
115
+ self.assertTrue(cook.skewer(make("GeNY1", "3k4/R7/8/1BK3p1/P1P2bPp/6r1/8/8 w - - 3 67", "a4a5 f4e3 c5c6 e3a7")))
116
+ self.assertTrue(cook.skewer(make("frYL7", "7r/3q4/5k1p/8/4pp2/2Q5/P1P3PP/6K1 b - - 1 35", "f6f5 c3h3 f5f6 h3d7")))
117
+
118
+ def test_interference(self):
119
+ self.assertFalse(cook.interference(make("2t6Xz", "6k1/1b1q1pbp/4pnp1/2Pp4/rp1P1P2/3BPRNP/4Q1P1/4B1K1 b - - 1 26", "f6e4 d3b5 b7c6 b5a4")))
120
+ self.assertTrue(cook.interference(make("QssMO", "r5k1/ppp2r2/3p3p/3Pp3/1P2N1bb/R5N1/1P3P1K/6R1 b - - 5 25", "g4f3 g3f5 g8h7 a3f3")))
121
+
122
+ # def test_overloading(self):
123
+ # self.assertTrue(cook.overloading(make("MB3gB", "r4rk1/ppq2ppp/2nb1n2/1Bpp2N1/6b1/P1N1P1P1/1PQP1P1P/R1B1R1K1 b - - 6 12", "h7h6 c3d5 h6g5 d5c7")))
124
+
125
+ # def test_clearance(self):
126
+ # self.assertTrue(cook.clearance(make("iq12Z", "1R6/1P2r1pk/7p/6pr/3Pp3/1KP1R3/8/8 b - - 0 55", "g5g4 b8h8 h7h8 b7b8q")))
127
+
128
+ def test_x_ray(self):
129
+ self.assertTrue(cook.x_ray(make("fo0LG", "5R2/8/p1p4p/1p1p2k1/6r1/1P2P1r1/P1PKR3/8 b - - 3 33", "g3g2 f8g8 g5f6 e2g2 g4g2 g8g2")))
130
+
131
+ def test_quiet_move(self):
132
+ self.assertFalse(cook.quiet_move(make("SxOf2", "7r/3k4/1P3p2/1K1Pp1p1/2N1P1P1/8/8/8 b - - 2 49", "h8h4 b6b7 h4h1 b7b8n")))
133
+
134
+ def test_pin_prevents_attack(self):
135
+ # pins the queen from attacking the g2 pawn
136
+ self.assertTrue(cook.pin_prevents_attack(make("P2D4h", "2k5/p7/bpq1p3/8/2PP2P1/1K2P1p1/4Q1P1/8 b - - 4 36", "a6c4 e2c4 c6c4 b3c4")))
137
+ self.assertTrue(cook.pin_prevents_attack(make("aJPsJ", "r2q1r1k/pp3pp1/2p2n1p/3PB2b/3P4/1B5P/P1PQ1PP1/R3R1K1 b - - 0 18", "f6d5 d2h6 h8g8 h6g7")))
138
+ self.assertFalse(cook.pin_prevents_attack(make("9CkIh", "r4r2/pp3pkp/2p5/3pPp1q/3p1P2/3Q1R2/PPP3PP/R5K1 b - - 3 18", "c6c5 f3h3 h5g6 h3g3 g7h8 g3g6")))
139
+ self.assertFalse(cook.pin_prevents_attack(make("0CR44", "r2q4/4b1kp/6p1/2ppPr2/3P4/2P2N2/P4RQP/R5K1 w - - 0 27", "f3d2 f5g5 d2f3 g5g2")))
140
+ self.assertFalse(cook.pin_prevents_attack(make("NCP9T", "1kr5/p3R3/7p/5Pp1/6P1/6K1/PP1R1P1P/6r1 w - - 1 32", "g3h3 h6h5 g4h5 c8h8 e7e8 h8e8")))
141
+ # relative pin
142
+ # self.assertTrue(cook.pin_prevents_attack(make("spQRx", "8/8/5K2/5p2/6k1/3R2Pr/8/8 w - - 16 56", "f6e5 f5f4")))
143
+
144
+ def test_pin_prevents_escape(self):
145
+ self.assertFalse(cook.pin_prevents_escape(make("P2D4h", "2k5/p7/bpq1p3/8/2PP2P1/1K2P1p1/4Q1P1/8 b - - 4 36", "a6c4 e2c4 c6c4 b3c4")))
146
+ self.assertFalse(cook.pin_prevents_escape(make("aJPsJ", "r2q1r1k/pp3pp1/2p2n1p/3PB2b/3P4/1B5P/P1PQ1PP1/R3R1K1 b - - 0 18", "f6d5 d2h6 h8g8 h6g7")))
147
+ self.assertTrue(cook.pin_prevents_escape(make("9CkIh", "r4r2/pp3pkp/2p5/3pPp1q/3p1P2/3Q1R2/PPP3PP/R5K1 b - - 3 18", "c6c5 f3h3 h5g6 h3g3 g7h8 g3g6")))
148
+ self.assertTrue(cook.pin_prevents_escape(make("0CR44", "r2q4/4b1kp/6p1/2ppPr2/3P4/2P2N2/P4RQP/R5K1 w - - 0 27", "f3d2 f5g5 d2f3 g5g2")))
149
+ self.assertFalse(cook.pin_prevents_escape(make("NCP9T", "1kr5/p3R3/7p/5Pp1/6P1/6K1/PP1R1P1P/6r1 w - - 1 32", "g3h3 h6h5 g4h5 c8h8 e7e8 h8e8")))
150
+ self.assertFalse(cook.pin_prevents_escape(make("6Jh1x", "2r5/1KP5/8/4k3/7p/7P/4p3/2R5 b - - 1 49", "c8e8 c1e1 e5f4 e1e2 e8e2 c7c8q")))
151
+
152
+ def test_hanging_piece(self):
153
+ self.assertTrue(cook.hanging_piece(make("069il", "r2qr1k1/1p3ppp/p1p2nb1/8/4P3/1P5P/PBQN1PP1/R3R1K1 w - - 1 17", "c2c4 d8d2 b2f6 g7f6")))
154
+ self.assertTrue(cook.hanging_piece(make("cWlcD", "8/p4p2/2p2Pk1/1p1p2pp/1P4P1/2P4P/2r2R2/5K2 b - - 1 40", "h5g4 f2c2")))
155
+ self.assertTrue(cook.hanging_piece(make("YJNLD", "2B2k2/pp5p/2p5/2n1p3/1PPbPp1q/P6P/4Q1P1/3N3K b - - 0 28", "c5e4 e2e4")))
156
+ self.assertTrue(cook.hanging_piece(make("yXCrM", "2r3k1/5ppp/bq2p3/p2pPnP1/5PR1/NP3NbP/P2Q4/2BK4 b - - 0 27", "b6g1 f3g1")))
157
+
158
+ def test_advanced_pawn(self):
159
+ self.assertFalse(cook.advanced_pawn(make("C3gv2", "4r3/R1p2k2/3p1pp1/2r2p1p/1pN2Pn1/1P2PKP1/2P3P1/4R3 b - - 3 39", "d6d5 c4d6 f7e7 d6e8")))
160
+ self.assertFalse(cook.advanced_pawn(make("JgJgO", "1R6/6kp/4Pp1q/3P4/R1P5/P5pP/6P1/7K w - - 1 34", "e6e7 h6c1")))
161
+ self.assertTrue(cook.advanced_pawn(make("PKGhN", "2R5/2P2kpp/8/1p4b1/4n3/P6P/2p2PPK/2B5 b - - 0 41", "g5c1 c8f8 f7f8 c7c8q")))
162
+ self.assertFalse(cook.advanced_pawn(make("qqs1r", "6r1/pppq3k/2np2np/8/3P2pB/N1PR1p2/PP2QPBN/6K1 w - - 0 33", "g2f3 g4f3 e2f1 g6h4")))
163
+
164
+ def test_rook_endgame(self):
165
+ self.assertFalse(cook.piece_endgame(make("qgryh", "8/p5KP/k7/6R1/6P1/1p6/8/7r w - - 0 44", "h7h8q h1h8 g7h8 b3b2 g5h5 b2b1q"), ROOK))
166
+ self.assertFalse(cook.piece_endgame(make("p5BrZ", "8/4R1P1/8/3r4/6K1/8/4p3/3k4 b - - 0 62", "e2e1q e7e1 d1e1 g7g8q"), ROOK))
167
+ self.assertTrue(cook.piece_endgame(make("j0qyE", "8/5p2/5k2/p4p2/8/1PPp1R2/r7/3K2R1 w - - 1 36", "f3d3 a2a1 d1d2 a1g1"), ROOK))
168
+ self.assertFalse(cook.piece_endgame(make("Zjk3J", "8/pppk4/3p4/3P1p1p/PP3Rr1/4PpPK/5P2/8 w - - 5 36", "f4g4 h5g4 h3h4 c7c5 d5c6 b7c6 h4g5 d7e6"), ROOK))
169
+
170
+ def test_intermezzo(self):
171
+ self.assertTrue(cook.intermezzo(make("11pYZ", "8/5rpk/7p/8/3Q4/B4NKP/R2n2P1/5q2 b - - 3 42", "d2f3 d4e4 g7g6 g2f3")))
172
+ self.assertTrue(cook.intermezzo(make("1E2zU", "6k1/4rpp1/3r3p/p2N4/PbB5/1Pq2Q1P/R2p1PP1/3R2K1 b - - 8 31", "c3f3 d5e7 g8f8 g2f3")))
173
+ self.assertFalse(cook.intermezzo(make("1KWbk", "3r2k1/p3bqpp/2b1p3/2p2p2/8/2PNB1QP/PP3PP1/R5K1 w - - 2 26", "d3c5 f5f4 e3f4 e7c5")))
174
+ self.assertFalse(cook.intermezzo(make("21ViC", "4b2r/r6k/6p1/3BQ1Rn/3P1P1P/p1qN4/2P5/2K5 b - - 0 33", "c3c7 g5h5 g6h5 d5e4 e8g6 e5h5 h7g8 h5g6")))
175
+
176
+ def test_back_rank_mate(self):
177
+ self.assertTrue(cook.back_rank_mate(make("tMEri", "5r1k/4q1p1/p2pP2p/1p6/1P2Q3/PB6/1BP3PP/6K1 w - - 1 27", "e4g6 e7a7 b2d4 a7d4 g1h1 f8f1")))
178
+ self.assertFalse(cook.back_rank_mate(make("08VjT", "3r2k1/1bQ3p1/p2p3p/3qp1b1/1p6/1P1B4/P1P3PP/1K3R2 b - - 4 25", "d5c6 c7f7 g8h8 f7f8 d8f8 f1f8")))
179
+ self.assertTrue(cook.back_rank_mate(make("LYKY0", "r5k1/pQ3ppp/8/8/B1pp4/4q3/PP5P/5R1K b - - 0 26", "a8d8 b7f7 g8h8 f7f8 d8f8 f1f8")))
180
+ self.assertFalse(cook.back_rank_mate(make("ABCL2", "3r2k1/1b4pp/1p2pr2/p5N1/8/PP2n1P1/1BR2bBP/4R2K w - - 1 27", "b2f6 b7g2")))
181
+
182
+ def test_side_attack(self):
183
+ self.assertFalse(cook.kingside_attack(make("UTR0G", "rn1qk2r/5ppp/2p1p3/pp3bN1/1b1P2n1/1QN1PP2/P3B2P/R1B2RK1 w kq - 0 13", "f3g4 d8g5 e3e4 g5d8 e4f5 d8d4")))
184
+ self.assertFalse(cook.kingside_attack(make("KnAMG", "6k1/1p4p1/p1p4p/3p1rq1/3Pp1N1/2P5/PP2K1Q1/5R2 w - - 0 39", "g4h6 g7h6 g2g5 f5g5")))
185
+ self.assertTrue(cook.kingside_attack(make("mFqus", "3r2k1/1p3ppp/pq6/8/P3B3/5PNb/1PP1Qb1P/R1B3K1 w - - 0 25", "e2f2 d8d1 g3f1 d1f1")))
186
+ self.assertTrue(cook.kingside_attack(make("XbfXS", "r4rk1/bpp3p1/p2p2qp/3bp3/1P6/P1PP3P/1B1Q1PPN/R4RK1 w - - 1 21", "g2g3 g6g3")))
187
+ self.assertTrue(cook.kingside_attack(make("djudB", "r1b1kb2/pp1n1p2/4p3/3pP2r/3n4/3B1N1q/PP3P1P/R1BQ1RK1 w q - 0 17", "f3d4 h3h2")))
188
+ self.assertTrue(cook.kingside_attack(make("NZvxf", "rn1q1rk1/pp1bbpp1/2p4p/2PpN3/3PnN1P/3B1P2/PPQ3P1/R1B2RK1 b - - 0 15", "e4g3 d3h7 g8h8 e5f7 f8f7 f4g6 h8h7 g6f8 h7g8 c2h7 g8f8 h7h8")))
189
+ # self.assertFalse("kingsideAttack" in cook.cook(make("6h1wj", "r3r1k1/pppb2pp/1b6/3PRp2/1q3B2/1N3Q2/PP3PPP/R5K1 w - - 1 18", "a1e1 b4e1 e5e1 e8e1")))
190
+ self.assertFalse(cook.kingside_attack(make("fLaC0", "2r2rk1/1q3pp1/p3p2p/1p1N1b2/8/P3PQ2/1P3PPP/R2R2K1 b - - 0 25", "f5c2 d5f6 g7f6 f3b7")))
191
+ self.assertFalse("kingsideAttack" in cook.cook(make("NIxjp", "r1b1k2r/pppp2pp/5n2/b3q3/8/2PBP3/PP4PP/RNBQ1RK1 w kq - 3 11", "b1d2 e5e3 g1h1 e3d3")))
192
+
193
+ self.assertTrue(cook.queenside_attack(make("gO5Jg", "2k2b2/1p3b1p/2p2p2/1p1qp3/6PN/1P2Q2P/P1P2P2/2KB4 w - - 1 28", "h4f5 f8a3 c1b1 d5d1 e3c1 d1c1")))
194
+ self.assertTrue(cook.queenside_attack(make("Oiyfh", "k2r1b2/ppR1p1p1/7r/4B2p/8/1P3B2/P2PK1PP/8 b - - 2 25", "d8b8 f3b7 b8b7 c7c8 b7b8 c8b8")))
195
+ # self.assertTrue(cook.queenside_attack(make("nAZo8", "2kr1b2/Q1p2pp1/8/1bPpN1p1/8/2P5/Pr6/R3K3 b - - 0 23", "g5g4 a7a8")))
196
+ self.assertFalse(cook.queenside_attack(make("TiK0f", "1kq5/pp3pQ1/2p5/4p3/4Pn1p/5P1P/1PP2P1K/5B2 b - - 0 38", "c8c7 g7h8 c7c8 h8e5")))
197
+ self.assertFalse(cook.queenside_attack(make("Zk4Jr", "3rr1k1/p5pp/2p5/8/1P1bbp2/P1PP1B2/6PP/RK3R2 w - - 0 28", "c3d4 e4d3 b1b2 d3f1")))
198
+ self.assertFalse(cook.queenside_attack(make("umd5a", "r4r1k/5p1p/5qp1/p3b1RP/1p3P2/8/PP1BQ3/2K4R w - - 0 32", "g5e5 f6c6 c1d1 c6h1")))
199
+
200
+ def test_underpromotion(self):
201
+ #unnecessary underpromotion to rook with mate
202
+ self.assertFalse(cook.under_promotion(make("1nFrQ", "8/1Pp3p1/8/2p5/2P5/5kbp/3p4/7K w - - 0 52", "b7b8q d2d1r")))
203
+ #underpromotion to knight with mate
204
+ self.assertTrue(cook.under_promotion(make("2WyFZ", "3R3r/p1P1kp1b/4pnpp/7P/6P1/2p5/P4P2/3R2K1 b - - 0 31", "c3c2 c7c8n")))
205
+ #Necessary underpromotions to knight, rook & bishop respectively:-
206
+ self.assertTrue(cook.under_promotion(make("0Xyxz", "6k1/p7/4pr2/2P3r1/4Bp1q/1Q3PpP/P4bP1/3R1R1K w - - 1 33", "d1d7 h4h3 g2h3 g3g2 h1h2 g2f1n h2h1 g5g1")))
207
+ self.assertTrue(cook.under_promotion(make("AB2ON", "R7/P7/8/8/6k1/7p/r7/5K2 b - - 0 51", "g4g3 a8g8 g3h2 a7a8r")))
208
+ self.assertTrue(cook.under_promotion(make("DzdfL", "6k1/P5P1/1n4K1/8/8/8/8/8 b - - 2 68", "b6c8 a7a8b c8e7 g6f6")))
209
+ #underpromotion to bishop with mate
210
+ self.assertFalse(cook.under_promotion(make("iLgxo", "3B4/1pp5/p1b1B3/P3Q1N1/1P5k/2P5/R3R1p1/1q4K1 w - - 2 39", "g1h2 g2g1b")))
211
+ #promotion to queen with mate(also possible with rook)
212
+ self.assertFalse(cook.under_promotion(make("00ueM", "2kr4/2pR4/2P1K1P1/8/8/p3n3/8/8 b - - 1 49", "a3a2 d7d8 c8d8 g6g7 a2a1q g7g8q")))
213
+
214
+
215
+ class TestUtil(unittest.TestCase):
216
+
217
+ def test_trapped(self):
218
+ self.assertFalse(util.is_trapped(
219
+ chess.Board("q3k3/7p/8/4N2q/3PP3/4B3/8/4K2R b - - 0 1"), parse_square("h5")
220
+ ))
221
+ self.assertTrue(util.is_trapped(
222
+ chess.Board("q3k3/7p/8/4N2q/3PP3/4B3/7R/4K2R b - - 0 1"), parse_square("h5")
223
+ ))
224
+ self.assertFalse(util.is_trapped(
225
+ chess.Board("q3k3/7p/8/4N2b/3PP3/4B3/7R/4K2R b - - 0 1"), parse_square("h5")
226
+ ))
227
+ self.assertFalse(util.is_trapped(
228
+ chess.Board("4k3/7p/8/4N2q/3PP2p/4B3/8/4K3 b - - 0 1"), parse_square("h5")
229
+ ))
230
+ self.assertTrue(util.is_trapped(
231
+ chess.Board("8/3P4/8/4N2b/7p/6N1/8/4K3 b - - 0 1"), parse_square("h5")
232
+ ))
233
+
234
+ if __name__ == '__main__':
235
+ unittest.main()
puzzler/tagger/util.py ADDED
@@ -0,0 +1,134 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import List, Optional, Tuple
2
+ import chess
3
+ from chess import square_rank, Color, Board, Square, Piece, square_distance
4
+ from chess import KING, QUEEN, ROOK, BISHOP, KNIGHT, PAWN
5
+ from chess.pgn import ChildNode
6
+ from typing import Type, TypeVar
7
+
8
+ A = TypeVar('A')
9
+ def pp(a: A, msg = None) -> A:
10
+ print(f'{msg + ": " if msg else ""}{a}')
11
+ return a
12
+
13
+ def moved_piece_type(node: ChildNode) -> chess.PieceType:
14
+ pt = node.board().piece_type_at(node.move.to_square)
15
+ assert(pt)
16
+ return pt
17
+
18
+ def is_advanced_pawn_move(node: ChildNode) -> bool:
19
+ if node.move.promotion:
20
+ return True
21
+ if moved_piece_type(node) != chess.PAWN:
22
+ return False
23
+ to_rank = square_rank(node.move.to_square)
24
+ return to_rank < 3 if node.turn() else to_rank > 4
25
+
26
+ def is_very_advanced_pawn_move(node: ChildNode) -> bool:
27
+ if not is_advanced_pawn_move(node):
28
+ return False
29
+ to_rank = square_rank(node.move.to_square)
30
+ return to_rank < 2 if node.turn() else to_rank > 5
31
+
32
+ def is_king_move(node: ChildNode) -> bool:
33
+ return moved_piece_type(node) == chess.KING
34
+
35
+ def is_castling(node: ChildNode) -> bool:
36
+ return is_king_move(node) and square_distance(node.move.from_square, node.move.to_square) > 1
37
+
38
+ def is_capture(node: ChildNode) -> bool:
39
+ return node.parent.board().is_capture(node.move)
40
+
41
+ def next_node(node: ChildNode) -> Optional[ChildNode]:
42
+ return node.variations[0] if node.variations else None
43
+
44
+ def next_next_node(node: ChildNode) -> Optional[ChildNode]:
45
+ nn = next_node(node)
46
+ return next_node(nn) if nn else None
47
+
48
+ values = { PAWN: 1, KNIGHT: 3, BISHOP: 3, ROOK: 5, QUEEN: 9 }
49
+ king_values = { PAWN: 1, KNIGHT: 3, BISHOP: 3, ROOK: 5, QUEEN: 9, KING: 99 }
50
+ ray_piece_types = [QUEEN, ROOK, BISHOP]
51
+
52
+ def piece_value(piece_type: chess.PieceType) -> int:
53
+ return values[piece_type]
54
+
55
+ def material_count(board: Board, side: Color) -> int:
56
+ return sum(len(board.pieces(piece_type, side)) * value for piece_type, value in values.items())
57
+
58
+ def material_diff(board: Board, side: Color) -> int:
59
+ return material_count(board, side) - material_count(board, not side)
60
+
61
+ def attacked_opponent_pieces(board: Board, from_square: Square, pov: Color) -> List[Piece]:
62
+ return [piece for (piece, _) in attacked_opponent_squares(board, from_square, pov)]
63
+
64
+ def attacked_opponent_squares(board: Board, from_square: Square, pov: Color) -> List[Tuple[Piece, Square]]:
65
+ pieces = []
66
+ for attacked_square in board.attacks(from_square):
67
+ attacked_piece = board.piece_at(attacked_square)
68
+ if attacked_piece and attacked_piece.color != pov:
69
+ pieces.append((attacked_piece, attacked_square))
70
+ return pieces
71
+
72
+ def is_defended(board: Board, piece: Piece, square: Square) -> bool:
73
+ if board.attackers(piece.color, square):
74
+ return True
75
+ # ray defense https://lichess.org/editor/6k1/3q1pbp/2b1p1p1/1BPp4/rp1PnP2/4PRNP/4Q1P1/4B1K1_w_-_-_0_1
76
+ for attacker in board.attackers(not piece.color, square):
77
+ attacker_piece = board.piece_at(attacker)
78
+ assert(attacker_piece)
79
+ if attacker_piece.piece_type in ray_piece_types:
80
+ bc = board.copy(stack = False)
81
+ bc.remove_piece_at(attacker)
82
+ if bc.attackers(piece.color, square):
83
+ return True
84
+
85
+ return False
86
+
87
+ def is_hanging(board: Board, piece: Piece, square: Square) -> bool:
88
+ return not is_defended(board, piece, square)
89
+
90
+ def can_be_taken_by_lower_piece(board: Board, piece: Piece, square: Square) -> bool:
91
+ for attacker_square in board.attackers(not piece.color, square):
92
+ attacker = board.piece_at(attacker_square)
93
+ assert(attacker)
94
+ if attacker.piece_type != chess.KING and values[attacker.piece_type] < values[piece.piece_type]:
95
+ return True
96
+ return False
97
+
98
+ def is_in_bad_spot(board: Board, square: Square) -> bool:
99
+ # hanging or takeable by lower piece
100
+ piece = board.piece_at(square)
101
+ assert(piece)
102
+ return (bool(board.attackers(not piece.color, square)) and
103
+ (is_hanging(board, piece, square) or can_be_taken_by_lower_piece(board, piece, square)))
104
+
105
+ def is_trapped(board: Board, square: Square) -> bool:
106
+ if board.is_check() or board.is_pinned(board.turn, square):
107
+ return False
108
+ piece = board.piece_at(square)
109
+ assert(piece)
110
+ if piece.piece_type in [PAWN, KING]:
111
+ return False
112
+ if not is_in_bad_spot(board, square):
113
+ return False
114
+ for escape in board.legal_moves:
115
+ if escape.from_square == square:
116
+ capturing = board.piece_at(escape.to_square)
117
+ if capturing and values[capturing.piece_type] >= values[piece.piece_type]:
118
+ return False
119
+ board.push(escape)
120
+ if not is_in_bad_spot(board, escape.to_square):
121
+ return False
122
+ board.pop()
123
+ return True
124
+
125
+ def attacker_pieces(board: Board, color: Color, square: Square) -> List[Piece]:
126
+ return [p for p in [board.piece_at(s) for s in board.attackers(color, square)] if p]
127
+
128
+ # def takers(board: Board, square: Square) -> List[Tuple[Piece, Square]]:
129
+ # # pieces that can legally take on a square
130
+ # t = []
131
+ # for attack in board.legal_moves:
132
+ # if attack.to_square == square:
133
+ # t.append((board.piece_at(attack.from_square), attack.from_square))
134
+ # return t
puzzler/tagger/zugzwang.py ADDED
@@ -0,0 +1,44 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import chess
2
+ import chess.engine
3
+ import math
4
+ from chess import Board, Move, Color
5
+ from chess.engine import SimpleEngine, Score
6
+ from model import Puzzle
7
+
8
+ engine_limit = chess.engine.Limit(depth = 30, time = 10, nodes = 12_000_000)
9
+
10
+ def zugzwang(engine: SimpleEngine, puzzle: Puzzle) -> bool:
11
+ for node in puzzle.mainline[1::2]:
12
+ board = node.board()
13
+ if board.is_check():
14
+ continue
15
+ if len(list(board.legal_moves)) > 15:
16
+ continue
17
+
18
+ score = score_of(engine, board, not puzzle.pov)
19
+
20
+ rev_board = node.board()
21
+ rev_board.push(Move.null())
22
+ rev_score = score_of(engine, rev_board, not puzzle.pov)
23
+
24
+ if win_chances(score) < win_chances(rev_score) - 0.3:
25
+ return True
26
+
27
+ return False
28
+
29
+ def score_of(engine: SimpleEngine, board: Board, pov: Color):
30
+ info = engine.analyse(board, limit = engine_limit)
31
+ if "nps" in info:
32
+ print(f'knps: {int(info["nps"] / 1000)} kn: {int(info["nodes"] / 1000)} depth: {info["depth"]} time: {info["time"]}')
33
+ return info["score"].pov(pov)
34
+
35
+ def win_chances(score: Score) -> float:
36
+ """
37
+ winning chances from -1 to 1 https://graphsketch.com/?eqn1_color=1&eqn1_eqn=100+*+%282+%2F+%281+%2B+exp%28-0.004+*+x%29%29+-+1%29&eqn2_color=2&eqn2_eqn=&eqn3_color=3&eqn3_eqn=&eqn4_color=4&eqn4_eqn=&eqn5_color=5&eqn5_eqn=&eqn6_color=6&eqn6_eqn=&x_min=-1000&x_max=1000&y_min=-100&y_max=100&x_tick=100&y_tick=10&x_label_freq=2&y_label_freq=2&do_grid=0&do_grid=1&bold_labeled_lines=0&bold_labeled_lines=1&line_width=4&image_w=850&image_h=525
38
+ """
39
+ mate = score.mate()
40
+ if mate is not None:
41
+ return 1 if mate > 0 else -1
42
+
43
+ cp = score.score()
44
+ return 2 / (1 + math.exp(-0.004 * cp)) - 1 if cp is not None else 0
requirements.txt ADDED
@@ -0,0 +1 @@
 
 
1
+ chess
stockfish/AUTHORS ADDED
@@ -0,0 +1,255 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Founders of the Stockfish project and Fishtest infrastructure
2
+ Tord Romstad (romstad)
3
+ Marco Costalba (mcostalba)
4
+ Joona Kiiski (zamar)
5
+ Gary Linscott (glinscott)
6
+
7
+ # Authors and inventors of NNUE, training, and NNUE port
8
+ Yu Nasu (ynasu87)
9
+ Motohiro Isozaki (yaneurao)
10
+ Hisayori Noda (nodchip)
11
+
12
+ # All other authors of Stockfish code (in alphabetical order)
13
+ Aditya (absimaldata)
14
+ Adrian Petrescu (apetresc)
15
+ Ahmed Kerimov (wcdbmv)
16
+ Ajith Chandy Jose (ajithcj)
17
+ Alain Savard (Rocky640)
18
+ Alayan Feh (Alayan-stk-2)
19
+ Alexander Kure
20
+ Alexander Pagel (Lolligerhans)
21
+ Alfredo Menezes (lonfom169)
22
+ Ali AlZhrani (Cooffe)
23
+ Andreas Jan van der Meulen (Andyson007)
24
+ Andreas Matthies (Matthies)
25
+ Andrei Vetrov (proukornew)
26
+ Andrew Grant (AndyGrant)
27
+ Andrey Neporada (nepal)
28
+ Andy Duplain
29
+ Antoine Champion (antoinechampion)
30
+ Aram Tumanian (atumanian)
31
+ Arjun Temurnikar
32
+ Artem Solopiy (EntityFX)
33
+ Auguste Pop
34
+ Balazs Szilagyi
35
+ Balint Pfliegel
36
+ Ben Chaney (Chaneybenjamini)
37
+ Ben Koshy (BKSpurgeon)
38
+ Bill Henry (VoyagerOne)
39
+ Bojun Guo (noobpwnftw, Nooby)
40
+ borg323
41
+ Boštjan Mejak (PedanticHacker)
42
+ braich
43
+ Brian Sheppard (SapphireBrand, briansheppard-toast)
44
+ Bruno de Melo Costa (BM123499)
45
+ Bruno Pellanda (pellanda)
46
+ Bryan Cross (crossbr)
47
+ candirufish
48
+ Carlos Esparza Sánchez (ces42)
49
+ Chess13234
50
+ Chris Bao (sscg13)
51
+ Chris Cain (ceebo)
52
+ Ciekce
53
+ clefrks
54
+ Clemens L. (rn5f107s2)
55
+ Cody Ho (aesrentai)
56
+ Dale Weiler (graphitemaster)
57
+ Daniel Axtens (daxtens)
58
+ Daniel Dugovic (ddugovic)
59
+ Daniel Monroe (Ergodice)
60
+ Dan Schmidt (dfannius)
61
+ Dariusz Orzechowski (dorzechowski)
62
+ David (dav1312)
63
+ David Zar
64
+ Daylen Yang (daylen)
65
+ Deshawn Mohan-Smith (GoldenRare)
66
+ Dieter Dobbelaere (ddobbelaere)
67
+ DiscanX
68
+ Dominik Schlösser (domschl)
69
+ double-beep
70
+ Douglas Matos Gomes (dsmsgms)
71
+ Dubslow
72
+ Eduardo Cáceres (eduherminio)
73
+ Eelco de Groot (KingDefender)
74
+ Ehsan Rashid (erashid)
75
+ Elvin Liu (solarlight2)
76
+ erbsenzaehler
77
+ Ernesto Gatti
78
+ evqsx
79
+ Fabian Beuke (madnight)
80
+ Fabian Fichter (ianfab)
81
+ Fanael Linithien (Fanael)
82
+ fanon
83
+ Fauzi Akram Dabat (fauzi2)
84
+ Felix Wittmann
85
+ gamander
86
+ Gabriele Lombardo (gabe)
87
+ Gahtan Nahdi
88
+ Gary Heckman (gheckman)
89
+ George Sobala (gsobala)
90
+ gguliash
91
+ Giacomo Lorenzetti (G-Lorenz)
92
+ Gian-Carlo Pascutto (gcp)
93
+ Goh CJ (cj5716)
94
+ Gontran Lemaire (gonlem)
95
+ Goodkov Vasiliy Aleksandrovich (goodkov)
96
+ Gregor Cramer
97
+ GuardianRM
98
+ Guy Vreuls (gvreuls)
99
+ Günther Demetz (pb00067, pb00068)
100
+ Henri Wiechers
101
+ Hiraoka Takuya (HiraokaTakuya)
102
+ homoSapiensSapiens
103
+ Hongzhi Cheng
104
+ Ivan Ivec (IIvec)
105
+ Jacques B. (Timshel)
106
+ Jake Senne (w1wwwwww)
107
+ Jan Ondruš (hxim)
108
+ Jared Kish (Kurtbusch, kurt22i)
109
+ Jarrod Torriero (DU-jdto)
110
+ Jasper Shovelton (Beanie496)
111
+ Jean-Francois Romang (jromang)
112
+ Jean Gauthier (OuaisBla)
113
+ Jekaa
114
+ Jerry Donald Watson (jerrydonaldwatson)
115
+ jjoshua2
116
+ Jonathan Buladas Dumale (SFisGOD)
117
+ Jonathan Calovski (Mysseno)
118
+ Jonathan McDermid (jonathanmcdermid)
119
+ Joost VandeVondele (vondele)
120
+ Joseph Ellis (jhellis3)
121
+ Joseph R. Prostko
122
+ Jörg Oster (joergoster)
123
+ Julian Willemer (NightlyKing)
124
+ jundery
125
+ Justin Blanchard (UncombedCoconut)
126
+ Kelly Wilson
127
+ Ken Takusagawa
128
+ Kenneth Lee (kennethlee33)
129
+ Kian E (KJE-98)
130
+ kinderchocolate
131
+ Kiran Panditrao (Krgp)
132
+ Kojirion
133
+ Krisztián Peőcz
134
+ Krystian Kuzniarek (kuzkry)
135
+ Leonardo Ljubičić (ICCF World Champion)
136
+ Leonid Pechenik (lp--)
137
+ Li Ying (yl25946)
138
+ Liam Keegan (lkeegan)
139
+ Linmiao Xu (linrock)
140
+ Linus Arver (listx)
141
+ loco-loco
142
+ Lub van den Berg (ElbertoOne)
143
+ Luca Brivio (lucabrivio)
144
+ Lucas Braesch (lucasart)
145
+ Lyudmil Antonov (lantonov)
146
+ Maciej Żenczykowski (zenczykowski)
147
+ Malcolm Campbell (xoto10)
148
+ Mark Tenzer (31m059)
149
+ marotear
150
+ Mathias Parnaudeau (mparnaudeau)
151
+ Matt Ginsberg (mattginsberg)
152
+ Matthew Lai (matthewlai)
153
+ Matthew Sullivan (Matt14916)
154
+ Max A. (Disservin)
155
+ Maxim Masiutin (maximmasiutin)
156
+ Maxim Molchanov (Maxim)
157
+ Michael An (man)
158
+ Michael Byrne (MichaelB7)
159
+ Michael Chaly (Vizvezdenec)
160
+ Michael Stembera (mstembera)
161
+ Michael Whiteley (protonspring)
162
+ Michel Van den Bergh (vdbergh)
163
+ Miguel Lahoz (miguel-l)
164
+ Mikael Bäckman (mbootsector)
165
+ Mike Babigian (Farseer)
166
+ Mira
167
+ Miroslav Fontán (Hexik)
168
+ Moez Jellouli (MJZ1977)
169
+ Mohammed Li (tthsqe12)
170
+ Muzhen J (XInTheDark)
171
+ Nathan Rugg (nmrugg)
172
+ Nguyen Pham (nguyenpham)
173
+ Nicklas Persson (NicklasPersson)
174
+ Nick Pelling (nickpelling)
175
+ Niklas Fiekas (niklasf)
176
+ Nikolay Kostov (NikolayIT)
177
+ Norman Schmidt (FireFather)
178
+ notruck
179
+ Nour Berakdar (Nonlinear)
180
+ Ofek Shochat (OfekShochat, ghostway)
181
+ Ondrej Mosnáček (WOnder93)
182
+ Ondřej Mišina (AndrovT)
183
+ Oskar Werkelin Ahlin
184
+ Ömer Faruk Tutkun (OmerFarukTutkun)
185
+ Pablo Vazquez
186
+ Panthee
187
+ Pascal Romaret
188
+ Pasquale Pigazzini (ppigazzini)
189
+ Patrick Jansen (mibere)
190
+ Peter Schneider (pschneider1968)
191
+ Peter Zsifkovits (CoffeeOne)
192
+ PikaCat
193
+ Praveen Kumar Tummala (praveentml)
194
+ Prokop Randáček (ProkopRandacek)
195
+ Rahul Dsilva (silversolver1)
196
+ Ralph Stößer (Ralph Stoesser)
197
+ Raminder Singh
198
+ renouve
199
+ Reuven Peleg (R-Peleg)
200
+ Richard Lloyd (Richard-Lloyd)
201
+ Robert Nürnberg (robertnurnberg)
202
+ Rodrigo Exterckötter Tjäder
203
+ Rodrigo Roim (roim)
204
+ Ronald de Man (syzygy1, syzygy)
205
+ Ron Britvich (Britvich)
206
+ rqs
207
+ Rui Coelho (ruicoelhopedro)
208
+ Ryan Schmitt
209
+ Ryan Takker
210
+ Sami Kiminki (skiminki)
211
+ Sebastian Buchwald (UniQP)
212
+ Sergei Antonov (saproj)
213
+ Sergei Ivanov (svivanov72)
214
+ Sergio Vieri (sergiovieri)
215
+ sf-x
216
+ Shahin M. Shahin (peregrine)
217
+ Shane Booth (shane31)
218
+ Shawn Varghese (xXH4CKST3RXx)
219
+ Shawn Xu (xu-shawn)
220
+ Siad Daboul (Topologist)
221
+ Stefan Geschwentner (locutus2)
222
+ Stefano Cardanobile (Stefano80)
223
+ Stefano Di Martino (StefanoD)
224
+ Steinar Gunderson (sesse)
225
+ Stéphane Nicolet (snicolet)
226
+ Stephen Touset (stouset)
227
+ Syine Mineta (MinetaS)
228
+ Taras Vuk (TarasVuk)
229
+ Thanar2
230
+ thaspel
231
+ theo77186
232
+ TierynnB
233
+ Ting-Hsuan Huang (fffelix-huang)
234
+ Tobias Steinmann
235
+ Tomasz Sobczyk (Sopel97)
236
+ Tom Truscott
237
+ Tom Vijlbrief (tomtor)
238
+ Torsten Franz (torfranz, tfranzer)
239
+ Torsten Hellwig (Torom)
240
+ Tracey Emery (basepr1me)
241
+ tttak
242
+ Unai Corzo (unaiic)
243
+ Uri Blass (uriblass)
244
+ Vince Negri (cuddlestmonkey)
245
+ Viren
246
+ Wencey Wang
247
+ windfishballad
248
+ xefoci7612
249
+ Xiang Wang (KatyushaScarlet)
250
+ zz4032
251
+
252
+ # Additionally, we acknowledge the authors and maintainers of fishtest,
253
+ # an amazing and essential framework for Stockfish development!
254
+ #
255
+ # https://github.com/official-stockfish/fishtest/blob/master/AUTHORS
stockfish/CITATION.cff ADDED
@@ -0,0 +1,23 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # This CITATION.cff file was generated with cffinit.
2
+ # Visit https://bit.ly/cffinit to generate yours today!
3
+
4
+ cff-version: 1.2.0
5
+ title: Stockfish
6
+ message: >-
7
+ Please cite this software using the metadata from this
8
+ file.
9
+ type: software
10
+ authors:
11
+ - name: The Stockfish developers (see AUTHORS file)
12
+ repository-code: 'https://github.com/official-stockfish/Stockfish'
13
+ url: 'https://stockfishchess.org/'
14
+ repository-artifact: 'https://stockfishchess.org/download/'
15
+ abstract: Stockfish is a free and strong UCI chess engine.
16
+ keywords:
17
+ - chess
18
+ - artificial intelligence (AI)
19
+ - tree search
20
+ - alpha-beta search
21
+ - neural networks (NN)
22
+ - efficiently updatable neural networks (NNUE)
23
+ license: GPL-3.0
stockfish/CONTRIBUTING.md ADDED
@@ -0,0 +1,96 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Contributing to Stockfish
2
+
3
+ Welcome to the Stockfish project! We are excited that you are interested in
4
+ contributing. This document outlines the guidelines and steps to follow when
5
+ making contributions to Stockfish.
6
+
7
+ ## Table of Contents
8
+
9
+ - [Building Stockfish](#building-stockfish)
10
+ - [Making Contributions](#making-contributions)
11
+ - [Reporting Issues](#reporting-issues)
12
+ - [Submitting Pull Requests](#submitting-pull-requests)
13
+ - [Code Style](#code-style)
14
+ - [Community and Communication](#community-and-communication)
15
+ - [License](#license)
16
+
17
+ ## Building Stockfish
18
+
19
+ In case you do not have a C++ compiler installed, you can follow the
20
+ instructions from our wiki.
21
+
22
+ - [Ubuntu][ubuntu-compiling-link]
23
+ - [Windows][windows-compiling-link]
24
+ - [macOS][macos-compiling-link]
25
+
26
+ ## Making Contributions
27
+
28
+ ### Reporting Issues
29
+
30
+ If you find a bug, please open an issue on the
31
+ [issue tracker][issue-tracker-link]. Be sure to include relevant information
32
+ like your operating system, build environment, and a detailed description of the
33
+ problem.
34
+
35
+ _Please note that Stockfish's development is not focused on adding new features.
36
+ Thus any issue regarding missing features will potentially be closed without
37
+ further discussion._
38
+
39
+ ### Submitting Pull Requests
40
+
41
+ - Functional changes need to be tested on fishtest. See
42
+ [Creating my First Test][creating-my-first-test] for more details.
43
+ The accompanying pull request should include a link to the test results and
44
+ the new bench.
45
+
46
+ - Non-functional changes (e.g. refactoring, code style, documentation) do not
47
+ need to be tested on fishtest, unless they might impact performance.
48
+
49
+ - Provide a clear and concise description of the changes in the pull request
50
+ description.
51
+
52
+ _First time contributors should add their name to [AUTHORS](./AUTHORS)._
53
+
54
+ _Stockfish's development is not focused on adding new features. Thus any pull
55
+ request introducing new features will potentially be closed without further
56
+ discussion._
57
+
58
+ ## Code Style
59
+
60
+ Changes to Stockfish C++ code should respect our coding style defined by
61
+ [.clang-format](.clang-format). You can format your changes by running
62
+ `make format`. This requires clang-format version 18 to be installed on your system.
63
+
64
+ ## Navigate
65
+
66
+ For experienced Git users who frequently use git blame, it is recommended to
67
+ configure the blame.ignoreRevsFile setting.
68
+ This setting is useful for excluding noisy formatting commits.
69
+
70
+ ```bash
71
+ git config blame.ignoreRevsFile .git-blame-ignore-revs
72
+ ```
73
+
74
+ ## Community and Communication
75
+
76
+ - Join the [Stockfish discord][discord-link] to discuss ideas, issues, and
77
+ development.
78
+ - Participate in the [Stockfish GitHub discussions][discussions-link] for
79
+ broader conversations.
80
+
81
+ ## License
82
+
83
+ By contributing to Stockfish, you agree that your contributions will be licensed
84
+ under the GNU General Public License v3.0. See [Copying.txt][copying-link] for
85
+ more details.
86
+
87
+ Thank you for contributing to Stockfish and helping us make it even better!
88
+
89
+ [copying-link]: https://github.com/official-stockfish/Stockfish/blob/master/Copying.txt
90
+ [discord-link]: https://discord.gg/GWDRS3kU6R
91
+ [discussions-link]: https://github.com/official-stockfish/Stockfish/discussions/new
92
+ [creating-my-first-test]: https://github.com/official-stockfish/fishtest/wiki/Creating-my-first-test#create-your-test
93
+ [issue-tracker-link]: https://github.com/official-stockfish/Stockfish/issues
94
+ [ubuntu-compiling-link]: https://github.com/official-stockfish/Stockfish/wiki/Developers#user-content-installing-a-compiler-1
95
+ [windows-compiling-link]: https://github.com/official-stockfish/Stockfish/wiki/Developers#user-content-installing-a-compiler
96
+ [macos-compiling-link]: https://github.com/official-stockfish/Stockfish/wiki/Developers#user-content-installing-a-compiler-2
stockfish/Copying.txt ADDED
@@ -0,0 +1,674 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ GNU GENERAL PUBLIC LICENSE
2
+ Version 3, 29 June 2007
3
+
4
+ Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
5
+ Everyone is permitted to copy and distribute verbatim copies
6
+ of this license document, but changing it is not allowed.
7
+
8
+ Preamble
9
+
10
+ The GNU General Public License is a free, copyleft license for
11
+ software and other kinds of works.
12
+
13
+ The licenses for most software and other practical works are designed
14
+ to take away your freedom to share and change the works. By contrast,
15
+ the GNU General Public License is intended to guarantee your freedom to
16
+ share and change all versions of a program--to make sure it remains free
17
+ software for all its users. We, the Free Software Foundation, use the
18
+ GNU General Public License for most of our software; it applies also to
19
+ any other work released this way by its authors. You can apply it to
20
+ your programs, too.
21
+
22
+ When we speak of free software, we are referring to freedom, not
23
+ price. Our General Public Licenses are designed to make sure that you
24
+ have the freedom to distribute copies of free software (and charge for
25
+ them if you wish), that you receive source code or can get it if you
26
+ want it, that you can change the software or use pieces of it in new
27
+ free programs, and that you know you can do these things.
28
+
29
+ To protect your rights, we need to prevent others from denying you
30
+ these rights or asking you to surrender the rights. Therefore, you have
31
+ certain responsibilities if you distribute copies of the software, or if
32
+ you modify it: responsibilities to respect the freedom of others.
33
+
34
+ For example, if you distribute copies of such a program, whether
35
+ gratis or for a fee, you must pass on to the recipients the same
36
+ freedoms that you received. You must make sure that they, too, receive
37
+ or can get the source code. And you must show them these terms so they
38
+ know their rights.
39
+
40
+ Developers that use the GNU GPL protect your rights with two steps:
41
+ (1) assert copyright on the software, and (2) offer you this License
42
+ giving you legal permission to copy, distribute and/or modify it.
43
+
44
+ For the developers' and authors' protection, the GPL clearly explains
45
+ that there is no warranty for this free software. For both users' and
46
+ authors' sake, the GPL requires that modified versions be marked as
47
+ changed, so that their problems will not be attributed erroneously to
48
+ authors of previous versions.
49
+
50
+ Some devices are designed to deny users access to install or run
51
+ modified versions of the software inside them, although the manufacturer
52
+ can do so. This is fundamentally incompatible with the aim of
53
+ protecting users' freedom to change the software. The systematic
54
+ pattern of such abuse occurs in the area of products for individuals to
55
+ use, which is precisely where it is most unacceptable. Therefore, we
56
+ have designed this version of the GPL to prohibit the practice for those
57
+ products. If such problems arise substantially in other domains, we
58
+ stand ready to extend this provision to those domains in future versions
59
+ of the GPL, as needed to protect the freedom of users.
60
+
61
+ Finally, every program is threatened constantly by software patents.
62
+ States should not allow patents to restrict development and use of
63
+ software on general-purpose computers, but in those that do, we wish to
64
+ avoid the special danger that patents applied to a free program could
65
+ make it effectively proprietary. To prevent this, the GPL assures that
66
+ patents cannot be used to render the program non-free.
67
+
68
+ The precise terms and conditions for copying, distribution and
69
+ modification follow.
70
+
71
+ TERMS AND CONDITIONS
72
+
73
+ 0. Definitions.
74
+
75
+ "This License" refers to version 3 of the GNU General Public License.
76
+
77
+ "Copyright" also means copyright-like laws that apply to other kinds of
78
+ works, such as semiconductor masks.
79
+
80
+ "The Program" refers to any copyrightable work licensed under this
81
+ License. Each licensee is addressed as "you". "Licensees" and
82
+ "recipients" may be individuals or organizations.
83
+
84
+ To "modify" a work means to copy from or adapt all or part of the work
85
+ in a fashion requiring copyright permission, other than the making of an
86
+ exact copy. The resulting work is called a "modified version" of the
87
+ earlier work or a work "based on" the earlier work.
88
+
89
+ A "covered work" means either the unmodified Program or a work based
90
+ on the Program.
91
+
92
+ To "propagate" a work means to do anything with it that, without
93
+ permission, would make you directly or secondarily liable for
94
+ infringement under applicable copyright law, except executing it on a
95
+ computer or modifying a private copy. Propagation includes copying,
96
+ distribution (with or without modification), making available to the
97
+ public, and in some countries other activities as well.
98
+
99
+ To "convey" a work means any kind of propagation that enables other
100
+ parties to make or receive copies. Mere interaction with a user through
101
+ a computer network, with no transfer of a copy, is not conveying.
102
+
103
+ An interactive user interface displays "Appropriate Legal Notices"
104
+ to the extent that it includes a convenient and prominently visible
105
+ feature that (1) displays an appropriate copyright notice, and (2)
106
+ tells the user that there is no warranty for the work (except to the
107
+ extent that warranties are provided), that licensees may convey the
108
+ work under this License, and how to view a copy of this License. If
109
+ the interface presents a list of user commands or options, such as a
110
+ menu, a prominent item in the list meets this criterion.
111
+
112
+ 1. Source Code.
113
+
114
+ The "source code" for a work means the preferred form of the work
115
+ for making modifications to it. "Object code" means any non-source
116
+ form of a work.
117
+
118
+ A "Standard Interface" means an interface that either is an official
119
+ standard defined by a recognized standards body, or, in the case of
120
+ interfaces specified for a particular programming language, one that
121
+ is widely used among developers working in that language.
122
+
123
+ The "System Libraries" of an executable work include anything, other
124
+ than the work as a whole, that (a) is included in the normal form of
125
+ packaging a Major Component, but which is not part of that Major
126
+ Component, and (b) serves only to enable use of the work with that
127
+ Major Component, or to implement a Standard Interface for which an
128
+ implementation is available to the public in source code form. A
129
+ "Major Component", in this context, means a major essential component
130
+ (kernel, window system, and so on) of the specific operating system
131
+ (if any) on which the executable work runs, or a compiler used to
132
+ produce the work, or an object code interpreter used to run it.
133
+
134
+ The "Corresponding Source" for a work in object code form means all
135
+ the source code needed to generate, install, and (for an executable
136
+ work) run the object code and to modify the work, including scripts to
137
+ control those activities. However, it does not include the work's
138
+ System Libraries, or general-purpose tools or generally available free
139
+ programs which are used unmodified in performing those activities but
140
+ which are not part of the work. For example, Corresponding Source
141
+ includes interface definition files associated with source files for
142
+ the work, and the source code for shared libraries and dynamically
143
+ linked subprograms that the work is specifically designed to require,
144
+ such as by intimate data communication or control flow between those
145
+ subprograms and other parts of the work.
146
+
147
+ The Corresponding Source need not include anything that users
148
+ can regenerate automatically from other parts of the Corresponding
149
+ Source.
150
+
151
+ The Corresponding Source for a work in source code form is that
152
+ same work.
153
+
154
+ 2. Basic Permissions.
155
+
156
+ All rights granted under this License are granted for the term of
157
+ copyright on the Program, and are irrevocable provided the stated
158
+ conditions are met. This License explicitly affirms your unlimited
159
+ permission to run the unmodified Program. The output from running a
160
+ covered work is covered by this License only if the output, given its
161
+ content, constitutes a covered work. This License acknowledges your
162
+ rights of fair use or other equivalent, as provided by copyright law.
163
+
164
+ You may make, run and propagate covered works that you do not
165
+ convey, without conditions so long as your license otherwise remains
166
+ in force. You may convey covered works to others for the sole purpose
167
+ of having them make modifications exclusively for you, or provide you
168
+ with facilities for running those works, provided that you comply with
169
+ the terms of this License in conveying all material for which you do
170
+ not control copyright. Those thus making or running the covered works
171
+ for you must do so exclusively on your behalf, under your direction
172
+ and control, on terms that prohibit them from making any copies of
173
+ your copyrighted material outside their relationship with you.
174
+
175
+ Conveying under any other circumstances is permitted solely under
176
+ the conditions stated below. Sublicensing is not allowed; section 10
177
+ makes it unnecessary.
178
+
179
+ 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
180
+
181
+ No covered work shall be deemed part of an effective technological
182
+ measure under any applicable law fulfilling obligations under article
183
+ 11 of the WIPO copyright treaty adopted on 20 December 1996, or
184
+ similar laws prohibiting or restricting circumvention of such
185
+ measures.
186
+
187
+ When you convey a covered work, you waive any legal power to forbid
188
+ circumvention of technological measures to the extent such circumvention
189
+ is effected by exercising rights under this License with respect to
190
+ the covered work, and you disclaim any intention to limit operation or
191
+ modification of the work as a means of enforcing, against the work's
192
+ users, your or third parties' legal rights to forbid circumvention of
193
+ technological measures.
194
+
195
+ 4. Conveying Verbatim Copies.
196
+
197
+ You may convey verbatim copies of the Program's source code as you
198
+ receive it, in any medium, provided that you conspicuously and
199
+ appropriately publish on each copy an appropriate copyright notice;
200
+ keep intact all notices stating that this License and any
201
+ non-permissive terms added in accord with section 7 apply to the code;
202
+ keep intact all notices of the absence of any warranty; and give all
203
+ recipients a copy of this License along with the Program.
204
+
205
+ You may charge any price or no price for each copy that you convey,
206
+ and you may offer support or warranty protection for a fee.
207
+
208
+ 5. Conveying Modified Source Versions.
209
+
210
+ You may convey a work based on the Program, or the modifications to
211
+ produce it from the Program, in the form of source code under the
212
+ terms of section 4, provided that you also meet all of these conditions:
213
+
214
+ a) The work must carry prominent notices stating that you modified
215
+ it, and giving a relevant date.
216
+
217
+ b) The work must carry prominent notices stating that it is
218
+ released under this License and any conditions added under section
219
+ 7. This requirement modifies the requirement in section 4 to
220
+ "keep intact all notices".
221
+
222
+ c) You must license the entire work, as a whole, under this
223
+ License to anyone who comes into possession of a copy. This
224
+ License will therefore apply, along with any applicable section 7
225
+ additional terms, to the whole of the work, and all its parts,
226
+ regardless of how they are packaged. This License gives no
227
+ permission to license the work in any other way, but it does not
228
+ invalidate such permission if you have separately received it.
229
+
230
+ d) If the work has interactive user interfaces, each must display
231
+ Appropriate Legal Notices; however, if the Program has interactive
232
+ interfaces that do not display Appropriate Legal Notices, your
233
+ work need not make them do so.
234
+
235
+ A compilation of a covered work with other separate and independent
236
+ works, which are not by their nature extensions of the covered work,
237
+ and which are not combined with it such as to form a larger program,
238
+ in or on a volume of a storage or distribution medium, is called an
239
+ "aggregate" if the compilation and its resulting copyright are not
240
+ used to limit the access or legal rights of the compilation's users
241
+ beyond what the individual works permit. Inclusion of a covered work
242
+ in an aggregate does not cause this License to apply to the other
243
+ parts of the aggregate.
244
+
245
+ 6. Conveying Non-Source Forms.
246
+
247
+ You may convey a covered work in object code form under the terms
248
+ of sections 4 and 5, provided that you also convey the
249
+ machine-readable Corresponding Source under the terms of this License,
250
+ in one of these ways:
251
+
252
+ a) Convey the object code in, or embodied in, a physical product
253
+ (including a physical distribution medium), accompanied by the
254
+ Corresponding Source fixed on a durable physical medium
255
+ customarily used for software interchange.
256
+
257
+ b) Convey the object code in, or embodied in, a physical product
258
+ (including a physical distribution medium), accompanied by a
259
+ written offer, valid for at least three years and valid for as
260
+ long as you offer spare parts or customer support for that product
261
+ model, to give anyone who possesses the object code either (1) a
262
+ copy of the Corresponding Source for all the software in the
263
+ product that is covered by this License, on a durable physical
264
+ medium customarily used for software interchange, for a price no
265
+ more than your reasonable cost of physically performing this
266
+ conveying of source, or (2) access to copy the
267
+ Corresponding Source from a network server at no charge.
268
+
269
+ c) Convey individual copies of the object code with a copy of the
270
+ written offer to provide the Corresponding Source. This
271
+ alternative is allowed only occasionally and noncommercially, and
272
+ only if you received the object code with such an offer, in accord
273
+ with subsection 6b.
274
+
275
+ d) Convey the object code by offering access from a designated
276
+ place (gratis or for a charge), and offer equivalent access to the
277
+ Corresponding Source in the same way through the same place at no
278
+ further charge. You need not require recipients to copy the
279
+ Corresponding Source along with the object code. If the place to
280
+ copy the object code is a network server, the Corresponding Source
281
+ may be on a different server (operated by you or a third party)
282
+ that supports equivalent copying facilities, provided you maintain
283
+ clear directions next to the object code saying where to find the
284
+ Corresponding Source. Regardless of what server hosts the
285
+ Corresponding Source, you remain obligated to ensure that it is
286
+ available for as long as needed to satisfy these requirements.
287
+
288
+ e) Convey the object code using peer-to-peer transmission, provided
289
+ you inform other peers where the object code and Corresponding
290
+ Source of the work are being offered to the general public at no
291
+ charge under subsection 6d.
292
+
293
+ A separable portion of the object code, whose source code is excluded
294
+ from the Corresponding Source as a System Library, need not be
295
+ included in conveying the object code work.
296
+
297
+ A "User Product" is either (1) a "consumer product", which means any
298
+ tangible personal property which is normally used for personal, family,
299
+ or household purposes, or (2) anything designed or sold for incorporation
300
+ into a dwelling. In determining whether a product is a consumer product,
301
+ doubtful cases shall be resolved in favor of coverage. For a particular
302
+ product received by a particular user, "normally used" refers to a
303
+ typical or common use of that class of product, regardless of the status
304
+ of the particular user or of the way in which the particular user
305
+ actually uses, or expects or is expected to use, the product. A product
306
+ is a consumer product regardless of whether the product has substantial
307
+ commercial, industrial or non-consumer uses, unless such uses represent
308
+ the only significant mode of use of the product.
309
+
310
+ "Installation Information" for a User Product means any methods,
311
+ procedures, authorization keys, or other information required to install
312
+ and execute modified versions of a covered work in that User Product from
313
+ a modified version of its Corresponding Source. The information must
314
+ suffice to ensure that the continued functioning of the modified object
315
+ code is in no case prevented or interfered with solely because
316
+ modification has been made.
317
+
318
+ If you convey an object code work under this section in, or with, or
319
+ specifically for use in, a User Product, and the conveying occurs as
320
+ part of a transaction in which the right of possession and use of the
321
+ User Product is transferred to the recipient in perpetuity or for a
322
+ fixed term (regardless of how the transaction is characterized), the
323
+ Corresponding Source conveyed under this section must be accompanied
324
+ by the Installation Information. But this requirement does not apply
325
+ if neither you nor any third party retains the ability to install
326
+ modified object code on the User Product (for example, the work has
327
+ been installed in ROM).
328
+
329
+ The requirement to provide Installation Information does not include a
330
+ requirement to continue to provide support service, warranty, or updates
331
+ for a work that has been modified or installed by the recipient, or for
332
+ the User Product in which it has been modified or installed. Access to a
333
+ network may be denied when the modification itself materially and
334
+ adversely affects the operation of the network or violates the rules and
335
+ protocols for communication across the network.
336
+
337
+ Corresponding Source conveyed, and Installation Information provided,
338
+ in accord with this section must be in a format that is publicly
339
+ documented (and with an implementation available to the public in
340
+ source code form), and must require no special password or key for
341
+ unpacking, reading or copying.
342
+
343
+ 7. Additional Terms.
344
+
345
+ "Additional permissions" are terms that supplement the terms of this
346
+ License by making exceptions from one or more of its conditions.
347
+ Additional permissions that are applicable to the entire Program shall
348
+ be treated as though they were included in this License, to the extent
349
+ that they are valid under applicable law. If additional permissions
350
+ apply only to part of the Program, that part may be used separately
351
+ under those permissions, but the entire Program remains governed by
352
+ this License without regard to the additional permissions.
353
+
354
+ When you convey a copy of a covered work, you may at your option
355
+ remove any additional permissions from that copy, or from any part of
356
+ it. (Additional permissions may be written to require their own
357
+ removal in certain cases when you modify the work.) You may place
358
+ additional permissions on material, added by you to a covered work,
359
+ for which you have or can give appropriate copyright permission.
360
+
361
+ Notwithstanding any other provision of this License, for material you
362
+ add to a covered work, you may (if authorized by the copyright holders of
363
+ that material) supplement the terms of this License with terms:
364
+
365
+ a) Disclaiming warranty or limiting liability differently from the
366
+ terms of sections 15 and 16 of this License; or
367
+
368
+ b) Requiring preservation of specified reasonable legal notices or
369
+ author attributions in that material or in the Appropriate Legal
370
+ Notices displayed by works containing it; or
371
+
372
+ c) Prohibiting misrepresentation of the origin of that material, or
373
+ requiring that modified versions of such material be marked in
374
+ reasonable ways as different from the original version; or
375
+
376
+ d) Limiting the use for publicity purposes of names of licensors or
377
+ authors of the material; or
378
+
379
+ e) Declining to grant rights under trademark law for use of some
380
+ trade names, trademarks, or service marks; or
381
+
382
+ f) Requiring indemnification of licensors and authors of that
383
+ material by anyone who conveys the material (or modified versions of
384
+ it) with contractual assumptions of liability to the recipient, for
385
+ any liability that these contractual assumptions directly impose on
386
+ those licensors and authors.
387
+
388
+ All other non-permissive additional terms are considered "further
389
+ restrictions" within the meaning of section 10. If the Program as you
390
+ received it, or any part of it, contains a notice stating that it is
391
+ governed by this License along with a term that is a further
392
+ restriction, you may remove that term. If a license document contains
393
+ a further restriction but permits relicensing or conveying under this
394
+ License, you may add to a covered work material governed by the terms
395
+ of that license document, provided that the further restriction does
396
+ not survive such relicensing or conveying.
397
+
398
+ If you add terms to a covered work in accord with this section, you
399
+ must place, in the relevant source files, a statement of the
400
+ additional terms that apply to those files, or a notice indicating
401
+ where to find the applicable terms.
402
+
403
+ Additional terms, permissive or non-permissive, may be stated in the
404
+ form of a separately written license, or stated as exceptions;
405
+ the above requirements apply either way.
406
+
407
+ 8. Termination.
408
+
409
+ You may not propagate or modify a covered work except as expressly
410
+ provided under this License. Any attempt otherwise to propagate or
411
+ modify it is void, and will automatically terminate your rights under
412
+ this License (including any patent licenses granted under the third
413
+ paragraph of section 11).
414
+
415
+ However, if you cease all violation of this License, then your
416
+ license from a particular copyright holder is reinstated (a)
417
+ provisionally, unless and until the copyright holder explicitly and
418
+ finally terminates your license, and (b) permanently, if the copyright
419
+ holder fails to notify you of the violation by some reasonable means
420
+ prior to 60 days after the cessation.
421
+
422
+ Moreover, your license from a particular copyright holder is
423
+ reinstated permanently if the copyright holder notifies you of the
424
+ violation by some reasonable means, this is the first time you have
425
+ received notice of violation of this License (for any work) from that
426
+ copyright holder, and you cure the violation prior to 30 days after
427
+ your receipt of the notice.
428
+
429
+ Termination of your rights under this section does not terminate the
430
+ licenses of parties who have received copies or rights from you under
431
+ this License. If your rights have been terminated and not permanently
432
+ reinstated, you do not qualify to receive new licenses for the same
433
+ material under section 10.
434
+
435
+ 9. Acceptance Not Required for Having Copies.
436
+
437
+ You are not required to accept this License in order to receive or
438
+ run a copy of the Program. Ancillary propagation of a covered work
439
+ occurring solely as a consequence of using peer-to-peer transmission
440
+ to receive a copy likewise does not require acceptance. However,
441
+ nothing other than this License grants you permission to propagate or
442
+ modify any covered work. These actions infringe copyright if you do
443
+ not accept this License. Therefore, by modifying or propagating a
444
+ covered work, you indicate your acceptance of this License to do so.
445
+
446
+ 10. Automatic Licensing of Downstream Recipients.
447
+
448
+ Each time you convey a covered work, the recipient automatically
449
+ receives a license from the original licensors, to run, modify and
450
+ propagate that work, subject to this License. You are not responsible
451
+ for enforcing compliance by third parties with this License.
452
+
453
+ An "entity transaction" is a transaction transferring control of an
454
+ organization, or substantially all assets of one, or subdividing an
455
+ organization, or merging organizations. If propagation of a covered
456
+ work results from an entity transaction, each party to that
457
+ transaction who receives a copy of the work also receives whatever
458
+ licenses to the work the party's predecessor in interest had or could
459
+ give under the previous paragraph, plus a right to possession of the
460
+ Corresponding Source of the work from the predecessor in interest, if
461
+ the predecessor has it or can get it with reasonable efforts.
462
+
463
+ You may not impose any further restrictions on the exercise of the
464
+ rights granted or affirmed under this License. For example, you may
465
+ not impose a license fee, royalty, or other charge for exercise of
466
+ rights granted under this License, and you may not initiate litigation
467
+ (including a cross-claim or counterclaim in a lawsuit) alleging that
468
+ any patent claim is infringed by making, using, selling, offering for
469
+ sale, or importing the Program or any portion of it.
470
+
471
+ 11. Patents.
472
+
473
+ A "contributor" is a copyright holder who authorizes use under this
474
+ License of the Program or a work on which the Program is based. The
475
+ work thus licensed is called the contributor's "contributor version".
476
+
477
+ A contributor's "essential patent claims" are all patent claims
478
+ owned or controlled by the contributor, whether already acquired or
479
+ hereafter acquired, that would be infringed by some manner, permitted
480
+ by this License, of making, using, or selling its contributor version,
481
+ but do not include claims that would be infringed only as a
482
+ consequence of further modification of the contributor version. For
483
+ purposes of this definition, "control" includes the right to grant
484
+ patent sublicenses in a manner consistent with the requirements of
485
+ this License.
486
+
487
+ Each contributor grants you a non-exclusive, worldwide, royalty-free
488
+ patent license under the contributor's essential patent claims, to
489
+ make, use, sell, offer for sale, import and otherwise run, modify and
490
+ propagate the contents of its contributor version.
491
+
492
+ In the following three paragraphs, a "patent license" is any express
493
+ agreement or commitment, however denominated, not to enforce a patent
494
+ (such as an express permission to practice a patent or covenant not to
495
+ sue for patent infringement). To "grant" such a patent license to a
496
+ party means to make such an agreement or commitment not to enforce a
497
+ patent against the party.
498
+
499
+ If you convey a covered work, knowingly relying on a patent license,
500
+ and the Corresponding Source of the work is not available for anyone
501
+ to copy, free of charge and under the terms of this License, through a
502
+ publicly available network server or other readily accessible means,
503
+ then you must either (1) cause the Corresponding Source to be so
504
+ available, or (2) arrange to deprive yourself of the benefit of the
505
+ patent license for this particular work, or (3) arrange, in a manner
506
+ consistent with the requirements of this License, to extend the patent
507
+ license to downstream recipients. "Knowingly relying" means you have
508
+ actual knowledge that, but for the patent license, your conveying the
509
+ covered work in a country, or your recipient's use of the covered work
510
+ in a country, would infringe one or more identifiable patents in that
511
+ country that you have reason to believe are valid.
512
+
513
+ If, pursuant to or in connection with a single transaction or
514
+ arrangement, you convey, or propagate by procuring conveyance of, a
515
+ covered work, and grant a patent license to some of the parties
516
+ receiving the covered work authorizing them to use, propagate, modify
517
+ or convey a specific copy of the covered work, then the patent license
518
+ you grant is automatically extended to all recipients of the covered
519
+ work and works based on it.
520
+
521
+ A patent license is "discriminatory" if it does not include within
522
+ the scope of its coverage, prohibits the exercise of, or is
523
+ conditioned on the non-exercise of one or more of the rights that are
524
+ specifically granted under this License. You may not convey a covered
525
+ work if you are a party to an arrangement with a third party that is
526
+ in the business of distributing software, under which you make payment
527
+ to the third party based on the extent of your activity of conveying
528
+ the work, and under which the third party grants, to any of the
529
+ parties who would receive the covered work from you, a discriminatory
530
+ patent license (a) in connection with copies of the covered work
531
+ conveyed by you (or copies made from those copies), or (b) primarily
532
+ for and in connection with specific products or compilations that
533
+ contain the covered work, unless you entered into that arrangement,
534
+ or that patent license was granted, prior to 28 March 2007.
535
+
536
+ Nothing in this License shall be construed as excluding or limiting
537
+ any implied license or other defenses to infringement that may
538
+ otherwise be available to you under applicable patent law.
539
+
540
+ 12. No Surrender of Others' Freedom.
541
+
542
+ If conditions are imposed on you (whether by court order, agreement or
543
+ otherwise) that contradict the conditions of this License, they do not
544
+ excuse you from the conditions of this License. If you cannot convey a
545
+ covered work so as to satisfy simultaneously your obligations under this
546
+ License and any other pertinent obligations, then as a consequence you may
547
+ not convey it at all. For example, if you agree to terms that obligate you
548
+ to collect a royalty for further conveying from those to whom you convey
549
+ the Program, the only way you could satisfy both those terms and this
550
+ License would be to refrain entirely from conveying the Program.
551
+
552
+ 13. Use with the GNU Affero General Public License.
553
+
554
+ Notwithstanding any other provision of this License, you have
555
+ permission to link or combine any covered work with a work licensed
556
+ under version 3 of the GNU Affero General Public License into a single
557
+ combined work, and to convey the resulting work. The terms of this
558
+ License will continue to apply to the part which is the covered work,
559
+ but the special requirements of the GNU Affero General Public License,
560
+ section 13, concerning interaction through a network will apply to the
561
+ combination as such.
562
+
563
+ 14. Revised Versions of this License.
564
+
565
+ The Free Software Foundation may publish revised and/or new versions of
566
+ the GNU General Public License from time to time. Such new versions will
567
+ be similar in spirit to the present version, but may differ in detail to
568
+ address new problems or concerns.
569
+
570
+ Each version is given a distinguishing version number. If the
571
+ Program specifies that a certain numbered version of the GNU General
572
+ Public License "or any later version" applies to it, you have the
573
+ option of following the terms and conditions either of that numbered
574
+ version or of any later version published by the Free Software
575
+ Foundation. If the Program does not specify a version number of the
576
+ GNU General Public License, you may choose any version ever published
577
+ by the Free Software Foundation.
578
+
579
+ If the Program specifies that a proxy can decide which future
580
+ versions of the GNU General Public License can be used, that proxy's
581
+ public statement of acceptance of a version permanently authorizes you
582
+ to choose that version for the Program.
583
+
584
+ Later license versions may give you additional or different
585
+ permissions. However, no additional obligations are imposed on any
586
+ author or copyright holder as a result of your choosing to follow a
587
+ later version.
588
+
589
+ 15. Disclaimer of Warranty.
590
+
591
+ THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
592
+ APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
593
+ HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
594
+ OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
595
+ THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
596
+ PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
597
+ IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
598
+ ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
599
+
600
+ 16. Limitation of Liability.
601
+
602
+ IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
603
+ WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
604
+ THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
605
+ GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
606
+ USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
607
+ DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
608
+ PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
609
+ EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
610
+ SUCH DAMAGES.
611
+
612
+ 17. Interpretation of Sections 15 and 16.
613
+
614
+ If the disclaimer of warranty and limitation of liability provided
615
+ above cannot be given local legal effect according to their terms,
616
+ reviewing courts shall apply local law that most closely approximates
617
+ an absolute waiver of all civil liability in connection with the
618
+ Program, unless a warranty or assumption of liability accompanies a
619
+ copy of the Program in return for a fee.
620
+
621
+ END OF TERMS AND CONDITIONS
622
+
623
+ How to Apply These Terms to Your New Programs
624
+
625
+ If you develop a new program, and you want it to be of the greatest
626
+ possible use to the public, the best way to achieve this is to make it
627
+ free software which everyone can redistribute and change under these terms.
628
+
629
+ To do so, attach the following notices to the program. It is safest
630
+ to attach them to the start of each source file to most effectively
631
+ state the exclusion of warranty; and each file should have at least
632
+ the "copyright" line and a pointer to where the full notice is found.
633
+
634
+ <one line to give the program's name and a brief idea of what it does.>
635
+ Copyright (C) <year> <name of author>
636
+
637
+ This program is free software: you can redistribute it and/or modify
638
+ it under the terms of the GNU General Public License as published by
639
+ the Free Software Foundation, either version 3 of the License, or
640
+ (at your option) any later version.
641
+
642
+ This program is distributed in the hope that it will be useful,
643
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
644
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
645
+ GNU General Public License for more details.
646
+
647
+ You should have received a copy of the GNU General Public License
648
+ along with this program. If not, see <https://www.gnu.org/licenses/>.
649
+
650
+ Also add information on how to contact you by electronic and paper mail.
651
+
652
+ If the program does terminal interaction, make it output a short
653
+ notice like this when it starts in an interactive mode:
654
+
655
+ <program> Copyright (C) <year> <name of author>
656
+ This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
657
+ This is free software, and you are welcome to redistribute it
658
+ under certain conditions; type `show c' for details.
659
+
660
+ The hypothetical commands `show w' and `show c' should show the appropriate
661
+ parts of the General Public License. Of course, your program's commands
662
+ might be different; for a GUI interface, you would use an "about box".
663
+
664
+ You should also get your employer (if you work as a programmer) or school,
665
+ if any, to sign a "copyright disclaimer" for the program, if necessary.
666
+ For more information on this, and how to apply and follow the GNU GPL, see
667
+ <https://www.gnu.org/licenses/>.
668
+
669
+ The GNU General Public License does not permit incorporating your program
670
+ into proprietary programs. If your program is a subroutine library, you
671
+ may consider it more useful to permit linking proprietary applications with
672
+ the library. If this is what you want to do, use the GNU Lesser General
673
+ Public License instead of this License. But first, please read
674
+ <https://www.gnu.org/licenses/why-not-lgpl.html>.
stockfish/README.md ADDED
@@ -0,0 +1,161 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <div align="center">
2
+
3
+ [![Stockfish][stockfish128-logo]][website-link]
4
+
5
+ <h3>Stockfish</h3>
6
+
7
+ A free and strong UCI chess engine.
8
+ <br>
9
+ <strong>[Explore Stockfish docs »][wiki-link]</strong>
10
+ <br>
11
+ <br>
12
+ [Report bug][issue-link]
13
+ ·
14
+ [Open a discussion][discussions-link]
15
+ ·
16
+ [Discord][discord-link]
17
+ ·
18
+ [Blog][website-blog-link]
19
+
20
+ [![Build][build-badge]][build-link]
21
+ [![License][license-badge]][license-link]
22
+ <br>
23
+ [![Release][release-badge]][release-link]
24
+ [![Commits][commits-badge]][commits-link]
25
+ <br>
26
+ [![Website][website-badge]][website-link]
27
+ [![Fishtest][fishtest-badge]][fishtest-link]
28
+ [![Discord][discord-badge]][discord-link]
29
+
30
+ </div>
31
+
32
+ ## Overview
33
+
34
+ [Stockfish][website-link] is a **free and strong UCI chess engine** derived from
35
+ Glaurung 2.1 that analyzes chess positions and computes the optimal moves.
36
+
37
+ Stockfish **does not include a graphical user interface** (GUI) that is required
38
+ to display a chessboard and to make it easy to input moves. These GUIs are
39
+ developed independently from Stockfish and are available online. **Read the
40
+ documentation for your GUI** of choice for information about how to use
41
+ Stockfish with it.
42
+
43
+ See also the Stockfish [documentation][wiki-usage-link] for further usage help.
44
+
45
+ ## Files
46
+
47
+ This distribution of Stockfish consists of the following files:
48
+
49
+ * [README.md][readme-link], the file you are currently reading.
50
+
51
+ * [Copying.txt][license-link], a text file containing the GNU General Public
52
+ License version 3.
53
+
54
+ * [AUTHORS][authors-link], a text file with the list of authors for the project.
55
+
56
+ * [src][src-link], a subdirectory containing the full source code, including a
57
+ Makefile that can be used to compile Stockfish on Unix-like systems.
58
+
59
+ * a file with the .nnue extension, storing the neural network for the NNUE
60
+ evaluation. Binary distributions will have this file embedded.
61
+
62
+ ## Contributing
63
+
64
+ __See [Contributing Guide](CONTRIBUTING.md).__
65
+
66
+ ### Donating hardware
67
+
68
+ Improving Stockfish requires a massive amount of testing. You can donate your
69
+ hardware resources by installing the [Fishtest Worker][worker-link] and viewing
70
+ the current tests on [Fishtest][fishtest-link].
71
+
72
+ ### Improving the code
73
+
74
+ In the [chessprogramming wiki][programming-link], many techniques used in
75
+ Stockfish are explained with a lot of background information.
76
+ The [section on Stockfish][programmingsf-link] describes many features
77
+ and techniques used by Stockfish. However, it is generic rather than
78
+ focused on Stockfish's precise implementation.
79
+
80
+ The engine testing is done on [Fishtest][fishtest-link].
81
+ If you want to help improve Stockfish, please read this [guideline][guideline-link]
82
+ first, where the basics of Stockfish development are explained.
83
+
84
+ Discussions about Stockfish take place these days mainly in the Stockfish
85
+ [Discord server][discord-link]. This is also the best place to ask questions
86
+ about the codebase and how to improve it.
87
+
88
+ ## Compiling Stockfish
89
+
90
+ Stockfish has support for 32 or 64-bit CPUs, certain hardware instructions,
91
+ big-endian machines such as Power PC, and other platforms.
92
+
93
+ On Unix-like systems, it should be easy to compile Stockfish directly from the
94
+ source code with the included Makefile in the folder `src`. In general, it is
95
+ recommended to run `make help` to see a list of make targets with corresponding
96
+ descriptions. An example suitable for most Intel and AMD chips:
97
+
98
+ ```
99
+ cd src
100
+ make -j profile-build
101
+ ```
102
+
103
+ Detailed compilation instructions for all platforms can be found in our
104
+ [documentation][wiki-compile-link]. Our wiki also has information about
105
+ the [UCI commands][wiki-uci-link] supported by Stockfish.
106
+
107
+ ## Terms of use
108
+
109
+ Stockfish is free and distributed under the
110
+ [**GNU General Public License version 3**][license-link] (GPL v3). Essentially,
111
+ this means you are free to do almost exactly what you want with the program,
112
+ including distributing it among your friends, making it available for download
113
+ from your website, selling it (either by itself or as part of some bigger
114
+ software package), or using it as the starting point for a software project of
115
+ your own.
116
+
117
+ The only real limitation is that whenever you distribute Stockfish in some way,
118
+ you MUST always include the license and the full source code (or a pointer to
119
+ where the source code can be found) to generate the exact binary you are
120
+ distributing. If you make any changes to the source code, these changes must
121
+ also be made available under GPL v3.
122
+
123
+ ## Acknowledgements
124
+
125
+ Stockfish uses neural networks trained on [data provided by the Leela Chess Zero
126
+ project][lc0-data-link], which is made available under the [Open Database License][odbl-link] (ODbL).
127
+
128
+
129
+ [authors-link]: https://github.com/official-stockfish/Stockfish/blob/master/AUTHORS
130
+ [build-link]: https://github.com/official-stockfish/Stockfish/actions/workflows/stockfish.yml
131
+ [commits-link]: https://github.com/official-stockfish/Stockfish/commits/master
132
+ [discord-link]: https://discord.gg/GWDRS3kU6R
133
+ [issue-link]: https://github.com/official-stockfish/Stockfish/issues/new?assignees=&labels=&template=BUG-REPORT.yml
134
+ [discussions-link]: https://github.com/official-stockfish/Stockfish/discussions/new
135
+ [fishtest-link]: https://tests.stockfishchess.org/tests
136
+ [guideline-link]: https://github.com/official-stockfish/fishtest/wiki/Creating-my-first-test
137
+ [license-link]: https://github.com/official-stockfish/Stockfish/blob/master/Copying.txt
138
+ [programming-link]: https://www.chessprogramming.org/Main_Page
139
+ [programmingsf-link]: https://www.chessprogramming.org/Stockfish
140
+ [readme-link]: https://github.com/official-stockfish/Stockfish/blob/master/README.md
141
+ [release-link]: https://github.com/official-stockfish/Stockfish/releases/latest
142
+ [src-link]: https://github.com/official-stockfish/Stockfish/tree/master/src
143
+ [stockfish128-logo]: https://stockfishchess.org/images/logo/icon_128x128.png
144
+ [uci-link]: https://backscattering.de/chess/uci/
145
+ [website-link]: https://stockfishchess.org
146
+ [website-blog-link]: https://stockfishchess.org/blog/
147
+ [wiki-link]: https://github.com/official-stockfish/Stockfish/wiki
148
+ [wiki-compile-link]: https://github.com/official-stockfish/Stockfish/wiki/Compiling-from-source
149
+ [wiki-uci-link]: https://github.com/official-stockfish/Stockfish/wiki/UCI-&-Commands
150
+ [wiki-usage-link]: https://github.com/official-stockfish/Stockfish/wiki/Download-and-usage
151
+ [worker-link]: https://github.com/official-stockfish/fishtest/wiki/Running-the-worker
152
+ [lc0-data-link]: https://storage.lczero.org/files/training_data
153
+ [odbl-link]: https://opendatacommons.org/licenses/odbl/odbl-10.txt
154
+
155
+ [build-badge]: https://img.shields.io/github/actions/workflow/status/official-stockfish/Stockfish/stockfish.yml?branch=master&style=for-the-badge&label=stockfish&logo=github
156
+ [commits-badge]: https://img.shields.io/github/commits-since/official-stockfish/Stockfish/latest?style=for-the-badge
157
+ [discord-badge]: https://img.shields.io/discord/435943710472011776?style=for-the-badge&label=discord&logo=Discord
158
+ [fishtest-badge]: https://img.shields.io/website?style=for-the-badge&down_color=red&down_message=Offline&label=Fishtest&up_color=success&up_message=Online&url=https%3A%2F%2Ftests.stockfishchess.org%2Ftests%2Ffinished
159
+ [license-badge]: https://img.shields.io/github/license/official-stockfish/Stockfish?style=for-the-badge&label=license&color=success
160
+ [release-badge]: https://img.shields.io/github/v/release/official-stockfish/Stockfish?style=for-the-badge&label=official%20release
161
+ [website-badge]: https://img.shields.io/website?style=for-the-badge&down_color=red&down_message=Offline&label=website&up_color=success&up_message=Online&url=https%3A%2F%2Fstockfishchess.org
stockfish/Top CPU Contributors.txt ADDED
@@ -0,0 +1,322 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Contributors to Fishtest with >10,000 CPU hours, as of 2025-03-22.
2
+ Thank you!
3
+
4
+ Username CPU Hours Games played
5
+ ------------------------------------------------------------------
6
+ noobpwnftw 41712226 3294628533
7
+ vdv 28993864 954145232
8
+ technologov 24984442 1115931964
9
+ linrock 11463033 741692823
10
+ mlang 3026000 200065824
11
+ okrout 2726068 248285678
12
+ olafm 2420096 161297116
13
+ pemo 1838361 62294199
14
+ TueRens 1804847 80170868
15
+ dew 1689162 100033738
16
+ sebastronomy 1655637 67294942
17
+ grandphish2 1474752 92156319
18
+ JojoM 1130625 73666098
19
+ rpngn 973590 59996557
20
+ oz 921203 60370346
21
+ tvijlbrief 796125 51897690
22
+ gvreuls 792215 55184194
23
+ mibere 703840 46867607
24
+ leszek 599745 44681421
25
+ cw 519602 34988289
26
+ fastgm 503862 30260818
27
+ CSU_Dynasty 474794 31654170
28
+ maximmasiutin 441753 28129452
29
+ robal 437950 28869118
30
+ ctoks 435150 28542141
31
+ crunchy 427414 27371625
32
+ bcross 415724 29061187
33
+ mgrabiak 380202 27586936
34
+ velislav 342588 22140902
35
+ ncfish1 329039 20624527
36
+ Fisherman 327231 21829379
37
+ Sylvain27 317021 11494912
38
+ marrco 310446 19587107
39
+ Dantist 296386 18031762
40
+ Fifis 289595 14969251
41
+ tolkki963 286043 23596996
42
+ Calis007 272677 17281620
43
+ cody 258835 13301710
44
+ nordlandia 249322 16420192
45
+ javran 212141 16507618
46
+ glinscott 208125 13277240
47
+ drabel 204167 13930674
48
+ mhoram 202894 12601997
49
+ bking_US 198894 11876016
50
+ Wencey 198537 9606420
51
+ Thanar 179852 12365359
52
+ sschnee 170521 10891112
53
+ armo9494 168141 11177514
54
+ DesolatedDodo 160605 10392474
55
+ spams 157128 10319326
56
+ maposora 155839 13963260
57
+ sqrt2 147963 9724586
58
+ vdbergh 140514 9242985
59
+ jcAEie 140086 10603658
60
+ CoffeeOne 137100 5024116
61
+ malala 136182 8002293
62
+ Goatminola 134893 11640524
63
+ xoto 133759 9159372
64
+ markkulix 132104 11000548
65
+ naclosagc 131472 4660806
66
+ Dubslow 129685 8527664
67
+ davar 129023 8376525
68
+ DMBK 122960 8980062
69
+ dsmith 122059 7570238
70
+ Wolfgang 120919 8619168
71
+ CypressChess 120902 8683904
72
+ amicic 119661 7938029
73
+ cuistot 116864 7828864
74
+ sterni1971 113754 6054022
75
+ Data 113305 8220352
76
+ BrunoBanani 112960 7436849
77
+ megaman7de 109139 7360928
78
+ skiminki 107583 7218170
79
+ zeryl 104523 6618969
80
+ MaZePallas 102823 6633619
81
+ sunu 100167 7040199
82
+ thirdlife 99178 2246544
83
+ ElbertoOne 99028 7023771
84
+ TataneSan 97257 4239502
85
+ romangol 95662 7784954
86
+ bigpen0r 94825 6529241
87
+ brabos 92118 6186135
88
+ Maxim 90818 3283364
89
+ psk 89957 5984901
90
+ szupaw 89775 7800606
91
+ jromang 87260 5988073
92
+ racerschmacer 85805 6122790
93
+ Vizvezdenec 83761 5344740
94
+ 0x3C33 82614 5271253
95
+ Spprtr 82103 5663635
96
+ BRAVONE 81239 5054681
97
+ MarcusTullius 78930 5189659
98
+ Mineta 78731 4947996
99
+ Torom 77978 2651656
100
+ nssy 76497 5259388
101
+ woutboat 76379 6031688
102
+ teddybaer 75125 5407666
103
+ Pking_cda 73776 5293873
104
+ Viren6 73664 1356502
105
+ yurikvelo 73611 5046822
106
+ Bobo1239 70579 4794999
107
+ solarlight 70517 5028306
108
+ dv8silencer 70287 3883992
109
+ manap 66273 4121774
110
+ tinker 64333 4268790
111
+ qurashee 61208 3429862
112
+ DanielMiao1 60181 1317252
113
+ AGI 58316 4336328
114
+ jojo2357 57435 4944212
115
+ robnjr 57262 4053117
116
+ Freja 56938 3733019
117
+ MaxKlaxxMiner 56879 3423958
118
+ ttruscott 56010 3680085
119
+ rkl 55132 4164467
120
+ jmdana 54988 4041917
121
+ notchris 53936 4184018
122
+ renouve 53811 3501516
123
+ CounterFlow 52536 3203740
124
+ finfish 51360 3370515
125
+ eva42 51272 3599691
126
+ eastorwest 51117 3454811
127
+ rap 49985 3219146
128
+ pb00067 49733 3298934
129
+ GPUex 48686 3684998
130
+ OuaisBla 48626 3445134
131
+ ronaldjerum 47654 3240695
132
+ biffhero 46564 3111352
133
+ oryx 46141 3583236
134
+ jibarbosa 45890 4541218
135
+ DeepnessFulled 45734 3944282
136
+ abdicj 45577 2631772
137
+ VoyagerOne 45476 3452465
138
+ mecevdimitar 44240 2584396
139
+ speedycpu 43842 3003273
140
+ jbwiebe 43305 2805433
141
+ gopeto 43046 2821514
142
+ YvesKn 42628 2177630
143
+ Antihistamine 41788 2761312
144
+ mhunt 41735 2691355
145
+ somethingintheshadows 41502 3330418
146
+ homyur 39893 2850481
147
+ gri 39871 2515779
148
+ vidar808 39774 1656372
149
+ Garf 37741 2999686
150
+ SC 37299 2731694
151
+ Gaster319 37229 3289674
152
+ csnodgrass 36207 2688994
153
+ ZacHFX 35528 2486328
154
+ icewulf 34782 2415146
155
+ strelock 34716 2074055
156
+ EthanOConnor 33370 2090311
157
+ slakovv 32915 2021889
158
+ shawnxu 32144 2814668
159
+ Gelma 31771 1551204
160
+ srowen 31181 1732120
161
+ kdave 31157 2198362
162
+ manapbk 30987 1810399
163
+ votoanthuan 30691 2460856
164
+ Prcuvu 30377 2170122
165
+ anst 30301 2190091
166
+ jkiiski 30136 1904470
167
+ spcc 29925 1901692
168
+ hyperbolic.tom 29840 2017394
169
+ chuckstablers 29659 2093438
170
+ Pyafue 29650 1902349
171
+ WoodMan777 29300 2579864
172
+ belzedar94 28846 1811530
173
+ chriswk 26902 1868317
174
+ xwziegtm 26897 2124586
175
+ Jopo12321 26818 1816482
176
+ achambord 26582 1767323
177
+ Patrick_G 26276 1801617
178
+ yorkman 26193 1992080
179
+ Ulysses 25517 1711634
180
+ SFTUser 25182 1675689
181
+ nabildanial 25068 1531665
182
+ Sharaf_DG 24765 1786697
183
+ rodneyc 24376 1416402
184
+ jsys14 24297 1721230
185
+ AndreasKrug 24235 1934711
186
+ agg177 23890 1395014
187
+ Ente 23752 1678188
188
+ JanErik 23408 1703875
189
+ Isidor 23388 1680691
190
+ Norabor 23371 1603244
191
+ Nullvalue 23155 2022752
192
+ fishtester 23115 1581502
193
+ wizardassassin 23073 1789536
194
+ Skiff84 22984 1053680
195
+ cisco2015 22920 1763301
196
+ ols 22914 1322047
197
+ Hjax 22561 1566151
198
+ Zirie 22542 1472937
199
+ team-oh 22272 1636708
200
+ mkstockfishtester 22253 2029566
201
+ Roady 22220 1465606
202
+ MazeOfGalious 21978 1629593
203
+ sg4032 21950 1643373
204
+ tsim67 21939 1343944
205
+ ianh2105 21725 1632562
206
+ Serpensin 21704 1809188
207
+ xor12 21628 1680365
208
+ dex 21612 1467203
209
+ nesoneg 21494 1463031
210
+ IslandLambda 21468 1239756
211
+ user213718 21454 1404128
212
+ sphinx 21211 1384728
213
+ qoo_charly_cai 21136 1514927
214
+ jjoshua2 21001 1423089
215
+ Zake9298 20938 1565848
216
+ horst.prack 20878 1465656
217
+ 0xB00B1ES 20590 1208666
218
+ Dinde 20459 1292774
219
+ t3hf1sht3ster 20456 670646
220
+ j3corre 20405 941444
221
+ 0x539 20332 1039516
222
+ Adrian.Schmidt123 20316 1281436
223
+ malfoy 20313 1350694
224
+ purpletree 20019 1461026
225
+ wei 19973 1745989
226
+ teenychess 19819 1762006
227
+ rstoesser 19569 1293588
228
+ eudhan 19274 1283717
229
+ nalanzeyu 19211 396674
230
+ vulcan 18871 1729392
231
+ Karpovbot 18766 1053178
232
+ jundery 18445 1115855
233
+ Farseer 18281 1074642
234
+ sebv15 18267 1262588
235
+ whelanh 17887 347974
236
+ ville 17883 1384026
237
+ chris 17698 1487385
238
+ purplefishies 17595 1092533
239
+ dju 17414 981289
240
+ iisiraider 17275 1049015
241
+ Karby 17177 1030688
242
+ DragonLord 17014 1162790
243
+ pirt 16991 1274215
244
+ redstone59 16842 1461780
245
+ Alb11747 16787 1213990
246
+ Naven94 16414 951718
247
+ scuzzi 16155 995347
248
+ IgorLeMasson 16064 1147232
249
+ ako027ako 15671 1173203
250
+ xuhdev 15516 1528278
251
+ infinigon 15285 965966
252
+ Nikolay.IT 15154 1068349
253
+ Andrew Grant 15114 895539
254
+ OssumOpossum 14857 1007129
255
+ LunaticBFF57 14525 1190310
256
+ enedene 14476 905279
257
+ YELNAMRON 14475 1141330
258
+ RickGroszkiewicz 14272 1385984
259
+ joendter 14269 982014
260
+ bpfliegel 14233 882523
261
+ mpx86 14019 759568
262
+ jpulman 13982 870599
263
+ getraideBFF 13871 1172846
264
+ crocogoat 13817 1119086
265
+ Nesa92 13806 1116101
266
+ joster 13710 946160
267
+ mbeier 13650 1044928
268
+ Pablohn26 13552 1088532
269
+ wxt9861 13550 1312306
270
+ Dark_wizzie 13422 1007152
271
+ Rudolphous 13244 883140
272
+ Jackfish 13177 894206
273
+ MooTheCow 13091 892304
274
+ Machariel 13010 863104
275
+ mabichito 12903 749391
276
+ thijsk 12886 722107
277
+ AdrianSA 12860 804972
278
+ Flopzee 12698 894821
279
+ szczur90 12684 977536
280
+ Kyrega 12661 456438
281
+ mschmidt 12644 863193
282
+ korposzczur 12606 838168
283
+ fatmurphy 12547 853210
284
+ Oakwen 12532 855759
285
+ SapphireBrand 12416 969604
286
+ deflectooor 12386 579392
287
+ modolief 12386 896470
288
+ ckaz 12273 754644
289
+ Hongildong 12201 648712
290
+ pgontarz 12151 848794
291
+ dbernier 12103 860824
292
+ FormazChar 12051 913497
293
+ shreven 12044 884734
294
+ rensonthemove 11999 971993
295
+ stocky 11954 699440
296
+ 3cho 11842 1036786
297
+ ImperiumAeternum 11482 979142
298
+ infinity 11470 727027
299
+ aga 11412 695127
300
+ Def9Infinity 11408 700682
301
+ torbjo 11395 729145
302
+ Thomas A. Anderson 11372 732094
303
+ savage84 11358 670860
304
+ d64 11263 789184
305
+ ali-al-zhrani 11245 779246
306
+ vaskoul 11144 953906
307
+ snicolet 11106 869170
308
+ dapper 11032 771402
309
+ Ethnikoi 10993 945906
310
+ Snuuka 10938 435504
311
+ Karmatron 10871 678306
312
+ gerbil 10871 1005842
313
+ OliverClarke 10696 942654
314
+ basepi 10637 744851
315
+ michaelrpg 10624 748179
316
+ Cubox 10621 826448
317
+ dragon123118 10421 936506
318
+ OIVAS7572 10420 995586
319
+ GBx3TV 10388 339952
320
+ Garruk 10365 706465
321
+ dzjp 10343 732529
322
+ borinot 10026 902130
stockfish/scripts/get_native_properties.sh ADDED
@@ -0,0 +1,153 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/bin/sh
2
+
3
+ #
4
+ # Returns properties of the native system.
5
+ # best architecture as supported by the CPU
6
+ # filename of the best binary uploaded as an artifact during CI
7
+ #
8
+
9
+ # Check if all the given flags are present in the CPU flags list
10
+ check_flags() {
11
+ for flag; do
12
+ printf '%s\n' "$flags" | grep -q -w "$flag" || return 1
13
+ done
14
+ }
15
+
16
+ # Set the CPU flags list
17
+ # remove underscores and points from flags, e.g. gcc uses avx512vnni, while some cpuinfo can have avx512_vnni, some systems use sse4_1 others sse4.1
18
+ get_flags() {
19
+ flags=$(awk '/^flags[ \t]*:|^Features[ \t]*:/{gsub(/^flags[ \t]*:[ \t]*|^Features[ \t]*:[ \t]*|[_.]/, ""); line=$0} END{print line}' /proc/cpuinfo)
20
+ }
21
+
22
+ # Check for gcc march "znver1" or "znver2" https://en.wikichip.org/wiki/amd/cpuid
23
+ check_znver_1_2() {
24
+ vendor_id=$(awk '/^vendor_id/{print $3; exit}' /proc/cpuinfo)
25
+ cpu_family=$(awk '/^cpu family/{print $4; exit}' /proc/cpuinfo)
26
+ [ "$vendor_id" = "AuthenticAMD" ] && [ "$cpu_family" = "23" ] && znver_1_2=true
27
+ }
28
+
29
+ # Set the file CPU loongarch64 architecture
30
+ set_arch_loongarch64() {
31
+ if check_flags 'lasx'; then
32
+ true_arch='loongarch64-lasx'
33
+ elif check_flags 'lsx'; then
34
+ true_arch='lonngarch64-lsx'
35
+ else
36
+ true_arch='loongarch64'
37
+ fi
38
+ }
39
+
40
+ # Set the file CPU x86_64 architecture
41
+ set_arch_x86_64() {
42
+ if check_flags 'avx512vnni' 'avx512dq' 'avx512f' 'avx512bw' 'avx512vl'; then
43
+ true_arch='x86-64-vnni256'
44
+ elif check_flags 'avx512f' 'avx512bw'; then
45
+ true_arch='x86-64-avx512'
46
+ elif [ -z "${znver_1_2+1}" ] && check_flags 'bmi2'; then
47
+ true_arch='x86-64-bmi2'
48
+ elif check_flags 'avx2'; then
49
+ true_arch='x86-64-avx2'
50
+ elif check_flags 'sse41' && check_flags 'popcnt'; then
51
+ true_arch='x86-64-sse41-popcnt'
52
+ else
53
+ true_arch='x86-64'
54
+ fi
55
+ }
56
+
57
+ set_arch_ppc_64() {
58
+ if $(grep -q -w "altivec" /proc/cpuinfo); then
59
+ power=$(grep -oP -m 1 'cpu\t+: POWER\K\d+' /proc/cpuinfo)
60
+ if [ "0$power" -gt 7 ]; then
61
+ # VSX started with POWER8
62
+ true_arch='ppc-64-vsx'
63
+ else
64
+ true_arch='ppc-64-altivec'
65
+ fi
66
+ else
67
+ true_arch='ppc-64'
68
+ fi
69
+ }
70
+
71
+ # Check the system type
72
+ uname_s=$(uname -s)
73
+ uname_m=$(uname -m)
74
+ case $uname_s in
75
+ 'Darwin') # Mac OSX system
76
+ case $uname_m in
77
+ 'arm64')
78
+ true_arch='apple-silicon'
79
+ file_arch='m1-apple-silicon'
80
+ ;;
81
+ 'x86_64')
82
+ flags=$(sysctl -n machdep.cpu.features machdep.cpu.leaf7_features | tr '\n' ' ' | tr '[:upper:]' '[:lower:]' | tr -d '_.')
83
+ set_arch_x86_64
84
+ if [ "$true_arch" = 'x86-64-vnni256' ] || [ "$true_arch" = 'x86-64-avx512' ]; then
85
+ file_arch='x86-64-bmi2'
86
+ fi
87
+ ;;
88
+ esac
89
+ file_os='macos'
90
+ file_ext='tar'
91
+ ;;
92
+ 'Linux') # Linux system
93
+ get_flags
94
+ case $uname_m in
95
+ 'x86_64')
96
+ file_os='ubuntu'
97
+ check_znver_1_2
98
+ set_arch_x86_64
99
+ ;;
100
+ 'i686')
101
+ file_os='ubuntu'
102
+ true_arch='x86-32'
103
+ ;;
104
+ 'ppc64'*)
105
+ file_os='ubuntu'
106
+ set_arch_ppc_64
107
+ ;;
108
+ 'aarch64')
109
+ file_os='android'
110
+ true_arch='armv8'
111
+ if check_flags 'asimddp'; then
112
+ true_arch="$true_arch-dotprod"
113
+ fi
114
+ ;;
115
+ 'armv7'*)
116
+ file_os='android'
117
+ true_arch='armv7'
118
+ if check_flags 'neon'; then
119
+ true_arch="$true_arch-neon"
120
+ fi
121
+ ;;
122
+ 'loongarch64'*)
123
+ file_os='linux'
124
+ set_arch_loongarch64
125
+ ;;
126
+ *) # Unsupported machine type, exit with error
127
+ printf 'Unsupported machine type: %s\n' "$uname_m"
128
+ exit 1
129
+ ;;
130
+ esac
131
+ file_ext='tar'
132
+ ;;
133
+ 'CYGWIN'*|'MINGW'*|'MSYS'*) # Windows system with POSIX compatibility layer
134
+ get_flags
135
+ check_znver_1_2
136
+ set_arch_x86_64
137
+ file_os='windows'
138
+ file_ext='zip'
139
+ ;;
140
+ *)
141
+ # Unknown system type, exit with error
142
+ printf 'Unsupported system type: %s\n' "$uname_s"
143
+ exit 1
144
+ ;;
145
+ esac
146
+
147
+ if [ -z "$file_arch" ]; then
148
+ file_arch=$true_arch
149
+ fi
150
+
151
+ file_name="stockfish-$file_os-$file_arch.$file_ext"
152
+
153
+ printf '%s %s\n' "$true_arch" "$file_name"
stockfish/scripts/net.sh ADDED
@@ -0,0 +1,76 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/bin/sh
2
+
3
+ wget_or_curl=$( (command -v wget > /dev/null 2>&1 && echo "wget -qO-") || \
4
+ (command -v curl > /dev/null 2>&1 && echo "curl -skL"))
5
+
6
+
7
+ sha256sum=$( (command -v shasum > /dev/null 2>&1 && echo "shasum -a 256") || \
8
+ (command -v sha256sum > /dev/null 2>&1 && echo "sha256sum"))
9
+
10
+ if [ -z "$sha256sum" ]; then
11
+ >&2 echo "sha256sum not found, NNUE files will be assumed valid."
12
+ fi
13
+
14
+ get_nnue_filename() {
15
+ grep "$1" evaluate.h | grep "#define" | sed "s/.*\(nn-[a-z0-9]\{12\}.nnue\).*/\1/"
16
+ }
17
+
18
+ validate_network() {
19
+ # If no sha256sum command is available, assume the file is always valid.
20
+ if [ -n "$sha256sum" ] && [ -f "$1" ]; then
21
+ if [ "$1" != "nn-$($sha256sum "$1" | cut -c 1-12).nnue" ]; then
22
+ rm -f "$1"
23
+ return 1
24
+ fi
25
+ fi
26
+ }
27
+
28
+ fetch_network() {
29
+ _filename="$(get_nnue_filename "$1")"
30
+
31
+ if [ -z "$_filename" ]; then
32
+ >&2 echo "NNUE file name not found for: $1"
33
+ return 1
34
+ fi
35
+
36
+ if [ -f "$_filename" ]; then
37
+ if validate_network "$_filename"; then
38
+ echo "Existing $_filename validated, skipping download"
39
+ return
40
+ else
41
+ echo "Removing invalid NNUE file: $_filename"
42
+ fi
43
+ fi
44
+
45
+ if [ -z "$wget_or_curl" ]; then
46
+ >&2 printf "%s\n" "Neither wget or curl is installed." \
47
+ "Install one of these tools to download NNUE files automatically."
48
+ exit 1
49
+ fi
50
+
51
+ for url in \
52
+ "https://tests.stockfishchess.org/api/nn/$_filename" \
53
+ "https://github.com/official-stockfish/networks/raw/master/$_filename"; do
54
+ echo "Downloading from $url ..."
55
+ if $wget_or_curl "$url" > "$_filename"; then
56
+ if validate_network "$_filename"; then
57
+ echo "Successfully validated $_filename"
58
+ else
59
+ echo "Downloaded $_filename is invalid"
60
+ continue
61
+ fi
62
+ else
63
+ echo "Failed to download from $url"
64
+ fi
65
+ if [ -f "$_filename" ]; then
66
+ return
67
+ fi
68
+ done
69
+
70
+ # Download was not successful in the loop, return false.
71
+ >&2 echo "Failed to download $_filename"
72
+ return 1
73
+ }
74
+
75
+ fetch_network EvalFileDefaultNameBig && \
76
+ fetch_network EvalFileDefaultNameSmall
stockfish/src/Makefile ADDED
@@ -0,0 +1,1123 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Stockfish, a UCI chess playing engine derived from Glaurung 2.1
2
+ # Copyright (C) 2004-2025 The Stockfish developers (see AUTHORS file)
3
+ #
4
+ # Stockfish is free software: you can redistribute it and/or modify
5
+ # it under the terms of the GNU General Public License as published by
6
+ # the Free Software Foundation, either version 3 of the License, or
7
+ # (at your option) any later version.
8
+ #
9
+ # Stockfish is distributed in the hope that it will be useful,
10
+ # but WITHOUT ANY WARRANTY; without even the implied warranty of
11
+ # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12
+ # GNU General Public License for more details.
13
+ #
14
+ # You should have received a copy of the GNU General Public License
15
+ # along with this program. If not, see <http://www.gnu.org/licenses/>.
16
+
17
+
18
+ ### ==========================================================================
19
+ ### Section 1. General Configuration
20
+ ### ==========================================================================
21
+
22
+ ### Establish the operating system name
23
+ KERNEL := $(shell uname -s)
24
+ ifeq ($(KERNEL),Linux)
25
+ OS := $(shell uname -o)
26
+ endif
27
+
28
+ ### Target Windows OS
29
+ ifeq ($(OS),Windows_NT)
30
+ ifneq ($(COMP),ndk)
31
+ target_windows = yes
32
+ endif
33
+ else ifeq ($(COMP),mingw)
34
+ target_windows = yes
35
+ ifeq ($(WINE_PATH),)
36
+ WINE_PATH := $(shell which wine)
37
+ endif
38
+ endif
39
+
40
+ ### Executable name
41
+ ifeq ($(target_windows),yes)
42
+ EXE = stockfish.exe
43
+ else
44
+ EXE = stockfish
45
+ endif
46
+
47
+ ### Installation dir definitions
48
+ PREFIX = /usr/local
49
+ BINDIR = $(PREFIX)/bin
50
+
51
+ ### Built-in benchmark for pgo-builds
52
+ PGOBENCH = $(WINE_PATH) ./$(EXE) bench
53
+
54
+ ### Source and object files
55
+ SRCS = benchmark.cpp bitboard.cpp evaluate.cpp main.cpp \
56
+ misc.cpp movegen.cpp movepick.cpp position.cpp \
57
+ search.cpp thread.cpp timeman.cpp tt.cpp uci.cpp ucioption.cpp tune.cpp syzygy/tbprobe.cpp \
58
+ nnue/nnue_accumulator.cpp nnue/nnue_misc.cpp nnue/features/half_ka_v2_hm.cpp nnue/network.cpp \
59
+ engine.cpp score.cpp memory.cpp
60
+
61
+ HEADERS = benchmark.h bitboard.h evaluate.h misc.h movegen.h movepick.h history.h \
62
+ nnue/nnue_misc.h nnue/features/half_ka_v2_hm.h nnue/layers/affine_transform.h \
63
+ nnue/layers/affine_transform_sparse_input.h nnue/layers/clipped_relu.h nnue/layers/simd.h \
64
+ nnue/layers/sqr_clipped_relu.h nnue/nnue_accumulator.h nnue/nnue_architecture.h \
65
+ nnue/nnue_common.h nnue/nnue_feature_transformer.h position.h \
66
+ search.h syzygy/tbprobe.h thread.h thread_win32_osx.h timeman.h \
67
+ tt.h tune.h types.h uci.h ucioption.h perft.h nnue/network.h engine.h score.h numa.h memory.h
68
+
69
+ OBJS = $(notdir $(SRCS:.cpp=.o))
70
+
71
+ VPATH = syzygy:nnue:nnue/features
72
+
73
+ ### ==========================================================================
74
+ ### Section 2. High-level Configuration
75
+ ### ==========================================================================
76
+ #
77
+ # flag --- Comp switch --- Description
78
+ # ----------------------------------------------------------------------------
79
+ #
80
+ # debug = yes/no --- -DNDEBUG --- Enable/Disable debug mode
81
+ # sanitize = none/<sanitizer> ... (-fsanitize )
82
+ # --- ( undefined ) --- enable undefined behavior checks
83
+ # --- ( thread ) --- enable threading error checks
84
+ # --- ( address ) --- enable memory access checks
85
+ # --- ...etc... --- see compiler documentation for supported sanitizers
86
+ # optimize = yes/no --- (-O3/-fast etc.) --- Enable/Disable optimizations
87
+ # arch = (name) --- (-arch) --- Target architecture
88
+ # bits = 64/32 --- -DIS_64BIT --- 64-/32-bit operating system
89
+ # prefetch = yes/no --- -DUSE_PREFETCH --- Use prefetch asm-instruction
90
+ # popcnt = yes/no --- -DUSE_POPCNT --- Use popcnt asm-instruction
91
+ # pext = yes/no --- -DUSE_PEXT --- Use pext x86_64 asm-instruction
92
+ # sse = yes/no --- -msse --- Use Intel Streaming SIMD Extensions
93
+ # mmx = yes/no --- -mmmx --- Use Intel MMX instructions
94
+ # sse2 = yes/no --- -msse2 --- Use Intel Streaming SIMD Extensions 2
95
+ # ssse3 = yes/no --- -mssse3 --- Use Intel Supplemental Streaming SIMD Extensions 3
96
+ # sse41 = yes/no --- -msse4.1 --- Use Intel Streaming SIMD Extensions 4.1
97
+ # avx2 = yes/no --- -mavx2 --- Use Intel Advanced Vector Extensions 2
98
+ # avxvnni = yes/no --- -mavxvnni --- Use Intel Vector Neural Network Instructions AVX
99
+ # avx512 = yes/no --- -mavx512bw --- Use Intel Advanced Vector Extensions 512
100
+ # vnni256 = yes/no --- -mavx256vnni --- Use Intel Vector Neural Network Instructions 512 with 256bit operands
101
+ # vnni512 = yes/no --- -mavx512vnni --- Use Intel Vector Neural Network Instructions 512
102
+ # altivec = yes/no --- -maltivec --- Use PowerPC Altivec SIMD extension
103
+ # vsx = yes/no --- -mvsx --- Use POWER VSX SIMD extension
104
+ # neon = yes/no --- -DUSE_NEON --- Use ARM SIMD architecture
105
+ # dotprod = yes/no --- -DUSE_NEON_DOTPROD --- Use ARM advanced SIMD Int8 dot product instructions
106
+ # lsx = yes/no --- -mlsx --- Use Loongson SIMD eXtension
107
+ # lasx = yes/no --- -mlasx --- use Loongson Advanced SIMD eXtension
108
+ #
109
+ # Note that Makefile is space sensitive, so when adding new architectures
110
+ # or modifying existing flags, you have to make sure there are no extra spaces
111
+ # at the end of the line for flag values.
112
+ #
113
+ # Example of use for these flags:
114
+ # make build ARCH=x86-64-avx512 debug=yes sanitize="address undefined"
115
+
116
+
117
+ ### 2.1. General and architecture defaults
118
+
119
+ ifeq ($(ARCH),)
120
+ ARCH = native
121
+ endif
122
+
123
+ ifeq ($(ARCH), native)
124
+ override ARCH := $(shell $(SHELL) ../scripts/get_native_properties.sh | cut -d " " -f 1)
125
+ endif
126
+
127
+ # explicitly check for the list of supported architectures (as listed with make help),
128
+ # the user can override with `make ARCH=x86-32-vnni256 SUPPORTED_ARCH=true`
129
+ ifeq ($(ARCH), $(filter $(ARCH), \
130
+ x86-64-vnni512 x86-64-vnni256 x86-64-avx512 x86-64-avxvnni x86-64-bmi2 \
131
+ x86-64-avx2 x86-64-sse41-popcnt x86-64-modern x86-64-ssse3 x86-64-sse3-popcnt \
132
+ x86-64 x86-32-sse41-popcnt x86-32-sse2 x86-32 ppc-64 ppc-64-altivec ppc-64-vsx ppc-32 e2k \
133
+ armv7 armv7-neon armv8 armv8-dotprod apple-silicon general-64 general-32 riscv64 \
134
+ loongarch64 loongarch64-lsx loongarch64-lasx))
135
+ SUPPORTED_ARCH=true
136
+ else
137
+ SUPPORTED_ARCH=false
138
+ endif
139
+
140
+ optimize = yes
141
+ debug = no
142
+ sanitize = none
143
+ bits = 64
144
+ prefetch = no
145
+ popcnt = no
146
+ pext = no
147
+ sse = no
148
+ mmx = no
149
+ sse2 = no
150
+ ssse3 = no
151
+ sse41 = no
152
+ avx2 = no
153
+ avxvnni = no
154
+ avx512 = no
155
+ vnni256 = no
156
+ vnni512 = no
157
+ altivec = no
158
+ vsx = no
159
+ neon = no
160
+ dotprod = no
161
+ arm_version = 0
162
+ lsx = no
163
+ lasx = no
164
+ STRIP = strip
165
+
166
+ ifneq ($(shell which clang-format-18 2> /dev/null),)
167
+ CLANG-FORMAT = clang-format-18
168
+ else
169
+ CLANG-FORMAT = clang-format
170
+ endif
171
+
172
+ ### 2.2 Architecture specific
173
+
174
+ ifeq ($(findstring x86,$(ARCH)),x86)
175
+
176
+ # x86-32/64
177
+
178
+ ifeq ($(findstring x86-32,$(ARCH)),x86-32)
179
+ arch = i386
180
+ bits = 32
181
+ sse = no
182
+ mmx = yes
183
+ else
184
+ arch = x86_64
185
+ sse = yes
186
+ sse2 = yes
187
+ endif
188
+
189
+ ifeq ($(findstring -sse,$(ARCH)),-sse)
190
+ sse = yes
191
+ endif
192
+
193
+ ifeq ($(findstring -popcnt,$(ARCH)),-popcnt)
194
+ popcnt = yes
195
+ endif
196
+
197
+ ifeq ($(findstring -mmx,$(ARCH)),-mmx)
198
+ mmx = yes
199
+ endif
200
+
201
+ ifeq ($(findstring -sse2,$(ARCH)),-sse2)
202
+ sse = yes
203
+ sse2 = yes
204
+ endif
205
+
206
+ ifeq ($(findstring -ssse3,$(ARCH)),-ssse3)
207
+ sse = yes
208
+ sse2 = yes
209
+ ssse3 = yes
210
+ endif
211
+
212
+ ifeq ($(findstring -sse41,$(ARCH)),-sse41)
213
+ sse = yes
214
+ sse2 = yes
215
+ ssse3 = yes
216
+ sse41 = yes
217
+ endif
218
+
219
+ ifeq ($(findstring -modern,$(ARCH)),-modern)
220
+ $(warning *** ARCH=$(ARCH) is deprecated, defaulting to ARCH=x86-64-sse41-popcnt. Execute `make help` for a list of available architectures. ***)
221
+ $(shell sleep 5)
222
+ popcnt = yes
223
+ sse = yes
224
+ sse2 = yes
225
+ ssse3 = yes
226
+ sse41 = yes
227
+ endif
228
+
229
+ ifeq ($(findstring -avx2,$(ARCH)),-avx2)
230
+ popcnt = yes
231
+ sse = yes
232
+ sse2 = yes
233
+ ssse3 = yes
234
+ sse41 = yes
235
+ avx2 = yes
236
+ endif
237
+
238
+ ifeq ($(findstring -avxvnni,$(ARCH)),-avxvnni)
239
+ popcnt = yes
240
+ sse = yes
241
+ sse2 = yes
242
+ ssse3 = yes
243
+ sse41 = yes
244
+ avx2 = yes
245
+ avxvnni = yes
246
+ pext = yes
247
+ endif
248
+
249
+ ifeq ($(findstring -bmi2,$(ARCH)),-bmi2)
250
+ popcnt = yes
251
+ sse = yes
252
+ sse2 = yes
253
+ ssse3 = yes
254
+ sse41 = yes
255
+ avx2 = yes
256
+ pext = yes
257
+ endif
258
+
259
+ ifeq ($(findstring -avx512,$(ARCH)),-avx512)
260
+ popcnt = yes
261
+ sse = yes
262
+ sse2 = yes
263
+ ssse3 = yes
264
+ sse41 = yes
265
+ avx2 = yes
266
+ pext = yes
267
+ avx512 = yes
268
+ endif
269
+
270
+ ifeq ($(findstring -vnni256,$(ARCH)),-vnni256)
271
+ popcnt = yes
272
+ sse = yes
273
+ sse2 = yes
274
+ ssse3 = yes
275
+ sse41 = yes
276
+ avx2 = yes
277
+ pext = yes
278
+ vnni256 = yes
279
+ endif
280
+
281
+ ifeq ($(findstring -vnni512,$(ARCH)),-vnni512)
282
+ popcnt = yes
283
+ sse = yes
284
+ sse2 = yes
285
+ ssse3 = yes
286
+ sse41 = yes
287
+ avx2 = yes
288
+ pext = yes
289
+ avx512 = yes
290
+ vnni512 = yes
291
+ endif
292
+
293
+ ifeq ($(sse),yes)
294
+ prefetch = yes
295
+ endif
296
+
297
+ # 64-bit pext is not available on x86-32
298
+ ifeq ($(bits),32)
299
+ pext = no
300
+ endif
301
+
302
+ else
303
+
304
+ # all other architectures
305
+
306
+ ifeq ($(ARCH),general-32)
307
+ arch = any
308
+ bits = 32
309
+ endif
310
+
311
+ ifeq ($(ARCH),general-64)
312
+ arch = any
313
+ endif
314
+
315
+ ifeq ($(ARCH),armv7)
316
+ arch = armv7
317
+ prefetch = yes
318
+ bits = 32
319
+ arm_version = 7
320
+ endif
321
+
322
+ ifeq ($(ARCH),armv7-neon)
323
+ arch = armv7
324
+ prefetch = yes
325
+ popcnt = yes
326
+ neon = yes
327
+ bits = 32
328
+ arm_version = 7
329
+ endif
330
+
331
+ ifeq ($(ARCH),armv8)
332
+ arch = armv8
333
+ prefetch = yes
334
+ popcnt = yes
335
+ neon = yes
336
+ arm_version = 8
337
+ endif
338
+
339
+ ifeq ($(ARCH),armv8-dotprod)
340
+ arch = armv8
341
+ prefetch = yes
342
+ popcnt = yes
343
+ neon = yes
344
+ dotprod = yes
345
+ arm_version = 8
346
+ endif
347
+
348
+ ifeq ($(ARCH),apple-silicon)
349
+ arch = arm64
350
+ prefetch = yes
351
+ popcnt = yes
352
+ neon = yes
353
+ dotprod = yes
354
+ arm_version = 8
355
+ endif
356
+
357
+ ifeq ($(ARCH),ppc-32)
358
+ arch = ppc
359
+ bits = 32
360
+ endif
361
+
362
+ ifeq ($(ARCH),ppc-64)
363
+ arch = ppc64
364
+ popcnt = yes
365
+ prefetch = yes
366
+ endif
367
+
368
+ ifeq ($(ARCH),ppc-64-altivec)
369
+ arch = ppc64
370
+ popcnt = yes
371
+ prefetch = yes
372
+ altivec = yes
373
+ endif
374
+
375
+ ifeq ($(ARCH),ppc-64-vsx)
376
+ arch = ppc64
377
+ popcnt = yes
378
+ prefetch = yes
379
+ vsx = yes
380
+ endif
381
+
382
+ ifeq ($(findstring e2k,$(ARCH)),e2k)
383
+ arch = e2k
384
+ mmx = yes
385
+ bits = 64
386
+ sse = yes
387
+ sse2 = yes
388
+ ssse3 = yes
389
+ sse41 = yes
390
+ popcnt = yes
391
+ endif
392
+
393
+ ifeq ($(ARCH),riscv64)
394
+ arch = riscv64
395
+ endif
396
+
397
+ ifeq ($(findstring loongarch64,$(ARCH)),loongarch64)
398
+ arch = loongarch64
399
+ prefetch = yes
400
+
401
+ ifeq ($(findstring -lasx,$(ARCH)),-lasx)
402
+ lsx = yes
403
+ lasx = yes
404
+ endif
405
+
406
+ ifeq ($(findstring -lsx,$(ARCH)),-lsx)
407
+ lsx = yes
408
+ endif
409
+
410
+ endif
411
+ endif
412
+
413
+
414
+ ### ==========================================================================
415
+ ### Section 3. Low-level Configuration
416
+ ### ==========================================================================
417
+
418
+ ### 3.1 Selecting compiler (default = gcc)
419
+ ifeq ($(MAKELEVEL),0)
420
+ export ENV_CXXFLAGS := $(CXXFLAGS)
421
+ export ENV_DEPENDFLAGS := $(DEPENDFLAGS)
422
+ export ENV_LDFLAGS := $(LDFLAGS)
423
+ endif
424
+
425
+ CXXFLAGS = $(ENV_CXXFLAGS) -Wall -Wcast-qual -fno-exceptions -std=c++17 $(EXTRACXXFLAGS)
426
+ DEPENDFLAGS = $(ENV_DEPENDFLAGS) -std=c++17
427
+ LDFLAGS = $(ENV_LDFLAGS) $(EXTRALDFLAGS)
428
+
429
+ ifeq ($(COMP),)
430
+ COMP=gcc
431
+ endif
432
+
433
+ ifeq ($(COMP),gcc)
434
+ comp=gcc
435
+ CXX=g++
436
+ CXXFLAGS += -pedantic -Wextra -Wshadow -Wmissing-declarations
437
+
438
+ ifeq ($(arch),$(filter $(arch),armv7 armv8 riscv64))
439
+ ifeq ($(OS),Android)
440
+ CXXFLAGS += -m$(bits)
441
+ LDFLAGS += -m$(bits)
442
+ endif
443
+ ifeq ($(ARCH),riscv64)
444
+ CXXFLAGS += -latomic
445
+ endif
446
+ else ifeq ($(arch),loongarch64)
447
+ CXXFLAGS += -latomic
448
+ else
449
+ CXXFLAGS += -m$(bits)
450
+ LDFLAGS += -m$(bits)
451
+ endif
452
+
453
+ ifeq ($(arch),$(filter $(arch),armv7))
454
+ LDFLAGS += -latomic
455
+ endif
456
+
457
+ ifneq ($(KERNEL),Darwin)
458
+ LDFLAGS += -Wl,--no-as-needed
459
+ endif
460
+ endif
461
+
462
+ ifeq ($(target_windows),yes)
463
+ LDFLAGS += -static
464
+ endif
465
+
466
+ ifeq ($(COMP),mingw)
467
+ comp=mingw
468
+
469
+ ifeq ($(bits),64)
470
+ ifeq ($(shell which x86_64-w64-mingw32-c++-posix 2> /dev/null),)
471
+ CXX=x86_64-w64-mingw32-c++
472
+ else
473
+ CXX=x86_64-w64-mingw32-c++-posix
474
+ endif
475
+ else
476
+ ifeq ($(shell which i686-w64-mingw32-c++-posix 2> /dev/null),)
477
+ CXX=i686-w64-mingw32-c++
478
+ else
479
+ CXX=i686-w64-mingw32-c++-posix
480
+ endif
481
+ endif
482
+ CXXFLAGS += -pedantic -Wextra -Wshadow -Wmissing-declarations
483
+ endif
484
+
485
+ ifeq ($(COMP),icx)
486
+ comp=icx
487
+ CXX=icpx
488
+ CXXFLAGS += --intel -pedantic -Wextra -Wshadow -Wmissing-prototypes \
489
+ -Wconditional-uninitialized -Wabi -Wdeprecated
490
+ endif
491
+
492
+ ifeq ($(COMP),clang)
493
+ comp=clang
494
+ CXX=clang++
495
+ ifeq ($(target_windows),yes)
496
+ CXX=x86_64-w64-mingw32-clang++
497
+ endif
498
+
499
+ CXXFLAGS += -pedantic -Wextra -Wshadow -Wmissing-prototypes \
500
+ -Wconditional-uninitialized
501
+
502
+ ifeq ($(filter $(KERNEL),Darwin OpenBSD FreeBSD),)
503
+ ifeq ($(target_windows),)
504
+ ifneq ($(RTLIB),compiler-rt)
505
+ LDFLAGS += -latomic
506
+ endif
507
+ endif
508
+ endif
509
+
510
+ ifeq ($(arch),$(filter $(arch),armv7 armv8 riscv64))
511
+ ifeq ($(OS),Android)
512
+ CXXFLAGS += -m$(bits)
513
+ LDFLAGS += -m$(bits)
514
+ endif
515
+ ifeq ($(ARCH),riscv64)
516
+ CXXFLAGS += -latomic
517
+ endif
518
+ else ifeq ($(arch),loongarch64)
519
+ CXXFLAGS += -latomic
520
+ else
521
+ CXXFLAGS += -m$(bits)
522
+ LDFLAGS += -m$(bits)
523
+ endif
524
+ endif
525
+
526
+ ifeq ($(KERNEL),Darwin)
527
+ CXXFLAGS += -mmacosx-version-min=10.15
528
+ LDFLAGS += -mmacosx-version-min=10.15
529
+ ifneq ($(arch),any)
530
+ CXXFLAGS += -arch $(arch)
531
+ LDFLAGS += -arch $(arch)
532
+ endif
533
+ XCRUN = xcrun
534
+ endif
535
+
536
+ # To cross-compile for Android, NDK version r21 or later is recommended.
537
+ # In earlier NDK versions, you'll need to pass -fno-addrsig if using GNU binutils.
538
+ # Currently we don't know how to make PGO builds with the NDK yet.
539
+ ifeq ($(COMP),ndk)
540
+ CXXFLAGS += -stdlib=libc++ -fPIE
541
+ comp=clang
542
+ ifeq ($(arch),armv7)
543
+ CXX=armv7a-linux-androideabi16-clang++
544
+ CXXFLAGS += -mthumb -march=armv7-a -mfloat-abi=softfp -mfpu=neon
545
+ ifneq ($(shell which arm-linux-androideabi-strip 2>/dev/null),)
546
+ STRIP=arm-linux-androideabi-strip
547
+ else
548
+ STRIP=llvm-strip
549
+ endif
550
+ endif
551
+ ifeq ($(arch),armv8)
552
+ CXX=aarch64-linux-android21-clang++
553
+ ifneq ($(shell which aarch64-linux-android-strip 2>/dev/null),)
554
+ STRIP=aarch64-linux-android-strip
555
+ else
556
+ STRIP=llvm-strip
557
+ endif
558
+ endif
559
+ ifeq ($(arch),x86_64)
560
+ CXX=x86_64-linux-android21-clang++
561
+ ifneq ($(shell which x86_64-linux-android-strip 2>/dev/null),)
562
+ STRIP=x86_64-linux-android-strip
563
+ else
564
+ STRIP=llvm-strip
565
+ endif
566
+ endif
567
+ LDFLAGS += -static-libstdc++ -pie -lm -latomic
568
+ endif
569
+
570
+ ifeq ($(comp),icx)
571
+ profile_make = icx-profile-make
572
+ profile_use = icx-profile-use
573
+ else ifeq ($(comp),clang)
574
+ profile_make = clang-profile-make
575
+ profile_use = clang-profile-use
576
+ else
577
+ profile_make = gcc-profile-make
578
+ profile_use = gcc-profile-use
579
+ ifeq ($(KERNEL),Darwin)
580
+ EXTRAPROFILEFLAGS = -fvisibility=hidden
581
+ endif
582
+ endif
583
+
584
+ ### Allow overwriting CXX from command line
585
+ ifdef COMPCXX
586
+ CXX=$(COMPCXX)
587
+ endif
588
+
589
+ ### Sometimes gcc is really clang
590
+ ifeq ($(COMP),gcc)
591
+ gccversion := $(shell $(CXX) --version 2>/dev/null)
592
+ gccisclang := $(findstring clang,$(gccversion))
593
+ ifneq ($(gccisclang),)
594
+ profile_make = clang-profile-make
595
+ profile_use = clang-profile-use
596
+ endif
597
+ endif
598
+
599
+ ### On mingw use Windows threads, otherwise POSIX
600
+ ifneq ($(comp),mingw)
601
+ CXXFLAGS += -DUSE_PTHREADS
602
+ # On Android Bionic's C library comes with its own pthread implementation bundled in
603
+ ifneq ($(OS),Android)
604
+ # Haiku has pthreads in its libroot, so only link it in on other platforms
605
+ ifneq ($(KERNEL),Haiku)
606
+ ifneq ($(COMP),ndk)
607
+ LDFLAGS += -lpthread
608
+ endif
609
+ endif
610
+ endif
611
+ endif
612
+
613
+ ### 3.2.1 Debugging
614
+ ifeq ($(debug),no)
615
+ CXXFLAGS += -DNDEBUG
616
+ else
617
+ CXXFLAGS += -g
618
+ endif
619
+
620
+ ### 3.2.2 Debugging with undefined behavior sanitizers
621
+ ifneq ($(sanitize),none)
622
+ CXXFLAGS += -g3 $(addprefix -fsanitize=,$(sanitize))
623
+ LDFLAGS += $(addprefix -fsanitize=,$(sanitize))
624
+ endif
625
+
626
+ ### 3.3 Optimization
627
+ ifeq ($(optimize),yes)
628
+
629
+ CXXFLAGS += -O3 -funroll-loops
630
+
631
+ ifeq ($(comp),gcc)
632
+ ifeq ($(OS), Android)
633
+ CXXFLAGS += -fno-gcse -mthumb -march=armv7-a -mfloat-abi=softfp
634
+ endif
635
+ endif
636
+
637
+ ifeq ($(KERNEL),Darwin)
638
+ ifeq ($(comp),$(filter $(comp),clang icx))
639
+ CXXFLAGS += -mdynamic-no-pic
640
+ endif
641
+
642
+ ifeq ($(comp),gcc)
643
+ ifneq ($(arch),arm64)
644
+ CXXFLAGS += -mdynamic-no-pic
645
+ endif
646
+ endif
647
+ endif
648
+
649
+ ifeq ($(comp),clang)
650
+ clangmajorversion := $(shell $(CXX) -dumpversion 2>/dev/null | cut -f1 -d.)
651
+ ifeq ($(shell expr $(clangmajorversion) \< 16),1)
652
+ CXXFLAGS += -fexperimental-new-pass-manager
653
+ endif
654
+ endif
655
+ endif
656
+
657
+ ### 3.4 Bits
658
+ ifeq ($(bits),64)
659
+ CXXFLAGS += -DIS_64BIT
660
+ endif
661
+
662
+ ### 3.5 prefetch and popcount
663
+ ifeq ($(prefetch),yes)
664
+ ifeq ($(sse),yes)
665
+ CXXFLAGS += -msse
666
+ endif
667
+ else
668
+ CXXFLAGS += -DNO_PREFETCH
669
+ endif
670
+
671
+ ifeq ($(popcnt),yes)
672
+ ifeq ($(arch),$(filter $(arch),ppc64 ppc64-altivec ppc64-vsx armv7 armv8 arm64))
673
+ CXXFLAGS += -DUSE_POPCNT
674
+ else
675
+ CXXFLAGS += -msse3 -mpopcnt -DUSE_POPCNT
676
+ endif
677
+ endif
678
+
679
+ ### 3.6 SIMD architectures
680
+ ifeq ($(avx2),yes)
681
+ CXXFLAGS += -DUSE_AVX2
682
+ ifeq ($(comp),$(filter $(comp),gcc clang mingw icx))
683
+ CXXFLAGS += -mavx2 -mbmi
684
+ endif
685
+ endif
686
+
687
+ ifeq ($(avxvnni),yes)
688
+ CXXFLAGS += -DUSE_VNNI -DUSE_AVXVNNI
689
+ ifeq ($(comp),$(filter $(comp),gcc clang mingw icx))
690
+ CXXFLAGS += -mavxvnni
691
+ endif
692
+ endif
693
+
694
+ ifeq ($(avx512),yes)
695
+ CXXFLAGS += -DUSE_AVX512
696
+ ifeq ($(comp),$(filter $(comp),gcc clang mingw icx))
697
+ CXXFLAGS += -mavx512f -mavx512bw
698
+ endif
699
+ endif
700
+
701
+ ifeq ($(vnni256),yes)
702
+ CXXFLAGS += -DUSE_VNNI
703
+ ifeq ($(comp),$(filter $(comp),gcc clang mingw icx))
704
+ CXXFLAGS += -mavx512f -mavx512bw -mavx512vnni -mavx512dq -mavx512vl -mprefer-vector-width=256
705
+ endif
706
+ endif
707
+
708
+ ifeq ($(vnni512),yes)
709
+ CXXFLAGS += -DUSE_VNNI
710
+ ifeq ($(comp),$(filter $(comp),gcc clang mingw icx))
711
+ CXXFLAGS += -mavx512f -mavx512bw -mavx512vnni -mavx512dq -mavx512vl -mprefer-vector-width=512
712
+ endif
713
+ endif
714
+
715
+ ifeq ($(sse41),yes)
716
+ CXXFLAGS += -DUSE_SSE41
717
+ ifeq ($(comp),$(filter $(comp),gcc clang mingw icx))
718
+ CXXFLAGS += -msse4.1
719
+ endif
720
+ endif
721
+
722
+ ifeq ($(ssse3),yes)
723
+ CXXFLAGS += -DUSE_SSSE3
724
+ ifeq ($(comp),$(filter $(comp),gcc clang mingw icx))
725
+ CXXFLAGS += -mssse3
726
+ endif
727
+ endif
728
+
729
+ ifeq ($(sse2),yes)
730
+ CXXFLAGS += -DUSE_SSE2
731
+ ifeq ($(comp),$(filter $(comp),gcc clang mingw icx))
732
+ CXXFLAGS += -msse2
733
+ endif
734
+ endif
735
+
736
+ ifeq ($(mmx),yes)
737
+ ifeq ($(comp),$(filter $(comp),gcc clang mingw icx))
738
+ CXXFLAGS += -mmmx
739
+ endif
740
+ endif
741
+
742
+ ifeq ($(altivec),yes)
743
+ CXXFLAGS += -maltivec
744
+ ifeq ($(COMP),gcc)
745
+ CXXFLAGS += -mabi=altivec
746
+ endif
747
+ endif
748
+
749
+ ifeq ($(vsx),yes)
750
+ CXXFLAGS += -mvsx
751
+ ifeq ($(COMP),gcc)
752
+ CXXFLAGS += -DNO_WARN_X86_INTRINSICS -DUSE_SSE2
753
+ endif
754
+ endif
755
+
756
+ ifeq ($(neon),yes)
757
+ CXXFLAGS += -DUSE_NEON=$(arm_version)
758
+ ifeq ($(KERNEL),Linux)
759
+ ifneq ($(COMP),ndk)
760
+ ifneq ($(arch),armv8)
761
+ CXXFLAGS += -mfpu=neon
762
+ endif
763
+ endif
764
+ endif
765
+ endif
766
+
767
+ ifeq ($(dotprod),yes)
768
+ CXXFLAGS += -march=armv8.2-a+dotprod -DUSE_NEON_DOTPROD
769
+ endif
770
+
771
+ ifeq ($(lasx),yes)
772
+ ifeq ($(comp),$(filter $(comp),gcc clang mingw icx))
773
+ CXXFLAGS += -mlasx
774
+ endif
775
+ endif
776
+
777
+ ifeq ($(lsx),yes)
778
+ ifeq ($(comp),$(filter $(comp),gcc clang mingw icx))
779
+ CXXFLAGS += -mlsx
780
+ endif
781
+ endif
782
+
783
+ ### 3.7 pext
784
+ ifeq ($(pext),yes)
785
+ CXXFLAGS += -DUSE_PEXT
786
+ ifeq ($(comp),$(filter $(comp),gcc clang mingw icx))
787
+ CXXFLAGS += -mbmi2
788
+ endif
789
+ endif
790
+
791
+ ### 3.8.1 Try to include git commit sha for versioning
792
+ GIT_SHA := $(shell git rev-parse HEAD 2>/dev/null | cut -c 1-8)
793
+ ifneq ($(GIT_SHA), )
794
+ CXXFLAGS += -DGIT_SHA=$(GIT_SHA)
795
+ endif
796
+
797
+ ### 3.8.2 Try to include git commit date for versioning
798
+ GIT_DATE := $(shell git show -s --date=format:'%Y%m%d' --format=%cd HEAD 2>/dev/null)
799
+ ifneq ($(GIT_DATE), )
800
+ CXXFLAGS += -DGIT_DATE=$(GIT_DATE)
801
+ endif
802
+
803
+ ### 3.8.3 Try to include architecture
804
+ ifneq ($(ARCH), )
805
+ CXXFLAGS += -DARCH=$(ARCH)
806
+ endif
807
+
808
+ ### 3.9 Link Time Optimization
809
+ ### This is a mix of compile and link time options because the lto link phase
810
+ ### needs access to the optimization flags.
811
+ ifeq ($(optimize),yes)
812
+ ifeq ($(debug), no)
813
+ ifeq ($(comp),$(filter $(comp),clang icx))
814
+ CXXFLAGS += -flto=full
815
+ ifeq ($(comp),icx)
816
+ CXXFLAGS += -fwhole-program-vtables
817
+ endif
818
+ ifeq ($(target_windows),yes)
819
+ CXXFLAGS += -fuse-ld=lld
820
+ endif
821
+ LDFLAGS += $(CXXFLAGS)
822
+
823
+ # GCC and CLANG use different methods for parallelizing LTO and CLANG pretends to be
824
+ # GCC on some systems.
825
+ else ifeq ($(comp),gcc)
826
+ ifeq ($(gccisclang),)
827
+ CXXFLAGS += -flto -flto-partition=one
828
+ LDFLAGS += $(CXXFLAGS) -flto=jobserver
829
+ else
830
+ CXXFLAGS += -flto=full
831
+ LDFLAGS += $(CXXFLAGS)
832
+ endif
833
+
834
+ # To use LTO and static linking on Windows,
835
+ # the tool chain requires gcc version 10.1 or later.
836
+ else ifeq ($(comp),mingw)
837
+ CXXFLAGS += -flto -flto-partition=one
838
+ LDFLAGS += $(CXXFLAGS) -save-temps
839
+ endif
840
+ endif
841
+ endif
842
+
843
+ ### 3.10 Android 5 can only run position independent executables. Note that this
844
+ ### breaks Android 4.0 and earlier.
845
+ ifeq ($(OS), Android)
846
+ CXXFLAGS += -fPIE
847
+ LDFLAGS += -fPIE -pie
848
+ endif
849
+
850
+ ### ==========================================================================
851
+ ### Section 4. Public Targets
852
+ ### ==========================================================================
853
+
854
+ help:
855
+ @echo "" && \
856
+ echo "To compile stockfish, type: " && \
857
+ echo "" && \
858
+ echo "make -j target [ARCH=arch] [COMP=compiler] [COMPCXX=cxx]" && \
859
+ echo "" && \
860
+ echo "Supported targets:" && \
861
+ echo "" && \
862
+ echo "help > Display architecture details" && \
863
+ echo "profile-build > standard build with profile-guided optimization" && \
864
+ echo "build > skip profile-guided optimization" && \
865
+ echo "net > Download the default nnue nets" && \
866
+ echo "strip > Strip executable" && \
867
+ echo "install > Install executable" && \
868
+ echo "clean > Clean up" && \
869
+ echo "" && \
870
+ echo "Supported archs:" && \
871
+ echo "" && \
872
+ echo "native > select the best architecture for the host processor (default)" && \
873
+ echo "x86-64-vnni512 > x86 64-bit with vnni 512bit support" && \
874
+ echo "x86-64-vnni256 > x86 64-bit with vnni 512bit support, limit operands to 256bit wide" && \
875
+ echo "x86-64-avx512 > x86 64-bit with avx512 support" && \
876
+ echo "x86-64-avxvnni > x86 64-bit with vnni 256bit support" && \
877
+ echo "x86-64-bmi2 > x86 64-bit with bmi2 support" && \
878
+ echo "x86-64-avx2 > x86 64-bit with avx2 support" && \
879
+ echo "x86-64-sse41-popcnt > x86 64-bit with sse41 and popcnt support" && \
880
+ echo "x86-64-modern > deprecated, currently x86-64-sse41-popcnt" && \
881
+ echo "x86-64-ssse3 > x86 64-bit with ssse3 support" && \
882
+ echo "x86-64-sse3-popcnt > x86 64-bit with sse3 compile and popcnt support" && \
883
+ echo "x86-64 > x86 64-bit generic (with sse2 support)" && \
884
+ echo "x86-32-sse41-popcnt > x86 32-bit with sse41 and popcnt support" && \
885
+ echo "x86-32-sse2 > x86 32-bit with sse2 support" && \
886
+ echo "x86-32 > x86 32-bit generic (with mmx compile support)" && \
887
+ echo "ppc-64 > PPC 64-bit" && \
888
+ echo "ppc-64-altivec > PPC 64-bit with altivec support" && \
889
+ echo "ppc-64-vsx > PPC 64-bit with vsx support" && \
890
+ echo "ppc-32 > PPC 32-bit" && \
891
+ echo "armv7 > ARMv7 32-bit" && \
892
+ echo "armv7-neon > ARMv7 32-bit with popcnt and neon" && \
893
+ echo "armv8 > ARMv8 64-bit with popcnt and neon" && \
894
+ echo "armv8-dotprod > ARMv8 64-bit with popcnt, neon and dot product support" && \
895
+ echo "e2k > Elbrus 2000" && \
896
+ echo "apple-silicon > Apple silicon ARM64" && \
897
+ echo "general-64 > unspecified 64-bit" && \
898
+ echo "general-32 > unspecified 32-bit" && \
899
+ echo "riscv64 > RISC-V 64-bit" && \
900
+ echo "loongarch64 > LoongArch 64-bit" && \
901
+ echo "loongarch64-lsx > LoongArch 64-bit with SIMD eXtension" && \
902
+ echo "loongarch64-lasx > LoongArch 64-bit with Advanced SIMD eXtension" && \
903
+ echo "" && \
904
+ echo "Supported compilers:" && \
905
+ echo "" && \
906
+ echo "gcc > GNU compiler (default)" && \
907
+ echo "mingw > GNU compiler with MinGW under Windows" && \
908
+ echo "clang > LLVM Clang compiler" && \
909
+ echo "icx > Intel oneAPI DPC++/C++ Compiler" && \
910
+ echo "ndk > Google NDK to cross-compile for Android" && \
911
+ echo "" && \
912
+ echo "Simple examples. If you don't know what to do, you likely want to run one of: " && \
913
+ echo "" && \
914
+ echo "make -j profile-build ARCH=x86-64-avx2 # typically a fast compile for common systems " && \
915
+ echo "make -j profile-build ARCH=x86-64-sse41-popcnt # A more portable compile for 64-bit systems " && \
916
+ echo "make -j profile-build ARCH=x86-64 # A portable compile for 64-bit systems " && \
917
+ echo "" && \
918
+ echo "Advanced examples, for experienced users: " && \
919
+ echo "" && \
920
+ echo "make -j profile-build ARCH=x86-64-avxvnni" && \
921
+ echo "make -j profile-build ARCH=x86-64-avxvnni COMP=gcc COMPCXX=g++-12.0" && \
922
+ echo "make -j build ARCH=x86-64-ssse3 COMP=clang" && \
923
+ echo ""
924
+ ifneq ($(SUPPORTED_ARCH), true)
925
+ @echo "Specify a supported architecture with the ARCH option for more details"
926
+ @echo ""
927
+ endif
928
+
929
+
930
+ .PHONY: help analyze build profile-build strip install clean net \
931
+ objclean profileclean config-sanity \
932
+ icx-profile-use icx-profile-make \
933
+ gcc-profile-use gcc-profile-make \
934
+ clang-profile-use clang-profile-make FORCE \
935
+ format analyze
936
+
937
+ analyze: net config-sanity objclean
938
+ $(MAKE) -k ARCH=$(ARCH) COMP=$(COMP) $(OBJS)
939
+
940
+ build: net config-sanity
941
+ $(MAKE) ARCH=$(ARCH) COMP=$(COMP) all
942
+
943
+ profile-build: net config-sanity objclean profileclean
944
+ @echo ""
945
+ @echo "Step 1/4. Building instrumented executable ..."
946
+ $(MAKE) ARCH=$(ARCH) COMP=$(COMP) $(profile_make)
947
+ @echo ""
948
+ @echo "Step 2/4. Running benchmark for pgo-build ..."
949
+ $(PGOBENCH) > PGOBENCH.out 2>&1
950
+ tail -n 4 PGOBENCH.out
951
+ @echo ""
952
+ @echo "Step 3/4. Building optimized executable ..."
953
+ $(MAKE) ARCH=$(ARCH) COMP=$(COMP) objclean
954
+ $(MAKE) ARCH=$(ARCH) COMP=$(COMP) $(profile_use)
955
+ @echo ""
956
+ @echo "Step 4/4. Deleting profile data ..."
957
+ $(MAKE) ARCH=$(ARCH) COMP=$(COMP) profileclean
958
+
959
+ strip:
960
+ $(STRIP) $(EXE)
961
+
962
+ install:
963
+ -mkdir -p -m 755 $(BINDIR)
964
+ -cp $(EXE) $(BINDIR)
965
+ $(STRIP) $(BINDIR)/$(EXE)
966
+
967
+ # clean all
968
+ clean: objclean profileclean
969
+ @rm -f .depend *~ core
970
+
971
+ # clean binaries and objects
972
+ objclean:
973
+ @rm -f stockfish stockfish.exe *.o ./syzygy/*.o ./nnue/*.o ./nnue/features/*.o
974
+
975
+ # clean auxiliary profiling files
976
+ profileclean:
977
+ @rm -rf profdir
978
+ @rm -f bench.txt *.gcda *.gcno ./syzygy/*.gcda ./nnue/*.gcda ./nnue/features/*.gcda *.s PGOBENCH.out
979
+ @rm -f stockfish.profdata *.profraw
980
+ @rm -f stockfish.*args*
981
+ @rm -f stockfish.*lt*
982
+ @rm -f stockfish.res
983
+ @rm -f ./-lstdc++.res
984
+
985
+ # evaluation network (nnue)
986
+ net:
987
+ @$(SHELL) ../scripts/net.sh
988
+
989
+ format:
990
+ $(CLANG-FORMAT) -i $(SRCS) $(HEADERS) -style=file
991
+
992
+ # default target
993
+ default:
994
+ help
995
+
996
+ ### ==========================================================================
997
+ ### Section 5. Private Targets
998
+ ### ==========================================================================
999
+
1000
+ all: $(EXE) .depend
1001
+
1002
+ config-sanity: net
1003
+ @echo ""
1004
+ @echo "Config:" && \
1005
+ echo "debug: '$(debug)'" && \
1006
+ echo "sanitize: '$(sanitize)'" && \
1007
+ echo "optimize: '$(optimize)'" && \
1008
+ echo "arch: '$(arch)'" && \
1009
+ echo "bits: '$(bits)'" && \
1010
+ echo "kernel: '$(KERNEL)'" && \
1011
+ echo "os: '$(OS)'" && \
1012
+ echo "prefetch: '$(prefetch)'" && \
1013
+ echo "popcnt: '$(popcnt)'" && \
1014
+ echo "pext: '$(pext)'" && \
1015
+ echo "sse: '$(sse)'" && \
1016
+ echo "mmx: '$(mmx)'" && \
1017
+ echo "sse2: '$(sse2)'" && \
1018
+ echo "ssse3: '$(ssse3)'" && \
1019
+ echo "sse41: '$(sse41)'" && \
1020
+ echo "avx2: '$(avx2)'" && \
1021
+ echo "avxvnni: '$(avxvnni)'" && \
1022
+ echo "avx512: '$(avx512)'" && \
1023
+ echo "vnni256: '$(vnni256)'" && \
1024
+ echo "vnni512: '$(vnni512)'" && \
1025
+ echo "altivec: '$(altivec)'" && \
1026
+ echo "vsx: '$(vsx)'" && \
1027
+ echo "neon: '$(neon)'" && \
1028
+ echo "dotprod: '$(dotprod)'" && \
1029
+ echo "arm_version: '$(arm_version)'" && \
1030
+ echo "lsx: '$(lsx)'" && \
1031
+ echo "lasx: '$(lasx)'" && \
1032
+ echo "target_windows: '$(target_windows)'" && \
1033
+ echo "" && \
1034
+ echo "Flags:" && \
1035
+ echo "CXX: $(CXX)" && \
1036
+ echo "CXXFLAGS: $(CXXFLAGS)" && \
1037
+ echo "LDFLAGS: $(LDFLAGS)" && \
1038
+ echo "" && \
1039
+ echo "Testing config sanity. If this fails, try 'make help' ..." && \
1040
+ echo "" && \
1041
+ (test "$(debug)" = "yes" || test "$(debug)" = "no") && \
1042
+ (test "$(optimize)" = "yes" || test "$(optimize)" = "no") && \
1043
+ (test "$(SUPPORTED_ARCH)" = "true") && \
1044
+ (test "$(arch)" = "any" || test "$(arch)" = "x86_64" || test "$(arch)" = "i386" || \
1045
+ test "$(arch)" = "ppc64" || test "$(arch)" = "ppc" || test "$(arch)" = "e2k" || \
1046
+ test "$(arch)" = "armv7" || test "$(arch)" = "armv8" || test "$(arch)" = "arm64" || \
1047
+ test "$(arch)" = "riscv64" || test "$(arch)" = "loongarch64") && \
1048
+ (test "$(bits)" = "32" || test "$(bits)" = "64") && \
1049
+ (test "$(prefetch)" = "yes" || test "$(prefetch)" = "no") && \
1050
+ (test "$(popcnt)" = "yes" || test "$(popcnt)" = "no") && \
1051
+ (test "$(pext)" = "yes" || test "$(pext)" = "no") && \
1052
+ (test "$(sse)" = "yes" || test "$(sse)" = "no") && \
1053
+ (test "$(mmx)" = "yes" || test "$(mmx)" = "no") && \
1054
+ (test "$(sse2)" = "yes" || test "$(sse2)" = "no") && \
1055
+ (test "$(ssse3)" = "yes" || test "$(ssse3)" = "no") && \
1056
+ (test "$(sse41)" = "yes" || test "$(sse41)" = "no") && \
1057
+ (test "$(avx2)" = "yes" || test "$(avx2)" = "no") && \
1058
+ (test "$(avx512)" = "yes" || test "$(avx512)" = "no") && \
1059
+ (test "$(vnni256)" = "yes" || test "$(vnni256)" = "no") && \
1060
+ (test "$(vnni512)" = "yes" || test "$(vnni512)" = "no") && \
1061
+ (test "$(altivec)" = "yes" || test "$(altivec)" = "no") && \
1062
+ (test "$(vsx)" = "yes" || test "$(vsx)" = "no") && \
1063
+ (test "$(neon)" = "yes" || test "$(neon)" = "no") && \
1064
+ (test "$(lsx)" = "yes" || test "$(lsx)" = "no") && \
1065
+ (test "$(lasx)" = "yes" || test "$(lasx)" = "no") && \
1066
+ (test "$(comp)" = "gcc" || test "$(comp)" = "icx" || test "$(comp)" = "mingw" || \
1067
+ test "$(comp)" = "clang" || test "$(comp)" = "armv7a-linux-androideabi16-clang" || \
1068
+ test "$(comp)" = "aarch64-linux-android21-clang")
1069
+
1070
+ $(EXE): $(OBJS)
1071
+ +$(CXX) -o $@ $(OBJS) $(LDFLAGS)
1072
+
1073
+ # Force recompilation to ensure version info is up-to-date
1074
+ misc.o: FORCE
1075
+ FORCE:
1076
+
1077
+ clang-profile-make:
1078
+ $(MAKE) ARCH=$(ARCH) COMP=$(COMP) \
1079
+ EXTRACXXFLAGS='-fprofile-generate ' \
1080
+ EXTRALDFLAGS=' -fprofile-generate' \
1081
+ all
1082
+
1083
+ clang-profile-use:
1084
+ $(XCRUN) llvm-profdata merge -output=stockfish.profdata *.profraw
1085
+ $(MAKE) ARCH=$(ARCH) COMP=$(COMP) \
1086
+ EXTRACXXFLAGS='-fprofile-use=stockfish.profdata' \
1087
+ EXTRALDFLAGS='-fprofile-use ' \
1088
+ all
1089
+
1090
+ gcc-profile-make:
1091
+ @mkdir -p profdir
1092
+ $(MAKE) ARCH=$(ARCH) COMP=$(COMP) \
1093
+ EXTRACXXFLAGS='-fprofile-generate=profdir' \
1094
+ EXTRACXXFLAGS+=$(EXTRAPROFILEFLAGS) \
1095
+ EXTRALDFLAGS='-lgcov' \
1096
+ all
1097
+
1098
+ gcc-profile-use:
1099
+ $(MAKE) ARCH=$(ARCH) COMP=$(COMP) \
1100
+ EXTRACXXFLAGS='-fprofile-use=profdir -fno-peel-loops -fno-tracer' \
1101
+ EXTRACXXFLAGS+=$(EXTRAPROFILEFLAGS) \
1102
+ EXTRALDFLAGS='-lgcov' \
1103
+ all
1104
+
1105
+ icx-profile-make:
1106
+ $(MAKE) ARCH=$(ARCH) COMP=$(COMP) \
1107
+ EXTRACXXFLAGS='-fprofile-instr-generate ' \
1108
+ EXTRALDFLAGS=' -fprofile-instr-generate' \
1109
+ all
1110
+
1111
+ icx-profile-use:
1112
+ $(XCRUN) llvm-profdata merge -output=stockfish.profdata *.profraw
1113
+ $(MAKE) ARCH=$(ARCH) COMP=$(COMP) \
1114
+ EXTRACXXFLAGS='-fprofile-instr-use=stockfish.profdata' \
1115
+ EXTRALDFLAGS='-fprofile-use ' \
1116
+ all
1117
+
1118
+ .depend: $(SRCS)
1119
+ -@$(CXX) $(DEPENDFLAGS) -MM $(SRCS) > $@ 2> /dev/null
1120
+
1121
+ ifeq (, $(filter $(MAKECMDGOALS), help strip install clean net objclean profileclean config-sanity))
1122
+ -include .depend
1123
+ endif
stockfish/src/benchmark.cpp ADDED
@@ -0,0 +1,512 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /*
2
+ Stockfish, a UCI chess playing engine derived from Glaurung 2.1
3
+ Copyright (C) 2004-2025 The Stockfish developers (see AUTHORS file)
4
+
5
+ Stockfish is free software: you can redistribute it and/or modify
6
+ it under the terms of the GNU General Public License as published by
7
+ the Free Software Foundation, either version 3 of the License, or
8
+ (at your option) any later version.
9
+
10
+ Stockfish is distributed in the hope that it will be useful,
11
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
12
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13
+ GNU General Public License for more details.
14
+
15
+ You should have received a copy of the GNU General Public License
16
+ along with this program. If not, see <http://www.gnu.org/licenses/>.
17
+ */
18
+
19
+ #include "benchmark.h"
20
+ #include "numa.h"
21
+
22
+ #include <cstdlib>
23
+ #include <fstream>
24
+ #include <iostream>
25
+ #include <vector>
26
+
27
+ namespace {
28
+
29
+ // clang-format off
30
+ const std::vector<std::string> Defaults = {
31
+ "setoption name UCI_Chess960 value false",
32
+ "rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1",
33
+ "r3k2r/p1ppqpb1/bn2pnp1/3PN3/1p2P3/2N2Q1p/PPPBBPPP/R3K2R w KQkq - 0 10",
34
+ "8/2p5/3p4/KP5r/1R3p1k/8/4P1P1/8 w - - 0 11",
35
+ "4rrk1/pp1n3p/3q2pQ/2p1pb2/2PP4/2P3N1/P2B2PP/4RRK1 b - - 7 19",
36
+ "rq3rk1/ppp2ppp/1bnpb3/3N2B1/3NP3/7P/PPPQ1PP1/2KR3R w - - 7 14 moves d4e6",
37
+ "r1bq1r1k/1pp1n1pp/1p1p4/4p2Q/4Pp2/1BNP4/PPP2PPP/3R1RK1 w - - 2 14 moves g2g4",
38
+ "r3r1k1/2p2ppp/p1p1bn2/8/1q2P3/2NPQN2/PPP3PP/R4RK1 b - - 2 15",
39
+ "r1bbk1nr/pp3p1p/2n5/1N4p1/2Np1B2/8/PPP2PPP/2KR1B1R w kq - 0 13",
40
+ "r1bq1rk1/ppp1nppp/4n3/3p3Q/3P4/1BP1B3/PP1N2PP/R4RK1 w - - 1 16",
41
+ "4r1k1/r1q2ppp/ppp2n2/4P3/5Rb1/1N1BQ3/PPP3PP/R5K1 w - - 1 17",
42
+ "2rqkb1r/ppp2p2/2npb1p1/1N1Nn2p/2P1PP2/8/PP2B1PP/R1BQK2R b KQ - 0 11",
43
+ "r1bq1r1k/b1p1npp1/p2p3p/1p6/3PP3/1B2NN2/PP3PPP/R2Q1RK1 w - - 1 16",
44
+ "3r1rk1/p5pp/bpp1pp2/8/q1PP1P2/b3P3/P2NQRPP/1R2B1K1 b - - 6 22",
45
+ "r1q2rk1/2p1bppp/2Pp4/p6b/Q1PNp3/4B3/PP1R1PPP/2K4R w - - 2 18",
46
+ "4k2r/1pb2ppp/1p2p3/1R1p4/3P4/2r1PN2/P4PPP/1R4K1 b - - 3 22",
47
+ "3q2k1/pb3p1p/4pbp1/2r5/PpN2N2/1P2P2P/5PP1/Q2R2K1 b - - 4 26",
48
+ "6k1/6p1/6Pp/ppp5/3pn2P/1P3K2/1PP2P2/3N4 b - - 0 1",
49
+ "3b4/5kp1/1p1p1p1p/pP1PpP1P/P1P1P3/3KN3/8/8 w - - 0 1",
50
+ "2K5/p7/7P/5pR1/8/5k2/r7/8 w - - 0 1 moves g5g6 f3e3 g6g5 e3f3",
51
+ "8/6pk/1p6/8/PP3p1p/5P2/4KP1q/3Q4 w - - 0 1",
52
+ "7k/3p2pp/4q3/8/4Q3/5Kp1/P6b/8 w - - 0 1",
53
+ "8/2p5/8/2kPKp1p/2p4P/2P5/3P4/8 w - - 0 1",
54
+ "8/1p3pp1/7p/5P1P/2k3P1/8/2K2P2/8 w - - 0 1",
55
+ "8/pp2r1k1/2p1p3/3pP2p/1P1P1P1P/P5KR/8/8 w - - 0 1",
56
+ "8/3p4/p1bk3p/Pp6/1Kp1PpPp/2P2P1P/2P5/5B2 b - - 0 1",
57
+ "5k2/7R/4P2p/5K2/p1r2P1p/8/8/8 b - - 0 1",
58
+ "6k1/6p1/P6p/r1N5/5p2/7P/1b3PP1/4R1K1 w - - 0 1",
59
+ "1r3k2/4q3/2Pp3b/3Bp3/2Q2p2/1p1P2P1/1P2KP2/3N4 w - - 0 1",
60
+ "6k1/4pp1p/3p2p1/P1pPb3/R7/1r2P1PP/3B1P2/6K1 w - - 0 1",
61
+ "8/3p3B/5p2/5P2/p7/PP5b/k7/6K1 w - - 0 1",
62
+ "5rk1/q6p/2p3bR/1pPp1rP1/1P1Pp3/P3B1Q1/1K3P2/R7 w - - 93 90",
63
+ "4rrk1/1p1nq3/p7/2p1P1pp/3P2bp/3Q1Bn1/PPPB4/1K2R1NR w - - 40 21",
64
+ "r3k2r/3nnpbp/q2pp1p1/p7/Pp1PPPP1/4BNN1/1P5P/R2Q1RK1 w kq - 0 16",
65
+ "3Qb1k1/1r2ppb1/pN1n2q1/Pp1Pp1Pr/4P2p/4BP2/4B1R1/1R5K b - - 11 40",
66
+ "4k3/3q1r2/1N2r1b1/3ppN2/2nPP3/1B1R2n1/2R1Q3/3K4 w - - 5 1",
67
+
68
+ // 5-man positions
69
+ "8/8/8/8/5kp1/P7/8/1K1N4 w - - 0 1", // Kc2 - mate
70
+ "8/8/8/5N2/8/p7/8/2NK3k w - - 0 1", // Na2 - mate
71
+ "8/3k4/8/8/8/4B3/4KB2/2B5 w - - 0 1", // draw
72
+
73
+ // 6-man positions
74
+ "8/8/1P6/5pr1/8/4R3/7k/2K5 w - - 0 1", // Re5 - mate
75
+ "8/2p4P/8/kr6/6R1/8/8/1K6 w - - 0 1", // Ka2 - mate
76
+ "8/8/3P3k/8/1p6/8/1P6/1K3n2 b - - 0 1", // Nd2 - draw
77
+
78
+ // 7-man positions
79
+ "8/R7/2q5/8/6k1/8/1P5p/K6R w - - 0 124", // Draw
80
+
81
+ // Mate and stalemate positions
82
+ "6k1/3b3r/1p1p4/p1n2p2/1PPNpP1q/P3Q1p1/1R1RB1P1/5K2 b - - 0 1",
83
+ "r2r1n2/pp2bk2/2p1p2p/3q4/3PN1QP/2P3R1/P4PP1/5RK1 w - - 0 1",
84
+ "8/8/8/8/8/6k1/6p1/6K1 w - -",
85
+ "7k/7P/6K1/8/3B4/8/8/8 b - -",
86
+
87
+ // Chess 960
88
+ "setoption name UCI_Chess960 value true",
89
+ "bbqnnrkr/pppppppp/8/8/8/8/PPPPPPPP/BBQNNRKR w HFhf - 0 1 moves g2g3 d7d5 d2d4 c8h3 c1g5 e8d6 g5e7 f7f6",
90
+ "nqbnrkrb/pppppppp/8/8/8/8/PPPPPPPP/NQBNRKRB w KQkq - 0 1",
91
+ "setoption name UCI_Chess960 value false"
92
+ };
93
+ // clang-format on
94
+
95
+ // clang-format off
96
+ // human-randomly picked 5 games with <60 moves from
97
+ // https://tests.stockfishchess.org/tests/view/665c71f9fd45fb0f907c21e0
98
+ // only moves for one side
99
+ const std::vector<std::vector<std::string>> BenchmarkPositions = {
100
+ {
101
+ "rnbq1k1r/ppp1bppp/4pn2/8/2B5/2NP1N2/PPP2PPP/R1BQR1K1 b - - 2 8",
102
+ "rnbq1k1r/pp2bppp/4pn2/2p5/2B2B2/2NP1N2/PPP2PPP/R2QR1K1 b - - 1 9",
103
+ "r1bq1k1r/pp2bppp/2n1pn2/2p5/2B1NB2/3P1N2/PPP2PPP/R2QR1K1 b - - 3 10",
104
+ "r1bq1k1r/pp2bppp/2n1p3/2p5/2B1PB2/5N2/PPP2PPP/R2QR1K1 b - - 0 11",
105
+ "r1b2k1r/pp2bppp/2n1p3/2p5/2B1PB2/5N2/PPP2PPP/3RR1K1 b - - 0 12",
106
+ "r1b1k2r/pp2bppp/2n1p3/2p5/2B1PB2/2P2N2/PP3PPP/3RR1K1 b - - 0 13",
107
+ "r1b1k2r/1p2bppp/p1n1p3/2p5/4PB2/2P2N2/PP2BPPP/3RR1K1 b - - 1 14",
108
+ "r1b1k2r/4bppp/p1n1p3/1pp5/P3PB2/2P2N2/1P2BPPP/3RR1K1 b - - 0 15",
109
+ "r1b1k2r/4bppp/p1n1p3/1P6/2p1PB2/2P2N2/1P2BPPP/3RR1K1 b - - 0 16",
110
+ "r1b1k2r/4bppp/2n1p3/1p6/2p1PB2/1PP2N2/4BPPP/3RR1K1 b - - 0 17",
111
+ "r3k2r/3bbppp/2n1p3/1p6/2P1PB2/2P2N2/4BPPP/3RR1K1 b - - 0 18",
112
+ "r3k2r/3bbppp/2n1p3/8/1pP1P3/2P2N2/3BBPPP/3RR1K1 b - - 1 19",
113
+ "1r2k2r/3bbppp/2n1p3/8/1pPNP3/2P5/3BBPPP/3RR1K1 b - - 3 20",
114
+ "1r2k2r/3bbppp/2n1p3/8/2PNP3/2B5/4BPPP/3RR1K1 b - - 0 21",
115
+ "1r2k2r/3bb1pp/2n1pp2/1N6/2P1P3/2B5/4BPPP/3RR1K1 b - - 1 22",
116
+ "1r2k2r/3b2pp/2n1pp2/1N6/1BP1P3/8/4BPPP/3RR1K1 b - - 0 23",
117
+ "1r2k2r/3b2pp/4pp2/1N6/1nP1P3/8/3RBPPP/4R1K1 b - - 1 24",
118
+ "1r5r/3bk1pp/4pp2/1N6/1nP1PP2/8/3RB1PP/4R1K1 b - - 0 25",
119
+ "1r5r/3bk1pp/2n1pp2/1N6/2P1PP2/8/3RBKPP/4R3 b - - 2 26",
120
+ "1r5r/3bk1pp/2n2p2/1N2p3/2P1PP2/6P1/3RBK1P/4R3 b - - 0 27",
121
+ "1r1r4/3bk1pp/2n2p2/1N2p3/2P1PP2/6P1/3RBK1P/R7 b - - 2 28",
122
+ "1r1r4/N3k1pp/2n1bp2/4p3/2P1PP2/6P1/3RBK1P/R7 b - - 4 29",
123
+ "1r1r4/3bk1pp/2N2p2/4p3/2P1PP2/6P1/3RBK1P/R7 b - - 0 30",
124
+ "1r1R4/4k1pp/2b2p2/4p3/2P1PP2/6P1/4BK1P/R7 b - - 0 31",
125
+ "3r4/4k1pp/2b2p2/4P3/2P1P3/6P1/4BK1P/R7 b - - 0 32",
126
+ "3r4/R3k1pp/2b5/4p3/2P1P3/6P1/4BK1P/8 b - - 1 33",
127
+ "8/3rk1pp/2b5/R3p3/2P1P3/6P1/4BK1P/8 b - - 3 34",
128
+ "8/3r2pp/2bk4/R1P1p3/4P3/6P1/4BK1P/8 b - - 0 35",
129
+ "8/2kr2pp/2b5/R1P1p3/4P3/4K1P1/4B2P/8 b - - 2 36",
130
+ "1k6/3r2pp/2b5/RBP1p3/4P3/4K1P1/7P/8 b - - 4 37",
131
+ "8/1k1r2pp/2b5/R1P1p3/4P3/3BK1P1/7P/8 b - - 6 38",
132
+ "1k6/3r2pp/2b5/2P1p3/4P3/3BK1P1/7P/R7 b - - 8 39",
133
+ "1k6/r5pp/2b5/2P1p3/4P3/3BK1P1/7P/5R2 b - - 10 40",
134
+ "1k3R2/6pp/2b5/2P1p3/4P3/r2BK1P1/7P/8 b - - 12 41",
135
+ "5R2/2k3pp/2b5/2P1p3/4P3/r2B2P1/3K3P/8 b - - 14 42",
136
+ "5R2/2k3pp/2b5/2P1p3/4P3/3BK1P1/r6P/8 b - - 16 43",
137
+ "5R2/2k3pp/2b5/2P1p3/4P3/r2B2P1/4K2P/8 b - - 18 44",
138
+ "5R2/2k3pp/2b5/2P1p3/4P3/3B1KP1/r6P/8 b - - 20 45",
139
+ "8/2k2Rpp/2b5/2P1p3/4P3/r2B1KP1/7P/8 b - - 22 46",
140
+ "3k4/5Rpp/2b5/2P1p3/4P3/r2B2P1/4K2P/8 b - - 24 47",
141
+ "3k4/5Rpp/2b5/2P1p3/4P3/3B1KP1/r6P/8 b - - 26 48",
142
+ "3k4/5Rpp/2b5/2P1p3/4P3/r2B2P1/4K2P/8 b - - 28 49",
143
+ "3k4/5Rpp/2b5/2P1p3/4P3/3BK1P1/r6P/8 b - - 30 50",
144
+ "3k4/5Rpp/2b5/2P1p3/4P3/r2B2P1/3K3P/8 b - - 32 51",
145
+ "3k4/5Rpp/2b5/2P1p3/4P3/2KB2P1/r6P/8 b - - 34 52",
146
+ "3k4/5Rpp/2b5/2P1p3/4P3/r2B2P1/2K4P/8 b - - 36 53",
147
+ "3k4/5Rpp/2b5/2P1p3/4P3/1K1B2P1/r6P/8 b - - 38 54",
148
+ "3k4/6Rp/2b5/2P1p3/4P3/1K1B2P1/7r/8 b - - 0 55",
149
+ "3k4/8/2b3Rp/2P1p3/4P3/1K1B2P1/7r/8 b - - 1 56",
150
+ "8/2k3R1/2b4p/2P1p3/4P3/1K1B2P1/7r/8 b - - 3 57",
151
+ "3k4/8/2b3Rp/2P1p3/4P3/1K1B2P1/7r/8 b - - 5 58",
152
+ "8/2k5/2b3Rp/2P1p3/1K2P3/3B2P1/7r/8 b - - 7 59",
153
+ "8/2k5/2b3Rp/2P1p3/4P3/2KB2P1/3r4/8 b - - 9 60",
154
+ "8/2k5/2b3Rp/2P1p3/1K2P3/3B2P1/6r1/8 b - - 11 61",
155
+ "8/2k5/2b3Rp/2P1p3/4P3/2KB2P1/3r4/8 b - - 13 62",
156
+ "8/2k5/2b3Rp/2P1p3/2K1P3/3B2P1/6r1/8 b - - 15 63",
157
+ "4b3/2k3R1/7p/2P1p3/2K1P3/3B2P1/6r1/8 b - - 17 64",
158
+ },
159
+ {
160
+ "r1bqkbnr/npp1pppp/p7/3P4/4pB2/2N5/PPP2PPP/R2QKBNR w KQkq - 1 6",
161
+ "r1bqkb1r/npp1pppp/p4n2/3P4/4pB2/2N5/PPP1QPPP/R3KBNR w KQkq - 3 7",
162
+ "r2qkb1r/npp1pppp/p4n2/3P1b2/4pB2/2N5/PPP1QPPP/2KR1BNR w kq - 5 8",
163
+ "r2qkb1r/1pp1pppp/p4n2/1n1P1b2/4pB2/2N4P/PPP1QPP1/2KR1BNR w kq - 1 9",
164
+ "r2qkb1r/1pp1pppp/5n2/1p1P1b2/4pB2/7P/PPP1QPP1/2KR1BNR w kq - 0 10",
165
+ "r2qkb1r/1ppbpppp/5n2/1Q1P4/4pB2/7P/PPP2PP1/2KR1BNR w kq - 1 11",
166
+ "3qkb1r/1Qpbpppp/5n2/3P4/4pB2/7P/rPP2PP1/2KR1BNR w k - 0 12",
167
+ "q3kb1r/1Qpbpppp/5n2/3P4/4pB2/7P/rPP2PP1/1K1R1BNR w k - 2 13",
168
+ "r3kb1r/2pbpppp/5n2/3P4/4pB2/7P/1PP2PP1/1K1R1BNR w k - 0 14",
169
+ "r3kb1r/2Bb1ppp/4pn2/3P4/4p3/7P/1PP2PP1/1K1R1BNR w k - 0 15",
170
+ "r3kb1r/2Bb2pp/4pn2/8/4p3/7P/1PP2PP1/1K1R1BNR w k - 0 16",
171
+ "r3k2r/2Bb2pp/4pn2/2b5/4p3/7P/1PP1NPP1/1K1R1B1R w k - 2 17",
172
+ "r6r/2Bbk1pp/4pn2/2b5/3Np3/7P/1PP2PP1/1K1R1B1R w - - 4 18",
173
+ "r6r/b2bk1pp/4pn2/4B3/3Np3/7P/1PP2PP1/1K1R1B1R w - - 6 19",
174
+ "r1r5/b2bk1pp/4pn2/4B3/2BNp3/7P/1PP2PP1/1K1R3R w - - 8 20",
175
+ "r7/b2bk1pp/4pn2/2r1B3/2BNp3/1P5P/2P2PP1/1K1R3R w - - 1 21",
176
+ "rb6/3bk1pp/4pn2/2r1B3/2BNpP2/1P5P/2P3P1/1K1R3R w - - 1 22",
177
+ "1r6/3bk1pp/4pn2/2r5/2BNpP2/1P5P/2P3P1/1K1R3R w - - 0 23",
178
+ "1r6/3bk1p1/4pn1p/2r5/2BNpP2/1P5P/2P3P1/2KR3R w - - 0 24",
179
+ "8/3bk1p1/1r2pn1p/2r5/2BNpP1P/1P6/2P3P1/2KR3R w - - 1 25",
180
+ "8/3bk3/1r2pnpp/2r5/2BNpP1P/1P6/2P3P1/2K1R2R w - - 0 26",
181
+ "2b5/4k3/1r2pnpp/2r5/2BNpP1P/1P4P1/2P5/2K1R2R w - - 1 27",
182
+ "8/1b2k3/1r2pnpp/2r5/2BNpP1P/1P4P1/2P5/2K1R1R1 w - - 3 28",
183
+ "8/1b1nk3/1r2p1pp/2r5/2BNpPPP/1P6/2P5/2K1R1R1 w - - 1 29",
184
+ "8/1b2k3/1r2p1pp/2r1nP2/2BNp1PP/1P6/2P5/2K1R1R1 w - - 1 30",
185
+ "8/1b2k3/1r2p1p1/2r1nPp1/2BNp2P/1P6/2P5/2K1R1R1 w - - 0 31",
186
+ "8/1b2k3/1r2p1n1/2r3p1/2BNp2P/1P6/2P5/2K1R1R1 w - - 0 32",
187
+ "8/1b2k3/1r2p1n1/6r1/2BNp2P/1P6/2P5/2K1R3 w - - 0 33",
188
+ "8/1b2k3/1r2p3/4n1P1/2BNp3/1P6/2P5/2K1R3 w - - 1 34",
189
+ "8/1b2k3/1r2p3/4n1P1/2BN4/1P2p3/2P5/2K4R w - - 0 35",
190
+ "8/1b2k3/1r2p2R/6P1/2nN4/1P2p3/2P5/2K5 w - - 0 36",
191
+ "8/1b2k3/3rp2R/6P1/2PN4/4p3/2P5/2K5 w - - 1 37",
192
+ "8/4k3/3rp2R/6P1/2PN4/2P1p3/6b1/2K5 w - - 1 38",
193
+ "8/4k3/r3p2R/2P3P1/3N4/2P1p3/6b1/2K5 w - - 1 39",
194
+ "8/3k4/r3p2R/2P2NP1/8/2P1p3/6b1/2K5 w - - 3 40",
195
+ "8/3k4/4p2R/2P3P1/8/2P1N3/6b1/r1K5 w - - 1 41",
196
+ "8/3k4/4p2R/2P3P1/8/2P1N3/3K2b1/6r1 w - - 3 42",
197
+ "8/3k4/4p2R/2P3P1/8/2PKNb2/8/6r1 w - - 5 43",
198
+ "8/4k3/4p1R1/2P3P1/8/2PKNb2/8/6r1 w - - 7 44",
199
+ "8/4k3/4p1R1/2P3P1/3K4/2P1N3/8/6rb w - - 9 45",
200
+ "8/3k4/4p1R1/2P1K1P1/8/2P1N3/8/6rb w - - 11 46",
201
+ "8/3k4/4p1R1/2P3P1/5K2/2P1N3/8/4r2b w - - 13 47",
202
+ "8/3k4/2b1p2R/2P3P1/5K2/2P1N3/8/4r3 w - - 15 48",
203
+ "8/3k4/2b1p3/2P3P1/5K2/2P1N2R/8/6r1 w - - 17 49",
204
+ "2k5/7R/2b1p3/2P3P1/5K2/2P1N3/8/6r1 w - - 19 50",
205
+ "2k5/7R/4p3/2P3P1/b1P2K2/4N3/8/6r1 w - - 1 51",
206
+ "2k5/3bR3/4p3/2P3P1/2P2K2/4N3/8/6r1 w - - 3 52",
207
+ "3k4/3b2R1/4p3/2P3P1/2P2K2/4N3/8/6r1 w - - 5 53",
208
+ "3kb3/6R1/4p1P1/2P5/2P2K2/4N3/8/6r1 w - - 1 54",
209
+ "3kb3/6R1/4p1P1/2P5/2P2KN1/8/8/2r5 w - - 3 55",
210
+ "3kb3/6R1/4p1P1/2P1N3/2P2K2/8/8/5r2 w - - 5 56",
211
+ "3kb3/6R1/4p1P1/2P1N3/2P5/4K3/8/4r3 w - - 7 57",
212
+ },
213
+ {
214
+ "rnbq1rk1/ppp1npb1/4p1p1/3P3p/3PP3/2N2N2/PP2BPPP/R1BQ1RK1 b - - 0 8",
215
+ "rnbq1rk1/ppp1npb1/6p1/3pP2p/3P4/2N2N2/PP2BPPP/R1BQ1RK1 b - - 0 9",
216
+ "rn1q1rk1/ppp1npb1/6p1/3pP2p/3P2b1/2N2N2/PP2BPPP/R1BQR1K1 b - - 2 10",
217
+ "r2q1rk1/ppp1npb1/2n3p1/3pP2p/3P2bN/2N5/PP2BPPP/R1BQR1K1 b - - 4 11",
218
+ "r4rk1/pppqnpb1/2n3p1/3pP2p/3P2bN/2N4P/PP2BPP1/R1BQR1K1 b - - 0 12",
219
+ "r4rk1/pppqnpb1/2n3p1/3pP2p/3P3N/7P/PP2NPP1/R1BQR1K1 b - - 0 13",
220
+ "r4rk1/pppq1pb1/2n3p1/3pPN1p/3P4/7P/PP2NPP1/R1BQR1K1 b - - 0 14",
221
+ "r4rk1/ppp2pb1/2n3p1/3pPq1p/3P1N2/7P/PP3PP1/R1BQR1K1 b - - 1 15",
222
+ "r4rk1/pppq1pb1/2n3p1/3pP2p/P2P1N2/7P/1P3PP1/R1BQR1K1 b - - 0 16",
223
+ "r2n1rk1/pppq1pb1/6p1/3pP2p/P2P1N2/R6P/1P3PP1/2BQR1K1 b - - 2 17",
224
+ "r4rk1/pppq1pb1/4N1p1/3pP2p/P2P4/R6P/1P3PP1/2BQR1K1 b - - 0 18",
225
+ "r4rk1/ppp2pb1/4q1p1/3pP1Bp/P2P4/R6P/1P3PP1/3QR1K1 b - - 1 19",
226
+ "r3r1k1/ppp2pb1/4q1p1/3pP1Bp/P2P1P2/R6P/1P4P1/3QR1K1 b - - 0 20",
227
+ "r3r1k1/ppp3b1/4qpp1/3pP2p/P2P1P1B/R6P/1P4P1/3QR1K1 b - - 1 21",
228
+ "r3r1k1/ppp3b1/4q1p1/3pP2p/P4P1B/R6P/1P4P1/3QR1K1 b - - 0 22",
229
+ "r4rk1/ppp3b1/4q1p1/3pP1Bp/P4P2/R6P/1P4P1/3QR1K1 b - - 2 23",
230
+ "r4rk1/pp4b1/4q1p1/2ppP1Bp/P4P2/3R3P/1P4P1/3QR1K1 b - - 1 24",
231
+ "r4rk1/pp4b1/4q1p1/2p1P1Bp/P2p1PP1/3R3P/1P6/3QR1K1 b - - 0 25",
232
+ "r4rk1/pp4b1/4q1p1/2p1P1B1/P2p1PP1/3R4/1P6/3QR1K1 b - - 0 26",
233
+ "r5k1/pp3rb1/4q1p1/2p1P1B1/P2p1PP1/6R1/1P6/3QR1K1 b - - 2 27",
234
+ "5rk1/pp3rb1/4q1p1/2p1P1B1/P2pRPP1/6R1/1P6/3Q2K1 b - - 4 28",
235
+ "5rk1/1p3rb1/p3q1p1/P1p1P1B1/3pRPP1/6R1/1P6/3Q2K1 b - - 0 29",
236
+ "4r1k1/1p3rb1/p3q1p1/P1p1P1B1/3pRPP1/1P4R1/8/3Q2K1 b - - 0 30",
237
+ "4r1k1/5rb1/pP2q1p1/2p1P1B1/3pRPP1/1P4R1/8/3Q2K1 b - - 0 31",
238
+ "4r1k1/5rb1/pq4p1/2p1P1B1/3pRPP1/1P4R1/4Q3/6K1 b - - 1 32",
239
+ "4r1k1/1r4b1/pq4p1/2p1P1B1/3pRPP1/1P4R1/2Q5/6K1 b - - 3 33",
240
+ "4r1k1/1r4b1/1q4p1/p1p1P1B1/3p1PP1/1P4R1/2Q5/4R1K1 b - - 1 34",
241
+ "4r1k1/3r2b1/1q4p1/p1p1P1B1/2Qp1PP1/1P4R1/8/4R1K1 b - - 3 35",
242
+ "4r1k1/3r2b1/4q1p1/p1p1P1B1/2Qp1PP1/1P4R1/5K2/4R3 b - - 5 36",
243
+ "4r1k1/3r2b1/6p1/p1p1P1B1/2Pp1PP1/6R1/5K2/4R3 b - - 0 37",
244
+ "4r1k1/3r2b1/6p1/p1p1P1B1/2P2PP1/3p2R1/5K2/3R4 b - - 1 38",
245
+ "5rk1/3r2b1/6p1/p1p1P1B1/2P2PP1/3p2R1/8/3RK3 b - - 3 39",
246
+ "5rk1/6b1/6p1/p1p1P1B1/2Pr1PP1/3R4/8/3RK3 b - - 0 40",
247
+ "5rk1/3R2b1/6p1/p1p1P1B1/2r2PP1/8/8/3RK3 b - - 1 41",
248
+ "5rk1/3R2b1/6p1/p1p1P1B1/4rPP1/8/3K4/3R4 b - - 3 42",
249
+ "1r4k1/3R2b1/6p1/p1p1P1B1/4rPP1/2K5/8/3R4 b - - 5 43",
250
+ "1r4k1/3R2b1/6p1/p1p1P1B1/2K2PP1/4r3/8/3R4 b - - 7 44",
251
+ "1r3bk1/8/3R2p1/p1p1P1B1/2K2PP1/4r3/8/3R4 b - - 9 45",
252
+ "1r3bk1/8/6R1/2p1P1B1/p1K2PP1/4r3/8/3R4 b - - 0 46",
253
+ "1r3b2/5k2/R7/2p1P1B1/p1K2PP1/4r3/8/3R4 b - - 2 47",
254
+ "5b2/1r3k2/R7/2p1P1B1/p1K2PP1/4r3/8/7R b - - 4 48",
255
+ "5b2/5k2/R7/2pKP1B1/pr3PP1/4r3/8/7R b - - 6 49",
256
+ "5b2/5k2/R1K5/2p1P1B1/p2r1PP1/4r3/8/7R b - - 8 50",
257
+ "8/R4kb1/2K5/2p1P1B1/p2r1PP1/4r3/8/7R b - - 10 51",
258
+ "8/R5b1/2K3k1/2p1PPB1/p2r2P1/4r3/8/7R b - - 0 52",
259
+ "8/6R1/2K5/2p1PPk1/p2r2P1/4r3/8/7R b - - 0 53",
260
+ "8/6R1/2K5/2p1PP2/p2r1kP1/4r3/8/5R2 b - - 2 54",
261
+ "8/6R1/2K2P2/2p1P3/p2r2P1/4r1k1/8/5R2 b - - 0 55",
262
+ "8/5PR1/2K5/2p1P3/p2r2P1/4r3/6k1/5R2 b - - 0 56",
263
+ },
264
+ {
265
+ "rn1qkb1r/p1pbpppp/5n2/8/2pP4/2N5/1PQ1PPPP/R1B1KBNR w KQkq - 0 7",
266
+ "r2qkb1r/p1pbpppp/2n2n2/8/2pP4/2N2N2/1PQ1PPPP/R1B1KB1R w KQkq - 2 8",
267
+ "r2qkb1r/p1pbpppp/5n2/8/1npPP3/2N2N2/1PQ2PPP/R1B1KB1R w KQkq - 1 9",
268
+ "r2qkb1r/p1pb1ppp/4pn2/8/1npPP3/2N2N2/1P3PPP/R1BQKB1R w KQkq - 0 10",
269
+ "r2qk2r/p1pbbppp/4pn2/8/1nBPP3/2N2N2/1P3PPP/R1BQK2R w KQkq - 1 11",
270
+ "r2q1rk1/p1pbbppp/4pn2/8/1nBPP3/2N2N2/1P3PPP/R1BQ1RK1 w - - 3 12",
271
+ "r2q1rk1/2pbbppp/p3pn2/8/1nBPPB2/2N2N2/1P3PPP/R2Q1RK1 w - - 0 13",
272
+ "r2q1rk1/2p1bppp/p3pn2/1b6/1nBPPB2/2N2N2/1P3PPP/R2QR1K1 w - - 2 14",
273
+ "r2q1rk1/4bppp/p1p1pn2/1b6/1nBPPB2/1PN2N2/5PPP/R2QR1K1 w - - 0 15",
274
+ "r4rk1/3qbppp/p1p1pn2/1b6/1nBPPB2/1PN2N2/3Q1PPP/R3R1K1 w - - 2 16",
275
+ "r4rk1/1q2bppp/p1p1pn2/1b6/1nBPPB2/1PN2N1P/3Q1PP1/R3R1K1 w - - 1 17",
276
+ "r3r1k1/1q2bppp/p1p1pn2/1b6/1nBPPB2/1PN2N1P/4QPP1/R3R1K1 w - - 3 18",
277
+ "r3r1k1/1q1nbppp/p1p1p3/1b6/1nBPPB2/1PN2N1P/4QPP1/3RR1K1 w - - 5 19",
278
+ "r3rbk1/1q1n1ppp/p1p1p3/1b6/1nBPPB2/1PN2N1P/3RQPP1/4R1K1 w - - 7 20",
279
+ "r3rbk1/1q3ppp/pnp1p3/1b6/1nBPPB2/1PN2N1P/3RQPP1/4R2K w - - 9 21",
280
+ "2r1rbk1/1q3ppp/pnp1p3/1b6/1nBPPB2/1PN2N1P/3RQPP1/1R5K w - - 11 22",
281
+ "2r1rbk1/1q4pp/pnp1pp2/1b6/1nBPPB2/1PN2N1P/4QPP1/1R1R3K w - - 0 23",
282
+ "2r1rbk1/5qpp/pnp1pp2/1b6/1nBPP3/1PN1BN1P/4QPP1/1R1R3K w - - 2 24",
283
+ "2r1rbk1/5qp1/pnp1pp1p/1b6/1nBPP3/1PN1BN1P/4QPP1/1R1R2K1 w - - 0 25",
284
+ "2r1rbk1/5qp1/pnp1pp1p/1b6/2BPP3/1P2BN1P/n3QPP1/1R1R2K1 w - - 0 26",
285
+ "r3rbk1/5qp1/pnp1pp1p/1b6/2BPP3/1P2BN1P/Q4PP1/1R1R2K1 w - - 1 27",
286
+ "rr3bk1/5qp1/pnp1pp1p/1b6/2BPP3/1P2BN1P/Q4PP1/R2R2K1 w - - 3 28",
287
+ "rr2qbk1/6p1/pnp1pp1p/1b6/2BPP3/1P2BN1P/4QPP1/R2R2K1 w - - 5 29",
288
+ "rr2qbk1/6p1/1np1pp1p/pb6/2BPP3/1P1QBN1P/5PP1/R2R2K1 w - - 0 30",
289
+ "rr2qbk1/6p1/1n2pp1p/pp6/3PP3/1P1QBN1P/5PP1/R2R2K1 w - - 0 31",
290
+ "rr2qbk1/6p1/1n2pp1p/1p1P4/p3P3/1P1QBN1P/5PP1/R2R2K1 w - - 0 32",
291
+ "rr2qbk1/3n2p1/3Ppp1p/1p6/p3P3/1P1QBN1P/5PP1/R2R2K1 w - - 1 33",
292
+ "rr3bk1/3n2p1/3Ppp1p/1p5q/pP2P3/3QBN1P/5PP1/R2R2K1 w - - 1 34",
293
+ "rr3bk1/3n2p1/3Ppp1p/1p5q/1P2P3/p2QBN1P/5PP1/2RR2K1 w - - 0 35",
294
+ "1r3bk1/3n2p1/r2Ppp1p/1p5q/1P2P3/pQ2BN1P/5PP1/2RR2K1 w - - 2 36",
295
+ "1r2qbk1/2Rn2p1/r2Ppp1p/1p6/1P2P3/pQ2BN1P/5PP1/3R2K1 w - - 4 37",
296
+ "1r2qbk1/2Rn2p1/r2Ppp1p/1pB5/1P2P3/1Q3N1P/p4PP1/3R2K1 w - - 0 38",
297
+ "1r2q1k1/2Rn2p1/r2bpp1p/1pB5/1P2P3/1Q3N1P/p4PP1/R5K1 w - - 0 39",
298
+ "1r2q1k1/2Rn2p1/3rpp1p/1p6/1P2P3/1Q3N1P/p4PP1/R5K1 w - - 0 40",
299
+ "2r1q1k1/2Rn2p1/3rpp1p/1p6/1P2P3/5N1P/Q4PP1/R5K1 w - - 1 41",
300
+ "1r2q1k1/1R1n2p1/3rpp1p/1p6/1P2P3/5N1P/Q4PP1/R5K1 w - - 3 42",
301
+ "2r1q1k1/2Rn2p1/3rpp1p/1p6/1P2P3/5N1P/Q4PP1/R5K1 w - - 5 43",
302
+ "1r2q1k1/1R1n2p1/3rpp1p/1p6/1P2P3/5N1P/Q4PP1/R5K1 w - - 7 44",
303
+ "1rq3k1/R2n2p1/3rpp1p/1p6/1P2P3/5N1P/Q4PP1/R5K1 w - - 9 45",
304
+ "2q3k1/Rr1n2p1/3rpp1p/1p6/1P2P3/5N1P/4QPP1/R5K1 w - - 11 46",
305
+ "Rrq3k1/3n2p1/3rpp1p/1p6/1P2P3/5N1P/4QPP1/R5K1 w - - 13 47",
306
+ },
307
+ {
308
+ "rn1qkb1r/1pp2ppp/p4p2/3p1b2/5P2/1P2PN2/P1PP2PP/RN1QKB1R b KQkq - 1 6",
309
+ "r2qkb1r/1pp2ppp/p1n2p2/3p1b2/3P1P2/1P2PN2/P1P3PP/RN1QKB1R b KQkq - 0 7",
310
+ "r2qkb1r/1pp2ppp/p4p2/3p1b2/1n1P1P2/1P1BPN2/P1P3PP/RN1QK2R b KQkq - 2 8",
311
+ "r2qkb1r/1pp2ppp/p4p2/3p1b2/3P1P2/1P1PPN2/P5PP/RN1QK2R b KQkq - 0 9",
312
+ "r2qk2r/1pp2ppp/p2b1p2/3p1b2/3P1P2/1PNPPN2/P5PP/R2QK2R b KQkq - 2 10",
313
+ "r2qk2r/1p3ppp/p1pb1p2/3p1b2/3P1P2/1PNPPN2/P5PP/R2Q1RK1 b kq - 1 11",
314
+ "r2q1rk1/1p3ppp/p1pb1p2/3p1b2/3P1P2/1PNPPN2/P2Q2PP/R4RK1 b - - 3 12",
315
+ "r2qr1k1/1p3ppp/p1pb1p2/3p1b2/3P1P2/1P1PPN2/P2QN1PP/R4RK1 b - - 5 13",
316
+ "r3r1k1/1p3ppp/pqpb1p2/3p1b2/3P1P2/1P1PPNN1/P2Q2PP/R4RK1 b - - 7 14",
317
+ "r3r1k1/1p3ppp/pqp2p2/3p1b2/1b1P1P2/1P1PPNN1/P1Q3PP/R4RK1 b - - 9 15",
318
+ "r3r1k1/1p1b1ppp/pqp2p2/3p4/1b1P1P2/1P1PPNN1/P4QPP/R4RK1 b - - 11 16",
319
+ "2r1r1k1/1p1b1ppp/pqp2p2/3p4/1b1PPP2/1P1P1NN1/P4QPP/R4RK1 b - - 0 17",
320
+ "2r1r1k1/1p1b1ppp/pq3p2/2pp4/1b1PPP2/PP1P1NN1/5QPP/R4RK1 b - - 0 18",
321
+ "2r1r1k1/1p1b1ppp/pq3p2/2Pp4/4PP2/PPbP1NN1/5QPP/R4RK1 b - - 0 19",
322
+ "2r1r1k1/1p1b1ppp/p4p2/2Pp4/4PP2/PqbP1NN1/5QPP/RR4K1 b - - 1 20",
323
+ "2r1r1k1/1p1b1ppp/p4p2/2Pp4/q3PP2/P1bP1NN1/R4QPP/1R4K1 b - - 3 21",
324
+ "2r1r1k1/1p3ppp/p4p2/1bPP4/q4P2/P1bP1NN1/R4QPP/1R4K1 b - - 0 22",
325
+ "2r1r1k1/1p3ppp/p4p2/2PP4/q4P2/P1bb1NN1/R4QPP/2R3K1 b - - 1 23",
326
+ "2r1r1k1/1p3ppp/p2P1p2/2P5/2q2P2/P1bb1NN1/R4QPP/2R3K1 b - - 0 24",
327
+ "2rr2k1/1p3ppp/p2P1p2/2P5/2q2P2/P1bb1NN1/R4QPP/2R4K b - - 2 25",
328
+ "2rr2k1/1p3ppp/p2P1p2/2Q5/5P2/P1bb1NN1/R5PP/2R4K b - - 0 26",
329
+ "3r2k1/1p3ppp/p2P1p2/2r5/5P2/P1bb1N2/R3N1PP/2R4K b - - 1 27",
330
+ "3r2k1/1p3ppp/p2P1p2/2r5/5P2/P1b2N2/4R1PP/2R4K b - - 0 28",
331
+ "3r2k1/1p3ppp/p2P1p2/2r5/1b3P2/P4N2/4R1PP/3R3K b - - 2 29",
332
+ "3r2k1/1p2Rppp/p2P1p2/b1r5/5P2/P4N2/6PP/3R3K b - - 4 30",
333
+ "3r2k1/1R3ppp/p1rP1p2/b7/5P2/P4N2/6PP/3R3K b - - 0 31",
334
+ "3r2k1/1R3ppp/p2R1p2/b7/5P2/P4N2/6PP/7K b - - 0 32",
335
+ "6k1/1R3ppp/p2r1p2/b7/5P2/P4NP1/7P/7K b - - 0 33",
336
+ "6k1/1R3p1p/p2r1pp1/b7/5P1P/P4NP1/8/7K b - - 0 34",
337
+ "6k1/3R1p1p/pr3pp1/b7/5P1P/P4NP1/8/7K b - - 2 35",
338
+ "6k1/5p2/pr3pp1/b2R3p/5P1P/P4NP1/8/7K b - - 1 36",
339
+ "6k1/5p2/pr3pp1/7p/5P1P/P1bR1NP1/8/7K b - - 3 37",
340
+ "6k1/5p2/p1r2pp1/7p/5P1P/P1bR1NP1/6K1/8 b - - 5 38",
341
+ "6k1/5p2/p1r2pp1/b2R3p/5P1P/P4NP1/6K1/8 b - - 7 39",
342
+ "6k1/5p2/p4pp1/b2R3p/5P1P/P4NPK/2r5/8 b - - 9 40",
343
+ "6k1/2b2p2/p4pp1/7p/5P1P/P2R1NPK/2r5/8 b - - 11 41",
344
+ "6k1/2b2p2/5pp1/p6p/3N1P1P/P2R2PK/2r5/8 b - - 1 42",
345
+ "6k1/2b2p2/5pp1/p6p/3N1P1P/P1R3PK/r7/8 b - - 3 43",
346
+ "6k1/5p2/1b3pp1/p6p/5P1P/P1R3PK/r1N5/8 b - - 5 44",
347
+ "8/5pk1/1bR2pp1/p6p/5P1P/P5PK/r1N5/8 b - - 7 45",
348
+ "3b4/5pk1/2R2pp1/p4P1p/7P/P5PK/r1N5/8 b - - 0 46",
349
+ "8/4bpk1/2R2pp1/p4P1p/6PP/P6K/r1N5/8 b - - 0 47",
350
+ "8/5pk1/2R2pP1/p6p/6PP/b6K/r1N5/8 b - - 0 48",
351
+ "8/6k1/2R2pp1/p6P/7P/b6K/r1N5/8 b - - 0 49",
352
+ "8/6k1/2R2p2/p6p/7P/b5K1/r1N5/8 b - - 1 50",
353
+ "8/8/2R2pk1/p6p/7P/b4K2/r1N5/8 b - - 3 51",
354
+ "8/8/2R2pk1/p6p/7P/4NK2/rb6/8 b - - 5 52",
355
+ "2R5/8/5pk1/7p/p6P/4NK2/rb6/8 b - - 1 53",
356
+ "6R1/8/5pk1/7p/p6P/4NK2/1b6/r7 b - - 3 54",
357
+ "R7/5k2/5p2/7p/p6P/4NK2/1b6/r7 b - - 5 55",
358
+ "R7/5k2/5p2/7p/7P/p3N3/1b2K3/r7 b - - 1 56",
359
+ "8/R4k2/5p2/7p/7P/p3N3/1b2K3/7r b - - 3 57",
360
+ "8/8/5pk1/7p/R6P/p3N3/1b2K3/7r b - - 5 58",
361
+ "8/8/5pk1/7p/R6P/p7/4K3/2bN3r b - - 7 59",
362
+ "8/8/5pk1/7p/R6P/p7/4KN1r/2b5 b - - 9 60",
363
+ "8/8/5pk1/7p/R6P/p3K3/1b3N1r/8 b - - 11 61",
364
+ "8/8/R4pk1/7p/7P/p1b1K3/5N1r/8 b - - 13 62",
365
+ "8/8/5pk1/7p/7P/2b1K3/R4N1r/8 b - - 0 63",
366
+ "8/8/5pk1/7p/3K3P/8/R4N1r/4b3 b - - 2 64",
367
+ }
368
+ };
369
+ // clang-format on
370
+
371
+ } // namespace
372
+
373
+ namespace Stockfish::Benchmark {
374
+
375
+ // Builds a list of UCI commands to be run by bench. There
376
+ // are five parameters: TT size in MB, number of search threads that
377
+ // should be used, the limit value spent for each position, a file name
378
+ // where to look for positions in FEN format, and the type of the limit:
379
+ // depth, perft, nodes and movetime (in milliseconds). Examples:
380
+ //
381
+ // bench : search default positions up to depth 13
382
+ // bench 64 1 15 : search default positions up to depth 15 (TT = 64MB)
383
+ // bench 64 1 100000 default nodes : search default positions for 100K nodes each
384
+ // bench 64 4 5000 current movetime : search current position with 4 threads for 5 sec
385
+ // bench 16 1 5 blah perft : run a perft 5 on positions in file "blah"
386
+ std::vector<std::string> setup_bench(const std::string& currentFen, std::istream& is) {
387
+
388
+ std::vector<std::string> fens, list;
389
+ std::string go, token;
390
+
391
+ // Assign default values to missing arguments
392
+ std::string ttSize = (is >> token) ? token : "16";
393
+ std::string threads = (is >> token) ? token : "1";
394
+ std::string limit = (is >> token) ? token : "13";
395
+ std::string fenFile = (is >> token) ? token : "default";
396
+ std::string limitType = (is >> token) ? token : "depth";
397
+
398
+ go = limitType == "eval" ? "eval" : "go " + limitType + " " + limit;
399
+
400
+ if (fenFile == "default")
401
+ fens = Defaults;
402
+
403
+ else if (fenFile == "current")
404
+ fens.push_back(currentFen);
405
+
406
+ else
407
+ {
408
+ std::string fen;
409
+ std::ifstream file(fenFile);
410
+
411
+ if (!file.is_open())
412
+ {
413
+ std::cerr << "Unable to open file " << fenFile << std::endl;
414
+ exit(EXIT_FAILURE);
415
+ }
416
+
417
+ while (getline(file, fen))
418
+ if (!fen.empty())
419
+ fens.push_back(fen);
420
+
421
+ file.close();
422
+ }
423
+
424
+ list.emplace_back("setoption name Threads value " + threads);
425
+ list.emplace_back("setoption name Hash value " + ttSize);
426
+ list.emplace_back("ucinewgame");
427
+
428
+ for (const std::string& fen : fens)
429
+ if (fen.find("setoption") != std::string::npos)
430
+ list.emplace_back(fen);
431
+ else
432
+ {
433
+ list.emplace_back("position fen " + fen);
434
+ list.emplace_back(go);
435
+ }
436
+
437
+ return list;
438
+ }
439
+
440
+ BenchmarkSetup setup_benchmark(std::istream& is) {
441
+ // TT_SIZE_PER_THREAD is chosen such that roughly half of the hash is used all positions
442
+ // for the current sequence have been searched.
443
+ static constexpr int TT_SIZE_PER_THREAD = 128;
444
+
445
+ static constexpr int DEFAULT_DURATION_S = 150;
446
+
447
+ BenchmarkSetup setup{};
448
+
449
+ // Assign default values to missing arguments
450
+ int desiredTimeS;
451
+
452
+ if (!(is >> setup.threads))
453
+ setup.threads = get_hardware_concurrency();
454
+ else
455
+ setup.originalInvocation += std::to_string(setup.threads);
456
+
457
+ if (!(is >> setup.ttSize))
458
+ setup.ttSize = TT_SIZE_PER_THREAD * setup.threads;
459
+ else
460
+ setup.originalInvocation += " " + std::to_string(setup.ttSize);
461
+
462
+ if (!(is >> desiredTimeS))
463
+ desiredTimeS = DEFAULT_DURATION_S;
464
+ else
465
+ setup.originalInvocation += " " + std::to_string(desiredTimeS);
466
+
467
+ setup.filledInvocation += std::to_string(setup.threads) + " " + std::to_string(setup.ttSize)
468
+ + " " + std::to_string(desiredTimeS);
469
+
470
+ auto getCorrectedTime = [&](int ply) {
471
+ // time per move is fit roughly based on LTC games
472
+ // seconds = 50/{ply+15}
473
+ // ms = 50000/{ply+15}
474
+ // with this fit 10th move gets 2000ms
475
+ // adjust for desired 10th move time
476
+ return 50000.0 / (static_cast<double>(ply) + 15.0);
477
+ };
478
+
479
+ float totalTime = 0;
480
+ for (const auto& game : BenchmarkPositions)
481
+ {
482
+ setup.commands.emplace_back("ucinewgame");
483
+ int ply = 1;
484
+ for (int i = 0; i < static_cast<int>(game.size()); ++i)
485
+ {
486
+ const float correctedTime = getCorrectedTime(ply);
487
+ totalTime += correctedTime;
488
+ ply += 1;
489
+ }
490
+ }
491
+
492
+ float timeScaleFactor = static_cast<float>(desiredTimeS * 1000) / totalTime;
493
+
494
+ for (const auto& game : BenchmarkPositions)
495
+ {
496
+ setup.commands.emplace_back("ucinewgame");
497
+ int ply = 1;
498
+ for (const std::string& fen : game)
499
+ {
500
+ setup.commands.emplace_back("position fen " + fen);
501
+
502
+ const int correctedTime = static_cast<int>(getCorrectedTime(ply) * timeScaleFactor);
503
+ setup.commands.emplace_back("go movetime " + std::to_string(correctedTime));
504
+
505
+ ply += 1;
506
+ }
507
+ }
508
+
509
+ return setup;
510
+ }
511
+
512
+ } // namespace Stockfish
stockfish/src/benchmark.h ADDED
@@ -0,0 +1,42 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /*
2
+ Stockfish, a UCI chess playing engine derived from Glaurung 2.1
3
+ Copyright (C) 2004-2025 The Stockfish developers (see AUTHORS file)
4
+
5
+ Stockfish is free software: you can redistribute it and/or modify
6
+ it under the terms of the GNU General Public License as published by
7
+ the Free Software Foundation, either version 3 of the License, or
8
+ (at your option) any later version.
9
+
10
+ Stockfish is distributed in the hope that it will be useful,
11
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
12
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13
+ GNU General Public License for more details.
14
+
15
+ You should have received a copy of the GNU General Public License
16
+ along with this program. If not, see <http://www.gnu.org/licenses/>.
17
+ */
18
+
19
+ #ifndef BENCHMARK_H_INCLUDED
20
+ #define BENCHMARK_H_INCLUDED
21
+
22
+ #include <iosfwd>
23
+ #include <string>
24
+ #include <vector>
25
+
26
+ namespace Stockfish::Benchmark {
27
+
28
+ std::vector<std::string> setup_bench(const std::string&, std::istream&);
29
+
30
+ struct BenchmarkSetup {
31
+ int ttSize;
32
+ int threads;
33
+ std::vector<std::string> commands;
34
+ std::string originalInvocation;
35
+ std::string filledInvocation;
36
+ };
37
+
38
+ BenchmarkSetup setup_benchmark(std::istream&);
39
+
40
+ } // namespace Stockfish
41
+
42
+ #endif // #ifndef BENCHMARK_H_INCLUDED
stockfish/src/bitboard.cpp ADDED
@@ -0,0 +1,228 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /*
2
+ Stockfish, a UCI chess playing engine derived from Glaurung 2.1
3
+ Copyright (C) 2004-2025 The Stockfish developers (see AUTHORS file)
4
+
5
+ Stockfish is free software: you can redistribute it and/or modify
6
+ it under the terms of the GNU General Public License as published by
7
+ the Free Software Foundation, either version 3 of the License, or
8
+ (at your option) any later version.
9
+
10
+ Stockfish is distributed in the hope that it will be useful,
11
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
12
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13
+ GNU General Public License for more details.
14
+
15
+ You should have received a copy of the GNU General Public License
16
+ along with this program. If not, see <http://www.gnu.org/licenses/>.
17
+ */
18
+
19
+ #include "bitboard.h"
20
+
21
+ #include <algorithm>
22
+ #include <bitset>
23
+ #include <initializer_list>
24
+
25
+ #include "misc.h"
26
+
27
+ namespace Stockfish {
28
+
29
+ uint8_t PopCnt16[1 << 16];
30
+ uint8_t SquareDistance[SQUARE_NB][SQUARE_NB];
31
+
32
+ Bitboard LineBB[SQUARE_NB][SQUARE_NB];
33
+ Bitboard BetweenBB[SQUARE_NB][SQUARE_NB];
34
+ Bitboard PseudoAttacks[PIECE_TYPE_NB][SQUARE_NB];
35
+ Bitboard PawnAttacks[COLOR_NB][SQUARE_NB];
36
+
37
+ alignas(64) Magic Magics[SQUARE_NB][2];
38
+
39
+ namespace {
40
+
41
+ Bitboard RookTable[0x19000]; // To store rook attacks
42
+ Bitboard BishopTable[0x1480]; // To store bishop attacks
43
+
44
+ void init_magics(PieceType pt, Bitboard table[], Magic magics[][2]);
45
+
46
+ // Returns the bitboard of target square for the given step
47
+ // from the given square. If the step is off the board, returns empty bitboard.
48
+ Bitboard safe_destination(Square s, int step) {
49
+ Square to = Square(s + step);
50
+ return is_ok(to) && distance(s, to) <= 2 ? square_bb(to) : Bitboard(0);
51
+ }
52
+ }
53
+
54
+ // Returns an ASCII representation of a bitboard suitable
55
+ // to be printed to standard output. Useful for debugging.
56
+ std::string Bitboards::pretty(Bitboard b) {
57
+
58
+ std::string s = "+---+---+---+---+---+---+---+---+\n";
59
+
60
+ for (Rank r = RANK_8; r >= RANK_1; --r)
61
+ {
62
+ for (File f = FILE_A; f <= FILE_H; ++f)
63
+ s += b & make_square(f, r) ? "| X " : "| ";
64
+
65
+ s += "| " + std::to_string(1 + r) + "\n+---+---+---+---+---+---+---+---+\n";
66
+ }
67
+ s += " a b c d e f g h\n";
68
+
69
+ return s;
70
+ }
71
+
72
+
73
+ // Initializes various bitboard tables. It is called at
74
+ // startup and relies on global objects to be already zero-initialized.
75
+ void Bitboards::init() {
76
+
77
+ for (unsigned i = 0; i < (1 << 16); ++i)
78
+ PopCnt16[i] = uint8_t(std::bitset<16>(i).count());
79
+
80
+ for (Square s1 = SQ_A1; s1 <= SQ_H8; ++s1)
81
+ for (Square s2 = SQ_A1; s2 <= SQ_H8; ++s2)
82
+ SquareDistance[s1][s2] = std::max(distance<File>(s1, s2), distance<Rank>(s1, s2));
83
+
84
+ init_magics(ROOK, RookTable, Magics);
85
+ init_magics(BISHOP, BishopTable, Magics);
86
+
87
+ for (Square s1 = SQ_A1; s1 <= SQ_H8; ++s1)
88
+ {
89
+ PawnAttacks[WHITE][s1] = pawn_attacks_bb<WHITE>(square_bb(s1));
90
+ PawnAttacks[BLACK][s1] = pawn_attacks_bb<BLACK>(square_bb(s1));
91
+
92
+ for (int step : {-9, -8, -7, -1, 1, 7, 8, 9})
93
+ PseudoAttacks[KING][s1] |= safe_destination(s1, step);
94
+
95
+ for (int step : {-17, -15, -10, -6, 6, 10, 15, 17})
96
+ PseudoAttacks[KNIGHT][s1] |= safe_destination(s1, step);
97
+
98
+ PseudoAttacks[QUEEN][s1] = PseudoAttacks[BISHOP][s1] = attacks_bb<BISHOP>(s1, 0);
99
+ PseudoAttacks[QUEEN][s1] |= PseudoAttacks[ROOK][s1] = attacks_bb<ROOK>(s1, 0);
100
+
101
+ for (PieceType pt : {BISHOP, ROOK})
102
+ for (Square s2 = SQ_A1; s2 <= SQ_H8; ++s2)
103
+ {
104
+ if (PseudoAttacks[pt][s1] & s2)
105
+ {
106
+ LineBB[s1][s2] = (attacks_bb(pt, s1, 0) & attacks_bb(pt, s2, 0)) | s1 | s2;
107
+ BetweenBB[s1][s2] =
108
+ (attacks_bb(pt, s1, square_bb(s2)) & attacks_bb(pt, s2, square_bb(s1)));
109
+ }
110
+ BetweenBB[s1][s2] |= s2;
111
+ }
112
+ }
113
+ }
114
+
115
+ namespace {
116
+
117
+ Bitboard sliding_attack(PieceType pt, Square sq, Bitboard occupied) {
118
+
119
+ Bitboard attacks = 0;
120
+ Direction RookDirections[4] = {NORTH, SOUTH, EAST, WEST};
121
+ Direction BishopDirections[4] = {NORTH_EAST, SOUTH_EAST, SOUTH_WEST, NORTH_WEST};
122
+
123
+ for (Direction d : (pt == ROOK ? RookDirections : BishopDirections))
124
+ {
125
+ Square s = sq;
126
+ while (safe_destination(s, d))
127
+ {
128
+ attacks |= (s += d);
129
+ if (occupied & s)
130
+ {
131
+ break;
132
+ }
133
+ }
134
+ }
135
+
136
+ return attacks;
137
+ }
138
+
139
+
140
+ // Computes all rook and bishop attacks at startup. Magic
141
+ // bitboards are used to look up attacks of sliding pieces. As a reference see
142
+ // https://www.chessprogramming.org/Magic_Bitboards. In particular, here we use
143
+ // the so called "fancy" approach.
144
+ void init_magics(PieceType pt, Bitboard table[], Magic magics[][2]) {
145
+
146
+ #ifndef USE_PEXT
147
+ // Optimal PRNG seeds to pick the correct magics in the shortest time
148
+ int seeds[][RANK_NB] = {{8977, 44560, 54343, 38998, 5731, 95205, 104912, 17020},
149
+ {728, 10316, 55013, 32803, 12281, 15100, 16645, 255}};
150
+
151
+ Bitboard occupancy[4096];
152
+ int epoch[4096] = {}, cnt = 0;
153
+ #endif
154
+ Bitboard reference[4096];
155
+ int size = 0;
156
+
157
+ for (Square s = SQ_A1; s <= SQ_H8; ++s)
158
+ {
159
+ // Board edges are not considered in the relevant occupancies
160
+ Bitboard edges = ((Rank1BB | Rank8BB) & ~rank_bb(s)) | ((FileABB | FileHBB) & ~file_bb(s));
161
+
162
+ // Given a square 's', the mask is the bitboard of sliding attacks from
163
+ // 's' computed on an empty board. The index must be big enough to contain
164
+ // all the attacks for each possible subset of the mask and so is 2 power
165
+ // the number of 1s of the mask. Hence we deduce the size of the shift to
166
+ // apply to the 64 or 32 bits word to get the index.
167
+ Magic& m = magics[s][pt - BISHOP];
168
+ m.mask = sliding_attack(pt, s, 0) & ~edges;
169
+ #ifndef USE_PEXT
170
+ m.shift = (Is64Bit ? 64 : 32) - popcount(m.mask);
171
+ #endif
172
+ // Set the offset for the attacks table of the square. We have individual
173
+ // table sizes for each square with "Fancy Magic Bitboards".
174
+ m.attacks = s == SQ_A1 ? table : magics[s - 1][pt - BISHOP].attacks + size;
175
+ size = 0;
176
+
177
+ // Use Carry-Rippler trick to enumerate all subsets of masks[s] and
178
+ // store the corresponding sliding attack bitboard in reference[].
179
+ Bitboard b = 0;
180
+ do
181
+ {
182
+ #ifndef USE_PEXT
183
+ occupancy[size] = b;
184
+ #endif
185
+ reference[size] = sliding_attack(pt, s, b);
186
+
187
+ if (HasPext)
188
+ m.attacks[pext(b, m.mask)] = reference[size];
189
+
190
+ size++;
191
+ b = (b - m.mask) & m.mask;
192
+ } while (b);
193
+
194
+ #ifndef USE_PEXT
195
+ PRNG rng(seeds[Is64Bit][rank_of(s)]);
196
+
197
+ // Find a magic for square 's' picking up an (almost) random number
198
+ // until we find the one that passes the verification test.
199
+ for (int i = 0; i < size;)
200
+ {
201
+ for (m.magic = 0; popcount((m.magic * m.mask) >> 56) < 6;)
202
+ m.magic = rng.sparse_rand<Bitboard>();
203
+
204
+ // A good magic must map every possible occupancy to an index that
205
+ // looks up the correct sliding attack in the attacks[s] database.
206
+ // Note that we build up the database for square 's' as a side
207
+ // effect of verifying the magic. Keep track of the attempt count
208
+ // and save it in epoch[], little speed-up trick to avoid resetting
209
+ // m.attacks[] after every failed attempt.
210
+ for (++cnt, i = 0; i < size; ++i)
211
+ {
212
+ unsigned idx = m.index(occupancy[i]);
213
+
214
+ if (epoch[idx] < cnt)
215
+ {
216
+ epoch[idx] = cnt;
217
+ m.attacks[idx] = reference[i];
218
+ }
219
+ else if (m.attacks[idx] != reference[i])
220
+ break;
221
+ }
222
+ }
223
+ #endif
224
+ }
225
+ }
226
+ }
227
+
228
+ } // namespace Stockfish
stockfish/src/bitboard.h ADDED
@@ -0,0 +1,374 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /*
2
+ Stockfish, a UCI chess playing engine derived from Glaurung 2.1
3
+ Copyright (C) 2004-2025 The Stockfish developers (see AUTHORS file)
4
+
5
+ Stockfish is free software: you can redistribute it and/or modify
6
+ it under the terms of the GNU General Public License as published by
7
+ the Free Software Foundation, either version 3 of the License, or
8
+ (at your option) any later version.
9
+
10
+ Stockfish is distributed in the hope that it will be useful,
11
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
12
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13
+ GNU General Public License for more details.
14
+
15
+ You should have received a copy of the GNU General Public License
16
+ along with this program. If not, see <http://www.gnu.org/licenses/>.
17
+ */
18
+
19
+ #ifndef BITBOARD_H_INCLUDED
20
+ #define BITBOARD_H_INCLUDED
21
+
22
+ #include <algorithm>
23
+ #include <cassert>
24
+ #include <cmath>
25
+ #include <cstring>
26
+ #include <cstdint>
27
+ #include <cstdlib>
28
+ #include <string>
29
+
30
+ #include "types.h"
31
+
32
+ namespace Stockfish {
33
+
34
+ namespace Bitboards {
35
+
36
+ void init();
37
+ std::string pretty(Bitboard b);
38
+
39
+ } // namespace Stockfish::Bitboards
40
+
41
+ constexpr Bitboard FileABB = 0x0101010101010101ULL;
42
+ constexpr Bitboard FileBBB = FileABB << 1;
43
+ constexpr Bitboard FileCBB = FileABB << 2;
44
+ constexpr Bitboard FileDBB = FileABB << 3;
45
+ constexpr Bitboard FileEBB = FileABB << 4;
46
+ constexpr Bitboard FileFBB = FileABB << 5;
47
+ constexpr Bitboard FileGBB = FileABB << 6;
48
+ constexpr Bitboard FileHBB = FileABB << 7;
49
+
50
+ constexpr Bitboard Rank1BB = 0xFF;
51
+ constexpr Bitboard Rank2BB = Rank1BB << (8 * 1);
52
+ constexpr Bitboard Rank3BB = Rank1BB << (8 * 2);
53
+ constexpr Bitboard Rank4BB = Rank1BB << (8 * 3);
54
+ constexpr Bitboard Rank5BB = Rank1BB << (8 * 4);
55
+ constexpr Bitboard Rank6BB = Rank1BB << (8 * 5);
56
+ constexpr Bitboard Rank7BB = Rank1BB << (8 * 6);
57
+ constexpr Bitboard Rank8BB = Rank1BB << (8 * 7);
58
+
59
+ extern uint8_t PopCnt16[1 << 16];
60
+ extern uint8_t SquareDistance[SQUARE_NB][SQUARE_NB];
61
+
62
+ extern Bitboard BetweenBB[SQUARE_NB][SQUARE_NB];
63
+ extern Bitboard LineBB[SQUARE_NB][SQUARE_NB];
64
+ extern Bitboard PseudoAttacks[PIECE_TYPE_NB][SQUARE_NB];
65
+ extern Bitboard PawnAttacks[COLOR_NB][SQUARE_NB];
66
+
67
+
68
+ // Magic holds all magic bitboards relevant data for a single square
69
+ struct Magic {
70
+ Bitboard mask;
71
+ Bitboard* attacks;
72
+ #ifndef USE_PEXT
73
+ Bitboard magic;
74
+ unsigned shift;
75
+ #endif
76
+
77
+ // Compute the attack's index using the 'magic bitboards' approach
78
+ unsigned index(Bitboard occupied) const {
79
+
80
+ #ifdef USE_PEXT
81
+ return unsigned(pext(occupied, mask));
82
+ #else
83
+ if (Is64Bit)
84
+ return unsigned(((occupied & mask) * magic) >> shift);
85
+
86
+ unsigned lo = unsigned(occupied) & unsigned(mask);
87
+ unsigned hi = unsigned(occupied >> 32) & unsigned(mask >> 32);
88
+ return (lo * unsigned(magic) ^ hi * unsigned(magic >> 32)) >> shift;
89
+ #endif
90
+ }
91
+
92
+ Bitboard attacks_bb(Bitboard occupied) const { return attacks[index(occupied)]; }
93
+ };
94
+
95
+ extern Magic Magics[SQUARE_NB][2];
96
+
97
+ constexpr Bitboard square_bb(Square s) {
98
+ assert(is_ok(s));
99
+ return (1ULL << s);
100
+ }
101
+
102
+
103
+ // Overloads of bitwise operators between a Bitboard and a Square for testing
104
+ // whether a given bit is set in a bitboard, and for setting and clearing bits.
105
+
106
+ inline Bitboard operator&(Bitboard b, Square s) { return b & square_bb(s); }
107
+ inline Bitboard operator|(Bitboard b, Square s) { return b | square_bb(s); }
108
+ inline Bitboard operator^(Bitboard b, Square s) { return b ^ square_bb(s); }
109
+ inline Bitboard& operator|=(Bitboard& b, Square s) { return b |= square_bb(s); }
110
+ inline Bitboard& operator^=(Bitboard& b, Square s) { return b ^= square_bb(s); }
111
+
112
+ inline Bitboard operator&(Square s, Bitboard b) { return b & s; }
113
+ inline Bitboard operator|(Square s, Bitboard b) { return b | s; }
114
+ inline Bitboard operator^(Square s, Bitboard b) { return b ^ s; }
115
+
116
+ inline Bitboard operator|(Square s1, Square s2) { return square_bb(s1) | s2; }
117
+
118
+ constexpr bool more_than_one(Bitboard b) { return b & (b - 1); }
119
+
120
+
121
+ // rank_bb() and file_bb() return a bitboard representing all the squares on
122
+ // the given file or rank.
123
+
124
+ constexpr Bitboard rank_bb(Rank r) { return Rank1BB << (8 * r); }
125
+
126
+ constexpr Bitboard rank_bb(Square s) { return rank_bb(rank_of(s)); }
127
+
128
+ constexpr Bitboard file_bb(File f) { return FileABB << f; }
129
+
130
+ constexpr Bitboard file_bb(Square s) { return file_bb(file_of(s)); }
131
+
132
+
133
+ // Moves a bitboard one or two steps as specified by the direction D
134
+ template<Direction D>
135
+ constexpr Bitboard shift(Bitboard b) {
136
+ return D == NORTH ? b << 8
137
+ : D == SOUTH ? b >> 8
138
+ : D == NORTH + NORTH ? b << 16
139
+ : D == SOUTH + SOUTH ? b >> 16
140
+ : D == EAST ? (b & ~FileHBB) << 1
141
+ : D == WEST ? (b & ~FileABB) >> 1
142
+ : D == NORTH_EAST ? (b & ~FileHBB) << 9
143
+ : D == NORTH_WEST ? (b & ~FileABB) << 7
144
+ : D == SOUTH_EAST ? (b & ~FileHBB) >> 7
145
+ : D == SOUTH_WEST ? (b & ~FileABB) >> 9
146
+ : 0;
147
+ }
148
+
149
+
150
+ // Returns the squares attacked by pawns of the given color
151
+ // from the squares in the given bitboard.
152
+ template<Color C>
153
+ constexpr Bitboard pawn_attacks_bb(Bitboard b) {
154
+ return C == WHITE ? shift<NORTH_WEST>(b) | shift<NORTH_EAST>(b)
155
+ : shift<SOUTH_WEST>(b) | shift<SOUTH_EAST>(b);
156
+ }
157
+
158
+ inline Bitboard pawn_attacks_bb(Color c, Square s) {
159
+
160
+ assert(is_ok(s));
161
+ return PawnAttacks[c][s];
162
+ }
163
+
164
+ // Returns a bitboard representing an entire line (from board edge
165
+ // to board edge) that intersects the two given squares. If the given squares
166
+ // are not on a same file/rank/diagonal, the function returns 0. For instance,
167
+ // line_bb(SQ_C4, SQ_F7) will return a bitboard with the A2-G8 diagonal.
168
+ inline Bitboard line_bb(Square s1, Square s2) {
169
+
170
+ assert(is_ok(s1) && is_ok(s2));
171
+ return LineBB[s1][s2];
172
+ }
173
+
174
+
175
+ // Returns a bitboard representing the squares in the semi-open
176
+ // segment between the squares s1 and s2 (excluding s1 but including s2). If the
177
+ // given squares are not on a same file/rank/diagonal, it returns s2. For instance,
178
+ // between_bb(SQ_C4, SQ_F7) will return a bitboard with squares D5, E6 and F7, but
179
+ // between_bb(SQ_E6, SQ_F8) will return a bitboard with the square F8. This trick
180
+ // allows to generate non-king evasion moves faster: the defending piece must either
181
+ // interpose itself to cover the check or capture the checking piece.
182
+ inline Bitboard between_bb(Square s1, Square s2) {
183
+
184
+ assert(is_ok(s1) && is_ok(s2));
185
+ return BetweenBB[s1][s2];
186
+ }
187
+
188
+ // Returns true if the squares s1, s2 and s3 are aligned either on a
189
+ // straight or on a diagonal line.
190
+ inline bool aligned(Square s1, Square s2, Square s3) { return line_bb(s1, s2) & s3; }
191
+
192
+
193
+ // distance() functions return the distance between x and y, defined as the
194
+ // number of steps for a king in x to reach y.
195
+
196
+ template<typename T1 = Square>
197
+ inline int distance(Square x, Square y);
198
+
199
+ template<>
200
+ inline int distance<File>(Square x, Square y) {
201
+ return std::abs(file_of(x) - file_of(y));
202
+ }
203
+
204
+ template<>
205
+ inline int distance<Rank>(Square x, Square y) {
206
+ return std::abs(rank_of(x) - rank_of(y));
207
+ }
208
+
209
+ template<>
210
+ inline int distance<Square>(Square x, Square y) {
211
+ return SquareDistance[x][y];
212
+ }
213
+
214
+ inline int edge_distance(File f) { return std::min(f, File(FILE_H - f)); }
215
+
216
+ // Returns the pseudo attacks of the given piece type
217
+ // assuming an empty board.
218
+ template<PieceType Pt>
219
+ inline Bitboard attacks_bb(Square s) {
220
+
221
+ assert((Pt != PAWN) && (is_ok(s)));
222
+ return PseudoAttacks[Pt][s];
223
+ }
224
+
225
+
226
+ // Returns the attacks by the given piece
227
+ // assuming the board is occupied according to the passed Bitboard.
228
+ // Sliding piece attacks do not continue passed an occupied square.
229
+ template<PieceType Pt>
230
+ inline Bitboard attacks_bb(Square s, Bitboard occupied) {
231
+
232
+ assert((Pt != PAWN) && (is_ok(s)));
233
+
234
+ switch (Pt)
235
+ {
236
+ case BISHOP :
237
+ case ROOK :
238
+ return Magics[s][Pt - BISHOP].attacks_bb(occupied);
239
+ case QUEEN :
240
+ return attacks_bb<BISHOP>(s, occupied) | attacks_bb<ROOK>(s, occupied);
241
+ default :
242
+ return PseudoAttacks[Pt][s];
243
+ }
244
+ }
245
+
246
+ // Returns the attacks by the given piece
247
+ // assuming the board is occupied according to the passed Bitboard.
248
+ // Sliding piece attacks do not continue passed an occupied square.
249
+ inline Bitboard attacks_bb(PieceType pt, Square s, Bitboard occupied) {
250
+
251
+ assert((pt != PAWN) && (is_ok(s)));
252
+
253
+ switch (pt)
254
+ {
255
+ case BISHOP :
256
+ return attacks_bb<BISHOP>(s, occupied);
257
+ case ROOK :
258
+ return attacks_bb<ROOK>(s, occupied);
259
+ case QUEEN :
260
+ return attacks_bb<BISHOP>(s, occupied) | attacks_bb<ROOK>(s, occupied);
261
+ default :
262
+ return PseudoAttacks[pt][s];
263
+ }
264
+ }
265
+
266
+
267
+ // Counts the number of non-zero bits in a bitboard.
268
+ inline int popcount(Bitboard b) {
269
+
270
+ #ifndef USE_POPCNT
271
+
272
+ std::uint16_t indices[4];
273
+ std::memcpy(indices, &b, sizeof(b));
274
+ return PopCnt16[indices[0]] + PopCnt16[indices[1]] + PopCnt16[indices[2]]
275
+ + PopCnt16[indices[3]];
276
+
277
+ #elif defined(_MSC_VER)
278
+
279
+ return int(_mm_popcnt_u64(b));
280
+
281
+ #else // Assumed gcc or compatible compiler
282
+
283
+ return __builtin_popcountll(b);
284
+
285
+ #endif
286
+ }
287
+
288
+ // Returns the least significant bit in a non-zero bitboard.
289
+ inline Square lsb(Bitboard b) {
290
+ assert(b);
291
+
292
+ #if defined(__GNUC__) // GCC, Clang, ICX
293
+
294
+ return Square(__builtin_ctzll(b));
295
+
296
+ #elif defined(_MSC_VER)
297
+ #ifdef _WIN64 // MSVC, WIN64
298
+
299
+ unsigned long idx;
300
+ _BitScanForward64(&idx, b);
301
+ return Square(idx);
302
+
303
+ #else // MSVC, WIN32
304
+ unsigned long idx;
305
+
306
+ if (b & 0xffffffff)
307
+ {
308
+ _BitScanForward(&idx, int32_t(b));
309
+ return Square(idx);
310
+ }
311
+ else
312
+ {
313
+ _BitScanForward(&idx, int32_t(b >> 32));
314
+ return Square(idx + 32);
315
+ }
316
+ #endif
317
+ #else // Compiler is neither GCC nor MSVC compatible
318
+ #error "Compiler not supported."
319
+ #endif
320
+ }
321
+
322
+ // Returns the most significant bit in a non-zero bitboard.
323
+ inline Square msb(Bitboard b) {
324
+ assert(b);
325
+
326
+ #if defined(__GNUC__) // GCC, Clang, ICX
327
+
328
+ return Square(63 ^ __builtin_clzll(b));
329
+
330
+ #elif defined(_MSC_VER)
331
+ #ifdef _WIN64 // MSVC, WIN64
332
+
333
+ unsigned long idx;
334
+ _BitScanReverse64(&idx, b);
335
+ return Square(idx);
336
+
337
+ #else // MSVC, WIN32
338
+
339
+ unsigned long idx;
340
+
341
+ if (b >> 32)
342
+ {
343
+ _BitScanReverse(&idx, int32_t(b >> 32));
344
+ return Square(idx + 32);
345
+ }
346
+ else
347
+ {
348
+ _BitScanReverse(&idx, int32_t(b));
349
+ return Square(idx);
350
+ }
351
+ #endif
352
+ #else // Compiler is neither GCC nor MSVC compatible
353
+ #error "Compiler not supported."
354
+ #endif
355
+ }
356
+
357
+ // Returns the bitboard of the least significant
358
+ // square of a non-zero bitboard. It is equivalent to square_bb(lsb(bb)).
359
+ inline Bitboard least_significant_square_bb(Bitboard b) {
360
+ assert(b);
361
+ return b & -b;
362
+ }
363
+
364
+ // Finds and clears the least significant bit in a non-zero bitboard.
365
+ inline Square pop_lsb(Bitboard& b) {
366
+ assert(b);
367
+ const Square s = lsb(b);
368
+ b &= b - 1;
369
+ return s;
370
+ }
371
+
372
+ } // namespace Stockfish
373
+
374
+ #endif // #ifndef BITBOARD_H_INCLUDED
stockfish/src/engine.cpp ADDED
@@ -0,0 +1,372 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /*
2
+ Stockfish, a UCI chess playing engine derived from Glaurung 2.1
3
+ Copyright (C) 2004-2025 The Stockfish developers (see AUTHORS file)
4
+
5
+ Stockfish is free software: you can redistribute it and/or modify
6
+ it under the terms of the GNU General Public License as published by
7
+ the Free Software Foundation, either version 3 of the License, or
8
+ (at your option) any later version.
9
+
10
+ Stockfish is distributed in the hope that it will be useful,
11
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
12
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13
+ GNU General Public License for more details.
14
+
15
+ You should have received a copy of the GNU General Public License
16
+ along with this program. If not, see <http://www.gnu.org/licenses/>.
17
+ */
18
+
19
+ #include "engine.h"
20
+
21
+ #include <algorithm>
22
+ #include <cassert>
23
+ #include <deque>
24
+ #include <iosfwd>
25
+ #include <memory>
26
+ #include <ostream>
27
+ #include <sstream>
28
+ #include <string_view>
29
+ #include <utility>
30
+ #include <vector>
31
+
32
+ #include "evaluate.h"
33
+ #include "misc.h"
34
+ #include "nnue/network.h"
35
+ #include "nnue/nnue_common.h"
36
+ #include "numa.h"
37
+ #include "perft.h"
38
+ #include "position.h"
39
+ #include "search.h"
40
+ #include "syzygy/tbprobe.h"
41
+ #include "types.h"
42
+ #include "uci.h"
43
+ #include "ucioption.h"
44
+
45
+ namespace Stockfish {
46
+
47
+ namespace NN = Eval::NNUE;
48
+
49
+ constexpr auto StartFEN = "rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1";
50
+ constexpr int MaxHashMB = Is64Bit ? 33554432 : 2048;
51
+ int MaxThreads = std::max(1024, 4 * int(get_hardware_concurrency()));
52
+
53
+ Engine::Engine(std::optional<std::string> path) :
54
+ binaryDirectory(path ? CommandLine::get_binary_directory(*path) : ""),
55
+ numaContext(NumaConfig::from_system()),
56
+ states(new std::deque<StateInfo>(1)),
57
+ threads(),
58
+ networks(
59
+ numaContext,
60
+ NN::Networks(
61
+ NN::NetworkBig({EvalFileDefaultNameBig, "None", ""}, NN::EmbeddedNNUEType::BIG),
62
+ NN::NetworkSmall({EvalFileDefaultNameSmall, "None", ""}, NN::EmbeddedNNUEType::SMALL))) {
63
+ pos.set(StartFEN, false, &states->back());
64
+
65
+
66
+ options.add( //
67
+ "Debug Log File", Option("", [](const Option& o) {
68
+ start_logger(o);
69
+ return std::nullopt;
70
+ }));
71
+
72
+ options.add( //
73
+ "NumaPolicy", Option("auto", [this](const Option& o) {
74
+ set_numa_config_from_option(o);
75
+ return numa_config_information_as_string() + "\n"
76
+ + thread_allocation_information_as_string();
77
+ }));
78
+
79
+ options.add( //
80
+ "Threads", Option(1, 1, MaxThreads, [this](const Option&) {
81
+ resize_threads();
82
+ return thread_allocation_information_as_string();
83
+ }));
84
+
85
+ options.add( //
86
+ "Hash", Option(16, 1, MaxHashMB, [this](const Option& o) {
87
+ set_tt_size(o);
88
+ return std::nullopt;
89
+ }));
90
+
91
+ options.add( //
92
+ "Clear Hash", Option([this](const Option&) {
93
+ search_clear();
94
+ return std::nullopt;
95
+ }));
96
+
97
+ options.add( //
98
+ "Ponder", Option(false));
99
+
100
+ options.add( //
101
+ "MultiPV", Option(1, 1, MAX_MOVES));
102
+
103
+ options.add("Skill Level", Option(20, 0, 20));
104
+
105
+ options.add("Move Overhead", Option(10, 0, 5000));
106
+
107
+ options.add("nodestime", Option(0, 0, 10000));
108
+
109
+ options.add("UCI_Chess960", Option(false));
110
+
111
+ options.add("UCI_LimitStrength", Option(false));
112
+
113
+ options.add("UCI_Elo",
114
+ Option(Stockfish::Search::Skill::LowestElo, Stockfish::Search::Skill::LowestElo,
115
+ Stockfish::Search::Skill::HighestElo));
116
+
117
+ options.add("UCI_ShowWDL", Option(false));
118
+
119
+ options.add( //
120
+ "SyzygyPath", Option("", [](const Option& o) {
121
+ Tablebases::init(o);
122
+ return std::nullopt;
123
+ }));
124
+
125
+ options.add("SyzygyProbeDepth", Option(1, 1, 100));
126
+
127
+ options.add("Syzygy50MoveRule", Option(true));
128
+
129
+ options.add("SyzygyProbeLimit", Option(7, 0, 7));
130
+
131
+ options.add( //
132
+ "EvalFile", Option(EvalFileDefaultNameBig, [this](const Option& o) {
133
+ load_big_network(o);
134
+ return std::nullopt;
135
+ }));
136
+
137
+ options.add( //
138
+ "EvalFileSmall", Option(EvalFileDefaultNameSmall, [this](const Option& o) {
139
+ load_small_network(o);
140
+ return std::nullopt;
141
+ }));
142
+
143
+ load_networks();
144
+ resize_threads();
145
+ }
146
+
147
+ std::uint64_t Engine::perft(const std::string& fen, Depth depth, bool isChess960) {
148
+ verify_networks();
149
+
150
+ return Benchmark::perft(fen, depth, isChess960);
151
+ }
152
+
153
+ void Engine::go(Search::LimitsType& limits) {
154
+ assert(limits.perft == 0);
155
+ verify_networks();
156
+
157
+ threads.start_thinking(options, pos, states, limits);
158
+ }
159
+ void Engine::stop() { threads.stop = true; }
160
+
161
+ void Engine::search_clear() {
162
+ wait_for_search_finished();
163
+
164
+ tt.clear(threads);
165
+ threads.clear();
166
+
167
+ // @TODO wont work with multiple instances
168
+ Tablebases::init(options["SyzygyPath"]); // Free mapped files
169
+ }
170
+
171
+ void Engine::set_on_update_no_moves(std::function<void(const Engine::InfoShort&)>&& f) {
172
+ updateContext.onUpdateNoMoves = std::move(f);
173
+ }
174
+
175
+ void Engine::set_on_update_full(std::function<void(const Engine::InfoFull&)>&& f) {
176
+ updateContext.onUpdateFull = std::move(f);
177
+ }
178
+
179
+ void Engine::set_on_iter(std::function<void(const Engine::InfoIter&)>&& f) {
180
+ updateContext.onIter = std::move(f);
181
+ }
182
+
183
+ void Engine::set_on_bestmove(std::function<void(std::string_view, std::string_view)>&& f) {
184
+ updateContext.onBestmove = std::move(f);
185
+ }
186
+
187
+ void Engine::set_on_verify_networks(std::function<void(std::string_view)>&& f) {
188
+ onVerifyNetworks = std::move(f);
189
+ }
190
+
191
+ void Engine::wait_for_search_finished() { threads.main_thread()->wait_for_search_finished(); }
192
+
193
+ void Engine::set_position(const std::string& fen, const std::vector<std::string>& moves) {
194
+ // Drop the old state and create a new one
195
+ states = StateListPtr(new std::deque<StateInfo>(1));
196
+ pos.set(fen, options["UCI_Chess960"], &states->back());
197
+
198
+ for (const auto& move : moves)
199
+ {
200
+ auto m = UCIEngine::to_move(pos, move);
201
+
202
+ if (m == Move::none())
203
+ break;
204
+
205
+ states->emplace_back();
206
+ pos.do_move(m, states->back());
207
+ }
208
+ }
209
+
210
+ // modifiers
211
+
212
+ void Engine::set_numa_config_from_option(const std::string& o) {
213
+ if (o == "auto" || o == "system")
214
+ {
215
+ numaContext.set_numa_config(NumaConfig::from_system());
216
+ }
217
+ else if (o == "hardware")
218
+ {
219
+ // Don't respect affinity set in the system.
220
+ numaContext.set_numa_config(NumaConfig::from_system(false));
221
+ }
222
+ else if (o == "none")
223
+ {
224
+ numaContext.set_numa_config(NumaConfig{});
225
+ }
226
+ else
227
+ {
228
+ numaContext.set_numa_config(NumaConfig::from_string(o));
229
+ }
230
+
231
+ // Force reallocation of threads in case affinities need to change.
232
+ resize_threads();
233
+ threads.ensure_network_replicated();
234
+ }
235
+
236
+ void Engine::resize_threads() {
237
+ threads.wait_for_search_finished();
238
+ threads.set(numaContext.get_numa_config(), {options, threads, tt, networks}, updateContext);
239
+
240
+ // Reallocate the hash with the new threadpool size
241
+ set_tt_size(options["Hash"]);
242
+ threads.ensure_network_replicated();
243
+ }
244
+
245
+ void Engine::set_tt_size(size_t mb) {
246
+ wait_for_search_finished();
247
+ tt.resize(mb, threads);
248
+ }
249
+
250
+ void Engine::set_ponderhit(bool b) { threads.main_manager()->ponder = b; }
251
+
252
+ // network related
253
+
254
+ void Engine::verify_networks() const {
255
+ networks->big.verify(options["EvalFile"], onVerifyNetworks);
256
+ networks->small.verify(options["EvalFileSmall"], onVerifyNetworks);
257
+ }
258
+
259
+ void Engine::load_networks() {
260
+ networks.modify_and_replicate([this](NN::Networks& networks_) {
261
+ networks_.big.load(binaryDirectory, options["EvalFile"]);
262
+ networks_.small.load(binaryDirectory, options["EvalFileSmall"]);
263
+ });
264
+ threads.clear();
265
+ threads.ensure_network_replicated();
266
+ }
267
+
268
+ void Engine::load_big_network(const std::string& file) {
269
+ networks.modify_and_replicate(
270
+ [this, &file](NN::Networks& networks_) { networks_.big.load(binaryDirectory, file); });
271
+ threads.clear();
272
+ threads.ensure_network_replicated();
273
+ }
274
+
275
+ void Engine::load_small_network(const std::string& file) {
276
+ networks.modify_and_replicate(
277
+ [this, &file](NN::Networks& networks_) { networks_.small.load(binaryDirectory, file); });
278
+ threads.clear();
279
+ threads.ensure_network_replicated();
280
+ }
281
+
282
+ void Engine::save_network(const std::pair<std::optional<std::string>, std::string> files[2]) {
283
+ networks.modify_and_replicate([&files](NN::Networks& networks_) {
284
+ networks_.big.save(files[0].first);
285
+ networks_.small.save(files[1].first);
286
+ });
287
+ }
288
+
289
+ // utility functions
290
+
291
+ void Engine::trace_eval() const {
292
+ StateListPtr trace_states(new std::deque<StateInfo>(1));
293
+ Position p;
294
+ p.set(pos.fen(), options["UCI_Chess960"], &trace_states->back());
295
+
296
+ verify_networks();
297
+
298
+ sync_cout << "\n" << Eval::trace(p, *networks) << sync_endl;
299
+ }
300
+
301
+ const OptionsMap& Engine::get_options() const { return options; }
302
+ OptionsMap& Engine::get_options() { return options; }
303
+
304
+ std::string Engine::fen() const { return pos.fen(); }
305
+
306
+ void Engine::flip() { pos.flip(); }
307
+
308
+ std::string Engine::visualize() const {
309
+ std::stringstream ss;
310
+ ss << pos;
311
+ return ss.str();
312
+ }
313
+
314
+ int Engine::get_hashfull(int maxAge) const { return tt.hashfull(maxAge); }
315
+
316
+ std::vector<std::pair<size_t, size_t>> Engine::get_bound_thread_count_by_numa_node() const {
317
+ auto counts = threads.get_bound_thread_count_by_numa_node();
318
+ const NumaConfig& cfg = numaContext.get_numa_config();
319
+ std::vector<std::pair<size_t, size_t>> ratios;
320
+ NumaIndex n = 0;
321
+ for (; n < counts.size(); ++n)
322
+ ratios.emplace_back(counts[n], cfg.num_cpus_in_numa_node(n));
323
+ if (!counts.empty())
324
+ for (; n < cfg.num_numa_nodes(); ++n)
325
+ ratios.emplace_back(0, cfg.num_cpus_in_numa_node(n));
326
+ return ratios;
327
+ }
328
+
329
+ std::string Engine::get_numa_config_as_string() const {
330
+ return numaContext.get_numa_config().to_string();
331
+ }
332
+
333
+ std::string Engine::numa_config_information_as_string() const {
334
+ auto cfgStr = get_numa_config_as_string();
335
+ return "Available processors: " + cfgStr;
336
+ }
337
+
338
+ std::string Engine::thread_binding_information_as_string() const {
339
+ auto boundThreadsByNode = get_bound_thread_count_by_numa_node();
340
+ std::stringstream ss;
341
+ if (boundThreadsByNode.empty())
342
+ return ss.str();
343
+
344
+ bool isFirst = true;
345
+
346
+ for (auto&& [current, total] : boundThreadsByNode)
347
+ {
348
+ if (!isFirst)
349
+ ss << ":";
350
+ ss << current << "/" << total;
351
+ isFirst = false;
352
+ }
353
+
354
+ return ss.str();
355
+ }
356
+
357
+ std::string Engine::thread_allocation_information_as_string() const {
358
+ std::stringstream ss;
359
+
360
+ size_t threadsSize = threads.size();
361
+ ss << "Using " << threadsSize << (threadsSize > 1 ? " threads" : " thread");
362
+
363
+ auto boundThreadsByNodeStr = thread_binding_information_as_string();
364
+ if (boundThreadsByNodeStr.empty())
365
+ return ss.str();
366
+
367
+ ss << " with NUMA node thread binding: ";
368
+ ss << boundThreadsByNodeStr;
369
+
370
+ return ss.str();
371
+ }
372
+ }
stockfish/src/engine.h ADDED
@@ -0,0 +1,130 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /*
2
+ Stockfish, a UCI chess playing engine derived from Glaurung 2.1
3
+ Copyright (C) 2004-2025 The Stockfish developers (see AUTHORS file)
4
+
5
+ Stockfish is free software: you can redistribute it and/or modify
6
+ it under the terms of the GNU General Public License as published by
7
+ the Free Software Foundation, either version 3 of the License, or
8
+ (at your option) any later version.
9
+
10
+ Stockfish is distributed in the hope that it will be useful,
11
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
12
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13
+ GNU General Public License for more details.
14
+
15
+ You should have received a copy of the GNU General Public License
16
+ along with this program. If not, see <http://www.gnu.org/licenses/>.
17
+ */
18
+
19
+ #ifndef ENGINE_H_INCLUDED
20
+ #define ENGINE_H_INCLUDED
21
+
22
+ #include <cstddef>
23
+ #include <cstdint>
24
+ #include <functional>
25
+ #include <optional>
26
+ #include <string>
27
+ #include <string_view>
28
+ #include <utility>
29
+ #include <vector>
30
+
31
+ #include "nnue/network.h"
32
+ #include "numa.h"
33
+ #include "position.h"
34
+ #include "search.h"
35
+ #include "syzygy/tbprobe.h" // for Stockfish::Depth
36
+ #include "thread.h"
37
+ #include "tt.h"
38
+ #include "ucioption.h"
39
+
40
+ namespace Stockfish {
41
+
42
+ class Engine {
43
+ public:
44
+ using InfoShort = Search::InfoShort;
45
+ using InfoFull = Search::InfoFull;
46
+ using InfoIter = Search::InfoIteration;
47
+
48
+ Engine(std::optional<std::string> path = std::nullopt);
49
+
50
+ // Cannot be movable due to components holding backreferences to fields
51
+ Engine(const Engine&) = delete;
52
+ Engine(Engine&&) = delete;
53
+ Engine& operator=(const Engine&) = delete;
54
+ Engine& operator=(Engine&&) = delete;
55
+
56
+ ~Engine() { wait_for_search_finished(); }
57
+
58
+ std::uint64_t perft(const std::string& fen, Depth depth, bool isChess960);
59
+
60
+ // non blocking call to start searching
61
+ void go(Search::LimitsType&);
62
+ // non blocking call to stop searching
63
+ void stop();
64
+
65
+ // blocking call to wait for search to finish
66
+ void wait_for_search_finished();
67
+ // set a new position, moves are in UCI format
68
+ void set_position(const std::string& fen, const std::vector<std::string>& moves);
69
+
70
+ // modifiers
71
+
72
+ void set_numa_config_from_option(const std::string& o);
73
+ void resize_threads();
74
+ void set_tt_size(size_t mb);
75
+ void set_ponderhit(bool);
76
+ void search_clear();
77
+
78
+ void set_on_update_no_moves(std::function<void(const InfoShort&)>&&);
79
+ void set_on_update_full(std::function<void(const InfoFull&)>&&);
80
+ void set_on_iter(std::function<void(const InfoIter&)>&&);
81
+ void set_on_bestmove(std::function<void(std::string_view, std::string_view)>&&);
82
+ void set_on_verify_networks(std::function<void(std::string_view)>&&);
83
+
84
+ // network related
85
+
86
+ void verify_networks() const;
87
+ void load_networks();
88
+ void load_big_network(const std::string& file);
89
+ void load_small_network(const std::string& file);
90
+ void save_network(const std::pair<std::optional<std::string>, std::string> files[2]);
91
+
92
+ // utility functions
93
+
94
+ void trace_eval() const;
95
+
96
+ const OptionsMap& get_options() const;
97
+ OptionsMap& get_options();
98
+
99
+ int get_hashfull(int maxAge = 0) const;
100
+
101
+ std::string fen() const;
102
+ void flip();
103
+ std::string visualize() const;
104
+ std::vector<std::pair<size_t, size_t>> get_bound_thread_count_by_numa_node() const;
105
+ std::string get_numa_config_as_string() const;
106
+ std::string numa_config_information_as_string() const;
107
+ std::string thread_allocation_information_as_string() const;
108
+ std::string thread_binding_information_as_string() const;
109
+
110
+ private:
111
+ const std::string binaryDirectory;
112
+
113
+ NumaReplicationContext numaContext;
114
+
115
+ Position pos;
116
+ StateListPtr states;
117
+
118
+ OptionsMap options;
119
+ ThreadPool threads;
120
+ TranspositionTable tt;
121
+ LazyNumaReplicated<Eval::NNUE::Networks> networks;
122
+
123
+ Search::SearchManager::UpdateContext updateContext;
124
+ std::function<void(std::string_view)> onVerifyNetworks;
125
+ };
126
+
127
+ } // namespace Stockfish
128
+
129
+
130
+ #endif // #ifndef ENGINE_H_INCLUDED
stockfish/src/evaluate.cpp ADDED
@@ -0,0 +1,128 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /*
2
+ Stockfish, a UCI chess playing engine derived from Glaurung 2.1
3
+ Copyright (C) 2004-2025 The Stockfish developers (see AUTHORS file)
4
+
5
+ Stockfish is free software: you can redistribute it and/or modify
6
+ it under the terms of the GNU General Public License as published by
7
+ the Free Software Foundation, either version 3 of the License, or
8
+ (at your option) any later version.
9
+
10
+ Stockfish is distributed in the hope that it will be useful,
11
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
12
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13
+ GNU General Public License for more details.
14
+
15
+ You should have received a copy of the GNU General Public License
16
+ along with this program. If not, see <http://www.gnu.org/licenses/>.
17
+ */
18
+
19
+ #include "evaluate.h"
20
+
21
+ #include <algorithm>
22
+ #include <cassert>
23
+ #include <cmath>
24
+ #include <cstdlib>
25
+ #include <iomanip>
26
+ #include <iostream>
27
+ #include <memory>
28
+ #include <sstream>
29
+ #include <tuple>
30
+
31
+ #include "nnue/network.h"
32
+ #include "nnue/nnue_misc.h"
33
+ #include "position.h"
34
+ #include "types.h"
35
+ #include "uci.h"
36
+ #include "nnue/nnue_accumulator.h"
37
+
38
+ namespace Stockfish {
39
+
40
+ // Returns a static, purely materialistic evaluation of the position from
41
+ // the point of view of the given color. It can be divided by PawnValue to get
42
+ // an approximation of the material advantage on the board in terms of pawns.
43
+ int Eval::simple_eval(const Position& pos, Color c) {
44
+ return PawnValue * (pos.count<PAWN>(c) - pos.count<PAWN>(~c))
45
+ + (pos.non_pawn_material(c) - pos.non_pawn_material(~c));
46
+ }
47
+
48
+ bool Eval::use_smallnet(const Position& pos) {
49
+ int simpleEval = simple_eval(pos, pos.side_to_move());
50
+ return std::abs(simpleEval) > 962;
51
+ }
52
+
53
+ // Evaluate is the evaluator for the outer world. It returns a static evaluation
54
+ // of the position from the point of view of the side to move.
55
+ Value Eval::evaluate(const Eval::NNUE::Networks& networks,
56
+ const Position& pos,
57
+ Eval::NNUE::AccumulatorStack& accumulators,
58
+ Eval::NNUE::AccumulatorCaches& caches,
59
+ int optimism) {
60
+
61
+ assert(!pos.checkers());
62
+
63
+ bool smallNet = use_smallnet(pos);
64
+ auto [psqt, positional] = smallNet ? networks.small.evaluate(pos, accumulators, &caches.small)
65
+ : networks.big.evaluate(pos, accumulators, &caches.big);
66
+
67
+ Value nnue = (125 * psqt + 131 * positional) / 128;
68
+
69
+ // Re-evaluate the position when higher eval accuracy is worth the time spent
70
+ if (smallNet && (std::abs(nnue) < 236))
71
+ {
72
+ std::tie(psqt, positional) = networks.big.evaluate(pos, accumulators, &caches.big);
73
+ nnue = (125 * psqt + 131 * positional) / 128;
74
+ smallNet = false;
75
+ }
76
+
77
+ // Blend optimism and eval with nnue complexity
78
+ int nnueComplexity = std::abs(psqt - positional);
79
+ optimism += optimism * nnueComplexity / 468;
80
+ nnue -= nnue * nnueComplexity / 18000;
81
+
82
+ int material = 535 * pos.count<PAWN>() + pos.non_pawn_material();
83
+ int v = (nnue * (77777 + material) + optimism * (7777 + material)) / 77777;
84
+
85
+ // Damp down the evaluation linearly when shuffling
86
+ v -= v * pos.rule50_count() / 212;
87
+
88
+ // Guarantee evaluation does not hit the tablebase range
89
+ v = std::clamp(v, VALUE_TB_LOSS_IN_MAX_PLY + 1, VALUE_TB_WIN_IN_MAX_PLY - 1);
90
+
91
+ return v;
92
+ }
93
+
94
+ // Like evaluate(), but instead of returning a value, it returns
95
+ // a string (suitable for outputting to stdout) that contains the detailed
96
+ // descriptions and values of each evaluation term. Useful for debugging.
97
+ // Trace scores are from white's point of view
98
+ std::string Eval::trace(Position& pos, const Eval::NNUE::Networks& networks) {
99
+
100
+ if (pos.checkers())
101
+ return "Final evaluation: none (in check)";
102
+
103
+ Eval::NNUE::AccumulatorStack accumulators;
104
+ auto caches = std::make_unique<Eval::NNUE::AccumulatorCaches>(networks);
105
+
106
+ accumulators.reset(pos, networks, *caches);
107
+
108
+ std::stringstream ss;
109
+ ss << std::showpoint << std::noshowpos << std::fixed << std::setprecision(2);
110
+ ss << '\n' << NNUE::trace(pos, networks, *caches) << '\n';
111
+
112
+ ss << std::showpoint << std::showpos << std::fixed << std::setprecision(2) << std::setw(15);
113
+
114
+ auto [psqt, positional] = networks.big.evaluate(pos, accumulators, &caches->big);
115
+ Value v = psqt + positional;
116
+ v = pos.side_to_move() == WHITE ? v : -v;
117
+ ss << "NNUE evaluation " << 0.01 * UCIEngine::to_cp(v, pos) << " (white side)\n";
118
+
119
+ v = evaluate(networks, pos, accumulators, *caches, VALUE_ZERO);
120
+ v = pos.side_to_move() == WHITE ? v : -v;
121
+ ss << "Final evaluation " << 0.01 * UCIEngine::to_cp(v, pos) << " (white side)";
122
+ ss << " [with scaled NNUE, ...]";
123
+ ss << "\n";
124
+
125
+ return ss.str();
126
+ }
127
+
128
+ } // namespace Stockfish
stockfish/src/evaluate.h ADDED
@@ -0,0 +1,58 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /*
2
+ Stockfish, a UCI chess playing engine derived from Glaurung 2.1
3
+ Copyright (C) 2004-2025 The Stockfish developers (see AUTHORS file)
4
+
5
+ Stockfish is free software: you can redistribute it and/or modify
6
+ it under the terms of the GNU General Public License as published by
7
+ the Free Software Foundation, either version 3 of the License, or
8
+ (at your option) any later version.
9
+
10
+ Stockfish is distributed in the hope that it will be useful,
11
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
12
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13
+ GNU General Public License for more details.
14
+
15
+ You should have received a copy of the GNU General Public License
16
+ along with this program. If not, see <http://www.gnu.org/licenses/>.
17
+ */
18
+
19
+ #ifndef EVALUATE_H_INCLUDED
20
+ #define EVALUATE_H_INCLUDED
21
+
22
+ #include <string>
23
+
24
+ #include "types.h"
25
+
26
+ namespace Stockfish {
27
+
28
+ class Position;
29
+
30
+ namespace Eval {
31
+
32
+ // The default net name MUST follow the format nn-[SHA256 first 12 digits].nnue
33
+ // for the build process (profile-build and fishtest) to work. Do not change the
34
+ // name of the macro or the location where this macro is defined, as it is used
35
+ // in the Makefile/Fishtest.
36
+ #define EvalFileDefaultNameBig "nn-1c0000000000.nnue"
37
+ #define EvalFileDefaultNameSmall "nn-37f18f62d772.nnue"
38
+
39
+ namespace NNUE {
40
+ struct Networks;
41
+ struct AccumulatorCaches;
42
+ class AccumulatorStack;
43
+ }
44
+
45
+ std::string trace(Position& pos, const Eval::NNUE::Networks& networks);
46
+
47
+ int simple_eval(const Position& pos, Color c);
48
+ bool use_smallnet(const Position& pos);
49
+ Value evaluate(const NNUE::Networks& networks,
50
+ const Position& pos,
51
+ Eval::NNUE::AccumulatorStack& accumulators,
52
+ Eval::NNUE::AccumulatorCaches& caches,
53
+ int optimism);
54
+ } // namespace Eval
55
+
56
+ } // namespace Stockfish
57
+
58
+ #endif // #ifndef EVALUATE_H_INCLUDED
stockfish/src/history.h ADDED
@@ -0,0 +1,171 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /*
2
+ Stockfish, a UCI chess playing engine derived from Glaurung 2.1
3
+ Copyright (C) 2004-2025 The Stockfish developers (see AUTHORS file)
4
+
5
+ Stockfish is free software: you can redistribute it and/or modify
6
+ it under the terms of the GNU General Public License as published by
7
+ the Free Software Foundation, either version 3 of the License, or
8
+ (at your option) any later version.
9
+
10
+ Stockfish is distributed in the hope that it will be useful,
11
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
12
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13
+ GNU General Public License for more details.
14
+
15
+ You should have received a copy of the GNU General Public License
16
+ along with this program. If not, see <http://www.gnu.org/licenses/>.
17
+ */
18
+
19
+ #ifndef HISTORY_H_INCLUDED
20
+ #define HISTORY_H_INCLUDED
21
+
22
+ #include <algorithm>
23
+ #include <array>
24
+ #include <cassert>
25
+ #include <cmath>
26
+ #include <cstdint>
27
+ #include <cstdlib>
28
+ #include <limits>
29
+ #include <type_traits> // IWYU pragma: keep
30
+
31
+ #include "misc.h"
32
+ #include "position.h"
33
+
34
+ namespace Stockfish {
35
+
36
+ constexpr int PAWN_HISTORY_SIZE = 512; // has to be a power of 2
37
+ constexpr int CORRECTION_HISTORY_SIZE = 32768; // has to be a power of 2
38
+ constexpr int CORRECTION_HISTORY_LIMIT = 1024;
39
+ constexpr int LOW_PLY_HISTORY_SIZE = 4;
40
+
41
+ static_assert((PAWN_HISTORY_SIZE & (PAWN_HISTORY_SIZE - 1)) == 0,
42
+ "PAWN_HISTORY_SIZE has to be a power of 2");
43
+
44
+ static_assert((CORRECTION_HISTORY_SIZE & (CORRECTION_HISTORY_SIZE - 1)) == 0,
45
+ "CORRECTION_HISTORY_SIZE has to be a power of 2");
46
+
47
+ enum PawnHistoryType {
48
+ Normal,
49
+ Correction
50
+ };
51
+
52
+ template<PawnHistoryType T = Normal>
53
+ inline int pawn_structure_index(const Position& pos) {
54
+ return pos.pawn_key() & ((T == Normal ? PAWN_HISTORY_SIZE : CORRECTION_HISTORY_SIZE) - 1);
55
+ }
56
+
57
+ inline int minor_piece_index(const Position& pos) {
58
+ return pos.minor_piece_key() & (CORRECTION_HISTORY_SIZE - 1);
59
+ }
60
+
61
+ template<Color c>
62
+ inline int non_pawn_index(const Position& pos) {
63
+ return pos.non_pawn_key(c) & (CORRECTION_HISTORY_SIZE - 1);
64
+ }
65
+
66
+ // StatsEntry is the container of various numerical statistics. We use a class
67
+ // instead of a naked value to directly call history update operator<<() on
68
+ // the entry. The first template parameter T is the base type of the array,
69
+ // and the second template parameter D limits the range of updates in [-D, D]
70
+ // when we update values with the << operator
71
+ template<typename T, int D>
72
+ class StatsEntry {
73
+
74
+ static_assert(std::is_arithmetic_v<T>, "Not an arithmetic type");
75
+ static_assert(D <= std::numeric_limits<T>::max(), "D overflows T");
76
+
77
+ T entry;
78
+
79
+ public:
80
+ StatsEntry& operator=(const T& v) {
81
+ entry = v;
82
+ return *this;
83
+ }
84
+ operator const T&() const { return entry; }
85
+
86
+ void operator<<(int bonus) {
87
+ // Make sure that bonus is in range [-D, D]
88
+ int clampedBonus = std::clamp(bonus, -D, D);
89
+ entry += clampedBonus - entry * std::abs(clampedBonus) / D;
90
+
91
+ assert(std::abs(entry) <= D);
92
+ }
93
+ };
94
+
95
+ enum StatsType {
96
+ NoCaptures,
97
+ Captures
98
+ };
99
+
100
+ template<typename T, int D, std::size_t... Sizes>
101
+ using Stats = MultiArray<StatsEntry<T, D>, Sizes...>;
102
+
103
+ // ButterflyHistory records how often quiet moves have been successful or unsuccessful
104
+ // during the current search, and is used for reduction and move ordering decisions.
105
+ // It uses 2 tables (one for each color) indexed by the move's from and to squares,
106
+ // see https://www.chessprogramming.org/Butterfly_Boards (~11 elo)
107
+ using ButterflyHistory = Stats<std::int16_t, 7183, COLOR_NB, int(SQUARE_NB) * int(SQUARE_NB)>;
108
+
109
+ // LowPlyHistory is adressed by play and move's from and to squares, used
110
+ // to improve move ordering near the root
111
+ using LowPlyHistory =
112
+ Stats<std::int16_t, 7183, LOW_PLY_HISTORY_SIZE, int(SQUARE_NB) * int(SQUARE_NB)>;
113
+
114
+ // CapturePieceToHistory is addressed by a move's [piece][to][captured piece type]
115
+ using CapturePieceToHistory = Stats<std::int16_t, 10692, PIECE_NB, SQUARE_NB, PIECE_TYPE_NB>;
116
+
117
+ // PieceToHistory is like ButterflyHistory but is addressed by a move's [piece][to]
118
+ using PieceToHistory = Stats<std::int16_t, 30000, PIECE_NB, SQUARE_NB>;
119
+
120
+ // ContinuationHistory is the combined history of a given pair of moves, usually
121
+ // the current one given a previous one. The nested history table is based on
122
+ // PieceToHistory instead of ButterflyBoards.
123
+ // (~63 elo)
124
+ using ContinuationHistory = MultiArray<PieceToHistory, PIECE_NB, SQUARE_NB>;
125
+
126
+ // PawnHistory is addressed by the pawn structure and a move's [piece][to]
127
+ using PawnHistory = Stats<std::int16_t, 8192, PAWN_HISTORY_SIZE, PIECE_NB, SQUARE_NB>;
128
+
129
+ // Correction histories record differences between the static evaluation of
130
+ // positions and their search score. It is used to improve the static evaluation
131
+ // used by some search heuristics.
132
+ // see https://www.chessprogramming.org/Static_Evaluation_Correction_History
133
+ enum CorrHistType {
134
+ Pawn, // By color and pawn structure
135
+ Minor, // By color and positions of minor pieces (Knight, Bishop)
136
+ NonPawn, // By non-pawn material positions and color
137
+ PieceTo, // By [piece][to] move
138
+ Continuation, // Combined history of move pairs
139
+ };
140
+
141
+ namespace Detail {
142
+
143
+ template<CorrHistType>
144
+ struct CorrHistTypedef {
145
+ using type = Stats<std::int16_t, CORRECTION_HISTORY_LIMIT, CORRECTION_HISTORY_SIZE, COLOR_NB>;
146
+ };
147
+
148
+ template<>
149
+ struct CorrHistTypedef<PieceTo> {
150
+ using type = Stats<std::int16_t, CORRECTION_HISTORY_LIMIT, PIECE_NB, SQUARE_NB>;
151
+ };
152
+
153
+ template<>
154
+ struct CorrHistTypedef<Continuation> {
155
+ using type = MultiArray<CorrHistTypedef<PieceTo>::type, PIECE_NB, SQUARE_NB>;
156
+ };
157
+
158
+ template<>
159
+ struct CorrHistTypedef<NonPawn> {
160
+ using type =
161
+ Stats<std::int16_t, CORRECTION_HISTORY_LIMIT, CORRECTION_HISTORY_SIZE, COLOR_NB, COLOR_NB>;
162
+ };
163
+
164
+ }
165
+
166
+ template<CorrHistType T>
167
+ using CorrectionHistory = typename Detail::CorrHistTypedef<T>::type;
168
+
169
+ } // namespace Stockfish
170
+
171
+ #endif // #ifndef HISTORY_H_INCLUDED
stockfish/src/incbin/UNLICENCE ADDED
@@ -0,0 +1,26 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ The file "incbin.h" is free and unencumbered software released into
2
+ the public domain by Dale Weiler, see:
3
+ <https://github.com/graphitemaster/incbin>
4
+
5
+ Anyone is free to copy, modify, publish, use, compile, sell, or
6
+ distribute this software, either in source code form or as a compiled
7
+ binary, for any purpose, commercial or non-commercial, and by any
8
+ means.
9
+
10
+ In jurisdictions that recognize copyright laws, the author or authors
11
+ of this software dedicate any and all copyright interest in the
12
+ software to the public domain. We make this dedication for the benefit
13
+ of the public at large and to the detriment of our heirs and
14
+ successors. We intend this dedication to be an overt act of
15
+ relinquishment in perpetuity of all present and future rights to this
16
+ software under copyright law.
17
+
18
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
19
+ EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
20
+ MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
21
+ IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR
22
+ OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
23
+ ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
24
+ OTHER DEALINGS IN THE SOFTWARE.
25
+
26
+ For more information, please refer to <http://unlicense.org/>
stockfish/src/incbin/incbin.h ADDED
@@ -0,0 +1,476 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /**
2
+ * @file incbin.h
3
+ * @author Dale Weiler
4
+ * @brief Utility for including binary files
5
+ *
6
+ * Facilities for including binary files into the current translation unit and
7
+ * making use from them externally in other translation units.
8
+ */
9
+ #ifndef INCBIN_HDR
10
+ #define INCBIN_HDR
11
+ #include <limits.h>
12
+ #if defined(__AVX512BW__) || \
13
+ defined(__AVX512CD__) || \
14
+ defined(__AVX512DQ__) || \
15
+ defined(__AVX512ER__) || \
16
+ defined(__AVX512PF__) || \
17
+ defined(__AVX512VL__) || \
18
+ defined(__AVX512F__)
19
+ # define INCBIN_ALIGNMENT_INDEX 6
20
+ #elif defined(__AVX__) || \
21
+ defined(__AVX2__)
22
+ # define INCBIN_ALIGNMENT_INDEX 5
23
+ #elif defined(__SSE__) || \
24
+ defined(__SSE2__) || \
25
+ defined(__SSE3__) || \
26
+ defined(__SSSE3__) || \
27
+ defined(__SSE4_1__) || \
28
+ defined(__SSE4_2__) || \
29
+ defined(__neon__) || \
30
+ defined(__ARM_NEON) || \
31
+ defined(__ALTIVEC__)
32
+ # define INCBIN_ALIGNMENT_INDEX 4
33
+ #elif ULONG_MAX != 0xffffffffu
34
+ # define INCBIN_ALIGNMENT_INDEX 3
35
+ # else
36
+ # define INCBIN_ALIGNMENT_INDEX 2
37
+ #endif
38
+
39
+ /* Lookup table of (1 << n) where `n' is `INCBIN_ALIGNMENT_INDEX' */
40
+ #define INCBIN_ALIGN_SHIFT_0 1
41
+ #define INCBIN_ALIGN_SHIFT_1 2
42
+ #define INCBIN_ALIGN_SHIFT_2 4
43
+ #define INCBIN_ALIGN_SHIFT_3 8
44
+ #define INCBIN_ALIGN_SHIFT_4 16
45
+ #define INCBIN_ALIGN_SHIFT_5 32
46
+ #define INCBIN_ALIGN_SHIFT_6 64
47
+
48
+ /* Actual alignment value */
49
+ #define INCBIN_ALIGNMENT \
50
+ INCBIN_CONCATENATE( \
51
+ INCBIN_CONCATENATE(INCBIN_ALIGN_SHIFT, _), \
52
+ INCBIN_ALIGNMENT_INDEX)
53
+
54
+ /* Stringize */
55
+ #define INCBIN_STR(X) \
56
+ #X
57
+ #define INCBIN_STRINGIZE(X) \
58
+ INCBIN_STR(X)
59
+ /* Concatenate */
60
+ #define INCBIN_CAT(X, Y) \
61
+ X ## Y
62
+ #define INCBIN_CONCATENATE(X, Y) \
63
+ INCBIN_CAT(X, Y)
64
+ /* Deferred macro expansion */
65
+ #define INCBIN_EVAL(X) \
66
+ X
67
+ #define INCBIN_INVOKE(N, ...) \
68
+ INCBIN_EVAL(N(__VA_ARGS__))
69
+ /* Variable argument count for overloading by arity */
70
+ #define INCBIN_VA_ARG_COUNTER(_1, _2, _3, N, ...) N
71
+ #define INCBIN_VA_ARGC(...) INCBIN_VA_ARG_COUNTER(__VA_ARGS__, 3, 2, 1, 0)
72
+
73
+ /* Green Hills uses a different directive for including binary data */
74
+ #if defined(__ghs__)
75
+ # if (__ghs_asm == 2)
76
+ # define INCBIN_MACRO ".file"
77
+ /* Or consider the ".myrawdata" entry in the ld file */
78
+ # else
79
+ # define INCBIN_MACRO "\tINCBIN"
80
+ # endif
81
+ #else
82
+ # define INCBIN_MACRO ".incbin"
83
+ #endif
84
+
85
+ #ifndef _MSC_VER
86
+ # define INCBIN_ALIGN \
87
+ __attribute__((aligned(INCBIN_ALIGNMENT)))
88
+ #else
89
+ # define INCBIN_ALIGN __declspec(align(INCBIN_ALIGNMENT))
90
+ #endif
91
+
92
+ #if defined(__arm__) || /* GNU C and RealView */ \
93
+ defined(__arm) || /* Diab */ \
94
+ defined(_ARM) /* ImageCraft */
95
+ # define INCBIN_ARM
96
+ #endif
97
+
98
+ #ifdef __GNUC__
99
+ /* Utilize .balign where supported */
100
+ # define INCBIN_ALIGN_HOST ".balign " INCBIN_STRINGIZE(INCBIN_ALIGNMENT) "\n"
101
+ # define INCBIN_ALIGN_BYTE ".balign 1\n"
102
+ #elif defined(INCBIN_ARM)
103
+ /*
104
+ * On arm assemblers, the alignment value is calculated as (1 << n) where `n' is
105
+ * the shift count. This is the value passed to `.align'
106
+ */
107
+ # define INCBIN_ALIGN_HOST ".align " INCBIN_STRINGIZE(INCBIN_ALIGNMENT_INDEX) "\n"
108
+ # define INCBIN_ALIGN_BYTE ".align 0\n"
109
+ #else
110
+ /* We assume other inline assembler's treat `.align' as `.balign' */
111
+ # define INCBIN_ALIGN_HOST ".align " INCBIN_STRINGIZE(INCBIN_ALIGNMENT) "\n"
112
+ # define INCBIN_ALIGN_BYTE ".align 1\n"
113
+ #endif
114
+
115
+ /* INCBIN_CONST is used by incbin.c generated files */
116
+ #if defined(__cplusplus)
117
+ # define INCBIN_EXTERNAL extern "C"
118
+ # define INCBIN_CONST extern const
119
+ #else
120
+ # define INCBIN_EXTERNAL extern
121
+ # define INCBIN_CONST const
122
+ #endif
123
+
124
+ /**
125
+ * @brief Optionally override the linker section into which size and data is
126
+ * emitted.
127
+ *
128
+ * @warning If you use this facility, you might have to deal with
129
+ * platform-specific linker output section naming on your own.
130
+ */
131
+ #if !defined(INCBIN_OUTPUT_SECTION)
132
+ # if defined(__APPLE__)
133
+ # define INCBIN_OUTPUT_SECTION ".const_data"
134
+ # else
135
+ # define INCBIN_OUTPUT_SECTION ".rodata"
136
+ # endif
137
+ #endif
138
+
139
+ /**
140
+ * @brief Optionally override the linker section into which data is emitted.
141
+ *
142
+ * @warning If you use this facility, you might have to deal with
143
+ * platform-specific linker output section naming on your own.
144
+ */
145
+ #if !defined(INCBIN_OUTPUT_DATA_SECTION)
146
+ # define INCBIN_OUTPUT_DATA_SECTION INCBIN_OUTPUT_SECTION
147
+ #endif
148
+
149
+ /**
150
+ * @brief Optionally override the linker section into which size is emitted.
151
+ *
152
+ * @warning If you use this facility, you might have to deal with
153
+ * platform-specific linker output section naming on your own.
154
+ *
155
+ * @note This is useful for Harvard architectures where program memory cannot
156
+ * be directly read from the program without special instructions. With this you
157
+ * can chose to put the size variable in RAM rather than ROM.
158
+ */
159
+ #if !defined(INCBIN_OUTPUT_SIZE_SECTION)
160
+ # define INCBIN_OUTPUT_SIZE_SECTION INCBIN_OUTPUT_SECTION
161
+ #endif
162
+
163
+ #if defined(__APPLE__)
164
+ # include "TargetConditionals.h"
165
+ # if defined(TARGET_OS_IPHONE) && !defined(INCBIN_SILENCE_BITCODE_WARNING)
166
+ # warning "incbin is incompatible with bitcode. Using the library will break upload to App Store if you have bitcode enabled. Add `#define INCBIN_SILENCE_BITCODE_WARNING` before including this header to silence this warning."
167
+ # endif
168
+ /* The directives are different for Apple branded compilers */
169
+ # define INCBIN_SECTION INCBIN_OUTPUT_SECTION "\n"
170
+ # define INCBIN_GLOBAL(NAME) ".globl " INCBIN_MANGLE INCBIN_STRINGIZE(INCBIN_PREFIX) #NAME "\n"
171
+ # define INCBIN_INT ".long "
172
+ # define INCBIN_MANGLE "_"
173
+ # define INCBIN_BYTE ".byte "
174
+ # define INCBIN_TYPE(...)
175
+ #else
176
+ # define INCBIN_SECTION ".section " INCBIN_OUTPUT_SECTION "\n"
177
+ # define INCBIN_GLOBAL(NAME) ".global " INCBIN_STRINGIZE(INCBIN_PREFIX) #NAME "\n"
178
+ # if defined(__ghs__)
179
+ # define INCBIN_INT ".word "
180
+ # else
181
+ # define INCBIN_INT ".int "
182
+ # endif
183
+ # if defined(__USER_LABEL_PREFIX__)
184
+ # define INCBIN_MANGLE INCBIN_STRINGIZE(__USER_LABEL_PREFIX__)
185
+ # else
186
+ # define INCBIN_MANGLE ""
187
+ # endif
188
+ # if defined(INCBIN_ARM)
189
+ /* On arm assemblers, `@' is used as a line comment token */
190
+ # define INCBIN_TYPE(NAME) ".type " INCBIN_STRINGIZE(INCBIN_PREFIX) #NAME ", %object\n"
191
+ # elif defined(__MINGW32__) || defined(__MINGW64__)
192
+ /* Mingw doesn't support this directive either */
193
+ # define INCBIN_TYPE(NAME)
194
+ # else
195
+ /* It's safe to use `@' on other architectures */
196
+ # define INCBIN_TYPE(NAME) ".type " INCBIN_STRINGIZE(INCBIN_PREFIX) #NAME ", @object\n"
197
+ # endif
198
+ # define INCBIN_BYTE ".byte "
199
+ #endif
200
+
201
+ /* List of style types used for symbol names */
202
+ #define INCBIN_STYLE_CAMEL 0
203
+ #define INCBIN_STYLE_SNAKE 1
204
+
205
+ /**
206
+ * @brief Specify the prefix to use for symbol names.
207
+ *
208
+ * @note By default this is "g".
209
+ *
210
+ * @code
211
+ * #define INCBIN_PREFIX incbin
212
+ * #include "incbin.h"
213
+ * INCBIN(Foo, "foo.txt");
214
+ *
215
+ * // Now you have the following symbols instead:
216
+ * // const unsigned char incbinFoo<data>[];
217
+ * // const unsigned char *const incbinFoo<end>;
218
+ * // const unsigned int incbinFoo<size>;
219
+ * @endcode
220
+ */
221
+ #if !defined(INCBIN_PREFIX)
222
+ # define INCBIN_PREFIX g
223
+ #endif
224
+
225
+ /**
226
+ * @brief Specify the style used for symbol names.
227
+ *
228
+ * Possible options are
229
+ * - INCBIN_STYLE_CAMEL "CamelCase"
230
+ * - INCBIN_STYLE_SNAKE "snake_case"
231
+ *
232
+ * @note By default this is INCBIN_STYLE_CAMEL
233
+ *
234
+ * @code
235
+ * #define INCBIN_STYLE INCBIN_STYLE_SNAKE
236
+ * #include "incbin.h"
237
+ * INCBIN(foo, "foo.txt");
238
+ *
239
+ * // Now you have the following symbols:
240
+ * // const unsigned char <prefix>foo_data[];
241
+ * // const unsigned char *const <prefix>foo_end;
242
+ * // const unsigned int <prefix>foo_size;
243
+ * @endcode
244
+ */
245
+ #if !defined(INCBIN_STYLE)
246
+ # define INCBIN_STYLE INCBIN_STYLE_CAMEL
247
+ #endif
248
+
249
+ /* Style lookup tables */
250
+ #define INCBIN_STYLE_0_DATA Data
251
+ #define INCBIN_STYLE_0_END End
252
+ #define INCBIN_STYLE_0_SIZE Size
253
+ #define INCBIN_STYLE_1_DATA _data
254
+ #define INCBIN_STYLE_1_END _end
255
+ #define INCBIN_STYLE_1_SIZE _size
256
+
257
+ /* Style lookup: returning identifier */
258
+ #define INCBIN_STYLE_IDENT(TYPE) \
259
+ INCBIN_CONCATENATE( \
260
+ INCBIN_STYLE_, \
261
+ INCBIN_CONCATENATE( \
262
+ INCBIN_EVAL(INCBIN_STYLE), \
263
+ INCBIN_CONCATENATE(_, TYPE)))
264
+
265
+ /* Style lookup: returning string literal */
266
+ #define INCBIN_STYLE_STRING(TYPE) \
267
+ INCBIN_STRINGIZE( \
268
+ INCBIN_STYLE_IDENT(TYPE)) \
269
+
270
+ /* Generate the global labels by indirectly invoking the macro with our style
271
+ * type and concatenating the name against them. */
272
+ #define INCBIN_GLOBAL_LABELS(NAME, TYPE) \
273
+ INCBIN_INVOKE( \
274
+ INCBIN_GLOBAL, \
275
+ INCBIN_CONCATENATE( \
276
+ NAME, \
277
+ INCBIN_INVOKE( \
278
+ INCBIN_STYLE_IDENT, \
279
+ TYPE))) \
280
+ INCBIN_INVOKE( \
281
+ INCBIN_TYPE, \
282
+ INCBIN_CONCATENATE( \
283
+ NAME, \
284
+ INCBIN_INVOKE( \
285
+ INCBIN_STYLE_IDENT, \
286
+ TYPE)))
287
+
288
+ /**
289
+ * @brief Externally reference binary data included in another translation unit.
290
+ *
291
+ * Produces three external symbols that reference the binary data included in
292
+ * another translation unit.
293
+ *
294
+ * The symbol names are a concatenation of `INCBIN_PREFIX' before *NAME*; with
295
+ * "Data", as well as "End" and "Size" after. An example is provided below.
296
+ *
297
+ * @param TYPE Optional array type. Omitting this picks a default of `unsigned char`.
298
+ * @param NAME The name given for the binary data
299
+ *
300
+ * @code
301
+ * INCBIN_EXTERN(Foo);
302
+ *
303
+ * // Now you have the following symbols:
304
+ * // extern const unsigned char <prefix>Foo<data>[];
305
+ * // extern const unsigned char *const <prefix>Foo<end>;
306
+ * // extern const unsigned int <prefix>Foo<size>;
307
+ * @endcode
308
+ *
309
+ * You may specify a custom optional data type as well as the first argument.
310
+ * @code
311
+ * INCBIN_EXTERN(custom_type, Foo);
312
+ *
313
+ * // Now you have the following symbols:
314
+ * // extern const custom_type <prefix>Foo<data>[];
315
+ * // extern const custom_type *const <prefix>Foo<end>;
316
+ * // extern const unsigned int <prefix>Foo<size>;
317
+ * @endcode
318
+ */
319
+ #define INCBIN_EXTERN(...) \
320
+ INCBIN_CONCATENATE(INCBIN_EXTERN_, INCBIN_VA_ARGC(__VA_ARGS__))(__VA_ARGS__)
321
+ #define INCBIN_EXTERN_1(NAME, ...) \
322
+ INCBIN_EXTERN_2(unsigned char, NAME)
323
+ #define INCBIN_EXTERN_2(TYPE, NAME) \
324
+ INCBIN_EXTERNAL const INCBIN_ALIGN TYPE \
325
+ INCBIN_CONCATENATE( \
326
+ INCBIN_CONCATENATE(INCBIN_PREFIX, NAME), \
327
+ INCBIN_STYLE_IDENT(DATA))[]; \
328
+ INCBIN_EXTERNAL const INCBIN_ALIGN TYPE *const \
329
+ INCBIN_CONCATENATE( \
330
+ INCBIN_CONCATENATE(INCBIN_PREFIX, NAME), \
331
+ INCBIN_STYLE_IDENT(END)); \
332
+ INCBIN_EXTERNAL const unsigned int \
333
+ INCBIN_CONCATENATE( \
334
+ INCBIN_CONCATENATE(INCBIN_PREFIX, NAME), \
335
+ INCBIN_STYLE_IDENT(SIZE))
336
+
337
+ /**
338
+ * @brief Externally reference textual data included in another translation unit.
339
+ *
340
+ * Produces three external symbols that reference the textual data included in
341
+ * another translation unit.
342
+ *
343
+ * The symbol names are a concatenation of `INCBIN_PREFIX' before *NAME*; with
344
+ * "Data", as well as "End" and "Size" after. An example is provided below.
345
+ *
346
+ * @param NAME The name given for the textual data
347
+ *
348
+ * @code
349
+ * INCBIN_EXTERN(Foo);
350
+ *
351
+ * // Now you have the following symbols:
352
+ * // extern const char <prefix>Foo<data>[];
353
+ * // extern const char *const <prefix>Foo<end>;
354
+ * // extern const unsigned int <prefix>Foo<size>;
355
+ * @endcode
356
+ */
357
+ #define INCTXT_EXTERN(NAME) \
358
+ INCBIN_EXTERN_2(char, NAME)
359
+
360
+ /**
361
+ * @brief Include a binary file into the current translation unit.
362
+ *
363
+ * Includes a binary file into the current translation unit, producing three symbols
364
+ * for objects that encode the data and size respectively.
365
+ *
366
+ * The symbol names are a concatenation of `INCBIN_PREFIX' before *NAME*; with
367
+ * "Data", as well as "End" and "Size" after. An example is provided below.
368
+ *
369
+ * @param TYPE Optional array type. Omitting this picks a default of `unsigned char`.
370
+ * @param NAME The name to associate with this binary data (as an identifier.)
371
+ * @param FILENAME The file to include (as a string literal.)
372
+ *
373
+ * @code
374
+ * INCBIN(Icon, "icon.png");
375
+ *
376
+ * // Now you have the following symbols:
377
+ * // const unsigned char <prefix>Icon<data>[];
378
+ * // const unsigned char *const <prefix>Icon<end>;
379
+ * // const unsigned int <prefix>Icon<size>;
380
+ * @endcode
381
+ *
382
+ * You may specify a custom optional data type as well as the first argument.
383
+ * These macros are specialized by arity.
384
+ * @code
385
+ * INCBIN(custom_type, Icon, "icon.png");
386
+ *
387
+ * // Now you have the following symbols:
388
+ * // const custom_type <prefix>Icon<data>[];
389
+ * // const custom_type *const <prefix>Icon<end>;
390
+ * // const unsigned int <prefix>Icon<size>;
391
+ * @endcode
392
+ *
393
+ * @warning This must be used in global scope
394
+ * @warning The identifiers may be different if INCBIN_STYLE is not default
395
+ *
396
+ * To externally reference the data included by this in another translation unit
397
+ * please @see INCBIN_EXTERN.
398
+ */
399
+ #ifdef _MSC_VER
400
+ # define INCBIN(NAME, FILENAME) \
401
+ INCBIN_EXTERN(NAME)
402
+ #else
403
+ # define INCBIN(...) \
404
+ INCBIN_CONCATENATE(INCBIN_, INCBIN_VA_ARGC(__VA_ARGS__))(__VA_ARGS__)
405
+ # if defined(__GNUC__)
406
+ # define INCBIN_1(...) _Pragma("GCC error \"Single argument INCBIN not allowed\"")
407
+ # elif defined(__clang__)
408
+ # define INCBIN_1(...) _Pragma("clang error \"Single argument INCBIN not allowed\"")
409
+ # else
410
+ # define INCBIN_1(...) /* Cannot do anything here */
411
+ # endif
412
+ # define INCBIN_2(NAME, FILENAME) \
413
+ INCBIN_3(unsigned char, NAME, FILENAME)
414
+ # define INCBIN_3(TYPE, NAME, FILENAME) INCBIN_COMMON(TYPE, NAME, FILENAME, /* No terminator for binary data */)
415
+ # define INCBIN_COMMON(TYPE, NAME, FILENAME, TERMINATOR) \
416
+ __asm__(INCBIN_SECTION \
417
+ INCBIN_GLOBAL_LABELS(NAME, DATA) \
418
+ INCBIN_ALIGN_HOST \
419
+ INCBIN_MANGLE INCBIN_STRINGIZE(INCBIN_PREFIX) #NAME INCBIN_STYLE_STRING(DATA) ":\n" \
420
+ INCBIN_MACRO " \"" FILENAME "\"\n" \
421
+ TERMINATOR \
422
+ INCBIN_GLOBAL_LABELS(NAME, END) \
423
+ INCBIN_ALIGN_BYTE \
424
+ INCBIN_MANGLE INCBIN_STRINGIZE(INCBIN_PREFIX) #NAME INCBIN_STYLE_STRING(END) ":\n" \
425
+ INCBIN_BYTE "1\n" \
426
+ INCBIN_GLOBAL_LABELS(NAME, SIZE) \
427
+ INCBIN_ALIGN_HOST \
428
+ INCBIN_MANGLE INCBIN_STRINGIZE(INCBIN_PREFIX) #NAME INCBIN_STYLE_STRING(SIZE) ":\n" \
429
+ INCBIN_INT INCBIN_MANGLE INCBIN_STRINGIZE(INCBIN_PREFIX) #NAME INCBIN_STYLE_STRING(END) " - " \
430
+ INCBIN_MANGLE INCBIN_STRINGIZE(INCBIN_PREFIX) #NAME INCBIN_STYLE_STRING(DATA) "\n" \
431
+ INCBIN_ALIGN_HOST \
432
+ ".text\n" \
433
+ ); \
434
+ INCBIN_EXTERN(TYPE, NAME)
435
+ #endif
436
+
437
+ /**
438
+ * @brief Include a textual file into the current translation unit.
439
+ *
440
+ * This behaves the same as INCBIN except it produces char compatible arrays
441
+ * and implicitly adds a null-terminator byte, thus the size of data included
442
+ * by this is one byte larger than that of INCBIN.
443
+ *
444
+ * Includes a textual file into the current translation unit, producing three
445
+ * symbols for objects that encode the data and size respectively.
446
+ *
447
+ * The symbol names are a concatenation of `INCBIN_PREFIX' before *NAME*; with
448
+ * "Data", as well as "End" and "Size" after. An example is provided below.
449
+ *
450
+ * @param NAME The name to associate with this binary data (as an identifier.)
451
+ * @param FILENAME The file to include (as a string literal.)
452
+ *
453
+ * @code
454
+ * INCTXT(Readme, "readme.txt");
455
+ *
456
+ * // Now you have the following symbols:
457
+ * // const char <prefix>Readme<data>[];
458
+ * // const char *const <prefix>Readme<end>;
459
+ * // const unsigned int <prefix>Readme<size>;
460
+ * @endcode
461
+ *
462
+ * @warning This must be used in global scope
463
+ * @warning The identifiers may be different if INCBIN_STYLE is not default
464
+ *
465
+ * To externally reference the data included by this in another translation unit
466
+ * please @see INCBIN_EXTERN.
467
+ */
468
+ #if defined(_MSC_VER)
469
+ # define INCTXT(NAME, FILENAME) \
470
+ INCBIN_EXTERN(NAME)
471
+ #else
472
+ # define INCTXT(NAME, FILENAME) \
473
+ INCBIN_COMMON(char, NAME, FILENAME, INCBIN_BYTE "0\n")
474
+ #endif
475
+
476
+ #endif
stockfish/src/main.cpp ADDED
@@ -0,0 +1,44 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /*
2
+ Stockfish, a UCI chess playing engine derived from Glaurung 2.1
3
+ Copyright (C) 2004-2025 The Stockfish developers (see AUTHORS file)
4
+
5
+ Stockfish is free software: you can redistribute it and/or modify
6
+ it under the terms of the GNU General Public License as published by
7
+ the Free Software Foundation, either version 3 of the License, or
8
+ (at your option) any later version.
9
+
10
+ Stockfish is distributed in the hope that it will be useful,
11
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
12
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13
+ GNU General Public License for more details.
14
+
15
+ You should have received a copy of the GNU General Public License
16
+ along with this program. If not, see <http://www.gnu.org/licenses/>.
17
+ */
18
+
19
+ #include <iostream>
20
+
21
+ #include "bitboard.h"
22
+ #include "misc.h"
23
+ #include "position.h"
24
+ #include "types.h"
25
+ #include "uci.h"
26
+ #include "tune.h"
27
+
28
+ using namespace Stockfish;
29
+
30
+ int main(int argc, char* argv[]) {
31
+
32
+ std::cout << engine_info() << std::endl;
33
+
34
+ Bitboards::init();
35
+ Position::init();
36
+
37
+ UCIEngine uci(argc, argv);
38
+
39
+ Tune::init(uci.engine_options());
40
+
41
+ uci.loop();
42
+
43
+ return 0;
44
+ }
stockfish/src/memory.cpp ADDED
@@ -0,0 +1,268 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /*
2
+ Stockfish, a UCI chess playing engine derived from Glaurung 2.1
3
+ Copyright (C) 2004-2025 The Stockfish developers (see AUTHORS file)
4
+
5
+ Stockfish is free software: you can redistribute it and/or modify
6
+ it under the terms of the GNU General Public License as published by
7
+ the Free Software Foundation, either version 3 of the License, or
8
+ (at your option) any later version.
9
+
10
+ Stockfish is distributed in the hope that it will be useful,
11
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
12
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13
+ GNU General Public License for more details.
14
+
15
+ You should have received a copy of the GNU General Public License
16
+ along with this program. If not, see <http://www.gnu.org/licenses/>.
17
+ */
18
+
19
+ #include "memory.h"
20
+
21
+ #include <cstdlib>
22
+
23
+ #if __has_include("features.h")
24
+ #include <features.h>
25
+ #endif
26
+
27
+ #if defined(__linux__) && !defined(__ANDROID__)
28
+ #include <sys/mman.h>
29
+ #endif
30
+
31
+ #if defined(__APPLE__) || defined(__ANDROID__) || defined(__OpenBSD__) \
32
+ || (defined(__GLIBCXX__) && !defined(_GLIBCXX_HAVE_ALIGNED_ALLOC) && !defined(_WIN32)) \
33
+ || defined(__e2k__)
34
+ #define POSIXALIGNEDALLOC
35
+ #include <stdlib.h>
36
+ #endif
37
+
38
+ #ifdef _WIN32
39
+ #if _WIN32_WINNT < 0x0601
40
+ #undef _WIN32_WINNT
41
+ #define _WIN32_WINNT 0x0601 // Force to include needed API prototypes
42
+ #endif
43
+
44
+ #ifndef NOMINMAX
45
+ #define NOMINMAX
46
+ #endif
47
+
48
+ #include <ios> // std::hex, std::dec
49
+ #include <iostream> // std::cerr
50
+ #include <ostream> // std::endl
51
+ #include <windows.h>
52
+
53
+ // The needed Windows API for processor groups could be missed from old Windows
54
+ // versions, so instead of calling them directly (forcing the linker to resolve
55
+ // the calls at compile time), try to load them at runtime. To do this we need
56
+ // first to define the corresponding function pointers.
57
+
58
+ extern "C" {
59
+ using OpenProcessToken_t = bool (*)(HANDLE, DWORD, PHANDLE);
60
+ using LookupPrivilegeValueA_t = bool (*)(LPCSTR, LPCSTR, PLUID);
61
+ using AdjustTokenPrivileges_t =
62
+ bool (*)(HANDLE, BOOL, PTOKEN_PRIVILEGES, DWORD, PTOKEN_PRIVILEGES, PDWORD);
63
+ }
64
+ #endif
65
+
66
+
67
+ namespace Stockfish {
68
+
69
+ // Wrappers for systems where the c++17 implementation does not guarantee the
70
+ // availability of aligned_alloc(). Memory allocated with std_aligned_alloc()
71
+ // must be freed with std_aligned_free().
72
+
73
+ void* std_aligned_alloc(size_t alignment, size_t size) {
74
+ #if defined(_ISOC11_SOURCE)
75
+ return aligned_alloc(alignment, size);
76
+ #elif defined(POSIXALIGNEDALLOC)
77
+ void* mem = nullptr;
78
+ posix_memalign(&mem, alignment, size);
79
+ return mem;
80
+ #elif defined(_WIN32) && !defined(_M_ARM) && !defined(_M_ARM64)
81
+ return _mm_malloc(size, alignment);
82
+ #elif defined(_WIN32)
83
+ return _aligned_malloc(size, alignment);
84
+ #else
85
+ return std::aligned_alloc(alignment, size);
86
+ #endif
87
+ }
88
+
89
+ void std_aligned_free(void* ptr) {
90
+
91
+ #if defined(POSIXALIGNEDALLOC)
92
+ free(ptr);
93
+ #elif defined(_WIN32) && !defined(_M_ARM) && !defined(_M_ARM64)
94
+ _mm_free(ptr);
95
+ #elif defined(_WIN32)
96
+ _aligned_free(ptr);
97
+ #else
98
+ free(ptr);
99
+ #endif
100
+ }
101
+
102
+ // aligned_large_pages_alloc() will return suitably aligned memory,
103
+ // if possible using large pages.
104
+
105
+ #if defined(_WIN32)
106
+
107
+ static void* aligned_large_pages_alloc_windows([[maybe_unused]] size_t allocSize) {
108
+
109
+ #if !defined(_WIN64)
110
+ return nullptr;
111
+ #else
112
+
113
+ HANDLE hProcessToken{};
114
+ LUID luid{};
115
+ void* mem = nullptr;
116
+
117
+ const size_t largePageSize = GetLargePageMinimum();
118
+ if (!largePageSize)
119
+ return nullptr;
120
+
121
+ // Dynamically link OpenProcessToken, LookupPrivilegeValue and AdjustTokenPrivileges
122
+
123
+ HMODULE hAdvapi32 = GetModuleHandle(TEXT("advapi32.dll"));
124
+
125
+ if (!hAdvapi32)
126
+ hAdvapi32 = LoadLibrary(TEXT("advapi32.dll"));
127
+
128
+ auto OpenProcessToken_f =
129
+ OpenProcessToken_t((void (*)()) GetProcAddress(hAdvapi32, "OpenProcessToken"));
130
+ if (!OpenProcessToken_f)
131
+ return nullptr;
132
+ auto LookupPrivilegeValueA_f =
133
+ LookupPrivilegeValueA_t((void (*)()) GetProcAddress(hAdvapi32, "LookupPrivilegeValueA"));
134
+ if (!LookupPrivilegeValueA_f)
135
+ return nullptr;
136
+ auto AdjustTokenPrivileges_f =
137
+ AdjustTokenPrivileges_t((void (*)()) GetProcAddress(hAdvapi32, "AdjustTokenPrivileges"));
138
+ if (!AdjustTokenPrivileges_f)
139
+ return nullptr;
140
+
141
+ // We need SeLockMemoryPrivilege, so try to enable it for the process
142
+
143
+ if (!OpenProcessToken_f( // OpenProcessToken()
144
+ GetCurrentProcess(), TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, &hProcessToken))
145
+ return nullptr;
146
+
147
+ if (LookupPrivilegeValueA_f(nullptr, "SeLockMemoryPrivilege", &luid))
148
+ {
149
+ TOKEN_PRIVILEGES tp{};
150
+ TOKEN_PRIVILEGES prevTp{};
151
+ DWORD prevTpLen = 0;
152
+
153
+ tp.PrivilegeCount = 1;
154
+ tp.Privileges[0].Luid = luid;
155
+ tp.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED;
156
+
157
+ // Try to enable SeLockMemoryPrivilege. Note that even if AdjustTokenPrivileges()
158
+ // succeeds, we still need to query GetLastError() to ensure that the privileges
159
+ // were actually obtained.
160
+
161
+ if (AdjustTokenPrivileges_f(hProcessToken, FALSE, &tp, sizeof(TOKEN_PRIVILEGES), &prevTp,
162
+ &prevTpLen)
163
+ && GetLastError() == ERROR_SUCCESS)
164
+ {
165
+ // Round up size to full pages and allocate
166
+ allocSize = (allocSize + largePageSize - 1) & ~size_t(largePageSize - 1);
167
+ mem = VirtualAlloc(nullptr, allocSize, MEM_RESERVE | MEM_COMMIT | MEM_LARGE_PAGES,
168
+ PAGE_READWRITE);
169
+
170
+ // Privilege no longer needed, restore previous state
171
+ AdjustTokenPrivileges_f(hProcessToken, FALSE, &prevTp, 0, nullptr, nullptr);
172
+ }
173
+ }
174
+
175
+ CloseHandle(hProcessToken);
176
+
177
+ return mem;
178
+
179
+ #endif
180
+ }
181
+
182
+ void* aligned_large_pages_alloc(size_t allocSize) {
183
+
184
+ // Try to allocate large pages
185
+ void* mem = aligned_large_pages_alloc_windows(allocSize);
186
+
187
+ // Fall back to regular, page-aligned, allocation if necessary
188
+ if (!mem)
189
+ mem = VirtualAlloc(nullptr, allocSize, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE);
190
+
191
+ return mem;
192
+ }
193
+
194
+ #else
195
+
196
+ void* aligned_large_pages_alloc(size_t allocSize) {
197
+
198
+ #if defined(__linux__)
199
+ constexpr size_t alignment = 2 * 1024 * 1024; // 2MB page size assumed
200
+ #else
201
+ constexpr size_t alignment = 4096; // small page size assumed
202
+ #endif
203
+
204
+ // Round up to multiples of alignment
205
+ size_t size = ((allocSize + alignment - 1) / alignment) * alignment;
206
+ void* mem = std_aligned_alloc(alignment, size);
207
+ #if defined(MADV_HUGEPAGE)
208
+ madvise(mem, size, MADV_HUGEPAGE);
209
+ #endif
210
+ return mem;
211
+ }
212
+
213
+ #endif
214
+
215
+ bool has_large_pages() {
216
+
217
+ #if defined(_WIN32)
218
+
219
+ constexpr size_t page_size = 2 * 1024 * 1024; // 2MB page size assumed
220
+ void* mem = aligned_large_pages_alloc_windows(page_size);
221
+ if (mem == nullptr)
222
+ {
223
+ return false;
224
+ }
225
+ else
226
+ {
227
+ aligned_large_pages_free(mem);
228
+ return true;
229
+ }
230
+
231
+ #elif defined(__linux__)
232
+
233
+ #if defined(MADV_HUGEPAGE)
234
+ return true;
235
+ #else
236
+ return false;
237
+ #endif
238
+
239
+ #else
240
+
241
+ return false;
242
+
243
+ #endif
244
+ }
245
+
246
+
247
+ // aligned_large_pages_free() will free the previously memory allocated
248
+ // by aligned_large_pages_alloc(). The effect is a nop if mem == nullptr.
249
+
250
+ #if defined(_WIN32)
251
+
252
+ void aligned_large_pages_free(void* mem) {
253
+
254
+ if (mem && !VirtualFree(mem, 0, MEM_RELEASE))
255
+ {
256
+ DWORD err = GetLastError();
257
+ std::cerr << "Failed to free large page memory. Error code: 0x" << std::hex << err
258
+ << std::dec << std::endl;
259
+ exit(EXIT_FAILURE);
260
+ }
261
+ }
262
+
263
+ #else
264
+
265
+ void aligned_large_pages_free(void* mem) { std_aligned_free(mem); }
266
+
267
+ #endif
268
+ } // namespace Stockfish
stockfish/src/memory.h ADDED
@@ -0,0 +1,218 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /*
2
+ Stockfish, a UCI chess playing engine derived from Glaurung 2.1
3
+ Copyright (C) 2004-2025 The Stockfish developers (see AUTHORS file)
4
+
5
+ Stockfish is free software: you can redistribute it and/or modify
6
+ it under the terms of the GNU General Public License as published by
7
+ the Free Software Foundation, either version 3 of the License, or
8
+ (at your option) any later version.
9
+
10
+ Stockfish is distributed in the hope that it will be useful,
11
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
12
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13
+ GNU General Public License for more details.
14
+
15
+ You should have received a copy of the GNU General Public License
16
+ along with this program. If not, see <http://www.gnu.org/licenses/>.
17
+ */
18
+
19
+ #ifndef MEMORY_H_INCLUDED
20
+ #define MEMORY_H_INCLUDED
21
+
22
+ #include <algorithm>
23
+ #include <cstddef>
24
+ #include <cstdint>
25
+ #include <memory>
26
+ #include <new>
27
+ #include <type_traits>
28
+ #include <utility>
29
+
30
+ #include "types.h"
31
+
32
+ namespace Stockfish {
33
+
34
+ void* std_aligned_alloc(size_t alignment, size_t size);
35
+ void std_aligned_free(void* ptr);
36
+
37
+ // Memory aligned by page size, min alignment: 4096 bytes
38
+ void* aligned_large_pages_alloc(size_t size);
39
+ void aligned_large_pages_free(void* mem);
40
+
41
+ bool has_large_pages();
42
+
43
+ // Frees memory which was placed there with placement new.
44
+ // Works for both single objects and arrays of unknown bound.
45
+ template<typename T, typename FREE_FUNC>
46
+ void memory_deleter(T* ptr, FREE_FUNC free_func) {
47
+ if (!ptr)
48
+ return;
49
+
50
+ // Explicitly needed to call the destructor
51
+ if constexpr (!std::is_trivially_destructible_v<T>)
52
+ ptr->~T();
53
+
54
+ free_func(ptr);
55
+ return;
56
+ }
57
+
58
+ // Frees memory which was placed there with placement new.
59
+ // Works for both single objects and arrays of unknown bound.
60
+ template<typename T, typename FREE_FUNC>
61
+ void memory_deleter_array(T* ptr, FREE_FUNC free_func) {
62
+ if (!ptr)
63
+ return;
64
+
65
+
66
+ // Move back on the pointer to where the size is allocated
67
+ const size_t array_offset = std::max(sizeof(size_t), alignof(T));
68
+ char* raw_memory = reinterpret_cast<char*>(ptr) - array_offset;
69
+
70
+ if constexpr (!std::is_trivially_destructible_v<T>)
71
+ {
72
+ const size_t size = *reinterpret_cast<size_t*>(raw_memory);
73
+
74
+ // Explicitly call the destructor for each element in reverse order
75
+ for (size_t i = size; i-- > 0;)
76
+ ptr[i].~T();
77
+ }
78
+
79
+ free_func(raw_memory);
80
+ }
81
+
82
+ // Allocates memory for a single object and places it there with placement new
83
+ template<typename T, typename ALLOC_FUNC, typename... Args>
84
+ inline std::enable_if_t<!std::is_array_v<T>, T*> memory_allocator(ALLOC_FUNC alloc_func,
85
+ Args&&... args) {
86
+ void* raw_memory = alloc_func(sizeof(T));
87
+ ASSERT_ALIGNED(raw_memory, alignof(T));
88
+ return new (raw_memory) T(std::forward<Args>(args)...);
89
+ }
90
+
91
+ // Allocates memory for an array of unknown bound and places it there with placement new
92
+ template<typename T, typename ALLOC_FUNC>
93
+ inline std::enable_if_t<std::is_array_v<T>, std::remove_extent_t<T>*>
94
+ memory_allocator(ALLOC_FUNC alloc_func, size_t num) {
95
+ using ElementType = std::remove_extent_t<T>;
96
+
97
+ const size_t array_offset = std::max(sizeof(size_t), alignof(ElementType));
98
+
99
+ // Save the array size in the memory location
100
+ char* raw_memory =
101
+ reinterpret_cast<char*>(alloc_func(array_offset + num * sizeof(ElementType)));
102
+ ASSERT_ALIGNED(raw_memory, alignof(T));
103
+
104
+ new (raw_memory) size_t(num);
105
+
106
+ for (size_t i = 0; i < num; ++i)
107
+ new (raw_memory + array_offset + i * sizeof(ElementType)) ElementType();
108
+
109
+ // Need to return the pointer at the start of the array so that
110
+ // the indexing in unique_ptr<T[]> works.
111
+ return reinterpret_cast<ElementType*>(raw_memory + array_offset);
112
+ }
113
+
114
+ //
115
+ //
116
+ // aligned large page unique ptr
117
+ //
118
+ //
119
+
120
+ template<typename T>
121
+ struct LargePageDeleter {
122
+ void operator()(T* ptr) const { return memory_deleter<T>(ptr, aligned_large_pages_free); }
123
+ };
124
+
125
+ template<typename T>
126
+ struct LargePageArrayDeleter {
127
+ void operator()(T* ptr) const { return memory_deleter_array<T>(ptr, aligned_large_pages_free); }
128
+ };
129
+
130
+ template<typename T>
131
+ using LargePagePtr =
132
+ std::conditional_t<std::is_array_v<T>,
133
+ std::unique_ptr<T, LargePageArrayDeleter<std::remove_extent_t<T>>>,
134
+ std::unique_ptr<T, LargePageDeleter<T>>>;
135
+
136
+ // make_unique_large_page for single objects
137
+ template<typename T, typename... Args>
138
+ std::enable_if_t<!std::is_array_v<T>, LargePagePtr<T>> make_unique_large_page(Args&&... args) {
139
+ static_assert(alignof(T) <= 4096,
140
+ "aligned_large_pages_alloc() may fail for such a big alignment requirement of T");
141
+
142
+ T* obj = memory_allocator<T>(aligned_large_pages_alloc, std::forward<Args>(args)...);
143
+
144
+ return LargePagePtr<T>(obj);
145
+ }
146
+
147
+ // make_unique_large_page for arrays of unknown bound
148
+ template<typename T>
149
+ std::enable_if_t<std::is_array_v<T>, LargePagePtr<T>> make_unique_large_page(size_t num) {
150
+ using ElementType = std::remove_extent_t<T>;
151
+
152
+ static_assert(alignof(ElementType) <= 4096,
153
+ "aligned_large_pages_alloc() may fail for such a big alignment requirement of T");
154
+
155
+ ElementType* memory = memory_allocator<T>(aligned_large_pages_alloc, num);
156
+
157
+ return LargePagePtr<T>(memory);
158
+ }
159
+
160
+ //
161
+ //
162
+ // aligned unique ptr
163
+ //
164
+ //
165
+
166
+ template<typename T>
167
+ struct AlignedDeleter {
168
+ void operator()(T* ptr) const { return memory_deleter<T>(ptr, std_aligned_free); }
169
+ };
170
+
171
+ template<typename T>
172
+ struct AlignedArrayDeleter {
173
+ void operator()(T* ptr) const { return memory_deleter_array<T>(ptr, std_aligned_free); }
174
+ };
175
+
176
+ template<typename T>
177
+ using AlignedPtr =
178
+ std::conditional_t<std::is_array_v<T>,
179
+ std::unique_ptr<T, AlignedArrayDeleter<std::remove_extent_t<T>>>,
180
+ std::unique_ptr<T, AlignedDeleter<T>>>;
181
+
182
+ // make_unique_aligned for single objects
183
+ template<typename T, typename... Args>
184
+ std::enable_if_t<!std::is_array_v<T>, AlignedPtr<T>> make_unique_aligned(Args&&... args) {
185
+ const auto func = [](size_t size) { return std_aligned_alloc(alignof(T), size); };
186
+ T* obj = memory_allocator<T>(func, std::forward<Args>(args)...);
187
+
188
+ return AlignedPtr<T>(obj);
189
+ }
190
+
191
+ // make_unique_aligned for arrays of unknown bound
192
+ template<typename T>
193
+ std::enable_if_t<std::is_array_v<T>, AlignedPtr<T>> make_unique_aligned(size_t num) {
194
+ using ElementType = std::remove_extent_t<T>;
195
+
196
+ const auto func = [](size_t size) { return std_aligned_alloc(alignof(ElementType), size); };
197
+ ElementType* memory = memory_allocator<T>(func, num);
198
+
199
+ return AlignedPtr<T>(memory);
200
+ }
201
+
202
+
203
+ // Get the first aligned element of an array.
204
+ // ptr must point to an array of size at least `sizeof(T) * N + alignment` bytes,
205
+ // where N is the number of elements in the array.
206
+ template<uintptr_t Alignment, typename T>
207
+ T* align_ptr_up(T* ptr) {
208
+ static_assert(alignof(T) < Alignment);
209
+
210
+ const uintptr_t ptrint = reinterpret_cast<uintptr_t>(reinterpret_cast<char*>(ptr));
211
+ return reinterpret_cast<T*>(
212
+ reinterpret_cast<char*>((ptrint + (Alignment - 1)) / Alignment * Alignment));
213
+ }
214
+
215
+
216
+ } // namespace Stockfish
217
+
218
+ #endif // #ifndef MEMORY_H_INCLUDED
stockfish/src/misc.cpp ADDED
@@ -0,0 +1,524 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /*
2
+ Stockfish, a UCI chess playing engine derived from Glaurung 2.1
3
+ Copyright (C) 2004-2025 The Stockfish developers (see AUTHORS file)
4
+
5
+ Stockfish is free software: you can redistribute it and/or modify
6
+ it under the terms of the GNU General Public License as published by
7
+ the Free Software Foundation, either version 3 of the License, or
8
+ (at your option) any later version.
9
+
10
+ Stockfish is distributed in the hope that it will be useful,
11
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
12
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13
+ GNU General Public License for more details.
14
+
15
+ You should have received a copy of the GNU General Public License
16
+ along with this program. If not, see <http://www.gnu.org/licenses/>.
17
+ */
18
+
19
+ #include "misc.h"
20
+
21
+ #include <array>
22
+ #include <atomic>
23
+ #include <cassert>
24
+ #include <cctype>
25
+ #include <cmath>
26
+ #include <cstdlib>
27
+ #include <fstream>
28
+ #include <iomanip>
29
+ #include <iostream>
30
+ #include <iterator>
31
+ #include <limits>
32
+ #include <mutex>
33
+ #include <sstream>
34
+ #include <string_view>
35
+
36
+ #include "types.h"
37
+
38
+ namespace Stockfish {
39
+
40
+ namespace {
41
+
42
+ // Version number or dev.
43
+ constexpr std::string_view version = "17.1";
44
+
45
+ // Our fancy logging facility. The trick here is to replace cin.rdbuf() and
46
+ // cout.rdbuf() with two Tie objects that tie cin and cout to a file stream. We
47
+ // can toggle the logging of std::cout and std:cin at runtime whilst preserving
48
+ // usual I/O functionality, all without changing a single line of code!
49
+ // Idea from http://groups.google.com/group/comp.lang.c++/msg/1d941c0f26ea0d81
50
+
51
+ struct Tie: public std::streambuf { // MSVC requires split streambuf for cin and cout
52
+
53
+ Tie(std::streambuf* b, std::streambuf* l) :
54
+ buf(b),
55
+ logBuf(l) {}
56
+
57
+ int sync() override { return logBuf->pubsync(), buf->pubsync(); }
58
+ int overflow(int c) override { return log(buf->sputc(char(c)), "<< "); }
59
+ int underflow() override { return buf->sgetc(); }
60
+ int uflow() override { return log(buf->sbumpc(), ">> "); }
61
+
62
+ std::streambuf *buf, *logBuf;
63
+
64
+ int log(int c, const char* prefix) {
65
+
66
+ static int last = '\n'; // Single log file
67
+
68
+ if (last == '\n')
69
+ logBuf->sputn(prefix, 3);
70
+
71
+ return last = logBuf->sputc(char(c));
72
+ }
73
+ };
74
+
75
+ class Logger {
76
+
77
+ Logger() :
78
+ in(std::cin.rdbuf(), file.rdbuf()),
79
+ out(std::cout.rdbuf(), file.rdbuf()) {}
80
+ ~Logger() { start(""); }
81
+
82
+ std::ofstream file;
83
+ Tie in, out;
84
+
85
+ public:
86
+ static void start(const std::string& fname) {
87
+
88
+ static Logger l;
89
+
90
+ if (l.file.is_open())
91
+ {
92
+ std::cout.rdbuf(l.out.buf);
93
+ std::cin.rdbuf(l.in.buf);
94
+ l.file.close();
95
+ }
96
+
97
+ if (!fname.empty())
98
+ {
99
+ l.file.open(fname, std::ifstream::out);
100
+
101
+ if (!l.file.is_open())
102
+ {
103
+ std::cerr << "Unable to open debug log file " << fname << std::endl;
104
+ exit(EXIT_FAILURE);
105
+ }
106
+
107
+ std::cin.rdbuf(&l.in);
108
+ std::cout.rdbuf(&l.out);
109
+ }
110
+ }
111
+ };
112
+
113
+ } // namespace
114
+
115
+
116
+ // Returns the full name of the current Stockfish version.
117
+ //
118
+ // For local dev compiles we try to append the commit SHA and
119
+ // commit date from git. If that fails only the local compilation
120
+ // date is set and "nogit" is specified:
121
+ // Stockfish dev-YYYYMMDD-SHA
122
+ // or
123
+ // Stockfish dev-YYYYMMDD-nogit
124
+ //
125
+ // For releases (non-dev builds) we only include the version number:
126
+ // Stockfish version
127
+ std::string engine_version_info() {
128
+ std::stringstream ss;
129
+ ss << "Stockfish " << version << std::setfill('0');
130
+
131
+ if constexpr (version == "dev")
132
+ {
133
+ ss << "-";
134
+ #ifdef GIT_DATE
135
+ ss << stringify(GIT_DATE);
136
+ #else
137
+ constexpr std::string_view months("Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec");
138
+
139
+ std::string month, day, year;
140
+ std::stringstream date(__DATE__); // From compiler, format is "Sep 21 2008"
141
+
142
+ date >> month >> day >> year;
143
+ ss << year << std::setw(2) << std::setfill('0') << (1 + months.find(month) / 4)
144
+ << std::setw(2) << std::setfill('0') << day;
145
+ #endif
146
+
147
+ ss << "-";
148
+
149
+ #ifdef GIT_SHA
150
+ ss << stringify(GIT_SHA);
151
+ #else
152
+ ss << "nogit";
153
+ #endif
154
+ }
155
+
156
+ return ss.str();
157
+ }
158
+
159
+ std::string engine_info(bool to_uci) {
160
+ return engine_version_info() + (to_uci ? "\nid author " : " by ")
161
+ + "the Stockfish developers (see AUTHORS file)";
162
+ }
163
+
164
+
165
+ // Returns a string trying to describe the compiler we use
166
+ std::string compiler_info() {
167
+
168
+ #define make_version_string(major, minor, patch) \
169
+ stringify(major) "." stringify(minor) "." stringify(patch)
170
+
171
+ // Predefined macros hell:
172
+ //
173
+ // __GNUC__ Compiler is GCC, Clang or ICX
174
+ // __clang__ Compiler is Clang or ICX
175
+ // __INTEL_LLVM_COMPILER Compiler is ICX
176
+ // _MSC_VER Compiler is MSVC
177
+ // _WIN32 Building on Windows (any)
178
+ // _WIN64 Building on Windows 64 bit
179
+
180
+ std::string compiler = "\nCompiled by : ";
181
+
182
+ #if defined(__INTEL_LLVM_COMPILER)
183
+ compiler += "ICX ";
184
+ compiler += stringify(__INTEL_LLVM_COMPILER);
185
+ #elif defined(__clang__)
186
+ compiler += "clang++ ";
187
+ compiler += make_version_string(__clang_major__, __clang_minor__, __clang_patchlevel__);
188
+ #elif _MSC_VER
189
+ compiler += "MSVC ";
190
+ compiler += "(version ";
191
+ compiler += stringify(_MSC_FULL_VER) "." stringify(_MSC_BUILD);
192
+ compiler += ")";
193
+ #elif defined(__e2k__) && defined(__LCC__)
194
+ #define dot_ver2(n) \
195
+ compiler += char('.'); \
196
+ compiler += char('0' + (n) / 10); \
197
+ compiler += char('0' + (n) % 10);
198
+
199
+ compiler += "MCST LCC ";
200
+ compiler += "(version ";
201
+ compiler += std::to_string(__LCC__ / 100);
202
+ dot_ver2(__LCC__ % 100) dot_ver2(__LCC_MINOR__) compiler += ")";
203
+ #elif __GNUC__
204
+ compiler += "g++ (GNUC) ";
205
+ compiler += make_version_string(__GNUC__, __GNUC_MINOR__, __GNUC_PATCHLEVEL__);
206
+ #else
207
+ compiler += "Unknown compiler ";
208
+ compiler += "(unknown version)";
209
+ #endif
210
+
211
+ #if defined(__APPLE__)
212
+ compiler += " on Apple";
213
+ #elif defined(__CYGWIN__)
214
+ compiler += " on Cygwin";
215
+ #elif defined(__MINGW64__)
216
+ compiler += " on MinGW64";
217
+ #elif defined(__MINGW32__)
218
+ compiler += " on MinGW32";
219
+ #elif defined(__ANDROID__)
220
+ compiler += " on Android";
221
+ #elif defined(__linux__)
222
+ compiler += " on Linux";
223
+ #elif defined(_WIN64)
224
+ compiler += " on Microsoft Windows 64-bit";
225
+ #elif defined(_WIN32)
226
+ compiler += " on Microsoft Windows 32-bit";
227
+ #else
228
+ compiler += " on unknown system";
229
+ #endif
230
+
231
+ compiler += "\nCompilation architecture : ";
232
+ #if defined(ARCH)
233
+ compiler += stringify(ARCH);
234
+ #else
235
+ compiler += "(undefined architecture)";
236
+ #endif
237
+
238
+ compiler += "\nCompilation settings : ";
239
+ compiler += (Is64Bit ? "64bit" : "32bit");
240
+ #if defined(USE_VNNI)
241
+ compiler += " VNNI";
242
+ #endif
243
+ #if defined(USE_AVX512)
244
+ compiler += " AVX512";
245
+ #endif
246
+ compiler += (HasPext ? " BMI2" : "");
247
+ #if defined(USE_AVX2)
248
+ compiler += " AVX2";
249
+ #endif
250
+ #if defined(USE_SSE41)
251
+ compiler += " SSE41";
252
+ #endif
253
+ #if defined(USE_SSSE3)
254
+ compiler += " SSSE3";
255
+ #endif
256
+ #if defined(USE_SSE2)
257
+ compiler += " SSE2";
258
+ #endif
259
+ compiler += (HasPopCnt ? " POPCNT" : "");
260
+ #if defined(USE_NEON_DOTPROD)
261
+ compiler += " NEON_DOTPROD";
262
+ #elif defined(USE_NEON)
263
+ compiler += " NEON";
264
+ #endif
265
+
266
+ #if !defined(NDEBUG)
267
+ compiler += " DEBUG";
268
+ #endif
269
+
270
+ compiler += "\nCompiler __VERSION__ macro : ";
271
+ #ifdef __VERSION__
272
+ compiler += __VERSION__;
273
+ #else
274
+ compiler += "(undefined macro)";
275
+ #endif
276
+
277
+ compiler += "\n";
278
+
279
+ return compiler;
280
+ }
281
+
282
+
283
+ // Debug functions used mainly to collect run-time statistics
284
+ constexpr int MaxDebugSlots = 32;
285
+
286
+ namespace {
287
+
288
+ template<size_t N>
289
+ struct DebugInfo {
290
+ std::array<std::atomic<int64_t>, N> data = {0};
291
+
292
+ [[nodiscard]] constexpr std::atomic<int64_t>& operator[](size_t index) {
293
+ assert(index < N);
294
+ return data[index];
295
+ }
296
+
297
+ constexpr DebugInfo& operator=(const DebugInfo& other) {
298
+ for (size_t i = 0; i < N; i++)
299
+ data[i].store(other.data[i].load());
300
+ return *this;
301
+ }
302
+ };
303
+
304
+ struct DebugExtremes: public DebugInfo<3> {
305
+ DebugExtremes() {
306
+ data[1] = std::numeric_limits<int64_t>::min();
307
+ data[2] = std::numeric_limits<int64_t>::max();
308
+ }
309
+ };
310
+
311
+ std::array<DebugInfo<2>, MaxDebugSlots> hit;
312
+ std::array<DebugInfo<2>, MaxDebugSlots> mean;
313
+ std::array<DebugInfo<3>, MaxDebugSlots> stdev;
314
+ std::array<DebugInfo<6>, MaxDebugSlots> correl;
315
+ std::array<DebugExtremes, MaxDebugSlots> extremes;
316
+
317
+ } // namespace
318
+
319
+ void dbg_hit_on(bool cond, int slot) {
320
+
321
+ ++hit.at(slot)[0];
322
+ if (cond)
323
+ ++hit.at(slot)[1];
324
+ }
325
+
326
+ void dbg_mean_of(int64_t value, int slot) {
327
+
328
+ ++mean.at(slot)[0];
329
+ mean.at(slot)[1] += value;
330
+ }
331
+
332
+ void dbg_stdev_of(int64_t value, int slot) {
333
+
334
+ ++stdev.at(slot)[0];
335
+ stdev.at(slot)[1] += value;
336
+ stdev.at(slot)[2] += value * value;
337
+ }
338
+
339
+ void dbg_extremes_of(int64_t value, int slot) {
340
+ ++extremes.at(slot)[0];
341
+
342
+ int64_t current_max = extremes.at(slot)[1].load();
343
+ while (current_max < value && !extremes.at(slot)[1].compare_exchange_weak(current_max, value))
344
+ {}
345
+
346
+ int64_t current_min = extremes.at(slot)[2].load();
347
+ while (current_min > value && !extremes.at(slot)[2].compare_exchange_weak(current_min, value))
348
+ {}
349
+ }
350
+
351
+ void dbg_correl_of(int64_t value1, int64_t value2, int slot) {
352
+
353
+ ++correl.at(slot)[0];
354
+ correl.at(slot)[1] += value1;
355
+ correl.at(slot)[2] += value1 * value1;
356
+ correl.at(slot)[3] += value2;
357
+ correl.at(slot)[4] += value2 * value2;
358
+ correl.at(slot)[5] += value1 * value2;
359
+ }
360
+
361
+ void dbg_print() {
362
+
363
+ int64_t n;
364
+ auto E = [&n](int64_t x) { return double(x) / n; };
365
+ auto sqr = [](double x) { return x * x; };
366
+
367
+ for (int i = 0; i < MaxDebugSlots; ++i)
368
+ if ((n = hit[i][0]))
369
+ std::cerr << "Hit #" << i << ": Total " << n << " Hits " << hit[i][1]
370
+ << " Hit Rate (%) " << 100.0 * E(hit[i][1]) << std::endl;
371
+
372
+ for (int i = 0; i < MaxDebugSlots; ++i)
373
+ if ((n = mean[i][0]))
374
+ {
375
+ std::cerr << "Mean #" << i << ": Total " << n << " Mean " << E(mean[i][1]) << std::endl;
376
+ }
377
+
378
+ for (int i = 0; i < MaxDebugSlots; ++i)
379
+ if ((n = stdev[i][0]))
380
+ {
381
+ double r = sqrt(E(stdev[i][2]) - sqr(E(stdev[i][1])));
382
+ std::cerr << "Stdev #" << i << ": Total " << n << " Stdev " << r << std::endl;
383
+ }
384
+
385
+ for (int i = 0; i < MaxDebugSlots; ++i)
386
+ if ((n = extremes[i][0]))
387
+ {
388
+ std::cerr << "Extremity #" << i << ": Total " << n << " Min " << extremes[i][2]
389
+ << " Max " << extremes[i][1] << std::endl;
390
+ }
391
+
392
+ for (int i = 0; i < MaxDebugSlots; ++i)
393
+ if ((n = correl[i][0]))
394
+ {
395
+ double r = (E(correl[i][5]) - E(correl[i][1]) * E(correl[i][3]))
396
+ / (sqrt(E(correl[i][2]) - sqr(E(correl[i][1])))
397
+ * sqrt(E(correl[i][4]) - sqr(E(correl[i][3]))));
398
+ std::cerr << "Correl. #" << i << ": Total " << n << " Coefficient " << r << std::endl;
399
+ }
400
+ }
401
+
402
+ void dbg_clear() {
403
+ hit.fill({});
404
+ mean.fill({});
405
+ stdev.fill({});
406
+ correl.fill({});
407
+ extremes.fill({});
408
+ }
409
+
410
+ // Used to serialize access to std::cout
411
+ // to avoid multiple threads writing at the same time.
412
+ std::ostream& operator<<(std::ostream& os, SyncCout sc) {
413
+
414
+ static std::mutex m;
415
+
416
+ if (sc == IO_LOCK)
417
+ m.lock();
418
+
419
+ if (sc == IO_UNLOCK)
420
+ m.unlock();
421
+
422
+ return os;
423
+ }
424
+
425
+ void sync_cout_start() { std::cout << IO_LOCK; }
426
+ void sync_cout_end() { std::cout << IO_UNLOCK; }
427
+
428
+ // Trampoline helper to avoid moving Logger to misc.h
429
+ void start_logger(const std::string& fname) { Logger::start(fname); }
430
+
431
+
432
+ #ifdef NO_PREFETCH
433
+
434
+ void prefetch(const void*) {}
435
+
436
+ #else
437
+
438
+ void prefetch(const void* addr) {
439
+
440
+ #if defined(_MSC_VER)
441
+ _mm_prefetch((char const*) addr, _MM_HINT_T0);
442
+ #else
443
+ __builtin_prefetch(addr);
444
+ #endif
445
+ }
446
+
447
+ #endif
448
+
449
+ #ifdef _WIN32
450
+ #include <direct.h>
451
+ #define GETCWD _getcwd
452
+ #else
453
+ #include <unistd.h>
454
+ #define GETCWD getcwd
455
+ #endif
456
+
457
+ size_t str_to_size_t(const std::string& s) {
458
+ unsigned long long value = std::stoull(s);
459
+ if (value > std::numeric_limits<size_t>::max())
460
+ std::exit(EXIT_FAILURE);
461
+ return static_cast<size_t>(value);
462
+ }
463
+
464
+ std::optional<std::string> read_file_to_string(const std::string& path) {
465
+ std::ifstream f(path, std::ios_base::binary);
466
+ if (!f)
467
+ return std::nullopt;
468
+ return std::string(std::istreambuf_iterator<char>(f), std::istreambuf_iterator<char>());
469
+ }
470
+
471
+ void remove_whitespace(std::string& s) {
472
+ s.erase(std::remove_if(s.begin(), s.end(), [](char c) { return std::isspace(c); }), s.end());
473
+ }
474
+
475
+ bool is_whitespace(std::string_view s) {
476
+ return std::all_of(s.begin(), s.end(), [](char c) { return std::isspace(c); });
477
+ }
478
+
479
+ std::string CommandLine::get_binary_directory(std::string argv0) {
480
+ std::string pathSeparator;
481
+
482
+ #ifdef _WIN32
483
+ pathSeparator = "\\";
484
+ #ifdef _MSC_VER
485
+ // Under windows argv[0] may not have the extension. Also _get_pgmptr() had
486
+ // issues in some Windows 10 versions, so check returned values carefully.
487
+ char* pgmptr = nullptr;
488
+ if (!_get_pgmptr(&pgmptr) && pgmptr != nullptr && *pgmptr)
489
+ argv0 = pgmptr;
490
+ #endif
491
+ #else
492
+ pathSeparator = "/";
493
+ #endif
494
+
495
+ // Extract the working directory
496
+ auto workingDirectory = CommandLine::get_working_directory();
497
+
498
+ // Extract the binary directory path from argv0
499
+ auto binaryDirectory = argv0;
500
+ size_t pos = binaryDirectory.find_last_of("\\/");
501
+ if (pos == std::string::npos)
502
+ binaryDirectory = "." + pathSeparator;
503
+ else
504
+ binaryDirectory.resize(pos + 1);
505
+
506
+ // Pattern replacement: "./" at the start of path is replaced by the working directory
507
+ if (binaryDirectory.find("." + pathSeparator) == 0)
508
+ binaryDirectory.replace(0, 1, workingDirectory);
509
+
510
+ return binaryDirectory;
511
+ }
512
+
513
+ std::string CommandLine::get_working_directory() {
514
+ std::string workingDirectory = "";
515
+ char buff[40000];
516
+ char* cwd = GETCWD(buff, 40000);
517
+ if (cwd)
518
+ workingDirectory = cwd;
519
+
520
+ return workingDirectory;
521
+ }
522
+
523
+
524
+ } // namespace Stockfish
stockfish/src/misc.h ADDED
@@ -0,0 +1,322 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /*
2
+ Stockfish, a UCI chess playing engine derived from Glaurung 2.1
3
+ Copyright (C) 2004-2025 The Stockfish developers (see AUTHORS file)
4
+
5
+ Stockfish is free software: you can redistribute it and/or modify
6
+ it under the terms of the GNU General Public License as published by
7
+ the Free Software Foundation, either version 3 of the License, or
8
+ (at your option) any later version.
9
+
10
+ Stockfish is distributed in the hope that it will be useful,
11
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
12
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13
+ GNU General Public License for more details.
14
+
15
+ You should have received a copy of the GNU General Public License
16
+ along with this program. If not, see <http://www.gnu.org/licenses/>.
17
+ */
18
+
19
+ #ifndef MISC_H_INCLUDED
20
+ #define MISC_H_INCLUDED
21
+
22
+ #include <algorithm>
23
+ #include <array>
24
+ #include <cassert>
25
+ #include <chrono>
26
+ #include <cstddef>
27
+ #include <cstdint>
28
+ #include <cstdio>
29
+ #include <iosfwd>
30
+ #include <optional>
31
+ #include <string>
32
+ #include <string_view>
33
+ #include <vector>
34
+
35
+ #define stringify2(x) #x
36
+ #define stringify(x) stringify2(x)
37
+
38
+ namespace Stockfish {
39
+
40
+ std::string engine_version_info();
41
+ std::string engine_info(bool to_uci = false);
42
+ std::string compiler_info();
43
+
44
+ // Preloads the given address in L1/L2 cache. This is a non-blocking
45
+ // function that doesn't stall the CPU waiting for data to be loaded from memory,
46
+ // which can be quite slow.
47
+ void prefetch(const void* addr);
48
+
49
+ void start_logger(const std::string& fname);
50
+
51
+ size_t str_to_size_t(const std::string& s);
52
+
53
+ #if defined(__linux__)
54
+
55
+ struct PipeDeleter {
56
+ void operator()(FILE* file) const {
57
+ if (file != nullptr)
58
+ {
59
+ pclose(file);
60
+ }
61
+ }
62
+ };
63
+
64
+ #endif
65
+
66
+ // Reads the file as bytes.
67
+ // Returns std::nullopt if the file does not exist.
68
+ std::optional<std::string> read_file_to_string(const std::string& path);
69
+
70
+ void dbg_hit_on(bool cond, int slot = 0);
71
+ void dbg_mean_of(int64_t value, int slot = 0);
72
+ void dbg_stdev_of(int64_t value, int slot = 0);
73
+ void dbg_extremes_of(int64_t value, int slot = 0);
74
+ void dbg_correl_of(int64_t value1, int64_t value2, int slot = 0);
75
+ void dbg_print();
76
+ void dbg_clear();
77
+
78
+ using TimePoint = std::chrono::milliseconds::rep; // A value in milliseconds
79
+ static_assert(sizeof(TimePoint) == sizeof(int64_t), "TimePoint should be 64 bits");
80
+ inline TimePoint now() {
81
+ return std::chrono::duration_cast<std::chrono::milliseconds>(
82
+ std::chrono::steady_clock::now().time_since_epoch())
83
+ .count();
84
+ }
85
+
86
+ inline std::vector<std::string_view> split(std::string_view s, std::string_view delimiter) {
87
+ std::vector<std::string_view> res;
88
+
89
+ if (s.empty())
90
+ return res;
91
+
92
+ size_t begin = 0;
93
+ for (;;)
94
+ {
95
+ const size_t end = s.find(delimiter, begin);
96
+ if (end == std::string::npos)
97
+ break;
98
+
99
+ res.emplace_back(s.substr(begin, end - begin));
100
+ begin = end + delimiter.size();
101
+ }
102
+
103
+ res.emplace_back(s.substr(begin));
104
+
105
+ return res;
106
+ }
107
+
108
+ void remove_whitespace(std::string& s);
109
+ bool is_whitespace(std::string_view s);
110
+
111
+ enum SyncCout {
112
+ IO_LOCK,
113
+ IO_UNLOCK
114
+ };
115
+ std::ostream& operator<<(std::ostream&, SyncCout);
116
+
117
+ #define sync_cout std::cout << IO_LOCK
118
+ #define sync_endl std::endl << IO_UNLOCK
119
+
120
+ void sync_cout_start();
121
+ void sync_cout_end();
122
+
123
+ // True if and only if the binary is compiled on a little-endian machine
124
+ static inline const std::uint16_t Le = 1;
125
+ static inline const bool IsLittleEndian = *reinterpret_cast<const char*>(&Le) == 1;
126
+
127
+
128
+ template<typename T, std::size_t MaxSize>
129
+ class ValueList {
130
+
131
+ public:
132
+ std::size_t size() const { return size_; }
133
+ void push_back(const T& value) { values_[size_++] = value; }
134
+ const T* begin() const { return values_; }
135
+ const T* end() const { return values_ + size_; }
136
+ const T& operator[](int index) const { return values_[index]; }
137
+
138
+ private:
139
+ T values_[MaxSize];
140
+ std::size_t size_ = 0;
141
+ };
142
+
143
+
144
+ template<typename T, std::size_t Size, std::size_t... Sizes>
145
+ class MultiArray;
146
+
147
+ namespace Detail {
148
+
149
+ template<typename T, std::size_t Size, std::size_t... Sizes>
150
+ struct MultiArrayHelper {
151
+ using ChildType = MultiArray<T, Sizes...>;
152
+ };
153
+
154
+ template<typename T, std::size_t Size>
155
+ struct MultiArrayHelper<T, Size> {
156
+ using ChildType = T;
157
+ };
158
+
159
+ template<typename To, typename From>
160
+ constexpr bool is_strictly_assignable_v =
161
+ std::is_assignable_v<To&, From> && (std::is_same_v<To, From> || !std::is_convertible_v<From, To>);
162
+
163
+ }
164
+
165
+ // MultiArray is a generic N-dimensional array.
166
+ // The template parameters (Size and Sizes) encode the dimensions of the array.
167
+ template<typename T, std::size_t Size, std::size_t... Sizes>
168
+ class MultiArray {
169
+ using ChildType = typename Detail::MultiArrayHelper<T, Size, Sizes...>::ChildType;
170
+ using ArrayType = std::array<ChildType, Size>;
171
+ ArrayType data_;
172
+
173
+ public:
174
+ using value_type = typename ArrayType::value_type;
175
+ using size_type = typename ArrayType::size_type;
176
+ using difference_type = typename ArrayType::difference_type;
177
+ using reference = typename ArrayType::reference;
178
+ using const_reference = typename ArrayType::const_reference;
179
+ using pointer = typename ArrayType::pointer;
180
+ using const_pointer = typename ArrayType::const_pointer;
181
+ using iterator = typename ArrayType::iterator;
182
+ using const_iterator = typename ArrayType::const_iterator;
183
+ using reverse_iterator = typename ArrayType::reverse_iterator;
184
+ using const_reverse_iterator = typename ArrayType::const_reverse_iterator;
185
+
186
+ constexpr auto& at(size_type index) noexcept { return data_.at(index); }
187
+ constexpr const auto& at(size_type index) const noexcept { return data_.at(index); }
188
+
189
+ constexpr auto& operator[](size_type index) noexcept { return data_[index]; }
190
+ constexpr const auto& operator[](size_type index) const noexcept { return data_[index]; }
191
+
192
+ constexpr auto& front() noexcept { return data_.front(); }
193
+ constexpr const auto& front() const noexcept { return data_.front(); }
194
+ constexpr auto& back() noexcept { return data_.back(); }
195
+ constexpr const auto& back() const noexcept { return data_.back(); }
196
+
197
+ auto* data() { return data_.data(); }
198
+ const auto* data() const { return data_.data(); }
199
+
200
+ constexpr auto begin() noexcept { return data_.begin(); }
201
+ constexpr auto end() noexcept { return data_.end(); }
202
+ constexpr auto begin() const noexcept { return data_.begin(); }
203
+ constexpr auto end() const noexcept { return data_.end(); }
204
+ constexpr auto cbegin() const noexcept { return data_.cbegin(); }
205
+ constexpr auto cend() const noexcept { return data_.cend(); }
206
+
207
+ constexpr auto rbegin() noexcept { return data_.rbegin(); }
208
+ constexpr auto rend() noexcept { return data_.rend(); }
209
+ constexpr auto rbegin() const noexcept { return data_.rbegin(); }
210
+ constexpr auto rend() const noexcept { return data_.rend(); }
211
+ constexpr auto crbegin() const noexcept { return data_.crbegin(); }
212
+ constexpr auto crend() const noexcept { return data_.crend(); }
213
+
214
+ constexpr bool empty() const noexcept { return data_.empty(); }
215
+ constexpr size_type size() const noexcept { return data_.size(); }
216
+ constexpr size_type max_size() const noexcept { return data_.max_size(); }
217
+
218
+ template<typename U>
219
+ void fill(const U& v) {
220
+ static_assert(Detail::is_strictly_assignable_v<T, U>,
221
+ "Cannot assign fill value to entry type");
222
+ for (auto& ele : data_)
223
+ {
224
+ if constexpr (sizeof...(Sizes) == 0)
225
+ ele = v;
226
+ else
227
+ ele.fill(v);
228
+ }
229
+ }
230
+
231
+ constexpr void swap(MultiArray<T, Size, Sizes...>& other) noexcept { data_.swap(other.data_); }
232
+ };
233
+
234
+
235
+ // xorshift64star Pseudo-Random Number Generator
236
+ // This class is based on original code written and dedicated
237
+ // to the public domain by Sebastiano Vigna (2014).
238
+ // It has the following characteristics:
239
+ //
240
+ // - Outputs 64-bit numbers
241
+ // - Passes Dieharder and SmallCrush test batteries
242
+ // - Does not require warm-up, no zeroland to escape
243
+ // - Internal state is a single 64-bit integer
244
+ // - Period is 2^64 - 1
245
+ // - Speed: 1.60 ns/call (Core i7 @3.40GHz)
246
+ //
247
+ // For further analysis see
248
+ // <http://vigna.di.unimi.it/ftp/papers/xorshift.pdf>
249
+
250
+ class PRNG {
251
+
252
+ uint64_t s;
253
+
254
+ uint64_t rand64() {
255
+
256
+ s ^= s >> 12, s ^= s << 25, s ^= s >> 27;
257
+ return s * 2685821657736338717LL;
258
+ }
259
+
260
+ public:
261
+ PRNG(uint64_t seed) :
262
+ s(seed) {
263
+ assert(seed);
264
+ }
265
+
266
+ template<typename T>
267
+ T rand() {
268
+ return T(rand64());
269
+ }
270
+
271
+ // Special generator used to fast init magic numbers.
272
+ // Output values only have 1/8th of their bits set on average.
273
+ template<typename T>
274
+ T sparse_rand() {
275
+ return T(rand64() & rand64() & rand64());
276
+ }
277
+ };
278
+
279
+ inline uint64_t mul_hi64(uint64_t a, uint64_t b) {
280
+ #if defined(__GNUC__) && defined(IS_64BIT)
281
+ __extension__ using uint128 = unsigned __int128;
282
+ return (uint128(a) * uint128(b)) >> 64;
283
+ #else
284
+ uint64_t aL = uint32_t(a), aH = a >> 32;
285
+ uint64_t bL = uint32_t(b), bH = b >> 32;
286
+ uint64_t c1 = (aL * bL) >> 32;
287
+ uint64_t c2 = aH * bL + c1;
288
+ uint64_t c3 = aL * bH + uint32_t(c2);
289
+ return aH * bH + (c2 >> 32) + (c3 >> 32);
290
+ #endif
291
+ }
292
+
293
+
294
+ struct CommandLine {
295
+ public:
296
+ CommandLine(int _argc, char** _argv) :
297
+ argc(_argc),
298
+ argv(_argv) {}
299
+
300
+ static std::string get_binary_directory(std::string argv0);
301
+ static std::string get_working_directory();
302
+
303
+ int argc;
304
+ char** argv;
305
+ };
306
+
307
+ namespace Utility {
308
+
309
+ template<typename T, typename Predicate>
310
+ void move_to_front(std::vector<T>& vec, Predicate pred) {
311
+ auto it = std::find_if(vec.begin(), vec.end(), pred);
312
+
313
+ if (it != vec.end())
314
+ {
315
+ std::rotate(vec.begin(), it, it + 1);
316
+ }
317
+ }
318
+ }
319
+
320
+ } // namespace Stockfish
321
+
322
+ #endif // #ifndef MISC_H_INCLUDED
stockfish/src/movegen.cpp ADDED
@@ -0,0 +1,256 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /*
2
+ Stockfish, a UCI chess playing engine derived from Glaurung 2.1
3
+ Copyright (C) 2004-2025 The Stockfish developers (see AUTHORS file)
4
+
5
+ Stockfish is free software: you can redistribute it and/or modify
6
+ it under the terms of the GNU General Public License as published by
7
+ the Free Software Foundation, either version 3 of the License, or
8
+ (at your option) any later version.
9
+
10
+ Stockfish is distributed in the hope that it will be useful,
11
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
12
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13
+ GNU General Public License for more details.
14
+
15
+ You should have received a copy of the GNU General Public License
16
+ along with this program. If not, see <http://www.gnu.org/licenses/>.
17
+ */
18
+
19
+ #include "movegen.h"
20
+
21
+ #include <cassert>
22
+ #include <initializer_list>
23
+
24
+ #include "bitboard.h"
25
+ #include "position.h"
26
+
27
+ namespace Stockfish {
28
+
29
+ namespace {
30
+
31
+ template<GenType Type, Direction D, bool Enemy>
32
+ ExtMove* make_promotions(ExtMove* moveList, [[maybe_unused]] Square to) {
33
+
34
+ constexpr bool all = Type == EVASIONS || Type == NON_EVASIONS;
35
+
36
+ if constexpr (Type == CAPTURES || all)
37
+ *moveList++ = Move::make<PROMOTION>(to - D, to, QUEEN);
38
+
39
+ if constexpr ((Type == CAPTURES && Enemy) || (Type == QUIETS && !Enemy) || all)
40
+ {
41
+ *moveList++ = Move::make<PROMOTION>(to - D, to, ROOK);
42
+ *moveList++ = Move::make<PROMOTION>(to - D, to, BISHOP);
43
+ *moveList++ = Move::make<PROMOTION>(to - D, to, KNIGHT);
44
+ }
45
+
46
+ return moveList;
47
+ }
48
+
49
+
50
+ template<Color Us, GenType Type>
51
+ ExtMove* generate_pawn_moves(const Position& pos, ExtMove* moveList, Bitboard target) {
52
+
53
+ constexpr Color Them = ~Us;
54
+ constexpr Bitboard TRank7BB = (Us == WHITE ? Rank7BB : Rank2BB);
55
+ constexpr Bitboard TRank3BB = (Us == WHITE ? Rank3BB : Rank6BB);
56
+ constexpr Direction Up = pawn_push(Us);
57
+ constexpr Direction UpRight = (Us == WHITE ? NORTH_EAST : SOUTH_WEST);
58
+ constexpr Direction UpLeft = (Us == WHITE ? NORTH_WEST : SOUTH_EAST);
59
+
60
+ const Bitboard emptySquares = ~pos.pieces();
61
+ const Bitboard enemies = Type == EVASIONS ? pos.checkers() : pos.pieces(Them);
62
+
63
+ Bitboard pawnsOn7 = pos.pieces(Us, PAWN) & TRank7BB;
64
+ Bitboard pawnsNotOn7 = pos.pieces(Us, PAWN) & ~TRank7BB;
65
+
66
+ // Single and double pawn pushes, no promotions
67
+ if constexpr (Type != CAPTURES)
68
+ {
69
+ Bitboard b1 = shift<Up>(pawnsNotOn7) & emptySquares;
70
+ Bitboard b2 = shift<Up>(b1 & TRank3BB) & emptySquares;
71
+
72
+ if constexpr (Type == EVASIONS) // Consider only blocking squares
73
+ {
74
+ b1 &= target;
75
+ b2 &= target;
76
+ }
77
+
78
+ while (b1)
79
+ {
80
+ Square to = pop_lsb(b1);
81
+ *moveList++ = Move(to - Up, to);
82
+ }
83
+
84
+ while (b2)
85
+ {
86
+ Square to = pop_lsb(b2);
87
+ *moveList++ = Move(to - Up - Up, to);
88
+ }
89
+ }
90
+
91
+ // Promotions and underpromotions
92
+ if (pawnsOn7)
93
+ {
94
+ Bitboard b1 = shift<UpRight>(pawnsOn7) & enemies;
95
+ Bitboard b2 = shift<UpLeft>(pawnsOn7) & enemies;
96
+ Bitboard b3 = shift<Up>(pawnsOn7) & emptySquares;
97
+
98
+ if constexpr (Type == EVASIONS)
99
+ b3 &= target;
100
+
101
+ while (b1)
102
+ moveList = make_promotions<Type, UpRight, true>(moveList, pop_lsb(b1));
103
+
104
+ while (b2)
105
+ moveList = make_promotions<Type, UpLeft, true>(moveList, pop_lsb(b2));
106
+
107
+ while (b3)
108
+ moveList = make_promotions<Type, Up, false>(moveList, pop_lsb(b3));
109
+ }
110
+
111
+ // Standard and en passant captures
112
+ if constexpr (Type == CAPTURES || Type == EVASIONS || Type == NON_EVASIONS)
113
+ {
114
+ Bitboard b1 = shift<UpRight>(pawnsNotOn7) & enemies;
115
+ Bitboard b2 = shift<UpLeft>(pawnsNotOn7) & enemies;
116
+
117
+ while (b1)
118
+ {
119
+ Square to = pop_lsb(b1);
120
+ *moveList++ = Move(to - UpRight, to);
121
+ }
122
+
123
+ while (b2)
124
+ {
125
+ Square to = pop_lsb(b2);
126
+ *moveList++ = Move(to - UpLeft, to);
127
+ }
128
+
129
+ if (pos.ep_square() != SQ_NONE)
130
+ {
131
+ assert(rank_of(pos.ep_square()) == relative_rank(Us, RANK_6));
132
+
133
+ // An en passant capture cannot resolve a discovered check
134
+ if (Type == EVASIONS && (target & (pos.ep_square() + Up)))
135
+ return moveList;
136
+
137
+ b1 = pawnsNotOn7 & pawn_attacks_bb(Them, pos.ep_square());
138
+
139
+ assert(b1);
140
+
141
+ while (b1)
142
+ *moveList++ = Move::make<EN_PASSANT>(pop_lsb(b1), pos.ep_square());
143
+ }
144
+ }
145
+
146
+ return moveList;
147
+ }
148
+
149
+
150
+ template<Color Us, PieceType Pt>
151
+ ExtMove* generate_moves(const Position& pos, ExtMove* moveList, Bitboard target) {
152
+
153
+ static_assert(Pt != KING && Pt != PAWN, "Unsupported piece type in generate_moves()");
154
+
155
+ Bitboard bb = pos.pieces(Us, Pt);
156
+
157
+ while (bb)
158
+ {
159
+ Square from = pop_lsb(bb);
160
+ Bitboard b = attacks_bb<Pt>(from, pos.pieces()) & target;
161
+
162
+ while (b)
163
+ *moveList++ = Move(from, pop_lsb(b));
164
+ }
165
+
166
+ return moveList;
167
+ }
168
+
169
+
170
+ template<Color Us, GenType Type>
171
+ ExtMove* generate_all(const Position& pos, ExtMove* moveList) {
172
+
173
+ static_assert(Type != LEGAL, "Unsupported type in generate_all()");
174
+
175
+ const Square ksq = pos.square<KING>(Us);
176
+ Bitboard target;
177
+
178
+ // Skip generating non-king moves when in double check
179
+ if (Type != EVASIONS || !more_than_one(pos.checkers()))
180
+ {
181
+ target = Type == EVASIONS ? between_bb(ksq, lsb(pos.checkers()))
182
+ : Type == NON_EVASIONS ? ~pos.pieces(Us)
183
+ : Type == CAPTURES ? pos.pieces(~Us)
184
+ : ~pos.pieces(); // QUIETS
185
+
186
+ moveList = generate_pawn_moves<Us, Type>(pos, moveList, target);
187
+ moveList = generate_moves<Us, KNIGHT>(pos, moveList, target);
188
+ moveList = generate_moves<Us, BISHOP>(pos, moveList, target);
189
+ moveList = generate_moves<Us, ROOK>(pos, moveList, target);
190
+ moveList = generate_moves<Us, QUEEN>(pos, moveList, target);
191
+ }
192
+
193
+ Bitboard b = attacks_bb<KING>(ksq) & (Type == EVASIONS ? ~pos.pieces(Us) : target);
194
+
195
+ while (b)
196
+ *moveList++ = Move(ksq, pop_lsb(b));
197
+
198
+ if ((Type == QUIETS || Type == NON_EVASIONS) && pos.can_castle(Us & ANY_CASTLING))
199
+ for (CastlingRights cr : {Us & KING_SIDE, Us & QUEEN_SIDE})
200
+ if (!pos.castling_impeded(cr) && pos.can_castle(cr))
201
+ *moveList++ = Move::make<CASTLING>(ksq, pos.castling_rook_square(cr));
202
+
203
+ return moveList;
204
+ }
205
+
206
+ } // namespace
207
+
208
+
209
+ // <CAPTURES> Generates all pseudo-legal captures plus queen promotions
210
+ // <QUIETS> Generates all pseudo-legal non-captures and underpromotions
211
+ // <EVASIONS> Generates all pseudo-legal check evasions
212
+ // <NON_EVASIONS> Generates all pseudo-legal captures and non-captures
213
+ //
214
+ // Returns a pointer to the end of the move list.
215
+ template<GenType Type>
216
+ ExtMove* generate(const Position& pos, ExtMove* moveList) {
217
+
218
+ static_assert(Type != LEGAL, "Unsupported type in generate()");
219
+ assert((Type == EVASIONS) == bool(pos.checkers()));
220
+
221
+ Color us = pos.side_to_move();
222
+
223
+ return us == WHITE ? generate_all<WHITE, Type>(pos, moveList)
224
+ : generate_all<BLACK, Type>(pos, moveList);
225
+ }
226
+
227
+ // Explicit template instantiations
228
+ template ExtMove* generate<CAPTURES>(const Position&, ExtMove*);
229
+ template ExtMove* generate<QUIETS>(const Position&, ExtMove*);
230
+ template ExtMove* generate<EVASIONS>(const Position&, ExtMove*);
231
+ template ExtMove* generate<NON_EVASIONS>(const Position&, ExtMove*);
232
+
233
+
234
+ // generate<LEGAL> generates all the legal moves in the given position
235
+
236
+ template<>
237
+ ExtMove* generate<LEGAL>(const Position& pos, ExtMove* moveList) {
238
+
239
+ Color us = pos.side_to_move();
240
+ Bitboard pinned = pos.blockers_for_king(us) & pos.pieces(us);
241
+ Square ksq = pos.square<KING>(us);
242
+ ExtMove* cur = moveList;
243
+
244
+ moveList =
245
+ pos.checkers() ? generate<EVASIONS>(pos, moveList) : generate<NON_EVASIONS>(pos, moveList);
246
+ while (cur != moveList)
247
+ if (((pinned & cur->from_sq()) || cur->from_sq() == ksq || cur->type_of() == EN_PASSANT)
248
+ && !pos.legal(*cur))
249
+ *cur = *(--moveList);
250
+ else
251
+ ++cur;
252
+
253
+ return moveList;
254
+ }
255
+
256
+ } // namespace Stockfish
stockfish/src/movegen.h ADDED
@@ -0,0 +1,73 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /*
2
+ Stockfish, a UCI chess playing engine derived from Glaurung 2.1
3
+ Copyright (C) 2004-2025 The Stockfish developers (see AUTHORS file)
4
+
5
+ Stockfish is free software: you can redistribute it and/or modify
6
+ it under the terms of the GNU General Public License as published by
7
+ the Free Software Foundation, either version 3 of the License, or
8
+ (at your option) any later version.
9
+
10
+ Stockfish is distributed in the hope that it will be useful,
11
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
12
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13
+ GNU General Public License for more details.
14
+
15
+ You should have received a copy of the GNU General Public License
16
+ along with this program. If not, see <http://www.gnu.org/licenses/>.
17
+ */
18
+
19
+ #ifndef MOVEGEN_H_INCLUDED
20
+ #define MOVEGEN_H_INCLUDED
21
+
22
+ #include <algorithm> // IWYU pragma: keep
23
+ #include <cstddef>
24
+
25
+ #include "types.h"
26
+
27
+ namespace Stockfish {
28
+
29
+ class Position;
30
+
31
+ enum GenType {
32
+ CAPTURES,
33
+ QUIETS,
34
+ EVASIONS,
35
+ NON_EVASIONS,
36
+ LEGAL
37
+ };
38
+
39
+ struct ExtMove: public Move {
40
+ int value;
41
+
42
+ void operator=(Move m) { data = m.raw(); }
43
+
44
+ // Inhibit unwanted implicit conversions to Move
45
+ // with an ambiguity that yields to a compile error.
46
+ operator float() const = delete;
47
+ };
48
+
49
+ inline bool operator<(const ExtMove& f, const ExtMove& s) { return f.value < s.value; }
50
+
51
+ template<GenType>
52
+ ExtMove* generate(const Position& pos, ExtMove* moveList);
53
+
54
+ // The MoveList struct wraps the generate() function and returns a convenient
55
+ // list of moves. Using MoveList is sometimes preferable to directly calling
56
+ // the lower level generate() function.
57
+ template<GenType T>
58
+ struct MoveList {
59
+
60
+ explicit MoveList(const Position& pos) :
61
+ last(generate<T>(pos, moveList)) {}
62
+ const ExtMove* begin() const { return moveList; }
63
+ const ExtMove* end() const { return last; }
64
+ size_t size() const { return last - moveList; }
65
+ bool contains(Move move) const { return std::find(begin(), end(), move) != end(); }
66
+
67
+ private:
68
+ ExtMove moveList[MAX_MOVES], *last;
69
+ };
70
+
71
+ } // namespace Stockfish
72
+
73
+ #endif // #ifndef MOVEGEN_H_INCLUDED
stockfish/src/movepick.cpp ADDED
@@ -0,0 +1,320 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /*
2
+ Stockfish, a UCI chess playing engine derived from Glaurung 2.1
3
+ Copyright (C) 2004-2025 The Stockfish developers (see AUTHORS file)
4
+
5
+ Stockfish is free software: you can redistribute it and/or modify
6
+ it under the terms of the GNU General Public License as published by
7
+ the Free Software Foundation, either version 3 of the License, or
8
+ (at your option) any later version.
9
+
10
+ Stockfish is distributed in the hope that it will be useful,
11
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
12
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13
+ GNU General Public License for more details.
14
+
15
+ You should have received a copy of the GNU General Public License
16
+ along with this program. If not, see <http://www.gnu.org/licenses/>.
17
+ */
18
+
19
+ #include "movepick.h"
20
+
21
+ #include <cassert>
22
+ #include <limits>
23
+
24
+ #include "bitboard.h"
25
+ #include "misc.h"
26
+ #include "position.h"
27
+
28
+ namespace Stockfish {
29
+
30
+ namespace {
31
+
32
+ enum Stages {
33
+ // generate main search moves
34
+ MAIN_TT,
35
+ CAPTURE_INIT,
36
+ GOOD_CAPTURE,
37
+ QUIET_INIT,
38
+ GOOD_QUIET,
39
+ BAD_CAPTURE,
40
+ BAD_QUIET,
41
+
42
+ // generate evasion moves
43
+ EVASION_TT,
44
+ EVASION_INIT,
45
+ EVASION,
46
+
47
+ // generate probcut moves
48
+ PROBCUT_TT,
49
+ PROBCUT_INIT,
50
+ PROBCUT,
51
+
52
+ // generate qsearch moves
53
+ QSEARCH_TT,
54
+ QCAPTURE_INIT,
55
+ QCAPTURE
56
+ };
57
+
58
+ // Sort moves in descending order up to and including a given limit.
59
+ // The order of moves smaller than the limit is left unspecified.
60
+ void partial_insertion_sort(ExtMove* begin, ExtMove* end, int limit) {
61
+
62
+ for (ExtMove *sortedEnd = begin, *p = begin + 1; p < end; ++p)
63
+ if (p->value >= limit)
64
+ {
65
+ ExtMove tmp = *p, *q;
66
+ *p = *++sortedEnd;
67
+ for (q = sortedEnd; q != begin && *(q - 1) < tmp; --q)
68
+ *q = *(q - 1);
69
+ *q = tmp;
70
+ }
71
+ }
72
+
73
+ } // namespace
74
+
75
+
76
+ // Constructors of the MovePicker class. As arguments, we pass information
77
+ // to decide which class of moves to emit, to help sorting the (presumably)
78
+ // good moves first, and how important move ordering is at the current node.
79
+
80
+ // MovePicker constructor for the main search and for the quiescence search
81
+ MovePicker::MovePicker(const Position& p,
82
+ Move ttm,
83
+ Depth d,
84
+ const ButterflyHistory* mh,
85
+ const LowPlyHistory* lph,
86
+ const CapturePieceToHistory* cph,
87
+ const PieceToHistory** ch,
88
+ const PawnHistory* ph,
89
+ int pl) :
90
+ pos(p),
91
+ mainHistory(mh),
92
+ lowPlyHistory(lph),
93
+ captureHistory(cph),
94
+ continuationHistory(ch),
95
+ pawnHistory(ph),
96
+ ttMove(ttm),
97
+ depth(d),
98
+ ply(pl) {
99
+
100
+ if (pos.checkers())
101
+ stage = EVASION_TT + !(ttm && pos.pseudo_legal(ttm));
102
+
103
+ else
104
+ stage = (depth > 0 ? MAIN_TT : QSEARCH_TT) + !(ttm && pos.pseudo_legal(ttm));
105
+ }
106
+
107
+ // MovePicker constructor for ProbCut: we generate captures with Static Exchange
108
+ // Evaluation (SEE) greater than or equal to the given threshold.
109
+ MovePicker::MovePicker(const Position& p, Move ttm, int th, const CapturePieceToHistory* cph) :
110
+ pos(p),
111
+ captureHistory(cph),
112
+ ttMove(ttm),
113
+ threshold(th) {
114
+ assert(!pos.checkers());
115
+
116
+ stage = PROBCUT_TT
117
+ + !(ttm && pos.capture_stage(ttm) && pos.pseudo_legal(ttm) && pos.see_ge(ttm, threshold));
118
+ }
119
+
120
+ // Assigns a numerical value to each move in a list, used for sorting.
121
+ // Captures are ordered by Most Valuable Victim (MVV), preferring captures
122
+ // with a good history. Quiets moves are ordered using the history tables.
123
+ template<GenType Type>
124
+ void MovePicker::score() {
125
+
126
+ static_assert(Type == CAPTURES || Type == QUIETS || Type == EVASIONS, "Wrong type");
127
+
128
+ [[maybe_unused]] Bitboard threatenedByPawn, threatenedByMinor, threatenedByRook,
129
+ threatenedPieces;
130
+ if constexpr (Type == QUIETS)
131
+ {
132
+ Color us = pos.side_to_move();
133
+
134
+ threatenedByPawn = pos.attacks_by<PAWN>(~us);
135
+ threatenedByMinor =
136
+ pos.attacks_by<KNIGHT>(~us) | pos.attacks_by<BISHOP>(~us) | threatenedByPawn;
137
+ threatenedByRook = pos.attacks_by<ROOK>(~us) | threatenedByMinor;
138
+
139
+ // Pieces threatened by pieces of lesser material value
140
+ threatenedPieces = (pos.pieces(us, QUEEN) & threatenedByRook)
141
+ | (pos.pieces(us, ROOK) & threatenedByMinor)
142
+ | (pos.pieces(us, KNIGHT, BISHOP) & threatenedByPawn);
143
+ }
144
+
145
+ for (auto& m : *this)
146
+ if constexpr (Type == CAPTURES)
147
+ m.value =
148
+ 7 * int(PieceValue[pos.piece_on(m.to_sq())])
149
+ + (*captureHistory)[pos.moved_piece(m)][m.to_sq()][type_of(pos.piece_on(m.to_sq()))];
150
+
151
+ else if constexpr (Type == QUIETS)
152
+ {
153
+ Piece pc = pos.moved_piece(m);
154
+ PieceType pt = type_of(pc);
155
+ Square from = m.from_sq();
156
+ Square to = m.to_sq();
157
+
158
+ // histories
159
+ m.value = 2 * (*mainHistory)[pos.side_to_move()][m.from_to()];
160
+ m.value += 2 * (*pawnHistory)[pawn_structure_index(pos)][pc][to];
161
+ m.value += (*continuationHistory[0])[pc][to];
162
+ m.value += (*continuationHistory[1])[pc][to];
163
+ m.value += (*continuationHistory[2])[pc][to];
164
+ m.value += (*continuationHistory[3])[pc][to];
165
+ m.value += (*continuationHistory[4])[pc][to] / 3;
166
+ m.value += (*continuationHistory[5])[pc][to];
167
+
168
+ // bonus for checks
169
+ m.value += bool(pos.check_squares(pt) & to) * 16384;
170
+
171
+ // bonus for escaping from capture
172
+ m.value += threatenedPieces & from ? (pt == QUEEN && !(to & threatenedByRook) ? 51700
173
+ : pt == ROOK && !(to & threatenedByMinor) ? 25600
174
+ : !(to & threatenedByPawn) ? 14450
175
+ : 0)
176
+ : 0;
177
+
178
+ // malus for putting piece en prise
179
+ m.value -= (pt == QUEEN ? bool(to & threatenedByRook) * 49000
180
+ : pt == ROOK && bool(to & threatenedByMinor) ? 24335
181
+ : 0);
182
+
183
+ if (ply < LOW_PLY_HISTORY_SIZE)
184
+ m.value += 8 * (*lowPlyHistory)[ply][m.from_to()] / (1 + 2 * ply);
185
+ }
186
+
187
+ else // Type == EVASIONS
188
+ {
189
+ if (pos.capture_stage(m))
190
+ m.value = PieceValue[pos.piece_on(m.to_sq())] + (1 << 28);
191
+ else
192
+ m.value = (*mainHistory)[pos.side_to_move()][m.from_to()]
193
+ + (*continuationHistory[0])[pos.moved_piece(m)][m.to_sq()]
194
+ + (*pawnHistory)[pawn_structure_index(pos)][pos.moved_piece(m)][m.to_sq()];
195
+ }
196
+ }
197
+
198
+ // Returns the next move satisfying a predicate function.
199
+ // This never returns the TT move, as it was emitted before.
200
+ template<typename Pred>
201
+ Move MovePicker::select(Pred filter) {
202
+
203
+ for (; cur < endMoves; ++cur)
204
+ if (*cur != ttMove && filter())
205
+ return *cur++;
206
+
207
+ return Move::none();
208
+ }
209
+
210
+ // This is the most important method of the MovePicker class. We emit one
211
+ // new pseudo-legal move on every call until there are no more moves left,
212
+ // picking the move with the highest score from a list of generated moves.
213
+ Move MovePicker::next_move() {
214
+
215
+ auto quiet_threshold = [](Depth d) { return -3560 * d; };
216
+
217
+ top:
218
+ switch (stage)
219
+ {
220
+
221
+ case MAIN_TT :
222
+ case EVASION_TT :
223
+ case QSEARCH_TT :
224
+ case PROBCUT_TT :
225
+ ++stage;
226
+ return ttMove;
227
+
228
+ case CAPTURE_INIT :
229
+ case PROBCUT_INIT :
230
+ case QCAPTURE_INIT :
231
+ cur = endBadCaptures = moves;
232
+ endMoves = generate<CAPTURES>(pos, cur);
233
+
234
+ score<CAPTURES>();
235
+ partial_insertion_sort(cur, endMoves, std::numeric_limits<int>::min());
236
+ ++stage;
237
+ goto top;
238
+
239
+ case GOOD_CAPTURE :
240
+ if (select([&]() {
241
+ // Move losing capture to endBadCaptures to be tried later
242
+ return pos.see_ge(*cur, -cur->value / 18) ? true
243
+ : (*endBadCaptures++ = *cur, false);
244
+ }))
245
+ return *(cur - 1);
246
+
247
+ ++stage;
248
+ [[fallthrough]];
249
+
250
+ case QUIET_INIT :
251
+ if (!skipQuiets)
252
+ {
253
+ cur = endBadCaptures;
254
+ endMoves = beginBadQuiets = endBadQuiets = generate<QUIETS>(pos, cur);
255
+
256
+ score<QUIETS>();
257
+ partial_insertion_sort(cur, endMoves, quiet_threshold(depth));
258
+ }
259
+
260
+ ++stage;
261
+ [[fallthrough]];
262
+
263
+ case GOOD_QUIET :
264
+ if (!skipQuiets && select([]() { return true; }))
265
+ {
266
+ if ((cur - 1)->value > -7998 || (cur - 1)->value <= quiet_threshold(depth))
267
+ return *(cur - 1);
268
+
269
+ // Remaining quiets are bad
270
+ beginBadQuiets = cur - 1;
271
+ }
272
+
273
+ // Prepare the pointers to loop over the bad captures
274
+ cur = moves;
275
+ endMoves = endBadCaptures;
276
+
277
+ ++stage;
278
+ [[fallthrough]];
279
+
280
+ case BAD_CAPTURE :
281
+ if (select([]() { return true; }))
282
+ return *(cur - 1);
283
+
284
+ // Prepare the pointers to loop over the bad quiets
285
+ cur = beginBadQuiets;
286
+ endMoves = endBadQuiets;
287
+
288
+ ++stage;
289
+ [[fallthrough]];
290
+
291
+ case BAD_QUIET :
292
+ if (!skipQuiets)
293
+ return select([]() { return true; });
294
+
295
+ return Move::none();
296
+
297
+ case EVASION_INIT :
298
+ cur = moves;
299
+ endMoves = generate<EVASIONS>(pos, cur);
300
+
301
+ score<EVASIONS>();
302
+ partial_insertion_sort(cur, endMoves, std::numeric_limits<int>::min());
303
+ ++stage;
304
+ [[fallthrough]];
305
+
306
+ case EVASION :
307
+ case QCAPTURE :
308
+ return select([]() { return true; });
309
+
310
+ case PROBCUT :
311
+ return select([&]() { return pos.see_ge(*cur, threshold); });
312
+ }
313
+
314
+ assert(false);
315
+ return Move::none(); // Silence warning
316
+ }
317
+
318
+ void MovePicker::skip_quiet_moves() { skipQuiets = true; }
319
+
320
+ } // namespace Stockfish
stockfish/src/movepick.h ADDED
@@ -0,0 +1,80 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /*
2
+ Stockfish, a UCI chess playing engine derived from Glaurung 2.1
3
+ Copyright (C) 2004-2025 The Stockfish developers (see AUTHORS file)
4
+
5
+ Stockfish is free software: you can redistribute it and/or modify
6
+ it under the terms of the GNU General Public License as published by
7
+ the Free Software Foundation, either version 3 of the License, or
8
+ (at your option) any later version.
9
+
10
+ Stockfish is distributed in the hope that it will be useful,
11
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
12
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13
+ GNU General Public License for more details.
14
+
15
+ You should have received a copy of the GNU General Public License
16
+ along with this program. If not, see <http://www.gnu.org/licenses/>.
17
+ */
18
+
19
+ #ifndef MOVEPICK_H_INCLUDED
20
+ #define MOVEPICK_H_INCLUDED
21
+
22
+ #include "history.h"
23
+ #include "movegen.h"
24
+ #include "types.h"
25
+
26
+ namespace Stockfish {
27
+
28
+ class Position;
29
+
30
+ // The MovePicker class is used to pick one pseudo-legal move at a time from the
31
+ // current position. The most important method is next_move(), which emits one
32
+ // new pseudo-legal move on every call, until there are no moves left, when
33
+ // Move::none() is returned. In order to improve the efficiency of the alpha-beta
34
+ // algorithm, MovePicker attempts to return the moves which are most likely to get
35
+ // a cut-off first.
36
+ class MovePicker {
37
+
38
+ public:
39
+ MovePicker(const MovePicker&) = delete;
40
+ MovePicker& operator=(const MovePicker&) = delete;
41
+ MovePicker(const Position&,
42
+ Move,
43
+ Depth,
44
+ const ButterflyHistory*,
45
+ const LowPlyHistory*,
46
+ const CapturePieceToHistory*,
47
+ const PieceToHistory**,
48
+ const PawnHistory*,
49
+ int);
50
+ MovePicker(const Position&, Move, int, const CapturePieceToHistory*);
51
+ Move next_move();
52
+ void skip_quiet_moves();
53
+
54
+ private:
55
+ template<typename Pred>
56
+ Move select(Pred);
57
+ template<GenType>
58
+ void score();
59
+ ExtMove* begin() { return cur; }
60
+ ExtMove* end() { return endMoves; }
61
+
62
+ const Position& pos;
63
+ const ButterflyHistory* mainHistory;
64
+ const LowPlyHistory* lowPlyHistory;
65
+ const CapturePieceToHistory* captureHistory;
66
+ const PieceToHistory** continuationHistory;
67
+ const PawnHistory* pawnHistory;
68
+ Move ttMove;
69
+ ExtMove * cur, *endMoves, *endBadCaptures, *beginBadQuiets, *endBadQuiets;
70
+ int stage;
71
+ int threshold;
72
+ Depth depth;
73
+ int ply;
74
+ bool skipQuiets = false;
75
+ ExtMove moves[MAX_MOVES];
76
+ };
77
+
78
+ } // namespace Stockfish
79
+
80
+ #endif // #ifndef MOVEPICK_H_INCLUDED
stockfish/src/nnue/features/half_ka_v2_hm.cpp ADDED
@@ -0,0 +1,84 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /*
2
+ Stockfish, a UCI chess playing engine derived from Glaurung 2.1
3
+ Copyright (C) 2004-2025 The Stockfish developers (see AUTHORS file)
4
+
5
+ Stockfish is free software: you can redistribute it and/or modify
6
+ it under the terms of the GNU General Public License as published by
7
+ the Free Software Foundation, either version 3 of the License, or
8
+ (at your option) any later version.
9
+
10
+ Stockfish is distributed in the hope that it will be useful,
11
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
12
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13
+ GNU General Public License for more details.
14
+
15
+ You should have received a copy of the GNU General Public License
16
+ along with this program. If not, see <http://www.gnu.org/licenses/>.
17
+ */
18
+
19
+ //Definition of input features HalfKAv2_hm of NNUE evaluation function
20
+
21
+ #include "half_ka_v2_hm.h"
22
+
23
+ #include "../../bitboard.h"
24
+ #include "../../position.h"
25
+ #include "../../types.h"
26
+ #include "../nnue_accumulator.h"
27
+
28
+ namespace Stockfish::Eval::NNUE::Features {
29
+
30
+ // Index of a feature for a given king position and another piece on some square
31
+ template<Color Perspective>
32
+ inline IndexType HalfKAv2_hm::make_index(Square s, Piece pc, Square ksq) {
33
+ return IndexType((int(s) ^ OrientTBL[Perspective][ksq]) + PieceSquareIndex[Perspective][pc]
34
+ + KingBuckets[Perspective][ksq]);
35
+ }
36
+
37
+ // Get a list of indices for active features
38
+ template<Color Perspective>
39
+ void HalfKAv2_hm::append_active_indices(const Position& pos, IndexList& active) {
40
+ Square ksq = pos.square<KING>(Perspective);
41
+ Bitboard bb = pos.pieces();
42
+ while (bb)
43
+ {
44
+ Square s = pop_lsb(bb);
45
+ active.push_back(make_index<Perspective>(s, pos.piece_on(s), ksq));
46
+ }
47
+ }
48
+
49
+ // Explicit template instantiations
50
+ template void HalfKAv2_hm::append_active_indices<WHITE>(const Position& pos, IndexList& active);
51
+ template void HalfKAv2_hm::append_active_indices<BLACK>(const Position& pos, IndexList& active);
52
+ template IndexType HalfKAv2_hm::make_index<WHITE>(Square s, Piece pc, Square ksq);
53
+ template IndexType HalfKAv2_hm::make_index<BLACK>(Square s, Piece pc, Square ksq);
54
+
55
+ // Get a list of indices for recently changed features
56
+ template<Color Perspective>
57
+ void HalfKAv2_hm::append_changed_indices(Square ksq,
58
+ const DirtyPiece& dp,
59
+ IndexList& removed,
60
+ IndexList& added) {
61
+ for (int i = 0; i < dp.dirty_num; ++i)
62
+ {
63
+ if (dp.from[i] != SQ_NONE)
64
+ removed.push_back(make_index<Perspective>(dp.from[i], dp.piece[i], ksq));
65
+ if (dp.to[i] != SQ_NONE)
66
+ added.push_back(make_index<Perspective>(dp.to[i], dp.piece[i], ksq));
67
+ }
68
+ }
69
+
70
+ // Explicit template instantiations
71
+ template void HalfKAv2_hm::append_changed_indices<WHITE>(Square ksq,
72
+ const DirtyPiece& dp,
73
+ IndexList& removed,
74
+ IndexList& added);
75
+ template void HalfKAv2_hm::append_changed_indices<BLACK>(Square ksq,
76
+ const DirtyPiece& dp,
77
+ IndexList& removed,
78
+ IndexList& added);
79
+
80
+ bool HalfKAv2_hm::requires_refresh(const DirtyPiece& dirtyPiece, Color perspective) {
81
+ return dirtyPiece.piece[0] == make_piece(perspective, KING);
82
+ }
83
+
84
+ } // namespace Stockfish::Eval::NNUE::Features