def sendCommand(self, totalX, totalY, tank): othertanks = self.bzrc.get_othertanks() me = Point(tank.x, tank.y) cur = 100000 mins = 100000 enemy = Point(0, 0) for other in othertanks: cur = Point(other.x, other.y).distance(me) if (cur < mins): mins = cur enemy = other if mins <= 200: self.doKalman(enemy.x, enemy.y) else: theta = math.atan2(totalY, totalX) theta = self.normalize_angle(theta - tank.angle) speed = math.sqrt(totalY**2 + totalX**2) self.commands = [] command = Command(tank.index, .15 * speed, .85 * theta, False) self.commands.append(command) self.bzrc.do_commands(self.commands) self.commands = []
def question_22_17(query): VertexB = Point(Fraction(1), Fraction(-2), "B") VertexC = Point(Fraction(-2), Fraction(-1), "C") EdgeA = Line.get_line_contains_points(VertexB, VertexC) p1 = Point(Fraction(2), Fraction(0), "p1") p2 = Point(Fraction(2), Fraction(1), "p2") EdgeC = Line.get_line_contains_points(VertexB, p1) EdgeB = Line.get_line_contains_points(VertexC, p2) del p1, p2 BisectorAngleA = Line.get_bisectors_for_2lines(EdgeB, EdgeC)[0] VertexOfTargetRhombusInsideEdgeA = EdgeA.get_cross_point(BisectorAngleA) EageOfTargetRhombusParallelsToEdgeC = Line.get_line_parallel_to(EdgeC, VertexOfTargetRhombusInsideEdgeA) EageOfTargetRhombusParallelsToEdgeB = Line.get_line_parallel_to(EdgeB, VertexOfTargetRhombusInsideEdgeA) VertexOfTargetRhombusInsideEdgeB = Line.get_cross_point(EageOfTargetRhombusParallelsToEdgeC, EdgeB) VertexOfTargetRhombusInsideEdgeC = Line.get_cross_point(EageOfTargetRhombusParallelsToEdgeB, EdgeC) TriangleEdges = {(EdgeA.a, EdgeA.b, EdgeA.c), (EdgeB.a, EdgeB.b, EdgeB.c), (EdgeC.a, EdgeC.b, EdgeC.c)} init_figure, grid_size = common.INIT_FIGURE(), common.GRID_SIZE() init_figure.extend(TriangleEdges) resolution_vertex_in_edge_a = query.query_point_by_symmetry(VertexOfTargetRhombusInsideEdgeA, init_figure) resolution_vertex_in_edge_b = query.query_point_by_symmetry(VertexOfTargetRhombusInsideEdgeB, init_figure) resolution_vertex_in_edge_c = query.query_point_by_symmetry(VertexOfTargetRhombusInsideEdgeC, init_figure) resolution_product = itertools.product(resolution_vertex_in_edge_a, resolution_vertex_in_edge_b, resolution_vertex_in_edge_c) solution_for_all = [frozenset((set(r[0]) | set(r[1]) | set(r[2]))) for r in resolution_product] solution_for_all.sort() targets = (VertexOfTargetRhombusInsideEdgeA, VertexOfTargetRhombusInsideEdgeB, VertexOfTargetRhombusInsideEdgeC) for r in solution_for_all: draw_resolution(r, targets, init_figure, grid_size)
def __init__(self, bzrc, tank, job): self.updatecounts = 0 self.tank = tank self.bzrc = bzrc self.fields = fields.Calculations() self.throttle = .15 self.commands = [] self.constants = self.bzrc.get_constants() self.job = job self.base = bzrc.get_bases()[self.getFlagIndex()] c1 = Point(self.base.corner1_x, self.base.corner1_y) c3 = Point(self.base.corner3_x, self.base.corner3_y) line = Line(c1, c3) self.base = line.getMidpoint() flags = bzrc.get_flags() for flag in flags: if flag.color == self.constants['team']: self.flag = flag self.obstacles = [] #the .07125 comes from the 4 Ls world where 7.125% of the world was occupied self.time = time.time() self.locationList = [] self.oldlocation = [] self.startTime = time.time() self.mytanks = self.bzrc.get_mytanks()
def doKalman(self, X, Y): self.Kfilter = Kalman(X, Y) Mu, Sigma = self.Kfilter.runKalman(self.bzrc) enemyX = Mu.item((0, 0)) enemyY = Mu.item((3, 0)) distance = Point(self.tank.x, self.tank.y).distance(Point(enemyX, enemyY)) if distance > 450: return pred = (distance / float(self.constants['shotspeed'])) * (1.0 / t) pred = int(pred + 1) MuPred, garbage = self.Kfilter.predictiveKalman(Mu, Sigma, pred) targetX, targetY = MuPred.item((0, 0)), MuPred.item((3, 0)) deltaX, deltaY = self.getDeltaXY(self.tank, Point(targetX, targetY)) theta = math.atan2(deltaY, deltaX) theta = self.normalize_angle(theta - self.tank.angle) #distance = Point(tank.x, tank.y).distance(Point(targetX,targetY)) if distance <= 390 and (theta < 0.2 and theta > -0.2): shoot = True else: shoot = False self.kalmanCommand(deltaX, deltaY, theta, shoot, self.tank)
def shoot_em(self, tank): my_position = Point(tank.x, tank.y) for enemy in self.enemies: enemy_position = Point(enemy.x, enemy.y) if my_position.distance(enemy_position) <= 50: theta = self.fields.angle(tank, enemy) if theta < 1.5 and theta > -1.5: line_to_enemy = Line(my_position, enemy_position) safe = True for teamMate in self.mytanks: if teamMate.index == tank.index: continue teamMate_position = Point(teamMate.x, teamMate.y) cp2 = teamMate_position.closestPointOnLine( line_to_enemy) teamMate_enemy_line = Line(teamMate_position, cp2) if teamMate_position.distance(cp2) < 10: safe = False break if safe == True: return True return False
def getDeltaXY(self, tank, enemy): theta = self.angle(tank, enemy) distance = Point(tank.x, tank.y).distance(Point(enemy.x, enemy.y)) deltaX = distance * math.cos(theta) deltaY = distance * math.sin(theta) return deltaX, deltaY
def tick(self): mytanks, othertanks, flags, shots = self.bzrc.get_lots_o_stuff() ''' list of teammates with velocities and position and flag posession etc. ''' self.mytanks = self.bzrc.get_mytanks() ''' positions and angle of othertanks ''' self.othertanks = othertanks self.enemies = [tank for tank in othertanks if tank.color != self.constants['team']] self.commands = [] tank = self.bzrc.get_mytanks()[0] if(self.enemies[0].status == 'dead'): return '''do a predictive filter here maybe, before they shoot''' Mu,Sigma = self.Kfilter.runKalman(self.bzrc) enemyX = Mu.item((0,0)) enemyY = Mu.item((3,0)) distance = Point(tank.x, tank.y).distance(Point(enemyX,enemyY)) if distance > 450: return pred = (distance/float(self.constants['shotspeed']))*(1.0/t) pred = int(pred+1) MuPred,SigmaPred = self.Kfilter.predictiveKalman(Mu,Sigma,pred) targetX,targetY = MuPred.item((0,0)),MuPred.item((3,0)) deltaX, deltaY = self.getDeltaXY(tank,Point(targetX,targetY)) theta = math.atan2(deltaY,deltaX) theta = self.normalize_angle(theta-tank.angle) #distance = Point(tank.x, tank.y).distance(Point(targetX,targetY)) if distance <= 390 and (theta < 0.1 and theta > -0.1): shoot = True else: shoot = False self.sendCommand(deltaX, deltaY, theta, shoot, tank) '''call gnuplot here''' sigmaX,sigmaY,rho = self.Kfilter.covarianceMatrix(self.bzrc,Mu,Sigma) #print "sigmaX and Y", sigmaX,sigmaY #print "rho" , rho plotter.plot(sigmaX,sigmaY,0,enemyX,enemyY) return True
def question_16_15(query): line1 = Line.get_line_contains_points(Point(-2, 0), Point(0, 1)) line2 = Line.get_line_contains_points(Point(0, -1), Point(1, 1)) line = Line.get_bisectors_for_2lines(line1, line2)[0] A = line1.get_cross_point(line2) # query and show it(them) init_figure, grid_size = common.INIT_FIGURE(), common.GRID_SIZE() init_figure.extend(((line1.a, line1.b, line1.c), (line2.a, line2.b, line2.c))) solution = query.query_line_by_symmetry(line, (A,), init_figure) points = set([s[0] for s in solution]) for r in solution[:4]: p, fig = r draw_resolution(fig, points, init_figure, grid_size)
def __init__ (self,enemyx,enemyy): self.enemy = Point(enemyx,enemyy) self.F = np.matrix([[1,t,(.5*(t**2)),0,0,0], [0,1,t,0,0,0], [0,0,1,0,0,0], [0,0,0,1,t,(.5*(t**2))], [0,0,0,0,1,t], [0,0,0,0,0,1]]) self.SigmaS = np.matrix([[.1,0,0,0,0,0], [0,.1,0,0,0,0,], [0,0,50,0,0,0], [0,0,0,.1,0,0], [0,0,0,0,.1,0], [0,0,0,0,0,50]]) self.H = np.matrix([[1,0,0,0,0,0], [0,0,0,1,0,0]]) self.SigmaE = np.matrix([[25,0],[0,25]]) self.FTrans = self.F.transpose() self.HTrans = self.H.transpose() self.MuKnot = np.matrix([[enemyx],[0],[0],[enemyy],[0],[0]]) self.SigmaKnot = np.matrix([[100,0,0,0,0,0], [0,.1,0,0,0,0], [0,0,.1,0,0,0], [0,0,0,100,0,0], [0,0,0,0,.1,0], [0,0,0,0,0,.1]]) self.SigmaCurrent = self.SigmaKnot self.SigmaPrev = self.SigmaKnot self.MuCurrent = self.MuKnot self.MuPrev = self.MuKnot
def parse_xml(xml): cities = [] for node in xml: if node.tag == "node": lon = float(node.attrib["lon"]) lat = float(node.attrib["lat"]) id_ = node.attrib["id"] city = { "name": id_, "pos": Point(lon, lat), "population": 0, "zipcode": "UNKNOWN" } ctable = { "name": "name", "population": "population", "ref:INSEE": "zipcode" } for data in node: if data.tag == "tag": key, value = data.attrib["k"], data.attrib["v"] if key in ctable: new_key = ctable[key] city[new_key] = value city["population"] = int(city["population"]) cities.append(city) else: # Not a 'node' tag pass return cities
def __init__(self, vid, length, width, height, weight, cat, axles, doublemount, studs, fuel, cc, maxspeed, maxdecel, maxaccel, position = Point(0.0,0.0,0.0), direction = Direction(0.0,0.0), speed = 0.0, acceleration = 0.0): object.__init__(self) # unique vehicle ID self._vid = vid # size properties self._length = length # in m self._width = width # in m self._height = height # in m self._weight = weight # in kg # emission related properties self._cat = cat # emission category (usually an integer), to be interpreted by the emission models self._axles = axles # integer, number of axles of vehicle self._doublemount = doublemount # boolean, true for double-mounted tires (for trucks) self._studs = studs # boolean, true if the vehicle has winter tires self._fuel = fuel # the type of fuel the vehicle uses (string, e.g. 'petrol', 'diesel', 'electric') self._cc = cc # the cilinder capacity (cc) # kinematic properties self._maxspeed = maxspeed # in km/h self._maxdecel = maxdecel # in m/s^2 (negative value) self._maxaccel = maxaccel # in m/s^2 # dynamic properties self._position = position # position Point(x,y,z) - center of bottom plane - in m self._direction = direction # Direction(bearing,gradient) of the vehicle, in degrees (0-360) self._speed = speed # velocity (km/h) self._acceleration = acceleration # acceleration (m/s^2)
def tick(self): self.commands = [] curtime = time.time() self.mytanks = self.bzrc.get_mytanks() for tank in self.mytanks: curLocation = Point(tank.x, tank.y) target = self.locationList[tank.index] if curLocation.distance(target) < 10: target = self.getRandomCoordinate(tank.index) while self.grid.get(target.x, target.y) > .95: target = self.getRandomCoordinate(tank.index) self.locationList[tank.index] = target self.oldlocation[tank.index] = curLocation self.goToPoint(tank, target) if(curtime - self.time > 4.25 ): for tank in self.mytanks: command = Command(tank.index,0,0,False) self.commands = [] self.commands.append(command) self.bzrc.do_commands(self.commands) self.commands = [] self.getObservation(tank) self.time = time.time()
def tick(self): if(self.ticks < 10): pass if self.tank.status == "dead": return self.commands = [] curtime = time.time() curLocation = Point(self.tank.x, self.tank.y) target = self.locationList[self.tank.index] if curLocation.distance(target) < 10: target = self.getRandomCoordinate(self.tank.index) while self.grid.get(target.x, target.y) > .95: target = self.getRandomCoordinate(self.tank.index) self.locationList[self.tank.index] = target self.oldlocation[self.tank.index] = curLocation self.goToPoint(self.tank, target) if(curtime - self.time > 2.25 ): command = Command(self.tank.index,0,0,False) self.commands = [] self.commands.append(command) self.bzrc.do_commands(self.commands) self.commands = [] self.getObservation(self.tank) self.time = time.time()
def query_point_by_symmetry(self, point, init_fig=None): # init_fig: will be subtracted from each result item if init_fig is None: init_fig = set() init_fig = set(init_fig) point_vector = (point.x.numerator, point.x.denominator, point.y.numerator, point.y.denominator) mat_table = common.get_symmetry_matrix_table() result = [] for mat in mat_table: p = common.apply_mat_on_point(point_vector, mat) p0 = Point(Fraction(p[0], p[1]), Fraction(p[2], p[3])) fig_list = self.query_point(p0) for fig in fig_list: fig0 = common.apply_mat_on_figure( fig, common.inv_for_symmetry_mat(mat)) result.append(tuple(set(fig0) - init_fig)) shortest = min(map(len, result)) result = [r for r in result if len(r) == shortest] result = list(set(result)) result.sort() return result
def build_list(self, difficulty=1): if not self.ranking_available(): difficulty = 1.1 min_rank = max(10, difficulty * max(self.ranks)) return {((clean_city(city), hint), Point(lon, lat)) for city, hint, lon, lat, rank in zip( self.places, self.hints, self.lons, self.lats, self.ranks) if rank <= min_rank}
def getRandomCoordinate(self, tankIndex): #1 and 2: quadrant 1 (x,y) if tankIndex == 1 or tankIndex == 2: rval = Point(random.randrange(0,400), random.randrange(0,400)) #3 and 4: quadrant 2 (x,-y) elif tankIndex == 3 or tankIndex == 4: rval = Point(random.randrange(0,400), random.randrange(-400,0)) #5 and 6: quadrant 3 (-x,-y) elif tankIndex == 5 or tankIndex == 6: rval = Point(random.randrange(-400,0), random.randrange(-400,0)) #7 and 8: quadrant 4 (-x, y) elif tankIndex == 7 or tankIndex == 8: rval = Point(random.randrange(-400,0), random.randrange(0,400)) #9 and 10: middle ([-200,200],[-200,200]) else: rval = Point(random.randrange(-200,200), random.randrange(-200,200)) return rval
def __init__(self, bzrc, enemy): self.bzrc = bzrc self.constants = self.bzrc.get_constants() self.commands = [] self.throttle = .15 self.obstacles = [] self.fields = Calculations() self.flagIndex = self.getIndex() self.base = bzrc.get_bases()[self.flagIndex] self.enemyFlag = int(enemy) c1 = Point(self.base.corner1_x, self.base.corner1_y) c3 = Point(self.base.corner3_x, self.base.corner3_y) line = Line(c1, c3) self.base = line.getMidpoint() for obs in bzrc.get_obstacles(): self.obstacles.append(Obstacle(obs))
def add(self, source): """ add the effect of a single source to the noise map """ for i in range(len(self.recx)): for j in range(len(self.recy)): receiver = Receiver( position=Point(self.recx[i], self.recy[j], self.recz)) level = pmodel.immission( source, receiver).laeq() # A-weighted SPL at receiver self.energy[i, j] += fromdB(level)
def get_latlng_from_tile_at(self, bounds, x, y): scale = self.size / float(self.zoom_scale) ne = bounds.getNorthEast() sw = bounds.getSouthWest() top_right = projection.fromLatLngToPoint(ne) bottom_left = projection.fromLatLngToPoint(sw) point = Point(float(x) * scale + bottom_left.x, float(y) * scale + top_right.y) return projection.fromPointToLatLng(point)
def receivers(self): """ construct a list of receivers based on the stored parameters """ if not hasattr(self, '_receivers'): locs = self.get('receivers-locations').strip() if len(locs) == 0: self._receivers = [] else: points = [Point(x) for x in locs.split(';')] self._receivers = [Receiver(p) for p in points] return self._receivers
def read_track(fname, max_points=None): k = read_kml(fname) track = extract_track(k) name = track.name points = [] for line in track.geometry.geoms: for lon, lat, alt in line.coords: points.append(Point(lon, lat)) if max_points is not None and len(points) == max_points: return points, name return points, name
def clear(self): """ clear the simulation """ self._t = 0.0 self._passbys = [] # list with vehicle passbys (at the origin) self._passbytimes = {1: [], 3: []} self._history = [] # history of vehicles at each timestep self._factory = VehicleFactory(fleet=self._fleet, position=Point(self._xmin, 0.0, 0.0), direction=Direction(bearing=0.0), speed=self._vlimit, acceleration=0.0)
def question_14_9(query): # get Point B line1 = Line.get_line_contains_points(Point(-3, 1), Point(3, 3)) line2 = Line(1, 0, -2) B = line1.get_cross_point(line2) # get Point A line1 = Line.get_line_contains_points(Point(2, -3), Point(3, 0)) line2 = Line(0, 1, -1) A = line1.get_cross_point(line2) del line1, line2 # get the midpoint target_point_x = (A.x + B.x) / 2 target_point_y = (A.y + B.y) / 2 point_target = Point(target_point_x, target_point_y, "Target") # query and show it(them) solution = query.query_point_by_symmetry(point_target) init_figure, grid_size = common.INIT_FIGURE(), common.GRID_SIZE() for r in solution: draw_resolution(r, [point_target], init_figure, grid_size)
def question_27_14(query): total = [] total.append(centroid_of_2x2_grid(-2, +2, (True, True, True, False))) total.append(centroid_of_2x2_grid(+2, +2, (True, True, False, True))) total.append(centroid_of_2x2_grid(-2, -2, (True, False, True, True))) total.append(centroid_of_2x2_grid(+2, -2, (True, True, True, False))) x, y, w = centroid_of_iter(total) point_target = Point(x, y, "Target") solution = query.query_point_by_symmetry(point_target) init_figure, grid_size = common.INIT_FIGURE(), common.GRID_SIZE() for r in solution: draw_resolution(r, [point_target], init_figure, grid_size)
def question_24_6(query): A = Point(1, -2) B = Point(0, 1) line1 = Line.get_line_contains_points(A, B) line2 = Line.get_line_by_point_slope(A, Fraction(4)) tan_alpha = Fraction(1, 4) tan_beta = Fraction(1, 3) tan_theta = tan_of_add(tan_of_double(tan_beta), tan_alpha) slope = tan_of_neg(tan_of_complementary(tan_theta)) line = Line.get_line_by_point_slope(A, slope) # query and show it(them) init_figure, grid_size = common.INIT_FIGURE(), common.GRID_SIZE() init_figure.extend(((line1.a, line1.b, line1.c), (line2.a, line2.b, line2.c))) solution = query.query_line_by_symmetry(line, (A,), init_figure) points = set([s[0] for s in solution]) for r in solution[:4]: p, fig = r draw_resolution(fig, points, init_figure, grid_size)
def sources(self, vehicle, road = ReferenceRoadsurface()): # calculate position of sources pos = vehicle.position() h = {1: (0.01, 0.30), 2: (0.01, 0.75), 3: (0.01, 0.75), 4: (0.30, 0.30), 5: (0.30, 0.30)}[vehicle.cat()] lopos = Point(pos[0], pos[1], pos[2] + h[0]) hipos = Point(pos[0], pos[1], pos[2] + h[1]) # calculate rolling and propulsion noise r = fromdB(self.rollingNoise(vehicle, road)) p = fromdB(self.propulsionNoise(vehicle, road)) # calculate low and high noise lonoise = 10.0*numpy.log10(0.8*r + 0.2*p) hinoise = 10.0*numpy.log10(0.2*r + 0.8*p) # construct sources return [Source(position = lopos, direction = asDirection(vehicle.direction()), emission = TertsBandSpectrum(lonoise), directivity = ImagineDirectivity(cat = vehicle.cat(), h = h[0])), Source(position = hipos, direction = asDirection(vehicle.direction()), emission = TertsBandSpectrum(hinoise), directivity = ImagineDirectivity(cat = vehicle.cat(), h = h[1]))]
def question_14_8(query): # get Point B line1 = Line.get_line_contains_points(Point(-3, -1), Point(3, -3)) line_tmp = Line(1, 0, -2) B = line1.get_cross_point(line_tmp) # get Point A line2 = Line.get_line_contains_points(Point(-3, 1), Point(2, 2)) line_tmp = Line(1, 0, 1) A = line2.get_cross_point(line_tmp) line = Line.get_line_contains_points(A, B) point_target = A.middle(B) # query and show it(them) init_figure, grid_size = common.INIT_FIGURE(), common.GRID_SIZE() for ll in (line, line1, line2): init_figure.append((ll.a, ll.b, ll.c)) solution = query.query_point_by_symmetry(point_target, init_figure) for r in solution[:4]: draw_resolution(r, [point_target], init_figure, grid_size)
def createVehicle(self, tokens): """ create a Vehicle object based on the supplied logger line tokens """ # fetch vehicle parameters vID = int(tokens[0]) vLength = float(tokens[1]) vPosition = Point(float(tokens[2]), float(tokens[3])) vDirection = Direction(bearing = float(tokens[4])) vSpeed = float(tokens[5]) vAcceleration = float(tokens[6]) # simple check between light and heavy vehicles vClass = {False: LightVehicle, True: HeavyVehicle}[(vLength>10.0)] return vClass(vid = vID, position = vPosition, direction = vDirection, speed = vSpeed, acceleration = vAcceleration)
def __init__(self, db_file_name='new_graph.db'): try: self.db_file_name = db_file_name self.connect = sqlite3.connect("file:" + self.db_file_name + "?mode=ro", uri=True) self.query_point(Point(Fraction(0), Fraction(0))) except Exception: try: self.connect.close() except: pass raise FileNotFoundError
def question_24_7(query): A = Point(2, -1) B = Point(-2, 0) line1 = Line.get_line_contains_points(A, B) line2 = Line.get_line_by_point_slope(A, Fraction(-1)) tan_alpha = Fraction(1, 4) tan_beta = tan_of_sub(Fraction(1), tan_alpha) tan_theta = tan_of_sub(tan_beta, tan_alpha) slope = tan_theta line = Line.get_line_by_point_slope(A, slope) # query and show it(them) init_figure, grid_size = common.INIT_FIGURE(), common.GRID_SIZE() init_figure.extend(((line1.a, line1.b, line1.c), (line2.a, line2.b, line2.c))) solution = query.query_line_by_symmetry(line, (A,), init_figure) points = set([s[0] for s in solution]) for r in solution[:4]: p, fig = r draw_resolution(fig, points, init_figure, grid_size)