Python math.hypot() Examples

The following are code examples for showing how to use math.hypot(). They are from open source Python projects. You can vote up the examples you like or vote down the ones you don't like.

Example 1
Project: building-boundary   Author: Geodan   File: geometry.py    MIT License 6 votes vote down vote up
def distance(p1, p2):
    """
    The euclidean distance between two points.

    Parameters
    ----------
    p1 : list or array
        A point in 2D space.
    p2 : list or array
        A point in 2D space.

    Returns
    -------
    distance : float
        The euclidean distance between the two points.
    """
    return math.hypot(*(p1-p2)) 
Example 2
Project: building-boundary   Author: Geodan   File: segment.py    MIT License 6 votes vote down vote up
def _create_line_segment(self):
        """
        Defines a line segment of the fitted line by creating
        the end points, length and orientation.

        Raises
        ------
        ValueError
            If not enough points exist to create a line segment.
        """
        if len(self.points) == 1:
            raise ValueError('Not enough points to create a line.')
        else:
            start_point = self._point_on_line(self.points[0])
            end_point = self._point_on_line(self.points[-1])
            self.end_points = np.array([start_point, end_point])
            dx, dy = np.diff(self.end_points, axis=0)[0]
            self.length = math.hypot(dx, dy)
            self.orientation = math.atan2(dy, dx) 
Example 3
Project: Old-school-processing   Author: cianfrocco-lab   File: ImagePanelTools.py    MIT License 6 votes vote down vote up
def OnLeftClick(self, evt):
		if self.button.GetToggle():
			if self.start is not None:
				x = evt.m_x #- self.imagepanel.offset[0]
				y = evt.m_y #- self.imagepanel.offset[1]
				x0, y0 = self.start
				dx, dy = x - x0, y - y0
				self.measurement = {
					'from': self.start,
					'to': (x, y),
					'delta': (dx, dy),
					'magnitude': math.hypot(dx, dy),
					'angle': math.degrees(math.atan2(dy, dx)),
				}
				mevt = MeasurementEvent(self.imagepanel, dict(self.measurement))
				self.imagepanel.GetEventHandler().AddPendingEvent(mevt)
			self.start = self.imagepanel.view2image((evt.m_x, evt.m_y))

	#-------------------- 
Example 4
Project: Old-school-processing   Author: cianfrocco-lab   File: fftfun.py    MIT License 6 votes vote down vote up
def fitFirstCTFNode(pow, rpixelsize, defocus, ht):
	filter = ndimage.gaussian_filter(pow,3)
	grad = ndimage.gaussian_gradient_magnitude(filter,3)
	thr = imagefun.threshold(grad,grad.mean()+3*grad.std())
	if defocus:
		z = abs(defocus)
		s = calculateFirstNode(ht,z)
		dmean = max(0.8*s/rpixelsize, 30)
	else:
		shape = pow.shape
		r = 20
		center = ( shape[0] / 2, shape[1] / 2 ) 
		grad[center[0]-r: center[0]+r, center[1]-r: center[1]+r] = 0
		peak = ndimage.maximum_position(grad)
		dmean = math.hypot(peak[0] - center[0], peak[1] - center[1])
	drange = max(dmean / 4, 10)
	eparams = find_ast_ellipse(grad,thr,dmean,drange)
	if eparams:
		z0, zast, ast_ratio, alpha = getAstigmaticDefocii(eparams,rpixelsize, ht)
		return z0,zast,ast_ratio, alpha, eparams 
Example 5
Project: AxiSurface   Author: patriciogonzalezvivo   File: tools.py    BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def join_path(path, tolerance):
    if len(path) < 2:
        return path
    result = [list(path[0])]
    for path in path[1:]:
        x1, y1 = result[-1][-1]
        x2, y2 = path[0]
        d = hypot(x2 - x1, y2 - y1)
        if d <= tolerance:
            result[-1].extend(path)
        else:
            result.append(list(path))
    return result

# Convertions
# ----------------------------------------------------------------- 
Example 6
Project: Autoenv   Author: intelligent-control-lab   File: trajdata.py    MIT License 6 votes vote down vote up
def __init__(self, trajdata: ngsim_trajdata.NGSIMTrajdata, carid: int):
        dfstart = trajdata.car2start[carid]
        N = trajdata.df.at[dfstart, 'n_frames_in_dataset']
        x_arr = []
        y_arr = []
        theta_arr = []
        v_arr = []
        for i in range(N):
            x_arr.append(trajdata.df.at[dfstart + i, 'global_x'])
            y_arr.append(trajdata.df.at[dfstart + i, 'global_y'])
        theta_arr.append(math.atan2(y_arr[4] - y_arr[0], x_arr[4] - x_arr[0]))
        v_arr.append(trajdata.df.at[dfstart, 'speed'])
        # hypot(ftr.y_arr[lookahead] - y₀, ftr.x_arr[lookahead] - x₀)/ν.Δt
        if v_arr[0] < 1.0:  # small speed
            # estimate with greater lookahead
            theta_arr[0] = math.atan2(y_arr[-1] - y_arr[0], x_arr[-1] - x_arr[0])
        self.carid = carid
        self.x_arr = x_arr
        self.y_arr = y_arr
        self.theta_arr = theta_arr
        self.v_arr = v_arr 
Example 7
Project: inyourface   Author: yacomink   File: Crying.py    MIT License 6 votes vote down vote up
def cry_frame(self, frame_image, faces, index):
        # Instantiates a client
        tear = Image.open(self.__class__.get_os_path('overlays/tear.png'))

        lowest = 0

        for face in faces:

            for side in ('left', 'right'):

                ((lcx, lcy), (ex, ey), (rcx, rcy)) = face.get_eye_coords(side)

                ew = int(1.25 * math.hypot(rcx - lcx, rcy - lcy))

                pasted = tear.resize((ew, ew), Image.BICUBIC).rotate(face.angles.tilt, Image.BICUBIC)
                left_y = int(lcy + (index * ew * 1.5) + (ew * .5))
                right_y = int(rcy + (index * ew * 1.5) + (ew * .75) )
                frame_image.paste(pasted, (int(lcx - ew/2), left_y), pasted)
                frame_image.paste(pasted, (int(rcx - ew/2), right_y), pasted)
                lowest = max(left_y, right_y)

        return lowest 
Example 8
Project: inyourface   Author: yacomink   File: Cryingblood.py    MIT License 6 votes vote down vote up
def cry_frame(self, frame_image, faces, index):
        # Instantiates a client
        tear = Image.open(self.__class__.get_os_path('overlays/tearblood.png'))

        lowest = 0

        for face in faces:

            for side in ('left', 'right'):

                ((lcx, lcy), (ex, ey), (rcx, rcy)) = face.get_eye_coords(side)

                ew = int(1.25 * math.hypot(rcx - lcx, rcy - lcy))

                pasted = tear.resize((ew, ew), Image.BICUBIC)
                left_y = int(lcy + (index * ew * 1.5) + (ew * .75))
                right_y = int(rcy + (index * ew * 1.5) + (ew * .5) )
                frame_image.paste(pasted, (int(lcx - ew/2), left_y), pasted)
                frame_image.paste(pasted, (int(rcx - ew/2), right_y), pasted)
                lowest = max(left_y, right_y)

        return lowest 
Example 9
Project: inyourface   Author: yacomink   File: Googly.py    MIT License 6 votes vote down vote up
def manipulate_frame(self, frame_image, faces, index):
        # Instantiates a client
        googly_eye = Image.open(self.__class__.get_os_path('overlays/eye.png'))

        for face in faces:

            for side in ('left', 'right'):

                ((lcx, lcy), (ex, ey), (rcx, rcy)) = face.get_eye_coords(side)

                ew = int(1.5 * math.hypot(rcx - lcx, rcy - lcy))

                pasted = googly_eye.rotate(random.randint(0, 360), Image.BICUBIC).resize((ew, ew), Image.BICUBIC)
                frame_image.paste(pasted, (int(ex - ew/2), int(ey - ew/2)), pasted)

        return frame_image 
Example 10
Project: 3DCT   Author: coraxx   File: QtCustom.py    GNU General Public License v3.0 6 votes vote down vote up
def addArrow(self,start,end,arrowangle=45,color=QtCore.Qt.red):
		dx, dy = map(lambda a,b: a - b, end, start)
		length = math.hypot(dx,dy)
		angle = -(math.asin(dy / length))
		if dx < 0:
			angle = math.radians(180) - angle
		if debug is True: print clrmsg.DEBUG + 'Radians:', angle, 'Degree', math.degrees(angle)
		path = QtGui.QPainterPath()
		path.moveTo(*start)
		path.lineTo(*end)
		path.arcMoveTo(
			end[0] - 0.25 * length, end[1] - 0.25 * length,
			0.5 * length, 0.5 * length,
			180 - arrowangle + math.degrees(angle))
		path.lineTo(*end)
		path.arcMoveTo(
			end[0] - 0.25 * length, end[1] - 0.25 * length,
			0.5 * length, 0.5 * length,
			180 + arrowangle + math.degrees(angle))
		path.lineTo(*end)
		self.addPath(path,QtGui.QPen(color)) 
Example 11
Project: dockerizeme   Author: dockerizeme   File: snippet.py    Apache License 2.0 6 votes vote down vote up
def update(self, bots):
        px, py = self.position
        tx, ty = self.target
        angle = atan2(ty - py, tx - px)
        dx = cos(angle)
        dy = sin(angle)
        for bot in bots:
            if bot == self:
                continue
            x, y = bot.position
            d = hypot(px - x, py - y) ** 2
            p = bot.padding ** 2
            angle = atan2(py - y, px - x)
            dx += cos(angle) / d * p
            dy += sin(angle) / d * p
        angle = atan2(dy, dx)
        magnitude = hypot(dx, dy)
        return angle, magnitude 
Example 12
Project: renpy-shader   Author: bitsawer   File: geometry.py    MIT License 6 votes vote down vote up
def simplifyEdgePixels(pixels, minDistance):
    results = []

    i = 0
    while i < len(pixels):
        results.append((float(pixels[i][0]), float(pixels[i][1])))

        distance = 0
        i2 = i + 1
        while i2 < len(pixels):
            previous = (pixels[i2 - 1][0], pixels[i2 - 1][1])
            current = (pixels[i2][0], pixels[i2][1])
            distance += math.hypot(current[0] - previous[0], current[1] - previous[1])
            if distance > minDistance:
                break
            i2 += 1
        i = i2

    return results 
Example 13
Project: rpython-lang-scheme   Author: tomoh1r   File: rcomplex.py    MIT License 6 votes vote down vote up
def c_acos(x, y):
    if not isfinite(x) or not isfinite(y):
        return acos_special_values[special_type(x)][special_type(y)]

    if fabs(x) > CM_LARGE_DOUBLE or fabs(y) > CM_LARGE_DOUBLE:
        # avoid unnecessary overflow for large arguments
        real = math.atan2(fabs(y), x)
        # split into cases to make sure that the branch cut has the
        # correct continuity on systems with unsigned zeros
        if x < 0.:
            imag = -copysign(math.log(math.hypot(x/2., y/2.)) +
                             M_LN2*2., y)
        else:
            imag = copysign(math.log(math.hypot(x/2., y/2.)) +
                            M_LN2*2., -y)
    else:
        s1x, s1y = c_sqrt(1.-x, -y)
        s2x, s2y = c_sqrt(1.+x, y)
        real = 2.*math.atan2(s1x, s2x)
        imag = asinh(s2x*s1y - s2y*s1x)
    return (real, imag) 
Example 14
Project: rpython-lang-scheme   Author: tomoh1r   File: rcomplex.py    MIT License 6 votes vote down vote up
def c_acosh(x, y):
    # XXX the following two lines seem unnecessary at least on Linux;
    # the tests pass fine without them
    if not isfinite(x) or not isfinite(y):
        return acosh_special_values[special_type(x)][special_type(y)]

    if fabs(x) > CM_LARGE_DOUBLE or fabs(y) > CM_LARGE_DOUBLE:
        # avoid unnecessary overflow for large arguments
        real = math.log(math.hypot(x/2., y/2.)) + M_LN2*2.
        imag = math.atan2(y, x)
    else:
        s1x, s1y = c_sqrt(x - 1., y)
        s2x, s2y = c_sqrt(x + 1., y)
        real = asinh(s1x*s2x + s1y*s2y)
        imag = 2.*math.atan2(s1y, s2x)
    return (real, imag) 
Example 15
Project: rpython-lang-scheme   Author: tomoh1r   File: rcomplex.py    MIT License 6 votes vote down vote up
def c_asinh(x, y):
    if not isfinite(x) or not isfinite(y):
        return asinh_special_values[special_type(x)][special_type(y)]

    if fabs(x) > CM_LARGE_DOUBLE or fabs(y) > CM_LARGE_DOUBLE:
        if y >= 0.:
            real = copysign(math.log(math.hypot(x/2., y/2.)) +
                            M_LN2*2., x)
        else:
            real = -copysign(math.log(math.hypot(x/2., y/2.)) +
                             M_LN2*2., -x)
        imag = math.atan2(y, fabs(x))
    else:
        s1x, s1y = c_sqrt(1.+y, -x)
        s2x, s2y = c_sqrt(1.-y, x)
        real = asinh(s1x*s2y - s2x*s1y)
        imag = math.atan2(y, s1x*s2x - s1y*s2y)
    return (real, imag) 
Example 16
Project: rpython-lang-scheme   Author: tomoh1r   File: rcomplex.py    MIT License 6 votes vote down vote up
def c_abs(r, i):
    if not isfinite(r) or not isfinite(i):
        # C99 rules: if either the real or the imaginary part is an
        # infinity, return infinity, even if the other part is a NaN.
        if isinf(r):
            return INF
        if isinf(i):
            return INF

        # either the real or imaginary part is a NaN,
        # and neither is infinite. Result should be NaN.
        return NAN

    result = math.hypot(r, i)
    if not isfinite(result):
        raise OverflowError("math range error")
    return result 
Example 17
Project: OctoPrint-ExcludeRegionPlugin   Author: bradcfisher   File: CircularRegion.py    GNU Affero General Public License v3.0 6 votes vote down vote up
def containsRegion(self, otherRegion):
        """
        Check if another region is fully contained in this region.

        Returns
        -------
        True if the other region is fully contained inside this region, and False otherwise.
        """
        from octoprint_excluderegion.RectangularRegion import RectangularRegion

        if (isinstance(otherRegion, RectangularRegion)):
            return (
                self.containsPoint(otherRegion.x1, otherRegion.y1) and
                self.containsPoint(otherRegion.x2, otherRegion.y1) and
                self.containsPoint(otherRegion.x2, otherRegion.y2) and
                self.containsPoint(otherRegion.x1, otherRegion.y2)
            )
        elif (isinstance(otherRegion, CircularRegion)):
            dist = math.hypot(self.cx - otherRegion.cx, self.cy - otherRegion.cy) + otherRegion.r
            return (dist <= self.r)
        else:
            raise ValueError("unexpected type: {otherRegion}".format(otherRegion=otherRegion)) 
Example 18
Project: OCRDataGenerator   Author: DongfeiJi   File: background_generator.py    MIT License 6 votes vote down vote up
def quasicrystal(height, width):
    """
        Create a background with quasicrystal (https://en.wikipedia.org/wiki/Quasicrystal)
    """

    image = Image.new("L", (width, height))
    pixels = image.load()

    frequency = random.random() * 30 + 20 # frequency
    phase = random.random() * 2 * math.pi # phase
    rotation_count = random.randint(10, 20) # of rotations

    for kw in range(width):
        y = float(kw) / (width - 1) * 4 * math.pi - 2 * math.pi
        for kh in range(height):
            x = float(kh) / (height - 1) * 4 * math.pi - 2 * math.pi
            z = 0.0
            for i in range(rotation_count):
                r = math.hypot(x, y)
                a = math.atan2(y, x) + i * math.pi * 2.0 / rotation_count
                z += math.cos(r * math.sin(a) * frequency + phase)
            c = int(255 - round(255 * z / rotation_count))
            pixels[kw, kh] = c # grayscale
    return image.convert('RGBA') 
Example 19
Project: smoke-detection   Author: annaformaniuk   File: detection.py    MIT License 6 votes vote down vote up
def get_direction(first_pos, second_pos, shape):
    directions = []
    distances = []
    print(shape[0])
    i = 0
    for p in first_pos:
        direction = d_l(p, second_pos[i], shape[0], shape[1])

        directions.append(direction)

        # distance
        dist = math.hypot(
            second_pos[i][0] - p[0], second_pos[i][1] - p[1])
        distances.append(round(dist))

        i += 1

    all_travelled = check_travelled(distances, directions)

    return directions, distances, all_travelled 
Example 20
Project: respeaker_python_library   Author: respeaker   File: fft.py    Apache License 2.0 6 votes vote down vote up
def dft(self, data, typecode='h'):
        if type(data) is str:
            a = array.array(typecode, data)
            for index, value in enumerate(a):
                self.real_input[index] = float(value)
        elif type(data) is array.array:
            for index, value in enumerate(data):
                self.real_input[index] = float(value)

        self.fftwf_execute(self.fftwf_plan)

        for i in range(len(self.amplitude)):
            self.amplitude[i] = math.hypot(self.complex_output[i * 2], self.complex_output[i * 2 + 1])
            # self.phase[i] = math.atan2(self.complex_output[i * 2 + 1], self.complex_output[i * 2])

        return self.amplitude  # , self.phase 
Example 21
Project: codecad   Author: bluecube   File: ray_caster.py    GNU General Public License v3.0 6 votes vote down vote up
def get_camera_params(box, size, view_angle):
    box_size = box.size()

    size_diagonal = math.hypot(*size)

    if view_angle is None:
        focal_length = size_diagonal  # Normal lens by default
    else:
        focal_length = size_diagonal / (2 * math.tan(math.radians(view_angle) / 2))

    distance = focal_length * max(
        _zero_if_inf(box_size.x) / size[0], _zero_if_inf(box_size.z) / size[1]
    )

    if distance == 0:
        distance = 1

    distance *= 1.2  # 20% margin around the object

    origin = box.midpoint() - util.Vector(0, distance + _zero_if_inf(box_size.y) / 2, 0)
    direction = util.Vector(0, 1, 0)
    up = util.Vector(0, 0, 1)

    return (origin, direction, up, focal_length) 
Example 22
Project: codecad   Author: bluecube   File: ray_caster.py    GNU General Public License v3.0 6 votes vote down vote up
def get_camera_params(box, size, view_angle):
    box_size = box.size()

    size_diagonal = math.hypot(*size)

    if view_angle is None:
        focal_length = size_diagonal  # Normal lens by default
    else:
        focal_length = size_diagonal / (2 * math.tan(math.radians(view_angle) / 2))

    distance = focal_length * max(
        _zero_if_inf(box_size.x) / size[0], _zero_if_inf(box_size.z) / size[1]
    )

    if distance == 0:
        distance = 1

    distance *= 1.2  # 20% margin around the object

    origin = box.midpoint() - util.Vector(0, distance + _zero_if_inf(box_size.y) / 2, 0)
    direction = util.Vector(0, 1, 0)
    up = util.Vector(0, 0, 1)

    return (origin, direction, up, focal_length) 
Example 23
Project: pyblish-win   Author: pyblish   File: test_math.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def testHypot(self):
        self.assertRaises(TypeError, math.hypot)
        self.ftest('hypot(0,0)', math.hypot(0,0), 0)
        self.ftest('hypot(3,4)', math.hypot(3,4), 5)
        self.assertEqual(math.hypot(NAN, INF), INF)
        self.assertEqual(math.hypot(INF, NAN), INF)
        self.assertEqual(math.hypot(NAN, NINF), INF)
        self.assertEqual(math.hypot(NINF, NAN), INF)
        self.assertTrue(math.isnan(math.hypot(1.0, NAN)))
        self.assertTrue(math.isnan(math.hypot(NAN, -2.0))) 
Example 24
Project: building-boundary   Author: Geodan   File: alpha_shape.py    MIT License 5 votes vote down vote up
def triangle_geometry(triangle):
    """
    Compute the area and circumradius of a triangle.

    Parameters
    ----------
    triangle : (3x3) array-like
        The coordinates of the points which form the triangle.

    Returns
    -------
    area : float
        The area of the triangle
    circum_r : float
        The circumradius of the triangle
    """
    pa, pb, pc = triangle
    # Lengths of sides of triangle
    a = math.hypot((pa[0] - pb[0]), (pa[1] - pb[1]))
    b = math.hypot((pb[0] - pc[0]), (pb[1] - pc[1]))
    c = math.hypot((pc[0] - pa[0]), (pc[1] - pa[1]))
    # Semiperimeter of triangle
    s = (a + b + c) / 2.0
    # Area of triangle by Heron's formula
    area = math.sqrt(s * (s - a) * (s - b) * (s - c))
    if area != 0:
        circum_r = (a * b * c) / (4.0 * area)
    else:
        circum_r = 0
    return area, circum_r 
Example 25
Project: Old-school-processing   Author: cianfrocco-lab   File: TargetPanel.py    MIT License 5 votes vote down vote up
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

	#-------------------- 
Example 26
Project: Old-school-processing   Author: cianfrocco-lab   File: ImagePanelTools.py    MIT License 5 votes vote down vote up
def distance(self, p1, p2):
		return math.hypot(p2[0]-p1[0], p2[1]-p1[1]) 
Example 27
Project: Old-school-processing   Author: cianfrocco-lab   File: ImagePanelTools.py    MIT License 5 votes vote down vote up
def OnMotion(self, evt, dc):
		if self.button.GetToggle():
			if self.left_or_right == 'left':
				x,y = self.imagepanel.view2image((evt.m_x, evt.m_y))
				self.xypath.append((x,y))
				return True
			elif self.left_or_right == 'right':
				if not self.ellipse_params:
					return False
				# calculate distance dragged
				x,y = self.imagepanel.view2image((evt.m_x, evt.m_y))
				dx = x - self.start[0]
				dy = y - self.start[1]
				print ' XY', dx,dy
				# calculate new key point
				newellipseparams = dict(self.start_ellipse_params)
				print 'AXIS', self.ellipsepointaxis
				newx = self.ellipsepoint[0]+dx
				newy = self.ellipsepoint[1]+dy
				if self.ellipsepointaxis == 'center':
					newellipseparams['center'] = newx,newy
				else:
					newvect = newx-newellipseparams['center'][0], newy-newellipseparams['center'][1]
					newdist = math.hypot(*newvect)
					newellipseparams[self.ellipsepointaxis] = newdist
					newangle = math.atan2(*newvect)
					while newangle < 0:
						newangle += 2*math.pi
					print 'pointangle', self.ellipsepointangle
					print 'newangle', newangle
					dangle = newangle - self.ellipsepointangle
					print 'dangle', dangle
					#newellipseparams['alpha'] += dangle
				self.ellipse_params = newellipseparams
				self.ellipse = self.drawEllipse()
				self.imagepanel.UpdateDrawing()
		return False

	#-------------------- 
Example 28
Project: Old-school-processing   Author: cianfrocco-lab   File: ImagePanelTools.py    MIT License 5 votes vote down vote up
def getToolTipStrings(self, x, y, value):
		if self.button.GetToggle() and self.start is not None:
			x0, y0 = self.start
			dx, dy = x - x0, y - y0
			return ['From (%d, %d) x=%d y=%d d=%.2f a=%.0f' % (x0, y0, dx, dy, math.hypot(dx, dy),math.degrees(math.atan2(dy, dx)))]
		else:
			return []

##################################
##
################################## 
Example 29
Project: clacker   Author: wez   File: tri.py    GNU General Public License v2.0 5 votes vote down vote up
def distance(self, other):
        """Cartesian distance to other point """
        # only used in triangle.__str__
        return hypot(self.x - other.x, self.y - other.y) 
Example 30
Project: VRPTW-ga   Author: shayan-ys   File: nodes.py    MIT License 5 votes vote down vote up
def get_distance_customers_pair(c1: Customer, c2: Customer) -> float:
    return math.hypot(c2.x - c1.x, c2.y - c1.y) 
Example 31
Project: AxiSurface   Author: patriciogonzalezvivo   File: Path.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def length(self):
        if self._length is None:
            length = self.down_length
            for p0, p1 in zip(self.path, self.path[1:]):
                x0, y0 = p0[-1]
                x1, y1 = p1[0]
                length += math.hypot(x1 - x0, y1 - y0)
            self._length = length
        return self._length 
Example 32
Project: AxiSurface   Author: patriciogonzalezvivo   File: Path.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def getJoined(self, tolerance = None, boundary = None):
        try:
            from shapely import geometry
        except ImportError:
            geometry = None

        if boundary != None and geometry is None:
            print('Path.joined() will not work with boundary bacause needs Shapely')
            boundary = None

        if len(self.path) < 2:
            return self

        if tolerance is None:
            tolerance = self.head_width

        result = [list(self.path[0])]
        for path in self.path[1:]:
            x1, y1 = result[-1][-1]
            x2, y2 = path[0]

            join = False

            if boundary != None:
                walk_path = geometry.LineString( [result[-1][-1], path[0]] )
                walk_cut = walk_path.buffer( self.head_width * 0.5 )
                join = walk_cut.within(boundary) # and walk_path.length < max_walk
            else:
                join = math.hypot(x2 - x1, y2 - y1) <= tolerance

            if join:
                result[-1].extend(path)
            else:
                result.append(list(path))
                
        return Path(result) 
Example 33
Project: AxiSurface   Author: patriciogonzalezvivo   File: tools.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def points_length(points):
    result = 0
    for (x1, y1), (x2, y2) in zip(points, points[1:]):
        result += math.hypot(x2 - x1, y2 - y1)
    return result 
Example 34
Project: AxiSurface   Author: patriciogonzalezvivo   File: Index.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def nearest(self, point):
        x, y = point[:2]
        i, j = self.normalize(x, y)
        points = []
        r = 0
        while not points:
            points.extend(self.ring(i, j, r))
            r += 1
        points.extend(self.ring(i, j, r))
        return min(points, key=lambda p: (hypot(x - p[0], y - p[1]), p[1], p[0])) 
Example 35
Project: RouteOptimization   Author: andre-le   File: geomath.py    MIT License 5 votes vote down vote up
def norm(x, y):
    """Private: Normalize a two-vector."""
    r = math.hypot(x, y)
    return x/r, y/r 
Example 36
Project: IA   Author: HerouFenix   File: cidades.py    MIT License 5 votes vote down vote up
def heuristic(self, cidade, goal_cidade):
        x1,y1 = self.coordinates[cidade]
        x2,y2 = self.coordinates[goal_cidade]
        return math.hypot(x1-x2, y1-y2) 
Example 37
Project: NiujiaoDebugger   Author: MrSrc   File: test_math.py    GNU General Public License v3.0 5 votes vote down vote up
def testHypot(self):
        self.assertRaises(TypeError, math.hypot)
        self.ftest('hypot(0,0)', math.hypot(0,0), 0)
        self.ftest('hypot(3,4)', math.hypot(3,4), 5)
        self.assertEqual(math.hypot(NAN, INF), INF)
        self.assertEqual(math.hypot(INF, NAN), INF)
        self.assertEqual(math.hypot(NAN, NINF), INF)
        self.assertEqual(math.hypot(NINF, NAN), INF)
        self.assertRaises(OverflowError, math.hypot, FLOAT_MAX, FLOAT_MAX)
        self.assertTrue(math.isnan(math.hypot(1.0, NAN)))
        self.assertTrue(math.isnan(math.hypot(NAN, -2.0))) 
Example 38
Project: Autoenv   Author: intelligent-control-lab   File: CarLidarFeatureExtractor.py    MIT License 5 votes vote down vote up
def observe(lidar: LidarSensor, scene: Frame, roadway: Roadway, vehicle_index: int):
    state_ego = scene[vehicle_index].state
    egoid = scene[vehicle_index].id
    ego_vel = VecE2.polar(state_ego.v, state_ego.posG.theta)

    in_range_ids = set()

    for i in range(scene.n):
        veh = scene[i]
        if veh.id != egoid:
            a = state_ego.posG - veh.state.posG
            distance = VecE2.norm(VecE2.VecE2(a.x, a.y))
            # account for the length and width of the vehicle by considering
            # the worst case where their maximum radius is aligned
            distance = distance - math.hypot(veh.definition.length_ / 2., veh.definition.width_ / 2.)
            if distance < lidar.max_range:
                in_range_ids.add(veh.id)

                # compute range and range_rate for each angle
    for (i, angle) in enumerate(lidar.angles):
        ray_angle = state_ego.posG.theta + angle
        ray_vec = VecE2.polar(1.0, ray_angle)
        ray = VecSE2.VecSE2(state_ego.posG.x, state_ego.posG.y, ray_angle)

        range_ = lidar.max_range
        range_rate = 0.0
        for j in range(scene.n):
            veh = scene[j]
            # only consider the set of potentially in range vehicles
            if veh.id in in_range_ids:
                lidar.poly.set(to_oriented_bounding_box_2(lidar.poly, veh))

                range2 = get_collision_time(ray, lidar.poly, 1.0)  # TODO: continue finish here
                if range2 and range2 < range_:
                    range_ = range2
                    relative_speed = VecE2.polar(veh.state.v, veh.state.posG.theta) - ego_vel
                    range_rate = VecE2.proj_(relative_speed, ray_vec)
        lidar.ranges[i] = range_
        lidar.range_rates[i] = range_rate

    return lidar 
Example 39
Project: Autoenv   Author: intelligent-control-lab   File: VecE2.py    MIT License 5 votes vote down vote up
def hypot(self):
        return math.hypot(self.x, self.y) 
Example 40
Project: Autoenv   Author: intelligent-control-lab   File: VecE2.py    MIT License 5 votes vote down vote up
def dist(a: VecE2, b: VecE2):
    return math.hypot(a.x-b.x, a.y-b.y) 
Example 41
Project: Autoenv   Author: intelligent-control-lab   File: VecE2.py    MIT License 5 votes vote down vote up
def proj(a: VecE2, b: VecE2, t: type):
    if t == int:
        return (a.x*b.x + a.y*b.y) / math.hypot(b.x, b.y)  # dot(a,b)/|b|
    elif t == VecE2:
        # dot(a,b) / dot(b,b) ⋅ b
        s = (a.x*b.x + a.y*b.y) / (b.x*b.x + b.y*b.y)
        return VecE2(s*b.x, s*b.y)
    else:
        raise TypeError("Wrong type!") 
Example 42
Project: Autoenv   Author: intelligent-control-lab   File: VecE2.py    MIT License 5 votes vote down vote up
def proj_(a: VecE2, b: VecE2):
    return (a.x * b.x + a.y * b.y) / math.hypot(b.x, b.y)  # dot(a,b)/|b| 
Example 43
Project: Autoenv   Author: intelligent-control-lab   File: trajdata.py    MIT License 5 votes vote down vote up
def copy(trajdata: ngsim_trajdata.NGSIMTrajdata, ftr: FilterTrajectoryResult):
    dfstart = trajdata.car2start[ftr.carid]
    N = trajdata.df.at[dfstart, 'n_frames_in_dataset']

    # copy results back to trajdata
    # print("start copying: ")
    for i in range(N):
        #print(dfstart, i, N)
        #print('global_x')
        trajdata.df.at[dfstart + i, 'global_x'] = ftr.x_arr[i]
        #print('global_y')
        trajdata.df.at[dfstart + i, 'global_y'] = ftr.y_arr[i]
        trajdata.df.at[dfstart + i, 'speed'] = ftr.v_arr[i]
        #print("speed")
        if i > 0:
            a = ftr.x_arr[i]
            b = ftr.x_arr[i-1]
            c = ftr.y_arr[i]
            d = ftr.y_arr[i-1]
            trajdata.df.at[dfstart + i, 'speed'] = math.hypot(a-b, c-d) / const.NGSIM_TIMESTEP
        else:
            a = ftr.x_arr[i + 1]
            b = ftr.x_arr[i]
            c = ftr.y_arr[i + 1]
            d = ftr.y_arr[i]
            trajdata.df.at[dfstart + i, 'speed'] = math.hypot(a-b, c-d) / const.NGSIM_TIMESTEP
        #print("global_heading")
        trajdata.df.at[dfstart + i, 'global_heading'] = ftr.theta_arr[i]

    return trajdata 
Example 44
Project: IntentionPrediction   Author: djp42   File: data_util.py    MIT License 5 votes vote down vote up
def calcMovesDists(frameDict):
    nextMoves = {} #vid-fid : move at next intersection
    distances = {} #same, except distance to intersection
    vidfidstoupdate = {}
    s = '-' #this is sep
    sortedFrames = sorted(list(frameDict.keys()), reverse=False)
    framesDone = 0
    numFids = len(sortedFrames)
    for fid in sortedFrames:
        if fid % int(numFids/10) == 0:
            print("Done", fid, "/", numFids, "frames...")
        framesDone = framesDone + 1
        frame = frameDict[fid]
        for vid in frame.keys():
            veh = frame[vid]
            if int(veh[c.Section]) > 0:
                posX = float(veh[c.LocalX])
                posY = float(veh[c.LocalY])
                if vid in vidfidstoupdate.keys():
                    vidfidstoupdate[vid][fid]=[posX, posY]
                else:
                    vidfidstoupdate[vid] = {fid:[posX, posY]}
            else:
                move = int(veh[c.Movement])
                posX = float(veh[c.LocalX])
                posY = float(veh[c.LocalY])
                if vid in vidfidstoupdate.keys():
                    for fid2 in vidfidstoupdate[vid].keys():
                        indx = str(vid)+s+str(fid2)
                        nextMoves[indx] = move
                        dx = posX - vidfidstoupdate[vid][fid2][0]
                        dy = posY - vidfidstoupdate[vid][fid2][1]
                        distances[indx] = math.hypot(dx, dy)
                vidfidstoupdate[vid] = {}
                nextMoves[str(vid)+s+str(fid)] = move #dont forget this one...
                distances[str(vid)+s+str(fid)] = 0  # in intersection
    return nextMoves, distances 
Example 45
Project: 2018-1-OSS-E7   Author: 18-1-SKKU-OSS   File: bmath.py    MIT License 5 votes vote down vote up
def polar(x, y, deg=False):
	"""
	Convert from rectangular (x,y) to polar (r,w)
	    r = sqrt(x^2 + y^2)
	    w = arctan(y/x) = [-pi,pi] = [-180,180]
	"""
	if deg:
		return hypot(x, y), degrees(atan2(y, x))
	else:
		return hypot(x, y), atan2(y, x)

#-------------------------------------------------------------------------------
# Quadratic equation: x^2 + ax + b = 0 (or ax^2 + bx + c = 0)
#    Solve quadratic equation with real coefficients
#
# Usage
#    number, number = quadratic(real, real [, real])
#
# Normally, x^2 + ax + b = 0 is assumed with the 2 coefficients # as
# arguments; but, if 3 arguments are present, then ax^2 + bx + c = 0 is assumed.
#-------------------------------------------------------------------------------
#def quadratic(a, b, c=None):
#	"""
#	x^2 + ax + b = 0 (or ax^2 + bx + c = 0)
#	By substituting x = y-t and t = a/2,
#	the equation reduces to y^2 + (b-t^2) = 0
#	which has easy solution
#	y = +/- sqrt(t^2-b)
#	"""
#	if c: # (ax^2 + bx + c = 0)
#		a, b = b / float(a), c / float(a)
#	t = a / 2.0
#	r = t**2 - b
#	if r >= 0: # real roots
#		y1 = sqrt(r)
#	else: # complex roots
#		y1 = cmath.sqrt(r)
#	y2 = -y1
#	return y1 - t, y2 - t 
Example 46
Project: 2018-1-OSS-E7   Author: 18-1-SKKU-OSS   File: imageToGcode.py    MIT License 5 votes vote down vote up
def make_tool_shape(NUMPY,f, wdia, resp, rough_offset=0.0):
	# resp is pixel size
	res = 1. / resp
	wrad = wdia/2.0 + rough_offset
	rad = int(math.ceil((wrad-resp/2.0)*res))
	if rad < 1: rad = 1
	dia = 2*rad+1

	hdia = rad
	l = []
	for x in range(dia):
		for y in range(dia):
			r = math.hypot(x-hdia, y-hdia) * resp
			if r < wrad:
				z = f(r, wrad)
				l.append(z)

	if NUMPY == True:
		Image_Matrix = Image_Matrix_Numpy
	else:
		Image_Matrix = Image_Matrix_List
	TOOL = Image_Matrix(dia,dia)
	l = []
	temp = []
	for x in range(dia):
		temp.append([])
		for y in range(dia):
			r = math.hypot(x-hdia, y-hdia) * resp
			if r < wrad:
				z = f(r, wrad)
				l.append(z)
				temp[x].append(float(z))
			else:
				temp[x].append(1e100000)
	TOOL.From_List(temp)
	TOOL.minus(TOOL.min()+rough_offset)
	return TOOL 
Example 47
Project: 2018-1-OSS-E7   Author: 18-1-SKKU-OSS   File: imageToGcode.py    MIT License 5 votes vote down vote up
def rad1(x1,y1,x2,y2,x3,y3):
    x12 = x1-x2
    y12 = y1-y2
    x23 = x2-x3
    y23 = y2-y3
    x31 = x3-x1
    y31 = y3-y1

    den = abs(x12 * y23 - x23 * y12)
    if abs(den) < 1e-5: return MAXINT
    return math.hypot(float(x12), float(y12)) * math.hypot(float(x23), float(y23)) * math.hypot(float(x31), float(y31)) / 2 / den 
Example 48
Project: 2018-1-OSS-E7   Author: 18-1-SKKU-OSS   File: imageToGcode.py    MIT License 5 votes vote down vote up
def mag(self):
        return math.hypot(self.x, self.y) 
Example 49
Project: inyourface   Author: yacomink   File: Angry.py    MIT License 5 votes vote down vote up
def manipulate_frame(self, frame_image, faces, index):

        draw = ImageDraw.Draw(frame_image)

        for face in faces:

            for side in ('left', 'right'):
                ((lcx, lcy), (rcx, rcy)) = face.get_paired_landmark_coords('%s_of_' + side + '_eyebrow')
                (ex, ey) = face.get_landmark_coords(side + '_eyebrow_upper_midpoint')

                ew = int(1.5 * math.hypot(rcx - lcx, rcy - lcy))
                rot = random.randint(0, 15)

                if (side == 'right'):
                    (x1, y1) = (lcx, lcy)
                    x2 = x1 + (ew * math.cos(math.radians( self.__class__.angle(lcx, lcy, rcx, rcy) - 25 - rot )))
                    y2 = y1 + (ew * math.sin(math.radians( self.__class__.angle(lcx, lcy, rcx, rcy) - 25 - rot )))

                if (side == 'left'):
                    (x1, y1) = (lcx, lcy)
                    x2 = x1 + (ew * math.cos(math.radians( self.__class__.angle(lcx, lcy, rcx, rcy) + 15 + rot )))
                    y2 = y1 + (ew * math.sin(math.radians( self.__class__.angle(lcx, lcy, rcx, rcy) + 15 + rot )))

                    delta = y2 - y1
                    y1 -= delta
                    y2 -= delta


                draw.line( [(x1, y1),(x2, y2)],fill='black', width=int(round(ew * 0.30)) )

        return frame_image 
Example 50
Project: complex_behaviors   Author: cpswarm   File: bag.py    Apache License 2.0 5 votes vote down vote up
def parse(self, ns, res_space, verbose=False):
        '''
        parse the messages of a bag file
        and store the results in class variables
        :param string ns: name space of topics
        :param float res_space: spatial resolution in meter to filter the input data by (minimum distance between two consecutive coordinates)
        :param bool verbose: whether be verbose (default False)
        '''
        # open bag to read messages
        bag = rosbag.Bag(self.folder + '/' + self.file)

        # read goal coordinates
        goal_coords = [msg[1].pose.position for msg in bag.read_messages(ns + 'pos_controller/goal_position/local')]
        self.goal = [[coord.x + self.origin[0] for coord in goal_coords], [coord.y + self.origin[1] for coord in goal_coords]]

        # read actual pose coordinates
        for topic,msg,t in bag.read_messages(ns + 'mavros/local_position/pose'):
            if len(self.pose) == 0:
                self.pose.append((t.secs + t.nsecs / 1000000000.0, msg.pose.position.x + self.origin[0], msg.pose.position.y + self.origin[1], msg.pose.position.z))
            elif math.hypot(msg.pose.position.x + self.origin[0] - self.pose[-1][1], msg.pose.position.y + self.origin[1] - self.pose[-1][2]) > res_space:
                self.pose.append((t.secs + t.nsecs / 1000000000.0, msg.pose.position.x + self.origin[0], msg.pose.position.y + self.origin[1], msg.pose.position.z))

        # validate end time of coverage
        if self.tstop == 0.0 and len(self.pose) > 0:
            self.tstop = self.pose[-1][0]

        # trim poses according to begin and end times
        self.pose = [p for p in self.pose if self.tstart <= p[0] and p[0] <= self.tstop]

        if verbose:
            print("Obtained {0} goal coordinates".format(len(self.goal[0])))
            print("Obtained {0} pose coordinates".format(len(self.pose)))

        # close bag
        bag.close() 
Example 51
Project: IA_TravellingSalesman   Author: brandtkilian   File: PVC-tester.py    MIT License 5 votes vote down vote up
def dist(x1,y1,x2,y2):
    return hypot(x2 -x1,y2-y1) 
Example 52
Project: IA_TravellingSalesman   Author: brandtkilian   File: PVC-tester.py    MIT License 5 votes vote down vote up
def dist(x1,y1,x2,y2):
    return hypot(x2 -x1,y2-y1) 
Example 53
Project: GlyphsScripts   Author: simoncozens   File: Sansomatic.py    MIT License 5 votes vote down vote up
def distance( node1, node2 ):
    return math.hypot( node1.x - node2.x, node1.y - node2.y ) 
Example 54
Project: unreal   Author: darius   File: renderer.py    GNU General Public License v3.0 5 votes vote down vote up
def circle(center, boundary_point):
    cx, cy = center
    bx, by = boundary_point
    radius = math.hypot(xscale * (bx - cx), yscale * (by - cy))
    print ('<circle cx="%s" cy="%s" r="%s" fill="transparent" stroke="black" stroke-width="1"/>'
           % (xstr(cx), ystr(cy), coord_str(radius))) 
Example 55
Project: eYSIP_2015_Marker_based_Robot_Localisation   Author: eyantrainternship   File: Client2.py    Creative Commons Zero v1.0 Universal 5 votes vote down vote up
def get_distance(x1,y1,x2,y2):
    """
    * Function Name:	get_distance
    * Input:		Points
    * Output:		Returns the distnce between two points
    * Logic:		Uses algebra to find the distance
    * Example Call:	get_distance(x, y, x1, y1)
    """
    distance = math.hypot(x2 - x1, y2 - y1)
    return distance

#### To resolve the occurence of points randomly which may tilt image in Perspective ###### 
Example 56
Project: dockerizeme   Author: dockerizeme   File: snippet.py    Apache License 2.0 5 votes vote down vote up
def normalize(pnt):
###Normalize given Point in place and return the length.
	len = hypot(pnt.x, pnt.y)
	pnt.x /= len
	pnt.y /= len
	return len 
Example 57
Project: dockerizeme   Author: dockerizeme   File: snippet.py    Apache License 2.0 5 votes vote down vote up
def anglefromvector(vect):
	#Return Tuple (radian rotation, vect length) represented by given vector.
	len = hypot(vect.x, vect.y) #sqrt(lensq(vect))
	if len > 0: #If not 0 length.
		a = acos(vect.y / len) #Get angle from cos.
		#If x negative then angle is between pi-2pi
		if vect.x < 0: a = pi2 - a
	else: a = 0
	return (a, len) 
Example 58
Project: dockerizeme   Author: dockerizeme   File: snippet.py    Apache License 2.0 5 votes vote down vote up
def set_position(self, position):
        self.position = position
        if not self.history:
            self.history.append(self.position)
            return
        x, y = self.position
        px, py = self.history[-1]
        d = hypot(px - x, py - y)
        if d >= 10:
            self.history.append(self.position) 
Example 59
Project: tmscoring   Author: Dapid   File: tmscore.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def get_default_values(self):
        """
        Make a crude estimation of the alignment using the center of mass
        and general C->N orientation.
        """
        out = dict(dx=0, dy=0, dz=0, theta=0, phi=0, psi=0)
        dx, dy, dz, _ = np.mean(self.coord1 - self.coord2, axis=1)
        out['dx'] = dx
        out['dy'] = dy
        out['dz'] = dz

        # C->N vector
        vec1 = self.coord1[:-1, 1] - self.coord1[:-1, -1]
        vec2 = self.coord2[:-1, 1] - self.coord2[:-1, -1]
        vec1 /= np.linalg.norm(vec1)
        vec2 /= np.linalg.norm(vec2)

        # Find the rotation matrix that converts vec1 to vec2:
        # http://math.stackexchange.com/questions/180418/#476311
        v = np.cross(vec1, vec2)
        s = np.linalg.norm(v) + np.finfo(DTYPE).eps

        c = vec1.dot(vec2)
        vx = np.array([[0, -v[2], v[1]],
                       [v[2], 0, -v[0]],
                       [-v[1], v[0], 0]], dtype=DTYPE)
        rotation_matrix = np.eye(3) + vx + vx.dot(vx) * (1 - c) / (s * s)

        # Recover the angles from the matrix as seen here:
        # http://nghiaho.com/?page_id=846
        out['theta'] = math.atan2(rotation_matrix[2, 1], rotation_matrix[2, 2])
        out['phi'] = math.atan2(-rotation_matrix[2, 0],
                                math.hypot(rotation_matrix[2, 1],
                                           rotation_matrix[2, 2]))
        out['psi'] = math.atan2(rotation_matrix[1, 0], rotation_matrix[0, 0])

        return out 
Example 60
Project: renpy-shader   Author: bitsawer   File: delaunay.py    MIT License 5 votes vote down vote up
def distance(self, other):
        """Cartesian distance to other point """
        # only used in triangle.__str__
        return hypot(self.x -other.x, self.y - other.y) 
Example 61
Project: renpy-shader   Author: bitsawer   File: geometry.py    MIT License 5 votes vote down vote up
def pointDistance(p1, p2):
    return math.hypot(p2[0] - p1[0], p2[1] - p1[1]) 
Example 62
Project: rpython-lang-scheme   Author: tomoh1r   File: rcomplex.py    MIT License 5 votes vote down vote up
def c_pow(x, y):
    (r1, i1), (r2, i2) = x, y
    if i1 == 0 and i2 == 0 and r1 > 0:
        rr = math.pow(r1, r2)
        ir = 0.
    elif r2 == 0.0 and i2 == 0.0:
        rr, ir = 1, 0
    elif r1 == 1.0 and i1 == 0.0:
        rr, ir = (1.0, 0.0)
    elif r1 == 0.0 and i1 == 0.0:
        if i2 != 0.0 or r2 < 0.0:
            raise ZeroDivisionError
        rr, ir = (0.0, 0.0)
    else:
        vabs = math.hypot(r1,i1)
        len = math.pow(vabs,r2)
        at = math.atan2(i1,r1)
        phase = at * r2
        if i2 != 0.0:
            len /= math.exp(at * i2)
            phase += i2 * math.log(vabs)
        try:
            rr = len * math.cos(phase)
            ir = len * math.sin(phase)
        except ValueError:
            rr = NAN
            ir = NAN
    return (rr, ir)

#unary 
Example 63
Project: bastl-laser-tool   Author: mbastl   File: bastl_laser.py    GNU General Public License v3.0 5 votes vote down vote up
def mag(self): return math.hypot(self.x, self.y) 
Example 64
Project: ironpython2   Author: IronLanguages   File: test_math.py    Apache License 2.0 5 votes vote down vote up
def testHypot(self):
        self.assertRaises(TypeError, math.hypot)
        self.ftest('hypot(0,0)', math.hypot(0,0), 0)
        self.ftest('hypot(3,4)', math.hypot(3,4), 5)
        self.assertEqual(math.hypot(NAN, INF), INF)
        self.assertEqual(math.hypot(INF, NAN), INF)
        self.assertEqual(math.hypot(NAN, NINF), INF)
        self.assertEqual(math.hypot(NINF, NAN), INF)
        self.assertTrue(math.isnan(math.hypot(1.0, NAN)))
        self.assertTrue(math.isnan(math.hypot(NAN, -2.0))) 
Example 65
Project: OctoPrint-ExcludeRegionPlugin   Author: bradcfisher   File: CircularRegion.py    GNU Affero General Public License v3.0 5 votes vote down vote up
def containsPoint(self, x, y):
        """
        Check if the specified point is contained in this region.

        Returns
        -------
        True if the point is inside this region, and False otherwise.
        """
        return self.r >= math.hypot(x - self.cx, y - self.cy) 
Example 66
Project: python-in-practice   Author: lovexiaov   File: Board.py    GNU General Public License v3.0 5 votes vote down vote up
def _nearest_to_middle(self, x, y, empty_neighbours):
        color = self.tiles[x][y]
        midX = self.columns // 2
        midY = self.rows // 2
        Δold = math.hypot(midX - x, midY - y)
        heap = []
        for nx, ny in empty_neighbours:
            if self._is_square(nx, ny):
                Δnew = math.hypot(midX - nx, midY - ny)
                if self._is_legal(nx, ny, color):
                    Δnew -= 0.1 # Make same colors slightly attractive
                heapq.heappush(heap, (Δnew, nx, ny))
        Δnew, nx, ny = heap[0]
        return (True, nx, ny) if Δold > Δnew else (False, x, y) 
Example 67
Project: python-in-practice   Author: lovexiaov   File: Board.py    GNU General Public License v3.0 5 votes vote down vote up
def _nearest_to_middle(self, x, y, empty_neighbours):
        color = self.tiles[x][y]
        midX = self.columns // 2
        midY = self.rows // 2
        Δold = math.hypot(midX - x, midY - y)
        heap = []
        for nx, ny in empty_neighbours:
            if self._is_square(nx, ny):
                Δnew = math.hypot(midX - nx, midY - ny)
                if self._is_legal(nx, ny, color):
                    Δnew -= 0.1 # Make same colors slightly attractive
                heapq.heappush(heap, (Δnew, nx, ny))
        Δnew, nx, ny = heap[0]
        return (True, nx, ny) if Δold > Δnew else (False, x, y) 
Example 68
Project: codecad   Author: bluecube   File: __init__.py    GNU General Public License v3.0 5 votes vote down vote up
def capsule(x1, y1, x2, y2, width):
    """ Use zero thickness rectangle trick to model a 2D capsule between two points """
    dx = x2 - x1
    dy = y2 - y1
    length = math.hypot(dx, dy)
    angle = math.atan2(dy, dx)
    return (
        rectangle(length, 0)
        .offset(width / 2)
        .rotated(math.degrees(angle))
        .translated((x1 + x2) / 2, (y1 + y2) / 2)
    ) 
Example 69
Project: codecad   Author: bluecube   File: __init__.py    GNU General Public License v3.0 5 votes vote down vote up
def capsule(x1, y1, x2, y2, width):
    """ Use zero thickness rectangle trick to model a 2D capsule between two points """
    dx = x2 - x1
    dy = y2 - y1
    length = math.hypot(dx, dy)
    angle = math.atan2(dy, dx)
    return (
        rectangle(length, 0)
        .offset(width / 2)
        .rotated(math.degrees(angle))
        .translated((x1 + x2) / 2, (y1 + y2) / 2)
    ) 
Example 70
Project: codecad   Author: bluecube   File: axes.py    GNU General Public License v3.0 5 votes vote down vote up
def line(x0, y0, x1, y1, thickness):
    dx = x1 - x0
    dy = y1 - y0
    midx = (x0 + x1) / 2
    midy = (y0 + y1) / 2
    length = math.hypot(dx, dy)
    angle = math.degrees(math.atan2(dy, dx))
    return (
        codecad.shapes.rectangle(length, thickness)
        .rotated(angle)
        .translated(midx, midy)
    ) 
Example 71
Project: autonomous_systems_architectures   Author: etsardou   File: path_planning.py    MIT License 5 votes vote down vote up
def aStarHeuristic(self, p, q):
        return math.hypot(p[0] - q[0], p[1] - q[1])

    # Reconstruction of path for A* 
Example 72
Project: Eyecandy-py   Author: Alquimista   File: asstags.py    MIT License 5 votes vote down vote up
def distance(x1, y1, x2=None, y2=None):
    if not x2 and not y2:
        dx, dy = x1, y1
    else:
        dx, dy = x2 - x1, y2 - y1
    return math.hypot(dx, dy) 
Example 73
Project: Old-school-processing   Author: cianfrocco-lab   File: ApTiltPicker_import.py    MIT License 4 votes vote down vote up
def onHelicalInsert(self, evt):
		"""
		connect the last two targets by filling inbetween
		copied from EMAN1 boxer
		"""
		### get last two targets
		targets = self.panel1.getTargets('Picked')
		if len(targets) < 2:
			apDisplay.printWarning("not enough targets")
			return
		array = self.targetsToArray(targets)
		### get pixelsize
		apix = self.appionloop.params['apix']
		if not apix or apix == 0.0:
			apDisplay.printWarning("unknown pixel size")
			return
		### get helicalstep
		if self.helicalstep is None:
			helicaldialog = HelicalStepDialog(self)
			helicaldialog.ShowModal()
			helicaldialog.Destroy()

		helicalstep  = self.helicalstep
		first = array[-2]
		last = array[-1]
		pixeldistance = math.hypot(first[0] - last[0], first[1] - last[1])
		if pixeldistance == 0:
			### this will probably never happen since mouse does not let you click same point twice
			apDisplay.printWarning("points have zero distance")
			return
		stepsize = helicalstep/pixeldistance*apix
		### parameterization of a line btw points (x1,y1) and (x2,y2):
		# x = (1 - t)*x1 + t*x2,
		# y = (1 - t)*y1 + t*y2,
		# t { [0,1] ; t is a real number btw 0 and 1
		points = list(array)
		t = 0.0
		while t < 1.0:
			x = int(round( (1.0 - t)*first[0] + t*last[0], 0))
			y = int(round( (1.0 - t)*first[1] + t*last[1], 0))
			points.append((x,y))
			t += stepsize

		self.panel1.setTargets('Picked', points)

		### transfer points to second panel
		a2 = self.getArray2()
		a1b = self.getAlignedArray1()
		lastpick = a1b[len(a2):]
		a2list = self.panel2.getTargets('Picked')
		a2list.extend(lastpick)
		self.panel2.setTargets('Picked', a2list )

		self.onUpdate(evt)

	#--------------------------------------- 
Example 74
Project: Old-school-processing   Author: cianfrocco-lab   File: ApTiltPicker.py    MIT License 4 votes vote down vote up
def onHelicalInsert(self, evt):
		"""
		connect the last two targets by filling inbetween
		copied from EMAN1 boxer
		"""
		### get last two targets
		targets = self.panel1.getTargets('Picked')
		if len(targets) < 2:
			apDisplay.printWarning("not enough targets")
			return
		array = self.targetsToArray(targets)
		### get pixelsize
		apix = self.appionloop.params['apix']
		if not apix or apix == 0.0:
			apDisplay.printWarning("unknown pixel size")
			return
		### get helicalstep
		if self.helicalstep is None:
			helicaldialog = HelicalStepDialog(self)
			helicaldialog.ShowModal()
			helicaldialog.Destroy()

		helicalstep  = self.helicalstep
		first = array[-2]
		last = array[-1]
		pixeldistance = math.hypot(first[0] - last[0], first[1] - last[1])
		if pixeldistance == 0:
			### this will probably never happen since mouse does not let you click same point twice
			apDisplay.printWarning("points have zero distance")
			return
		stepsize = helicalstep/pixeldistance*apix
		### parameterization of a line btw points (x1,y1) and (x2,y2):
		# x = (1 - t)*x1 + t*x2,
		# y = (1 - t)*y1 + t*y2,
		# t { [0,1] ; t is a real number btw 0 and 1
		points = list(array)
		t = 0.0
		while t < 1.0:
			x = int(round( (1.0 - t)*first[0] + t*last[0], 0))
			y = int(round( (1.0 - t)*first[1] + t*last[1], 0))
			points.append((x,y))
			t += stepsize

		self.panel1.setTargets('Picked', points)

		### transfer points to second panel
		a2 = self.getArray2()
		a1b = self.getAlignedArray1()
		lastpick = a1b[len(a2):]
		a2list = self.panel2.getTargets('Picked')
		a2list.extend(lastpick)
		self.panel2.setTargets('Picked', a2list )

		self.onUpdate(evt)

	#--------------------------------------- 
Example 75
Project: inyourface   Author: yacomink   File: Lasers.py    MIT License 4 votes vote down vote up
def manipulate_frame(self, frame_image, faces, index):

        draw = ImageDraw.Draw(frame_image)
        # font = ImageFont.truetype("Gotham.ttf", 10)

        progress = 0.9 + (float(index) / float(self.total_frames) * 0.2)

        for face in faces:

            for side in ('left', 'right'):
                ((lcx, lcy), (ex, ey), (rcx, rcy)) = face.get_eye_coords(side)
                ew = int(0.25 * math.hypot(rcx - lcx, rcy - lcy))

                (x1, y1) = face.get_landmark_coords(side + '_eye')
                pan_angle = face.angles.pan + 180
                tilt_angle = face.angles.tilt + 180
                if (abs(face.angles.pan) < 10):
                    pan_angle = 180
                    if (face.angles.pan > -1):
                        tilt_angle = 270
                    else:
                        tilt_angle = 90

                tilt_angle = tilt_angle * progress
                pan_angle = pan_angle * progress

                laser_length = Point(0,0).distance(Point(frame_image.width, frame_image.height))
                if (face.angles.pan < 0):
                    x2 = x1 + (laser_length * math.cos(math.radians( pan_angle )))
                else:
                    x2 = x1 - (laser_length * math.cos(math.radians( pan_angle )))

                if (tilt_angle > 180 or abs(face.angles.pan) < 10):
                    y2 = y1 + (laser_length * math.sin(math.radians( tilt_angle )))
                else:
                    y2 = y1 - (laser_length * math.sin(math.radians( tilt_angle )))

                shadow_width = ew/2
                draw.line( [(x1, y1),(x2-ew, y2-ew)],fill='darkred', width=ew )
                draw.line( [(x1, y1),(x2+ew, y2+ew)],fill='orangered', width=ew )
                draw.line( [(x1, y1),(x2, y2)],fill='red', width=ew )

                # (ex, ey) = face.get_landmark_coords('nose_tip')
                # draw.text((ex, ey),"{}, {}, {}".format(face.angles.pan, face.angles.tilt, face.angles.roll),(255,255,255),font=font)


        return frame_image 
Example 76
Project: usv_sim_lsa   Author: disaster-robotics-proalertas   File: rudder_control_heading_old.py    Apache License 2.0 4 votes vote down vote up
def rudder_ctrl():
    # erro = sp - atual
    # ver qual gira no horario ou anti-horario
    # aciona o motor (por enquanto valor fixo)
    global initial_pose
    global target_pose
    global target_distance
    global actuator_vel
    global Ianterior
    global rate_value

    x1 = initial_pose.pose.pose.position.x
    y1 = initial_pose.pose.pose.position.y
    x2 = target_pose.pose.pose.position.x
    y2 = target_pose.pose.pose.position.y

    # encontra angulo ate o ponto de destino (sp)
    myradians = math.atan2(y2-y1,x2-x1)
    sp_angle = math.degrees(myradians)

    target_distance = math.hypot(x2-x1, y2-y1) 


    # encontra angulo atual
    # initial_pose.pose.pose.orientation = nav_msgs.msg.Quaternion(*tf_conversions.transformations.quaternion_from_euler(roll, pitch, yaw))
    
    quaternion = (initial_pose.pose.pose.orientation.x, initial_pose.pose.pose.orientation.y, initial_pose.pose.pose.orientation.z,initial_pose.pose.pose.orientation.w) 
    
    euler = tf.transformations.euler_from_quaternion(quaternion) 

    # target_angle = initial_pose.pose.pose.orientation.yaw
    target_angle = math.degrees(euler[2])

    sp_angle = angle_saturation(sp_angle)
    target_angle = angle_saturation(target_angle)
    
    err = sp_angle - target_angle
    err = P(err) + I(err)

    teste = 5
    if target_distance < 5 and x2 != 0 and y2 != 0:
        actuator_vel = 0
    else:
        actuator_vel = 15

    log_msg = "sp: {0}; erro: {1}; x_atual: {2}; y_atual: {3}; x_destino: {4}; y_destino: {5}; distancia_destino: {6}" .format(sp_angle, err, initial_pose.pose.pose.position.x, initial_pose.pose.pose.position.y, target_pose.pose.pose.position.x, target_pose.pose.pose.position.y, target_distance)

    rospy.loginfo(log_msg)

    rudder_angle = 90 * (-err/180)

    return rudder_angle 
Example 77
Project: usv_sim_lsa   Author: disaster-robotics-proalertas   File: simple_control_1.py    Apache License 2.0 4 votes vote down vote up
def rudder_ctrl():
    # erro = sp - atual
    # ver qual gira no horario ou anti-horario
    # aciona o motor (por enquanto valor fixo)
    global initial_pose
    global target_pose
    global target_distance

    x1 = initial_pose.pose.pose.position.x
    y1 = initial_pose.pose.pose.position.y
    x2 = target_pose.pose.pose.position.x
    y2 = target_pose.pose.pose.position.y

    # encontra angulo ate o ponto de destino (sp)
    myradians = math.atan2(y2-y1,x2-x1)
    sp_angle = math.degrees(myradians)

    target_distance = math.hypot(x2-x1, y2-y1) 

    # encontra angulo atual
    # initial_pose.pose.pose.orientation = nav_msgs.msg.Quaternion(*tf_conversions.transformations.quaternion_from_euler(roll, pitch, yaw))
    
    quaternion = (initial_pose.pose.pose.orientation.x, initial_pose.pose.pose.orientation.y, initial_pose.pose.pose.orientation.z,initial_pose.pose.pose.orientation.w) 
    
    euler = tf.transformations.euler_from_quaternion(quaternion) 

    # target_angle = initial_pose.pose.pose.orientation.yaw
    target_angle = math.degrees(euler[2])

    sp_angle = angle_saturation(sp_angle)
    target_angle = angle_saturation(target_angle)
    
    err = sp_angle - target_angle
    teste = 5

    log_msg = "sp: {0}; erro: {1}; x_atual: {2}; y_atual: {3}; x_destino: {4}; y_destino: {5}; teste: {6}" .format(sp_angle, err, initial_pose.pose.pose.position.x, initial_pose.pose.pose.position.y, target_pose.pose.pose.position.x, target_pose.pose.pose.position.y, teste)

    rospy.loginfo(log_msg)

    rudder_angle = 90 * (-err/180)

    return rudder_angle 
Example 78
Project: dockerizeme   Author: dockerizeme   File: snippet.py    Apache License 2.0 4 votes vote down vote up
def setup(self):
		global screenrad
		# This will be called before the first frame is drawn.
		pos = self.bounds.center()
		cp = Point(*pos)
		pos.x = 0
		w = self.size.w
		h = self.size.h
		w3 = w / 5 #1/5th Screen width.
		w6 = w3 / 2 #1/10th Screen width.
		screenrad = hypot(w, h) * .5 #Set screen radius.
		self.pl = []
		plr = player(pos, self, 1.0) #Create player 1.
		self.pl.append(plr)
		plr.color = Color(1.00, 0.50, 0.00)
		plr.moverect = Rect(w - w3, 0, w3, w3) #Set movement button rectangle.
		plr.movepos = plr.moverect.center()
		plr.shootrect = Rect(w - w6, w3 * 2.25, w6, w3) #Set fire button rectangle.
		pos.x = w
		plr = player(pos, self, -1.0) #Create player 2.
		self.pl.append(plr)
		plr.color = Color(0.40, 1.00, 0.40)
		plr.shoot = sounds[1] #Change fire sound for player 2.
		plr.shootv = 0.3 #Set lower volume.
		plr.moverect = Rect(0, h - w3, w3, w3) #Set movement button rectangle.
		plr.movepos = plr.moverect.center()
		plr.shootrect = Rect(0, h - w3 * 2.25 - w3, w6, w3) #Set fire button rectangle.
		self.activebullets = [] #Array of active bullets.
		self.explosions = [] #Array of active explosions.
		self.controlalpha = 0.45 #Control rectangle alpha.
		self.wave = 0 #Wave counter.
		self.wpskipchance = wpskipchance
		self.killerinterval = killerinterval
		self.state = self.run
		self.gameovertxt = render_text('You\'ve been Ripped Off!', 'Copperplate', 32)
		self.pausetxt = render_text('Pause', 'Copperplate', 28)
		c = self.bounds.center()
		hh = self.pausetxt[1].w / 2
		self.pauserect = Rect(c.x - hh, 0, hh * 2, self.pausetxt[1].h)
		if mt:
			self.udstart = Event()
			self.uddone = Event()
			self.udthread = Thread(target=self.udthread)
			self.udthread.start()

		for s in sounds: load_effect(s) #pre-load sound effects.

		def makecrate(i):
		###Local function to create a crate mob.
			x = (int(i / 3) - 1) * cratespacing
			y = ((i % 3) - 1) * cratespacing
			cr = crate(Point(cp.x + x, cp.y + y), self)
			return cr

		self.crates = [makecrate(i) for i in xrange(numcrates)]
		self.robbers = [robber(self) for i in xrange(robbercount)]
		self.killers = [] #Start with 0 killers.
		self.numrobbers = 0

	###Remove crate from the crates array. 
Example 79
Project: rpython-lang-scheme   Author: tomoh1r   File: rcomplex.py    MIT License 4 votes vote down vote up
def c_sqrt(x, y):
    '''
    Method: use symmetries to reduce to the case when x = z.real and y
    = z.imag are nonnegative.  Then the real part of the result is
    given by
    
      s = sqrt((x + hypot(x, y))/2)
    
    and the imaginary part is
    
      d = (y/2)/s
    
    If either x or y is very large then there's a risk of overflow in
    computation of the expression x + hypot(x, y).  We can avoid this
    by rewriting the formula for s as:
    
      s = 2*sqrt(x/8 + hypot(x/8, y/8))
    
    This costs us two extra multiplications/divisions, but avoids the
    overhead of checking for x and y large.
    
    If both x and y are subnormal then hypot(x, y) may also be
    subnormal, so will lack full precision.  We solve this by rescaling
    x and y by a sufficiently large power of 2 to ensure that x and y
    are normal.
    '''
    if not isfinite(x) or not isfinite(y):
        return sqrt_special_values[special_type(x)][special_type(y)]

    if x == 0. and y == 0.:
        return (0., y)

    ax = fabs(x)
    ay = fabs(y)

    if ax < DBL_MIN and ay < DBL_MIN and (ax > 0. or ay > 0.):
        # here we catch cases where hypot(ax, ay) is subnormal
        ax = math.ldexp(ax, CM_SCALE_UP)
        ay1= math.ldexp(ay, CM_SCALE_UP)
        s = math.ldexp(math.sqrt(ax + math.hypot(ax, ay1)),
                       CM_SCALE_DOWN)
    else:
        ax /= 8.
        s = 2.*math.sqrt(ax + math.hypot(ax, ay/8.))

    d = ay/(2.*s)

    if x >= 0.:
        return (s, copysign(d, y))
    else:
        return (d, copysign(s, y)) 
Example 80
Project: rpython-lang-scheme   Author: tomoh1r   File: rcomplex.py    MIT License 4 votes vote down vote up
def c_log(x, y):
    # The usual formula for the real part is log(hypot(z.real, z.imag)).
    # There are four situations where this formula is potentially
    # problematic:
    #
    # (1) the absolute value of z is subnormal.  Then hypot is subnormal,
    # so has fewer than the usual number of bits of accuracy, hence may
    # have large relative error.  This then gives a large absolute error
    # in the log.  This can be solved by rescaling z by a suitable power
    # of 2.
    #
    # (2) the absolute value of z is greater than DBL_MAX (e.g. when both
    # z.real and z.imag are within a factor of 1/sqrt(2) of DBL_MAX)
    # Again, rescaling solves this.
    #
    # (3) the absolute value of z is close to 1.  In this case it's
    # difficult to achieve good accuracy, at least in part because a
    # change of 1ulp in the real or imaginary part of z can result in a
    # change of billions of ulps in the correctly rounded answer.
    #
    # (4) z = 0.  The simplest thing to do here is to call the
    # floating-point log with an argument of 0, and let its behaviour
    # (returning -infinity, signaling a floating-point exception, setting
    # errno, or whatever) determine that of c_log.  So the usual formula
    # is fine here.

    # XXX the following two lines seem unnecessary at least on Linux;
    # the tests pass fine without them
    if not isfinite(x) or not isfinite(y):
        return log_special_values[special_type(x)][special_type(y)]

    ax = fabs(x)
    ay = fabs(y)

    if ax > CM_LARGE_DOUBLE or ay > CM_LARGE_DOUBLE:
        real = math.log(math.hypot(ax/2., ay/2.)) + M_LN2
    elif ax < DBL_MIN and ay < DBL_MIN:
        if ax > 0. or ay > 0.:
            # catch cases where hypot(ax, ay) is subnormal
            real = math.log(math.hypot(math.ldexp(ax, DBL_MANT_DIG),
                                       math.ldexp(ay, DBL_MANT_DIG)))
            real -= DBL_MANT_DIG*M_LN2
        else:
            # log(+/-0. +/- 0i)
            raise ValueError("math domain error")
            #real = -INF
            #imag = atan2(y, x)
    else:
        h = math.hypot(ax, ay)
        if 0.71 <= h and h <= 1.73:
            am = max(ax, ay)
            an = min(ax, ay)
            real = log1p((am-1)*(am+1) + an*an) / 2.
        else:
            real = math.log(h)
    imag = math.atan2(y, x)
    return (real, imag)