def rounds (self, value): if not self.started: self.tk_rounds.set(0) Log("Not started.") else: self.__rounds = value self.tk_rounds.set(self.rounds) self.distance = self.rounds * CONFIG.distance self.tk_distance.set(self.distance) Log(f"Elapsed Time: {self.elapsed_time}") t = list(map(int, self.elapsed_time.split(':'))) self.pace = self.calc_pace(distance=self.distance, minutes=t[0]*60+t[1], seconds=t[2]) now = datetime.now() d = (str(now-self.starttime_round).split('.', 2)[0]).split(':') self.round_time = f"{d[1]}:{d[2]}" self.tk_round_time.set(self.round_time) self.starttime_round = now t = list(map(int, self.round_time.split(':'))) self.pace_round = self.calc_pace(distance=CONFIG.distance, minutes=t[0], seconds=t[1]) Log(f"Round #{self.rounds}")
def toggle(): if timer.status != 0: timer.off() Log("Manually switched off by button") else: timer.on() Log("Manually switched on by button")
def shutdown_application(): """called on shutdown; stops all threads""" Log("Stopping application.") flask_server.shutdown() radio.stop() Log("Application stopped.") sys.exit(0)
def process (self): import rrdtool data_complete = True rrd_template = "" rrd_data = "N:" for p in PIs: if not self.data[p]: data_complete = False else: rrd_template += self.DS[p][DS_TEMP1] + ":" + \ self.DS[p][DS_TEMP2] + ":" + \ self.DS[p][DS_TCPU] + ":" + \ self.DS[p][DS_HUMI] + ":" + \ self.DS[p][DS_PRESS] + ":" + \ self.DS[p][DS_AIRQ] + ":" rrd_data += self.data[p].split("N:")[1].rstrip() + ":" if data_complete: rrd_template = rrd_template.rstrip(":") rrd_data = rrd_data.rstrip(":") try: Log(f"Update RRD database: {rrd_data}") rrdtool.update(RRDFILE, "--template", rrd_template, rrd_data) except rrdtool.OperationalError: Log("Cannot update rrd database: {0[0]} {0[1]}".format(sys.exc_info()))
def count(self, Y, X, **kwargs): prediction = kwargs.get('prediction', 1) epochs = kwargs.get('epochs', 1) logging = kwargs.get('logging', False) learning = kwargs.get('learning', True) log = Log(logging, "MLPGD.count()") log.message("start") yr = Y #muw = 0.05 #muv = 0.01 muv = 0.005 N = len(Y) n1 = 400 nx = len(X) * 4 + 1 nv = 1 + n1 nxi = nv if len(self.w) < 1: self.w = randn( n1, nx ) / nx if len(self.v) < 1: self.v = randn( nv ) / nv e = zeros( N ) y = Y.copy() #x = ones( nx ) xi = ones( nxi ) dxidny = zeros ( n1 + 1 ) dydv = zeros(( N, nv )) dydw = zeros( ( N, nx, n1 ) ) SSE = zeros( epochs ) for epoch in range( epochs ): for k in range ( N - prediction): #input vector x = [1.] for i in range(len(X)): x = concatenate((x, [ X[i][k], X[i][k-1], X[i][k-2], X[i][k-3] ])) ny = dot( self.w, x ) xi[1:] = self.phi(ny) y[ k + prediction ] = dot( self.v, xi ) e[ k ] = yr[ k ] - y[ k ] #weights of output neuron dydv[k, :] = xi dv = muv/(1+sum(xi**2))*e[k]*dydv[k] # normalized GD if learning: self.v = self.v + dv return y
def log_gps(self): Log(f"GPS: time: {self.gps.data_stream.time}; lat: {self.gps.data_stream.lat}; " + f"lon: {self.gps.data_stream.lon}; alt: {self.gps.data_stream.alt}; " + f"speed: {self.gps.data_stream.speed}") Log(f"URL: https://maps.google.at/maps?q=loc:{self.gps.data_stream.lat},{self.gps.data_stream.lon}" )
def addFiles(self, path, recursive): #uses path to load a bunch of mutagen clusters keyed by shared directory. justfiles = [] #the path could be a file or a directory if os.path.isfile(path): justfiles.append(path) else: files = glob.glob(path + '/**/*.*', recursive=recursive) justfiles = [f for f in files if isfile(f)] for file in justfiles: filepath = os.path.dirname(file) #audio = FLAC(file) audio = mutagen.File(file) if audio is not None: afile = AudioFile(audio) #print(filepath) if filepath in self.clusters: #print('E-' + file) self.clusters[filepath].addFile(afile) else: #print('A-' + file) self.clusters[filepath] = Cluster() self.clusters[filepath].addFile(afile) else: Log.writeInfo('bad file: ' + file)
def start (self): while True: payload = self.udp.receive() Log(f"RRD Data received: {payload}") (source, values) = payload.split(',') self.data[source] = values # data['particulates_2'] = "2_pm25:2_pm10:N:11.1:5.5" data_complete = True rrd_template = "" rrd_data = "N:" for p in self.Particulates: if not self.data[p]: data_complete = False else: try: rrd_template += self.data[p].split(":N:")[0] + ":" rrd_data += self.data[p].split(":N:")[1] + ":" except IndexError: Log("Wrong data format: {0[0]} {0[1]}".format(sys.exc_info())) Log(f"data[p]: {data[p]}") data_complete = False if data_complete: rrd_template = rrd_template.rstrip(":") rrd_data = rrd_data.rstrip(":") try: # Log(f"Updating rrd: {rrd_template}, {rrd_data}") import rrdtool rrdtool.update(RRDFILE, "--template", rrd_template, rrd_data) except rrdtool.OperationalError: Log("Cannot update rrd database: {0[0]} {0[1]}".format(sys.exc_info()))
def shutdown_application(): """cleanup stuff""" Log("Stopping application") sds011_1.close() sds011_2.close() Log("Application stopped") sys.exit(0)
def count(self, Y, X, **kwargs): prediction = kwargs.get('prediction', 1) epochs = kwargs.get('epochs', 1) logging = kwargs.get('logging', False) learning = kwargs.get('learning', True) log = Log(logging, "MLPGD.count()") log.message("start") yr = Y #muw = 0.05 #muv = 0.01 muv = 0.005 N = len(Y) n1 = 400 nx = len(X) * 4 + 1 nv = 1 + n1 nxi = nv if len(self.w) < 1: self.w = randn(n1, nx) / nx if len(self.v) < 1: self.v = randn(nv) / nv e = zeros(N) y = Y.copy() #x = ones( nx ) xi = ones(nxi) dxidny = zeros(n1 + 1) dydv = zeros((N, nv)) dydw = zeros((N, nx, n1)) SSE = zeros(epochs) for epoch in range(epochs): for k in range(N - prediction): #input vector x = [1.] for i in range(len(X)): x = concatenate( (x, [X[i][k], X[i][k - 1], X[i][k - 2], X[i][k - 3]])) ny = dot(self.w, x) xi[1:] = self.phi(ny) y[k + prediction] = dot(self.v, xi) e[k] = yr[k] - y[k] #weights of output neuron dydv[k, :] = xi dv = muv / (1 + sum(xi**2)) * e[k] * dydv[k] # normalized GD if learning: self.v = self.v + dv return y
def shutdown_application(): """cleanup stuff""" Log("Stopping application") # TODO: bme680.shutdown() while calculating baseline sensors.stop() sensors.join() Log("Application stopped") sys.exit(0)
def shutdown_application(): """called on shutdown; stops all threads""" Log("Stopping application.") pictures.stop() pictures.join() deliver.join() # stopping itself due to QSTOP Log("Application stopped.") sys.exit(0)
def call_url (request): Log(f"Request: {request}") try: urlopen(request, timeout=2) except (HTTPError, URLError): Log("HTTPError, URLError: {0[0]} {0[1]}".format(sys.exc_info())) except socket.timeout: Log("socket.timeout: {0[0]} {0[1]}".format(sys.exc_info()))
def addEdge(self, start_node, letter, destination_node): edge = [letter, destination_node] if edge not in self.edges[start_node]: self.edges[start_node].append(edge) else: Log.warning( f'Treid to add an already existing edge to the node {start_node}' )
def shutdown_application(): """cleanup stuff""" Log("Stopping application") inp.close() led1.close() led2.close() Log("Application stopped") sys.exit(0)
def set_counter (self, value): try: value = int(value) except ValueError: Log(f"Value '{value}' is not an integer.") else: statistics.rounds = value Log(f"Manually set counter to {value}.")
def shutdown_application (): """cleanup stuff""" Log("Stopping application") to_rrd.stop() to_rrd.join() udp.stop() udp.join() Log("Application stopped") sys.exit(0)
def CallPilixControl(param): Log("CallPilixControl: {}".format(param)) try: with urlopen(CONFIG.API.url.format(param)) as response: data = response.read().decode("utf-8") except IOError: Log("Error: {0[0]} {0[1]}".format(sys.exc_info())) except socket.timeout: Log("socket.timeout: {0[0]} {0[1]}".format(sys.exc_info()))
def shutdown(): """shuts down the OS""" Log("Shutting down in 5 s ...") stop_threads() display.print("Shutting down in 5 s ...") time.sleep(5) display.off() Log("Shutdown now") subprocess.run(["sudo", "shutdown", "-h", "now"])
def send(self, data): datagram = "{},no digest available here".format(data).encode('utf-8') try: sent = self.socket.sendto(datagram, (self.IP_ADDRESS_SERVER, self.UDP_PORT)) Log("Sent bytes: {}; data: {}".format(sent, datagram)) except: Log("Cannot send data: {0[0]} {0[1]} (Data: {1})".format( sys.exc_info(), datagram))
def shutdown_application(): """cleanup stuff""" Log("Stopping application") control_input.stop() control_input.join() control_output.stop() control_output.join() Log("Application stopped") sys.exit(0)
def toggle (self): if Touchevent.event(): # brightness control Sound.play(CONFIG.CLICK_SOUND) try: urlopen(CONFIG.URL_ANTEROOM_CONTROL, timeout=2) except (HTTPError, URLError): Log("HTTPError, URLError: {0[0]} {0[1]}".format(sys.exc_info())) except socket.timeout: Log("socket.timeout: {0[0]} {0[1]}".format(sys.exc_info()))
def shutdown_application(): """cleanup stuff""" Log("Stopping application") storedata.stop() storedata.join() sensor.stop() sensor.join() Log("Application stopped") sys.exit(0)
def CallToggle(): try: response = urllib.urlopen(url) data = response.read().decode("utf-8") Log("toggled!") except (IOError): Log("Error: {0[0]} {0[1]}".format(sys.exc_info())) except socket.timeout: Log("socket.timeout: {0[0]} {0[1]}".format(sys.exc_info()))
def run(self): while True: data = self.udp.receive() Log(f"RRD Data received: {data}") try: rrdtool.update(RRDFILE, "--template", self.rrd_template, data) except rrdtool.OperationalError: Log("Cannot update rrd database: {0[0]} {0[1]}".format( sys.exc_info()))
def send(self, datagram): try: Log("Sending bytes (UDP): {}".format(datagram)) sent = self.socket.sendto(datagram, (CONFIG.Livetracking.IP_ADDRESS_SERVER, CONFIG.Livetracking.UDP_PORT)) Log("Sent bytes (UDP): {}; data: {}".format(sent, datagram)) except: Log("Cannot send data (UDP): {0[0]} {0[1]}".format(sys.exc_info()))
def shutdown(): """shuts down the OS""" import subprocess Log("Shutting down in 5 s ...") Log("Stopping application") r.stop() Log("Application stopped") time.sleep(5) Log("Shutdown now") subprocess.run(["sudo", "shutdown", "-h", "now"])
def device_login(cls, did): uid = cls.did_to_uid(did) is_new = False if uid is None: uid = cls.create_user(did, cls.DID2UID) is_new = True Log.info("create user by did: uid=%d" % uid) return (uid, is_new)
def send(self, data): payload = data datagram = "{},{}".format(payload, self.digest(payload)).encode('utf-8') try: sent = self.socket.sendto( datagram, (CONFIG.IP_ADDRESS_SERVER, CONFIG.UDP_PORT)) Log("Sent bytes: {}; data: {}".format(sent, datagram)) except: Log("Cannot send data: {0[0]} {0[1]}".format(sys.exc_info()))
def SendRelaisStatus(status): url_ = url.format(status) try: response = urllib.urlopen(url_) data = response.read().decode("utf-8") except (IOError): Log("Error: {0[0]} {0[1]}".format(sys.exc_info())) except socket.timeout: Log("socket.timeout: {0[0]} {0[1]}".format(sys.exc_info()))
def ReadJsonURL_cached(url): try: with urlopen(url, timeout=15) as response: data = AttrDict(json.loads(response.read().decode("utf-8"))[1]) except (HTTPError, URLError): Log("HTTPError, URLError: {0[0]} {0[1]}".format(sys.exc_info())) except socket.timeout: Log("socket.timeout: {0[0]} {0[1]}".format(sys.exc_info())) else: pass
def countSerie(self, Y, X, **kwargs): # optional parameters prediction = kwargs.get('prediction', 1) mu = kwargs.get('mu', 0.9) self.w = kwargs.get('weigths', self.w) logging = kwargs.get('logging', False) log = Log(logging, "MLP.phiCell()") log.message("start") N=len(Y) # X.shape[0] e=zeros(N) yn=Y.copy() # init output neuronu (site) nx = len(X) * 3 + 1 #lenX * X width + 1 nw=(nx*nx+nx)/2 if len(self.w) < 1: self.w = random.randn(nw)/nw x=[] colx=[] J=zeros((N,nw)) I=eye(nw) # for record MSE = [] #mean squer error for k in range(N-prediction): #input vector x = [1.] for i in range(len(X)): x = concatenate((x, [ X[i][k], X[i][k-1] , X[i][k-2]]))#, X[i][k-3], X[i][k-4], X[i][k-5] ])) colx = [] for i in range(nx): for j in range(i,nx): colx.append(x[i]*x[j]) yn[k+prediction]=dot(self.w,colx) e[k]=Y[k]-yn[k] dydw=colx # for QNU and HONU (Higher Order Neural Units) J[k,:]=dydw print "___" print len(dot(linalg.inv(dot(J.T,J)+1.0/mu*I),J.T)) print len(e) print len(inv(dot(J.T,J)+1./mu*I)) dw=dot(dot(linalg.inv(dot(J.T,J)+1.0/mu*I),J.T),e) self.w=self.w+dw MSE.append(sum(e**2)/N) return yn, self.w, MSE, e
def countSerie(self, Y, X, **kwargs): # optional parameters prediction = kwargs.get('prediction', 1) mu = kwargs.get('mu', 0.9) self.w = kwargs.get('weigths', self.w) logging = kwargs.get('logging', False) log = Log(logging, "MLP.phiCell()") log.message("start") N = len(Y) # X.shape[0] e = zeros(N) yn = Y.copy() # init output neuronu (site) nx = len(X) * 3 + 1 #lenX * X width + 1 nw = (nx * nx + nx) / 2 if len(self.w) < 1: self.w = random.randn(nw) / nw x = [] colx = [] J = zeros((N, nw)) I = eye(nw) # for record MSE = [] #mean squer error for k in range(N - prediction): #input vector x = [1.] for i in range(len(X)): x = concatenate( (x, [X[i][k], X[i][k - 1], X[i][k - 2]])) #, X[i][k-3], X[i][k-4], X[i][k-5] ])) colx = [] for i in range(nx): for j in range(i, nx): colx.append(x[i] * x[j]) yn[k + prediction] = dot(self.w, colx) e[k] = Y[k] - yn[k] dydw = colx # for QNU and HONU (Higher Order Neural Units) J[k, :] = dydw print "___" print len(dot(linalg.inv(dot(J.T, J) + 1.0 / mu * I), J.T)) print len(e) print len(inv(dot(J.T, J) + 1. / mu * I)) dw = dot(dot(linalg.inv(dot(J.T, J) + 1.0 / mu * I), J.T), e) self.w = self.w + dw MSE.append(sum(e**2) / N) return yn, self.w, MSE, e
def checkPara(para, in_list): for i in in_list: if isinstance(i, tuple): (k, func) = i if not (k in para and func(para[k])): Log.error("param error:" + k) return False elif i not in para: Log.error("param not exist:" + i) return False return True
def getLevelRange(self, range_id): if range_id > len(self.LV_RANGE): Log.error('range_id exceeded') return False r = range_id - 1 start = 1 end = self.LV_RANGE[r] if r > 0: start = self.LV_RANGE[r-1] + 1 return {'start':start, 'end':end}
def isEnd(self, total_time): now = int(time.time()) if now < self.start_time: Log.error('tournament start time error(<now)') return True offset = 5 if now - self.start_time >= total_time - offset: return True else: return False
def getUniformCircularLBPImgFAST(self): l = Log() self.hist = [] transformed_img = np.zeros((self.height,self.width)) for p in self.pixels: x=p[0] y=p[1] center = self.img[x,y] pixels = [] for point in range(1, self.P + 1): r = x + self.R * math.cos(2 * math.pi * point / self.P) c = y - self.R * math.sin(2 * math.pi * point / self.P) if r < 0 or c < 0: pixels.append(0) continue if int(r) == r: if int(c) != c: c1 = int(c) c2 = math.ceil(c) w1 = (c2 - c) / (c2 - c1) w2 = (c - c1) / (c2 - c1) pixels.append(int((w1 * self.get_pixel_else_0(self.img, int(r), int(c)) + \ w2 * self.get_pixel_else_0(self.img, int(r), math.ceil(c))) / (w1 + w2))) else: pixels.append(self.get_pixel_else_0(self.img, int(r), int(c))) elif int(c) == c: r1 = int(r) r2 = math.ceil(r) w1 = (r2 - r) / (r2 - r1) w2 = (r - r1) / (r2 - r1) pixels.append((w1 * self.get_pixel_else_0(self.img, int(r), int(c)) + \ w2 * self.get_pixel_else_0(self.img, math.ceil(r), int(c))) / (w1 + w2)) else: pixels.append(self.bilinear_interpolation(r, c, self.img)) values = self.thresholded(center, pixels) res = self.lblDict[tuple(values)]#self.find_variations(values) ''' if variations: res = 0 for a in range(0, len(values)): res += values[a] * 2 ** a transformed_img.itemset((x,y), res) self.hist.append(res) ''' if res > -1: transformed_img.itemset((x,y), res) self.hist.append(res) l.printLog('Duration UniformCircularLBP:') return transformed_img, self.hist
def reward(self, base_prize): self.is_rewarding = 1 for range_id in range(1, len(self.LV_RANGE) + 1): k = self.getRangePrizeKey(range_id) prize = self.get(k) pool = 0 if prize: pool = base_prize + int(prize) player_num = self.getPlayerNum(range_id) max_win_player = max(1, int(player_num * Config.WIN_PRIZE_RATE)) total_w = 0 total_n = 0 for (n, w) in Config.PRIZE: if total_n >= max_win_player: break total_n += n total_w += n * w win_player_list = self.getTopPlayer(range_id, total_n) rank = 1 for (n, w) in Config.PRIZE: for i in range(n): if win_player_list: uid = win_player_list.pop(0) prize = int((w * 1.0 / total_w) * pool) tid = self.key_ #TODO: skip robots if 563<= int(uid) <= 662: continue User(uid).coin += prize Log.debug('reward uid=%s, rank=%d, prize=%d' % (uid, rank, prize)) UserRewardLog.create(uid, tid, rank, prize) # notify Notice(uid).push({'type':Notice.TYPE_TOURNAMENT, 'rank': rank, 'tid': tid, 'prize': prize, 'time': int(time.time())}) rank += 1 data = {'tournament_prize': prize} Stat().incr(data)
def consume(self): now = self.left - 1 if now < 0: Log.error("not enough spin") return False ret = (self.lines, self.bet) if now == 0: self.remove() else: self.left = now return ret
def load_line(self, line): self.lineno += 1 s = line.strip() if s == "" or s[0] == "#": return s = Reg.spaces.split(s) try: fn = getattr(self,'cfg_'+s[0]) except AttributeError as e: Log.xerr('config syntax: {0}:{1}: {3} {4}: {2}', self.name, self.lineno, line, type(e), e) return try: fn(*s[1:]) except Exception as e: Log.xerr('config error: {0}:{1}: {3} {4}: {2}', self.name, self.lineno, line, type(e), e) return
def train(self, Y_train, X_train, **kwargs): prediction = kwargs.get('prediction', 1) logging = kwargs.get('logging', False) log = Log(logging, "RBF.train()") log.message("start") self.W = [] self.Y = [] # every row is RBF neuron center for k in range(len(X_train[0])): self.W.append([]) for i in range(len(X_train)): l = k - prediction self.W[k].append([ X_train[i][l] ]) #, X_train[i][l-1], X_train[i][l-2], X_train[i][l-3], X_train[i][l-4] ]) self.Y.append(Y_train[k]) log.message("done \n")
def train(self, Y_train, X_train, **kwargs): prediction = kwargs.get('prediction', 1) epochs = kwargs.get('epochs', 1) logging = kwargs.get('logging', False) log = Log(logging, "QNU.train()") log.message("start") Wall = [] MSE = [] # Training for epoch in range(epochs): yn, w, MSE0, e = self.countSerie(Y_train, X_train, prediction = prediction) Wall.append(w) MSE.append(MSE0) log.message("done \n") return yn, w, e, Wall, MSE
def cfg_host(self, nameport, *args): np = Tool.hostport(nameport, Defaults.PORT) name = np[0] port = len(np)>1 and Tool.intval(np[1]) or _PORT pw = len(np)>2 and np[2] or '' sa = socket.getaddrinfo(name, port) if not sa: Log.err("cannot resolve %s",name) return for a in sa: if a[0] != socket.AF_INET and a[0] != socket.AF_INET6: Log.warn("wrong family {0} for {1}", Tool.sockfam(a[0]), name) continue if a[1] != socket.SOCK_DGRAM: Log.info("ignore type {0} for {1}", Tool.socktype(a[1]), name) continue if a[2] != socket.IPPROTO_UDP: Log.info("ignore proto {0} for {1}", Tool.sockproto(a[2]), name) continue Log.info("host {0}: {2} {1}", name, a[4], Tool.sockfam(a[0])) self.target.add(a[0], a[4], pw)
def fb_login(cls, did, fbid, fb_name, frd_list): uid = cls.fbid_to_uid(fbid) is_new = False if uid is None: uid = cls.did_to_uid(did) # create new account if device already binded to a fb id if uid is None or cls.did_to_fbid(did) is not None: uid = cls.create_user(fbid, cls.FBID2UID) is_new = True Log.info("create user by fb: uid=%d" % uid) else: # clear device id map to enable new login by did? Redis().hset(cls.FBID2UID, fbid, uid) Redis().hset(cls.DID2FBID, did, fbid) Log.info("move user to fb map: uid=%d" % uid) #update info user = User(uid) user.setName(fb_name) if not user.fbid: #import friends for 1st time uid_list = [] for f in frd_list: u = cls.fbid_to_uid(f) if u is not None: uid_list.append(u) if len(uid_list) > 0: Social.importFriends(uid, uid_list) user.fbid = fbid return (uid, is_new)
def getBasicLBPImgFAST(self): l = Log() transformed_img = np.zeros((self.height,self.width)) for p in self.pixels: y = p[0] x = p[1] try: center = self.img[y,x] top_left = 1 if self.img[y-1,x-1] < center else 0 top_up = 2 if self.img[y,x-1] < center else 0 top_right = 4 if self.img[y+1,x-1] < center else 0 right = 8 if self.img[y+1,x] < center else 0 left = 16 if self.img[y-1,x] < center else 0 bottom_left = 32 if self.img[y-1,x+1] < center else 0 bottom_right = 64 if self.img[y+1,x+1] < center else 0 bottom_down = 128 if self.img[y,x+1] < center else 0 res = top_left + top_up + top_right + right + bottom_right + bottom_down + bottom_left + left transformed_img.itemset((y,x), res) except: pass l.printLog('Duration BasicLBP:') return transformed_img, None
def send(cls, para): from_uid = para['from_uid'] to_uid = para['to_uid'] #TODO # if cls.isSent(from_uid, to_uid): # return Error.GIFT_SENT now = int(time.time()) key = '%s:%s:%s' % (from_uid, to_uid, now) gift_type = random.randint(1, 2) data = { 'from_uid': from_uid, 'time': now, 'gid': key, 'type': gift_type, } item_type = cls.getIndexItemType() item_type(key).setAll(data) user_gift = cls(to_uid) if user_gift.size() < cls.MAX_SIZE: user_gift.addKey(key) cli = Redis() key = cls.genGiftCacheKey(from_uid, to_uid) cli.set(key, 1) cli.expire(key, cls.DAY_SEC) else: Log.error('user_gift full, unable to receive') return {}
def count(self, Y, X, **kwargs): prediction = kwargs.get('prediction', 1) beta = kwargs.get('beta', 0.1) logging = kwargs.get('logging', False) log = Log(logging, "RBF.count()") log.message("start") N=len(Y) self.Yn=Y.copy() e=zeros(N) colx = [] allColx = [] for j in range(N-prediction): log.message(j, conditioned=True) #update neuronu LIFO (moving window) start updating after prediction lag if (j > 0 and j > prediction): self.W = self.W[1:] #remove first self.W.append(allColx[-prediction]) self.Y = self.Y[1:] #remove first self.Y.append(Y[j]) colx = [] for i in range(len(X)): colx.append([X[i][j] ]) #, X[i][j-1], X[i][j-2], X[i][j-3], X[i][j-4]]) allColx.append(colx) Nw=len(self.W) phi=zeros(Nw) nu=zeros(Nw) for i in range(Nw): nu[i]=self.fnu(asarray(self.W[i]),asarray(colx)) #nu[i]=fnu(W[i,:],x) phi=self.fphi(nu,beta) # output of RBF self.Yn[j+prediction]=sum(asarray(phi)*asarray(self.Y))/sum(asarray(phi)) log.message("done \n") return self.Yn
def count(self, Y, X, **kwargs): prediction = kwargs.get('prediction', 1) epochs = kwargs.get('epochs', 1) logging = kwargs.get('logging', False) lw = kwargs.get('learningWindow', 0) ol = kwargs.get('overLearn', 0) log = Log(logging, "MLPGD.count()") log.message("start") yr = Y muw = 0.05 muv = 0.01 N = len(Y) nx = len(X) * 4 + 1 n1 = 5 nv = 1 + n1 nxi = nv if len(self.w) < 1: self.w = randn( n1, nx ) / nx if len(self.v) < 1: self.v = randn( nv ) / nv e = zeros( lw ) y = Y.copy() #x = ones( nx ) xi = ones( nxi ) dxidny = zeros ( n1 + 1 ) dydv = zeros(( lw, nv )) dydw = zeros(( lw, nx, n1 )) Lv = eye( nv ) Lw = eye( nx ) SSE = zeros( epochs ) for epoch in range( epochs ): for k in range ( N - prediction): #input vector x = [1.] for i in range(len(X)): x = concatenate((x, [ X[i][k], X[i][k-1], X[i][k-2], X[i][k-3] ])) ny = dot( self.w, x ) xi[1:] = self.phi(ny) y[ k + prediction ] = dot( self.v, xi ) ek = yr[ k ] - y[ k ] e = concatenate(( e, [ek] )) e = delete(e, 0, 0) #weights of output neuron dydv = delete(dydv, 0, 0) dydv = vstack(( dydv, xi )) #vweights of hidden nodes dxidny[1:] = self.dphidny(ny) dydwk = zeros( ( 1, nx, n1 ) ) for i in range(1, n1 + 1 ): dydwk[0, :,i-1] = self.v[ i ] * dxidny[ i ] * x dydw = delete(dydw, 0, 0) dydw = vstack(( dydw, dydwk)) if k > lw and k % ol == 0: print k Jv = dydv dv = dot( dot( inv( dot( Jv.T, Jv ) + 1. / muv * Lv ), Jv.T ), e ) self.v = self.v + dv for i in range( 1, n1 + 1 ): Jw = dydw[ :, :, i - 1 ] dw = dot( dot( inv( dot( Jw.T, Jw ) + 1. / muw * Lw ), Jw.T ), e ) self.w[ i - 1, : ] = self.w[ i - 1, : ] + dw SSE[ epoch ] = dot( e, e ) return y
def getPayTable(cls, game_id): if game_id not in cls.PAYTABLE: Log.error('getPayTable:game_id=%s invalid, using 1 instead'%game_id) game_id = 1 return cls.PAYTABLE[game_id]
def getSymbolWeightById(cls, game_id): if game_id not in cls.SYMBOL_WEIGHT: Log.error('getSymbolWeightById:game_id=%s invalid, using 1 instead'%game_id) game_id = 1 return cls.SYMBOL_WEIGHT[game_id]
def count(self, Y, X, **kwargs): prediction = kwargs.get('prediction', 1) epochs = kwargs.get('epochs', 1) logging = kwargs.get('logging', False) log = Log(logging, "MLPGD.count()") log.message("start") yr = Y muw = 0.05 muv = 0.01 N = len(Y) n1 = 2 nx = len(X) * 4 + 1 nv = 1 + n1 nxi = nv if len(self.w) < 1: self.w = randn( n1, nx ) / nx if len(self.v) < 1: self.v = randn( nv ) / nv e = zeros( N ) y = Y.copy() #x = ones( nx ) xi = ones( nxi ) dxidny = zeros ( n1 + 1 ) dydv = zeros(( N, nv )) dydw = zeros( ( N, nx, n1 ) ) Lv = eye( nv ) Lw = eye( nx ) SSE = zeros( epochs ) for epoch in range( epochs ): for k in range ( N - prediction): #input vector x = [1.] for i in range(len(X)): x = concatenate((x, [ X[i][k], X[i][k-1], X[i][k-2], X[i][k-3] ])) ny = dot( self.w, x ) xi[1:] = self.phi(ny) y[ k + prediction ] = dot( self.v, xi ) e[ k ] = yr[ k ] - y[ k - prediction] #weights of input neuron dydv[k, :] = xi #weights of hidden nodes dxidny[1:] = self.dphidny(ny) for i in range(1, n1 + 1 ): dydw[k, :, i-1 ] = self.v[ i ] * dxidny[ i ] * x Jv = dydv dv = dot( dot( inv( dot( Jv.T, Jv ) + 1. / muv * Lv ), Jv.T ), e ) self.v = self.v + dv for i in range( 1, n1 + 1 ): Jw = dydw[ :, :, i - 1 ] dw = dot( dot( inv( dot( Jw.T, Jw ) + 1. / muw * Lw ), Jw.T ), e ) self.w[ i - 1, : ] = self.w[ i - 1, : ] + dw SSE[ epoch ] = dot( e, e ) return y
def getNum(cls, machine_id, n): if machine_id not in cls.SCATTER_RATE: Log.error("FreeSpin::getNum: machine_id=%s invalid" % machine_id) machine_id = 1 return cls.SCATTER_RATE[machine_id][n]
def api(request): try: para = json.loads(request.body) Log.info('Request: %s' % (log_kv(para))) cmd = para['cmd'] if cmd in API_ROUTER: processPara(para) if cmd == 'login': if request.META.has_key('HTTP_X_REAL_IP'): para['ip'] = request.META['HTTP_X_REAL_IP'] else: para['ip'] = request.META['REMOTE_ADDR'] if cmd != 'verify_purchase' and para['version'] < Config.MIN_VERSION: Log.info('unsupported version: %d' % para['version']) return HttpResponse(genResponse(Error.VERSION_TOO_LOW)) if cmd != 'login' and cmd != 'verify_purchase': if not Session.is_valid(para['uid'], para['sid']): Log.error('session invalid') return HttpResponse(genResponse(Error.INVALID_SESSION)) ret = API_ROUTER[cmd](para) response = genResponse(ret, para['uid']) Log.info('Request: %s, Response: %s' % (para, response)) return HttpResponse(response, content_type="application/json") else: Log.error('unknown cmd') return HttpResponse(genResponse(Error.UNKNOWN_CMD)) except Exception, e: traceback.print_exc() Log.error(traceback.format_exc()) return HttpResponseServerError("Unknown error: %s" % str(e))
def spin(cls, para): if not checkPara(para, ['uid', 'machine_id', 'lines', 'bet', 'is_free']): return Error.INVALID_PARAM uid = para['uid'] game_id = para['machine_id'] lines = para['lines'] bet = para['bet'] is_free = para['is_free'] fake_flag = 0 if 'fakeflag' in para: fake_flag = int(para['fakeflag']) lv = User(uid).level #check if not ConfMgr.isMachineLocked(game_id, lv): return Error.MACHINE_LOCKED if not ConfMgr.isLineValid(game_id, lines): return Error.LINE_EXCEEDED if not ConfMgr.isBetValid(lv, bet): return Error.BET_EXCEEDED pay_in = 0 user = User(uid) cur_coin = user.coin # may change wild_tune for this user user.addSpin() if not is_free: user.clearWinRec() if not is_free: pay_in = lines * bet if cur_coin < pay_in: Log.error('no enough coin to spin') return Error.NO_COIN else: # pick saved bet and lines for free spin free_spin = FreeSpin(uid, game_id) ret = free_spin.consume() if ret is False: return Error.NO_FREE_SPIN # override (lines, bet) = ret machine = cls(game_id) # ignore bonus if skip playing it game_type = BonusGameType.getBonusGameType(game_id) bonus_game = game_type(uid, game_id) bonus_game.remove() (response, win, bonus_num, spin_num) = machine.doSpin(game_id, lv, lines, bet, is_free, fake_flag) if bonus_num > 0: game_type.create(uid, game_id, bonus_num, bet) Log.debug('created bonus games: bonus_num=%s'%bonus_num) if spin_num > 0: free_spin = FreeSpin(uid, game_id) free_spin.add(spin_num, lines, bet) response['is_new_freespin'] = True Log.debug('added free spin=%s'%spin_num) # save for big/mega win user.addWinRec(win / bet) # Tournament update Tournament.compete(uid, game_id, win) # compose reponse now_coin = cur_coin - pay_in + win user.coin = now_coin response['coin'] = now_coin (now_exp, lv_up) = user.addExp(lines*bet) response['exp'] = now_exp response['level'] = user.level free_spin = FreeSpin(uid, game_id).getAll() if free_spin: response['free_spin'] = free_spin win_info = user.checkWinRec() if win_info: response.update(win_info) rank_info = Tournament.getRank({'uid': uid, 'machine_id': game_id}) if rank_info != Error.TOUR_NOT_OPEN: response['rank_info'] = rank_info # share gift flag share = UserShareGift(uid) if '5combo' in response: share.setFlag(UserShareGift.TYPE_COMBO) # bonus may also trigger it if 'is_mega' in response: share.setFlag(UserShareGift.TYPE_MEGA) if lv_up: share.setFlag(UserShareGift.TYPE_LEVELUP) #only for stat data = {'bet': pay_in, 'win': win, 'spin': 1, 'trigger_freespin': 1 if spin_num > 0 else 0, 'trigger_bonus': 1 if bonus_num > 0 else 0, 'free_spin': 1 if is_free else 0, } Stat().incr(data) return response
def countSerie(self, Y, X, **kwargs): # optional parameters prediction = kwargs.get('prediction', 1) mu = kwargs.get('mu', 0.1) self.w = kwargs.get('weigths', self.w) logging = kwargs.get('logging', False) log = Log(logging, "LNU.count()") log.message("start") # for counting nx = len(X) * 4 + 1 #lenX * X width + 1 nw = nx N=len(Y) e=zeros(N) # "prazdna " array pro vypocet chyb v delce dat yn = Y.copy() # init vystup neuronu (site) yn[0] = float('nan') log.message(yn[1]) x = [1.] x = array(x) if len(self.w) < 1: self.w = random.randn(nw)/nw print self.w self.w = random.randn(nw) print self.w # for record Wall = [] Wall.append(self.w) #initial weigth MSE = [] for k in range(N-prediction): ## input vector x = [1.] for i in range(len(X)): x = concatenate((x, [ X[i][k], X[i][k-1], X[i][k-2], X[i][k-3] ])) # neuron count yn[k+prediction]=dot(self.w,x) if not isnan(yn[k]): e[k]=Y[k]-yn[k] #update weights dydw=x # pro LNU dy/dw = x dw=mu/(1+sum(x**2))*e[k]*dydw # normalizovany GD self.w=self.w+dw #for plotting Wall.append(self.w) MSE.append(sum(e**2)/N) log.message("done \n") return yn, self.w, Wall, MSE, e