Esempio n. 1
0
  def getTransitionStatesAndProbs(self, state, action = None):
    """
    The agent takes the action, and the world proceeds one time step.
    None action indicates no ball processor
    """
    # may move ball
    ball = state[0][:2]
    if action == None:
      ballVelocity = state[0][2:]
    else:
      ballVelocity = (0, 0)

    keepers = list(self.getKeepers(state))
    takers = list(self.getTakers(state))

    chasers = sorted(keepers, key=lambda keeper: util.getPointVectorDistance(keeper, ball, ballVelocity))
    # most closest agent, possess the ball, or go to the ball 
    if self.weHaveBall(state):
      # j has the ball, its transition depends on the action
      if action[0] == 'hold':
        pass
      elif action[0] == 'pass':
        # pass the ball to a teammate
        rand = util.randomVector(0.1)
        target = keepers[action[1]]
        diff = util.getDirection(keepers[0], (target[0] + rand[0], target[1] + rand[1]))
        ballVelocity = (self.ballSpeed * diff[0], self.ballSpeed * diff[1])
      else:
        raise Exception('Unknown action')
    else:
      # j should go to the ball
      chasers[0] = self.moveTowards(chasers[0], ball)

    # other agents get open for a pass
    for i in xrange(1, len(chasers)):
      # concretely, this agent goes to a least congested place
      chasers[i] = self.moveTowards(chasers[i], self.getLeastCongestedLoc(state, chasers[i]))
    keepers = sorted(chasers, key=lambda keeper: util.getDistance(keeper, ball))
    
    for i in xrange(2):
      takers[i] = self.moveTowards(takers[i], ball)
    for i in xrange(2, len(takers)):
      takers[i] = self.moveTowards(takers[i], keepers[1])
    takers = sorted(takers, key=lambda taker: util.getDistance(taker, keepers[0]))
    
    newBall = (ball[0] + ballVelocity[0], ball[1] + ballVelocity[1],\
               ballVelocity[0], ballVelocity[1])
    newState = [newBall] + keepers + takers
    return [(tuple(newState), 1)]
Esempio n. 2
0
 def opponentGetsTheBall(self, state):
   ballLoc = state[0][:2]
   for loc in self.getTakers(state):
     dist = util.getDistance(loc, ballLoc)
     if dist < self.ballAttainDist:
       return True
   return False
Esempio n. 3
0
def action(board, moves):
    """
    
    Args:
       board ${1:arg1}
       moves ${2:arg2}

    Returns:
        move 選択したmove

    """
    pprint(moves)

    # 確定マスではない辺はなるべく取りたい
    sidePos = len(board) - 1
    for move in moves:
        if isCorner(board, move):
            pass
        elif move[0] == 0 or move[0] == sidePos or move[1] == 0 or move[
                1] == sidePos:
            if not isStaticPoint(board, move):
                return move

    center = action1.getCenter(board)
    distances = []
    for move in moves:
        distances.append([
            util.getDistance([move[0], move[1]], [center[0], center[1]]), move
        ])

    sorted(distances, key=lambda x: x[1])

    moves = []
    for distance in distances:
        moves.append(distance[1])

    # 辺の確定マスにはなるべく打たない
    tmpH = []
    tmpL = []
    for move in moves:
        if isStaticPoint(board, move):
            tmpL.append(move)
        else:
            tmpH.append(move)
    tmpH.extend(tmpL)
    moves = tmpH

    # 角はなるべくとらない
    tmpH = []
    tmpL = []
    for move in moves:
        if isCorner(board, move):
            tmpL.append(move)
        else:
            tmpH.append(move)
    tmpH.extend(tmpL)
    moves = tmpH

    return moves[0]
Esempio n. 4
0
def evaluationFunc(board, target, size):
    nextBoard = OthelloLogic.execute(copy.deepcopy(board), target, 1, size)

    boardScore = 0
    for i in range(8):
        for j in range(8):
            boardScore = boardScore + util.getDistance([4, 4],
                                                       [i, j]) * board[i][j]
    return boardScore
def run():
	voxelArrayMap = util.getVoxelArray(False, False, False, True, [2])
	util.normalize(voxelArrayMap)

	centroids = [0] * 5
	keys = list(voxelArrayMap.keys())
	selected = []
	for index in range(len(centroids)):
		while True:
			centroidKey = random.choice(keys)
			category = centroidKey[1]
			if category not in selected:
				selected.append(category)
				break
		print centroidKey
		centroids[index] = voxelArrayMap[centroidKey]

	numIters = 120
	assignmentMap = {}
	for iteration in range(numIters):
		newCentroids = [ [0] * 1973 for i in range(len(centroids))]
		clusterCounts = [0] * len(newCentroids)
		for key in voxelArrayMap:
			value = voxelArrayMap[key]
			distances = [ util.getDistance(centroid, value) for centroid in centroids ]
			minDistance = min(distances)
			optCentroid = distances.index(minDistance)
			assignmentMap[key] = optCentroid
			for voxelIndex in range(len(newCentroids[optCentroid])):
				newCentroids[optCentroid][voxelIndex] += value[voxelIndex]
			clusterCounts[optCentroid] += 1

		for index in range(len(newCentroids)):
			numPoints = clusterCounts[index]
			if numPoints != 0:
				centroid = newCentroids[index]
				centroid = [ centroid[voxelIndex] / numPoints for voxelIndex in range(len(centroid)) ]
				newCentroids[index] = centroid
		centroids = newCentroids

	# we want ClusterNum -> What type of image
	catMap = {}
	for key in assignmentMap:
		assignment = assignmentMap[key]
		# key[1] is the category (0-5 for face, body, etc)
		# assignment is the optimal centroid
		if assignment in catMap:
			arr = catMap[assignment]
			arr.append(key[1])
			catMap[assignment] = arr
		else:
			catMap[assignment] = [key[1]]
	print catMap
def classifyByClosestCorrelation(exampleCorrelations, averageCategoryCorrelations):
	#Lets say (ex,0) = 5, (ex,1) = 15,(ex,2) = -30,(ex,3) = 40,(ex,4) = 100,
	#Can 		 (1,0) =3, (2,0) = 5...
	#should really see our 0 - their 0, our 1 vs real 1
	#For each possible category the image could be, 
	#We will go through and see how far its correlation to each category compares to average
	distances = [0]*5
	correlations = [0] *5
	indClosest = [0]*5
	for y in range(5):
		distances[y] = util.getDistance(exampleCorrelations,averageCategoryCorrelations[y])
		correlations[y] = scipy.stats.pearsonr(exampleCorrelations, averageCategoryCorrelations[y])[0]
		differences = [abs(a - b) for a,b in zip(exampleCorrelations, averageCategoryCorrelations[y])]
		indClosest[y] = min(differences)
	return (distances.index(min(distances)), indClosest.index(min(indClosest)), correlations.index(max(correlations)) )
    def kNearestNeighbor(self, k=1):
        # Choose one to leave out, out of all
        totalError = 0
        totalPredictions = len(self.data)

        for key in self.data:
            testedExample = self.data[key]
            self.data.pop(key, None)

            # (distance, category)
            nearestNeighbors = []
            for neighbor in self.data:
                category = neighbor[1]
                distance = util.getDistance(self.data[neighbor], testedExample)
                if len(nearestNeighbors) < k:
                    nearestNeighbors.append((distance, category))
                    nearestNeighbors.sort()
                elif distance < nearestNeighbors[k - 1][0]:
                    nearestNeighbors[k - 1] = (distance, category)
                    nearestNeighbors.sort()

            closestNeighbors = [0] * Constants.NUM_CATEGORIES
            for neighbor in nearestNeighbors:
                distance, category = neighbor
                closestNeighbors[category] += 1 / distance

            c = sum(closestNeighbors)
            closestNeighbors = [x / c for x in closestNeighbors]

            choice = numpy.random.choice(range(Constants.NUM_CATEGORIES),
                                         p=closestNeighbors)

            if key[1] != choice:
                # print "Tested on category ", key[1], " Classified it as: ", choice
                totalError += 1
            self.data[key] = testedExample
        percentCorrect = float(totalPredictions -
                               totalError) * 100 / totalPredictions
        print self.categories, totalPredictions - totalError, 'out of', totalPredictions, 'correct', 'for k =', k, 'or', percentCorrect, '%'
        return percentCorrect
Esempio n. 8
0
def classifyByClosestCorrelation(exampleCorrelations,
                                 averageCategoryCorrelations):
    #Lets say (ex,0) = 5, (ex,1) = 15,(ex,2) = -30,(ex,3) = 40,(ex,4) = 100,
    #Can 		 (1,0) =3, (2,0) = 5...
    #should really see our 0 - their 0, our 1 vs real 1
    #For each possible category the image could be,
    #We will go through and see how far its correlation to each category compares to average
    distances = [0] * 5
    correlations = [0] * 5
    indClosest = [0] * 5
    for y in range(5):
        distances[y] = util.getDistance(exampleCorrelations,
                                        averageCategoryCorrelations[y])
        correlations[y] = scipy.stats.pearsonr(
            exampleCorrelations, averageCategoryCorrelations[y])[0]
        differences = [
            abs(a - b) for a, b in zip(exampleCorrelations,
                                       averageCategoryCorrelations[y])
        ]
        indClosest[y] = min(differences)
    return (distances.index(min(distances)), indClosest.index(min(indClosest)),
            correlations.index(max(correlations)))
Esempio n. 9
0
def action(board, moves, size=8):
    # 撃てる場所が1つしかない場合はそこに打つ
    if len(moves) == 1:
        return moves[0]

    centerPos = getCenter(board)
    print("centerPos:", centerPos)

    minDistance = 100
    minDistanceIndex = 0
    returnMove = moves[0]
    for move in moves:
        distance = util.getDistance(move, centerPos)
        if ignoreSideLine(board, moves, move):
            print("ignore")
            continue
        if distance < minDistance:
            minDistance = distance
            returnMove = move

    pprint(board)
    util.printMoves(board, moves, returnMove, centerPos)
    return returnMove
Esempio n. 10
0
    def __init__(self, lightSrc, maxRadius, minRadius, *args, **kwargs):
        Widget.__init__(self, *args, **kwargs)

        self.minRadius = minRadius
        self.maxRadius = maxRadius
        self.lightSrc = lightSrc

        d = getDistance(centerX, centerY, self.lightSrc[0], self.lightSrc[1])
        t = np.linspace(0, 20, int(20 / 0.2), endpoint=False)

        # Get how pupil oscillates
        calculateMovement(1.135, 0.05, 1.135, 0.0003, 1250, 0.01, t)
        self.r = maxRadius * calculateMovement(
            1, self.lightSrc[2] / maxRadius, d / maxRadius, 0.0003, 1250, 0.01,
            t)
        self.counter = 0

        self.dilate = Clock.schedule_interval(self.updatePupil, 0.2)

        # plot results
        plt.plot(t, self.r)
        plt.xlabel('time')
        plt.ylabel('y(t)')
        plt.show()
Esempio n. 11
0
def fourVSThreeKeepawayFeatures(state, size):
    C = (0.5 * size, 0.5 * size)

    K1, K2, K3, K4, T1, T2, T3 = state[1:8]

    # get features as a list of real numbers
    feats = [getDistance(K1, C),\
             getDistance(K1, K2),\
             getDistance(K1, K3),\
             getDistance(K1, K4),\

             getDistance(K1, T1),\
             getDistance(K1, T2),\
             getDistance(K1, T3),\

             getDistance(K2, C),\
             getDistance(K3, C),\
             getDistance(K4, C),\

             getDistance(T1, C),\
             getDistance(T2, C),\
             getDistance(T3, C),\

             min([getDistance(K2, T1), getDistance(K2, T2), getDistance(K2, T3)]),\
             min([getDistance(K3, T1), getDistance(K3, T2), getDistance(K3, T3)]),\
             min([getDistance(K4, T1), getDistance(K4, T2), getDistance(K4, T3)]),\

             min([getAngle(K2, K1, T1), getAngle(K2, K1, T2), getAngle(K2, K1, T3)]),\
             min([getAngle(K3, K1, T1), getAngle(K3, K1, T2), getAngle(K3, K1, T3)]),\
             min([getAngle(K4, K1, T1), getAngle(K4, K1, T2), getAngle(K4, K1, T3)]),\
            ]
    return feats
Esempio n. 12
0
def threeVSTwoKeepawayFeatures(state, size):
    C = (0.5 * size, 0.5 * size)

    K1, K2, K3, T1, T2 = state[1:6]

    # get features as a list of real numbers
    feats = [getDistance(K1, C),\
             getDistance(K1, K2),\
             getDistance(K1, K3),\

             getDistance(K1, T1),\
             getDistance(K1, T2),\

             getDistance(K2, C),\
             getDistance(K3, C),\

             getDistance(T1, C),\
             getDistance(T2, C),\

             min(getDistance(K2, T1), getDistance(K2, T2)),\
             min(getDistance(K3, T1), getDistance(K3, T2)),\

             min(getAngle(K2, K1, T1), getAngle(K2, K1, T2)),\
             min(getAngle(K3, K1, T1), getAngle(K3, K1, T2))
            ]

    return feats
Esempio n. 13
0
def fourVSThreeKeepawayFeatures(state, size):
  C = (0.5 * size, 0.5 * size)

  K1, K2, K3, K4, T1, T2, T3 = state[1:8]
  
  # get features as a list of real numbers
  feats = [getDistance(K1, C),\
           getDistance(K1, K2),\
           getDistance(K1, K3),\
           getDistance(K1, K4),\

           getDistance(K1, T1),\
           getDistance(K1, T2),\
           getDistance(K1, T3),\

           getDistance(K2, C),\
           getDistance(K3, C),\
           getDistance(K4, C),\

           getDistance(T1, C),\
           getDistance(T2, C),\
           getDistance(T3, C),\

           min([getDistance(K2, T1), getDistance(K2, T2), getDistance(K2, T3)]),\
           min([getDistance(K3, T1), getDistance(K3, T2), getDistance(K3, T3)]),\
           min([getDistance(K4, T1), getDistance(K4, T2), getDistance(K4, T3)]),\
           
           min([getAngle(K2, K1, T1), getAngle(K2, K1, T2), getAngle(K2, K1, T3)]),\
           min([getAngle(K3, K1, T1), getAngle(K3, K1, T2), getAngle(K3, K1, T3)]),\
           min([getAngle(K4, K1, T1), getAngle(K4, K1, T2), getAngle(K4, K1, T3)]),\
          ]
  return feats
Esempio n. 14
0
def threeVSTwoKeepawayFeatures(state, size):
  C = (0.5 * size, 0.5 * size)
  
  K1, K2, K3, T1, T2 = state[1:6]

  # get features as a list of real numbers
  feats = [getDistance(K1, C),\
           getDistance(K1, K2),\
           getDistance(K1, K3),\

           getDistance(K1, T1),\
           getDistance(K1, T2),\

           getDistance(K2, C),\
           getDistance(K3, C),\

           getDistance(T1, C),\
           getDistance(T2, C),\

           min(getDistance(K2, T1), getDistance(K2, T2)),\
           min(getDistance(K3, T1), getDistance(K3, T2)),\
           
           min(getAngle(K2, K1, T1), getAngle(K2, K1, T2)),\
           min(getAngle(K3, K1, T1), getAngle(K3, K1, T2))
          ]

  return feats
Esempio n. 15
0
 def weHaveBall(self, state):
   ballLoc = state[0][:2]
   dist = util.getDistance(state[1], ballLoc)
   if dist < self.ballAttainDist:
     return True
   return False
Esempio n. 16
0
 def getCongestion(pos):
   congest = 0
   for i in range(1, self.keeperNum + self.takerNum + 1):
     if state[i] != loc:
       congest += 1.0 / (util.getDistance(pos, state[i]) + 0.0001)
   return congest