├── .gitignore ├── BookBuilder.py ├── LICENSE ├── README.md ├── gui.py ├── gui_generation_status.py ├── gui_themes.py ├── main.py ├── requirements.txt ├── settings.py └── workerEngineReduce.py /.gitignore: -------------------------------------------------------------------------------- 1 | .env 2 | __pycache__ 3 | build 4 | dist 5 | BookBuilder.spec 6 | .idea/ 7 | *.pgn 8 | *.pickle 9 | -------------------------------------------------------------------------------- /BookBuilder.py: -------------------------------------------------------------------------------- 1 | import io 2 | import os 3 | import logging 4 | from typing import Callable 5 | 6 | import chess 7 | import chess.pgn 8 | 9 | from gui_generation_status import GenerationStatus 10 | from settings import Settings 11 | from workerEngineReduce import WorkerPlay 12 | import chess.engine 13 | 14 | 15 | log_level = logging.DEBUG 16 | logging.basicConfig(level=log_level) 17 | logging.getLogger("chess.pgn").setLevel(logging.CRITICAL) 18 | 19 | working_dir = os.getcwd() 20 | 21 | 22 | class Rooter: 23 | def __init__(self, settings, status, engine, pgn): 24 | self.pgn = pgn 25 | self._calculate_pgns(settings, status, engine) 26 | 27 | def _calculate_pgns(self, settings, status, engine): 28 | try: 29 | game = chess.pgn.read_game(io.StringIO(self.pgn)) #reads the PGN submitted by the user 30 | except: 31 | self.status.error(f"Invalid PGN {self.pgn}") 32 | raise Exception(f'Invalid PGN {self.pgn}') #error if user submitted PGN is invalid 33 | 34 | board = game.board() 35 | moves = list(game.mainline_moves()) #we create a list of pgn moves in UCI 36 | logging.debug(moves) 37 | 38 | if len(moves) % 2 == 0: #if even moves in pgn, we are black. if odd, white. 39 | perspective = chess.BLACK 40 | self.perspective_str = 'Black' 41 | else: 42 | perspective = chess.WHITE 43 | self.perspective_str = 'White' 44 | 45 | self.likelihood = 1 #likelihood of oppoonent playing moves starts at 100% 46 | self.likelihood_path = [] 47 | validContinuations = [] 48 | pgnList = [] 49 | 50 | for move in moves: #we iterate through each move in the PGN/UCI generated 51 | if board.turn != perspective: #if it's not our move we check the likelihood the move in the PGN was played 52 | workerPlay = WorkerPlay(settings, status, engine, board.fen()) #we are calling the API each time 53 | move_stats, chance = workerPlay.find_opponent_move(move) #we look for the PGN move in the API response, and return the odds of it being played 54 | self.likelihood *= chance #we are creating a cumulative likelihood from each played move in the PGN 55 | self.likelihood_path.append((move_stats['san'], chance)) #we are creating a list of PGN moves with the chance of each of them being played 0-1 56 | logging.debug(f"likelihoods to get here: {self.likelihood_path}") 57 | logging.debug(f"cumulative likelihood {'{:+.2%}'.format(self.likelihood)}", ) 58 | board.push(move) #play each move in the PGN 59 | 60 | #now we have the likelihood path and cumulative likelihood of each opponent move in the PGN, so pgn can go to leafer 61 | 62 | pgnPlus = self.pgn, self.likelihood, self.likelihood_path 63 | 64 | 65 | pgnsreturned.append(pgnPlus) 66 | logging.debug(f"sent from rooter: {pgnsreturned}") 67 | 68 | 69 | class Leafer: 70 | def __init__(self, settings, status, engine, pgn, cumulative, likelyPath): 71 | self.pgn = pgn 72 | self.cumulative = cumulative 73 | self.likelyPath = likelyPath 74 | self._calculate_pgns(settings, status, engine) 75 | 76 | def _calculate_pgns(self, settings, status, engine): 77 | moveSelection = settings.moveSelection 78 | 79 | try: 80 | game = chess.pgn.read_game(io.StringIO(self.pgn)) #reads the PGN submitted by the user 81 | except: 82 | self.status.error(f"Invalid PGN {self.pgn}") 83 | raise Exception(f'Invalid PGN {self.pgn}') #error if user submitted PGN is invalid 84 | 85 | board = game.board() 86 | moves = list(game.mainline_moves()) #we create a list of pgn moves in UCI 87 | logging.debug(moves) 88 | 89 | if len(moves) % 2 == 0: #if even moves in pgn, we are black. if odd, white. 90 | perspective = chess.BLACK 91 | self.perspective_str = 'Black' 92 | else: 93 | perspective = chess.WHITE 94 | self.perspective_str = 'White' 95 | 96 | 97 | self.likelihood = self.cumulative #likelihood of oppoonent playing moves starts at 100% 98 | self.likelihood_path = self.likelyPath 99 | validContinuations = [] 100 | pgnList = [] 101 | 102 | for move in moves: #we iterate through each move in the PGN/UCI generated 103 | board.push(move) #play each move in the PGN 104 | 105 | #we find all continuations 106 | self.workerPlay = WorkerPlay(settings, status, engine, board.fen()) #we call the api to get the stats in the position 107 | continuations = self.workerPlay.find_move_tree() #list all continuations 108 | #logging.debug(continuations) 109 | 110 | 111 | for move in continuations: 112 | continuationLikelihood = float(move['playrate']) * float(self.likelihood) 113 | if (continuationLikelihood >= (float(moveSelection.depth_likelihood))) and (move['total_games'] > moveSelection.continuation_games): #we eliminate continuations that don't meet depth likelihood or minimum games 114 | move ['cumulativeLikelihood'] = (continuationLikelihood) 115 | validContinuations.append(move) 116 | #print (float(move['playrate']),float(self.likelihood),float(settings.moveSelection.depth_likelihood)) 117 | #logging.debug(continuationLikelihood) 118 | logging.debug (f'valid continuations: {validContinuations}') 119 | 120 | 121 | 122 | #now we iterate through each valid continuation, and find our best response 123 | for move in validContinuations: 124 | board.push_san(move['san']) #we play each valid continuation 125 | 126 | self.likelihood_path.append((move['san'], move['playrate'])) #we add the continuation to the likelihood path 127 | 128 | 129 | #we look for the best move for us to play 130 | self.workerPlay = WorkerPlay(settings, status, engine, board.fen()) 131 | _, self.best_move, self.potency, self.potency_range, self.total_games = self.workerPlay.pick_candidate() #list best candidate move, win rate, 132 | print_playrate = '{:+.2%}'.format(move['playrate']) 133 | print_cumulativelikelihood = '{:+.2%}'.format(move['cumulativeLikelihood']) 134 | print_winrate = "{:+.2%}".format(self.potency) 135 | print_potency_range = ["{:.2%}".format(x) for x in self.potency_range] 136 | logging.debug(f"against {move['san']} played {print_playrate} cumulative playrate {print_cumulativelikelihood} our best move {self.best_move} win rate is {print_winrate} with a range of {print_potency_range} over {self.total_games} games") 137 | 138 | #we check our response playrate and minimum played games meet threshold. if so we pass the pgn. if not we add pgn to final list 139 | 140 | if (move['playrate'] > moveSelection.min_play_rate) and (self.total_games > moveSelection.min_games) and (self.potency != 0): 141 | 142 | #we add the pgn of the continuation and our best move to a list 143 | if self.perspective_str == 'Black': 144 | newpgn = self.pgn + " " + str(board.fullmove_number) + ". " + str(move['san']) #we add opponent's continuations first 145 | newpgn = newpgn + " " + str(self.best_move) #then our best response 146 | pgnPlus = [newpgn, move ['cumulativeLikelihood'], self.likelihood_path[:]] 147 | #need to return a pgn as well as moves + chance + cumulative likelihood 148 | else: 149 | newpgn = self.pgn + " " + move['san'] #we add opponent's continuations first 150 | newpgn = newpgn + " " + str(board.fullmove_number) + ". " + str(self.best_move) #then our best response 151 | pgnPlus = [newpgn, move ['cumulativeLikelihood'], self.likelihood_path[:]] 152 | logging.debug(f"full new pgn after our move is {newpgn}") 153 | 154 | #we make a list of pgns that we want to feed back into the algorithm, along with cumulative winrates 155 | pgnList.append(pgnPlus) 156 | #logging.debug(pgnList) 157 | del self.likelihood_path [-1] #we remove the continuation from the likelihood path 158 | board.pop() #we go back a move to undo the continuation 159 | else: 160 | if settings.engine.enabled and settings.engine.finish: #if we want engine to finish lines where no good move data exists 161 | 162 | #we ask the engine the best move 163 | depth = settings.engine.depth 164 | status.info2(f"Running engine for '{board.fen()}' at depth {depth}, this can take a while") 165 | PlayResult = engine.play(board, chess.engine.Limit(depth=depth)) #we get the engine to finish the line 166 | board.push(PlayResult.move) 167 | logging.debug(f"engine finished {PlayResult.move}") 168 | board.pop() #we go back a move to undo the engine 169 | 170 | engineMove = board.san(PlayResult.move) 171 | 172 | #we add the pgn of the continuation and our best move to a list 173 | if self.perspective_str == 'Black': 174 | newpgn = self.pgn + " " + str(board.fullmove_number) + ". " + str(move['san']) #we add opponent's continuations first 175 | newpgn = newpgn + " " + str(engineMove) #then our best response 176 | pgnPlus = [newpgn, move ['cumulativeLikelihood'], self.likelihood_path[:]] 177 | #need to return a pgn as well as moves + chance + cumulative likelihood 178 | else: 179 | newpgn = self.pgn + " " + move['san'] #we add opponent's continuations first 180 | newpgn = newpgn + " " + str(board.fullmove_number) + ". " + str(engineMove) #then our best response 181 | pgnPlus = [newpgn, move ['cumulativeLikelihood'], self.likelihood_path[:]] 182 | logging.debug(f"full new pgn after our move is {newpgn}") 183 | 184 | #we make a list of pgns that we want to feed back into the algorithm, along with cumulative winrates 185 | pgnList.append(pgnPlus) 186 | #logging.debug(pgnList) 187 | del self.likelihood_path [-1] #we remove the continuation from the likelihood path 188 | board.pop() #we go back a move to undo the continuation 189 | 190 | else: 191 | logging.debug(f"we find no good reply to {self.pgn} {move['san']}") 192 | board.pop() #we go back a move to undo the continuation 193 | del self.likelihood_path [-1] #we remove the continuation from the likelihood path 194 | #we find potency and other stats 195 | self.workerPlay = WorkerPlay(settings, status, engine, board.fen()) #we call the api to get the stats in the final position 196 | lineWinRate, totalLineGames, throwawayDraws = self.workerPlay.find_potency() #we get the win rate and games played in the final position 197 | logging.debug (f'saving no reply line {self.pgn} {self.likelihood} {self.likelihood_path} {lineWinRate} {totalLineGames}') 198 | line = (self.pgn, self.likelihood, self.likelihood_path,lineWinRate, totalLineGames) 199 | finalLine.append(line) #we add line to final line list 200 | 201 | 202 | global pgnsreturned #we make a globally accessible variable for the new pgns returned for each continuation 203 | pgnsreturned = pgnList #we define the variable as the completely made list of continuations and responses and send it to be extended to second list 204 | 205 | #if there are no valid continuations we save the line to a file 206 | if not validContinuations: 207 | 208 | logging.debug (f'no valid continuations to {self.pgn}') 209 | 210 | #we find potency and other stats 211 | self.workerPlay = WorkerPlay(settings, status, engine, board.fen()) #we call the api to get the stats in the final position 212 | lineWinRate, totalLineGames, throwawayDraws = self.workerPlay.find_potency() #we get the win rate and games played in the final position 213 | 214 | 215 | if (totalLineGames == 0) and (lineWinRate == None): #if the line ends in mate there are no games played from the position so we need to populate games number from last move 216 | board.pop() 217 | self.workerPlay = WorkerPlay(settings, status, engine, board.fen()) #we call the api to get the stats in the final position 218 | throwawayWinRate, totalLineGames, throwawayDraws = self.workerPlay.find_potency() #we get the games played in the pre Mate position 219 | lineWinRate = 1 #we make line win rate 1 220 | logging.debug(f'line ends in mate') 221 | 222 | else: 223 | if (totalLineGames < moveSelection.min_games) : #if our response is an engine 'novelty' there is no reliable lineWinRate or total games 224 | board.pop() #we go back to opponent's move 225 | self.workerPlay = WorkerPlay(settings, status, engine, board.fen()) 226 | lineWinRate, totalLineGames, draws = self.workerPlay.find_potency() 227 | 228 | 229 | if moveSelection.draws_are_half: #if draws are half we inverse the winrate on the last move, and add half the draws 230 | lineWinRate = 1 - lineWinRate + (0.5 * draws) 231 | logging.debug(f"total games on previous move: {totalLineGames}, draws are wins and our move is engine 'almost novelty' so win rate based on previous move is {lineWinRate}") 232 | else: 233 | 234 | lineWinRate = 1 - lineWinRate - draws #if draws aren't half we inverse the winrate and remove minus the draws 235 | logging.debug(f"total games on previous move: {totalLineGames}, draws aren't wins and our move is engine 'almost novelty' so win rate based on prev move is {lineWinRate}") 236 | 237 | 238 | line = (self.pgn, self.likelihood, self.likelihood_path, lineWinRate, totalLineGames) 239 | finalLine.append(line) #we add line to final line list 240 | 241 | 242 | class Printer: 243 | def __init__(self, settings, filepath): 244 | self.settings = settings 245 | self.filepath = filepath 246 | with open(self.filepath, 'w') as f: 247 | f.write('') 248 | logging.info(f"Created new file at: {self.filepath}") 249 | 250 | def print(self, pgn, cumulative, likelyPath, winRate, Games, lineNumber, openingName): 251 | with open(self.filepath, 'a') as file: 252 | pgnEvent = '[Event "' + openingName + " Line " + str(lineNumber) + '"]' #we name the event whatever you put in config 253 | # annotation = "{likelihoods to get here:" + str(self.likelihood_path) + ". Cumulative likelihood" + str("{:+.2%}".format(self.likelihood)) + " }" #we create annotation with opponent move likelihoods and our win rate 254 | 255 | file.write('\n' + '\n' + '\n' + pgnEvent + '\n' ) #write name of pgn 256 | file.write ('\n' + pgn) #write pgn 257 | 258 | file.write('\n' + "{Move playrates:") #start annotations 259 | 260 | for move, chance in likelyPath: 261 | moveAnnotation = str("{:+.2%}".format(chance)) + '\t' + move 262 | file.write ('\n' + moveAnnotation) 263 | 264 | 265 | #we write them in as annotations 266 | if self.settings.moveSelection.draws_are_half: 267 | lineAnnotations = "Line cumulative playrate: " + str("{:+.2%}".format(cumulative)) + '\n' + "Line winrate (draws are half): " + str("{:+.2%}".format(winRate)) + ' over ' + str(Games) + ' games' 268 | else: 269 | lineAnnotations = "Line cumulative playrate: " + str("{:+.2%}".format(cumulative)) + '\n' + "Line winrate (excluding draws): " + str("{:+.2%}".format(winRate)) + ' over ' + str(Games) + ' games' 270 | file.write('\n' + lineAnnotations) 271 | 272 | 273 | file.write("}") #end annotations 274 | logging.info(f"Wrote data to {self.filepath}") 275 | 276 | 277 | class Grower: 278 | is_running = False 279 | settings = None 280 | status = None 281 | engine = None 282 | 283 | # todo: this method needs to be synchronised, and main logic should run in a separate thread 284 | def run(self, settings: Settings, status: GenerationStatus, callback: Callable): 285 | if self.is_running: 286 | logging.info("Repertoire generation is already running") 287 | return 288 | 289 | self.is_running = True 290 | self.settings = settings 291 | self.status = status 292 | self.start_engine() 293 | 294 | try: 295 | for chapter, opening in enumerate(settings.book.get_books(), 1): 296 | status.info(f"Generating book #{chapter} '{opening.name}' for PGN '{opening.pgn}'") 297 | self.iterator(chapter, opening.name, opening.pgn) 298 | callback() 299 | except Exception as e: 300 | logging.error(e) 301 | finally: 302 | self.stop() 303 | 304 | def stop(self): 305 | if self.engine: 306 | self.engine.quit() 307 | self.is_running = False 308 | 309 | def start_engine(self): 310 | if not self.settings.engine.enabled: 311 | self.engine = None 312 | return 313 | 314 | engine = chess.engine.SimpleEngine.popen_uci(self.settings.engine.path) 315 | engine.configure({"Hash": self.settings.engine.hash}) 316 | engine.configure({"Threads": self.settings.engine.threads}) 317 | logging.getLogger('chess.engine').setLevel(logging.INFO) 318 | self.engine = engine 319 | 320 | def iterator(self, chapter, openingName, openingPgn): 321 | global finalLine 322 | finalLine = [] 323 | global pgnsreturned #we make a globally accessible variable for the new pgns returned by Rooter 324 | pgnsreturned = [] 325 | 326 | Rooter(self.settings, self.status, self.engine, openingPgn) 327 | 328 | secondList = [] 329 | secondList.extend(pgnsreturned) #we create list of pgns and cumulative probabilities returned by starter, calling the api each move 330 | print ("second list",secondList) 331 | 332 | 333 | # #we iterate through these with leafer, calling the api only for new moves. 334 | i = 0 335 | while i < len(secondList): 336 | for pgn, cumulative, likelyPath in secondList: 337 | Leafer(self.settings, self.status, self.engine, pgn, cumulative, likelyPath) 338 | secondList.extend(pgnsreturned) 339 | i += 1 340 | # logging.debug("iterative",secondList) 341 | 342 | #print ("final line list: ", finalLine) 343 | 344 | 345 | #we remove duplicate lines 346 | uniqueFinalLine = [] 347 | for line in finalLine: 348 | if line not in uniqueFinalLine: 349 | uniqueFinalLine.append(line) 350 | # logging.debug(f"unique lines with subsets {uniqueFinalLine}") 351 | 352 | printerFinalLine = [] #we prepare a list ready for printing 353 | 354 | # we remove lines that are subsets of other lines because no valid repsonse was found 355 | for line in uniqueFinalLine: 356 | uniqueFinalLinestring = str(uniqueFinalLine) 357 | lineString = str(line[0]) + " " 358 | lineCount = uniqueFinalLinestring.count(lineString) 359 | if lineCount == 0: 360 | printerFinalLine.append(line) #we add line to go to print 361 | else: 362 | logging.debug(f"duplicate line {line}") 363 | logging.debug(f"final line count { lineCount+1 } for line {lineString}") 364 | 365 | logging.debug(f'we sort the lines by consecutive move probabilities') 366 | 367 | def extract_key(printerFinalLine): 368 | return [v for _, v in printerFinalLine[2]] 369 | 370 | printerFinalLine = sorted(printerFinalLine, key=extract_key) 371 | 372 | for line in printerFinalLine: 373 | logging.debug (line[0]) 374 | 375 | logging.debug (f'we reverse the sort to make long to short') 376 | if self.settings.book.order.LONG_TO_SHORT: 377 | printerFinalLine.reverse() #we make the longest (main lines) first 378 | 379 | for line in printerFinalLine: 380 | logging.debug (line[0]) 381 | 382 | #we print the final list of lines 383 | logging.debug(f'number of final lines {len(printerFinalLine)}') 384 | logging.debug(f'final line sorted {printerFinalLine}') 385 | printer = Printer(self.settings, f"{working_dir}/Chapter_{chapter}_{openingName}.pgn") 386 | 387 | lineNumber = 1 388 | for pgn, cumulative, likelyPath, winRate, Games in printerFinalLine: 389 | printer.print(pgn, cumulative, likelyPath, winRate, Games, lineNumber, openingName) 390 | lineNumber += 1 391 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 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 | 635 | Copyright (C) 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 . 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 | Copyright (C) 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 | . 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 | . 675 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | 2 | 3 | # BookBuilder 4 | An automatic practical Chess opening repertoire builder. 5 | 6 | 7 | If you want to understand why this exists, how it works, or get example repertoires, check here: 8 | 9 | https://www.alexcrompton.com/blog/automatically-creating-a-practical-opening-repertoire-or-why-your-chess-openings-suck 10 | 11 | 12 | ## GUI Update 13 | The awesome @drauf has built an interface. It should be much more self explanatory now! 14 | 15 | ## ChessBook Update 16 | I'm no longer actively udpating BookBuilder, but the good people at https://chessbook.com/ have implemented many of the principles in a much more user friendly way. If you're interested in building your own repertoire I would start there. I'm not affiliated in any way. 17 | 18 | 19 | 20 | --- 21 | 22 | ### Acknowledgements 23 | 24 | Thanks to creators like Ben Johnson, Daniel Lona, Nate Solon, and Marcus Buffett, for all their ideas and inspiration. Thanks also to David Foster for Chess Trap Scorer, which was not just part of the inspiration, but also all of the starting point code wise for this program. 25 | 26 | The [lichess opening API](https://lichess.org/api) is used to gather data for the analysis. No token is required. 27 | -------------------------------------------------------------------------------- /gui.py: -------------------------------------------------------------------------------- 1 | import os 2 | import webbrowser 3 | from typing import List 4 | 5 | import dearpygui.dearpygui as dpg 6 | import psutil 7 | 8 | from BookBuilder import Grower 9 | from gui_generation_status import GenerationStatus 10 | from gui_themes import set_imgui_light_theme 11 | from settings import Settings, Speed, Rating, Book, Order, Variant 12 | 13 | WINDOW_WIDTH = 980 14 | WINDOW_HEIGHT = 720 15 | 16 | SETTINGS_GROUP_XOFFSET = 180 17 | 18 | PRIMARY_WINDOW_TAG = "primary_window" 19 | 20 | BLOG_LINK = "https://www.alexcrompton.com/blog/automatically-creating-a-practical-opening-repertoire-or-why-your-chess-openings-suck" 21 | SOURCE_CODE_LINK = "https://github.com/raccrompton/BookBuilder" 22 | 23 | 24 | class Gui: 25 | def __init__(self, settings: Settings, grower: Grower): 26 | self.settings = settings 27 | self.grower = grower 28 | 29 | def create(self): 30 | dpg.create_context() 31 | dpg.create_viewport( 32 | title='BookBuilder', 33 | width=WINDOW_WIDTH, 34 | min_width=WINDOW_WIDTH, 35 | height=WINDOW_HEIGHT, 36 | x_pos=0, 37 | y_pos=0) 38 | 39 | set_imgui_light_theme() 40 | self._create_primary_window() 41 | 42 | dpg.set_exit_callback(callback=self._shutdown_callback) 43 | dpg.setup_dearpygui() 44 | dpg.show_viewport() 45 | dpg.start_dearpygui() 46 | dpg.destroy_context() 47 | 48 | def _shutdown_callback(self): 49 | self.grower.stop() 50 | 51 | def _create_primary_window(self): 52 | with dpg.window(tag=PRIMARY_WINDOW_TAG): 53 | dpg.set_primary_window(PRIMARY_WINDOW_TAG, True) 54 | self._menu_bar() 55 | self._summary() 56 | self._book_settings() 57 | self._database_settings() 58 | self._move_selection_settings() 59 | self._engine_settings() 60 | 61 | def _menu_bar(self): 62 | def reload_settings_and_restart_gui(): 63 | self.settings.load_from_file() 64 | # the easiest way to show reloaded settings is to destroy the gui and recreate it 65 | dpg.delete_item(PRIMARY_WINDOW_TAG) 66 | self._create_primary_window() 67 | 68 | with dpg.menu_bar(): 69 | with dpg.menu(label="Settings"): 70 | dpg.add_menu_item(label="Load", callback=reload_settings_and_restart_gui) 71 | dpg.add_menu_item(label="Save", callback=lambda: self.settings.save_to_file()) 72 | 73 | with dpg.menu(label="Help"): 74 | _menu_link("Announcement blog post and FAQ", BLOG_LINK) 75 | _menu_link("Source code", SOURCE_CODE_LINK) 76 | 77 | def _summary(self): 78 | s = self.settings 79 | dpg.add_text("An automatic practical chess opening repertoire builder using Lichess opening explorer API") 80 | dpg.add_text("Customize your settings and then press the button below to begin generating your repertoire") 81 | status = GenerationStatus() 82 | 83 | def get_invalid_books() -> List[Book]: 84 | invalid_books = list() 85 | for book in s.book.get_books(): 86 | if not book.is_valid_pgn(): 87 | invalid_books.append(book) 88 | return invalid_books 89 | 90 | def start_generation(button_tag): 91 | # validate engine path 92 | if s.engine.enabled: 93 | if s.engine.path == s.engine.NO_FILE_SELECTED: 94 | status.error("No engine path was provided", 95 | "Provide it under 'Engine settings' or unselect 'Use engine' and retry") 96 | return 97 | if not os.path.exists(s.engine.path): 98 | status.error(f"Provided engine path '{s.engine.path}' does not exist\n", 99 | "Correct it under 'Engine settings' or unselect 'Use engine' and retry") 100 | return 101 | 102 | # validate books from free-text input are valid 103 | invalid_books = get_invalid_books() 104 | if len(invalid_books) > 0: 105 | status.error("Book(s) listed below are invalid. Correct them under 'Book settings' and retry\n", 106 | "\n\n".join([book.__str__() for book in invalid_books])) 107 | return 108 | 109 | def finish_callback(): 110 | dpg.enable_item(button_tag) 111 | status.info("Finished generating your repertoire", 112 | "You will find your PGNs in the same folder where BookBuilder is located") 113 | 114 | status.info("PGN generation started") 115 | dpg.disable_item(button_tag) 116 | self.grower.run(self.settings, status, finish_callback) 117 | 118 | dpg.add_button(label="Generate PGN", width=120, height=30, before=status._line1, callback=start_generation) 119 | 120 | def _book_settings(self): 121 | s = self.settings.book 122 | with dpg.group(): 123 | with dpg.collapsing_header(label="Book settings", default_open=True): 124 | with dpg.group(horizontal=True, xoffset=SETTINGS_GROUP_XOFFSET): 125 | dpg.add_text("Variations order") 126 | _help( 127 | "Choose whether you want chapters ordered from long lines to short lines or the opposite way") 128 | dpg.add_combo(items=[str(o.value) for o in Order], default_value=s.order.value, 129 | callback=s.order_callback) 130 | 131 | with dpg.group(horizontal=True, xoffset=SETTINGS_GROUP_XOFFSET): 132 | dpg.add_text("Opening books") 133 | _help("Add the starting point PGNs you want to create repertoires for\n" 134 | "The format is book name, new line, PGN, new line(s), like so:\n\n" 135 | "Book A\n" 136 | "1. e4 e5\n\n" 137 | "Book B\n" 138 | "1. e4 e5 2. f4\n\n" 139 | "Tip: Copying and pasting with keyboard shortcuts works in this input!") 140 | dpg.add_input_text(multiline=True, 141 | tab_input=True, 142 | height=200, 143 | default_value=s.books_string, 144 | callback=s.books_string_callback) 145 | 146 | def _database_settings(self): 147 | s = self.settings.database 148 | with dpg.group(): 149 | with dpg.collapsing_header(label="Database settings", default_open=True): 150 | with dpg.group(horizontal=True, xoffset=SETTINGS_GROUP_XOFFSET): 151 | dpg.add_text("Variant") 152 | _help("Variant to use in the analysis") 153 | dpg.add_combo( 154 | items=[v.name for v in Variant], 155 | default_value=s.variant.name, 156 | callback=s.variant_callback) 157 | 158 | with dpg.group(horizontal=True, xoffset=SETTINGS_GROUP_XOFFSET): 159 | with dpg.group(): 160 | dpg.add_text("Speeds") 161 | _help("Formats to include in the analysis") 162 | with dpg.group(): 163 | for speed in Speed: 164 | dpg.add_selectable( 165 | label=speed.name, 166 | user_data=speed.name, 167 | default_value=s.speeds.__contains__(speed), 168 | callback=s.speed_callback) 169 | 170 | with dpg.group(horizontal=True, xoffset=SETTINGS_GROUP_XOFFSET): 171 | dpg.add_text("Ratings") 172 | _help("Ratings of the players to include in the analysis") 173 | with dpg.group(): 174 | for rating in Rating: 175 | dpg.add_selectable( 176 | label=str(rating.value), 177 | user_data=rating.name, 178 | default_value=s.ratings.__contains__(rating), 179 | callback=s.rating_callback) 180 | 181 | with dpg.group(horizontal=True, xoffset=SETTINGS_GROUP_XOFFSET): 182 | dpg.add_text("Moves") 183 | _help("The number of most played moves to search over for the best move (minimum 5)") 184 | dpg.add_input_int( 185 | min_value=5, 186 | max_value=100, 187 | min_clamped=True, 188 | default_value=s.moves, 189 | callback=s.moves_callback) 190 | 191 | def _move_selection_settings(self): 192 | s = self.settings.moveSelection 193 | with dpg.group(): 194 | with dpg.collapsing_header(label="Move selection settings", default_open=True): 195 | with dpg.group(horizontal=True, xoffset=SETTINGS_GROUP_XOFFSET): 196 | dpg.add_text("Depth likelihood %") 197 | _help("This controls how deep moves and lines are generated\n" 198 | "The smaller the number the deeper the lines\n" 199 | "Once cumulative line likelihood reaches this probability threshold, no further continuations will be added\n" 200 | "E.g. for 1% only moves that appear at least once every 100 games will be considered") 201 | dpg.add_input_float( 202 | min_value=0, 203 | max_value=10, 204 | min_clamped=True, 205 | format='%.4f', 206 | step=0.01, 207 | step_fast=0.1, 208 | default_value=s.depth_likelihood * 100, 209 | callback=s.depth_callback) 210 | 211 | with dpg.group(horizontal=True, xoffset=SETTINGS_GROUP_XOFFSET): 212 | dpg.add_text("Alpha %") 213 | _help("The larger this number the more likely we are to select moves with less data\n" 214 | "This is the confidence interval alpha (e.g. 1 = 99% CI), for deciding the lower bounds of how good a move's winrate is") 215 | dpg.add_input_float( 216 | min_value=0, 217 | max_value=10, 218 | min_clamped=True, 219 | format='%.3f', 220 | step=0.01, 221 | step_fast=0.1, 222 | default_value=s.alpha * 100, 223 | callback=s.alpha_callback) 224 | 225 | with dpg.group(horizontal=True, xoffset=SETTINGS_GROUP_XOFFSET): 226 | dpg.add_text("Minimum play rate %") 227 | _help( 228 | "Minimum probability of our move being played in a position to be considered as a 'best move' candidate") 229 | dpg.add_input_float( 230 | min_value=0, 231 | max_value=10, 232 | min_clamped=True, 233 | format='%.3f', 234 | step=0.01, 235 | step_fast=0.1, 236 | default_value=s.min_play_rate * 100, 237 | callback=s.min_play_rate_callback) 238 | 239 | with dpg.group(horizontal=True, xoffset=SETTINGS_GROUP_XOFFSET): 240 | dpg.add_text("Minimum games") 241 | _help( 242 | "Games where our moves were played this or fewer times will be discarded (unless top engine move)") 243 | dpg.add_input_int( 244 | min_value=0, 245 | min_clamped=True, 246 | default_value=s.min_games, 247 | callback=s.min_games_callback) 248 | 249 | with dpg.group(horizontal=True, xoffset=SETTINGS_GROUP_XOFFSET): 250 | dpg.add_text("Continuation games") 251 | _help( 252 | "Games where moves played this or fewer times will not be considered a valid opponent continuation\n" 253 | "I.e. we don't want to be inferring cumulative probability or likely lines from tiny amounts of games/1 game") 254 | dpg.add_input_int( 255 | min_value=0, 256 | min_clamped=True, 257 | default_value=s.continuation_games, 258 | callback=s.continuation_games_callback) 259 | 260 | with dpg.group(horizontal=True, xoffset=SETTINGS_GROUP_XOFFSET): 261 | dpg.add_text("Draws are half") 262 | _help( 263 | "Select this if you want to count draws as half a win (0.5 points) for the win rate calculation\n" 264 | "When not selected draws will count as as losses") 265 | dpg.add_checkbox(default_value=s.draws_are_half, callback=s.draws_are_half_callback) 266 | 267 | def _engine_settings(self): 268 | s = self.settings.engine 269 | with dpg.group(): 270 | with dpg.collapsing_header(label="Engine settings", default_open=False): 271 | with dpg.group(horizontal=True, xoffset=SETTINGS_GROUP_XOFFSET): 272 | dpg.add_text("Use engine") 273 | _help("Select this if you want to use engine evaluations of positions or engine finishing") 274 | dpg.add_checkbox(default_value=s.enabled, callback=s.enabled_callback) 275 | 276 | with dpg.group(horizontal=True, xoffset=SETTINGS_GROUP_XOFFSET): 277 | dpg.add_text("Engine path") 278 | _help("Select where the engine is stored on your computer\n" 279 | "It should be a file named similar to 'stockfish_15_x64_avx2.exe'") 280 | with dpg.group(): 281 | with dpg.group(horizontal=True): 282 | engine_path_text = dpg.add_text(s.path) 283 | 284 | def call_path_callback_and_update_path_in_gui(_, file_selections): 285 | s.path_callback(file_selections) 286 | dpg.set_value(engine_path_text, s.path) 287 | 288 | with dpg.file_dialog(label="Select engine file", 289 | width=WINDOW_WIDTH - 100, 290 | height=WINDOW_HEIGHT - 100, 291 | show=False, 292 | callback=call_path_callback_and_update_path_in_gui): 293 | dpg.add_file_extension(".*") 294 | dpg.add_file_extension("", color=(0, 0, 255, 255)) 295 | dpg.add_file_extension(".exe", color=(0, 180, 0, 255)) 296 | 297 | dpg.add_button(label="Select engine file", 298 | user_data=dpg.last_container(), 299 | callback=lambda _, a, u: dpg.configure_item(u, show=True)) 300 | 301 | with dpg.group(horizontal=True): 302 | dpg.add_text("You can download the latest Stockfish executable from here:") 303 | dpg.add_button( 304 | label="Download Stockfish", 305 | callback=lambda: webbrowser.open("https://stockfishchess.org/download/")) 306 | dpg.add_text( 307 | "On Mac download engine only (not the app) and run `which stockfish` in Terminal to see where it's installed") 308 | 309 | with dpg.group(horizontal=True, xoffset=SETTINGS_GROUP_XOFFSET): 310 | dpg.add_text("Engine finish") 311 | _help( 312 | "Select to allow the engine to complete lines upto the cumulative likelihood, where human data doesn't meet the minimum criteria\n" 313 | "When not selected lines will end when there is no good human data for one player") 314 | dpg.add_checkbox(default_value=s.finish, callback=s.finish_callback) 315 | 316 | with dpg.group(horizontal=True, xoffset=SETTINGS_GROUP_XOFFSET): 317 | dpg.add_text("Engine depth") 318 | _help("To what depth the engine should evaluate best moves\n" 319 | "The higher this number the longer the evaluation will take\n\n" 320 | "RECOMMENDED a minimum of 20+, ideally 30+ for stable evaluations in the opening phase") 321 | dpg.add_input_int( 322 | min_value=1, 323 | min_clamped=True, 324 | default_value=s.depth, 325 | callback=s.depth_callback) 326 | 327 | with dpg.group(horizontal=True, xoffset=SETTINGS_GROUP_XOFFSET): 328 | logical_cores = psutil.cpu_count(logical=True) 329 | dpg.add_text("Engine threads") 330 | _help("How many threads you want the engine to use\n" 331 | "Increase this number to speed the engine up, at the cost of higher CPU usage\n\n" 332 | f"Your processor has {logical_cores} logical cores") 333 | dpg.add_input_int( 334 | min_value=1, 335 | max_value=logical_cores, 336 | min_clamped=True, 337 | max_clamped=True, 338 | default_value=s.threads, 339 | callback=s.threads_callback) 340 | 341 | with dpg.group(horizontal=True, xoffset=SETTINGS_GROUP_XOFFSET): 342 | total_ram_in_mb = int(psutil.virtual_memory().total / 1024 / 1024) 343 | available_ram_in_mb = int(psutil.virtual_memory().available / 1024 / 1024) 344 | dpg.add_text("Engine hash in MB") 345 | _help("How much RAM you want the engine to use\n" 346 | "Increase this number to speed the engine up\n\n" 347 | f"You have {total_ram_in_mb} MB total RAM and around {available_ram_in_mb} MB available (unused) RAM") 348 | dpg.add_input_int( 349 | min_value=16, 350 | max_value=total_ram_in_mb, 351 | min_clamped=True, 352 | max_clamped=True, 353 | default_value=s.hash, 354 | callback=s.hash_callback) 355 | 356 | with dpg.group(horizontal=True, xoffset=SETTINGS_GROUP_XOFFSET): 357 | dpg.add_text("Soundness limit") 358 | _help( 359 | "Maximum centipawns we are willing to be down in engine eval, provided the winrate is better (-300 = losing by 3 pawns in eval)\n" 360 | "We never give up a forced mate, however\n\n" 361 | "Example:\n" 362 | "Move A has 60% human win rate at -1.1 engine evaluation\n" 363 | "Move B has 55% human win rate at -0.9 engine evaluation\n" 364 | "With soundness limit of -99 centipawns (-0.99) we will select move B, as -1.1 exceeds -0.99") 365 | dpg.add_input_int(default_value=s.soundness_limit, callback=s.soundness_limit_callback) 366 | 367 | with dpg.group(horizontal=True, xoffset=SETTINGS_GROUP_XOFFSET): 368 | dpg.add_text("Move loss limit") 369 | _help( 370 | "Maximum centipawns we are willing to lose per move in favor of a higher human winrate move, compared to the top engine choice\n" 371 | "We never give up a forced mate, however\n\n" 372 | "RECOMMENDED to not go closer to 0 than -50 because engines are inconsistent when evaluating openings, especially on low depth\n\n" 373 | "Example:\n" 374 | "Move A has 80% human win rate at 1.0 engine evaluation\n" 375 | "Move B has 60% human win rate at 2.0 engine evaluation\n" 376 | "With move loss limit of -99 centipawns (-0.99) we will select move B, as 1.0-2.0=-1.0 exceeds -0.99") 377 | dpg.add_input_int(default_value=s.move_loss_limit, callback=s.move_loss_limit_callback) 378 | 379 | with dpg.group(horizontal=True, xoffset=SETTINGS_GROUP_XOFFSET): 380 | dpg.add_text("Ignore loss limit") 381 | _help( 382 | "Centipawns advantage above which we won't care if we play a move that hits our loss limit, if it has a higher human win rate\n\n" 383 | "Example:\n" 384 | "Move A has 80% human win rate at 3.2 engine evaluation\n" 385 | "Move B has 60% human win rate at 5.7 engine evaluation\n" 386 | "With ignore loss limit of 300 centipawns (3.0) we will select move A, as 3.2 exceeds 3.0") 387 | dpg.add_input_int(default_value=s.ignore_loss_limit, callback=s.ignore_loss_limit_callback) 388 | 389 | 390 | def _menu_link(label: str, url: str): 391 | dpg.add_menu_item(label=label, callback=lambda: webbrowser.open(url)) 392 | 393 | 394 | def _help(message: str): 395 | last_item = dpg.last_item() 396 | group = dpg.add_group(horizontal=True) 397 | dpg.move_item(last_item, parent=group) 398 | dpg.capture_next_item(lambda s: dpg.move_item(s, parent=group)) 399 | t = dpg.add_text("(?)", color=[0.26 * 255, 0.59 * 255, 0.98 * 255, 255]) 400 | with dpg.tooltip(t): 401 | dpg.add_text(message) 402 | -------------------------------------------------------------------------------- /gui_generation_status.py: -------------------------------------------------------------------------------- 1 | import dearpygui.dearpygui as dpg 2 | 3 | 4 | class GenerationStatus: 5 | black = [0, 0, 0] 6 | red = [255, 0, 0] 7 | 8 | def __init__(self): 9 | self._line1 = dpg.add_text() 10 | self._line2 = dpg.add_text() 11 | 12 | def info(self, line1: str = "", line2: str = ""): 13 | self._set_color(self.black) 14 | self._set_text(line1, line2) 15 | 16 | def info2(self, line2): 17 | dpg.set_value(self._line2, line2) 18 | 19 | def error(self, line1: str = "", line2: str = ""): 20 | self._set_color(self.red) 21 | self._set_text(line1, line2) 22 | 23 | def _set_color(self, color): 24 | dpg.configure_item(self._line1, color=color) 25 | dpg.configure_item(self._line2, color=color) 26 | 27 | def _set_text(self, line1, line2): 28 | dpg.set_value(self._line1, line1) 29 | dpg.set_value(self._line2, line2) 30 | -------------------------------------------------------------------------------- /gui_themes.py: -------------------------------------------------------------------------------- 1 | import dearpygui.dearpygui as dpg 2 | 3 | 4 | # Source: https://github.com/hoffstadt/DearPyGui_Ext/blob/master/dearpygui_ext/themes.py 5 | # 6 | # MIT License 7 | # 8 | # Copyright (c) 2021 Raylock, LLC 9 | # 10 | # Permission is hereby granted, free of charge, to any person obtaining a copy 11 | # of this software and associated documentation files (the "Software"), to deal 12 | # in the Software without restriction, including without limitation the rights 13 | # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 14 | # copies of the Software, and to permit persons to whom the Software is 15 | # furnished to do so, subject to the following conditions: 16 | # 17 | # The above copyright notice and this permission notice shall be included in all 18 | # copies or substantial portions of the Software. 19 | # 20 | # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 21 | # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 22 | # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 23 | # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 24 | # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 25 | # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 26 | # SOFTWARE. 27 | def set_imgui_light_theme(): 28 | with dpg.theme() as theme_id: 29 | with dpg.theme_component(0): 30 | dpg.add_theme_color(dpg.mvThemeCol_Text, (0.00 * 255, 0.00 * 255, 0.00 * 255, 1.00 * 255)) 31 | dpg.add_theme_color(dpg.mvThemeCol_TextDisabled, (0.60 * 255, 0.60 * 255, 0.60 * 255, 1.00 * 255)) 32 | dpg.add_theme_color(dpg.mvThemeCol_WindowBg, (0.94 * 255, 0.94 * 255, 0.94 * 255, 1.00 * 255)) 33 | dpg.add_theme_color(dpg.mvThemeCol_ChildBg, (0.00 * 255, 0.00 * 255, 0.00 * 255, 0.00 * 255)) 34 | dpg.add_theme_color(dpg.mvThemeCol_PopupBg, (1.00 * 255, 1.00 * 255, 1.00 * 255, 0.98 * 255)) 35 | dpg.add_theme_color(dpg.mvThemeCol_Border, (0.00 * 255, 0.00 * 255, 0.00 * 255, 0.30 * 255)) 36 | dpg.add_theme_color(dpg.mvThemeCol_BorderShadow, (0.00 * 255, 0.00 * 255, 0.00 * 255, 0.00 * 255)) 37 | dpg.add_theme_color(dpg.mvThemeCol_FrameBg, (1.00 * 255, 1.00 * 255, 1.00 * 255, 1.00 * 255)) 38 | dpg.add_theme_color(dpg.mvThemeCol_FrameBgHovered, (0.26 * 255, 0.59 * 255, 0.98 * 255, 0.40 * 255)) 39 | dpg.add_theme_color(dpg.mvThemeCol_FrameBgActive, (0.26 * 255, 0.59 * 255, 0.98 * 255, 0.67 * 255)) 40 | dpg.add_theme_color(dpg.mvThemeCol_TitleBg, (0.96 * 255, 0.96 * 255, 0.96 * 255, 1.00 * 255)) 41 | dpg.add_theme_color(dpg.mvThemeCol_TitleBgActive, (0.82 * 255, 0.82 * 255, 0.82 * 255, 1.00 * 255)) 42 | dpg.add_theme_color(dpg.mvThemeCol_TitleBgCollapsed, (1.00 * 255, 1.00 * 255, 1.00 * 255, 0.51 * 255)) 43 | dpg.add_theme_color(dpg.mvThemeCol_MenuBarBg, (0.86 * 255, 0.86 * 255, 0.86 * 255, 1.00 * 255)) 44 | dpg.add_theme_color(dpg.mvThemeCol_ScrollbarBg, (0.98 * 255, 0.98 * 255, 0.98 * 255, 0.53 * 255)) 45 | dpg.add_theme_color(dpg.mvThemeCol_ScrollbarGrab, (0.69 * 255, 0.69 * 255, 0.69 * 255, 0.80 * 255)) 46 | dpg.add_theme_color(dpg.mvThemeCol_ScrollbarGrabHovered, (0.49 * 255, 0.49 * 255, 0.49 * 255, 0.80 * 255)) 47 | dpg.add_theme_color(dpg.mvThemeCol_ScrollbarGrabActive, (0.49 * 255, 0.49 * 255, 0.49 * 255, 1.00 * 255)) 48 | dpg.add_theme_color(dpg.mvThemeCol_CheckMark, (0.26 * 255, 0.59 * 255, 0.98 * 255, 1.00 * 255)) 49 | dpg.add_theme_color(dpg.mvThemeCol_SliderGrab, (0.26 * 255, 0.59 * 255, 0.98 * 255, 0.78 * 255)) 50 | dpg.add_theme_color(dpg.mvThemeCol_SliderGrabActive, (0.46 * 255, 0.54 * 255, 0.80 * 255, 0.60 * 255)) 51 | dpg.add_theme_color(dpg.mvThemeCol_Button, (0.26 * 255, 0.59 * 255, 0.98 * 255, 0.40 * 255)) 52 | dpg.add_theme_color(dpg.mvThemeCol_ButtonHovered, (0.26 * 255, 0.59 * 255, 0.98 * 255, 1.00 * 255)) 53 | dpg.add_theme_color(dpg.mvThemeCol_ButtonActive, (0.06 * 255, 0.53 * 255, 0.98 * 255, 1.00 * 255)) 54 | dpg.add_theme_color(dpg.mvThemeCol_Header, (0.26 * 255, 0.59 * 255, 0.98 * 255, 0.31 * 255)) 55 | dpg.add_theme_color(dpg.mvThemeCol_HeaderHovered, (0.26 * 255, 0.59 * 255, 0.98 * 255, 0.80 * 255)) 56 | dpg.add_theme_color(dpg.mvThemeCol_HeaderActive, (0.26 * 255, 0.59 * 255, 0.98 * 255, 1.00 * 255)) 57 | dpg.add_theme_color(dpg.mvThemeCol_Separator, (0.39 * 255, 0.39 * 255, 0.39 * 255, 0.62 * 255)) 58 | dpg.add_theme_color(dpg.mvThemeCol_SeparatorHovered, (0.14 * 255, 0.44 * 255, 0.80 * 255, 0.78 * 255)) 59 | dpg.add_theme_color(dpg.mvThemeCol_SeparatorActive, (0.14 * 255, 0.44 * 255, 0.80 * 255, 1.00 * 255)) 60 | dpg.add_theme_color(dpg.mvThemeCol_ResizeGrip, (0.35 * 255, 0.35 * 255, 0.35 * 255, 0.17 * 255)) 61 | dpg.add_theme_color(dpg.mvThemeCol_ResizeGripHovered, (0.26 * 255, 0.59 * 255, 0.98 * 255, 0.67 * 255)) 62 | dpg.add_theme_color(dpg.mvThemeCol_ResizeGripActive, (0.26 * 255, 0.59 * 255, 0.98 * 255, 0.95 * 255)) 63 | dpg.add_theme_color(dpg.mvThemeCol_Tab, (0.76 * 255, 0.80 * 255, 0.84 * 255, 0.93 * 255)) 64 | dpg.add_theme_color(dpg.mvThemeCol_TabHovered, (0.26 * 255, 0.59 * 255, 0.98 * 255, 0.80 * 255)) 65 | dpg.add_theme_color(dpg.mvThemeCol_TabActive, (0.60 * 255, 0.73 * 255, 0.88 * 255, 1.00 * 255)) 66 | dpg.add_theme_color(dpg.mvThemeCol_TabUnfocused, (0.92 * 255, 0.93 * 255, 0.94 * 255, 0.99 * 255)) 67 | dpg.add_theme_color(dpg.mvThemeCol_TabUnfocusedActive, (0.74 * 255, 0.82 * 255, 0.91 * 255, 1.00 * 255)) 68 | dpg.add_theme_color(dpg.mvThemeCol_DockingPreview, (0.26 * 255, 0.59 * 255, 0.98 * 255, 0.22 * 255)) 69 | dpg.add_theme_color(dpg.mvThemeCol_DockingEmptyBg, (0.20 * 255, 0.20 * 255, 0.20 * 255, 1.00 * 255)) 70 | dpg.add_theme_color(dpg.mvThemeCol_PlotLines, (0.39 * 255, 0.39 * 255, 0.39 * 255, 1.00 * 255)) 71 | dpg.add_theme_color(dpg.mvThemeCol_PlotLinesHovered, (1.00 * 255, 0.43 * 255, 0.35 * 255, 1.00 * 255)) 72 | dpg.add_theme_color(dpg.mvThemeCol_PlotHistogram, (0.90 * 255, 0.70 * 255, 0.00 * 255, 1.00 * 255)) 73 | dpg.add_theme_color(dpg.mvThemeCol_PlotHistogramHovered, (1.00 * 255, 0.45 * 255, 0.00 * 255, 1.00 * 255)) 74 | dpg.add_theme_color(dpg.mvThemeCol_TableHeaderBg, (0.78 * 255, 0.87 * 255, 0.98 * 255, 1.00 * 255)) 75 | dpg.add_theme_color(dpg.mvThemeCol_TableBorderStrong, (0.57 * 255, 0.57 * 255, 0.64 * 255, 1.00 * 255)) 76 | dpg.add_theme_color(dpg.mvThemeCol_TableBorderLight, (0.68 * 255, 0.68 * 255, 0.74 * 255, 1.00 * 255)) 77 | dpg.add_theme_color(dpg.mvThemeCol_TableRowBg, (0.00 * 255, 0.00 * 255, 0.00 * 255, 0.00 * 255)) 78 | dpg.add_theme_color(dpg.mvThemeCol_TableRowBgAlt, (0.30 * 255, 0.30 * 255, 0.30 * 255, 0.09 * 255)) 79 | dpg.add_theme_color(dpg.mvThemeCol_TextSelectedBg, (0.26 * 255, 0.59 * 255, 0.98 * 255, 0.35 * 255)) 80 | dpg.add_theme_color(dpg.mvThemeCol_DragDropTarget, (0.26 * 255, 0.59 * 255, 0.98 * 255, 0.95 * 255)) 81 | dpg.add_theme_color(dpg.mvThemeCol_NavHighlight, (0.26 * 255, 0.59 * 255, 0.98 * 255, 0.80 * 255)) 82 | dpg.add_theme_color(dpg.mvThemeCol_NavWindowingHighlight, (0.70 * 255, 0.70 * 255, 0.70 * 255, 0.70 * 255)) 83 | dpg.add_theme_color(dpg.mvThemeCol_NavWindowingDimBg, (0.20 * 255, 0.20 * 255, 0.20 * 255, 0.20 * 255)) 84 | dpg.add_theme_color(dpg.mvThemeCol_ModalWindowDimBg, (0.20 * 255, 0.20 * 255, 0.20 * 255, 0.35 * 255)) 85 | dpg.add_theme_color(dpg.mvPlotCol_FrameBg, (1.00 * 255, 1.00 * 255, 1.00 * 255, 1.00 * 255), 86 | category=dpg.mvThemeCat_Plots) 87 | dpg.add_theme_color(dpg.mvPlotCol_PlotBg, (0.42 * 255, 0.57 * 255, 1.00 * 255, 0.13 * 255), 88 | category=dpg.mvThemeCat_Plots) 89 | dpg.add_theme_color(dpg.mvPlotCol_PlotBorder, (0.00 * 255, 0.00 * 255, 0.00 * 255, 0.00 * 255), 90 | category=dpg.mvThemeCat_Plots) 91 | dpg.add_theme_color(dpg.mvPlotCol_LegendBg, (1.00 * 255, 1.00 * 255, 1.00 * 255, 0.98 * 255), 92 | category=dpg.mvThemeCat_Plots) 93 | dpg.add_theme_color(dpg.mvPlotCol_LegendBorder, (0.82 * 255, 0.82 * 255, 0.82 * 255, 0.80 * 255), 94 | category=dpg.mvThemeCat_Plots) 95 | dpg.add_theme_color(dpg.mvPlotCol_LegendText, (0.00 * 255, 0.00 * 255, 0.00 * 255, 1.00 * 255), 96 | category=dpg.mvThemeCat_Plots) 97 | dpg.add_theme_color(dpg.mvPlotCol_TitleText, (0.00 * 255, 0.00 * 255, 0.00 * 255, 1.00 * 255), 98 | category=dpg.mvThemeCat_Plots) 99 | dpg.add_theme_color(dpg.mvPlotCol_InlayText, (0.00 * 255, 0.00 * 255, 0.00 * 255, 1.00 * 255), 100 | category=dpg.mvThemeCat_Plots) 101 | dpg.add_theme_color(dpg.mvPlotCol_XAxis, (0.00 * 255, 0.00 * 255, 0.00 * 255, 1.00 * 255), 102 | category=dpg.mvThemeCat_Plots) 103 | dpg.add_theme_color(dpg.mvPlotCol_XAxisGrid, (1.00 * 255, 1.00 * 255, 1.00 * 255, 1.00 * 255), 104 | category=dpg.mvThemeCat_Plots) 105 | dpg.add_theme_color(dpg.mvPlotCol_YAxis, (0.00 * 255, 0.00 * 255, 0.00 * 255, 1.00 * 255), 106 | category=dpg.mvThemeCat_Plots) 107 | dpg.add_theme_color(dpg.mvPlotCol_YAxisGrid, (1.00 * 255, 1.00 * 255, 1.00 * 255, 1.00 * 255), 108 | category=dpg.mvThemeCat_Plots) 109 | dpg.add_theme_color(dpg.mvPlotCol_YAxis2, (0.00 * 255, 0.00 * 255, 0.00 * 255, 1.00 * 255), 110 | category=dpg.mvThemeCat_Plots) 111 | dpg.add_theme_color(dpg.mvPlotCol_YAxisGrid2, (0.00 * 255, 0.00 * 255, 0.00 * 255, 0.50 * 255), 112 | category=dpg.mvThemeCat_Plots) 113 | dpg.add_theme_color(dpg.mvPlotCol_YAxis3, (0.00 * 255, 0.00 * 255, 0.00 * 255, 1.00 * 255), 114 | category=dpg.mvThemeCat_Plots) 115 | dpg.add_theme_color(dpg.mvPlotCol_YAxisGrid3, (0.00 * 255, 0.00 * 255, 0.00 * 255, 0.50 * 255), 116 | category=dpg.mvThemeCat_Plots) 117 | dpg.add_theme_color(dpg.mvPlotCol_Selection, (0.82 * 255, 0.64 * 255, 0.03 * 255, 1.00 * 255), 118 | category=dpg.mvThemeCat_Plots) 119 | dpg.add_theme_color(dpg.mvPlotCol_Query, (0.00 * 255, 0.84 * 255, 0.37 * 255, 1.00 * 255), 120 | category=dpg.mvThemeCat_Plots) 121 | dpg.add_theme_color(dpg.mvPlotCol_Crosshairs, (0.00 * 255, 0.00 * 255, 0.00 * 255, 0.50 * 255), 122 | category=dpg.mvThemeCat_Plots) 123 | dpg.add_theme_color(dpg.mvNodeCol_NodeBackground, (240, 240, 240, 255), category=dpg.mvThemeCat_Nodes) 124 | dpg.add_theme_color(dpg.mvNodeCol_NodeBackgroundHovered, (240, 240, 240, 255), 125 | category=dpg.mvThemeCat_Nodes) 126 | dpg.add_theme_color(dpg.mvNodeCol_NodeBackgroundSelected, (240, 240, 240, 255), 127 | category=dpg.mvThemeCat_Nodes) 128 | dpg.add_theme_color(dpg.mvNodeCol_NodeOutline, (100, 100, 100, 255), category=dpg.mvThemeCat_Nodes) 129 | dpg.add_theme_color(dpg.mvNodeCol_TitleBar, (248, 248, 248, 255), category=dpg.mvThemeCat_Nodes) 130 | dpg.add_theme_color(dpg.mvNodeCol_TitleBarHovered, (209, 209, 209, 255), category=dpg.mvThemeCat_Nodes) 131 | dpg.add_theme_color(dpg.mvNodeCol_TitleBarSelected, (209, 209, 209, 255), category=dpg.mvThemeCat_Nodes) 132 | dpg.add_theme_color(dpg.mvNodeCol_Link, (66, 150, 250, 100), category=dpg.mvThemeCat_Nodes) 133 | dpg.add_theme_color(dpg.mvNodeCol_LinkHovered, (66, 150, 250, 242), category=dpg.mvThemeCat_Nodes) 134 | dpg.add_theme_color(dpg.mvNodeCol_LinkSelected, (66, 150, 250, 242), category=dpg.mvThemeCat_Nodes) 135 | dpg.add_theme_color(dpg.mvNodeCol_Pin, (66, 150, 250, 160), category=dpg.mvThemeCat_Nodes) 136 | dpg.add_theme_color(dpg.mvNodeCol_PinHovered, (66, 150, 250, 255), category=dpg.mvThemeCat_Nodes) 137 | dpg.add_theme_color(dpg.mvNodeCol_BoxSelector, (90, 170, 250, 30), category=dpg.mvThemeCat_Nodes) 138 | dpg.add_theme_color(dpg.mvNodeCol_BoxSelectorOutline, (90, 170, 250, 150), category=dpg.mvThemeCat_Nodes) 139 | dpg.add_theme_color(dpg.mvNodeCol_GridBackground, (225, 225, 225, 255), category=dpg.mvThemeCat_Nodes) 140 | dpg.add_theme_color(dpg.mvNodeCol_GridLine, (180, 180, 180, 100), category=dpg.mvThemeCat_Nodes) 141 | 142 | dpg.bind_theme(theme_id) 143 | -------------------------------------------------------------------------------- /main.py: -------------------------------------------------------------------------------- 1 | from BookBuilder import Grower 2 | from gui import Gui 3 | from settings import Settings 4 | 5 | if __name__ == '__main__': 6 | settings = Settings() 7 | grower = Grower() 8 | Gui(settings, grower).create() 9 | -------------------------------------------------------------------------------- /requirements.txt: -------------------------------------------------------------------------------- 1 | addict==2.4.0 2 | chess==1.9.2 3 | numpy==1.23.1 4 | pyparsing==3.0.9 5 | PyYAML==6.0 6 | requests==2.28.1 7 | scipy==1.8.1 8 | dearpygui==1.8.0 9 | psutil==5.9.4 10 | -------------------------------------------------------------------------------- /settings.py: -------------------------------------------------------------------------------- 1 | import io 2 | import logging 3 | import os 4 | import pickle 5 | from enum import Enum 6 | from typing import List 7 | 8 | import chess 9 | import chess.pgn 10 | import psutil 11 | 12 | 13 | class Order(Enum): 14 | LONG_TO_SHORT = "Long lines to short lines" 15 | SHORT_TO_LONG = "Short lines to long lines" 16 | 17 | 18 | class Book: 19 | def __init__(self, name: str, pgn: str): 20 | self.name = name 21 | self.pgn = pgn 22 | 23 | def __str__(self) -> str: 24 | return f"Name: {self.name}\nPGN: {self.pgn}" 25 | 26 | def is_valid_pgn(self) -> bool: 27 | if not self.pgn: 28 | return False 29 | 30 | # poor man's validation: if chess.pgn throws when parsing a PGN, the PGN is not valid 31 | game = chess.pgn.read_game(io.StringIO(self.pgn)) 32 | return len(game.errors) == 0 33 | 34 | 35 | class BookSettings: 36 | def __init__(self) -> None: 37 | self.order: Order = Order.SHORT_TO_LONG 38 | self.books_string: str = "Book A\n1. e4 e5\n\nBook B\n1. e4 e5 2. f4" 39 | 40 | def order_callback(self, _, order_value): 41 | self.order = Order(order_value) 42 | 43 | def books_string_callback(self, _, books_string): 44 | self.books_string = books_string 45 | 46 | def get_books(self) -> List[Book]: 47 | books = list() 48 | lines = self.books_string.splitlines() 49 | non_empty_lines = iter([line.strip() for line in lines if line and line.strip()]) 50 | for book_name in non_empty_lines: 51 | books.append(Book(book_name, next(non_empty_lines, None))) 52 | return books 53 | 54 | 55 | class Variant(Enum): 56 | STANDARD = "standard" 57 | CHESS960 = "chess960" 58 | CRAZYHOUSE = "crazyhouse" 59 | ANTICHESS = "antichess" 60 | ATOMIC = "atomic" 61 | HORDE = "horde" 62 | KING_OF_THE_HILL = "kingOfTheHill" 63 | RACING_KINGS = "racingKings" 64 | THREE_CHECK = "threeCheck" 65 | 66 | 67 | class Speed(Enum): 68 | ULTRA_BULLET = "ultraBullet" 69 | BULLET = "bullet" 70 | BLITZ = "blitz" 71 | RAPID = "rapid" 72 | CLASSICAL = "classical" 73 | CORRESPONDENCE = "correspondence" 74 | 75 | 76 | class Rating(Enum): 77 | ELO_1600 = "1600" 78 | ELO_1800 = "1800" 79 | ELO_2000 = "2000" 80 | ELO_2200 = "2200" 81 | ELO_2500 = "2500" 82 | 83 | 84 | class DatabaseSettings: 85 | def __init__(self): 86 | self.variant: Variant = Variant.STANDARD 87 | self.speeds: List[Speed] = [Speed.RAPID, Speed.CLASSICAL] 88 | self.ratings: List[Rating] = [Rating.ELO_1800, Rating.ELO_2000, Rating.ELO_2200] 89 | self.moves: int = 10 90 | 91 | def variant_callback(self, _, variant_name): 92 | self.variant = Variant[variant_name] 93 | 94 | def speed_callback(self, _, is_selected, speed_name): 95 | speed = Speed[speed_name] 96 | if is_selected: 97 | self.speeds.append(speed) 98 | else: 99 | self.speeds.remove(speed) 100 | 101 | def rating_callback(self, _, is_selected, rating_name): 102 | rating = Rating[rating_name] 103 | if is_selected: 104 | self.ratings.append(rating) 105 | else: 106 | self.ratings.remove(rating) 107 | 108 | def moves_callback(self, _, moves): 109 | if moves > 5: 110 | self.moves = moves 111 | 112 | 113 | class MoveSelectionSettings: 114 | def __init__(self): 115 | self.depth_likelihood: float = 0.01 116 | self.alpha: float = 0.001 117 | self.min_play_rate: float = 0.001 118 | self.min_games: int = 20 119 | self.continuation_games: int = 10 120 | self.draws_are_half: bool = False 121 | 122 | def depth_callback(self, _, depth): 123 | if depth >= 0: 124 | self.depth_likelihood = depth / 100 125 | 126 | def alpha_callback(self, _, alpha): 127 | if alpha >= 0: 128 | self.alpha = alpha / 100 129 | 130 | def min_play_rate_callback(self, _, min_play_rate): 131 | if min_play_rate >= 0: 132 | self.min_play_rate = min_play_rate / 100 133 | 134 | def min_games_callback(self, _, min_games): 135 | if min_games >= 0: 136 | self.min_games = min_games 137 | 138 | def continuation_games_callback(self, _, continuation_games): 139 | if continuation_games >= 0: 140 | self.continuation_games = continuation_games 141 | 142 | def draws_are_half_callback(self, _, draws_are_half): 143 | self.draws_are_half = draws_are_half 144 | 145 | 146 | class EngineSettings: 147 | NO_FILE_SELECTED = "No engine file selected" 148 | 149 | def __init__(self): 150 | self.enabled: bool = False 151 | self.path: str = self.NO_FILE_SELECTED 152 | self.finish: bool = True 153 | self.depth: int = 20 154 | self.threads: int = int(psutil.cpu_count(logical=True) / 2) # half of logical CPU cores 155 | self.hash: int = int(psutil.virtual_memory().available / 1024 / 1024 / 2) # half of available RAM 156 | self.soundness_limit: int = -99 157 | self.move_loss_limit: int = -99 158 | self.ignore_loss_limit: int = 300 159 | 160 | def enabled_callback(self, _, enabled): 161 | self.enabled = enabled 162 | 163 | def path_callback(self, file_selections): 164 | full_file_paths = list(file_selections['selections'].values()) 165 | # currently there is no way to force a single file selection in dearpygui 166 | # we grab the first selected file as a workaround 167 | self.path = full_file_paths[0] 168 | 169 | def finish_callback(self, _, finish): 170 | self.finish = finish 171 | 172 | def depth_callback(self, _, depth): 173 | if depth > 0: 174 | self.depth = depth 175 | 176 | def threads_callback(self, _, threads): 177 | if threads > 0: 178 | self.threads = threads 179 | 180 | def hash_callback(self, _, hash): 181 | if hash > 0: 182 | self.hash = hash 183 | 184 | def soundness_limit_callback(self, _, soundness_limit): 185 | self.soundness_limit = soundness_limit 186 | 187 | def move_loss_limit_callback(self, _, move_loss_limit): 188 | self.move_loss_limit = move_loss_limit 189 | 190 | def ignore_loss_limit_callback(self, _, ignore_loss_limit): 191 | self.ignore_loss_limit = ignore_loss_limit 192 | 193 | 194 | class Settings: 195 | _settings_file = 'settings.pickle' 196 | 197 | def __init__(self): 198 | self.book = BookSettings() 199 | self.database = DatabaseSettings() 200 | self.moveSelection = MoveSelectionSettings() 201 | self.engine = EngineSettings() 202 | self.load_from_file() 203 | 204 | def save_to_file(self): 205 | with open(self._settings_file, 'wb') as file: 206 | pickle.dump(self, file, protocol=pickle.HIGHEST_PROTOCOL) 207 | logging.info(f"Saved settings to {self._settings_file}") 208 | 209 | def load_from_file(self): 210 | if not os.path.exists(self._settings_file): 211 | logging.info(f"No settings file {self._settings_file} found, skipping loading settings") 212 | return 213 | 214 | with open(self._settings_file, 'rb') as file: 215 | from_file = pickle.load(file) 216 | 217 | self.book = from_file.book 218 | self.database = from_file.database 219 | self.moveSelection = from_file.moveSelection 220 | self.engine = from_file.engine 221 | logging.info(f"Loaded settings from {self._settings_file}") 222 | -------------------------------------------------------------------------------- /workerEngineReduce.py: -------------------------------------------------------------------------------- 1 | import chess.svg 2 | import requests 3 | import scipy.stats as st 4 | import numpy as np 5 | import time 6 | import copy 7 | 8 | import chess 9 | import chess.engine 10 | import re 11 | import logging 12 | 13 | 14 | class WorkerPlay: 15 | def __init__(self, settings, status, engine, fen): 16 | self.settings = settings 17 | self.status = status 18 | self.engine = engine 19 | self.fen = fen #fen is the game moves format needed to feed lichess api 20 | self.short_fen = fen[:-4] 21 | self.explored = False 22 | self.best_move = None 23 | 24 | self.board = chess.Board(fen) 25 | 26 | self.stats = self.call_api() 27 | self.parse_stats() 28 | 29 | #generate the Lichess API URL from config file 30 | def call_api(self): 31 | db = self.settings.database 32 | variant = db.variant.value 33 | speeds = [speed.value for speed in db.speeds] 34 | ratings = [rating.value for rating in db.ratings] 35 | moves = db.moves 36 | recentGames = 0 37 | topGames = 0 38 | play = "" 39 | 40 | url = 'https://explorer.lichess.ovh/lichess?' 41 | url += f'variant={variant}&' 42 | url += f'speeds={",".join(speeds)}&' 43 | url += f'ratings={",".join(ratings)}&' 44 | url += f'recentGames={recentGames}&' 45 | url += f'topGames={topGames}&' 46 | url += f'moves={moves}&' 47 | url += f'play={play}&' 48 | url += f'fen={self.fen}' 49 | 50 | self.status.info2(f"Looking for a move at FEN {self.fen}") 51 | self.opening_url = url 52 | #logging.debug(f"url of position {url}") #uncomment for debugging 53 | while True: 54 | r = requests.get(url) 55 | if r.status_code == 429: 56 | self.status.info2(f"Hit Lichess API rate limit, waiting for 60 seconds") 57 | print('Rate limited - waiting 60s...') 58 | time.sleep(60) 59 | else: 60 | response = r.json() 61 | break 62 | 63 | return response 64 | 65 | def parse_stats(self, move = None): #parse the stats returned by the API 66 | 67 | stats = self.stats #self.stats is what the api call returns 68 | stats['white_perc'], stats['black_perc'], stats['draw_perc'], stats['total_games'] = self.calc_percs(stats['white'], stats['black'], stats['draws']) # base rate?? sends the whiteWin / blackWin / draw / total games move was played numbers to calculate win percentages function, and define stats 69 | #print(stats) #uncomment for debugging 70 | for m in self.stats['moves']: 71 | m['white_perc'], m['black_perc'], m['draw_perc'], m['total_games'] = self.calc_percs(m['white'], m['black'], m['draws']) #each position iterate through all the moves to get win rate stats 72 | m['playrate'] = m['total_games'] / stats['total_games'] 73 | #print(m) #uncomment for debugging 74 | #TO DO call api for each move to get real percentages and total game numbers for transposition 75 | 76 | 77 | 78 | def pick_candidate(self): #how the next best move is picked 79 | 80 | moves = {} 81 | best_lb_value = -np.inf 82 | best_move = None 83 | for move in self.stats['moves']: #array of all moves returned from the API as next moves in a given position. 84 | if self.board.turn == chess.WHITE: #if it's white to play 85 | value, lb_value, ub_value, n = self.calc_value(move['white_perc'], move['total_games'], move['playrate'], move['san'], self.board) #sends move white win percentage and total games move was played to calculate 'potency' on confidence intervals 86 | for_printing= ''.join([str(i) for i in ["candidate move is ", move['san'], ' win rate is ', "{:+.2%}".format(move['white_perc']), ' playrate ', "{:+.2%}".format(move['playrate'])," lb value ", lb_value]]) 87 | logging.debug(for_printing) 88 | else: #if it's not white it's black to play 89 | value, lb_value, ub_value, n = self.calc_value(move['black_perc'], move['total_games'], move['playrate'], move['san'], self.board) #sends move black win percentage and total games move was played to calculate 'potency' on confidence intervals 90 | for_printing= ''.join([str(i) for i in ["candidate move is ", move['san'], ' win rate is ', "{:+.2%}".format(move['black_perc']), ' playrate' , "{:+.2%}".format(move['playrate']), " lb value ", lb_value]]) 91 | logging.debug(for_printing) 92 | key = move['san'] 93 | moves[key] = { 94 | 'value': value #raw winrate 95 | , 'lb_value': lb_value #lower bound potency value 96 | , 'ub_value': ub_value #upper bound potency value 97 | , 'n': n #total games played 98 | } 99 | lb_potencies = {k:v['lb_value'] for k,v in moves.items()} #makes a set of lb values from potential moves picked 100 | #print ('continuation options and winrates - ',lb_potencies)#prints list of continuations with lower bound winrates 101 | 102 | 103 | best_move = max(lb_potencies, key=lb_potencies.get) #best move is the move with the highest lower bound win rate (based on 95% confidence interval) 104 | potency = moves[best_move]['value'] #basic win rate 105 | lb_potency = moves[best_move]['lb_value'] 106 | ub_potency = moves[best_move]['ub_value'] 107 | n = moves[best_move]['n'] 108 | 109 | if self.settings.engine.enabled and (potency > 0): 110 | 111 | engineChecked = 0 112 | bestEval = None 113 | 114 | while engineChecked == 0: 115 | board = self.board 116 | 117 | lb_potencies = {k:v['lb_value'] for k,v in moves.items()} 118 | best_move = max(lb_potencies, key=lb_potencies.get) #best move is the move with the highest lower bound win rate (based on 95% confidence interval) 119 | potency = moves[best_move]['value'] #basic win rate 120 | lb_potency = moves[best_move]['lb_value'] 121 | ub_potency = moves[best_move]['ub_value'] 122 | n = moves[best_move]['n'] 123 | gamesPlayed = n 124 | 125 | if moves[best_move]['lb_value'] == 0: #if there is no best move candidate with a potency > 0 we dont ask engine, we go straight to return no best move 126 | engineChecked = 1 127 | print("no engine approved move found by statistics") 128 | 129 | else: #we ask engine for eval after move 130 | 131 | # if we don't already have the top engine move and eval 132 | if bestEval == None: 133 | 134 | #we ask engine for best move. If candidate move is best move, we approve, otherwise we calc difference. 135 | depth = self.settings.engine.depth 136 | self.status.info2(f"Looking for best engine move at '{board.fen()}', depth {depth}, this can take a while") 137 | logging.debug(f"engine working...") 138 | PlayResult = self.engine.play(board, chess.engine.Limit(depth=depth)) #we get the engine to play 139 | 140 | engineMoveSan = board.san(PlayResult.move) 141 | board.push(PlayResult.move) 142 | 143 | engineMoveBoard = copy.copy(board) 144 | board.pop () #undo engine move to keep board state 145 | 146 | 147 | #If candidate move is best move, we approve, otherwise we calc difference. 148 | san = best_move 149 | board.push_san(san) # push our candidate move 150 | ourMoveBoard = copy.copy(board) 151 | board.pop () #undo our move to keep board state 152 | 153 | 154 | logging.debug (f"engine move {engineMoveSan}") 155 | # logging.debug(engineMoveBoard) 156 | 157 | logging.debug (f"our candidate move {san}") 158 | # logging.debug(ourMoveBoard) 159 | 160 | #if our move is the top engine move, we just approve it. Bug note: We can get loss limit / soundness limit slip in some scenarios (eg if move goes out of soundness limits and engine can't see, but unlikely) 161 | if ourMoveBoard == engineMoveBoard: 162 | logging.debug("our move is top engine move so we approve") 163 | lb_value = max(0, potency - st.norm.ppf(1 - self.settings.moveSelection.alpha/2) * np.sqrt(potency * (1-potency) / gamesPlayed)) #lower bound wr at 95% confidence interval 164 | ub_value = max(0, potency + st.norm.ppf(1 - self.settings.moveSelection.alpha/2) * np.sqrt(potency * (1-potency) / gamesPlayed)) #upper bound wr at 165 | engineChecked = 1 166 | logging.debug(f"move is top engine move {san}") 167 | 168 | #if our move is not top engine move, we compare the CP after our move with the centipawns after engine move. Bug note: Not checking after opponent's response could cause slip in some scenarios (eg if move goes out of soundness limits and engine can't see, but unlikely) 169 | else: 170 | logging.debug (f"our move is not top engine move. engine working...") 171 | 172 | if bestEval == None: 173 | #we get engine move eval 174 | # engineMoveReply = engine.play(engineMoveBoard, chess.engine.Limit(depth=settings.engine.depth)) #we play one more move after engine move, to avoid slipping out of soundness limits 175 | # engineMoveBoard.push(engineMoveReply.move) 176 | depth = self.settings.engine.depth 177 | self.status.info2(f"Looking for best engine move at '{board.fen()}', depth {depth}, this can take a while") 178 | engineMoveScore = self.engine.analyse(engineMoveBoard, chess.engine.Limit(depth=depth)) #we get engine's eval from opponent's perspective 179 | 180 | #we convert the engine move score to a string so we can parse it 181 | engineMoveScoreString = str(engineMoveScore["score"]) 182 | logging.debug (f"Eval from perspective after Engine move {engineMoveSan} {engineMoveScore['score']}") 183 | 184 | #we switch to our perspective 185 | goodForThem = not ('-' in engineMoveScoreString) # check if it's good for them 186 | # print("good for them", goodForThem) 187 | mateForThem = (goodForThem) and ('Mate' in engineMoveScoreString) #if it's mate for us 188 | # print("mate for us", mateForUs) 189 | mateForUs = (not goodForThem) and ('Mate' in engineMoveScoreString) #if it's mate for them 190 | # print("mate for them", mateForThem) 191 | afterEngineMoveScore = [int(s) for s in re.findall(r'\b\d+\b',engineMoveScoreString)] 192 | afterEngineMoveScore = afterEngineMoveScore[0] 193 | # print("raw centipawn score", afterEngineReply) 194 | if goodForThem: 195 | afterEngineMoveScore = -afterEngineMoveScore 196 | if mateForThem: 197 | afterEngineMoveScore = -9999999999 198 | if mateForUs: 199 | afterEngineMoveScore = 9999999999 200 | 201 | 202 | bestEval = afterEngineMoveScore 203 | logging.debug (f"centipawn eval from our perspective after engine move {engineMoveSan} {bestEval}") 204 | 205 | if bestEval < self.settings.engine.soundness_limit: 206 | # engine checked = 1 leaves the checking loop and setting values to 0 triggers bookbuilder to finish with engine. 207 | logging.debug (f"failed best engine move {engineMoveSan} on soundness limit - we may have slipped outside soundness limit. We will check other moves, but maybe move selection this move is left to engine finishing if available. eval: {bestEval}") 208 | # potency = 0 209 | # lb_value = 0 210 | # ub_value = 0 211 | # n = 0 212 | # engineChecked = 1 213 | 214 | logging.debug (f"analysing our move eval. engine working...") 215 | #we get our move eval 216 | # ourMoveReply = engine.play(ourMoveBoard, chess.engine.Limit(depth=settings.engine.depth)) #we play one more move after our move 217 | # ourMoveBoard.push(ourMoveReply.move) 218 | depth = self.settings.engine.depth 219 | self.status.info2(f"Evaluating board after best human move, {ourMoveBoard.fen()}, depth {depth}, this can take a while") 220 | ourMoveScore = self.engine.analyse(ourMoveBoard, chess.engine.Limit(depth=depth)) #we get engine's eval from opponent's perspective 221 | 222 | logging.debug (f"Eval from perspective after our move {ourMoveScore['score']}") 223 | 224 | #we convert our move score to a string so we can parse it 225 | ourMoveScoreString = str(ourMoveScore["score"]) 226 | 227 | #we switch to our perspective 228 | goodForThem = not ('-' in ourMoveScoreString) # check if it's good for us 229 | # print("good for them", goodForThem) 230 | mateForThem = (goodForThem) and ('Mate' in ourMoveScoreString) #if it's mate for us 231 | # print("mate for us", mateForUs) 232 | mateForUs = (not goodForThem) and ('Mate' in ourMoveScoreString) #if it's mate for them 233 | # print("mate for them", mateForThem) 234 | afterOurMoveScore = [int(s) for s in re.findall(r'\b\d+\b',ourMoveScoreString)] 235 | afterOurMoveScore = afterOurMoveScore[0] 236 | # print("raw centipawn score", afterEngineReply) 237 | if goodForThem: 238 | afterOurMoveScore = -afterOurMoveScore 239 | if mateForThem: 240 | afterOurMoveScore = -9999999999 241 | if mateForUs: 242 | afterOurMoveScore = 9999999999 243 | logging.debug (f"centipawn eval from our perspective after our move {san} {afterOurMoveScore}") 244 | 245 | if (afterOurMoveScore == 9999999999): #if move is mate we give lb winrate as 1 and approve the move 246 | potency = 1 247 | lb_value = 1 248 | ub_value = 1 249 | engineChecked = 1 250 | logging.debug(f"move is approved - engine checked as mate {moves[san]}") 251 | 252 | 253 | #if not, we check it doesn't break soundness and move loss limits 254 | else: 255 | 256 | #we calculated the CP loss between best move and our move 257 | if bestEval >= afterOurMoveScore: 258 | moveLoss = afterOurMoveScore - bestEval 259 | logging.debug(f'moveloss implies our move worse than engine move') 260 | #sometimes the engine actually prefers the user move once there is a reply 261 | else: 262 | moveLoss = afterOurMoveScore - bestEval 263 | logging.debug(f'moveloss implies our move better than engine move') 264 | 265 | logging.debug(f'our move centipawns vs engine move {moveLoss}') 266 | 267 | #we approve the move if it meets soundness limits + loss limits, or passes our ignorelosslimit, or is evaluated stronger than top engine move after playing 268 | if ( (afterOurMoveScore > self.settings.engine.soundness_limit) and (moveLoss > self.settings.engine.move_loss_limit)) or (afterOurMoveScore > (self.settings.engine.ignore_loss_limit)) or (moveLoss >= 0): 269 | lb_value = max(0, potency - st.norm.ppf(1 - self.settings.moveSelection.alpha/2) * np.sqrt(potency * (1-potency) / gamesPlayed)) #lower bound wr at 95% confidence interval 270 | ub_value = max(0, potency + st.norm.ppf(1 - self.settings.moveSelection.alpha/2) * np.sqrt(potency * (1-potency) / gamesPlayed)) #upper bound wr at 271 | engineChecked = 1 272 | logging.debug([str(i) for i in ["move is engine checked and passes soundness + moveloss limits, passes the ignoreloss limit or is better than engine move", best_move, moves[san], "eval:", afterOurMoveScore, "loss:", moveLoss]]) 273 | 274 | else: 275 | 276 | logging.debug ([str(i) for i in ["engine failed move on soundness or move loss limits", best_move, moves[san], "eval:", afterOurMoveScore, "loss:", moveLoss]]) 277 | moves[san] = { 278 | 'value': 0 #raw winrate 279 | , 'lb_value': 0 #lower bound potency value 280 | , 'ub_value': 0 #upper bound potency value 281 | , 'n': n #total games played 282 | } 283 | 284 | logging.debug(f'best move is - {best_move} & win rate is - {potency} & lower bound win rate is - {lb_potency}') 285 | return moves, best_move, potency, (lb_potency, ub_potency), n 286 | 287 | def find_opponent_move(self, move): 288 | if move.uci() == 'e8g8': #Change the values for castling in Universal Chess Interface codes, can ignore 289 | move_uci = 'e8h8' 290 | elif move.uci() == 'e1g1': 291 | move_uci = 'e1h1' 292 | else: 293 | move_uci = move.uci() 294 | 295 | try: # find the odds of the pgn opponent move in the opening stats from the API. 296 | move_stats = next(item for item in self.stats['moves'] if item["uci"] == move_uci) #move stats is the next move in self stats moves which matches the move fed into function 297 | except: 298 | self.status.error(f"Failed to find move {move_uci} in the Opening Explorer API response", f"FEN: {self.fen}") 299 | raise Exception(f'Cannot find move {move_uci} in opening explorer API response') 300 | 301 | chance = move_stats['total_games'] / self.stats['total_games'] #total games for next move overf total games for current move 302 | #print("move opponent played =",move, " & percent chance of them playing it =", chance) #prints move opponent played from each position 303 | #print (move_stats) 304 | return move_stats, chance 305 | 306 | def find_move_tree(self): #how we return possible opponent continuations 307 | return self.stats['moves'] 308 | 309 | def find_potency(self): #how we return possible opponent continuations 310 | stats = self.stats 311 | stats['white_perc'], stats['black_perc'], stats['draw_perc'], stats['total_games'] = self.calc_percs(stats['white'], stats['black'], stats['draws']) 312 | if self.board.turn == chess.WHITE: #if we are white 313 | potency = stats['black_perc'] 314 | draws = stats['draw_perc'] 315 | else: 316 | potency = stats['white_perc'] 317 | draws = stats['draw_perc'] 318 | return potency, stats ['total_games'], draws 319 | 320 | # function to calculate percentage win rates for each colour, if more than 0 games 321 | def calc_percs(self, white, black, draws): 322 | n = white + black + draws # wins + draws after move was played 323 | 324 | if (n > 0) and not self.settings.moveSelection.draws_are_half: 325 | total_games = n 326 | white_perc = white / n 327 | black_perc = black / n 328 | draw_perc = draws / n 329 | return white_perc, black_perc, draw_perc, total_games 330 | else: 331 | if (n > 0) and self.settings.moveSelection.draws_are_half: 332 | total_games = n 333 | white_perc = (white + (0.5 * draws)) / n 334 | black_perc = (black + (0.5 * draws)) / n 335 | draw_perc = draws / n 336 | return white_perc, black_perc, draw_perc, total_games 337 | else: 338 | return None, None, None, 0 339 | 340 | # p = white/black win rate and n = total games p was played, this function calculates values used in the potentcy score of each potential move. It do 341 | def calc_value(self, winRate, gamesPlayed, playRate, san, board): 342 | 343 | if (gamesPlayed > self.settings.moveSelection.min_games) and ( 344 | playRate > self.settings.moveSelection.min_play_rate): # total games move was played must be more than min games and min perc play rate (otherwise data is bad) 345 | # print("check this", np.sqrt(winRate * (1-winRate) / gamesPlayed)) 346 | # print ("check this",st.norm.ppf(1 - settings.moveSelection.alpha/2)) 347 | # print ("check this",winRate - st.norm.ppf(1 - settings.moveSelection.alpha/2) * np.sqrt(winRate * (1-winRate) / gamesPlayed)) 348 | lb_value = max(0, winRate - st.norm.ppf(1 - self.settings.moveSelection.alpha / 2) * np.sqrt( 349 | winRate * (1 - winRate) / gamesPlayed)) # lower bound wr at 95% confidence interval 350 | ub_value = max(0, winRate + st.norm.ppf(1 - self.settings.moveSelection.alpha / 2) * np.sqrt( 351 | winRate * (1 - winRate) / gamesPlayed)) # upper bound wr at 352 | else: 353 | winRate = 0 354 | lb_value = 0 355 | ub_value = 0 356 | 357 | return winRate, lb_value, ub_value, gamesPlayed --------------------------------------------------------------------------------