Python math.hypot() Examples

The following are code examples for showing how to use math.hypot(). They are extracted from open source Python projects. You can vote up the examples you like or vote down the exmaples you don't like. You can also save this page to your account.

Example 1
Project: convolutional-pose-machines-tensorflow   Author: timctho   File: cpm_utils.py    (Apache License 2.0) View Source Project 7 votes vote down vote up
def warpImage(src, theta, phi, gamma, scale, fovy):
    halfFovy = fovy * 0.5
    d = math.hypot(src.shape[1], src.shape[0])
    sideLength = scale * d / math.cos(deg2Rad(halfFovy))
    sideLength = np.int32(sideLength)

    M = warpMatrix(src.shape[1], src.shape[0], theta, phi, gamma, scale, fovy)
    dst = cv2.warpPerspective(src, M, (sideLength, sideLength))
    mid_x = mid_y = dst.shape[0] // 2
    target_x = target_y = src.shape[0] // 2
    offset = (target_x % 2)

    if len(dst.shape) == 3:
        dst = dst[mid_y - target_y:mid_y + target_y + offset,
              mid_x - target_x:mid_x + target_x + offset,
              :]
    else:
        dst = dst[mid_y - target_y:mid_y + target_y + offset,
              mid_x - target_x:mid_x + target_x + offset]

    return dst 
Example 2
Project: cpsc415   Author: WheezePuppet   File: atlas.py    (license) View Source Project 6 votes vote down vote up
def gen_adj_mat(longs, lats, prob_edge=.2,
                        additional_length=lambda: np.random.exponential(20,1)):
    '''Get an adjacency matrix for the cities whose longitudes and latitudes
    are passed. Each entry will either be a number somewhat greater than the
    crow-flies distance between the two cities (with probability prob_edge),
    or math.inf. The matrix will consist of floats, and be symmetric. The
    diagonal will be all zeroes. The "somewhat greater" is controlled by the
    additional_length parameter, a function returning a random amount.'''

    # Generate full nxn Bernoulli's, even though we'll only use the upper
    # triangle.
    edges = np.random.binomial(1, prob_edge, size=(len(longs),len(longs)))
    am = np.zeros((len(longs),len(longs)))
    for i in range(len(longs)):
        for j in range(len(longs)):
            if i==j:
                am[i,i] = 0
            elif i < j:
                if edges[i,j] == 1:
                    am[i,j] = (math.hypot(longs[i]-longs[j],lats[i]-lats[j])
                        + additional_length())
                    am[j,i] = am[i,j]
                else:
                    am[i,j] = am[j,i] = math.inf
    return np.around(am,1) 
Example 3
Project: codecad   Author: bluecube   File: ray_caster.py    (license) View Source Project 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 4
Project: codecad   Author: bluecube   File: ray_caster.py    (license) View Source Project 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 5
Project: CON-SAI   Author: SSL-Roots   File: paint_widget.py    (license) View Source Project 6 votes vote down vote up
def drawBallVelocity(self, painter):
        ballPos = self.ballOdom.pose.pose.position
        ballVel = self.ballOdom.twist.twist.linear

        if math.hypot(ballVel.x, ballVel.y) < 1.0:
            return 

        angleOfSpeed = math.atan2(ballVel.y, ballVel.x)

        paintDist = 10.0

        velPosX = paintDist * math.cos(angleOfSpeed) + ballPos.x
        velPosY = paintDist * math.sin(angleOfSpeed) + ballPos.y

        ballPosPoint = self.convertToDrawWorld(ballPos.x, ballPos.y)
        velPosPoint = self.convertToDrawWorld(velPosX, velPosY)

        painter.setPen(QPen(QColor(102,0,255),2))
        painter.drawLine(ballPosPoint, velPosPoint) 
Example 6
Project: QEsg   Author: jorgealmerio   File: ucs.py    (license) View Source Project 6 votes vote down vote up
def setup_xy(self, p1_world, p2_world, p1_ucs, p2_ucs):
        """ setup an UCS given by the points p1 and p2
        only xy-plane,  z' = z
        """
        ucs_angle_to_x_axis = get_angle(p1_ucs, p2_ucs)
        world_angle_to_x_axis = get_angle(p1_world, p2_world)
        rotation = normalize_angle(world_angle_to_x_axis - ucs_angle_to_x_axis)
        self._xaxis = (math.cos(rotation), math.sin(rotation), 0.)
        self._yaxis = (math.cos(rotation+HALF_PI), math.sin(rotation+HALF_PI), 0.)
        self._zaxis = (0., 0., 1.)

        ucs_angle_to_x_axis = get_angle((0., 0.), p1_ucs)
        world_angle_to_x_axis = rotation + ucs_angle_to_x_axis
        distance_from_ucs_origin = math.hypot(p1_ucs[0], p1_ucs[1])
        delta_x = distance_from_ucs_origin * math.cos(world_angle_to_x_axis)
        delta_y = distance_from_ucs_origin * math.sin(world_angle_to_x_axis)
        self._origin = (p1_world[0] - delta_x, p1_world[1] - delta_y, 0.) 
Example 7
Project: inyourface   Author: yacomink   File: Googly.py    (license) View Source Project 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 8
Project: inyourface   Author: yacomink   File: Cryingblood.py    (license) View Source Project 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: Crying.py    (license) View Source Project 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 10
Project: autoinjection   Author: ChengWiLL   File: xdot.py    (license) View Source Project 6 votes vote down vote up
def __init__(self, dot_widget, target_x, target_y):
        MoveToAnimation.__init__(self, dot_widget, target_x, target_y)
        self.source_zoom = dot_widget.zoom_ratio
        self.target_zoom = self.source_zoom
        self.extra_zoom = 0

        middle_zoom = 0.5 * (self.source_zoom + self.target_zoom)

        distance = math.hypot(self.source_x - self.target_x,
                              self.source_y - self.target_y)
        rect = self.dot_widget.get_allocation()
        visible = min(rect.width, rect.height) / self.dot_widget.zoom_ratio
        visible *= 0.9
        if distance > 0:
            desired_middle_zoom = visible / distance
            self.extra_zoom = min(0, 4 * (desired_middle_zoom - middle_zoom)) 
Example 11
Project: FreeCAD-PCB   Author: marmni   File: PCBobjects.py    (license) View Source Project 6 votes vote down vote up
def arcMidPoint(self, prev_vertex, vertex, angle):
        if len(prev_vertex) == 3:
            [x1, y1, z1] = prev_vertex
        else:
            [x1, y1] = prev_vertex
            
        if len(vertex) == 3:
            [x2, y2, z2] = vertex
        else:
            [x2, y2] = vertex
        
        angle = radians(angle / 2)
        basic_angle = atan2(y2 - y1, x2 - x1) - pi / 2
        shift = (1 - cos(angle)) * hypot(y2 - y1, x2 - x1) / 2 / sin(angle)
        midpoint = [(x2 + x1) / 2 + shift * cos(basic_angle), (y2 + y1) / 2 + shift * sin(basic_angle)]
        
        return midpoint 
Example 12
Project: bokken   Author: thestr4ng3r   File: xdot.py    (license) View Source Project 6 votes vote down vote up
def __init__(self, dot_widget, target_x, target_y):
        MoveToAnimation.__init__(self, dot_widget, target_x, target_y)
        self.source_zoom = dot_widget.zoom_ratio
        self.target_zoom = self.source_zoom
        self.extra_zoom = 0

        middle_zoom = 0.5 * (self.source_zoom + self.target_zoom)

        distance = math.hypot(self.source_x - self.target_x,
                              self.source_y - self.target_y)
        rect = self.dot_widget.get_allocation()
        visible = min(rect.width, rect.height) / self.dot_widget.zoom_ratio
        visible *= 0.9
        if distance > 0:
            desired_middle_zoom = visible / distance
            self.extra_zoom = min(0, 4 * (desired_middle_zoom - middle_zoom)) 
Example 13
Project: respeaker_python_library   Author: respeaker   File: fft.py    (license) View Source Project 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 14
Project: inf295   Author: Mondego   File: datamodel.py    (license) View Source Project 6 votes vote down vote up
def start(self, route=[], v=10):
        r = route

        self.TopSpeed = v
        self.Route = r

        # Calculating position and velocity vector according to route points
        if len(route) > 1:
            self.CurrentRoute += 1
            self.Position = Vector3(r[0]['X'], r[0]['Y'], self.Position.Z)

            ddash = math.hypot(self.Position.X-r[1]['X'], self.Position.Y-r[1]['Y'])
            self.Velocity = Vector3((v/ddash) * (r[1]['X']-self.Position.X), (v/ddash) * (r[1]['Y']-self.Position.Y), 0)
        else:
            self.Position = Vector3(0, 0, self.Position.Z)
            self.Velocity = Vector3(0, 0, 0) 
Example 15
Project: Mac-Python-3.X   Author: L1nwatch   File: lighting.py    (license) View Source Project 6 votes vote down vote up
def animate(self):
        self.angle += (math.pi / 30)
        xs = 200 * math.sin(self.angle) - 40 + 25
        ys = 200 * math.cos(self.angle) - 40 + 25
        self.m_lightSource.setPos(xs, ys)

        for item in self.m_items:
            effect = item.graphicsEffect()

            delta = QPointF(item.x() - xs, item.y() - ys)
            effect.setOffset(QPointF(delta.toPoint() / 30))

            dd = math.hypot(delta.x(), delta.y())
            color = effect.color()
            color.setAlphaF(max(0.4, min(1 - dd / 200.0, 0.7)))
            effect.setColor(color)

        self.m_scene.update() 
Example 16
Project: Mac-Python-3.X   Author: L1nwatch   File: stickman.py    (license) View Source Project 6 votes vote down vote up
def __init__(self):
        super(StickMan, self).__init__()

        self.m_sticks = True
        self.m_isDead = False
        self.m_pixmap = QPixmap('images/head.png')
        self.m_penColor = QColor(Qt.white)
        self.m_fillColor = QColor(Qt.black)

        # Set up start position of limbs.
        self.m_nodes = []
        for x, y in Coords:
            node = Node(QPointF(x, y), self)
            node.positionChanged.connect(self.childPositionChanged)
            self.m_nodes.append(node)

        self.m_perfectBoneLengths = []
        for n1, n2 in Bones:
            node1 = self.m_nodes[n1]
            node2 = self.m_nodes[n2]

            dist = node1.pos() - node2.pos()
            self.m_perfectBoneLengths.append(math.hypot(dist.x(), dist.y()))

        self.startTimer(10) 
Example 17
Project: Mac-Python-3.X   Author: L1nwatch   File: stickman.py    (license) View Source Project 6 votes vote down vote up
def stabilize(self):
        threshold = 0.001

        for i, (n1, n2) in enumerate(Bones):
            node1 = self.m_nodes[n1]
            node2 = self.m_nodes[n2]

            pos1 = node1.pos()
            pos2 = node2.pos()

            dist = pos1 - pos2
            length = math.hypot(dist.x(), dist.y())
            diff = (length - self.m_perfectBoneLengths[i]) / length

            p = dist * (0.5 * diff)
            if p.x() > threshold and p.y() > threshold:
                pos1 -= p
                pos2 += p

                node1.setPos(pos1)
                node2.setPos(pos2) 
Example 18
Project: computational_physics_N2014301020117   Author: yukangnineteen   File: 6 code.py    (license) View Source Project 6 votes vote down vote up
def __init__(self, initial_velocity, firing_angle, time_step, velocity_of_wind, angle_of_wind):
        self.x = [0]
        self.y = [0]
        self.theta = firing_angle
        self.alpha = angle_of_wind
        self.v_x = [initial_velocity * math.cos(self.theta / 180 * math.pi)]
        self.v_y = [initial_velocity * math.sin(self.theta / 180 * math.pi)]
        self.v0 = initial_velocity
        self.v = initial_velocity
        self.v_w = velocity_of_wind
        self.v_w_x = self.v_w * math.cos(self.alpha / 180 * math.pi)
        self.v_w_y = self.v_w * math.sin(self.alpha / 180 * math.pi)
        self.v_rel_x = self.v_x[0] - self.v_w_x
        self.v_rel_y = self.v_y[0] - self.v_w_y
        self.v_rel_module = math.hypot(self.v_rel_x, self.v_rel_y)
        self.C = 0
        self.B_2 = 0
        self.g = 9.8
        self.dt = time_step 
Example 19
Project: computational_physics_N2014301020117   Author: yukangnineteen   File: 6 code.py    (license) View Source Project 6 votes vote down vote up
def calculate(self):
        i = 0
        while(True):
            self.B_2 = 0.0039 + 0.0058 / (1 + math.exp((self.v - 35) / 5))
            self.C = math.pow(1 - 0.0065 * self.y[i] / 273, 2.5)
            self.x.append(self.x[i] + self.v_x[i] * self.dt)
            self.y.append(self.y[i] + self.v_y[i] * self.dt)
            self.v_x.append(self.v_x[i] - self.C * self.B_2 * self.v_rel_module * self.v_rel_x * self.dt)
            self.v_y.append(self.v_y[i] - self.g * self.dt - self.C * self.B_2 * self.v_rel_module * self.v_rel_y * self.dt)
            self.v = math.hypot(self.v_x[i + 1], self.v_y[i + 1])
            self.v_rel_x = self.v_x[i + 1] - self.v_w_x
            self.v_rel_y = self.v_y[i + 1] - self.v_w_y
            self.v_rel_module = math.hypot(self.v_rel_x, self.v_rel_y)
            i += 1
            if self.y[i] <= -100:
                break
        self.x[-1]=((-100 - self.y[-1])*(self.x[-1] - self.x[-2]) / (self.y[-1] - self.y[-2])) + self.x[-1]
        self.y[i] = -100
        global a
        a = self.x[-1] 
Example 20
Project: computational_physics_N2014301020117   Author: yukangnineteen   File: 5(improved) code.py    (license) View Source Project 6 votes vote down vote up
def calculate(self):
        i = 0
        while(True):
            self.C = 4E-2 * math.pow(1 - 6.5 * self.y[i] / 300, 2.5)
            self.g.append(self.G * self.M_E / (self.R_E + self.y[i]) ** 2)
            self.x.append(self.x[i] + self.v_x[i] * self.dt)
            self.y.append(self.y[i] + self.v_y[i] * self.dt)
            self.v_x.append(self.v_x[i] - self.C * math.hypot(self.v_x[i], self.v_y[i]) * self.v_x[i] * self.dt)
            self.v_y.append(self.v_y[i] - self.g[i-1] * self.dt - self.C * math.hypot(self.v_x[i], self.v_y[i]) * self.v_y[i] * self.dt)
            i += 1
            if self.y[i] < 0:
                break
#For the falling point
        self.x[i] = - self.y[i-1] * (self.x[i] - self.x[i-1]) / (self.y[i] - self.y[i-1]) + self.x[i-1]
        self.y[i] = 0

#Maxmize the range and find the corresponding firing angle 
Example 21
Project: Eagle   Author: magerx   File: xdot.py    (license) View Source Project 6 votes vote down vote up
def __init__(self, dot_widget, target_x, target_y):
        MoveToAnimation.__init__(self, dot_widget, target_x, target_y)
        self.source_zoom = dot_widget.zoom_ratio
        self.target_zoom = self.source_zoom
        self.extra_zoom = 0

        middle_zoom = 0.5 * (self.source_zoom + self.target_zoom)

        distance = math.hypot(self.source_x - self.target_x,
                              self.source_y - self.target_y)
        rect = self.dot_widget.get_allocation()
        visible = min(rect.width, rect.height) / self.dot_widget.zoom_ratio
        visible *= 0.9
        if distance > 0:
            desired_middle_zoom = visible / distance
            self.extra_zoom = min(0, 4 * (desired_middle_zoom - middle_zoom)) 
Example 22
Project: landport   Author: land-pack   File: xdot.py    (license) View Source Project 6 votes vote down vote up
def __init__(self, dot_widget, target_x, target_y):
        MoveToAnimation.__init__(self, dot_widget, target_x, target_y)
        self.source_zoom = dot_widget.zoom_ratio
        self.target_zoom = self.source_zoom
        self.extra_zoom = 0

        middle_zoom = 0.5 * (self.source_zoom + self.target_zoom)

        distance = math.hypot(self.source_x - self.target_x,
                              self.source_y - self.target_y)
        rect = self.dot_widget.get_allocation()
        visible = min(rect.width, rect.height) / self.dot_widget.zoom_ratio
        visible *= 0.9
        if distance > 0:
            desired_middle_zoom = visible / distance
            self.extra_zoom = min(0, 4 * (desired_middle_zoom - middle_zoom)) 
Example 23
Project: examples   Author: pyqt   File: lighting.py    (license) View Source Project 6 votes vote down vote up
def animate(self):
        self.angle += (math.pi / 30)
        xs = 200 * math.sin(self.angle) - 40 + 25
        ys = 200 * math.cos(self.angle) - 40 + 25
        self.m_lightSource.setPos(xs, ys)

        for item in self.m_items:
            effect = item.graphicsEffect()

            delta = QPointF(item.x() - xs, item.y() - ys)
            effect.setOffset(QPointF(delta.toPoint() / 30))

            dd = math.hypot(delta.x(), delta.y())
            color = effect.color()
            color.setAlphaF(max(0.4, min(1 - dd / 200.0, 0.7)))
            effect.setColor(color)

        self.m_scene.update() 
Example 24
Project: examples   Author: pyqt   File: stickman.py    (license) View Source Project 6 votes vote down vote up
def __init__(self):
        super(StickMan, self).__init__()

        self.m_sticks = True
        self.m_isDead = False
        self.m_pixmap = QPixmap('images/head.png')
        self.m_penColor = QColor(Qt.white)
        self.m_fillColor = QColor(Qt.black)

        # Set up start position of limbs.
        self.m_nodes = []
        for x, y in Coords:
            node = Node(QPointF(x, y), self)
            node.positionChanged.connect(self.childPositionChanged)
            self.m_nodes.append(node)

        self.m_perfectBoneLengths = []
        for n1, n2 in Bones:
            node1 = self.m_nodes[n1]
            node2 = self.m_nodes[n2]

            dist = node1.pos() - node2.pos()
            self.m_perfectBoneLengths.append(math.hypot(dist.x(), dist.y()))

        self.startTimer(10) 
Example 25
Project: examples   Author: pyqt   File: stickman.py    (license) View Source Project 6 votes vote down vote up
def stabilize(self):
        threshold = 0.001

        for i, (n1, n2) in enumerate(Bones):
            node1 = self.m_nodes[n1]
            node2 = self.m_nodes[n2]

            pos1 = node1.pos()
            pos2 = node2.pos()

            dist = pos1 - pos2
            length = math.hypot(dist.x(), dist.y())
            diff = (length - self.m_perfectBoneLengths[i]) / length

            p = dist * (0.5 * diff)
            if p.x() > threshold and p.y() > threshold:
                pos1 -= p
                pos2 += p

                node1.setPos(pos1)
                node2.setPos(pos2) 
Example 26
Project: ouroboros   Author: pybee   File: cmath.py    (license) View Source Project 6 votes vote down vote up
def _log(z):
    abs_x = abs(z.real)
    abs_y = abs(z.imag)

    if abs_x > _LARGE_INT or abs_y > _LARGE_INT:
        return complex(math.log(math.hypot(abs_x/2, abs_y/2)) + _LOG_2,
                       math.atan2(z.imag, z.real))
    if abs_x < _DBL_MIN and abs_y < _DBL_MIN:
        if abs_x > 0 or abs_y > 0:
            return complex(math.log(math.hypot(math.ldexp(abs_x, _DBL_MANT_DIG),
                                    math.ldexp(abs_y, _DBL_MANT_DIG)))
                           - _DBL_MANT_DIG * _LOG_2,
                           math.atan2(z.imag, z.real))
        raise ValueError

    rad, phi = polar(z)
    return complex(math.log(rad), phi) 
Example 27
Project: RoseLap   Author: RoseGPE   File: track_segmentation.py    (license) View Source Project 6 votes vote down vote up
def __init__(self,x1,y1,x2,y2,x3,y3,sector,endpoint):
    self.x_m=x1; self.x=x2; self.x_p=x3; self.y_m=y1; self.y=y2; self.y_p=y3;
    self.length_m = math.hypot(self.x_m-self.x, self.y_m-self.y)
    self.length_p = math.hypot(self.x_p-self.x, self.y_p-self.y)
    self.length_secant = math.hypot(self.x_p-self.x_m, self.y_p-self.y_m)
    self.length = (self.length_m+self.length_p)/2
    self.sector = sector;

    if endpoint:
      self.curvature = 0
    else:
      p = (self.length_m+self.length_p+self.length_secant)/2
      #print(p, self.length_m, self.length_p, self.length_secant)
      try:
        area = math.sqrt(p*(p-self.length_m)*(p-self.length_p)*(p-self.length_secant))
      except ValueError:
        area=0

      self.curvature = 4*area/(self.length_m*self.length_p*self.length_secant) 
Example 28
Project: Helix   Author: 3lackrush   File: xdot.py    (license) View Source Project 6 votes vote down vote up
def __init__(self, dot_widget, target_x, target_y):
        MoveToAnimation.__init__(self, dot_widget, target_x, target_y)
        self.source_zoom = dot_widget.zoom_ratio
        self.target_zoom = self.source_zoom
        self.extra_zoom = 0

        middle_zoom = 0.5 * (self.source_zoom + self.target_zoom)

        distance = math.hypot(self.source_x - self.target_x,
                              self.source_y - self.target_y)
        rect = self.dot_widget.get_allocation()
        visible = min(rect.width, rect.height) / self.dot_widget.zoom_ratio
        visible *= 0.9
        if distance > 0:
            desired_middle_zoom = visible / distance
            self.extra_zoom = min(0, 4 * (desired_middle_zoom - middle_zoom)) 
Example 29
Project: BetterBlender   Author: bobtherobot   File: uv_squares.py    (license) View Source Project 6 votes vote down vote up
def CursorClosestTo(verts, allowedError = 0.025):
    ratioX, ratioY = ImageRatio()
    
    #any length that is certantly not smaller than distance of the closest
    min = 1000
    minV = verts[0]
    for v in verts:
        if v is None: continue
        for area in bpy.context.screen.areas:
            if area.type == 'IMAGE_EDITOR':
                loc = area.spaces[0].cursor_location
                hyp = hypot(loc.x/ratioX -v.uv.x, loc.y/ratioY -v.uv.y)
                if (hyp < min):
                    min = hyp
                    minV = v
    
    if min is not 1000: return minV
    return None 
Example 30
Project: autoscan   Author: b01u   File: xdot.py    (license) View Source Project 6 votes vote down vote up
def __init__(self, dot_widget, target_x, target_y):
        MoveToAnimation.__init__(self, dot_widget, target_x, target_y)
        self.source_zoom = dot_widget.zoom_ratio
        self.target_zoom = self.source_zoom
        self.extra_zoom = 0

        middle_zoom = 0.5 * (self.source_zoom + self.target_zoom)

        distance = math.hypot(self.source_x - self.target_x,
                              self.source_y - self.target_y)
        rect = self.dot_widget.get_allocation()
        visible = min(rect.width, rect.height) / self.dot_widget.zoom_ratio
        visible *= 0.9
        if distance > 0:
            desired_middle_zoom = visible / distance
            self.extra_zoom = min(0, 4 * (desired_middle_zoom - middle_zoom)) 
Example 31
Project: dxfwrite   Author: mozman   File: ucs.py    (license) View Source Project 6 votes vote down vote up
def setup_xy(self, p1_world, p2_world, p1_ucs, p2_ucs):
        """ setup an UCS given by the points p1 and p2
        only xy-plane,  z' = z
        """
        ucs_angle_to_x_axis = get_angle(p1_ucs, p2_ucs)
        world_angle_to_x_axis = get_angle(p1_world, p2_world)
        rotation = normalize_angle(world_angle_to_x_axis - ucs_angle_to_x_axis)
        self._xaxis = (math.cos(rotation), math.sin(rotation), 0.)
        self._yaxis = (math.cos(rotation + HALF_PI), math.sin(rotation + HALF_PI), 0.)
        self._zaxis = (0., 0., 1.)

        ucs_angle_to_x_axis = get_angle((0., 0.), p1_ucs)
        world_angle_to_x_axis = rotation + ucs_angle_to_x_axis
        distance_from_ucs_origin = math.hypot(p1_ucs[0], p1_ucs[1])
        delta_x = distance_from_ucs_origin * math.cos(world_angle_to_x_axis)
        delta_y = distance_from_ucs_origin * math.sin(world_angle_to_x_axis)
        self._origin = (p1_world[0] - delta_x, p1_world[1] - delta_y, 0.) 
Example 32
Project: ToolPlus   Author: mkbreuer   File: uv_squares.py    (license) View Source Project 6 votes vote down vote up
def CursorClosestTo(verts, allowedError = 0.025):
    ratioX, ratioY = ImageRatio()
    
    #any length that is certantly not smaller than distance of the closest
    min = 1000
    minV = verts[0]
    for v in verts:
        if v is None: continue
        for area in bpy.context.screen.areas:
            if area.type == 'IMAGE_EDITOR':
                loc = area.spaces[0].cursor_location
                hyp = hypot(loc.x/ratioX -v.uv.x, loc.y/ratioY -v.uv.y)
                if (hyp < min):
                    min = hyp
                    minV = v
    
    if min is not 1000: return minV
    return None 
Example 33
Project: POTCO-PS   Author: ksmit799   File: RepairPitchingGame.py    (license) View Source Project 6 votes vote down vote up
def placeLeak(self, leak):
        tooClose = True
        attempts = 0
        while tooClose and attempts < self._MAX_TRIES:
            attempts += 1
            locator = self.locators[random.randint(0, len(self.locators) - 1)]
            relative = self.getRelativePoint(self.board, Point3(locator.getX(), 0, locator.getZ()))
            x = relative.getX()
            z = relative.getZ()
            tooClose = False
            for otherLeak in self.activeLeaks:
                dist = math.hypot(otherLeak.getX() - x, otherLeak.getZ() - z)
                if dist < self._MIN_DIST:
                    tooClose = True
                    continue
            
            for otherLeak in self.patchedLeaks:
                dist = math.hypot(otherLeak.getX() - x, otherLeak.getZ() - z)
                if dist < self._MIN_DIST:
                    tooClose = True
                    continue
            
        leak.repositionTo(x, z) 
Example 34
Project: LSTM-GA-StockTrader   Author: MartinLidy   File: tools.py    (license) View Source Project 6 votes vote down vote up
def diversity(first_front, first, last):
    """Given a Pareto front `first_front` and the two extreme points of the 
    optimal Pareto front, this function returns a metric of the diversity 
    of the front as explained in the original NSGA-II article by K. Deb.
    The smaller the value is, the better the front is.
    """
    df = hypot(first_front[0].fitness.values[0] - first[0],
               first_front[0].fitness.values[1] - first[1])
    dl = hypot(first_front[-1].fitness.values[0] - last[0],
               first_front[-1].fitness.values[1] - last[1])
    dt = [hypot(first.fitness.values[0] - second.fitness.values[0],
                first.fitness.values[1] - second.fitness.values[1])
          for first, second in zip(first_front[:-1], first_front[1:])]

    if len(first_front) == 1:
        return df + dl

    dm = sum(dt)/len(dt)
    di = sum(abs(d_i - dm) for d_i in dt)
    delta = (df + dl + di)/(df + dl + len(dt) * dm )
    return delta 
Example 35
Project: Robo-Plot   Author: JackBuck   File: path_following.py    (license) View Source Project 6 votes vote down vote up
def find_retreat_positions(self):

        total_num_position = 1
        retreat_positions = []
        current_segment = -1
        offset_distance = 1

        current_retrace_length = 0

        while offset_distance < total_num_position + 1:
            length = math.hypot(self.computed_path[current_segment][0] - self.computed_path[current_segment - 1][0],
                                self.computed_path[current_segment][1] - self.computed_path[current_segment - 1][1])

            while offset_distance < current_retrace_length + length and offset_distance < total_num_position + 1:
                proportion = (offset_distance - current_retrace_length) / length
                new_position = list(self.computed_path[current_segment]
                                    + (np.array(self.computed_path[current_segment - 1])
                                       - self.computed_path[current_segment]) * proportion)

                retreat_positions.append(new_position)
                offset_distance += 1

            current_retrace_length += length

        return retreat_positions 
Example 36
Project: zellij   Author: nedbat   File: test_defuzz.py    (Apache License 2.0) View Source Project 5 votes vote down vote up
def test_hypo(points):
    dfz = Defuzzer(ndigits=0)
    dfz_points = [dfz.defuzz(pt) for pt in points]

    # The output values should all be in the inputs.
    assert all(pt in points for pt in dfz_points)

    # No two unequal output values should be too close together.
    if len(points) > 1:
        for a, b in all_pairs(dfz_points):
            if a == b:
                continue
            distance = math.hypot(a[0] - b[0], a[1] - b[1])
            assert distance > .5 
Example 37
Project: zellij   Author: nedbat   File: euclid.py    (Apache License 2.0) View Source Project 5 votes vote down vote up
def distance(self, other):
        """Compute the distance from this Point to another Point."""
        assert isinstance(other, Point)
        x1, y1 = self
        x2, y2 = other
        return math.hypot(x2 - x1, y2 - y1) 
Example 38
Project: zellij   Author: nedbat   File: euclid.py    (Apache License 2.0) View Source Project 5 votes vote down vote up
def offset(self, distance):
        """Create another Line `distance` from this one."""
        (x1, y1), (x2, y2) = self
        dx = x2 - x1
        dy = y2 - y1
        hyp = math.hypot(dx, dy)
        offx = dy / hyp * distance
        offy = -dx / hyp * distance
        return Line(Point(x1 + offx, y1 + offy), Point(x2 + offx, y2 + offy)) 
Example 39
Project: Fluent-Python   Author: Ehco1996   File: vector2d_v2.py    (license) View Source Project 5 votes vote down vote up
def __abs__(self):  # ??
        return math.hypot(self.x, self.y) 
Example 40
Project: Fluent-Python   Author: Ehco1996   File: vector2d_v1.py    (license) View Source Project 5 votes vote down vote up
def __abs__(self):  # ??
        return math.hypot(self.x, self.y) 
Example 41
Project: Fluent-Python   Author: Ehco1996   File: vector2d_v3.py    (license) View Source Project 5 votes vote down vote up
def __abs__(self):  # ??
        return math.hypot(self.x, self.y) 
Example 42
Project: otRebuilder   Author: Pal3love   File: perimeterPen.py    (MIT License) View Source Project 5 votes vote down vote up
def _distance(p0, p1):
	return math.hypot(p0[0] - p1[0], p0[1] - p1[1]) 
Example 43
Project: otRebuilder   Author: Pal3love   File: cu2qu_test.py    (MIT License) View Source Project 5 votes vote down vote up
def dist(cls, p1, p2):
        (x1, y1), (x2, y2) = p1, p2
        return math.hypot(x1 - x2, y1 - y2) 
Example 44
Project: sc8pr   Author: dmaccarthy   File: shape.py    (GNU General Public License v3.0) View Source Project 5 votes vote down vote up
def __init__(self, start, point=None, vector=None):
        "Create a line or line segment"
        self.pos = start
        if point:
            ux = point[0] - start[0]
            uy = point[1] - start[1]
        elif type(vector) in (int, float):
            ux = 1
            uy = vector
        else: ux, uy = vector
        self._size = abs(ux), abs(uy)
        u = hypot(ux, uy)
        self.length = u #if point else None
        self.u = ux / u, uy / u 
Example 45
Project: sc8pr   Author: dmaccarthy   File: electric.py    (GNU General Public License v3.0) View Source Project 5 votes vote down vote up
def ondraw(self):

        # Calculate electric force
        sk = self.sketch
        dr = delta(self.pos, sk["blue"].pos)
        r = hypot(*dr) / sk.scale / 100
        F = delta(dr, mag = 8.99e-3 * sk.q1 * sk.q2 / (r * r))

        # Add electric plus gravitational forces 
        F = F[0], F[1] + sk.mass * 9.81e-3

        # Tangential acceleration
        s = sk["string"]
        u = s.u
        t = 1 / sk.frameRate
        F = (F[0] * u[1] - F[1] * u[0]) / (sk.mass / 1000) * (sk.scale / 100) / t ** 2
        ax, ay = F * u[1], -F * u[0]

        # Kinematics
        v1x, v1y = tuple(0.95 * v for v in self.vel)
        v2x = v1x + ax * t
        v2y = v1y + ay * t
        self.vel = v2x, v2y
        x, y = self.pos
        x += (v1x + v2x) * t / 2
        y += (v1y + v2y) * t / 2
        x, y = delta((x,y), s.pos, 20 * sk.scale)
        self.pos = s.pos[0] + x, s.pos[1] + y
        s.__init__(s.pos, self.pos)

        # Protractor
        if s.u[1] > 0:
            a = round(2 * degrees(asin(s.u[0]))) / 2
            a = "Angle = {:.1f}° ".format(abs(a))
        else: a = "Angle = ? "
        sk["angle"].config(data=a) 
Example 46
Project: sc8pr   Author: dmaccarthy   File: robot.py    (GNU General Public License v3.0) View Source Project 5 votes vote down vote up
def checkFront(self):
        "Update the front color sensor"

        # Get sensor position
        pos = delta(self.pos, vec2d(-self.radius, self.angle))

        # Sensor distance to edge of sketch
        sk = self.sketch
        if sk.weight:
            obj = sk
            prox = _distToWall(pos, self.angle, self.sensorWidth, *sk.size)
        else: obj = prox = None

        # Find closest object within sensor width
        u = vec2d(1, self.angle)
        sw = self.sensorWidth * DEG
        for gr in self.sensorObjects(sk):
            if gr is not self and gr.avgColor and hasattr(gr, "rect"):
                dr = delta(gr.rect.center, pos)
                d = hypot(*dr)
                r = gr.radius
                if r >= d:
                    prox = 0
                    obj = gr
                elif prox is None or d - r < prox:
                    minDot = cos(min(sw + asin(r/d), pi / 2))
                    x = (1 - sprod(u, dr) / d) / (1 - minDot)
                    if x < 1:
                        obj = gr
                        prox = (d - r) * (1 - x) + x * sqrt(d*d-r*r)

        # Save data
        self.closestObject = obj
        c = rgba(sk.border if obj is sk
            else obj.avgColor if obj else (0,0,0))
        self.sensorFront = noise(divAlpha(c), self.sensorNoise, 255)
        self.proximity = None if prox is None else round(prox) 
Example 47
Project: sc8pr   Author: dmaccarthy   File: geom.py    (GNU General Public License v3.0) View Source Project 5 votes vote down vote up
def dist(p1, p2):
    "Distance between two points"
    return hypot(p2[0] - p1[0], p2[1] - p1[1]) 
Example 48
Project: sc8pr   Author: dmaccarthy   File: geom.py    (GNU General Public License v3.0) View Source Project 5 votes vote down vote up
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) 
Example 49
Project: sc8pr   Author: dmaccarthy   File: sprite.py    (GNU General Public License v3.0) View Source Project 5 votes vote down vote up
def elasticCircles(mass1, mass2):
    "Set final velocities for an elastic collision between two circles"

    # Calculate the normal vector at contact point
    x1, y1 = mass1.rect.center
    x2, y2 = mass2.rect.center
    nx = x2 - x1
    ny = y2 - y1
    r = hypot(nx, ny)
    if r >= mass1.radius + mass2.radius or r == 0:
        return # No contact!
    nx /= r
    ny /= r

    # Calculate initial momenta
    m1 = mass1.mass
    m2 = mass2.mass
    v1x, v1y = mass1.vel
    v2x, v2y = mass2.vel
    p1x = m1 * v1x
    p1y = m1 * v1y
    p2x = m2 * v2x
    p2y = m2 * v2y

    # Calculate impulse and final velocities
    impulse = 2 * (m2 * (p1x * nx + p1y * ny) - m1 * (p2x * nx + p2y * ny)) / (m1 + m2)
    if impulse > 0:
        mass1.vel = (p1x - impulse * nx) / m1, (p1y - impulse * ny) / m1
        mass2.vel = (p2x + impulse * nx) / m2, (p2y + impulse * ny) / m2
        return True 
Example 50
Project: code   Author: ActiveState   File: recipe-510397.py    (MIT License) View Source Project 5 votes vote down vote up
def __abs__(self):
        'Return the vector\'s magnitude.'
        return _math.hypot(self.x, self.y)