def __init__(self, trigger): self.trigger = trigger self.name = trigger['name'] self.condition = datatypes.TriggerCondition(trigger['condition']) self.onAction = trigger['action'] self.repeat = int(trigger['repeat']) if trigger.has_key('repeat') else 0 if log.m(log.LEVEL_FILTERS): log.l('trigger initialized: ' + self.name)
def execute(self): """ executes the request and returns an answer according to the protocol @return: answer as JSON object """ if log.m(log.LEVEL_REQUESTS): log.l('executing request of type: ' + self.type) return None
def start(self): self.state = constants.CMD_STATE_STARTED if self.thread is not None and self.thread.state != constants.CMD_STATE_STARTED: #raise RuntimeError('the CommandThread of this task needs to be in CMD_STATE_STARTED-state to start child tasks!') return False if log.m(log.LEVEL_START_STOP_THREADS): log.l('<'+str(self.getThreadID())+'> starting ' + self.type) return True
def onChangeColor(self, newColor): if self.finishTrigger.isFalse(): self.finish() filteredColor = utils.interpolateColor(newColor, self.black, self.finishTrigger.progress()) if log.m(log.LEVEL_FILTER_ACTIONS): log.l(self.type+'-filter color ('+str(self.finishTrigger.progress()*100)+'%) from '+str(newColor)+' to '+str(filteredColor)) self.finishTrigger.step() return filteredColor
def run(self): if log.m(log.LEVEL_START_STOP_THREADS): log.l('<'+str(self.threadID)+'> starting Thread: ' + self.name) self.state = constants.CMD_STATE_STARTED self.task.start() self.stop() if log.m(log.LEVEL_START_STOP_THREADS): log.l('<'+str(self.threadID)+'> exiting:' + self.name)
def __init__(self, threadID, name): threading.Thread.__init__(self) self.threadID = threadID self.name = name self.daemon = True self.active = True self.triggers = {} self.mutex = threading.BoundedSemaphore() if log.m(log.LEVEL_TRIGGER): log.l('trigger manager initialized')
def run(self): l('stdin thread started') while True: line = sys.stdin.readline() self.q.put(line) l('stdin thread terminating')
def tt_init(size): global tt_size, tt_sub_size, tt l('Set TT size to %d entries ' % size) tt_size = size dummy_move = chess.Move(0, 0) tt = [[tt_element(None, None, None, -1, -1, None) for i in range(tt_sub_size)] for i in range(tt_size)]
def start(self): if super(Loop, self).start(): self.condition = datatypes.Condition(self.command['condition']) if log.m(log.LEVEL_COMMAND_DETAIL): log.l('<'+str(self.getThreadID())+'> starting loop with condition: ' + str(self.condition)) while self.isStarted(): for t in self.tasks: t.start() self.condition.step() self.stop()
def __init__(self, type, request): # takes a command as json encoded object """ initializes a new Request object @param type: type of the request (see protocol) @param request: JSON object with the request @return: instance of Request """ self.request = request self.type = type if log.m(log.LEVEL_REQUESTS): log.l('request received: ' + self.request)
def start(self): if super(Fade, self).start(): if self.command.has_key('start'): self.startColor = datatypes.Color(self.command['start']) self.endColor = datatypes.Color(self.command['end']) self.time = datatypes.Time(self.command['time']) if log.m(log.LEVEL_COMMAND_DETAIL): log.l('<'+str(self.getThreadID())+'> fading from '+str(self.startColor if self.startColor is not None else 'current color')+' to '+str(self.endColor)+' over ' + str(self.time) + ' seconds') corefunctions.fade(self, self.time.seconds, self.endColor, self.startColor) self.stop()
def finish(self): if self.onfinish == constants.FILTER_ONFINISH_REMOVE: server.CurrentFilters.remove(self) if self.onfinish == constants.FILTER_ONFINISH_STOP: if server.CurrentCMD is not None: server.CurrentCMD.stop() server.CurrentCMD = None server.CurrentFilters = [] if log.m(log.LEVEL_FILTER_ACTIONS): log.l(self.type+'-filter finished...')
def random_move(board): moves = board.get_move_list() idx = random.randint(0, len(moves) - 1) l('n moves: %d, chosen: %d = %s' % (len(moves), idx, moves[idx])) if not board.is_legal(moves[idx]): l('FAIL') return moves[idx]
def removeTrigger(self, name): exception = None self.mutex.acquire() try: self.triggers.pop(name) if log.m(log.LEVEL_TRIGGER): log.l('trigger removed with key=' + name) except: exception = StandardError(str(sys.exc_info()[0]) + ': '+str(sys.exc_info()[1])) self.mutex.release() if exception is not None: raise exception
def addTrigger(self, trigger): exception = None self.mutex.acquire() try: self.triggers[trigger.name] = trigger if log.m(log.LEVEL_TRIGGER): log.l('trigger added with key=' + trigger.name) except: exception = StandardError(str(sys.exc_info()[0]) + ': '+str(sys.exc_info()[1])) self.mutex.release() if exception is not None: raise exception
def calc_move_wrapper(board, duration, depth, is_ponder): global thread_result try: thread_result = calc_move(board, duration, depth, is_ponder) except Exception as ex: l(str(ex)) l(traceback.format_exc()) thread_result = None
def onChangeColor(self, newColor): if self.finishTrigger is not None and self.finishTrigger.isFalse(): self.finish() return newColor else: h, s, v = colorsys.rgb_to_hsv(newColor.red(), newColor.green(), newColor.blue()) r, g, b = colorsys.hsv_to_rgb(h, self.saturation, v) filteredColor = datatypes.Color(r, g, b) #utils.interpolateColor(newColor, self.black, self.finishTrigger.progress()) log.l(self.type+'-filter color from '+str(newColor)+' to '+str(filteredColor)) if self.finishTrigger is not None: self.finishTrigger.step() return filteredColor
def __init__(self, type, filter): # takes a filter type and a filter as json encoded object """ initializes a new Request object @param type: type of the request (see protocol) @param request: JSON object with the request @return: instance of Request """ self.active = True #TODO: not used yet self.filter = filter self.onfinish = filter['onfinish'] if filter.has_key('onfinish') else 'remove' self.type = type self.finishTrigger = self.finishTrigger = datatypes.Condition(filter['finish']) if filter.has_key('finish') else None if log.m(log.LEVEL_FILTERS): log.l('filter initialized: ' + self.type)
def setUpClass(cls): import sys,os sys.path.append(os.path.dirname(os.path.abspath(__file__)) + "/../../lib/utils") from log import Log as l l = l() cls.log = l.getLogger() cls.log.info("\n\nConf_test setUpClass finished.\n---------- start ---------")
def setUpClass(cls): sys.path.append( os.path.dirname(os.path.abspath(__file__)) + "/../../lib/utils") from log import Log as l cls.log = l().getLogger() cls.log.info( "\n\nIEEEXplore_test.setUpClass finished.\n---------- start ---------" )
def execute(self): super(RemoveRequest, self).execute() count = 0 if self.item == 'filter': i = 0 while i < len(server.CurrentFilters): if server.CurrentFilters[i].type == self.id: filter = server.CurrentFilters.pop(i) if log.m(log.LEVEL_FILTERS): log.l('removing ' + filter.type+' filter') count = count + 1 else: i += 1 if self.item == 'trigger': try: server.triggerManager.removeTrigger(self.id) count = 1 except: count = 0 answer = {"type":self.type, "item":self.item, "id":self.id, "count":count} return answer
def setUpClass(cls): sys.path.append( os.path.dirname(os.path.abspath(__file__)) + "/../../lib/utils") from log import Log as l cls.log = l().getLogger() sys.path.append( os.path.dirname(os.path.abspath(__file__)) + "/../../lib/db") import mysql_operator cls.db = mysql_operator.Mysql_operator() cls.log.info( "\n\nMySQL_test.setUpClass finished.\n---------- start ---------")
def start(self): if super(CC, self).start(): self.color = datatypes.Color(self.command['color']) if self.command.has_key('operator'): self.operator = self.command['operator'] if log.m(log.LEVEL_COMMAND_CC): log.l('<'+str(self.getThreadID())+'> color=' + str(led.COLOR[0]) + ' ' + self.operator + ' ' + str(self.color)) for i in range(0, len(config.LED_PINS)): if ((i + 1) & self.color.Address) != 0: newColor = led.COLOR[i] if self.operator == '*': newColor = newColor * self.color if self.operator == '/': newColor = newColor / self.color if self.operator == '+': newColor = newColor + self.color if self.operator == '-': newColor = newColor - self.color led.setColor(newColor) else: if log.m(log.LEVEL_COMMAND_CC): log.l('<'+str(self.getThreadID())+'> color=' + str(self.color)) led.setColor(self.color) self.stop()
def startServer(serverThread, var): global RUN if RUN == 0: RUN = 1 else: return #readcommands("socket thread", 0.01) thread.start_new_thread(server.readcommands, ("socket thread", var, )) time.sleep(1) log.l("'help' for commands\n\n", log.LEVEL_UI) while RUN: input = raw_input(">") if(input == 'exit'): if server.serversocket is not None: server.serversocket.close() server.RUN = 0 RUN = 0 server.triggerManager.stop() if server.CurrentCMD is not None: server.CurrentCMD.stop() server.CurrentCMD.join() server.CurrentCMD = None led.PIGPIO.stop() if(input == 'help'): help = "\n\nCommand list:" help = help + "\ncc r g b - change color" help = help + "\nclear - clears log" help = help + "\nexit - stops the server end kills process" log.l(help, log.LEVEL_UI) if input == 'clear': configure.cls() if input.startswith('cc'): try: args = input.split(' ') r = float(args[1]) g = float(args[2]) b = float(args[3]) led.changeColor(r, g, b) except: log.l('ERROR: ' + str(sys.exc_info()[0]) + ": "+ str(sys.exc_info()[1]), log.LEVEL_ERRORS)
def run(self): if log.m(log.LEVEL_TRIGGER): log.l('starting trigger manager...') while self.active: self.mutex.acquire() try: for k,v in self.triggers.items(): if v.isTrue(): v.action() except: if log.m(log.LEVEL_ERRORS): log.l('ERROR in trigger run method: ' + str(sys.exc_info()[0]) + ': '+str(sys.exc_info()[1])) self.mutex.release() time.sleep(config.DELAY) if log.m(log.LEVEL_TRIGGER): log.l('stopping trigger manager...')
def send(str_): print(str_) l('OUT: %s' % str_) sys.stdout.flush()
def start(self): if super(NOP, self).start(): if log.m(log.LEVEL_COMMAND_DETAIL): log.l('<'+str(self.getThreadID())+'> doing nothing') self.stop()
try: clientsocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) # clientsocket.connect(("192.168.1.150", 4321)) clientsocket.connect(("localhost", 4321)) cmdString = "" for s in range(2, len(sys.argv)): if len(cmdString) > 0: cmdString += " " cmdString += str(sys.argv[s]) print "sending command " + cmdString clientsocket.send(cmdString) clientsocket.close() except socket.error: log.l(str(sys.exc_info()[0]) + ": " + str(sys.exc_info()[1])) if len(sys.argv) >= 2 and sys.argv[1] == "test": try: clientsocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) # clientsocket.connect(("192.168.1.150", 4321)) if len(sys.argv) > 2: print "connecting to ", str.strip(sys.argv[2]) clientsocket.connect((str.strip(sys.argv[2]), 4321)) print "connected to ", str.strip(sys.argv[2]) else: print "connecting to localhost" clientsocket.connect(("localhost", 4321)) print "connected to localhost" cmdFile = None
def readcommands(threadName, intervall): #print the config parameters configure.cls() configure.printConfig() print '\n... starting server (',intervall,')...\n\n' #globals global ID global serversocket #create an INET, STREAMing socket serversocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) #bind the socket to a public host, # and a well-known port success = False while not success: try: log.l('trying to bind on port '+str(config.SERVER_PORT)+'...', log.LEVEL_UI) serversocket.bind(('', config.SERVER_PORT)) # socket.gethostname() # for getting own address success = True log.l('successfully bound server to port '+str(config.SERVER_PORT)+'...', log.LEVEL_UI) except: log.l('port is already in use. Trying to reconnect in 5 seconds', log.LEVEL_ERRORS) time.sleep(5) #become a server socket serversocket.listen(5) while RUN: try: (clientsocket, address) = serversocket.accept() global CurrentCMD global CurrentFilters global CommandHistory global CommandCount rcvString = '' clientsocket.setblocking(1) # recv() waits til data comes or timeout is reached clientsocket.settimeout(config.CONNECTION_TIMEOUT) # timeout for receiving and sending kilobyte = str(clientsocket.recv(1024)) try: while(kilobyte): rcvString += kilobyte try: json.loads(rcvString) kilobyte = None except: kilobyte = str(clientsocket.recv(1024)) except: pass #flag which is true if the received command comes from a http request isHTTPRequest = False mutex.acquire() try: answer = {} answer['error'] = [] if rcvString.startswith('GET') or rcvString.startswith('OPTIONS') or rcvString.startswith('POST') or rcvString.startswith('PUT'): isHTTPRequest = True indexOfLineBreak = rcvString.find('\n\n') if indexOfLineBreak < 0: indexOfLineBreak = rcvString.find('\r\n\r\n') rcvString = rcvString[indexOfLineBreak:] rcvString = urllib.unquote(rcvString) if log.m(log.LEVEL_SOCKET_COMMUNICATION): log.l('RECEIVED HTTP ('+str(rcvString)+'): '+rcvString+'\n\n') startIndex = rcvString.find('{') endIndex = rcvString.rfind('}') if startIndex >= 0 and endIndex >= 0: rcvString = rcvString[rcvString.find('{'):rcvString.rfind('}')+1] if log.m(log.LEVEL_SOCKET_COMMUNICATION): log.l('RECEIVED Command ('+str(len(rcvString))+'): '+rcvString+'\n\n') else: if log.m(log.LEVEL_SOCKET_COMMUNICATION): log.l('no valid command found in ('+str(len(rcvString))+'): '+rcvString+'\n\n') else: isHTTPRequest = False if log.m(log.LEVEL_SOCKET_COMMUNICATION): log.l('RECEIVED Command ('+str(len(rcvString))+'): '+rcvString+'\n\n') r = json.loads(rcvString) CommandCount += 1 CommandHistory.append(r) #limit command history to the last 10 commands (client request messages) if len(CommandHistory) > 10: CommandHistory = CommandHistory[len(CommandHistory)-10:len(CommandHistory)] # execute commands if isinstance(r, dict) and r.has_key('commands') and len(r['commands']) > 0: try: if log.m(log.LEVEL_COMMANDS): log.l( 'commands: '+ str(len(r['commands']))) if CurrentCMD is not None: CurrentCMD.stop() CurrentCMD.join() CurrentCMD = None ID = ID + 1 CurrentCMD = CommandThread(ID, 'command thread', r) CurrentFilters = [] answer['commands'] = 1 except: answer['error'].append('ERROR: ' + str(sys.exc_info()[0]) + ": "+ str(sys.exc_info()[1])) answer['commands'] = 0 log.l('ERROR: ' + str(sys.exc_info()[0]) + ": "+ str(sys.exc_info()[1]), log.LEVEL_ERRORS) #add new filters if a command is running if isinstance(r, dict) and r.has_key('filters') and len(r['filters']) > 0 and CurrentCMD is not None and CurrentCMD.state != constants.CMD_STATE_STOPPED: try: for f in r['filters']: CurrentFilters.append(filters.Filter.createFilter(f)) answer['filters'] = 1 except: answer['error'].append('ERROR: ' + str(sys.exc_info()[0]) + ": "+ str(sys.exc_info()[1])) answer['filters'] = 0 log.l('ERROR: ' + str(sys.exc_info()[0]) + ": "+ str(sys.exc_info()[1]), log.LEVEL_ERRORS) #answer request if isinstance(r, dict) and r.has_key('request'): try: req = requests.Request.createRequest(r['request']) answer['request'] = req.execute() except: answer['error'].append('ERROR: ' + str(sys.exc_info()[0]) + ": "+ str(sys.exc_info()[1])) answer['request'] = None log.l('ERROR: ' + str(sys.exc_info()[0]) + ": "+ str(sys.exc_info()[1]), log.LEVEL_ERRORS) #add new triggers if isinstance(r, dict) and r.has_key('triggers') and len(r['triggers']) > 0: try: for t in r['triggers']: triggerManager.addTrigger(trigger.Trigger(t)) answer['triggers'] = 1 except: answer['error'].append('ERROR: ' + str(sys.exc_info()[0]) + ": "+ str(sys.exc_info()[1])) answer['triggers'] = 0 log.l('ERROR: ' + str(sys.exc_info()[0]) + ": "+ str(sys.exc_info()[1]), log.LEVEL_ERRORS) #starting a new command if a new arrived and could be correctly decoded if answer.has_key('commands') and answer['commands'] == 1: CurrentCMD.start() if log.m(log.LEVEL_SOCKET_COMMUNICATION): log.l('---ANSWER---') log.l(str(answer)) except: log.l('ERROR: ' + str(sys.exc_info()[0]) + ": "+ str(sys.exc_info()[1]), log.LEVEL_ERRORS) answer['error'].append(str(sys.exc_info()[0]) + ": "+ str(sys.exc_info()[1])) #clientsocket.send(json.dumps(answer, separators=(',',':'))) mutex.release() if isHTTPRequest: answerString = json.dumps(answer, separators=(',',':')) httpResponse = 'HTTP/1.1 200 OK\n' httpResponse = httpResponse + 'Content-Type: application/json;charset=utf-8\n' httpResponse = httpResponse + 'Access-Control-Allow-Origin: *\n' httpResponse = httpResponse + 'Content-Length: '+str(len(answerString))+'\n\n' httpResponse = httpResponse + answerString clientsocket.send(httpResponse) log.l('answer sent (http response)', log.LEVEL_SOCKET_COMMUNICATION) else: clientsocket.send(json.dumps(answer, separators=(',',':'))) log.l('answer sent (normal socket)', log.LEVEL_SOCKET_COMMUNICATION) clientsocket.close() except: log.l('ERROR: ' + str(sys.exc_info()[0])+ ": "+ str(sys.exc_info()[1]), log.LEVEL_ERRORS)
def stop(self): if log.m(log.LEVEL_START_STOP_THREADS): log.l('<'+str(self.threadID)+'> stopping ' + self.name) self.state = constants.CMD_STATE_STOPPED self.task.stop()
def calc_move(board, max_think_time, max_depth, is_ponder): global to_flag to_flag = threading.Event() to_flag.clear() t = None if max_think_time: t = threading.Timer(max_think_time, set_to_flag, args=[to_flag]) t.start() reset_stats() tt_inc_age() l(board.fen()) if board.move_count() == 1 and not is_ponder: l('only 1 move possible') for m in board.get_move_list(): break return [0, m, 0, 0.0] result = None alpha = -infinite beta = infinite siblings = [] start_ts = time.time() for d in range(1, max_depth + 1): cur_result = search(board, alpha, beta, d, siblings, d, False) diff_ts = time.time() - start_ts if to_flag.is_set(): if result: result[3] = diff_ts break stats = get_stats() if cur_result[1]: diff_ts_ms = math.ceil(diff_ts * 1000.0) pv = tt_get_pv(board, cur_result[1]) msg = 'depth %d score cp %d time %d nodes %d pv %s' % ( d, cur_result[0], diff_ts_ms, stats['stats_node_count'], pv) if not is_ponder: print('info %s' % msg) sys.stdout.flush() l(msg) result = [cur_result[0], cur_result[1], d, diff_ts] if max_think_time and diff_ts > max_think_time / 2.0: break if cur_result[0] <= alpha: alpha = -infinite elif cur_result[0] >= beta: beta = infinite else: alpha = cur_result[0] - 50 if alpha < -infinite: alpha = -infinite beta = cur_result[0] + 50 if beta > infinite: beta = infinite #l('a: %d, b: %d' % (alpha, beta)) if t: t.cancel() l('valid moves: %s' % board.get_move_list()) if result == None or result[1] == None: l('random move!') l(board.get_stats()) result = [0, random_move(board), 0, time.time() - start_ts] l('selected move: %s' % result) diff_ts = time.time() - start_ts stats = get_stats() avg_bco = -1 if stats['stats_avg_bco_index_cnt']: avg_bco = float( stats['stats_avg_bco_index']) / stats['stats_avg_bco_index_cnt'] if stats['stats_tt_checks'] and diff_ts > 0: l('nps: %f, nodes: %d, tt_hits: %f%%, avg bco index: %.2f' % (stats['stats_node_count'] / diff_ts, stats['stats_node_count'], stats['stats_tt_hits'] * 100.0 / stats['stats_tt_checks'], avg_bco)) return result
# -*- coding: utf-8 -*- print("delete all ok? [y/n]") arg = input() import sys, os sys.path.append( os.path.dirname(os.path.abspath(__file__)) + "/../../lib/utils") from log import Log as l log = l().getLogger() sys.path.append(os.path.dirname(os.path.abspath(__file__)) + "/../../lib/db") import mysql_operator from table_papers import Table_papers from table_authors import Table_authors from table_citations import Table_citations from table_edges import Table_edges db = mysql_operator.Mysql_operator() if arg == "y": db.session.query(Table_papers).delete() db.session.query(Table_authors).delete() db.session.query(Table_citations).delete() db.session.query(Table_edges).delete() db.session.commit()
def stop(self): self.state = constants.CMD_STATE_STOPPED if log.m(log.LEVEL_START_STOP_THREADS): log.l('<'+str(self.getThreadID())+'> stopping ' + self.type)
log.l(help, log.LEVEL_UI) if input == 'clear': configure.cls() if input.startswith('cc'): try: args = input.split(' ') r = float(args[1]) g = float(args[2]) b = float(args[3]) led.changeColor(r, g, b) except: log.l('ERROR: ' + str(sys.exc_info()[0]) + ": "+ str(sys.exc_info()[1]), log.LEVEL_ERRORS) # starts server listening to commands: syntax: "./rgb.py server" try: if len(sys.argv)>1 and sys.argv[1] == "server": log.l("\nstarting server from console..." , log.LEVEL_UI) startServer('server thread', 0.01) except KeyboardInterrupt: if(len(sys.argv)>1 and sys.argv[1] == "server"): led.PIGPIO.stop() log.l("\nstopping server with errors..." , log.LEVEL_UI) else: if(len(sys.argv)>1 and sys.argv[1] == "server"): led.PIGPIO.stop() log.l("\nstopping server..." , log.LEVEL_UI)
# rgb-pi modules import datatypes import config import log import server import utils import mock GPIOMapping_BCM = [4, 17, 18, 21, 22, 23, 24, 25] PIGPIO = None try: import pigpio PIGPIO = pigpio.pi() # connect to local Pi log.l("starting pigpio...", log.LEVEL_UI) time.sleep(1) except ImportError: log.l("Error importing RPi.GPIO! This is probably because you need superuser privileges.", log.LEVEL_ERRORS) log.l("Mocking RPi.GPIO ...", log.LEVEL_ERRORS) PIGPIO = mock.PiGPIO_Mock.pi() # global rgb values COLOR = [ datatypes.Color("{x:000000}"), datatypes.Color("{x:000000}"), datatypes.Color("{x:000000}"), datatypes.Color("{x:000000}"), datatypes.Color("{x:000000}"), datatypes.Color("{x:000000}"),
def start(self): if super(Wait, self).start(): self.time = datatypes.Time(self.command['time']) if log.m(log.LEVEL_COMMAND_DETAIL): log.l('<'+str(self.getThreadID())+'> waiting for ' + str(self.time) + ' seconds') corefunctions.wait(self, self.time.seconds) self.stop()
def main(): t = threading.Thread(target=init_thread) t.start() try: sr = stdin_reader() sr.daemon = True sr.start() board = Board() while True: line = sr.get() if line == None: break line = line.rstrip('\n') if len(line) == 0: continue l('IN: %s' % line) parts = line.split(' ') if parts[0] == 'uci': send('id name Feeks') send('id author Folkert van Heusden <*****@*****.**>') send('uciok') elif parts[0] == 'isready': send('readyok') elif parts[0] == 'ucinewgame': board = Board() cm_thread_stop() elif parts[0] == 'auto': t = wait_init_thread(t) cm_thread_stop() tt = 1000 n_rnd = 4 if len(parts) == 2: tt = float(parts[1]) ab = Board() while not ab.is_checkmate(): if n_rnd > 0: m = random_move(ab) n_rnd -= 1 else: m = calc_move(ab, tt, 999999) m = m[1] if m == None: break ab.push(m) print(m) print('done') elif parts[0] == 'perft': cm_thread_stop() depth = 4 if len(parts) == 2: depth = int(parts[1]) start = time.time() total = 0 for m in board.get_move_list(): board.push(m) cnt = perft(board, depth - 1) board.pop() print('%s: %d' % (m.uci(), cnt)) total += cnt print('===========================') took = time.time() - start print('Total time (ms) : %d' % math.ceil(took * 1000.0)) print('Nodes searched : %d' % total) print('Nodes/second : %d' % math.floor(total / took)) elif parts[0] == 'position': is_moves = False nr = 1 while nr < len(parts): if is_moves: board.push_uci(parts[nr]) elif parts[nr] == 'fen': board = Board(' '.join(parts[nr + 1:nr + 7])) elif parts[nr] == 'startpos': board = Board() elif parts[nr] == 'moves': is_moves = True else: l('unknown: %s' % parts[nr]) nr += 1 elif parts[0] == 'go': t = wait_init_thread(t) if cm_thread_stop(): l('stop pondering') movetime = None depth = None wtime = btime = None winc = binc = 0 movestogo = None nr = 1 while nr < len(parts): if parts[nr] == 'wtime': wtime = int(parts[nr + 1]) nr += 1 elif parts[nr] == 'btime': btime = int(parts[nr + 1]) nr += 1 elif parts[nr] == 'winc': winc = int(parts[nr + 1]) nr += 1 elif parts[nr] == 'binc': binc = int(parts[nr + 1]) nr += 1 elif parts[nr] == 'movetime': movetime = int(parts[nr + 1]) nr += 1 elif parts[nr] == 'movestogo': movestogo = int(parts[nr + 1]) nr += 1 elif parts[nr] == 'depth': depth = int(parts[nr + 1]) nr += 1 else: l('unknown: %s' % parts[nr]) nr += 1 ### current_duration = movetime if current_duration: current_duration = float(current_duration) / 1000.0 elif wtime and btime: ms = wtime time_inc = winc if not board.turn: ms = btime time_inc = binc ms /= 1000.0 time_inc /= 1000.0 if movestogo == None: movestogo = 40 - board.fullmove_number while movestogo < 0: movestogo += 40 current_duration = (ms + movestogo * time_inc) / ( board.fullmove_number + 7) limit_duration = ms / 15.0 if current_duration > limit_duration: current_duration = limit_duration if current_duration == 0: current_duration = 0.001 l('mtg %d, ms %f, ti %f' % (movestogo, ms, time_inc)) ### if current_duration: l('search for %f seconds' % current_duration) if depth == None: depth = 999 cm_thread_start(board, current_duration, depth, False) line = None while cm_thread_check(): line = sr.get(0.01) if line: line = line.rstrip('\n') if line == 'stop' or line == 'quit': break result = cm_thread_stop() if line == 'quit': break if result and result[1]: send('bestmove %s' % result[1].uci()) board.push(result[1]) else: send('bestmove a1a1') if ponder and not board.is_game_over(): send('info string start pondering') cm_thread_start(board.copy(), is_ponder=True) elif parts[0] == 'quit': break elif parts[0] == 'fen': send('%s' % board.fen()) elif parts[0] == 'eval' or parts[0] == 'deval': moves = pc_to_list(board, []) depth = None if parts[0] == 'deval': t = wait_init_thread(t) depth = int(parts[1]) elif len(parts) == 2: check_move = chess.Move.from_uci(parts[1]) send('move\teval\tsort score') for m in moves: if not m.move == check_move: continue board.push(m.move) if depth: rc = calc_move(board, None, depth) v = rc[0] send('%s\t%d\t%d (%s)' % (m.move, v, m.score, rc[1])) else: v = evaluate(board) if board.turn == chess.BLACK: v = -v send('%s\t%d\t%d' % (m.move, v, m.score)) board.pop() elif parts[0] == 'moves': send('%s' % [m.uci() for m in board.get_move_list()]) elif parts[0] == 'smoves': moves = pc_to_list(board, []) send('%s' % [m.move.uci() for m in moves]) elif parts[0] == 'trymovedepth': t = wait_init_thread(t) board.push(chess.Move.from_uci(parts[1])) send('%s' % calc_move(board, None, int(parts[2]))) board.pop() elif parts[0] == 'probett': t = wait_init_thread(t) print(tt_lookup(board)) else: l('unknown: %s' % parts[0]) send('Unknown command') sys.stdout.flush() cm_thread_stop() except KeyboardInterrupt as ki: l('ctrl+c pressed') cm_thread_stop() except Exception as ex: l(str(ex)) l(traceback.format_exc())
def applyCommand(r): """ This method can be used from other scripts like triggers.py to apply commands to the server :param r: json object with command :return: None """ global ID global serversocket global CurrentCMD global CurrentFilters global CommandHistory global CommandCount answer = {} mutex.acquire() try: answer['error'] = [] CommandCount += 1 CommandHistory.append(r) #limit command history to the last 10 commands (client request messages) if len(CommandHistory) > 10: CommandHistory = CommandHistory[len(CommandHistory)-10:len(CommandHistory)] contains_cmd = False # execute commands if isinstance(r, dict) and r.has_key('commands') and len(r['commands']) > 0: try: if log.m(log.LEVEL_COMMANDS): log.l( 'commands: '+ str(len(r['commands']))) if CurrentCMD is not None: CurrentCMD.stop() CurrentCMD.join() CurrentCMD = None ID = ID + 1 CurrentCMD = CommandThread(ID, 'command thread', r) CurrentFilters = [] contains_cmd = True except: log.l('ERROR: ' + str(sys.exc_info()[0]) + ": "+ str(sys.exc_info()[1]), log.LEVEL_ERRORS) #add new filters if a command is running if isinstance(r, dict) and r.has_key('filters') and len(r['filters']) > 0 and CurrentCMD is not None and CurrentCMD.state != constants.CMD_STATE_STOPPED: try: for f in r['filters']: CurrentFilters.append(filters.Filter.createFilter(f)) except: log.l('ERROR: ' + str(sys.exc_info()[0]) + ": "+ str(sys.exc_info()[1]), log.LEVEL_ERRORS) #answer request if isinstance(r, dict) and r.has_key('request'): try: req = requests.Request.createRequest(r['request']) req.execute() except: log.l('ERROR: ' + str(sys.exc_info()[0]) + ": "+ str(sys.exc_info()[1]), log.LEVEL_ERRORS) #add new triggers if isinstance(r, dict) and r.has_key('triggers') and len(r['triggers']) > 0: try: for t in r['triggers']: triggerManager.addTrigger(trigger.Trigger(t)) except: log.l('ERROR: ' + str(sys.exc_info()[0]) + ": "+ str(sys.exc_info()[1]), log.LEVEL_ERRORS) #starting a new command if a new arrived and could be correctly decoded if contains_cmd: CurrentCMD.start() except: log.l('ERROR: ' + str(sys.exc_info()[0]) + ": "+ str(sys.exc_info()[1]), log.LEVEL_ERRORS) mutex.release() return answer
def stop(self): if log.m(log.LEVEL_COMMAND_DETAIL): log.l('<'+str(self.getThreadID())+'> stopping loop with condition: ' + str(self.condition)) for t in self.tasks: if t.state != constants.CMD_STATE_STOPPED: t.stop() super(Loop, self).stop()
def __init__(self, command, thread=None): # takes a command as json encoded object self.command = command self.thread = thread self.threadID = -1 self.state = constants.CMD_STATE_INIT if log.m(log.LEVEL_INIT_COMMAND): log.l('<'+str(self.getThreadID())+'> initialized: ' + self.type)
def search(board, alpha, beta, depth, siblings, max_depth, is_nm): global to_flag if to_flag.is_set(): return (-infinite, None) if board.is_checkmate(): return (-checkmate, None) if is_draw(board): return (0, None) if depth == 0: if with_qs: return (qs(board, alpha, beta), None) v = evaluate(board) return (-v if board.turn == chess.BLACK else v, None) top_of_tree = depth == max_depth global stats_node_count stats_node_count += 1 global stats_tt_checks stats_tt_checks += 1 tt_hit = tt_lookup_helper(board, alpha, beta, depth) if tt_hit: global stats_tt_hits stats_tt_hits += 1 if tt_hit[0]: return tt_hit[1] alpha_orig = alpha best = -infinite best_move = None ### NULL MOVE ### if not board.is_check() and depth >= 3 and not top_of_tree and not is_nm: board.push(chess.Move.null()) nm_result = search(board, -beta, -beta + 1, depth - 3, [], max_depth, True) board.pop() if -nm_result[0] >= beta: return (-nm_result[0], None) ################# moves_first = [] if tt_hit and tt_hit[1][1]: moves_first.append(tt_hit[1][1]) moves_first += siblings moves = pc_to_list(board, moves_first) new_siblings = [] is_check = board.is_check() allow_lmr = depth >= 3 and not is_check move_count = 0 for m_work in moves: m = m_work.move move_count += 1 new_depth = depth - 1 lmr = False if allow_lmr and move_count >= 4 and not board.is_capture( m) and not m.promotion: lmr = True new_depth -= 1 if move_count >= 6: new_depth -= 1 board.push(m) result = search(board, -beta, -alpha, new_depth, new_siblings, max_depth, False) score = -result[0] if score > alpha and lmr: result = search(board, -beta, -alpha, depth - 1, new_siblings, max_depth, False) score = -result[0] board.pop() if score > best: best = score best_move = m if not m in siblings: if len(siblings) == 2: del siblings[-1] siblings.insert(0, m) if score > alpha: alpha = score if score >= beta: global stats_avg_bco_index, stats_avg_bco_index_cnt stats_avg_bco_index += move_count - 1 stats_avg_bco_index_cnt += 1 break if move_count == 0: if not is_check: return (0, None) l('ERR') if alpha > alpha_orig and not to_flag.is_set(): bm = None if best >= alpha_orig: bm = best_move tt_store(board, alpha_orig, beta, best, bm, depth) return (best, best_move)
def set_to_flag(to_flag): to_flag.set() l("time is up")