def Execute(self, device, rect): if device.has_radial_gradient: self.execute_radial(device, rect) return steps = device.gradient_steps cx, cy = self.center cx = cx * rect.right + (1 - cx) * rect.left cy = cy * rect.top + (1 - cy) * rect.bottom radius = max( hypot(rect.left - cx, rect.top - cy), hypot(rect.right - cx, rect.top - cy), hypot(rect.right - cx, rect.bottom - cy), hypot(rect.left - cx, rect.bottom - cy), ) color = self.gradient.ColorAt SetFillColor = device.SetFillColor FillCircle = device.FillCircle SetFillColor(color(0)) apply(device.FillRectangle, tuple(rect)) radius = radius * (1.0 - self.border) dr = radius / steps device.PushTrafo() device.Translate(cx, cy) center = NullPoint for i in range(steps): SetFillColor(color(float(i) / (steps - 1))) FillCircle(center, radius) radius = radius - dr device.PopTrafo()
def angle_between_points(pt1, pt2): x1, y1 = pt1 x2, y2 = pt2 inner_product = x1 * x2 + y1 * y2 len1 = math.hypot(x1, y1) len2 = math.hypot(x2, y2) return math.acos(inner_product / (len1 * len2))
def vector(self): # 3D vector conversion # X Y and Z point is converted into polar notation # then rotated about the A B and C axis. # Finally to be converted back into rectangular co-ords. # Rotate about A - X axis angle = self.a * 0.01745329 if (self.y != 0 or self.z != 0): angle = math.atan2(self.y, self.z) + angle vector = math.hypot(self.y, self.z) self.z = vector * math.cos(angle) self.y = vector * math.sin(angle) # Rotate about B - Y axis angle = self.b * 0.01745329 if (self.x != 0 or self.z != 0): angle = math.atan2(self.z, self.x) + angle vector = math.hypot(self.x, self.z) self.x = vector * math.cos(angle) self.z = vector * math.sin(angle) # Rotate about C - Z axis angle = self.c * 0.01745329 if (self.x != 0 or self.y != 0): angle = math.atan2(self.y, self.x) + angle vector = math.hypot(self.x, self.y) self.x = vector * math.cos(angle) self.y = vector * math.sin(angle)
def focus_on_hole(self, good, all): cx,cy = self.centroid(all) focpoint = None ## make a list of the bad holes bad = [] for point in all: if point not in good: bad.append(point) ## if there are bad holes, use one if bad: point = bad[0] closest_dist = math.hypot(point[0]-cx,point[1]-cy) closest_point = point for point in bad: dist = math.hypot(point[0]-cx,point[1]-cy) if dist < closest_dist: closest_dist = dist closest_point = point return closest_point ## now use a good hole for focus point = good[0] closest_dist = math.hypot(point[0]-cx,point[1]-cy) closest_point = point for point in good: dist = math.hypot(point[0]-cx,point[1]-cy) if dist < closest_dist: closest_dist = dist closest_point = point good.remove(closest_point) return closest_point
def bounding_index(coords): min_x = 100000 # start with something much higher than expected min min_y = 100000 max_x = -100000 # start with something much lower than expected max max_y = -100000 for item in coords: if item[0] < min_x: min_x = item[0] if item[0] > max_x: max_x = item[0] if item[1] < min_y: min_y = item[1] if item[1] > max_y: max_y = item[1] Nedges = len(coords)-1 length = [] for i in xrange(Nedges): ax, ay = coords[i] bx, by = coords[i+1] #print ax,ay length.append(math.hypot(bx-ax, by-ay)) #print length peri_poly = np.sum(length) peri_rect =2*(math.hypot(min_x - max_x, min_y - min_y) + math.hypot(max_x - max_x, min_y - max_y)) #print "peri_poly",peri_poly #print "peri_rect",peri_rect return peri_poly/peri_rect
def drawArrow(self, painter, posx, posy, color, width): if posx == 0.0 and posy == 0.0: return _width = self.width() _height = self.height() pen = QtGui.QPen(color, width) painter.setPen(pen) # Draw main line px = _width/2*posx/10.0 py = _height/2*posy/10.0 painter.drawLine(QtCore.QPointF(0,0),QtCore.QPointF(-px, py)) # Draw sides sidex = math.hypot(px, py)/5.0 sidey = math.hypot(px, py)/5.0 if px != 0.0: ang = math.atan(py/px) else: ang = math.pi/2.0 if posx >= 0.0: px1 = px + sidex * math.cos(math.pi+ang-0.5) py1 = py + sidey * math.sin(math.pi+ang-0.5) px2 = px + sidex * math.cos(math.pi+ang+0.5) py2 = py + sidey * math.sin(math.pi+ang+0.5) else: px1 = px - sidex * math.cos(math.pi+ang-0.5) py1 = py - sidey * math.sin(math.pi+ang-0.5) px2 = px - sidex * math.cos(math.pi+ang+0.5) py2 = py - sidey * math.sin(math.pi+ang+0.5) painter.drawLine(QtCore.QPointF(-px, py),QtCore.QPointF(-px1, py1)) painter.drawLine(QtCore.QPointF(-px, py),QtCore.QPointF(-px2, py2))
def hasReachedDest(self): """ Snaps the signal to its destination waypoint if it's near enough, and sets it on its way to the next waypoint. Also returns whether the signal has reached its destination yet. """ dist = hypot(self.path[self.next][0]-self.x, self.path[self.next][1]-self.y) if dist < self.speed: #if it's near to the next waypoint, snap to it self.setCoords(self.path[self.next][0], self.path[self.next][1]) if self.next == len(self.path)-1: #this comparison ensures that the signal will be shown at its #destination before dissapearing if dist == 0: #signal has reached its final waypoint return 2 else: return True else: self.next += 1 if hypot(self.path[self.next][0]-self.x, self.path[self.next][1]-self.y) > self.speed/2: return True return False
def computePupil(self): a = self.get_allocation() if self.x is None or self.y is None: # look ahead, but not *directly* in the middle if a.x + a.width/2 < self.parent.get_allocation().width/2: cx = a.width * 0.6 else: cx = a.width * 0.4 return cx, a.height * 0.6 EYE_X, EYE_Y = self.translate_coordinates( self.get_toplevel(), a.width/2, a.height/2) EYE_HWIDTH = a.width EYE_HHEIGHT = a.height BALL_DIST = EYE_HWIDTH/4 dx = self.x - EYE_X dy = self.y - EYE_Y if dx or dy: angle = math.atan2(dy, dx) cosa = math.cos(angle) sina = math.sin(angle) h = math.hypot(EYE_HHEIGHT * cosa, EYE_HWIDTH * sina) x = (EYE_HWIDTH * EYE_HHEIGHT) * cosa / h y = (EYE_HWIDTH * EYE_HHEIGHT) * sina / h dist = BALL_DIST * math.hypot(x, y) if dist < math.hypot(dx, dy): dx = dist * cosa dy = dist * sina return a.width/2 + dx, a.height/2 + dy
def intercept(player, target1, target2, threshold = 0): #TODO : test this function """ :param player: the current robot :param target1: the position of the ball :param target2: the position of the object to cover :param treshold: the minimum distance between player and target2 :return: the nearest position from the current robot on the line between target1 and target2 this position must be between target1 and target2 """ assert(isinstance(player, Player)) assert(isinstance(target1, Position)) assert(isinstance(target2, Position)) assert(isinstance(threshold, (int, float))) #linear algebra for finding closest point on the line position = player.pose.position d1 = target1.x - target2.x d2 = target1.y - target2.y c1 = d2*target1.x - d1*target1.y c2 = d1*position.x + d2*position.y a = np.array([[d2, -1*d1], [d1, d2]]) b = np.array([c1, c2]) try: X = np.linalg.solve(a,b) destination = Position(X[0], X[1]) if (get_distance(target1, destination) >= get_distance(target1, target2)): #if target2 between target1 and destination norme = m.hypot(d1,d2) destination = Position(300*d1/norme + target2.x, 300*d2/norme + target2.y) #go 300 unit in front of target2 on the line elif (get_distance(target2, destination) >= get_distance(target1, target2)): #if target1 between target2 and destination norme = m.hypot(d1,d2) destination = Position(-300*d1/norme + target1.x, -300*d2/norme + target1.y)#go 300 unit in front of target1 on the line return area.stayOutsideCircle(destination, target2, threshold) except np.linalg.linalg.LinAlgError: return position #return the robot's current position
def closestTarget(self, type, x, y): minimum_magnitude = 10 if self.scaleImage(): xscale, yscale = self.getScale() minimum_magnitude /= xscale closest_target = None if type is not None: for target in self.targets[type]: magnitude = math.hypot(x - target.x, y - target.y) if magnitude < minimum_magnitude: minimum_magnitude = magnitude closest_target = target if closest_target is None: for key in self.reverseorder: if key == type: continue for target in self.targets[key]: magnitude = math.hypot(x - target.x, y - target.y) if magnitude < minimum_magnitude: minimum_magnitude = magnitude closest_target = target if closest_target is not None: break return closest_target
def run(self): """ generate observetion list :returns: list of observation dicts ordered by hz """ observations = [] for coo in self.coords: if self.station_id == coo['id']: #skip station continue obs = {} d_north = coo['north'] - self.station_north d_east = coo['east'] - self.station_east d_elev = coo['elev'] - self.station_elev - self.station_ih bearing = math.atan2(d_east, d_north) dist = math.hypot(d_east, d_north) zenith = math.atan2(dist, d_elev) obs['id'] = coo['id'] obs['ih'] = self.station_ih obs['hz'] = Angle(bearing).Positive() obs['v'] = Angle(zenith).Positive() obs['distance'] = math.hypot(dist, d_elev) obs['code'] = 'ATR' obs['faces'] = self.faces if 'code' in coo and coo['code'] in modes1: obs['code'] = coo['code'] observations.append(obs) observations = sorted(observations, key = lambda a: a['hz'].GetAngle()) obs = {} obs['station'] = self.station_id obs['ih'] = self.station_ih observations.insert(0, obs) return observations
def newPosition(avgError): dock = [0,300] xmin = 5 xmax = xmin+5 + ((1000-xmin-5)*(1-avgError)) ymid = 300 yrange = 295*(1-avgError) x = random.randrange(int(xmin), int(xmax)) y = random.randrange(int(ymid - 5 - yrange), int(ymid + 5 + yrange)) goalAngle = math.atan2((dock[1]-y),(dock[0]-x)) if goalAngle < 0: goalAngle += 2*pi goalAngle = math.degrees(goalAngle) nDist = math.hypot((x-dock[0]),(y-dock[1]))/(math.hypot(1000, 300)) ttrange = 80*(1-avgError)*(nDist) tt = math.radians(random.randrange(int(goalAngle - 5 - ttrange), int(goalAngle + 5 + ttrange))) if tt > 2*pi: tt -= 2*pi if tt < 0: tt += 2*pi tcrange = int(60*(1-avgError)*nDist) tc = math.radians(random.randrange((- 5 - tcrange), (5 + tcrange))) tc += math.radians(70) print(x, y, tt, tc) state = [x/1000, y/600, tt/(2*pi), tc/(math.radians(140))] return state
def getInit(p, q, P, Q): seq = range(0, len(p)) # Create index seq.append(seq.pop(0)) index = zip(range(0, len(p)), seq) # Convert input parameters to arrays p, q, P, Q = tuple(map(lambda x: np.array(x), [p, q, P, Q])) # Get mean value of scale factrs as initial parameter of Sigma Sigma = map( lambda i: hypot( p[i[1]] - p[i[0]], q[i[1]] - q[i[0]]) / hypot( P[i[1]] - P[i[0]], Q[i[1]] - Q[i[0]]), index) Sigma0 = sum(Sigma) / len(p) # Get mean rotate angle as initial parameter of theta theta = map( lambda i: atan2( Q[i[1]] - Q[i[0]], P[i[1]] - P[i[0]]) - atan2( q[i[1]] - q[i[0]], p[i[1]] - p[i[0]]), index) theta0 = sum(theta) / len(p) # Compute initial horizontal and vertical translation tp0 = (p - Sigma0 * (P * cos(theta0) + Q * sin(theta0))).mean() tq0 = (q - Sigma0 * (P * -sin(theta0) + Q * cos(theta0))).mean() return Sigma0, theta0, tp0, tq0
def vector_abs(*args): if len(args) == 1: point = args[0] return math.hypot(point.x, point.y) elif len(args) == 2: x, y = args return math.hypot(x, y)
def getRoadY(self, index, lane_traj_string, coordinates): """ get the road relative y coordinates based on the selected lane, a positive value means left of lane trajectory """ # Needs the trajectory lane_traj = self.vehicle.getLaneTrajectory(lane_traj_string) # Checks to see that index is not the last index of the trajectory list if not index == len(lane_traj[0]) - 1: # Calculates the tangent by taking two consecutive points tangent = [lane_traj[0][index+1] - lane_traj[0][index], lane_traj[1][index + 1] - lane_traj[1][index]] else: # Does same thing but for simplicity takes the previous index in the trajectory as a reference tangent = [lane_traj[0][index] - lane_traj[0][index-1], lane_traj[1][index] - lane_traj[1][index-1]] # Normalizing the tangent tangent = [tangent[0]/math.hypot(tangent[0], tangent[1]), tangent[1]/math.hypot(tangent[0], tangent[1])] # Calculating the orthogonal vector to the tangent normal = [-tangent[1], tangent[0]] # Relative coords being calculated relCoords = [coordinates[0] - lane_traj[0][index], coordinates[1] - lane_traj[1][index]] # Takes the scalar product road_y = relCoords[0]*normal[0] + relCoords[1]*normal[1] return road_y
def vectorAngle(u,v): d = hypot(*u)*hypot(*v) c = (u[0]*v[0]+u[1]*v[1])/d if c<-1: c = -1 elif c>1: c = 1 s = u[0]*v[1]-u[1]*v[0] return degrees(copysign(acos(c),s))
def generate_voronoi_diagram(width, height, num_cells): image = Image.new("RGB", (width, height)) putpixel = image.putpixel imgx, imgy = image.size nx = [] ny = [] nr = [] ng = [] nb = [] for i in range(num_cells): nx.append(randrange(imgx)) ny.append(randrange(imgy)) nr.append(randrange(256)) ng.append(randrange(256)) nb.append(randrange(256)) for y in range(imgy): for x in range(imgx): dmin = hypot(imgx-1, imgy-1) j = -1 for i in range(num_cells): d = hypot(nx[i]-x, ny[i]-y) if d < dmin: dmin = d j = i putpixel((x, y), (nr[j], ng[j], nb[j])) image.save("VoronoiDiagram.png", "PNG") image.show()
def _compute_pupil(self, eye, offset_x, offset_y, look_x, look_y): CIRC = eye.circ / _EYE_CIRCUMFERENCE EYE_X, EYE_Y = self.translate_coordinates( self.get_toplevel(), int(eye.center[0] + offset_x), int(eye.center[1] + offset_y)) EYE_HWIDTH = CIRC EYE_HHEIGHT = CIRC BALL_DIST = EYE_HWIDTH / (eye.circ / _BALL_DIST_CIRC_RATIO * 4) dx = look_x - EYE_X dy = look_y - EYE_Y if dx or dy: angle = math.atan2(dy, dx) cosa = math.cos(angle) sina = math.sin(angle) h = math.hypot(EYE_HHEIGHT * cosa, EYE_HWIDTH * sina) x = (EYE_HWIDTH * EYE_HHEIGHT) * cosa / h y = (EYE_HWIDTH * EYE_HHEIGHT) * sina / h dist = BALL_DIST * math.hypot(x, y) if dist < math.hypot(dx, dy): dx = dist * cosa dy = dist * sina return dx + EYE_X, dy + EYE_Y, CIRC
def onCollision(self,_other): Hitbox.onCollision(self, _other) if 'AbstractFighter' in list(map(lambda x:x.__name__,_other.__class__.__bases__)) + [_other.__class__.__name__]: if _other.lockHitbox(self): if self.article is None: self.owner.applyPushback(self.base_knockback/5.0, self.getTrajectory()+180, (self.damage / 3.0 + 3.0)*self.hitlag_multiplier) x_diff = self.rect.centerx - _other.rect.centerx y_diff = self.rect.centery - _other.rect.centery x_vel = self.x_bias*self.owner.facing+self.x_draw*x_diff y_vel = self.y_bias+self.y_draw*y_diff self.owner.data_log.addToData('Damage Dealt',self.damage) _other.applyKnockback(self.damage, math.hypot(x_vel,y_vel)*self.velocity_multiplier+self.base_knockback, self.knockback_growth, self.owner.getForwardWithOffset(self.owner.facing*(math.degrees(-math.atan2(y_vel,x_vel))+self.trajectory)), self.weight_influence, self.hitstun_multiplier, self.base_hitstun, self.hitlag_multiplier, self.ignore_armor) else: x_diff = self.article.rect.centerx - _other.rect.centerx y_diff = self.article.rect.centery - _other.rect.centery x_vel = self.x_bias*self.article.facing+self.x_draw*x_diff y_vel = self.y_bias+self.y_draw*y_diff self.owner.data_log.addToData('Damage Dealt',self.damage) _other.applyKnockback(self.damage, math.hypot(x_vel,y_vel)*self.velocity_multiplier+self.base_knockback, self.knockback_growth, getForwardWithOffset(self.article.facing*(math.degrees(-math.atan2(y_vel,x_vel))+self.trajectory), self.article), self.weight_influence, self.hitstun_multiplier, self.base_hitstun, self.hitlag_multiplier, self.ignore_armor) _other.trail_color = self.trail_color offset = random.randrange(0, 359) hit_intersection = self.rect.clip(_other.sprite.rect).center hitlag = (self.damage/3.0+3.0)*self.hitlag_multiplier from article import HitArticle for i in range(int(hitlag)): art = HitArticle(self.owner, hit_intersection, 0.5, offset+i*360/int(hitlag), 0.5*hitlag, .4, self.trail_color) self.owner.articles.add(art) Hitbox.onCollision(self, _other) if self.article and hasattr(self.article, 'onCollision'): self.article.onCollision(_other)
def calcCoordsAndDelay(self, startCoords, endCoords): veloX, veloY = (0, 0) coordsAndDelay = [] xs, ys = startCoords xe, ye = endCoords totalDist = math.hypot(xs - xe, ys - ye) self._windX = 0 self._windY = 0 while True: veloX, veloY = self._calcVelocity( (xs, ys), (xe, ye), veloX, veloY, totalDist) xs += veloX ys += veloY w = round( max(random.randint(0, max(0, round(100 / self.mouseSpeed) - 1)) * 6, 5) * 0.9) coordsAndDelay.append((xs, ys, w)) if math.hypot(xs - xe, ys - ye) < 1: break if round(xe) != round(xs) or round(ye) != round(ys): coordsAndDelay.append((round(xe), round(ye), 0)) return coordsAndDelay
def getPointBetweenBallAndGoal(self,dist_from_goal): '''returns defensive position between ball (x,y) and goal (x,y) at <dist_from_ball> centimeters away from ball''' leftPostToBall = hypot(Constants.LANDMARK_MY_GOAL_LEFT_POST_X - self.brain.ball.x, Constants.LANDMARK_MY_GOAL_LEFT_POST_Y - self.brain.ball.y) rightPostToBall = hypot(Constants.LANDMARK_MY_GOAL_RIGHT_POST_X - self.brain.ball.x, Constants.LANDMARK_MY_GOAL_RIGHT_POST_Y - self.brain.ball.y) goalLineIntersectionX = Constants.LANDMARK_MY_GOAL_LEFT_POST_X +\ (leftPostToBall*Constants.GOAL_WIDTH)/(leftPostToBall+rightPostToBall) ballToInterceptDist = hypot(self.brain.ball.y - Constants.LANDMARK_MY_GOAL_LEFT_POST_Y, self.brain.ball.x - goalLineIntersectionX) pos_x = ((dist_from_goal / ballToInterceptDist)* (self.brain.ball.x -goalLineIntersectionX) + goalLineIntersectionX) pos_y = ((dist_from_goal / ballToInterceptDist)* (self.brain.ball.y - Constants.LANDMARK_MY_GOAL_LEFT_POST_Y) + Constants.LANDMARK_MY_GOAL_LEFT_POST_Y) return pos_x,pos_y
def estimate(self): """ Estimate the additional drift since previous acquisition+estimation. Note: It should be only called once after every acquisition. To read the value again, use .orig_drift. return (float, float): estimated current drift in X/Y SEM px """ # Calculate the drift between the last two frames and # between the last and first frame if len(self.raw) > 1: # Note: prev_drift and orig_drift, don't represent exactly the same # value as the previous image also had drifted. So we need to # include also the drift of the previous image. # Also, CalculateDrift return the shift in image pixels, which is # different (usually bigger) from the SEM px. prev_drift = CalculateDrift(self.raw[-2], self.raw[-1], 10) prev_drift = (prev_drift[0] * self._scale[0] + self.orig_drift[0], prev_drift[1] * self._scale[1] + self.orig_drift[1]) orig_drift = CalculateDrift(self.raw[0], self.raw[-1], 10) self.orig_drift = (orig_drift[0] * self._scale[0], orig_drift[1] * self._scale[1]) logging.debug("Current drift: %s", self.orig_drift) logging.debug("Previous frame diff: %s", prev_drift) if (abs(self.orig_drift[0] - prev_drift[0]) > 5 or abs(self.orig_drift[1] - prev_drift[1]) > 5): logging.warning("Drift cannot be measured precisely, " "hesitating between %s and %s px", self.orig_drift, prev_drift) # Update max_drift if math.hypot(*self.orig_drift) > math.hypot(*self.max_drift): self.max_drift = self.orig_drift return self.orig_drift
def segment_sp(sp): bks = set() # direction changes xsg = 0 ysg = 0 for i in range(2 * len(sp)): imod = i % len(sp) xsg1 = sp[imod][-1][0] - sp[imod][0][0] ysg1 = sp[imod][-1][1] - sp[imod][0][1] if xsg * xsg1 < 0 or ysg * ysg1 < 0: bks.add(imod) xsg = xsg1 ysg = ysg1 else: if xsg == 0: xsg = xsg1 if ysg == 0: ysg = ysg1 # angle breaks for i in range(len(sp)): dx0 = sp[i-1][-1][0] - sp[i-1][-2][0] dy0 = sp[i-1][-1][1] - sp[i-1][-2][1] dx1 = sp[i][1][0] - sp[i][0][0] dy1 = sp[i][1][1] - sp[i][0][1] bend = dx1 * dy0 - dx0 * dy1 if (dx0 == 0 and dy0 == 0) or (dx1 == 0 and dy1 == 0): bks.add(i) else: bend = bend / (math.hypot(dx0, dy0) * math.hypot(dx1, dy1)) # for small angles, bend is in units of radians if abs(bend) > 0.02: bks.add(i) return sorted(bks)
def __init__(self, s1, s2, l, st=None, lt=None, col=None, t=None, **kw): super(Chamfer, self).__init__(s1, s2, st, lt, col, t, **kw) _len = util.get_float(l) if _len < 0.0: raise ValueError, "Invalid chamfer length: %g" % _len if _len > s1.length(): raise ValueError, "Chamfer is longer than first Segment." if _len > s2.length(): raise ValueError, "Chamfer is longer than second Segment." _xi, _yi = SegJoint.getIntersection(self) # print "xi: %g; yi: %g" % (_xi, _yi) _sp1, _sp2 = SegJoint.getMovingPoints(self) _xp, _yp = _sp1.getCoords() _sep = hypot((_yp - _yi), (_xp - _xi)) if _sep > (_len + 1e-10): # print "sep: %g" % _sep # print "xp: %g; yp: %g" % (_xp, _yp) raise ValueError, "First segment too far from intersection point." _xp, _yp = _sp2.getCoords() _sep = hypot((_yp - _yi), (_xp - _xi)) if _sep > (_len + 1e-10): # print "sep: %g" % _sep # print "xp: %g; yp: %g" % (_xp, _yp) raise ValueError, "Second segment too far from intersection point." self.__length = _len self.ignore('moved') try: self._moveSegmentPoints(_len) finally: self.receive('moved')
def _resolve_size(self, width, height, center_x, center_y): if self.size_type == 'explicit': size_x, size_y = self.size return percentage(size_x, width), percentage(size_y, height) left = abs(center_x) right = abs(width - center_x) top = abs(center_y) bottom = abs(height - center_y) pick = min if self.size.startswith('closest') else max if self.size.endswith('side'): if self.shape == 'circle': size_xy = pick(left, right, top, bottom) return size_xy, size_xy # else: ellipse return pick(left, right), pick(top, bottom) # else: corner if self.shape == 'circle': size_xy = pick(math.hypot(left, top), math.hypot(left, bottom), math.hypot(right, top), math.hypot(right, bottom)) return size_xy, size_xy # else: ellipse corner_x, corner_y = pick( (left, top), (left, bottom), (right, top), (right, bottom), key=lambda a: math.hypot(*a)) return corner_x * math.sqrt(2), corner_y * math.sqrt(2)
def fill_data(df, start_date, end_date, nan=True): """ Fill data in missing rows of *df* in the time interval *start_date* to *end_date* (one minute sample period, closed on the left and open on the right)). If *nan* will with not a numbers, otherwise fill with 88888 (i.e., the missing value in IAGA2002 data records). Return the tuple of the list of date/times for each data record and the list of tuple values (containing the N, E, Z, and F in [nT] in that order). """ data_map = {} for row in df.itertuples(): N = row.N E = row.E Z = row.Z F = math.hypot(math.hypot(N, E), Z) data_map[row.Date_UTC] = (N, E, Z, F) # fill missing records filled_data = [] dts = list(PD.date_range(start=start_date, end=end_date, freq="min"))[:-1] if nan: fill_value = (float("nan"),) * 4 else: fill_value = (88888,) * 4 missing_count = 0 for dt in dts: if dt not in data_map: missing_count += 1 filled_data.append(data_map.get(dt, fill_value)) if missing_count > 0: logger.info("filled {} missing values".format(missing_count)) return dts, filled_data
def update(self): self.show(self.image,False) #print 'time passed', time_passed #This goes through the location of the ant when it stops to see if there is a collony there if hypot ((self.int_pos[0]-self.int_target[0]),(self.int_pos[1]-self.int_target[1])) <=5: for c in self.game.colony_list: # and if so runs that collonies collide code if hypot((c.pos[0]-self.x),(c.pos[1]-self.y)) <= 20: c.collide(self) else: self.die() target_vector = sub(self.target, self.pos) # a threshold to stop moving if the distance is to small. # it prevents a 'flickering' between two points if magnitude(target_vector) < 2: return # apply the ship's speed to the vector move_vector = [c * self.speed for c in normalize(target_vector)] # update position self.x, self.y = add(self.pos, move_vector) #print self.x, self.y self.angle = degrees(atan2(self.t_y - self.y, self.t_x - self.x)) + 90 #calculate angle to target self.show(self.image,True)
def move(self,Coin,player): if self.state == "neutral": self.state = "chasecoin" if self.state == "chasecoin": if self.rect.x != Coin.rect.x or self.rect.y != Coin.rect.y: dx = Coin.rect.x - self.rect.x dy = Coin.rect.y - self.rect.y dist = math.hypot(dx, dy) dx = dx / dist dy = dy / dist self.speedX = dx * self.maxspeed self.speedY = dy * self.maxspeed if self.rect.x != player.rect.x or self.rect.y != player.rect.y: dx = player.rect.x - self.rect.x dy = player.rect.y - self.rect.y dist = math.hypot(dx,dy) if dist < 150: self.state = "chaseplayer" dx = dx / dist dy = dy / dist self.speedX = dx * self.maxspeed self.speedY = dy * self.maxspeed bullet = Bullet(self) self.bullets.add(bullet) else: self.state = "chasecoin"
def test_math_functions(self): df = self.sc.parallelize([Row(a=i, b=2 * i) for i in range(10)]).toDF() from pyspark.sql import functions import math def get_values(l): return [j[0] for j in l] def assert_close(a, b): c = get_values(b) diff = [abs(v - c[k]) < 1e-6 for k, v in enumerate(a)] return sum(diff) == len(a) assert_close([math.cos(i) for i in range(10)], df.select(functions.cos(df.a)).collect()) assert_close([math.cos(i) for i in range(10)], df.select(functions.cos("a")).collect()) assert_close([math.sin(i) for i in range(10)], df.select(functions.sin(df.a)).collect()) assert_close([math.sin(i) for i in range(10)], df.select(functions.sin(df['a'])).collect()) assert_close([math.pow(i, 2 * i) for i in range(10)], df.select(functions.pow(df.a, df.b)).collect()) assert_close([math.pow(i, 2) for i in range(10)], df.select(functions.pow(df.a, 2)).collect()) assert_close([math.pow(i, 2) for i in range(10)], df.select(functions.pow(df.a, 2.0)).collect()) assert_close([math.hypot(i, 2 * i) for i in range(10)], df.select(functions.hypot(df.a, df.b)).collect()) assert_close([math.hypot(i, 2 * i) for i in range(10)], df.select(functions.hypot("a", u"b")).collect()) assert_close([math.hypot(i, 2) for i in range(10)], df.select(functions.hypot("a", 2)).collect()) assert_close([math.hypot(i, 2) for i in range(10)], df.select(functions.hypot(df.a, 2)).collect())
def get_trans_power(n, control): """Takes the motor number and returns the power it should output for translational motion, from -1 to 1. Raises a ValueError if the motor number is unrecognized.""" # these motors don't have an effect on translational speed if n == MOTOR.FR_VT or n == MOTOR.BA_VT: return 0; x = control.trans_x_value(); y = control.trans_y_value(); if x == 0 and y == 0: return 0; m1 = .5 * x + y / (2 * math.sqrt(3)); m2 = -.5 * x + y / (2 * math.sqrt(3)); m1_norm = m1 / abs(max(m1, m2)) * min(math.hypot(x, y), 1); m2_norm = m2 / abs(max(m1, m2)) * min(math.hypot(x, y), 1); if n == MOTOR.FR_LF: return -1 * m1_norm; if n == MOTOR.FR_RT: return -1 * m2_norm; if n == MOTOR.BA_RT: return m1_norm; if n == MOTOR.BA_LF: return m2_norm; raise ValueError("get_trans_power: Illegal motor number");
def length(self) -> float: """ This property exists in case Point2 is used as a vector. """ return math.hypot(self[0], self[1])
def magnitude(self) -> float: """ Returns magnitude of vector""" return math.hypot(self.x, self.y)
def getGoalDistace(self): goal_distance = round( math.hypot(self.goal_x - self.position.x, self.goal_y - self.position.y), 2) return goal_distance
def distance(a, b): x1, y1 = a x2, y2 = b return hypot(x2 - x1, y2 - y1)
def did_hit(self, x, y, i): c = eval(self.cfg['param']['c']) ix = int(c[i][0]) iy = int(c[i][1]) return math.hypot(x - ix, y - iy) < 20
def _DoCenterSpot(future, ccd, stage, escan, mx_steps, type, background, dataflow): """ Iteratively acquires an optical image, finds the coordinates of the spot (center) and moves the stage to this position. Repeats until the found coordinates are at the center of the optical image or a maximum number of steps is reached. future (model.ProgressiveFuture): Progressive future provided by the wrapper ccd (model.DigitalCamera): The CCD stage (model.Actuator): The stage escan (model.Emitter): The e-beam scanner mx_steps (int): Maximum number of steps to reach the center type (string): Type of move in order to align returns (float or None): Final distance to the center #m raises: CancelledError() if cancelled """ try: logging.debug("Aligning spot...") if type == OBJECTIVE_MOVE: stage_ab = ConvertStage("converter-ab", "stage", children={"orig": stage}, axes=["b", "a"], rotation=math.radians(-135)) image = ccd.data.get(asap=False) # Center of optical image pixelSize = image.metadata[model.MD_PIXEL_SIZE] center_pxs = (image.shape[1] / 2, image.shape[0] / 2) # Epsilon distance below which the lens is considered centered. The worse of: # * 1.5 pixels (because the CCD resolution cannot give us better) # * 1 µm (because that's the best resolution of our actuators) err_mrg = max(1.5 * pixelSize[0], 1e-06) # m steps = 0 # Stop once spot is found on the center of the optical image dist = None while True: if future._spot_center_state == CANCELLED: raise CancelledError() # Or once max number of steps is reached if steps >= mx_steps: break # Wait to make sure no previous spot is detected image = SubstractBackground(ccd, dataflow) try: spot_pxs = FindSpot(image) except ValueError: return None, None tab_pxs = [a - b for a, b in zip(spot_pxs, center_pxs)] tab = (tab_pxs[0] * pixelSize[0], tab_pxs[1] * pixelSize[1]) dist = math.hypot(*tab) # If we are already there, stop if dist <= err_mrg: break # Move to the found spot if type == OBJECTIVE_MOVE: f = stage_ab.moveRel({"x": tab[0], "y": -tab[1]}) f.result() elif type == STAGE_MOVE: f = stage.moveRel({"x": -tab[0], "y": tab[1]}) f.result() else: escan.translation.value = (-tab_pxs[0], -tab_pxs[1]) steps += 1 # Update progress of the future future.set_end_time( time.time() + estimateCenterTime(ccd.exposureTime.value, dist)) return dist, tab finally: with future._center_lock: if future._spot_center_state == CANCELLED: raise CancelledError() future._spot_center_state = FINISHED
from math import hypot catetoOpostoY = float(input('\033[1m\033[7mDigite o cateto oposto(eixoY): ')) catetoAdjacenteX = float(input('Digite o cateto adjacente(eixoX): ')) # hipotenusa = sqrt(catetoOpostoY ** 2 + catetoAdjacenteX ** 2) hi = hypot(catetoOpostoY, catetoAdjacenteX) print('A hipotenusa do triângulo retângulo é {:.2f}.\033[m'.format(hi))
def get_distance(bar, longitude, latitude): bar_longitude, bar_latitude = bar['geometry']['coordinates'] distance = math.hypot(bar_longitude - longitude, bar_latitude - latitude) return distance
# calcula o cumprimento da hipotenusa '''opo = float(input('Digite o valor do cateto oposto: ')) adj = float(input('Digite o valor do cateto adjacente: ')) hip = (opo ** 2 + adj ** 2) ** (1/2) print('O cumprimento da hipotenusa é: {:.2f} '.format(hip))''' import math opo = float(input('Digite o valor do cateto oposto: ')) adj = float(input('Digite o valor do cateto adjacente: ')) hip = math.hypot(opo, adj) print('O cumprimento da hipotenusa é: {:.2f} '.format(hip))
def calc_distance(state, point_x, point_y): dx = state.rear_x - point_x dy = state.rear_y - point_y return math.hypot(dx, dy)
def __lt__(self, point): if isinstance(point, Vertex): return self.hypo() < math.hypot(point.x, point.y) else: raise Error('Argument is not a Vertex')
imgx = 500 imgy = 500 # image size image = Image.new("RGB", (imgx, imgy)) draw = ImageDraw.Draw(image) pixels = image.load() n = 200 # of seed points m = -30 # random.randint(0, n - 1) # degree (?) seedsX = [random.randint(0, imgx - 1) for i in range(n)] seedsY = [random.randint(0, imgy - 1) for i in range(n)] # find max distance maxDist = 0.0 for ky in range(imgy): for kx in range(imgx): # create a sorted list of distances to all seed points dists = [math.hypot(seedsX[i] - kx, seedsY[i] - ky) for i in range(n)] dists.sort() if dists[m] > maxDist: maxDist = dists[m] # paint for ky in range(imgy): for kx in range(imgx): # create a sorted list of distances to all seed points dists = [math.hypot(seedsX[i] - kx, seedsY[i] - ky) for i in range(n)] dists.sort() c = int(round(255 * dists[m] / maxDist)) pixels[kx, ky] = (c, c, c) label = "N = " + str(n) + " M = " + str(m) draw.text((0, 0), label, (0, 255, 0)) # write to top-left using green color image.save("WorleyNoise.png", "PNG")
def distance(x,y,x1,y1): return math.hypot(x-x1, y - y1)
def velocity(self): return math.hypot(self.vx, self.vy)
def __abs__(self): return hypot(self.x, self.y)
#!usr/bin/python3 ''' Faça um programa que leia o comprimento do cateto oposto e do cateto adjacente de um triângulo retângulo. Calcule e mostre o comprimento da hipotenusa. Utilizar o método hypot. ''' from math import hypot cateto_oposto = float(input('Comprimento do cateo oposto: ')) cateto_adjacente = float(input('Comprimento do cateto adjacente: ')) hipotenusa = hypot(cateto_oposto, cateto_adjacente) print(f'A hipotenusa vai medir {hipotenusa:.2f}')
def dist(p1, p2): "Distance between two points" return hypot(p2[0] - p1[0], p2[1] - p1[1])
def polar2d(vx, vy, deg=True): "2D Cartesian to Polar conversion" a = atan2(vy, vx) return hypot(vx, vy), (a / DEG if deg else a)
def xyDist(xxx_todo_changeme, xxx_todo_changeme1): '''return distance between two points''' (x0, y0) = xxx_todo_changeme (x1, y1) = xxx_todo_changeme1 return hypot((x1 - x0), (y1 - y0))
def __abs__(self): # 2 vektörün magnitutesini almak return hypot(self.x, self.y)
def __abs__(self) -> float: return math.hypot(self.x, self.y)
class MathTests: REGCASES = [] for name in unary_math_functions: try: input, output = (0.3,), getattr(math, name)(0.3) except AttributeError: # cannot test this function continue except ValueError: input, output = (1.3,), getattr(math, name)(1.3) REGCASES.append((name, input, output)) IRREGCASES = [ ('atan2', (0.31, 0.123), math.atan2(0.31, 0.123)), ('fmod', (0.31, 0.123), math.fmod(0.31, 0.123)), ('hypot', (0.31, 0.123), math.hypot(0.31, 0.123)), ('pow', (0.31, 0.123), math.pow(0.31, 0.123)), ('pow', (-0.31, 0.123), ValueError), ('pow', (-0.5, 2.0), 0.25), ('pow', (-0.5, 1.0), -0.5), ('pow', (-0.5, 0.0), 1.0), ('pow', (-0.5, -1.0), -2.0), ('ldexp', (3.375, 2), 13.5), ('ldexp', (1.0, -10000), 0.0), # underflow ('frexp', (-1.25,), lambda x: x == (-0.625, 1)), ('modf', (4.25,), lambda x: x == (0.25, 4.0)), ('modf', (-4.25,), lambda x: x == (-0.25, -4.0)), ('copysign', (1.5, 0.0), 1.5), ('copysign', (1.5, -0.0), -1.5), ('copysign', (1.5, INFINITY), 1.5), ('copysign', (1.5, -INFINITY), -1.5), ] if sys.platform != 'win32': # all NaNs seem to be negative there...? IRREGCASES += [ ('copysign', (1.5, NAN), 1.5), ('copysign', (1.75, -NAN), -1.75), # special case for -NAN here ] OVFCASES = [ ('cosh', (9999.9,), OverflowError), ('sinh', (9999.9,), OverflowError), ('exp', (9999.9,), OverflowError), ('pow', (10.0, 40000.0), OverflowError), ('ldexp', (10.0, 40000), OverflowError), ('log', (0.0,), ValueError), ('log', (-1.,), ValueError), ('log10', (0.0,), ValueError), ] INFCASES = [ ('acos', (INFINITY,), ValueError), ('acos', (-INFINITY,), ValueError), ('asin', (INFINITY,), ValueError), ('asin', (-INFINITY,), ValueError), ('atan', (INFINITY,), math.pi / 2), ('atan', (-INFINITY,), -math.pi / 2), ('atanh', (INFINITY,), ValueError), ('atanh', (-INFINITY,), ValueError), ('ceil', (INFINITY,), positiveinf), ('ceil', (-INFINITY,), negativeinf), ('cos', (INFINITY,), ValueError), ('cos', (-INFINITY,), ValueError), ('cosh', (INFINITY,), positiveinf), ('cosh', (-INFINITY,), positiveinf), ('exp', (INFINITY,), positiveinf), ('exp', (-INFINITY,), 0.0), ('fabs', (INFINITY,), positiveinf), ('fabs', (-INFINITY,), positiveinf), ('floor', (INFINITY,), positiveinf), ('floor', (-INFINITY,), negativeinf), ('sin', (INFINITY,), ValueError), ('sin', (-INFINITY,), ValueError), ('sinh', (INFINITY,), positiveinf), ('sinh', (-INFINITY,), negativeinf), ('sqrt', (INFINITY,), positiveinf), ('sqrt', (-INFINITY,), ValueError), ('tan', (INFINITY,), ValueError), ('tan', (-INFINITY,), ValueError), ('tanh', (INFINITY,), 1.0), ('tanh', (-INFINITY,), -1.0), ('log', (INFINITY,), positiveinf), ('log', (-INFINITY,), ValueError), ('log10', (INFINITY,), positiveinf), ('log10', (-INFINITY,), ValueError), ('frexp', (INFINITY,), lambda x: isinf(x[0])), ('ldexp', (INFINITY, 3), positiveinf), ('ldexp', (-INFINITY, 3), negativeinf), ('modf', (INFINITY,), lambda x: positiveinf(x[1])), ('modf', (-INFINITY,), lambda x: negativeinf(x[1])), ('pow', (INFINITY, 0.0), 1.0), ('pow', (INFINITY, 0.001), positiveinf), ('pow', (INFINITY, -0.001), 0.0), ('pow', (-INFINITY, 0.0), 1.0), ('pow', (-INFINITY, 0.001), positiveinf), ('pow', (-INFINITY, -0.001), 0.0), ('pow', (-INFINITY, 3.0), negativeinf), ('pow', (-INFINITY, 6.0), positiveinf), ('pow', (-INFINITY, -13.0), -0.0), ('pow', (-INFINITY, -128.0), 0.0), ('pow', (1.001, INFINITY), positiveinf), ('pow', (1.0, INFINITY), 1.0), ('pow', (0.999, INFINITY), 0.0), ('pow', (-0.999,INFINITY), 0.0), #('pow', (-1.0, INFINITY), 1.0, but strange, could also be -1.0), ('pow', (-1.001,INFINITY), positiveinf), ('pow', (1.001, -INFINITY), 0.0), ('pow', (1.0, -INFINITY), 1.0), #('pow', (0.999, -INFINITY), positiveinf, but get OverflowError), #('pow', (INFINITY, INFINITY), positiveinf, but get OverflowError), ('pow', (INFINITY, -INFINITY), 0.0), ('pow', (-INFINITY, INFINITY), positiveinf), ] IRREGERRCASES = [ # ('atan2', (INFINITY, -2.3), math.pi / 2), ('atan2', (INFINITY, 0.0), math.pi / 2), ('atan2', (INFINITY, 3.0), math.pi / 2), #('atan2', (INFINITY, INFINITY), ?strange), ('atan2', (2.1, INFINITY), 0.0), ('atan2', (0.0, INFINITY), 0.0), ('atan2', (-0.1, INFINITY), -0.0), ('atan2', (-INFINITY, 0.4), -math.pi / 2), ('atan2', (2.1, -INFINITY), math.pi), ('atan2', (0.0, -INFINITY), math.pi), ('atan2', (-0.1, -INFINITY), -math.pi), # ('fmod', (INFINITY, 1.0), ValueError), ('fmod', (1.0, INFINITY), 1.0), ('fmod', (1.0, -INFINITY), 1.0), ('fmod', (INFINITY, INFINITY), ValueError), # ('hypot', (-INFINITY, 1.0), positiveinf), ('hypot', (-2.3, -INFINITY), positiveinf), ] binary_math_functions = ['atan2', 'fmod', 'hypot', 'pow'] NANCASES1 = [ (name, (NAN,), isnan) for name in unary_math_functions] NANCASES2 = [ (name, (NAN, 0.1), isnan) for name in binary_math_functions] NANCASES3 = [ (name, (-0.2, NAN), isnan) for name in binary_math_functions] NANCASES4 = [ (name, (NAN, -INFINITY), isnan) for name in binary_math_functions if name != 'hypot'] NANCASES5 = [ (name, (INFINITY, NAN), isnan) for name in binary_math_functions if name != 'hypot'] NANCASES6 = [ ('frexp', (NAN,), lambda x: isnan(x[0])), ('ldexp', (NAN, 2), isnan), ('hypot', (NAN, INFINITY), positiveinf), ('hypot', (NAN, -INFINITY), positiveinf), ('hypot', (INFINITY, NAN), positiveinf), ('hypot', (-INFINITY, NAN), positiveinf), ('modf', (NAN,), lambda x: (isnan(x[0]) and isnan(x[1]))), ] # The list of test cases. Note that various tests import this, # notably in rpython/lltypesystem/module and in translator/c/test. TESTCASES = (REGCASES + IRREGCASES + OVFCASES + INFCASES + IRREGERRCASES + NANCASES1 + NANCASES2 + NANCASES3 + NANCASES4 + NANCASES5 + NANCASES6)
def distance(p1, p2): x1, y1 = p1 x2, y2 = p2 return math.hypot(x2 - x1, y2 - y1)
def distance_to(self, target: Union[Unit, Point2]) -> float: """Calculate a single distance from a point or unit to another point or unit :param target:""" p = target.position return math.hypot(self[0] - p[0], self[1] - p[1])
'atan2': [ lambda y, x: x / (x**2 + y**2), # Correct for x == 0 lambda y, x: -y / (x**2 + y**2) ], # Correct for x == 0 'atanh': [lambda x: 1 / (1 - x**2)], 'copysign': [_deriv_copysign, lambda x, y: 0], 'cos': [lambda x: -math.sin(x)], 'cosh': [math.sinh], 'degrees': [lambda x: math.degrees(1)], 'erf': [lambda x: math.exp(-x**2) * erf_coef], 'erfc': [lambda x: -math.exp(-x**2) * erf_coef], 'exp': [math.exp], 'expm1': [math.exp], 'fabs': [_deriv_fabs], 'hypot': [lambda x, y: x / math.hypot(x, y), lambda x, y: y / math.hypot(x, y)], 'log': [log_der0, lambda x, y: -math.log(x, y) / y / math.log(y)], 'log10': [lambda x: 1 / x / math.log(10)], 'log1p': [lambda x: 1 / (1 + x)], 'pow': [_deriv_pow_0, _deriv_pow_1], 'radians': [lambda x: math.radians(1)], 'sin': [math.cos], 'sinh': [math.cosh], 'sqrt': [lambda x: 0.5 / math.sqrt(x)], 'tan': [lambda x: 1 + math.tan(x)**2], 'tanh': [lambda x: 1 - math.tanh(x)**2] } # Many built-in functions in the math module are wrapped with a # version which is uncertainty aware:
def distance(self, other): return math.hypot((self.x - other.x), (self.y - other.y))
def _hypot_of_double(x): return math.hypot(x)
def calc_heuristic(self, n1, n2): w = 1.0 # weight of heuristic d = w * math.hypot(n1.x - n2.x, n1.y - n2.y) d = d * self.costPerGrid return d
def circumcircle_radius(self) -> float: """ circum circle radius""" return math.hypot(self._width, self._height) * .5
def _get_dpi(ctm_shorthand, image_size): """Given the transformation matrix and image size, find the image DPI. PDFs do not include image resolution information within image data. Instead, the PDF page content stream describes the location where the image will be rasterized, and the effective resolution is the ratio of the pixel size to raster target size. Normally a scanned PDF has the paper size set appropriately but this is not guaranteed. The most common case is a cropped image will change the page size (/CropBox) without altering the page content stream. That means it is not sufficient to assume that the image fills the page, even though that is the most common case. A PDF image may be scaled (always), cropped, translated, rotated in place to an arbitrary angle (rarely) and skewed. Only equal area mappings can be expressed, that is, it is not necessary to consider distortions where the effective DPI varies with position. To determine the image scale, transform an offset axis vector v0 (0, 0), width-axis vector v0 (1, 0), height-axis vector vh (0, 1) with the matrix, which gives the dimensions of the image in PDF units. From there we can compare to actual image dimensions. PDF uses row vector * matrix_tranposed unlike the traditional matrix * column vector. The offset, width and height vectors can be combined in a matrix and multiplied by the transform matrix. Then we want to calculated magnitude(width_vector - offset_vector) and magnitude(height_vector - offset_vector) When the above is worked out algebraically, the effect of translation cancels out, and the vector magnitudes become functions of the nonzero transformation matrix indices. The results of the derivation are used in this code. pdfimages -list does calculate the DPI in some way that is not completely naive, but it does not get the DPI of rotated images right, so cannot be used anymore to validate this. Photoshop works, or using Acrobat to rotate the image back to normal. It does not matter if the image is partially cropped, or even out of the /MediaBox. """ a, b, c, d, _, _ = ctm_shorthand # Calculate the width and height of the image in PDF units image_drawn_width = hypot(a, b) image_drawn_height = hypot(c, d) # The scale of the image is pixels per unit of default user space (1/72") scale_w = image_size[0] / image_drawn_width scale_h = image_size[1] / image_drawn_height # DPI = scale * 72 dpi_w = scale_w * 72.0 dpi_h = scale_h * 72.0 return dpi_w, dpi_h