Beispiel #1
0
    def next_step(self, things):
        '''Zombies attack if in range, else move in direction of players.'''
        action = None

        # possible targets for movement and attack
        humans = [thing for thing in things.values()
                  if isinstance(thing, Player)]
        positions = possible_moves(self.position, things)

        if humans:
            # targets available
            target = closest(self, humans)

            if distance(self.position, target.position) < self.weapon.max_range:
                # target in range, attack
                action = 'attack', target
            else:
                # target not in range, _try_ to move
                if positions:
                    by_distance = lambda position: distance(target.position,
                                                            position)
                    best_position = sorted(positions, key=by_distance)[0]
                    action = 'move', best_position
        else:
            # no targets, just wander around
            if positions:
                action = 'move', random.choice(positions)

        return action
    def _get_nearest_fort_on_lure_way(self, forts):

        if not self.lure_attraction:
            return None, 0

        lures = filter(lambda x: True if x.get("lure_info", None) != None else False, forts)

        if len(lures):
            dist_lure_me = distance(
                self.bot.position[0], self.bot.position[1], lures[0]["latitude"], lures[0]["longitude"]
            )
        else:
            dist_lure_me = 0

        if dist_lure_me > 0 and dist_lure_me < self.lure_max_distance:

            self.lure_distance = dist_lure_me

            for fort in forts:
                dist_lure_fort = distance(
                    fort["latitude"], fort["longitude"], lures[0]["latitude"], lures[0]["longitude"]
                )
                dist_fort_me = distance(fort["latitude"], fort["longitude"], self.bot.position[0], self.bot.position[1])

                if dist_lure_fort < dist_lure_me and dist_lure_me > dist_fort_me:
                    return fort, dist_lure_me

                if dist_fort_me > dist_lure_me:
                    break

            return lures[0], dist_lure_me

        else:
            return None, 0
Beispiel #3
0
def connect( self, pos ):
    """Search for any user-drawn platforms near pos. If one is found see if pos is
    close to either of its endpoints. If it is near an endpoint, set pos to that endpoint."""
    MAX_DIST = 30
    shape    = self.physics_interface.space.nearest_point_query_nearest( Vec2d( *pos ), 
                                                                         MAX_DIST, 
                                                                         COLLTYPE_USERPLAT | COLLTYPE_LAVA | COLLTYPE_USERCURVE )

    if shape:

        # Make sure magnets only connect two endpoints from different lines.
        touching_line = self.physics_interface.smap[ shape ]
        if touching_line != self.target_line and \
           ( shape.collision_type == COLLTYPE_USERPLAT or shape.collision_type == COLLTYPE_LAVA or shape.collision_type == COLLTYPE_USERCURVE ):

            if shape.collision_type == COLLTYPE_LAVA:
                start = touching_line.points[:2]
                end   = touching_line.points[2:]
            else:
                start = touching_line.get_start()
                end   = touching_line.get_end() 

            if distance( start, pos ) <= MAX_DIST:
                pos = Vec2d( *start )
            elif distance( end, pos ) <= MAX_DIST:
                pos = Vec2d( *end )

    return pos
    def work(self):
        if not self.config.catch_pokemon:
            return

        if 'catchable_pokemons' in self.cell and len(self.cell['catchable_pokemons']) > 0:
            logger.log('Something rustles nearby!')
            # Sort all by distance from current pos- eventually this should
            # build graph & A* it
            self.cell['catchable_pokemons'].sort(
                key=
                lambda x: distance(self.position[0], self.position[1], x['latitude'], x['longitude']))

            user_web_catchable = 'web/catchable-%s.json' % (self.config.username)
            for pokemon in self.cell['catchable_pokemons']:
                with open(user_web_catchable, 'w') as outfile:
                    json.dump(pokemon, outfile)

            return self.catch_pokemon(self.cell['catchable_pokemons'][0])

        if 'wild_pokemons' in self.cell and len(self.cell['wild_pokemons']) > 0:
            # Sort all by distance from current pos- eventually this should
            # build graph & A* it
            self.cell['wild_pokemons'].sort(
                key=
                lambda x: distance(self.position[0], self.position[1], x['latitude'], x['longitude']))
            return self.catch_pokemon(self.cell['wild_pokemons'][0])
    def work(self):
        if 'catchable_pokemons' in self.bot.cell and len(self.bot.cell['catchable_pokemons']) > 0:
            # Sort all by distance from current pos- eventually this should
            # build graph & A* it
            self.bot.cell['catchable_pokemons'].sort(
                key=
                lambda x: distance(self.bot.position[0], self.bot.position[1], x['latitude'], x['longitude'])
            )

            for pokemon in self.bot.cell['catchable_pokemons']:
                with open(user_web_catchable, 'w') as outfile:
                    json.dump(pokemon, outfile)
                self.emit_event(
                    'catchable_pokemon',
                    level='debug',
                    data={
                        'pokemon_id': pokemon['pokemon_id'],
                        'spawn_point_id': pokemon['spawn_point_id'],
                        'encounter_id': pokemon['encounter_id'],
                        'latitude': pokemon['latitude'],
                        'longitude': pokemon['longitude'],
                        'expiration_timestamp_ms': pokemon['expiration_timestamp_ms'],
                    }
                )

            return self.catch_pokemon(self.bot.cell['catchable_pokemons'].pop(0))

        if 'wild_pokemons' in self.bot.cell and len(self.bot.cell['wild_pokemons']) > 0:
            # Sort all by distance from current pos- eventually this should
            # build graph & A* it
            self.bot.cell['wild_pokemons'].sort(
                key=
                lambda x: distance(self.bot.position[0], self.bot.position[1], x['latitude'], x['longitude']))
            return self.catch_pokemon(self.bot.cell['wild_pokemons'].pop(0))
Beispiel #6
0
def find_closest(location, centroids):
    """Return the item in CENTROIDS that is closest to LOCATION. If two
    centroids are equally close, return the first one.

    >>> find_closest([3, 4], [[0, 0], [2, 3], [4, 3], [5, 5]])
    [2, 3]
    """
    return [x for x in centroids if distance(location,x) == min([distance(location,y) for y in centroids])][0]
Beispiel #7
0
def best_parent(step):
    ssga = world.ssga
    [motherId, parentId] = ssga.getParents(world.nam_tsize)
    population = ssga.population()
    mother = population[motherId]
    parent = population[parentId]
    distances = [utils.distance(population[i], mother) for i in range(world.popsize)]
    max_distances = np.array(distances).max()
    distance = utils.distance(parent, mother)
    assert distance == max_distances, "Distance from parent %f is different than maximum %f" % (distance, max_distances)
Beispiel #8
0
def findClosestAtom( frame, coords ):
    extendedCoords = ( coords[0], coords[1], 0 )
    minDist = distance(  extendedCoords , frame.atoms[0].x0 )
    minName = frame.atoms[0].symbol

    for atom in frame.atoms:
        if distance( extendedCoords, atom.x0 ) < minDist:
            minDist = distance( extendedCoords, atom.x0 ) 
            minName = atom.symbol
    return minName
Beispiel #9
0
def find_closest(location, centroids):
    """Return the item in CENTROIDS that is closest to LOCATION. If two
    centroids are equally close, return the first one.

    >>> find_closest([3, 4], [[0, 0], [2, 3], [4, 3], [5, 5]])
    [2, 3]
    """
    min_dist = lambda x: distance(location, x)
    min_distance = min_dist(min(centroids, key = min_dist))
    return [x for x in centroids if distance(location, x) == min_distance][0]
Beispiel #10
0
def find_closest(location, centroids):
    """Return the centroid in centroids that is closest to location. If
    multiple centroids are equally close, return the first one.

    >>> find_closest([3.0, 4.0], [[0.0, 0.0], [2.0, 3.0], [4.0, 3.0], [5.0, 5.0]])
    [2.0, 3.0]
    """
    # BEGIN Question 3
    dist = [distance(location, i) for i in centroids]
    res = [item for item in centroids if distance(location, item) == min(dist)][0]
    return res
Beispiel #11
0
 def similarity(self, stone):
     """ Computes similarity with another stone """
     dc = distance(self.center, stone.center)
     ds = distance(self.size, stone.size)
     da = abs(self.angle - stone.angle)
     if dc > 20:
         return 0.0
     if ds > 20:
         return 0.0
     if da > 20:
         return 0.0
     return 1.0 - max([dc / 20.0, ds / 20.0, da / 20.0])
    def work(self):
        num_catchable_pokemon = 0
        if 'catchable_pokemons' in self.bot.cell:
            num_catchable_pokemon = len(self.bot.cell['catchable_pokemons'])

        num_wild_pokemon = 0
        if 'wild_pokemons' in self.bot.cell:
            num_wild_pokemon = len(self.bot.cell['wild_pokemons'])

        num_available_pokemon = num_catchable_pokemon + num_wild_pokemon

        if num_catchable_pokemon > 0:
            # Sort all by distance from current pos- eventually this should
            # build graph & A* it
            self.bot.cell['catchable_pokemons'].sort(
                key=
                lambda x: distance(self.bot.position[0], self.bot.position[1], x['latitude'], x['longitude'])
            )
            user_web_catchable = os.path.join(_base_dir, 'web', 'catchable-{}.json'.format(self.bot.config.username))
            for pokemon in self.bot.cell['catchable_pokemons']:
                with open(user_web_catchable, 'w') as outfile:
                    json.dump(pokemon, outfile)
                self.emit_event(
                    'catchable_pokemon',
                    level='debug',
                    data={
                        'pokemon_id': pokemon['pokemon_id'],
                        'spawn_point_id': pokemon['spawn_point_id'],
                        'encounter_id': pokemon['encounter_id'],
                        'latitude': pokemon['latitude'],
                        'longitude': pokemon['longitude'],
                        'expiration_timestamp_ms': pokemon['expiration_timestamp_ms'],
                    }
                )

            self.catch_pokemon(self.bot.cell['catchable_pokemons'].pop(0))
            if num_catchable_pokemon > 1:
                return WorkerResult.RUNNING
            else:
                return WorkerResult.SUCCESS

        if num_available_pokemon > 0:
            # Sort all by distance from current pos- eventually this should
            # build graph & A* it
            self.bot.cell['wild_pokemons'].sort(
                key=
                lambda x: distance(self.bot.position[0], self.bot.position[1], x['latitude'], x['longitude']))
            self.catch_pokemon(self.bot.cell['wild_pokemons'].pop(0))

            if num_catchable_pokemon > 1:
                return WorkerResult.RUNNING
            else:
                return WorkerResult.SUCCESS
Beispiel #13
0
def find_closest(location, centroids):
    """Return the item in CENTROIDS that is closest to LOCATION. If two
    centroids are equally close, return the first one.

    >>> find_closest([3, 4], [[0, 0], [2, 3], [4, 3], [5, 5]])
    [2, 3]
    """
    "*** YOUR CODE HERE ***"
    min_dis=min(distance(location, i) for i in centroids)
    for i in range(len(centroids)):
        if distance(location, centroids[i])==min_dis:
            return centroids[i]
Beispiel #14
0
def calcHist(frame, extendedAtomsIter, binSize, boxSize, options):
    bins = [0 for _ in range(int(boxSize / (2 * binSize)))]
    extendedAtoms = [atom for atom in extendedAtomsIter]
    for atom in frame.atoms:
        if atom.symbol == options.name1 or options.name1 == 'all':
            for atomLst in extendedAtoms:
                for atom2 in atomLst:
                    if options.name2 == "all" or options.name2 == atom2.symbol:
                        if distance(atom.x0, atom2.x0) < boxSize / 2 and distance(atom.x0, atom2.x0) != 0:
                            for i in range(len(bins)):
                                if i * binSize > distance(atom.x0, atom2.x0):
                                    bins[i] += 1
    return bins
def find_closest(location, centroids):
    """Return the item in CENTROIDS that is closest to LOCATION. If two
    centroids are equally close, return the first one.

    >>> find_closest([3, 4], [[0, 0], [2, 3], [4, 3], [5, 5]])
    [2, 3]
    """
    "*** YOUR CODE HERE ***"
    distances=[]
    for pair in centroids:
        distances.append(distance(location, pair))
    for pair in centroids:
        if min(distances)==distance(location, pair):
            return pair
Beispiel #16
0
def find_closest(location, centroids):
    """Return the item in CENTROIDS that is closest to LOCATION. If two
    centroids are equally close, return the first one.

    >>> find_closest([3, 4], [[0, 0], [2, 3], [4, 3], [5, 5]])
    [2, 3]
    """
    "*** YOUR CODE HERE ***"
    min_dis = distance(location, centroids[0])
    min_cen = centroids[0]
    for li in centroids:
        if distance(location, li) < min_dis:
            min_cen, min_dis = li, distance(location, li)
    return min_cen
Beispiel #17
0
 def findPlace(atom, lattice, forbiddenList = []):
     availablePos = range(len(lattice.positions))
     for pos in forbiddenList:
         availablePos.remove(pos)
     if len(availablePos) > 0:
         nn = availablePos[0]
     else: return None
     dist = distance([atom.x, atom.y], lattice.positions[nn].x0)
     
     for posIndex in availablePos:
         pos = lattice.positions[posIndex]
         if distance([atom.x, atom.y], pos.x0) < dist:
             nn = posIndex
             dist = distance([atom.x, atom.y], pos.x0)
     return nn
 def findClosest(self, pos, checkReliable= True, notHere=None):
     dist = -1
     bestb=None
     #~ rpos = [0., 0.]
     
     for b in self.known:
         if notHere is not None and notHere[0] == b.pos[0] and notHere[1] == b.pos[1] :
             continue
         
         d = utils.distance(pos, b.pos)
         if dist == -1:
             dist = d
             bestb = b
             continue
         #~ print b.pos
         if checkReliable:
             if bestb.reliable < b.reliable and random.randint(0, 2) == 0:
                 dist = d
                 bestb = b    
                 continue
                 
         if d < dist+1 and random.randint(0, 2) == 0:
             dist = d
             bestb = b
             
     if bestb is not None:
         return bestb.pos
     return None
def draw_map(centroids, restaurants, ratings):
    """Write a JSON file containing inputs and load a visualization.

    Arguments:
    centroids -- A sequence of positions
    restaurants -- A sequence of restaurants
    ratings -- A dictionary from restaurant names to ratings
    """
    data = []
    locations = set()
    for restaurant in restaurants:
        p = tuple(restaurant_location(restaurant))
        cluster = min(enumerate(centroids), key=lambda v: distance(p, v[1]))[0]
        name = restaurant_name(restaurant)
        rating = ratings[name]
        if p not in locations:
            data.append({
                'x': p[0],
                'y': p[1],
                'weight': rating,
                'name': name,
                'cluster': cluster,
            })
            locations.add(p)
    with open('visualize/voronoi.json', 'w') as f:
        json.dump(data, f)
    load_visualization('voronoi.html')
Beispiel #20
0
 def match(self, atomsLists):
     """Function matches atoms from atomsLists to self.lattice.positions
     @return: match, referenceMatch, errors
     match is list of indices of places for atoms match[atomIndex] = placeIndex
     referenceMatch[atomIndex] = atomIndex on allAtomsList
     errors is a list of (max error, average error)"""
     errors = []
     allAtoms = concatenate(atomsLists)      
     forbiddenPosList = []
     forbiddenAtomsList = [] #we'll need both of this to know which atom is banned
     posCount = len(atomsLists[0])
     match = [0 for _ in range(posCount)]
     referenceMatch = [0 for _ in range(posCount)]
     self._initPosSearch(len(allAtoms))
     
     for _ in range(posCount):
         
         atomIndex, placeIndex = self.matchPos(allAtoms, len(atomsLists)
                                               , forbiddenPosList
                                               , forbiddenAtomsList)
         if not placeIndex is None: 
             forbiddenPosList.append(placeIndex)
         forbiddenAtomsList += [(atomIndex + n * len(atomsLists[0])) % len(allAtoms) 
                                for n in range(len(atomsLists))]
         if not placeIndex is None:
             pos = self.lattice.positions[placeIndex] 
         errors.append(distance(pos.x0, allAtoms[atomIndex].x0))            
         if not placeIndex is None:
             match[atomIndex % len(atomsLists[0])] = placeIndex
         referenceMatch[atomIndex % len(atomsLists[0])] = atomIndex
     return match, referenceMatch, errors
    def work(self):
        lat = self.fort['latitude']
        lng = self.fort['longitude']
        fortID = self.fort['id']
        unit = self.config.distance_unit  # Unit to use when printing formatted distance

        dist = distance(self.position[0], self.position[1], lat, lng)

        # print('[#] Found fort {} at distance {}m'.format(fortID, dist))
        self.logger.info('[#] Found fort {} at distance {}'.format(
            fortID, format_dist(dist, unit)))

        if dist > 10:
            self.logger.info('[#] Need to move closer to Pokestop')
            position = (lat, lng, 0.0)

            if self.config.walk > 0:
                self.stepper._walk_to(self.config.walk, *position)
            else:
                self.api.set_position(*position)

            self.api.player_update(latitude=lat, longitude=lng)
            response_dict = self.api.call()
            self.logger.info('[#] Arrived at Pokestop')
            sleep(1)
            return response_dict

        return None
    def work(self):
        lat = self.fort['latitude']
        lng = self.fort['longitude']
        fortID = self.fort['id']
        unit = self.config.distance_unit  # Unit to use when printing formatted distance

        dist = distance(self.position[0], self.position[1], lat, lng)

        # print('[#] Found fort {} at distance {}m'.format(fortID, dist))
        logger.log('[#] Ditemukan {} jarak {}'.format(
            fortID, format_dist(dist, unit)))

        if dist > 10:
            logger.log('[#] Harus cari Pokestop')
            position = (lat, lng, 0.0)

            if self.config.walk > 0:
                self.stepper._walk_to(self.config.walk, *position)
            else:
                self.api.set_position(*position)

            self.api.player_update(latitude=lat, longitude=lng)
            response_dict = self.api.call()
            logger.log('[#] Sampai di Pokestop')
            sleep(2)
            return response_dict

        return None
Beispiel #23
0
def RandomGraph(nodes=range(10), min_links=2, width=400, height=300,
                                curvature=lambda: random.uniform(1.1, 1.5)):
    """Construct a random graph, with the specified nodes, and random links.
    The nodes are laid out randomly on a (width x height) rectangle.
    Then each node is connected to the min_links nearest neighbors.
    Because inverse links are added, some nodes will have more connections.
    The distance between nodes is the hypotenuse times curvature(),
    where curvature() defaults to a random number between 1.1 and 1.5."""
    g = UndirectedGraph()
    g.locations = {}
    ## Build the cities
    for node in nodes:
        g.locations[node] = (random.randrange(width), random.randrange(height))
    ## Build roads from each city to at least min_links nearest neighbors.
    for i in range(min_links):
        for node in nodes:
            if len(g.get(node)) < min_links:
                here = g.locations[node]
                def distance_to_node(n):
                    if n is node or g.get(node,n): return infinity
                    return distance(g.locations[n], here)
                neighbor = argmin(nodes, distance_to_node)
                d = distance(g.locations[neighbor], here) * curvature()
                g.connect(node, neighbor, int(d))
    return g
        def distance_from_other_agents(neighbors):
            """
                Calculate the distance from other agents and return the list with the preferred action to make

                Args:
                    neighbors (list): The complete list of the agent

                Return:
                    (list): A list of tuple with a structure like [(distance, [action, ...]), ...]
            """
            distances = []
            for (agent_id, agent_type), pos in neighbors:
                if self.id != agent_id:
                    dis_from_other_agent = u.distance(self.position, (self.position[0] + pos[0], self.position[1] + pos[1]))
                    actions = []
                    
                    if pos[0] < 0:
                        actions.append(1)  # GoWest
                    elif pos[0] > 0:
                        actions.append(3)  # GoEast

                    if pos[1] < 0:
                        actions.append(2)  # GoSouth
                    elif pos[1] > 0:
                        actions.append(0)  # GoNorth
                    actions.append(random.randint(0, 3))
                    distances.append((dis_from_other_agent, actions))


            return list(sorted(distances, key=lambda elm: elm[0]))
Beispiel #25
0
 def h(self, node):
     "h function is straight-line distance from a node's state to goal."
     locs = getattr(self.graph, 'locations', None)
     if locs:
         return int(distance(locs[node.state], locs[self.goal]))
     else:
         return infinity
Beispiel #26
0
    def get_fort_in_range(self):
        forts = self.bot.get_forts(order_by_distance=True)

        for fort in forts:
            if 'cooldown_complete_timestamp_ms' in fort:
                self.bot.fort_timeouts[fort["id"]] = fort['cooldown_complete_timestamp_ms']
                forts.remove(fort)

        forts = filter(lambda x: x["id"] not in self.bot.fort_timeouts, forts)

        if len(forts) == 0:
            return None

        fort = forts[0]

        distance_to_fort = distance(
            self.bot.position[0],
            self.bot.position[1],
            fort['latitude'],
            fort['longitude']
        )

        if distance_to_fort <= Constants.MAX_DISTANCE_FORT_IS_REACHABLE:
            return fort

        return None
Beispiel #27
0
	def update(self):
		"""Rysuj tylko to co nie jest zasłonięte przez mgłę."""

		if self._refresh:
			self._refresh = False
			return [(0, 0) + self.surface.get_size()]

		updated = list(self._updated)
		self._updated = []
		_shadow = self._map.getLayer('Shadow')
		if _shadow:
			_shadow = _shadow.getRevealed()

		for field in self._sprites:
			_upd = field.update()
			if _shadow and utils.distance(field.getPos(), _shadow[0]) > _shadow[1]:
				continue

			if _upd:
				updated.extend(_upd)
				field.draw(self.surface)

		if updated:
			self._check = True

		return updated
Beispiel #28
0
def find_closest(location, centroids):
    """Return the centroid in centroids that is closest to location. If
    multiple centroids are equally close, return the first one.

    >>> find_closest([3.0, 4.0], [[0.0, 0.0], [2.0, 3.0], [4.0, 3.0], [5.0, 5.0]])
    [2.0, 3.0]
    """
    # BEGIN Question 3
    "*** REPLACE THIS LINE ***"
    closest_centroid = centroids[0]
    for current_centroid in centroids:
        if min(distance(location, closest_centroid), distance(location, current_centroid)) == distance(location, closest_centroid):
            closest_centroid = closest_centroid
        else:
            closest_centroid = current_centroid
    return closest_centroid
Beispiel #29
0
 def cost(p, k):
     """
     p: source o2o order
     k: target o2o order
     """
     return utils.travel_time(utils.distance(p.target(), k.target())) \
             + utils.part_time(k.num())
Beispiel #30
0
    def evite(self, coup, action, start_positions, state):
        depart = [coup[0], coup[1]]
        cible = [action.target_group.x, action.target_group.y]
        possibles = []

        # On regarde les positions possibles
        for i in range(0, 3):
            for j in range(0, 3):
                position = [depart[0]-1+i, depart[1]-1+j]
                if position not in start_positions:
                    if position[0]<state.width and position[1]<state.height and position[0]>=0 and position[1]>=0:
                        possibles.append(position)

        # Si aucune position possible, le groupe reste sur place
        if len(possibles) == 0:
            return None

        # Sinon on recherche la meilleure position à prendre, en fonction de la cible
        else:
            # On prend la position qui minimise la distance
            # Possiblement améliorable
            pos = None
            distance = 1000
            for position in possibles:
                d = utils.distance(position, cible)
                if d < distance:
                    pos = position
                    distance = d
            coup[3] = pos[0]
            coup[4] = pos[1]
            return coup
Beispiel #31
0
def find_closest(location, centroids):
    """Return the item in CENTROIDS that is closest to LOCATION. If two
    centroids are equally close, return the first one.

    >>> find_closest([3, 4], [[0, 0], [2, 3], [4, 3], [5, 5]])
    [2, 3]
    """
    "*** YOUR CODE HERE ***"

    return min(centroids, key=lambda x: distance(location, x))
Beispiel #32
0
def find_closest(location, centroids):
    """Return the centroid in centroids that is closest to location.
    If multiple centroids are equally close, return the first one.

    >>> find_closest([3.0, 4.0], [[0.0, 0.0], [2.0, 3.0], [4.0, 3.0], [5.0, 5.0]])
    [2.0, 3.0]
    """
    # BEGIN Question 3
    disc = (lambda x: lambda y: distance(x, y))(location)
    return min(centroids, key=disc)
Beispiel #33
0
 def updateCollision(self, duckies, tile_size):
     for duckie in duckies.values():
         if duckie.id == self.id or self.collision_level == 1:
             continue
         if utils.distance(
                 self.pose, duckie.pose
         ) * tile_size < self.length / 2 + duckie.length / 2:
             self.collision_level = 1
             self.max_vel = 0
             print('%s collided!' % self.id)
Beispiel #34
0
def find_closest(location, centroids):
    """Return the centroid in centroids that is closest to location.
    If multiple centroids are equally close, return the first one.

    >>> find_closest([3.0, 4.0], [[0.0, 0.0], [2.0, 3.0], [4.0, 3.0], [5.0, 5.0]])
    [2.0, 3.0]
    """
    # BEGIN Question 3
    "*** YOUR CODE HERE ***"
    return min(centroids, key=lambda x: distance(location, x))
Beispiel #35
0
def find_closest(location, centroids):
    """Return the centroid in centroids that is closest to location.
    If multiple centroids are equally close, return the first one.

    >>> find_closest([3.0, 4.0], [[0.0, 0.0], [2.0, 3.0], [4.0, 3.0], [5.0, 5.0]])
    [2.0, 3.0]
    """
    # BEGIN Question 3
    return min([centroid for centroid in centroids],
               key=lambda x: distance(x, location))
Beispiel #36
0
def find_closest(location, centroids):
    """Return the centroid in centroids that is closest to location.
    If multiple centroids are equally close, return the first one.

    >>> find_closest([3.0, 4.0], [[0.0, 0.0], [2.0, 3.0], [4.0, 3.0], [5.0, 5.0]])
    [2.0, 3.0]
    """
    for centroid in centroids:
        return min(centroids,
                   key=lambda centroid: distance(location, centroid))
 def path_control(self, path, robot_id, color, receive):
     N = len(path)
     for i in range(N-1):
         # 闭环检测部分
         receive.get_info(color, robot_id)
         now_x = receive.robot_info['x']
         now_y = receive.robot_info['y']
         point = [now_x, now_y]
         now_ori = receive.robot_info['ori']
         error = distance(point, path[i+1])
         error_max = distance(path[i], path[i+1])
         # print('error:', error)
         while error > 10:
             p = 1
             orientation_need_now = math.atan2((path[i + 1][1] - now_y), (path[i + 1][0] - now_x))
             theta = now_ori + orientation_need_now
             if error < error_max * self.threshold:
                 if i < N - 2:
                     alpha = math.atan2(path[i + 2][1] - path[i + 1][1], path[i + 2][0] - path[i + 1][0])
                     if orientation_need_now > 0:
                         angle = alpha + (PI - orientation_need_now)
                     else:
                         angle = alpha - (PI + orientation_need_now)
                     if angle > PI:
                         angle = 2 * PI - angle
                     if abs(angle) < self.angle_threshold:
                             p = error / ((self.threshold + self.time_turn) * error_max) * math.log(2)
                             p = math.exp(p) - 1
                     else:
                             p = error / (self.threshold * error_max) * math.log(2)
                             p = math.exp(p) - 1
                 else:
                     p = error / (self.threshold * error_max) * math.log(2)
                     p = math.exp(p) - 1
             vx_now = self.v * math.cos(theta) * p
             vy_now = self.v * math.sin(theta) * p
             self.send.send_msg(robot_id, vx_now, vy_now, 0)
             receive.get_info(color, robot_id)
             now_x = receive.robot_info['x']
             now_y = receive.robot_info['y']
             now_ori = receive.robot_info['ori']
             point = [now_x, now_y]
             error = distance(point, path[i+1])
Beispiel #38
0
 def set_d_a_for_all(self):
     for u, v in self.X.edges_iter():
         if self.get_contact_data(v, u, 'd_a'):
             continue
         dist = utils.distance(self.get_l_a(u), self.get_l_a(v))
         # if no l_a
         if dist < 0: continue
         data = {}
         data['d_a'] = dist
         self.X.set_edge_data(u, v, data)
Beispiel #39
0
    def get_forts_in_range(self):
        forts = self.bot.get_forts(order_by_distance=True)
        forts = filter(lambda fort: fort["id"] not in self.bot.fort_timeouts,
                       forts)
        forts = filter(
            lambda fort: distance(self.bot.position[0], self.bot.position[
                1], fort['latitude'], fort['longitude']) <= Constants.
            MAX_DISTANCE_FORT_IS_REACHABLE, forts)

        return forts
Beispiel #40
0
def find_closest(location, centroids):
    """Return the centroid in centroids that is closest to location. If
    multiple centroids are equally close, return the first one.

    >>> find_closest([3.0, 4.0], [[0.0, 0.0], [2.0, 3.0], [4.0, 3.0], [5.0, 5.0]]
)    [2.0, 3.0]
    """
    # BEGIN Question 3
    "*** REPLACE THIS LINE ***"
    return min([i for i in centroids], key = lambda i: distance(i, location))
Beispiel #41
0
def find_closest(location, centroids):
    """Return the centroid in centroids that is closest to location.
    If multiple centroids are equally close, return the first one.

    >>> find_closest([3.0, 4.0], [[0.0, 0.0], [2.0, 3.0], [4.0, 3.0], [5.0, 5.0]])
    [2.0, 3.0]
    """
    # BEGIN Question 3
    centroid_distance = [[c, distance(location, c)] for c in centroids]
    return min(centroid_distance, key=lambda x: x[1])[0]
Beispiel #42
0
 def nearest2Vertex(self, point):
     min_distance1 = float('inf')
     min_distance2 = float('inf')
     min1_i = None
     min2_i = None
     for i, p in enumerate(self.points):
         dist = utils.distance(p - point)
         if dist < min_distance1:
             min_distance1 = dist
             min1_i = i
     for i, p in enumerate(self.points):
         dist = utils.distance(p - point)
         if dist < min_distance2 and dist > min_distance1:
             min_distance2 = dist
             min2_i = i
     if min2_i < min1_i:
         return min2_i
     else:
         return min1_i
Beispiel #43
0
def find_closest(location, centroids):
    """Return the centroid in `centroids` that is closest to `location`. If two
    centroids are equally close, return the first one.

    >>> find_closest([3.0, 4.0], [[0.0, 0.0], [2.0, 3.0], [4.0, 3.0], [5.0, 5.0]])
    [2.0, 3.0]
    """
    # BEGIN Question 3
    "*** REPLACE THIS LINE ***"
    return min(centroids, key=lambda x: distance(location, x))
Beispiel #44
0
def cost(spawnpoint, cluster, time_threshold):
    distance = utils.distance(spawnpoint.position, cluster.centroid)

    min_time = min(cluster.min_time, spawnpoint.time)
    max_time = max(cluster.max_time, spawnpoint.time)

    if max_time - min_time > time_threshold:
        return float('inf')

    return distance
Beispiel #45
0
def find_closest(location, centroids):
    """Return the centroid in centroids that is closest to location.
    If multiple centroids are equally close, return the first one.

    >>> find_closest([3.0, 4.0], [[0.0, 0.0], [2.0, 3.0], [4.0, 3.0], [5.0, 5.0]])
    [2.0, 3.0]
    """
    # BEGIN Question 3
    dists = [distance(location, x) for x in centroids]
    return centroids[dists.index(min(dists))]
Beispiel #46
0
 def draw_contours(filtered_contours, original):
     for cnt in filtered_contours:
         (a, b), radius = cv2.minEnclosingCircle(cnt)
         center = (int(a), int(b))
         cv2.circle(original, center, int(radius), (255, 255, 0), 5)
         distance = utils.distance(constants.FOCAL_LENGTHS['lifecam'],
                                   constants.GAME_PIECE_SIZES['fuel']['diameter'],
                                   radius * 2)
         cv2.putText(original, str(int(distance * 100)), (int(a), int(b + 2 * radius)), cv2.FONT_HERSHEY_SIMPLEX, 2,
                     (0, 0, 0), 3)
Beispiel #47
0
    def mouseEvent(self, _event, _pos=None):
        """Blokuje zdarzenia na polach których nie widać."""

        if not _pos:
            return True

        if not utils.distance(self._last[0], _pos) <= self._last[1]:
            return False

        return True
Beispiel #48
0
    def get_next_move(self, player, things):
        if self.start_t is None:
            self.start_t = S.tick

        result = None
        g = self.map
        current = g[player.position]
        winner = None

        if player.life < 70 and random.random() < 0.3:
            result = ('heal', player)
        #elif player.life < 40:
        #        result = ('heal', player)
        else:
            #print "evaluating", self, self.position
            moves = utils.possible_moves(player, things)
            random.shuffle(moves)
            for pos in moves:
                #print pos, g[pos], current
                if g[pos] < current:
                    winner = pos

            if winner:
                result = ('move', winner)
            else:
                target = closest(
                    player,
                    [x for x in things.values() if isinstance(x, Zombie)])
                if target is not None:
                    if utils.distance(target,
                                      player) <= player.weapon.max_range:
                        result = ('attack', target)

        # if result is None:
        #     if random.random() < 0.25:
        #         moves = utils.possible_moves(self, things)
        #         if moves:
        #             pos = random.choice(moves)
        #             result = ('move', pos)

        if result is None:
            result = ('heal', player)

        if result[0] in ('attack', 'move'):
            S.last_action = S.tick

        if S.tick - S.last_action > self.wait:
            S.next_strategy = self.next_strategy
            S.last_action = S.tick

        if S.tick - self.start_t > self.timeout:
            S.next_strategy = self.next_strategy
            S.last_action = S.tick

        return result
Beispiel #49
0
    def fl(self, l, user_id):
        # if input coordinates is not within valid range
        lloc = l
        #print str(lloc)
        while not valid_coord(lloc):
            if lloc[0] > 90:
                lloc = (lloc[0] - 180, lloc[1])
            elif lloc[0] < -90:
                lloc = (lloc[0] + 180, lloc[1])
            if lloc[1] > 180:
                lloc = (lloc[0], lloc[1] - 360)

            elif lloc[1] < -180:
                lloc = (lloc[0], lloc[1] + 360)

        #if not valid_coord(l):
        #return 63700 # circumference of earth x 10
        res = 0.0

        # this part is D(l, L, P)
        #print 'fl'
        for l_k, p_k in self.iter_contacts_inf():
            if l_k is not None:
                dist = utils.distance(lloc, l_k)
                j = self.qntl_map(p_k)
                if self.stgrEdges[dist] > 0 and self.actEdges[j][dist] > 0:
                    p = float(self.actEdges[j][dist]) / self.stgrEdges[dist]
                else:
                    p = 0
                #p = self.p_inf(j, dist)
                #print 'p'
                #print p
                #print 'p'
                #print p
                #print 'logp'
                #print np.log(p)
                if p > 0:
                    res += np.log(p)
            # Add the next 7 lines to add the denominator back into the FL equation
            #try:
            #p2 = self.allActEdges[dist]/self.stgrEdges[dist]
            #print p2
            #except Exception as e:
            #print e
            #p2 = 0
            #res -= np.log(1 - p2)
        # pStgrs(lloc)
        # Add the next 2 lines to add the pStgrs back into the FL equation
        #if self.method == 'default':
        #return res + self.pStgrs(lloc, user_id)
        #print 'res: '
        #print res
        if res == 0.0:
            return 1000000
        return -res
Beispiel #50
0
  def get_improvement_of_swapping(self, trip, first, second):
    i = min(first, second)
    j = max(first, second)

    lat = 2
    lon = 3
    weight = 4

    # new_trip = trip[:]
    # old = utils.weighted_trip_length(pd.DataFrame(new_trip)[[lat, lon]], list(pd.DataFrame(new_trip)[weight]))
    # temp = new_trip[i]
    # new_trip[i] = new_trip[j]
    # new_trip[j] = temp
    # new = utils.weighted_trip_length(pd.DataFrame(new_trip)[[lat, lon]], list(pd.DataFrame(new_trip)[weight]))
    # return new - old

    # set up weights
    weight_diff = trip[i][weight] - trip[j][weight]
    cum_weight_before_i = np.sum(trip[i:][:, weight]) + utils.SLEIGH_WEIGHT
    cum_weight_before_j = np.sum(trip[j:][:, weight]) + utils.SLEIGH_WEIGHT
    weight_i = trip[i][weight]
    weight_j = trip[j][weight]

    # set up locations
    before_i = tuple(trip[i-1][[lat, lon]]) if i > 0 else utils.NORTH_POLE
    before_j = tuple(trip[j-1][[lat, lon]]) if j > 0 else utils.NORTH_POLE
    at_i = tuple(trip[i][[lat, lon]])
    at_j = tuple(trip[j][[lat, lon]])
    after_i = tuple(trip[i+1][[lat, lon]]) if i < len(trip)-1 else utils.NORTH_POLE
    after_j = tuple(trip[j+1][[lat, lon]]) if j < len(trip)-1 else utils.NORTH_POLE

    if i+1 == j:
      # swap adjacent locations is simplified
      improvement = self.get_cost_of_swapping_adjacent(before_i, at_i, at_j, after_j,
          cum_weight_before_i, weight_i, weight_j)
    else:
      # cost of the old segments around i/j
      old_i = self.get_cost_of_tour_of_three(before_i, at_i, after_i, cum_weight_before_i, weight_i)
      old_j = self.get_cost_of_tour_of_three(before_j, at_j, after_j, cum_weight_before_j, weight_j)

      # cost of the new segments around i/j
      new_j = self.get_cost_of_tour_of_three(before_i, at_j, after_i, cum_weight_before_i, weight_j)
      new_i = self.get_cost_of_tour_of_three(before_j, at_i, after_j, cum_weight_before_j + weight_diff, weight_i)

      # cost difference from weight between i and j (sub-trip between i+1..j-1)
      distance = 0
      for k in range(i+1, j-1):
        distance += utils.distance(
            tuple(trip[k][[lat, lon]]),
            tuple(trip[k+1][[lat, lon]])
            )
      diff = distance * weight_diff
      improvement = new_j + new_i - old_j - old_i + diff

    return improvement
Beispiel #51
0
def find_closest(location, centroids):
    """Return the centroid in centroids that is closest to location. If
    multiple centroids are equally close, return the first one.

    >>> find_closest([3.0, 4.0], [[0.0, 0.0], [2.0, 3.0], [4.0, 3.0], [5.0, 5.0]])
    [2.0, 3.0]
    """
    # BEGIN Question 3
    i = 0
    min_dist = distance(location, centroids[0])
    dist = 0.0
    closest_loc = centroids[0]
    while i < len(centroids):
        dist = distance(location, centroids[i])
        if dist < min_dist:
            min_dist = dist
            closest_loc = centroids[i]
        i += 1

    return closest_loc
Beispiel #52
0
 def line_control(self, now_x, now_y, now_ori, path, i, N, target_x, target_y, infos=None, k1=10, k2=10, v_obstacle_max=400, rr=100, color="blue", robot_id=0):
     point_now = [now_x, now_y]
     error = distance(point_now, path[i+1])
     orientation_need_now = math.atan2((path[i + 1][1] - now_y), (path[i + 1][0] - now_x))
     theta = now_ori - orientation_need_now
     if distance(point_now, [target_x, target_y]) > 30:
         thres = 20
         if i == N-2:
             thres = 7
         if error > thres:
             vx_now = self.v * math.cos(theta)
             vy_now = self.v * math.sin(theta)
             return vx_now, vy_now, False
         else:
             return 0, 0, True
     else:
         if error > 7:
             return self.v * math.cos(theta) * self.p, self.v * math.sin(theta) * self.p, False
         else:
             return 0, 0, True
Beispiel #53
0
def find_closest(location, centroids):
    """Return the centroid in centroids that is closest to location.
    If multiple centroids are equally close, return the first one.

    >>> find_closest([3.0, 4.0], [[0.0, 0.0], [2.0, 3.0], [4.0, 3.0], [5.0, 5.0]])
    [2.0, 3.0]
    """
    # BEGIN Question 3
    "*** YOUR CODE HERE ***"
    c=[]
    a=distance(location, centroids[0])
    for i in centroids:
        b=distance(location,i)
        c.append(b)
    b=min(c)
    d=[]
    for i in range(0,len(c)):
        if c[i] == b:
            d.append(centroids[i])
    return d[0]
Beispiel #54
0
    def clicked(self, _scene, _hero):
        """Akcja wywoływana gdy naciśnie się na pole.
	_scene - aktualna scena."""

        if utils.distance(_hero.getGrid()[:2], self._grid[:2]) > 1:
            return

        while self._items and len(_hero.inventory) < 15:
            _scene.inventory.add(self._items.pop())

        self._refresh = True
Beispiel #55
0
 def find_enemy(self, rat, colony, model):
     if config.use_index:
         enemies = model.map.get_neighbours(rat, config.sight_distance)
         for enemy in enemies:
             dist = utils.distance(enemy.rect.topleft, rat.rect.topleft)
             if dist <= config.sight_distance:
                 for other_colony in model.colonies:
                     if enemy in other_colony.get_rats():
                         return (enemy, other_colony, dist)
     else:
         for other_colony in model.colonies:
             if other_colony == colony:
                 continue
             else:
                 for enemy in other_colony.get_rats():
                     dist = utils.distance(enemy.rect.topleft,
                                           rat.rect.topleft)
                     if dist <= config.sight_distance:
                         return (enemy, other_colony, dist)
     return None
Beispiel #56
0
def find_closest(location, centroids):
    """Return the centroid in centroids that is closest to location.
    If multiple centroids are equally close, return the first one.

    >>> find_closest([3.0, 4.0], [[0.0, 0.0], [2.0, 3.0], [4.0, 3.0], [5.0, 5.0]])
    [2.0, 3.0]
    """
    # takes in a list of centoirds, and then accesses each pair, and calculates the
    # distance between each pair and location, and then finds the pair with the min
    # distance and returns that pair
    return min(centroids, key=lambda pair: distance(location, pair))
Beispiel #57
0
 def help_critical_teammates(self, things, players):
     critical = [
         player for player in players
         if player.life > 0 and player.status == 'critical'
     ]
     if critical:
         closest_critical = closest(self, critical)
         if distance(self, closest_critical) < core.HEALING_RANGE:
             self.status = u'heal ' + closest_critical.name
             return 'heal', closest_critical
     return None, None
	def assign(self):
		"""
		Assigning every point in the dataset to the closest center.

		Returns:
			mapping (list) : tuples of the form (point, center)
		"""
		mapping = [(i, sorted([(j, distance(self.data[i], self.data[j])) for j in self.centers], key=lambda x: x[1], 
						   reverse=False)[0][0]) for i in range(len(self.data))]
		
		return mapping
def find_closest(location, centroids):
    """Return the centroid in centroids that is closest to location.
    If multiple centroids are equally close, return the first one.

    >>> find_closest([3.0, 4.0], [[0.0, 0.0], [2.0, 3.0], [4.0, 3.0], [5.0, 5.0]])
    [2.0, 3.0]
    """
    # BEGIN Question 3
    min_key = key_of_min_value(
        dict(enumerate([distance(location, c) for c in centroids])))
    return centroids[min_key]
Beispiel #60
0
def Astar(start, goal, map):
    path = []
    searching = True
    current = start
    openlist = []
    pathlist = []
    searchedlist = []
    #initialization
    nodes_expanded = 1
    searchedlist.append(start)
    for x in map[start]:
        openlist.append(x)
        pathlist.append([start])
    # start searching
    i = 0
    while (searching):
        i = i + 1
        #print("iteration ", i, "openlist:")
        #print(openlist)
        #print(pathlist)
        f = math.inf
        next = None
        g = 0
        # find the next node
        for x in openlist:
            if (x[X], x[Y]) in searchedlist: continue
            temp_f = x[G] + ut.distance(
                (x[X], x[Y]), goal)  # f(n) = g(n) + h(n)
            if temp_f < f:
                # print("search x", x, "f(n)=",temp_f) #TODO: delete
                next = x.copy()
                f = temp_f
        idx = openlist.index(next)
        openlist.pop(idx)
        path = pathlist[idx].copy()
        pathlist.pop(idx)
        # if the next node is the goal, then we have found the path
        if next[X] == goal[X] and next[Y] == goal[Y]:
            nodes_expanded = nodes_expanded + 1
            path.append((next[X], next[Y]))
            print("A* search expanded ", nodes_expanded, " nodes")
            return (path, next[G], nodes_expanded)
        # open next node
        nodes_expanded = nodes_expanded + 1
        try:
            for x in map[(next[X], next[Y])]:
                if (x[X], x[Y]) in searchedlist: continue
                openlist.append([x[X], x[Y], x[G] + next[G]])
                t = path.copy()
                t.append((next[X], next[Y]))
                pathlist.append(t)
                searchedlist.append((next[X], next[Y]))
        except:
            continue