def updatePosition(self, point): self.moving_timer -= 1 if (self.moving and utils.manhattanDistance(self.position, point) >= self.stay_moving_threshold) or ( not self.moving and utils.manhattanDistance(self.position, point) > self.become_moving_threshold ): # self.moving_timer = 5 self.moving = True self.position = point else: self.moving = self.moving_timer > 0
def __findMatchings(circles_to_be_matched, balls): balls_in_play = [ball for ball in balls if not ball.scored] balls_is_matched = {} for ball in balls_in_play: balls_is_matched[ball] = False unmatched_circles = [] #find close matchings for circle_id,circle in enumerate(circles_to_be_matched): center = circle.intCenter() min,closest_ball = Tracker.__getBallClosestToPoint(center, balls_in_play) if min < 10: #really? match 1st one < 10? #magic closest_ball.vanished_frames = 0 balls_is_matched[closest_ball] = True closest_ball.updatePosition(circle.center()) else: unmatched_circles.append(circle) #check vanished balls vanished_balls = [ball for ball in balls_in_play if not balls_is_matched[ball]] ball_to_circle = {} for ball in vanished_balls: ball.vanished_frames += 1 if len(unmatched_circles) >= 1: ball_to_circle[ball] = Tracker.__getCircleClosestToBall(ball, unmatched_circles) ball_circle_pairs = ball_to_circle.items() #print ball_circle_pairs ball_circle_pairs.sort(key=lambda x:x[1][1]) for ball, circle in ball_circle_pairs: circle = circle[0] if circle in unmatched_circles: if utils.manhattanDistance(ball.position, circle.center()) < ball.vanished_frames * 60: ball.updatePosition(circle.center()) unmatched_circles.remove(circle)
def getDistribution( self, state ): # Read variables from state ghostState = state.getGhostState( self.index ) legalActions = state.getLegalActions( self.index ) pos = state.getGhostPosition( self.index ) isScared = ghostState.scaredTimer > 0 speed = 1 if isScared: speed = 0.5 actionVectors = [Actions.directionToVector( a, speed ) for a in legalActions] newPositions = [( pos[0]+a[0], pos[1]+a[1] ) for a in actionVectors] pacmanPosition = state.getPacmanPosition() # Select best actions given the state distancesToPacman = [manhattanDistance( pos, pacmanPosition ) for pos in newPositions] if isScared: bestScore = max( distancesToPacman ) bestProb = self.prob_scaredFlee else: bestScore = min( distancesToPacman ) bestProb = self.prob_attack bestActions = [action for action, distance in zip( legalActions, distancesToPacman ) if distance == bestScore] # Construct distribution dist = utils.Counter() for a in bestActions: dist[a] = bestProb / len(bestActions) for a in legalActions: dist[a] += ( 1-bestProb ) / len(legalActions) dist.normalize() return dist
def recalc(ball_id): global detector circles_d = detector.detect(frame) circles = circles_d[Color.RED] if ball_id < 5 else circles_d[Color.WHITE] circles_dists = [utils.manhattanDistance(c.center(),state.getBall(ball_id).position) for c in circles] match = circles[circles_dists.index(min(circles_dists))] state.getBall(ball_id).position = match.center() redraw()
def __getCircleClosestToBall(ball, circles): min = 1000 for circle in circles: dist = utils.manhattanDistance(ball.position,circle.center()) if(dist < min): best_circle = circle min = dist return best_circle,min
def __getBallClosestToPoint(point, available_balls): min = 1000 for ball in available_balls: dist = utils.manhattanDistance(ball.position, point) if(dist < min): best_ball = ball min = dist return min,best_ball
def ballScored(self, ball): self.cooldown_timer -= 1 if self.cooldown_timer > 0: return False if not ball.scored and utils.manhattanDistance(ball.position, self.position) < self.max_hole_distance: ball.scored = True ball.moving = False self.cooldown_timer = self.num_frames_cooldown return True return False
def __analyzeHistory(self,ball): print 'analyzing history!' frames = ball.position_history.frames #print frames for frame in frames: x,y = frame.ball_position if y >= 275: pass #print 'below white new age threshold' if x <= 70: pass #print 'bounced off right cushion' if utils.manhattanDistance((x,y),self.hole_positions[0]) < 40: pass
def applyAction( state, action ): """ Edits the state to reflect the results of the action. """ legal = PacmanRules.getLegalActions( state ) if action not in legal: raise Exception("Illegal action " + str(action)) pacmanState = state.data.agentStates[0] # Update Configuration vector = Actions.directionToVector( action, PacmanRules.PACMAN_SPEED ) pacmanState.configuration = pacmanState.configuration.generateSuccessor( vector ) # Eat next = pacmanState.configuration.getPosition() nearest = nearestPoint( next ) if manhattanDistance( nearest, next ) <= 0.5 : # Remove food PacmanRules.consume( nearest, state )
def applyAction(state, action): """ Edits the state to reflect the results of the action. """ legal = PacmanRules.getLegalActions(state) if action not in legal: raise Exception("Illegal action " + str(action)) pacmanState = state.data.agentStates[0] # Update Configuration vector = Actions.directionToVector(action, PacmanRules.PACMAN_SPEED) pacmanState.configuration = pacmanState.configuration.generateSuccessor( vector) # Eat next = pacmanState.configuration.getPosition() nearest = nearestPoint(next) if manhattanDistance(nearest, next) <= 0.5: # Remove food PacmanRules.consume(nearest, state)
def getDistribution(self, state): # Read variables from state ghostState = state.getGhostState(self.index) legalActions = state.getLegalActions(self.index) pos = state.getGhostPosition(self.index) isScared = ghostState.scaredTimer > 0 speed = 1 if isScared: speed = 0.5 actionVectors = [ Actions.directionToVector(a, speed) for a in legalActions ] newPositions = [(pos[0] + a[0], pos[1] + a[1]) for a in actionVectors] pacmanPosition = state.getPacmanPosition() # Select best actions given the state distancesToPacman = [ manhattanDistance(pos, pacmanPosition) for pos in newPositions ] if isScared: bestScore = max(distancesToPacman) bestProb = self.prob_scaredFlee else: bestScore = min(distancesToPacman) bestProb = self.prob_attack bestActions = [ action for action, distance in zip(legalActions, distancesToPacman) if distance == bestScore ] # Construct distribution dist = utils.Counter() for a in bestActions: dist[a] = bestProb / len(bestActions) for a in legalActions: dist[a] += (1 - bestProb) / len(legalActions) dist.normalize() return dist
def ManhattanModel(train_users, dev_users, test_users): subjects = train_users["user_id"].unique() #Se calcula la media de cada usuario agrupando el dataframe de train groupby = train_users.groupby("user_id").mean().copy() #Se incluye la columna del usuario train_users = groupby.reset_index() users_evaluation_dev = [] #Se hace el cálculo para cada usuario for subject in subjects: #Media del vector del usuario actual mean_vector = train_users.loc[train_users.user_id == subject, "ft_1":"ft_60"] #Para cada registro del subdataset de test for index, row in dev_users.iterrows(): temp_obj = {} #userid del del registro actual del subdataset de test current_user_id = row[0] #Vector de tiempo del registro actual del subdataset de test current_data = row[1:] temp_obj["user_model"] = subject temp_obj["user_id"] = current_user_id temp_obj["score"] = manhattanDistance(mean_vector, current_data) temp_obj["std_score"] = manhattanStandardization( manhattanDistance(mean_vector, current_data)) #temp_obj["std_score"] = standardizationMinMax(euclideanDistance(mean_vector, current_data)) if subject == current_user_id: temp_obj["y_test"] = "genuine" else: temp_obj["y_test"] = "impostor" users_evaluation_dev.append(temp_obj) users_evaluation_dev = pd.DataFrame(users_evaluation_dev) #Obtenemos la listas de scores de los registros que deberian de catalogarse como genuinos por los modelos genuine_scores_dev = list( users_evaluation_dev.loc[users_evaluation_dev.y_test == "genuine", "std_score"]) #Obtenemos la listas de scores de los registros que deberian de catalogarse como impostores por los modelos impostor_scores_dev = list( users_evaluation_dev.loc[users_evaluation_dev.y_test == "impostor", "std_score"]) #Calculo del ERR y del umbral de decisión global err_dev, thresh_dev = evaluate_EER_Thresh_Distance(genuine_scores_dev, impostor_scores_dev) #----------------------------------------------------------------------------------- users_evaluation_test = [] #Se hace el cálculo para cada usuario for subject in subjects: #Media del vector del usuario actual mean_vector = train_users.loc[train_users.user_id == subject, "ft_1":"ft_60"] #Para cada registro del subdataset de test for index, row in test_users.iterrows(): temp_obj = {} #userid del del registro actual del subdataset de test current_user_id = row[0] #Vector de tiempo del registro actual del subdataset de test current_data = row[1:] temp_obj["user_model"] = subject temp_obj["user_id"] = current_user_id temp_obj["score"] = manhattanDistance(mean_vector, current_data) temp_obj["std_score"] = manhattanStandardization( manhattanDistance(mean_vector, current_data)) #temp_obj["std_score"] = standardizationMinMax(euclideanDistance(mean_vector, current_data)) if subject == current_user_id: temp_obj["y_test"] = "genuine" else: temp_obj["y_test"] = "impostor" users_evaluation_test.append(temp_obj) users_evaluation_test = pd.DataFrame(users_evaluation_test) # OJO, aca se esta usando el score como umbral, si usaramos el score estandarizado, deberiamos de cambiar el sentido de la comparación users_evaluation_test['y_pred'] = np.where( users_evaluation_test['std_score'] >= thresh_dev, 'genuine', 'impostor') #Obtenemos los y_test y y_pred de nuestros resultados y_test_test = users_evaluation_test.loc[:, "y_test"] y_pred_test = users_evaluation_test.loc[:, "y_pred"] #----------------------------------------------------------------------------------- #Obtenemos la listas de scores de los registros que deberian de catalogarse como genuinos por los modelos genuine_scores_test = list( users_evaluation_test.loc[users_evaluation_test.y_test == "genuine", "std_score"]) #Obtenemos la listas de scores de los registros que deberian de catalogarse como impostores por los modelos impostor_scores_test = list( users_evaluation_test.loc[users_evaluation_test.y_test == "impostor", "std_score"]) thresh_x, thresh_y, _ = find_fpr_and_tpr_given_a_threshold_Distance( genuine_scores_test, impostor_scores_test, thresh_dev) thresh_std = round(thresh_dev.tolist(), 3) return y_test_test, y_pred_test, genuine_scores_test, impostor_scores_test, thresh_std, thresh_x, thresh_y
def getFurthestCorner(self, pacPos): poses = [(1, 1), (1, self.height - 2), (self.width - 2, 1), (self.width - 2, self.height - 2)] dist, pos = max([(manhattanDistance(p, pacPos), p) for p in poses]) return pos
def invalidDetection(self, detected_circle): return ( self.cooldown_timer > 0 and utils.manhattanDistance(detected_circle.center(), self.position) < self.max_hole_distance )
def flagged(self): ret = utils.manhattanDistance(self.position,self.ball.position) != 0 or self.hidden != self.ball.hidden self.position = self.ball.position self.hidden = self.ball.hidden return ret
def canKill( pacmanPosition, ghostPosition ): return manhattanDistance( ghostPosition, pacmanPosition ) <= COLLISION_TOLERANCE
def canKill(pacmanPosition, ghostPosition): return manhattanDistance(ghostPosition, pacmanPosition) <= COLLISION_TOLERANCE
def getFurthestCorner( self, pacPos ): poses = [(1,1), (1, self.height - 2), (self.width - 2, 1), (self.width - 2, self.height - 2)] dist, pos = max([(manhattanDistance(p, pacPos), p) for p in poses]) return pos