def connected_to(self, res, cutoff=3.0): """ Determine if another residue is connected to this residue, returns 0 if res is not connected to self, returns 1 if connection is going from 5' to 3' and returns -1 if connection is going from 3' to 5' :param res: another residue :type res: Residue object """ # 5' to 3' o3_atom = self.get_atom("O3'") p_atom = res.get_atom("P") if o3_atom and p_atom: if util.distance(o3_atom.coords, p_atom.coords) < cutoff: return 1 # 3' to 5' p_atom = self.get_atom("P") o3_atom = res.get_atom("O3'") if o3_atom and p_atom: if util.distance(o3_atom.coords, p_atom.coords) < cutoff: return -1 return 0
def destructor_action(self, bot): target = self.nearest_object(bot, self.walls + self.enemy_bots ) if target: target_distance = util.distance( bot.getX(), bot.getY(), bot.getSize(), target.getX(), target.getY(), target.getSize() ) if target_distance == 1 : objects = [b for b in self.objects_in_direction(bot,'t') if b in self.bots and b.getOwner() != self.playerID()] if len(objects) >= 1: self.my_move(bot,'t') if bot.getHealth() < (bot.getMaxHealth()) and bot.getBuildRate() > 0: bot.heal(bot) #bot.talk( "target id: %s (%s, %s) distance: %i" % (target.getId(), target.getX(), target.getY(), target_distance) ) elif( target_distance <= bot.getRange() + 1 ): bot.talk( "ATK: target id: %s (%s, %s) distance: %i" % (target.getId(), target.getX(), target.getY(), target_distance) ) bot.attack(target) else: heal_target = self.nearest_injured_ally(bot) if heal_target: heal_target_distance = util.distance( bot.getX(), bot.getY(), bot.getSize(), heal_target.getX(), heal_target.getY(), heal_target.getSize() ) if( target_distance <= bot.getRange() + 1 and bot.getBuildRate() > 0 ): bot.talk( "HEAL: target id: %s (%s, %s) distance: %i" % (heal_target.getId(), heal_target.getX(), healt_target.getY(), heal_target_distance) ) bot.heal(heal_target) if( target_distance > 1 ): if not self.move_towards(bot, target): pass#self.move_random(bot)
def _render_look_mode(self, console, origin): x, y = origin def render_entity(ent): xx, yy = ent.component('Position').get() ent_origin = (xx + x, yy + y) ent.component('Render').render(ent, console, ent_origin) self._map.render(console, origin) mvd = self._map.max_view_distance() player = self._map.entity('PLAYER') if mvd is None or player is None: self._map.entities().with_all_components(['Render', 'Item', 'Position'])\ .transform(render_entity) self._map.entities().without_components(['Item']).with_all_components(['Render', 'Position'])\ .transform(render_entity) else: import util player_pos = player.position().get() self._map.entities().with_all_components(['Render', 'Item', 'Position'])\ .where(lambda e : util.distance(player_pos, e.position().get()) <= mvd)\ .transform(render_entity) self._map.entities().without_components(['Item']).with_all_components(['Render', 'Position'])\ .where(lambda e : util.distance(player_pos, e.position().get()) <= mvd)\ .transform(render_entity) player = self._map.entity('PLAYER') passmap = self._map.passability_map_for(player) path = find_path(passmap, player.component('Position').get(), self._cursor_pos) for xx, yy in path: console.bg[x + xx][y + yy] = tcod.orange xx, yy = self._cursor_pos console.bg[x + xx][y + yy] = tcod.red
def detect_position_on_staff(self, staff, blob): distances_from_lines = [] x, y = blob.pt for line_no, line in enumerate(staff.lines_location): distances_from_lines.append( (2 * line_no, distance((x, y), (x, line)))) # Generate three upper lines for line_no in range(5, 8): distances_from_lines.append( (2 * line_no, distance( (x, y), (x, staff.min_range + line_no * staff.lines_distance)))) # Generate three lower lines for line_no in range(-3, 0): distances_from_lines.append( (2 * line_no, distance( (x, y), (x, staff.min_range + line_no * staff.lines_distance)))) distances_from_lines = sorted(distances_from_lines, key=lambda tup: tup[1]) # Check whether difference between two closest distances is within MIDDLE_SNAPPING value specified in config.py if distances_from_lines[1][1] - distances_from_lines[0][ 1] <= NOTE_PITCH_DETECTION_MIDDLE_SNAPPING: # Place the note between these two lines return int( (distances_from_lines[0][0] + distances_from_lines[1][0]) / 2) else: # Place the note on the line closest to blob's center return distances_from_lines[0][0]
def validate(tcn, use_cuda, arguments): # Run model on validation data and log results data_loader = DataLoader(validation_set, batch_size=256, shuffle=False, pin_memory=use_cuda) correct_with_margin = 0 correct_without_margin = 0 for minibatch, _ in data_loader: frames = Variable(minibatch, volatile=True) if use_cuda: frames = frames.cuda() anchor_frames = frames[:, 0, :, :, :] positive_frames = frames[:, 1, :, :, :] negative_frames = frames[:, 2, :, :, :] anchor_output = tcn(anchor_frames) positive_output = tcn(positive_frames) negative_output = tcn(negative_frames) d_positive = distance(anchor_output, positive_output) d_negative = distance(anchor_output, negative_output) assert(d_positive.size()[0] == minibatch.size()[0]) correct_with_margin += ((d_positive + arguments.margin) < d_negative).data.cpu().numpy().sum() correct_without_margin += (d_positive < d_negative).data.cpu().numpy().sum() message = "Validation score correct with margin {with_margin}/{total} and without margin {without_margin}/{total}".format( with_margin=correct_with_margin, without_margin=correct_without_margin, total=len(validation_set) ) logger.info(message)
def initialize(self): setupGraphs(self) # inits self.graph self.verbose = True self.bots = set() self.defenders = [] self.attackers = [] self.flagGetters = [] self.scouts = [] teamPosition, isTeamCorner = self.getStrategicPostion(self.game.team.flag.position) teamPosition = self.level.findNearestFreePosition(teamPosition) teamDirs = self.getDefendingDirs(teamPosition) enemyPosition, isEnemyCorner = self.getStrategicPostion(self.game.enemyTeam.flagScoreLocation) enemyPosition = self.level.findNearestFreePosition(enemyPosition) enemyDirs = self.getDefendingDirs(enemyPosition) for i, bot_info in enumerate(self.game.bots_available): bot = Bot(bot_info, self) if i < self.numOfDefenders: self.defenders.append(bot) elif self.numOfDefenders <= i < self.numOfFlagGetters + self.numOfDefenders: self.flagGetters.append(bot) elif i %3 == 0 or len(self.attackers) < 2: self.attackers.append(bot) elif i %3 == 1: self.defenders.append(bot) else: self.flagGetters.append(bot) #TODO: priority decided based on distance teamPriority = 1 if distance(self.level.findRandomFreePositionInBox(self.game.team.botSpawnArea), teamPosition) < 25 else 0 self.defendingGroup = Squad(self.defenders, Goal(Goal.DEFEND, teamPosition, isTeamCorner, priority=teamPriority, graph=self.graph, dirs=teamDirs), commander=self) enemyPriority = 1 if distance(self.level.findRandomFreePositionInBox(self.game.team.botSpawnArea), enemyPosition) < 25 else 0 self.attackingGroup = Squad(self.attackers, Goal(Goal.DEFEND, enemyPosition, isEnemyCorner, priority=enemyPriority, graph=self.graph, dirs=[(self.game.enemyTeam.flagScoreLocation - enemyPosition, 1)]), commander=self) self.flagGroup = Squad(self.flagGetters, Goal(Goal.GETFLAG, None, None, graph=self.graph)) self.squads = [self.defendingGroup, self.attackingGroup,self.flagGroup]
def make_one_arc(P0, T0, P2, T2, P): ''' Construct one rational Bezier conic arc. Since w1 can be negative or P1 infinite, this algorithm handles any conic arc except a full ellipse. It is thus adequate for parabolic and hyperbolic arcs, and for elliptical arcs for which w1 > 0 and whose sweep angle is not too large. Source: The NURBS Book (2nd Ed.), Pg. 314. ''' V02 = P2 - P0 try: P1 = util.intersect_3D_lines(P0, T0, P2, T2) V1P = P - P1 Q = util.intersect_3D_lines(P1, V1P, P0, V02) a = np.sqrt(util.distance(P0, Q) / util.distance(Q, P2)) u = a / (1.0 + a) num = ((1.0 - u)**2 * np.dot(P - P0, P1 - P) + u**2 * np.dot(P - P2, P1 - P)) den = 2.0 * u * (1.0 - u) * np.dot(P1 - P, P1 - P) w1 = num / den except util.ParallelLines: # infinite control point Q = util.intersect_3D_lines(P, T0, P0, V02) a = np.sqrt(util.distance(P0, Q) / util.distance(Q, P2)) u = a / (1.0 + a) b = 2.0 * u * (1 - u) b = util.distance(P, Q) * (1.0 - b) / b P1 = b * util.normalize(T0) w1 = 0.0 return P1, w1
def checkTerrain(self, c): #Confirm current region c.resetRegion() if c.region is None: for r in self.regions: dist = util.distance(c.precisePos, r.pos) if dist <= MAP_REGION_SIZE: c.region = r break #Check for Fortress for i in self.structures: sTeam = i.team cTeam = c.team + 1 if isinstance(i, mapstructure.Fortress) and (sTeam == cTeam): dist = util.distance(c.precisePos, i.precisePos) if (dist <= i.triggerSize): c.currTerrain = FORTRESS return #Check all terrain circles in current region for i in c.region.terrainMasterList: circle = i[0] terrainType = i[1] dist = util.distance(c.precisePos, circle[0]) if dist <= circle[1]: terrainType = self.terrainBasedOnWinter(terrainType, c) c.currTerrain = terrainType return c.currTerrain = self.terrainBasedOnWinter(PLAINS, c)
def constrain_points(points, num_points=DEFAULT_MAX_SIGNAL_POINTS, already_sorted=False): if not already_sorted: points.sort() if len(points) > num_points: while len(points) > num_points: min_dist = None min_dist_index = -1 for i in range(len(points) - 1): distance_candidate = distance(points[i], points[i + 1]) if not min_dist or distance_candidate < min_dist: min_dist = distance_candidate min_dist_index = i points.pop(min_dist_index) elif len(points) < num_points: while num_points > len(points) > 1: max_dist = None max_dist_index = -1 x, y = None, None for i in range(len(points) - 1): distance_candidate = distance(points[i], points[i + 1]) if not max_dist or distance_candidate > max_dist: max_dist = distance_candidate max_dist_index = i x = (points[i][0] + points[i + 1][0]) / 2 y = (points[i][1] + points[i + 1][1]) / 2 points.insert(max_dist_index, (x, y))
def test_case(self, start_pose, end_pose, cost4, cost8): """ Run one planning test and print the results. """ print("") msg = ("Testing ({}, {}) -> ({}. {})\n\t4-connected optimal: " + "{}\n\t8-connected optimal: {}") print( msg.format(start_pose.pose.position.x, start_pose.pose.position.y, end_pose.pose.position.x, end_pose.pose.position.y, cost4, cost8)) path_msg = self.request_plan(start_pose, end_pose) if path_msg is None: print("Planner service failed to return a plan.") elif len(path_msg.plan.poses) == 0: if cost8 == float('inf'): print("Correct: empty plan for unreachable goal.") else: print("Error: empty plan.") else: self.path_pub.publish(path_msg.plan) cost = self.plan_cost(path_msg.plan, start_pose, end_pose) if util.distance(path_msg.plan.poses[0], start_pose) > .01: print("Path doesn't start at the start location!") print path_msg.plan.poses[0], start_pose if util.distance(path_msg.plan.poses[-1], end_pose) > .1: print("Path doesn't end at the goal location!") print("Path cost: {:.2f}".format(cost))
def cross_validation2(T, y): """Use Cross Validation (leave-one-out) to select features. Args: T: feature statistics list y: labels """ from sklearn.model_selection import LeaveOneOut y = np.array(y) judge = list() T_principle_index = np.array([0, 18, 43]) for train_index, valid_index in LeaveOneOut().split(T): T_train = T[train_index] T_valid = T[valid_index] y_train = y[train_index] T_train, mean, std = feature.normalize(T_train) T_principle = T_train.T[T_principle_index].T C = gen_center(T_principle, y_train) dist = util.distance(T_principle, C) ts = threshold(dist, y_train) T_valid = (T_valid - mean) / std dist_valid = util.distance(T_valid.T[T_principle_index].T, C) if dist_valid[0] < ts: judge.append(1) else: judge.append(0) return np.array(judge)
def find_final_pos(self, s, t): k = (s.y - t.y) / (s.x - t.x) #c 1.225 bb = s.y - k * s.x #c 575.5 a = k**2 + 1 #c 2.500625 b = -2 * s.x - 2 * k * s.x * k #c -302.575625 c = s.x * s.x + (k * s.x)**2 - 1600 #c 7552.912 #print(a,b,c) x = (-b + math.sqrt(b * b - 4 * a * c)) / (2 * a) xx = (-b - math.sqrt(b * b - 4 * a * c)) / (2 * a) y = x * k + bb yy = xx * k + bb d1 = util.distance((x, y), (t.x, t.y)) d2 = util.distance((xx, yy), (t.x, t.y)) if d2 > d1: print("hahah") x = xx y = yy #print(x,y,x,k,b) return ((x, y))
def get_area(self): a = distance(p1, p2) b = distance(p1, p3) c = distance(p2, p3) s = (a + b + c) / 2.0 return math.sqrt(s * (s - a) * (s - b) * (s - c))
def connected_to(self, res, cutoff=3.0): """ Determine if another residue is connected to this residue, returns 0 if res is not connected to self, returns 1 if connection is going from 5' to 3' and returns -1 if connection is going from 3' to 5' :param res: another residue :param cutoff: distance to be considered connected, default: 3 Angstroms :type res: Residue :type cutoff: int :rtype: int """ # 5' to 3' o3_atom = self.get_atom("O3'") p_atom = res.get_atom("P") if o3_atom and p_atom: if util.distance(o3_atom.coords, p_atom.coords) < cutoff: return 1 # 3' to 5' p_atom = self.get_atom("P") o3_atom = res.get_atom("O3'") if o3_atom and p_atom: if util.distance(o3_atom.coords, p_atom.coords) < cutoff: return -1 return 0
def get_removal_bnd_curve(p, U, Pw, u, r, s): ''' Let ur be an interior knot of a pth degree nonrational curve, C(u), u_r != u_(r+1), and denote the multiplicity of ur by s, i.e., u_(r-s+j) = u_r for j=1,...,s. Let Ch(u) denote the curve obtained by removing one occurence of ur. After removal, Ch(u) differs from C(u) by Br. Source: The NURBS Book (2nd Ed.), Pg. 428. ''' o = p + 1 first, last = r - p, r - s off = first - 1 tmp = np.zeros((last - off + 2, 4)) tmp[0], tmp[last - off + 1] = Pw[off], Pw[last + 1] i, j = first, last ii, jj = 1, last - off while j - i > 0: alfi = (u - U[i]) / (U[i + o] - U[i]) alfj = (u - U[j]) / (U[j + o] - U[j]) tmp[ii] = (Pw[i] - (1.0 - alfi) * tmp[ii - 1]) / alfi tmp[jj] = (Pw[j] - alfj * tmp[jj + 1]) / (1.0 - alfj) i += 1 ii += 1 j -= 1 jj -= 1 if j - i < 0: Br = util.distance(tmp[ii - 1], tmp[jj + 1]) else: alfi = (u - U[i]) / (U[i + o] - U[i]) Br = util.distance(Pw[i], alfi * tmp[ii + 1] + (1.0 - alfi) * tmp[ii - 1]) return Br
def createTerritoryForStructure(self, s): for i in range(360 / TERRITORY_DEGREES_PER_DOT): deg = TERRITORY_DEGREES_PER_DOT * i pos = degreesToPoint(deg, s.territorySize, s.precisePos) if (pos[0] < 0) or (pos[0] > self.map.mapSize[0]) or ( pos[1] < 0) or (pos[1] > self.map.mapSize[1]): continue checker = True contested = False for t in self.structures: if (s == t) or t.team == 0: continue if s.team == t.team: if util.distance(t.precisePos, pos) <= t.territorySize: checker = False break else: if util.distance(t.precisePos, pos) <= t.territorySize: contested = True if checker: s.territoryPoints.append([pos, contested])
def findMeetpunt(self): # logger = logging.getLogger(__name__) if self.hacc > 25: # logger.debug('Cannot assign meting %s to a meetpunt, horizontal accuracy (%d) is too high' %(self, self.hacc)) return None else: within_range = [] for mp in Meetpunt.objects.all(): if util.is_in_range(self, mp, 25): within_range.append(mp) if len(within_range) == 0: mp = Meetpunt() mp.latitude = self.latitude mp.longitude = self.longitude mp.save() return mp # log mp created and assigned elif len(within_range) == 1: return within_range[0] else: closest = None for mp in within_range: if closest == None: closest = mp else: if util.distance(self, mp) < util.distance(self, closest): closest = mp return closest
def _render(self, console, origin): x, y = origin def render_entity(ent): xx, yy = ent.component('Position').get() ent_origin = (xx + x, yy + y) ent.component('Render').render(ent, console, ent_origin) self._map.render(console, origin, None if self._has_focus else tcod.gray) mvd = self._map.max_view_distance() player = self._map.entity('PLAYER') if mvd is None or player is None: self._map.entities().with_all_components(['Render', 'Item', 'Position'])\ .transform(render_entity) self._map.entities().without_components(['Item']).with_all_components(['Render', 'Position'])\ .transform(render_entity) else: import util player_pos = player.position().get() self._map.entities().with_all_components(['Render', 'Item', 'Position'])\ .where(lambda e : util.distance(player_pos, e.position().get()) <= mvd)\ .transform(render_entity) self._map.entities().without_components(['Item']).with_all_components(['Render', 'Position'])\ .where(lambda e : util.distance(player_pos, e.position().get()) <= mvd)\ .transform(render_entity)
def initialize(self): setupGraphs(self) # inits self.graph self.verbose = True self.bots = set() self.defenders = [] self.attackers = [] self.flagGetters = [] self.scouts = [] teamPosition, isTeamCorner = self.getStrategicPostion( self.game.team.flag.position) teamPosition = self.level.findNearestFreePosition(teamPosition) teamDirs = self.getDefendingDirs(teamPosition) enemyPosition, isEnemyCorner = self.getStrategicPostion( self.game.enemyTeam.flagScoreLocation) enemyPosition = self.level.findNearestFreePosition(enemyPosition) enemyDirs = self.getDefendingDirs(enemyPosition) for i, bot_info in enumerate(self.game.bots_available): bot = Bot(bot_info, self) if i < self.numOfDefenders: self.defenders.append(bot) elif self.numOfDefenders <= i < self.numOfFlagGetters + self.numOfDefenders: self.flagGetters.append(bot) elif i % 3 == 0 or len(self.attackers) < 2: self.attackers.append(bot) elif i % 3 == 1: self.defenders.append(bot) else: self.flagGetters.append(bot) #TODO: priority decided based on distance teamPriority = 1 if distance( self.level.findRandomFreePositionInBox( self.game.team.botSpawnArea), teamPosition) < 25 else 0 self.defendingGroup = Squad(self.defenders, Goal(Goal.DEFEND, teamPosition, isTeamCorner, priority=teamPriority, graph=self.graph, dirs=teamDirs), commander=self) enemyPriority = 1 if distance( self.level.findRandomFreePositionInBox( self.game.team.botSpawnArea), enemyPosition) < 25 else 0 self.attackingGroup = Squad( self.attackers, Goal(Goal.DEFEND, enemyPosition, isEnemyCorner, priority=enemyPriority, graph=self.graph, dirs=[(self.game.enemyTeam.flagScoreLocation - enemyPosition, 1)]), commander=self) self.flagGroup = Squad( self.flagGetters, Goal(Goal.GETFLAG, None, None, graph=self.graph)) self.squads = [ self.defendingGroup, self.attackingGroup, self.flagGroup ]
def _sugar_diff(self, state): diff_1 = util.distance(self.sugars[0], state.sugars[0]) + \ util.distance(self.sugars[1], state.sugars[1]) diff_2 = util.distance(self.sugars[1], state.sugars[0]) + \ util.distance(self.sugars[0], state.sugars[1]) if diff_1 > diff_2: diff_1 = diff_2 return diff_1
def do_move_action(self, game, action): # if action[0] == 1 and self.shoot_status['cd'] <= 0: # self.shoot_status['fire'] = False # self.shoot_status['angle'] = action[1] # existence = (self.status['bullet_penetration'] - 1) * 5 + 20 # bullet = Bullet(self.position['x'], self.position['y'], existence, self.status['bullet_damage'], { # 'x': math.cos(action[1]) * (10 + self.status['bullet_speed']), # 'y': math.sin(action[1]) * (10 + self.status['bullet_speed']) # }, self.id) # game.map_info['bullets'].append(bullet) # self.shoot_status['cd'] = 50 * math.log(self.status['bullet_reload'] + 1, 10) # else: # self.shoot_status['fire'] = False self.move_direction = { 'up': False, 'down': False, 'left': False, 'right': False } type_num = np.argwhere(action == 1) if type_num == 1: self.move_direction['up'] = True elif type_num == 2: self.move_direction['down'] = True elif type_num == 3: self.move_direction['left'] = True elif type_num == 4: self.move_direction['right'] = True elif type_num == 5: self.move_direction['up'] = True self.move_direction['left'] = True elif type_num == 6: self.move_direction['up'] = True self.move_direction['right'] = True elif type_num == 7: self.move_direction['down'] = True self.move_direction['left'] = True elif type_num == 8: self.move_direction['down'] = True self.move_direction['right'] = True target = None angle = -1 # find the closest stuff and shoot for stuff in game.map_info['stuffs']: dist = util.distance(self.position, stuff.position) if target: if dist < 200 and util.distance(self.position, target.position) > dist: angle = util.angle(self.position, stuff.position) target = stuff else: if dist < 200: angle = util.angle(self.position, stuff.position) target = stuff if target: self.do_shoot_action(game, [1, angle])
def findMoveTarget(self, unit): enemies = [i for i in self.bots if i.getOwner() == 0 and self.playerID() == 1 and i.getPartOf() == 0 or i.getOwner() == 1 and self.playerID() == 0 and i.getPartOf() == 0] targetDist = util.distance(unit.getX(),unit.getY(),unit.getSize(),enemies[0].getX(),enemies[0].getY(),enemies[0].getSize()) target = enemies[0] for e in enemies: if util.distance(unit.getX(),unit.getY(),unit.getSize(),e.getX(),e.getY(),e.getSize()) < targetDist: target = e targetDist = util.distance(unit.getX(),unit.getY(),unit.getSize(),e.getX(),e.getY(),e.getSize()) return target
def make_trilinear_interp_volume(Sk, Sl, Sm): ''' Linearly interpolate a tridirectional Surface network. Parameters ---------- Sk, Sl, Sm = the input Surfaces (three 2-tuples) Returns ------- Volume = the transfinite trilinear interpolation Volume Source ------ Handbook of Grid Generation, Pg. 30-23. ''' if len(Sk) != 2 or len(Sk) != 2 or len(Sm) != 2: raise ImproperInput() Sk = surface.make_surfaces_compatible1(Sk) Sk = Sk[-1] Sl = surface.make_surfaces_compatible1(Sl) Sl = Sl[-1] Sm = surface.make_surfaces_compatible1(Sm) Sm = Sm[-1] L1 = make_ruled_volume(*Sk) L1 = L1.swap('uw').swap('vw') L2 = make_ruled_volume(*Sl) L2 = L2.swap('uv').swap('vw') L3 = make_ruled_volume(*Sm) LT1 = make_ruled_volume2(*Sk) LT1 = LT1.swap('uw').swap('vw') LT2 = make_ruled_volume2(*Sl) LT2 = LT2.swap('uv').swap('vw') LT3 = make_ruled_volume2(*Sm) PT = np.ones((2, 2, 2, 4)) uk, vl, wm = (0, -1), (0, -1), (0, -1) for m in xrange(2): sm, w = Sm[m], wm[m] for l in xrange(2): sl, v = Sl[l], vl[l] for k in xrange(2): sk, u = Sk[k], uk[k] Q1, Q2, Q3 = (sk.cobj.cpts[v, w].xyz, sl.cobj.cpts[w, u].xyz, sm.cobj.cpts[u, v].xyz) l2n = (util.distance(Q1, Q2) + util.distance(Q1, Q3) + util.distance(Q2, Q3)) if l2n > 1e-3: print('nurbs.volume.make_trilinear_interp_volume :: ' 'point inconsistency ({})'.format(l2n)) PT[k, l, m, :3] = Q1 T = Volume(ControlVolume(Pw=PT), (1, 1, 1)) d, d, d, p, q, r, U, V, W, Vs = \ make_volumes_compatible1([L1, L2, L3, LT1, LT2, LT3, T]) Pijk = (Vs[0].cobj.Pw + Vs[1].cobj.Pw + Vs[2].cobj.Pw - Vs[3].cobj.Pw - Vs[4].cobj.Pw - Vs[5].cobj.Pw + Vs[6].cobj.Pw) return Volume(ControlVolume(Pw=Pijk), (p, q, r), (U, V, W))
def get_available_time(self): time = 0 prevX = 0 prevY = 0 for ride in self.rides: time += distance(prevX, prevY, ride.a, ride.b) time += distance(ride.a, ride.b, ride.x, ride.y) prevX = ride.x prevY = ride.y return time
def find_shooter(self, tt): t = tt() #import pdb;pdb.set_trace() for c in self.chesses: closest = None closedis = 10000 if c.side == 1 and c != t: if util.distance((c.x, c.y), (t.x, t.y)) < closedis: closedis = util.distance((c.x, c.y), (t.x, t.y)) closest = c return closest
def add_user(self, pos, alpha_bs_u, alpha_irs_u, beta_bs_u, beta_irs_u): idx = len(self.users) self.users.append(UE(1, pos)) self.bs_user_links.append( RicianChannel(1, self.bs.antnum, alpha_bs_u, beta_bs_u, util.distance(self.bs, self.users[idx]), self.c0, self.fc)) self.irs_user_links.append( RicianChannel(1, self.irs.antnum, alpha_irs_u, beta_irs_u, util.distance(self.irs, self.users[idx]), self.c0, self.fc))
def closetCluster(centroids, instance): """Find the closest cluster to an instance using the distance between the distance and centroids""" minDist = util.distance(centroids[0], instance) result = 0 i = 1 while i < len(centroids): if util.distance(centroids[i], instance) < minDist: minDist = util.distance(centroids[i], instance) result = i i += 1 return result
def approach(self, params): if distance((self.x, self.y), (params[0], params[1])) > params[2]: dist = distance((self.x, self.y), (params[0], params[1])) x_movement = ((params[0] - self.x) / dist) y_movement = ((params[1] - self.y) / dist) self.x += x_movement self.y += y_movement self.rect.x = int(self.x) self.rect.y = int(self.y) else: return True return False
def distancetest(self): print '' print ' c 0 1 2 3 4 5 6 7 8 9 X E' print 'r - - - - - - - - - - - -' for r in range(self.width()): print str(r) + ' |', for c in range(self.height()): print util.distance([0,0], [r,c]) % 10, print '| ' + str(r) print ' - - - - - - - - - - - -' print ' 0 1 2 3 4 5 6 7 8 9 X E' print ''
def update_with_sr(self, sr): ''' Adds the following to a filled-out Ride - distance to the original request location - distance to the closest destination ''' self.search_request = sr self.start_distance = util.distance( (sr.start_lat,sr.start_long), (self.requests[0].start_lat, self.requests[0].start_long)) self.end_distance = min([ util.distance( (sr.end_lat,sr.end_long), (r.end_lat, r.end_long)) for r in self.requests])
def on_step(self): self.time = self.agent.time self.pot_mat.time = self.time scouts = self.agent.get_scouts() if len(scouts) > 0: if len(scouts) > 1: scouts.pop() self.scout = scouts[0] position = self.scout.position self.pot_mat.scout_position = position radius = 10 self.pot_mat.set_time_area(position, 3) if util.distance(position, self.location_to_scout) < (radius//2): self.pot_mat.set_time(self.location_to_scout, self.time) enemies = self.close_enemies(radius) if enemies: potential_pos = self.potential_filed(enemies=enemies) self.drawings.append(potential_pos) if util.distance(position, self.location_to_scout) < 5*radius: self.pot_mat.set_time(self.location_to_scout, self.time) self.location_to_scout = self.pot_mat.lowest_potential_point(self.scout.position,radius=2*radius) #util.opposite_direction(position, potential_pos) self.move(self.location_to_scout) self.pot_path = [] else: self.location_to_scout = self.pot_mat.highest_intrest_point(self.get_bases(), self.time) if config.SAFE_PASSAGE and not self.pot_path: enemies = self.close_enemies(radius*2) if not enemies: self.pot_path = self.safe_passage_move(self.scout.position, self.location_to_scout) if len(self.pot_path) > 6: # BUG: some times it gets stuck due to a building being on top of point. only in start of game self.pot_path = self.pot_path[:-5] self.pot_mat.debug_lst = self.pot_path self.path_time_cache = self.time self.partcial_path = self.pot_path.pop(-1) elif config.SAFE_PASSAGE and self.pot_path: self.move(self.partcial_path) if self.close_location(self.partcial_path,self.scout.position) and self.pot_path: self.partcial_path = self.pot_path.pop(-1) else: self.move(self.location_to_scout) self.potesnial_to_buildings() if config.DEBUG_SCOUT: self.draw_potentsial() # draws pot in game self.hp_last_step = self.scout.hit_points self.pos_last_step = position
def single_clusters_dist(cluster1, cluster2): """ Compute pairwise distance btw clusters and pick the smallest distance (single linkage) :param cluster1: list :param cluster2: list :return min_dist: float """ min_dist = util.distance(cluster1[0], cluster2[0]) for i in range(len(cluster1)): for j in range(len(cluster2)): temp = util.distance(cluster1[i], cluster2[j]) if min_dist > temp: min_dist = temp return min_dist
def complete_cluster_dist(cluster1, cluster2): """ Compute pairwise distance btw clusters and pick the greatest distance (complete linkage) :param cluster1: list :param cluster2: list :return: max_dist: float """ max_dist = util.distance(cluster1[0], cluster2[0]) for i in range(len(cluster1)): for j in range(len(cluster2)): temp = util.distance(cluster1[i], cluster2[j]) if max_dist < temp: max_dist = temp return max_dist
def _find_target_ally(self, entity): import settings, util # find the nearest monster SEEK_DISTANCE = 8 current_map = settings.current_map pos = entity.position().get() monsters = current_map.entities()\ .with_component('NPC')\ .without_components(['Neutral', 'PlayerLogic', 'Ally'])\ .where(lambda e : util.distance(e.position().get(), pos) <= SEEK_DISTANCE)\ .as_list() monsters.sort(key=lambda e : util.distance(e.position().get(), pos)) if len(monsters) == 0: return None return monsters[0].ident()
def checkForStop(self): if not self.target is None: currDist = util.distance(self.precisePos, self.target) nextLoc = [] for i in range(2): nextLoc.append(self.precisePos[i] + self.vel[i]) nextDist = util.distance(nextLoc, self.target) if nextDist > currDist: if len(self.targetBuffer) > 0: self.target = self.targetBuffer[0] self.targetBuffer = self.targetBuffer[1:] self.startMovement() else: self.stop()
def on_mouse_press(self, x, y, button, modifiers): for eye in self._potato.eyes: if (self._title.timer < 1 and self._score.timer > 0 and distance((x, y), (eye.x, eye.y)) < 30): eye.kill() self._score.eyes_poked += 1
def getCorrespondencesForFace(selectedCorners, corners, currentFace, windowImage): h = compute2DHomography(selectedCorners) correspondences = [] # for every possible corner in the face for x in range(0, BOX_NUM * 2): for y in range(0, BOX_NUM * 2): # project the possible corner (in the range [-1,1]x[-1,1]) into image space with the homography h scale = (BOX_NUM * 2 - 1.0) / 2.0 projectedCorner = numpy.dot(h , numpy.array([x / scale - 1.0, y / scale - 1.0, 1])) projectedCorner /= projectedCorner[2] # find the closest corner from the corner detection set minDistance = 10000 minCorner = None pos = (projectedCorner[0], projectedCorner[1]) for corner in corners: dist = util.distance(corner, pos) if dist < minDistance: minDistance = dist minCorner = corner # check if the closest corner belongs to this corner -> add correspondence and paint a circle + the coordinates if minDistance < MIN_DISTANCE_THRESHOLD: coord3d = create3dCoord(currentFace, x + 1, y + 1) intPos = (int(pos[0] * ratio), int(pos[1] * ratio)) cv.Circle(windowImage, intPos , 6, cv.RGB(0, 0, 255)) # cv.PutText(windowImage, str(coord3d), intPos, DEFAULT_FONT , cv.RGB(0, 0, 255)) correspondences.append((minCorner, coord3d)) print("found " + str(len(correspondences)) + " correspondences") return correspondences
def act(self, acting_unit): # First chooses closest foe as target: chosen_target = None shortest_so_far = 999 # shortest distance of a foe so far for other_unit in self.things: if (other_unit.allegiance == 'gaia' or other_unit.allegiance == acting_unit.allegiance or other_unit.quantity <= 0): continue # invalid unit, not a foe dist = util.distance(other_unit.coord, acting_unit.coord) if dist < shortest_so_far: shortest_so_far = dist chosen_target = other_unit if chosen_target == None: return # Now moves toward target: # really hacky: cur = acting_unit.coord self.move( acting_unit, util.coord_sum( cur, util.direction_from(cur, chosen_target.coord))) # Now shoots target: self.shoot(acting_unit, chosen_target)
def heatAt(self, position): heat_from_sources = [] for hs in self.hsources: dist = util.distance(position, hs.position) heat = hs.getHeat(dist) heat_from_sources.append(heat) return sum(heat_from_sources)
def inlinequery(bot, update): logging.info('Answering inline query') query = update.inline_query.query results_list = list() facts = all_facts.get_facts() search_results = [ f for f in facts if distance(query, f, ignore_case=True) < 3 or query.lower() in f.lower() ] if len(search_results) > 0: facts = search_results[0:49] else: # 50 random facts range_start = random.randint(0, len(facts)) facts = facts[range_start:range_start + 49] results_list.append( InlineQueryResultArticle( id=uuid4(), title="No search results for '{}'.".format(query), input_message_content=InputTextMessageContent( message_text=get_random_fact()), description='Use a random fact below')) for fact in facts: results_list.append( InlineQueryResultArticle( id=uuid4(), title='Jeff Dean Fact', input_message_content=InputTextMessageContent( message_text=fact), description=fact)) bot.answerInlineQuery(update.inline_query.id, results=results_list)
def irregular2_galaxy_calc_positions(positions, size, width): """ Calculate positions for the irregular2 galaxy shape """ adjacency_grid = AdjacencyGrid(width) max_delta = max(min(float(fo.max_starlane_length()), width / 10.0), adjacency_grid.min_dist * 2.0) print "Irregular2 galaxy shape: max delta distance =", max_delta origin_x, origin_y = width / 2.0, width / 2.0 prev_x, prev_y = origin_x, origin_y reset_to_origin = 0 for n in range(size): attempts = 100 found = False while (attempts > 0) and not found: attempts -= 1 x = prev_x + uniform(-max_delta, max_delta) y = prev_y + uniform(-max_delta, max_delta) if util.distance(x, y, origin_x, origin_y) > width * 0.45: prev_x, prev_y = origin_x, origin_y reset_to_origin += 1 continue found = not adjacency_grid.too_close_to_other_positions(x, y) if attempts % 10: prev_x, prev_y = x, y if found: pos = fo.SystemPosition(x, y) adjacency_grid.insert_pos(pos) positions.append(pos) prev_x, prev_y = x, y print "Reset to origin", reset_to_origin, "times"
def find_intermediate_jump_point(self, start, end): dx = start[0]-end[0] dy = start[1]-end[1] center_pos = int(math.ceil(start[0]-dx/2.0)), int(math.ceil(start[1]-dy/2.0)) if self.fly_range > util.distance(start, center_pos): return None return center_pos
def _is_in_activity(self, user_traces, activity): """ Is in activity. :param user_traces: :param activity: :return: """ # geo point aty_lng = activity['location']['longitude'] aty_lat = activity['location']['latitude'] active_time = [] active_loc_records = [] activities_time_trace = [] s_time = time.mktime(activity['start_time'].timetuple()) # if has not end_time, mock an end_time data if (('end_time' in activity) and (activity['start_time'] != activity['end_time'])): e_time = time.mktime(activity['end_time'].timetuple()) elif activity['category'] in DEFAULT_ACTIVITY_LAST_TIME: e_time = s_time + DEFAULT_ACTIVITY_LAST_TIME[activity['category']] else: e_time = s_time + (3600 * 6) # for _trace in user_traces: if 'location' in _trace: u_loc = _trace['location'] else: u_loc = _trace u_lng = u_loc['longitude'] u_lat = u_loc['latitude'] _timestamp = _trace['timestamp'] / 1000 if s_time < _timestamp < e_time: activities_time_trace.append(_trace) dist = distance(aty_lng, aty_lat, u_lng, u_lat) if dist < DEFAULT_NEAR_POI_DISTANCE_THRESHOLD: active_time.append(_trace['timestamp']) active_loc_records.append(_trace) len_active_time = len(active_time) if 3 <= len_active_time: active_loc_records.sort(key=lambda x: x["timestamp"]) min_timestamp = datetime.datetime.fromtimestamp( active_loc_records[0]['timestamp'] / 1000) max_timestamp = datetime.datetime.fromtimestamp( active_loc_records[-1]['timestamp'] / 1000) if (max_timestamp - min_timestamp).total_seconds() > 1800: return active_loc_records return []
def stitching_positions(p1, p2): """ Returns a list of positions between p1 and p2 between MIN_SYSTEM_SEPARATION and MAX_STARLANE_LENGTH apart """ if 2 * universe_tables.MIN_SYSTEM_SEPARATION >= universe_tables.MAX_STARLANE_LENGTH: util.report_error("MAX_STARLANE_LENGTH must be twice MIN_SYSTEM_SEPARATION to " "allow extra positions to be added to enforce MAX_STARLANE_LENGTH") return [] max_dist = universe_tables.MAX_STARLANE_LENGTH min_dist = universe_tables.MIN_SYSTEM_SEPARATION p1_p2_dist = util.distance(p1, p2) if p1_p2_dist < max_dist: return [] # Pick a random point in an 2:1 ratio ellipse and then rotate and slide it in between p1 and p2 p1_p2_theta = acos((p2[0] - p1[0]) / p1_p2_dist) p1_p2_scale = (p1_p2_dist - 2*min_dist) / 2 p1_p2_translation = ((p1[0] + p2[0]) / 2, (p1[1] + p2[1]) / 2) radius_0space = uniform(0.0, 1.0) angle_0space = uniform(0.0, 2.0 * pi) rotated_point = (radius_0space * p1_p2_scale * cos(angle_0space + p1_p2_theta), radius_0space * p1_p2_scale * sin(angle_0space + p1_p2_theta)) p3 = (rotated_point[0] + p1_p2_translation[0], rotated_point[1] + p1_p2_translation[1]) return [p3] + stitching_positions(p1, p3) + stitching_positions(p2, p3)
def irregular_galaxy_calc_positions(positions, adjacency_grid, size, width): """ Calculate positions for the irregular galaxy shape. """ max_delta = max(min(float(universe_tables.MAX_STARLANE_LENGTH), width / 10.0), adjacency_grid.min_dist * 2.0) print "Irregular galaxy shape: max delta distance = {}".format(max_delta) origin_x, origin_y = width / 2.0, width / 2.0 prev_x, prev_y = origin_x, origin_y reset_to_origin = 0 for _ in range(size): attempts = 100 found = False while (attempts > 0) and not found: attempts -= 1 x = prev_x + uniform(-max_delta, max_delta) y = prev_y + uniform(-max_delta, max_delta) if util.distance((x, y), (origin_x, origin_y)) > width * 0.45: prev_x, prev_y = origin_x, origin_y reset_to_origin += 1 continue found = not adjacency_grid.too_close_to_other_positions((x, y)) if attempts % 10: prev_x, prev_y = x, y if found: pos = (x, y) adjacency_grid.insert_pos(pos) positions.append(pos) prev_x, prev_y = x, y print "Reset to origin {} times".format(reset_to_origin)
def resetRegion(self): if self.region is None: return if (util.distance(self.precisePos, self.region.pos) > MAP_REGION_SIZE): self.region = None
def evaluation_function(self, node_id, cur_days): """ Evaluation function: if I add node_id to the job schedule, how good is it? @author Aaron Nagao @param <String> node_id = id of the job I am evaluating @return <float> estimate of the value of choosing node_id. Higher value = better choice. TODO: change manual weights of 1 to learned weights Features for evaluation function: # 1) Number of miles required to fulfill this job # 2) price of this job # 3a) After we deliver this job, how many other jobs are in the area? # 3b) After we deliver this job, what's the average price of other jobs in the delivery area? # TODO: avg gas price in the area? """ # key: <String>featureName => value: <tuple>(weight, featureValue) # Positive weights for good features. return 0 features = dict() """ # First, check whether I can finish this job in time prevEnd_nextStart_nextEnd = self.distance_matrix[(prevJob['_id']['$oid'], nextJob['_id']['$oid'])] # miles required to drive to next job and fulfill next job (prevJob.end => nextJob.start => nextJob.end) (from_lng, from_lat) = nextJob['deliveryAddress']['location']['coordinates'] (to_lng, to_lat) = (self.start_lng, self.start_lat) nextEnd_home = util.distance(from_lat, from_lng, to_lat, to_lng) sumDays_nextJobAndHome = ( (prevEnd_nextStart_nextEnd + nextEnd_home) / util.MPH ) / 24 # day = miles / miles/hr / 24hr/day if cur_days + sumDays_nextJobAndHome > self.max_days: return float('-inf') # cannot take on this job """ # 1) Number of miles required to fulfill this job # negative weight (prefer shorter jobs) features['jobMiles'] = (-.2, util.distance(*self.graph.jobs[node_id]['pickup']+self.graph.jobs[node_id]['delivery'])) # 2) price of this job features['jobPrice'] = (0.3, self.graph.jobs[node_id]['price']) # 3a) After we deliver this job, how many other jobs are in the area? (to_lat, to_lng) = self.graph.jobs[node_id]['delivery'] to_i, to_j = int(to_lat), int(to_lng) jobsInDeliveryArea = self.graph.delivery_grid[ (to_i, to_j) ] numJobsInDeliveryArea = len(jobsInDeliveryArea) features['numJobsInDeliveryArea'] = (0.3, numJobsInDeliveryArea) # 3b) After we deliver nextJob, what's the average price of other jobs in the delivery area? if numJobsInDeliveryArea == 0: avgPriceInDeliveryArea = 0 else: avgPriceInDeliveryArea = sum([self.graph.get_price(job) for job in jobsInDeliveryArea]) / numJobsInDeliveryArea features['avgPriceInDeliveryArea'] = (0.1, avgPriceInDeliveryArea) # print features heur_score = sum([ v[0]*v[1] for k,v in features.iteritems() ]) / 10 #print("heur score: " + str(heur_score)) return heur_score # dot product of feature and its weight
def PerformIDEACluster(clusters,test,dataset="Unknown", treatment="IDEACLUSTER", disregardY=False): Stats = DefectStats() if type(test[0].klass()) is str: for instance in test: Closest = [sys.maxint, None] for cluster in clusters: for quadrant in cluster.quadrants: if distance(instance.Coord(), quadrant.center()) < Closest[0]: Closest[0] = distance(instance.Coord(), quadrant.center()) Closest[1] = cluster train = [] for quadrant in Closest[1].quadrants: train.extend(quadrant.ClassCoords()) Stats.Evaluate(NaiveBayesClassify(instance.Coord(),train, disregardY), instance.klass()) Stats.StatsLine(dataset, treatment) del Stats
def check_distance_accuracy(jobs_file): distance_diffs = [] c = 0 total = 0 with open(jobs_file) as f: for line in f: total += 1 job = json.loads(line) if job['distanceInMiles'] <= 0: c+= 1 continue from_latlng = job['pickupAddress']['location']['coordinates'] to_latlng = job['deliveryAddress']['location']['coordinates'] geodesic_distance = util.distance(from_latlng[1], from_latlng[0], to_latlng[1], to_latlng[0]) error = geodesic_distance/job['distanceInMiles']-1 distance_diffs.append(error) print 'Missing distances: ', c/float(total) print 'Mean: ', numpy.mean(distance_diffs) print 'Stdev: ', numpy.std(distance_diffs) values = [int(p*100) for p in distance_diffs] counts = collections.Counter(values) X = sorted(counts.keys()) Y = [counts[x] for x in X] fig = plt.figure() ax = fig.add_subplot(111) ax.plot(X, Y) ax.set_title('[Geodesic distance - Actual Distance] histogram') ax.set_xlabel('Miles') ax.set_ylabel('Count') plt.show()
def cornerProbabilityGivenParticleLocation(observation, particle): ''' Calculates P(e|x_t), given that observation is the (scalar) distance to the corner TODO: r, theta = observation ''' obs_dist, obs_heading = observation prob = 0.0 for corner in corners: # calculate distance to corner distance = util.distance(particle[0:2], corner) # calculate the relative heading w.r.t particle position and heading heading = util.normalizeRadians(util.heading(particle[0:2], corner) - particle[2]) # TODO tune sigmas # (assume P(e|x_t) ~ exp{-1/2 * |distance - obs_dist| / sigma_1^2} # * exp{-1/2 * |heading - obs_heading| / sigma_2^2} ) prob += numpy.exp(-0.1 * numpy.abs(distance - obs_dist) + -7 * numpy.abs(heading - obs_heading)) ''' if corner is corners[0]: print particle, 'hdg:', heading print numpy.exp(-0.1 * numpy.abs(distance - obs_dist) + -10 * numpy.abs(heading - obs_heading)) print numpy.exp(-1 * numpy.abs(heading - obs_heading)) ''' return prob
def initialize(self): if self.type == self.PROXIMAL: # Setup initial potential synapses for proximal segments n_inputs = self.region.n_inputs cell_x, cell_y = util.coords_from_index(self.cell.index, self.region._cell_side_len()) for source in range(n_inputs): # Loop through all inputs and randomly choose to create synapse or not input_x, input_y = util.coords_from_index(source, self.region._input_side_len()) dist = util.distance((cell_x, cell_y), (input_x, input_y)) max_distance = self.region.diagonal chance_of_synapse = ((MAX_PROXIMAL_INIT_SYNAPSE_CHANCE - MIN_PROXIMAL_INIT_SYNAPSE_CHANCE) * (1 - float(dist)/max_distance)) + MIN_PROXIMAL_INIT_SYNAPSE_CHANCE add_synapse = random.random() < chance_of_synapse if add_synapse: self.add_synapse(source) else: # Distal cell_index = self.cell.index for index in range(self.region.n_cells): if index == cell_index: # Avoid creating synapse with self continue chance_of_synapse = DISTAL_SYNAPSE_CHANCE add_synapse = random.random() < chance_of_synapse if add_synapse: self.add_synapse(index, permanence=0.15) log_message = "Initialized %s" % self log(log_message)
def getStatistics(self, tour): """ @param list of job ids. Does NOT include start_id @return (number of days to finish this tour, value of doing this tour in $/day) """ if len(tour)==0: return (0,0) totalNumDays, totalValue = 0, 0 prevID = self.start_job_id for jobID in tour: currJob = self.graph.jobs[jobID] interjob_distance = self.graph.get_distance(prevID, jobID) # drive from prev job to this job intrajob_distance = util.distance(*currJob['pickup']+currJob['delivery']) # do this job totalNumDays += util.miles_to_drive_days( interjob_distance+intrajob_distance ) totalValue += util.compute_profit(currJob['price'], interjob_distance, intrajob_distance) prevID = jobID # add # of days from the last job to home totalNumDays += util.miles_to_drive_days( self.graph.get_distance(jobID, self.start_job_id) ) if totalNumDays > self.max_days: totalValue = float('-inf') return (totalNumDays, totalValue/totalNumDays)
def refresh(self): tcod_map = self.game.dungeon.tcod_map if self.entity is self.game.player: libtcod.map_compute_fov(tcod_map, self.entity.x, self.entity.y, PLAYER_FOV_RADIUS) else: libtcod.map_compute_fov(tcod_map, self.entity.x, self.entity.y, self.creature.perception) if self.entity is self.game.player: for x in range(len(self.fov_map)): for y in range(len(self.fov_map[0])): self.fov_map[x][y]=int(libtcod.map_is_in_fov(tcod_map, x,y)) else: self.clear() for x in range(self.entity.x-self.creature.perception, self.entity.x+self.creature.perception+1): for y in range(self.entity.y-self.creature.perception, self.entity.y+self.creature.perception+1): fov_num = int(libtcod.map_is_in_fov(tcod_map,x,y)) if fov_num: if (x-self.entity.x==0 or y-self.entity.y==0 or abs(x-self.entity.x)-abs(y-self.entity.y)==0): fov_num += 1 if util.distance(self.entity.x,self.entity.y,x,y)<=self.creature.perception//3: fov_num += 1 try: self.fov_map[x][y] = fov_num except IndexError: pass
def too_close_to_other_positions(self, pos): """ Checks if the specified position is too close to the positions stored in the grid """ pos_cell = self.cell(pos) return any(util.distance(p2, pos) < self.min_dist for p2_cell in self._square_indices_containing_cell(pos_cell, 1) for p2 in self.grid[p2_cell])
def calcAcc(self, y): radius = util.distance(self.pos, y.pos) # to be fixed: calculate mass based on density if radius < y.size + self.size: return (False,(0,0)) force = GConstant*(self.mass*y.mass)/(radius**2) unit = ((y.pos[0]-self.pos[0])/radius, (y.pos[1]-self.pos[1])/radius) return (True, (force*unit[0]/self.mass, force*unit[1]/self.mass))
def zone_of_control_blocks(self, coord, mover): for other_thing in self.things: if (other_thing.ws > 0 and other_thing.allegiance != mover.allegiance and util.distance(coord, other_thing.coord) <= 1 and other_thing.quantity > 0): return True return False
def nearest_neighbor(self, p): """ Return nearest neighbor at any distance.""" for ring in self._generate_rings_around_point(p): candidates = [pos for cell in ring for pos in self.grid[cell]] if candidates: (_, pt) = min((util.distance(pos, p), pos) for pos in candidates) return pt return None
def collides_with(self, other_object): if not self.reacts_to_bullets and other_object.is_bullet: return False if self.is_bullet and not other_object.reacts_to_bullets: return False collision_distance = self.image.width / 2 + other_object.image.width / 2 actual_distance = util.distance(self.position, other_object.position) return actual_distance <= collision_distance