Python numpy.hypot() 使用实例

The following are code examples for showing how to use . 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

def _vlines(lines, ctrs=None, lengths=None, vecs=None, angle_lo=20, angle_hi=160, ransac_options=RANSAC_OPTIONS):
    ctrs = ctrs if ctrs is not None else lines.mean(1)
    vecs = vecs if vecs is not None else lines[:, 1, :] - lines[:, 0, :]
    lengths = lengths if lengths is not None else np.hypot(vecs[:, 0], vecs[:, 1])

    angles = np.degrees(np.arccos(vecs[:, 0] / lengths))
    points = np.column_stack([ctrs[:, 0], angles])
    point_indices, = np.nonzero((angles > angle_lo) & (angles < angle_hi))
    points = points[point_indices]
    if len(points) > 2:
        model_ransac = linear_model.RANSACRegressor(**ransac_options)
        model_ransac.fit(points[:, 0].reshape(-1, 1), points[:, 1].reshape(-1, 1))
        inlier_mask = model_ransac.inlier_mask_
        valid_lines = lines[point_indices[inlier_mask], :, :]
    else:
        valid_lines = []
    return valid_lines 

Example 2

def _hlines(lines, ctrs=None, lengths=None, vecs=None, angle_lo=20, angle_hi=160, ransac_options=RANSAC_OPTIONS):
    ctrs = ctrs if ctrs is not None else lines.mean(1)
    vecs = vecs if vecs is not None else lines[:, 1, :] - lines[:, 0, :]
    lengths = lengths if lengths is not None else np.hypot(vecs[:, 0], vecs[:, 1])

    angles = np.degrees(np.arccos(vecs[:, 1] / lengths))
    points = np.column_stack([ctrs[:, 1], angles])
    point_indices, = np.nonzero((angles > angle_lo) & (angles < angle_hi))
    points = points[point_indices]
    if len(points) > 2:
        model_ransac = linear_model.RANSACRegressor(**ransac_options)
        model_ransac.fit(points[:, 0].reshape(-1, 1), points[:, 1].reshape(-1, 1))
        inlier_mask = model_ransac.inlier_mask_
        valid_lines = lines[point_indices[inlier_mask], :, :]
    else:
        valid_lines = []
    return valid_lines 

Example 3

def get_ind_under_point(self, event):
        """
        get the index of the vertex under point if within epsilon tolerance
        :param event: qt event
        :return: index of selected point
        """

        # display coords
        distances = numpy.hypot(event.xdata - self.curData[:, 0],
                                event.ydata - self.curData[:, 1])
        indmin = distances.argmin()

        if distances[indmin] >= self.epsilon:
            ind = None
        else:
            ind = indmin
        self.lastind = ind
        return ind 

Example 4

def get_ind_under_point(self, event):
        """
        get the index of the vertex under point if within epsilon tolerance
        :param event: qt event
        :return: index of selected point
        """

        # display coords
        distances = numpy.hypot(event.xdata - self.curData[:, 0],
                                event.ydata - self.curData[:, 1])
        indmin = distances.argmin()

        if distances[indmin] >= self.epsilon:
            ind = None
        else:
            ind = indmin
        self.lastind = ind
        return ind 

Example 5

def calcPi(n):
    """ Calculating Pi using Monte Carlo Integration. 
        
        Quickly estimates the first 2 decimals, but it is terribly inefficient for estimating other decimals.

        Source: http://www.stealthcopter.com/blog/2009/09/python-calculating-pi-using-random-numbers/
    """

    inside = 0.0

    for i in range(n):
        x = np.random.random()
        y = np.random.random()

        # Calculate the length of hypotenuse given the sides x and y
        if np.hypot(x, y) <= 1:
            inside += 1

    return 4.0*inside/n

# Run the calcPi function without timing 

Example 6

def _filter(img, method, k):
        if method == 'Edge gradient':
            sy = cv2.Sobel(img, ddepth=cv2.CV_64F, dx=0, dy=1, ksize=k)
            sx = cv2.Sobel(img, ddepth=cv2.CV_64F,dx=1, dy=0, ksize=k)
#             sx = sobel(img, axis=0, mode='constant')
#             sy = sobel(img, axis=1, mode='constant')
            return np.hypot(sx, sy)
        if method == 'Sobel-H':
            return cv2.Sobel(img, ddepth=cv2.CV_64F,dx=0, dy=1, ksize=k)
        #sobel(img, axis=0, mode='constant')
        if method == 'Sobel-V':
            return cv2.Sobel(img, ddepth=cv2.CV_64F,dx=1, dy=0, ksize=k)
        #sobel(img, axis=1, mode='constant')
        if method == 'Laplace':
            return cv2.Laplacian(img, ddepth=cv2.CV_64F,ksize=5)
        #laplace(img) 

Example 7

def _pixel_select(self, event):

        x, y = event.xdata, event.ydata
        # get index by assuming even spacing
        # TODO use kdtree?
        diff = np.hypot((self.x_pos - x), (self.y_pos - y))
        y_ind, x_ind = np.unravel_index(np.argmin(diff), diff.shape)

        # get the spectrum for this point
        new_y_data = self.counts[y_ind, x_ind, :]
        self.mask = np.zeros(self.x_pos.shape, dtype='bool')
        self.mask[y_ind, x_ind] = True
        self.mask_im.set_data(self._overlay_image)
        self._pixel_txt.set_text(
            'pixel: [{:d}, {:d}] ({:.3g}, {:.3g})'.format(
                y_ind, x_ind,
                self.x_pos[y_ind, x_ind],
                self.y_pos[y_ind, x_ind]))

        self.spec.set_ydata(new_y_data)
        self.ax_spec.relim()
        self.ax_spec.autoscale(True, axis='y')
        self.fig.canvas.draw_idle() 

Example 8

def line_ball_collision_check(line, ball):
    # checks if the ball is half the line length from the line middle
    if distance_less_equal(line.middle, ball.pos, line.length / 2 + config.ball_radius):
        # displacement vector from the first point to the ball
        displacement_to_ball = ball.pos - line.line[0]
        # displacement vector from the first point to the second point on the
        # line
        displacement_to_second_point = line.line[1] - line.line[0]
        normalised_point_diff_vector = displacement_to_second_point / \
                                       np.hypot(*(displacement_to_second_point))
        # distance from the first point on the line to the perpendicular
        # projection point from the ball
        projected_distance = np.dot(normalised_point_diff_vector, displacement_to_ball)
        # closest point on the line to the ball
        closest_line_point = projected_distance * normalised_point_diff_vector
        perpendicular_vector = np.array(
            [-normalised_point_diff_vector[1], normalised_point_diff_vector[0]])
        # checking if closest point on the line is actually on the line (which is not always the case when projecting)
        # then checking if the distance from that point to the ball is less than the balls radius and finally
        # checking if the ball is moving towards the line with the dot product
        return -config.ball_radius / 3 <= projected_distance <= \
               np.hypot(*(displacement_to_second_point)) + config.ball_radius / 3 and \
               np.hypot(*(closest_line_point - ball.pos + line.line[0])) <= \
               config.ball_radius and np.dot(
            perpendicular_vector, ball.velocity) <= 0 

Example 9

def test_NotImplemented_not_returned(self):
        # See gh-5964 and gh-2091. Some of these functions are not operator
        # related and were fixed for other reasons in the past.
        binary_funcs = [
            np.power, np.add, np.subtract, np.multiply, np.divide,
            np.true_divide, np.floor_divide, np.bitwise_and, np.bitwise_or,
            np.bitwise_xor, np.left_shift, np.right_shift, np.fmax,
            np.fmin, np.fmod, np.hypot, np.logaddexp, np.logaddexp2,
            np.logical_and, np.logical_or, np.logical_xor, np.maximum,
            np.minimum, np.mod
            ]

        # These functions still return NotImplemented. Will be fixed in
        # future.
        # bad = [np.greater, np.greater_equal, np.less, np.less_equal, np.not_equal]

        a = np.array('1')
        b = 1
        for f in binary_funcs:
            assert_raises(TypeError, f, a, b) 

Example 10

def go_to_with_planner(self, x, y, t):
        start = self.position()[:-1]
        end = np.array([x, y])
        points = self.planner.get_points(start=start, end=end, robot=self)

        def add_t(points, t):
            points = np.array(points)
            lens = np.hypot(points[:, 0], points[:, 1])
            tpm = t / np.add.reduce(lens)
            npoints = np.zeros(shape=(points.shape[0], 3))
            npoints[:, :-1] = points
            npoints[:, -1] = tpm * lens
            return npoints

        npoints = add_t(points, t)

        if not points:
            logging.warning("no available path. start=%r, end=%r", start, end)
        else:
            self.follow(points, t) 

Example 11

def test_NotImplemented_not_returned(self):
        # See gh-5964 and gh-2091. Some of these functions are not operator
        # related and were fixed for other reasons in the past.
        binary_funcs = [
            np.power, np.add, np.subtract, np.multiply, np.divide,
            np.true_divide, np.floor_divide, np.bitwise_and, np.bitwise_or,
            np.bitwise_xor, np.left_shift, np.right_shift, np.fmax,
            np.fmin, np.fmod, np.hypot, np.logaddexp, np.logaddexp2,
            np.logical_and, np.logical_or, np.logical_xor, np.maximum,
            np.minimum, np.mod
            ]

        # These functions still return NotImplemented. Will be fixed in
        # future.
        # bad = [np.greater, np.greater_equal, np.less, np.less_equal, np.not_equal]

        a = np.array('1')
        b = 1
        for f in binary_funcs:
            assert_raises(TypeError, f, a, b) 

Example 12

def dist(apos, bpos):
	"""
	Angular separation between two points on a sphere.
	http://en.wikipedia.org/wiki/Great-circle_distance
	"""
	(a_ra, a_dec), (b_ra, b_dec) = apos, bpos
	lon1 = a_ra / 180 * pi
	lat1 = a_dec / 180 * pi
	lon2 = b_ra / 180 * pi
	lat2 = b_dec / 180 * pi
	sdlon = sin(lon2 - lon1)
	cdlon = cos(lon2 - lon1)
	slat1 = sin(lat1)
	slat2 = sin(lat2)
	clat1 = cos(lat1)
	clat2 = cos(lat2)

	num1 = clat2 * sdlon
	num2 = clat1 * slat2 - slat1 * clat2 * cdlon
	denominator = slat1 * slat2 + clat1 * clat2 * cdlon

	return arctan2(hypot(num1, num2), denominator) * 180 / pi 

Example 13

def test_NotImplemented_not_returned(self):
        # See gh-5964 and gh-2091. Some of these functions are not operator
        # related and were fixed for other reasons in the past.
        binary_funcs = [
            np.power, np.add, np.subtract, np.multiply, np.divide,
            np.true_divide, np.floor_divide, np.bitwise_and, np.bitwise_or,
            np.bitwise_xor, np.left_shift, np.right_shift, np.fmax,
            np.fmin, np.fmod, np.hypot, np.logaddexp, np.logaddexp2,
            np.logical_and, np.logical_or, np.logical_xor, np.maximum,
            np.minimum, np.mod
            ]

        # These functions still return NotImplemented. Will be fixed in
        # future.
        # bad = [np.greater, np.greater_equal, np.less, np.less_equal, np.not_equal]

        a = np.array('1')
        b = 1
        for f in binary_funcs:
            assert_raises(TypeError, f, a, b) 

Example 14

def test_NotImplemented_not_returned(self):
        # See gh-5964 and gh-2091. Some of these functions are not operator
        # related and were fixed for other reasons in the past.
        binary_funcs = [
            np.power, np.add, np.subtract, np.multiply, np.divide,
            np.true_divide, np.floor_divide, np.bitwise_and, np.bitwise_or,
            np.bitwise_xor, np.left_shift, np.right_shift, np.fmax,
            np.fmin, np.fmod, np.hypot, np.logaddexp, np.logaddexp2,
            np.logical_and, np.logical_or, np.logical_xor, np.maximum,
            np.minimum, np.mod
            ]

        # These functions still return NotImplemented. Will be fixed in
        # future.
        # bad = [np.greater, np.greater_equal, np.less, np.less_equal, np.not_equal]

        a = np.array('1')
        b = 1
        for f in binary_funcs:
            assert_raises(TypeError, f, a, b) 

Example 15

def direction_map(dmap: DistanceMap):
    r"""Computes normalized gradient of distance map. Not defined when length of
    the gradient is zero.

    .. math::
       \hat{\mathbf{e}}_{S} = -\frac{\nabla S(\mathbf{x})}{\| \nabla S(\mathbf{x}) \|}

    Args:
        dmap (numpy.ndarray):
            Distance map.

    Returns:
        DirectionMap: Direction map.
    """
    u, v = np.gradient(dmap)
    l = np.hypot(u, v)
    # Avoids zero division
    l[l == 0] = np.nan
    # Flip order from (row, col) to (x, y)
    return v / l, u / l


# Potentials 

Example 16

def collide(self, p1, p2):
        np = self.np
        dx = p1.x - p2.x
        dy = p1.y - p2.y
        elasticity = 1
        dist = np.hypot(dx, dy)
        if dist < p1.size + p2.size:
            tangent = np.arctan2(dy, dx)
            angle = 0.5 * np.pi + tangent

            angle1 = 2*tangent - p1.angle
            angle2 = 2*tangent - p2.angle
            speed1 = p2.speed*elasticity
            speed2 = p1.speed*elasticity

            (p1.angle, p1.speed) = (angle1, speed1)
            (p2.angle, p2.speed) = (angle2, speed2)

            p1.x += np.sin(angle)
            p1.y -= np.cos(angle)
            p2.x -= np.sin(angle)
            p2.y += np.cos(angle) 

Example 17

def angles_from_sphere(pts):
    """equirectangular projection, ie. map from sphere in R^3 to (0, 2*pi) x (-pi/2, pi/2)
    Parameters
    ----------
    pts : array_like (3,...)
        pts[0,...], pts[1,...], and pts[2,...] are x,y, and z coordinates
    Returns
    -------
    out : ndarray (2,...)
        pts transformed from x,y,z to longitude,latitude
    """
    pts = np.asarray(pts) #turn into an ndarray if necessary
    x,y,z = pts[0], pts[1], pts[2]
    out = np.empty((2,) + pts.shape[1:])
    #longitude:
    out[0] = np.arctan2(y,x)
    out[0] %= 2*pi #wrap negative values around the circle to positive
    #latitude:
    r = np.hypot(x,y)
    out[1] = np.arctan2(z,r)
    return out 

Example 18

def test_NotImplemented_not_returned(self):
        # See gh-5964 and gh-2091. Some of these functions are not operator
        # related and were fixed for other reasons in the past.
        binary_funcs = [
            np.power, np.add, np.subtract, np.multiply, np.divide,
            np.true_divide, np.floor_divide, np.bitwise_and, np.bitwise_or,
            np.bitwise_xor, np.left_shift, np.right_shift, np.fmax,
            np.fmin, np.fmod, np.hypot, np.logaddexp, np.logaddexp2,
            np.logical_and, np.logical_or, np.logical_xor, np.maximum,
            np.minimum, np.mod
            ]

        # These functions still return NotImplemented. Will be fixed in
        # future.
        # bad = [np.greater, np.greater_equal, np.less, np.less_equal, np.not_equal]

        a = np.array('1')
        b = 1
        for f in binary_funcs:
            assert_raises(TypeError, f, a, b) 

Example 19

def get_dH2(lab1, lab2):
    """squared hue difference term occurring in deltaE_cmc and deltaE_ciede94

    Despite its name, "dH" is not a simple difference of hue values.  We avoid
    working directly with the hue value, since differencing angles is
    troublesome.  The hue term is usually written as:
        c1 = sqrt(a1**2 + b1**2)
        c2 = sqrt(a2**2 + b2**2)
        term = (a1-a2)**2 + (b1-b2)**2 - (c1-c2)**2
        dH = sqrt(term)

    However, this has poor roundoff properties when a or b is dominant.
    Instead, ab is a vector with elements a and b.  The same dH term can be
    re-written as:
        |ab1-ab2|**2 - (|ab1| - |ab2|)**2
    and then simplified to:
        2*|ab1|*|ab2| - 2*dot(ab1, ab2)
    """
    lab1 = np.asarray(lab1)
    lab2 = np.asarray(lab2)
    a1, b1 = np.rollaxis(lab1, -1)[1:3]
    a2, b2 = np.rollaxis(lab2, -1)[1:3]

    # magnitude of (a, b) is the chroma
    C1 = np.hypot(a1, b1)
    C2 = np.hypot(a2, b2)

    term = (C1 * C2) - (a1 * a2 + b1 * b2)
    return 2 * term 

Example 20

def _cart2polar_2pi(x, y):
    """convert cartesian coordinates to polar (uses non-standard theta range!)

    NON-STANDARD RANGE! Maps to ``(0, 2*pi)`` rather than usual ``(-pi, +pi)``
    """
    r, t = np.hypot(x, y), np.arctan2(y, x)
    t += np.where(t < 0., 2 * np.pi, 0)
    return r, t 

Example 21

def xy2angles(x,y):
    elout = 90-np.hypot(x,y)
    azout = np.degrees(np.arctan2(x,y))
    return (azout,elout) 

Example 22

def parse(fname):
    """
    Parse FGM format data *fname*. Return :class:`DataFrame`
    containing all information found in the file.

    The FGM file format is used by CARISMA to store data and is
    described here:
    http://www.carisma.ca/carisma-data/fgm-data-format.
    """
    with open(fname) as fid:
        siteid, lat, lon, date, pos_format, units, sample_rate = fid.next().split()
        dt = []
        x = []
        y = []
        z = []
        flag = []
        for line in fid:
            cols = line.split()
            dt.append(datetime.strptime(cols[0], '%Y%m%d%H%M%S'))
            x.append(float(cols[1]))
            y.append(float(cols[2]))
            z.append(float(cols[3]))
            if cols[4] == '.':
                flag.append(False)
            elif cols[4] == 'x':
                flag.append(True)
            else:
                raise ValueError('unknown flag value {} encountered in {}'.format(cols[4], fname))
        f = NP.hypot(x, NP.hypot(y, z))
        df = PD.DataFrame(data={'x': x, 'y': y, 'z': z, 'f': f, 'flag': flag},
                          index=dt)
        df.siteid = siteid
        df.lat = float(lat)
        df.lon = float(lon)
        df.date = datetime.strptime(date, '%Y%m%d')
        df.pos_format = pos_format
        df.units = units
        df.sample_rate = sample_rate
    return df 

Example 23

def cart2sph(x, y, z):
    '''Converts cartesian coordinates x, y, z to spherical coordinates az, el, r.'''
    hxy = _np.hypot(x, y)
    r = _np.hypot(hxy, z)
    el = _np.arctan2(z, hxy)
    az = _np.arctan2(y, x)
    return az, el, r 

Example 24

def test_NotImplemented_not_returned(self):
        # See gh-5964 and gh-2091. Some of these functions are not operator
        # related and were fixed for other reasons in the past.
        binary_funcs = [
            np.power, np.add, np.subtract, np.multiply, np.divide,
            np.true_divide, np.floor_divide, np.bitwise_and, np.bitwise_or,
            np.bitwise_xor, np.left_shift, np.right_shift, np.fmax,
            np.fmin, np.fmod, np.hypot, np.logaddexp, np.logaddexp2,
            np.logical_and, np.logical_or, np.logical_xor, np.maximum,
            np.minimum, np.mod
            ]

        # These functions still return NotImplemented. Will be fixed in
        # future.
        # bad = [np.greater, np.greater_equal, np.less, np.less_equal, np.not_equal]

        a = np.array('1')
        b = 1
        for f in binary_funcs:
            assert_raises(TypeError, f, a, b) 

Example 25

def _vh_lines(lines, ctrs=None, lengths=None, vecs=None, angle_lo=20, angle_hi=160,
              ransac_options=RANSAC_OPTIONS):
    assert len(lines) > 0, "We need some lines to start with!"
    ctrs = ctrs if ctrs is not None else lines.mean(1)
    vecs = vecs if vecs is not None else lines[:, 1, :] - lines[:, 0, :]
    lengths = lengths if lengths is not None else np.hypot(vecs[:, 0], vecs[:, 1])

    return (_vlines(lines, ctrs, lengths, vecs, angle_lo, angle_hi, ransac_options=RANSAC_OPTIONS),
            _hlines(lines, ctrs, lengths, vecs, angle_lo, angle_hi, ransac_options=RANSAC_OPTIONS)) 

Example 26

def distance_between(x1, y1, x2, y2):
    """
    Calculates the distance between 2 points.
    """
    return np.hypot(x1 - x2, y1 - y2) 

Example 27

def make_dist_mat(xy1, xy2, longlat=True):
    """
    Return a distance matrix between two set of coordinates.
    Use geometric distance (default) or haversine distance (if longlat=True).

    Parameters
    ----------
    xy1 : numpy.array
        The first set of coordinates as [(x, y), (x, y), (x, y)].
    xy2 : numpy.array
        The second set of coordinates as [(x, y), (x, y), (x, y)].
    longlat : boolean, optionnal
        Whether the coordinates are in geographic (longitude/latitude) format
        or not (default: False)

    Returns
    -------
    mat_dist : numpy.array
        The distance matrix between xy1 and xy2
    """
    if longlat:
        return hav_dist(xy1[:, None], xy2)
    else:
        d0 = np.subtract.outer(xy1[:, 0], xy2[:, 0])
        d1 = np.subtract.outer(xy1[:, 1], xy2[:, 1])
        return np.hypot(d0, d1) 

Example 28

def edgedetect(channel):
    sobelx = cv2.Sobel(channel, cv2.CV_16S, 1, 0, ksize=3)
    sobely = cv2.Sobel(channel, cv2.CV_16S, 0, 1, ksize=3)
    sobel = np.hypot(sobelx, sobely)
    sobel[sobel > 255] = 255

    return sobel 

Example 29

def get_pixelist_interp_iq( qp, iq, ring_mask, center):
    
    qind, pixelist = roi.extract_label_indices(  ring_mask  )
    #pixely = pixelist%FD.md['nrows'] -center[1]  
    #pixelx = pixelist//FD.md['nrows'] - center[0]
    
    pixely = pixelist%ring_mask.shape[1] -center[1]  
    pixelx = pixelist//ring_mask.shape[1]  - center[0]
    
    r= np.hypot(pixelx, pixely)              #leave as float.
    #r= np.int_( np.hypot(pixelx, pixely)  +0.5  ) + 0.5  
    return np.interp( r, qp, iq ) 

Example 30

def transform(cls, value):
        value = np.asarray(value, dtype=np.float64)
        assert value.shape[-1] == 2
        result = np.empty_like(value)
        result[...,0] = np.hypot(value[...,1], value[...,0])
        result[...,1] = np.arctan2(value[...,1], value[...,0]) % (2 * np.pi)
        return result 

Example 31

def transform(cls, value):
        value = np.asarray(value, dtype=np.float64)
        result = np.empty_like(value)
        x, y, z = value.T
        xy = np.hypot(x, y)
        result[..., 0] = np.hypot(xy, z)
        result[..., 1] = np.arctan2(xy, z) % (2 * np.pi)
        result[..., 2] = np.arctan2(y, x) % (2 * np.pi)
        return result 

Example 32

def transform(cls, value):
        value = np.asarray(value, dtype=np.float64)
        result = np.empty_like(value)
        x, y, z = value.T
        result[..., 0] = np.hypot(x, y)                     # tho
        result[..., 1] = np.arctan2(y, x) % (2 * np.pi)     # phi
        result[..., 2] = z
        return result 

Example 33

def ecef2geodetic(x, y, z):
    """http://www.astro.uni.torun.pl/~kb/Papers/geod/Geod-BG.htm

    This algorithm provides a converging solution to the latitude equation in
    terms of the parametric or reduced latitude form (v).
    This algorithm provides a uniform solution over all latitudes as it does
    not involve division by cos(phi) or sin(phi).
    """
    ell = {}
    ell['a'] = 6378137.
    ell['f'] = 1. / 298.2572235630
    ell['b'] = ell['a'] * (1 - ell['f'])

    ea = ell['a']
    eb = ell['b']
    rad = np.hypot(x, y)
    # Constant required for Latitude equation
    rho = np.arctan2(eb * z, ea * rad)
    #Constant required for latitude equation
    c = (ea**2 - eb**2) / np.hypot(ea * rad, eb * z)
    # Starter for the Newtons Iteration Method
    vnew = np.arctan2(ea * z, eb * rad)
    # Initializing the parametric latitude
    v = 0
    count = 0
    while (v != vnew).any() and count < 5:
        v = vnew.copy()
        # Newtons Method for computing iterations
        vnew = v - ((2 * np.sin(v - rho) - c * np.sin(2 * v)) /
                    (2 * (np.cos(v - rho) - c * np.cos(2 * v))))
        count += 1

    # Computing latitude from the root of the latitude equation
    lat = np.arctan2(ea * np.tan(vnew), eb)
    lon = np.arctan2(y, x)
    alt = ((rad - ea * np.cos(vnew)) * np.cos(lat) +
           (z - eb * np.sin(vnew)) * np.sin(lat))

    return lat, lon, alt 

Example 34

def test_NotImplemented_not_returned(self):
        # See gh-5964 and gh-2091. Some of these functions are not operator
        # related and were fixed for other reasons in the past.
        binary_funcs = [
            np.power, np.add, np.subtract, np.multiply, np.divide,
            np.true_divide, np.floor_divide, np.bitwise_and, np.bitwise_or,
            np.bitwise_xor, np.left_shift, np.right_shift, np.fmax,
            np.fmin, np.fmod, np.hypot, np.logaddexp, np.logaddexp2,
            np.logical_and, np.logical_or, np.logical_xor, np.maximum,
            np.minimum, np.mod
            ]

        # These functions still return NotImplemented. Will be fixed in
        # future.
        # bad = [np.greater, np.greater_equal, np.less, np.less_equal, np.not_equal]

        a = np.array('1')
        b = 1
        for f in binary_funcs:
            assert_raises(TypeError, f, a, b) 

Example 35

def _cart2polar(x, y, center):
    xx = x - center[0]
    yy = y - center[1]
    phi = np.arctan2(yy, xx)
    r = np.hypot(xx, yy)
    return r, phi 

Example 36

def _grid(self):
        tsne_norm = self.tsne_vectors[:, ] / float(self.ratio)
        used_imgs = np.equal(self.tsne_vectors[:, 0], None)
        image = np.ones((self.output_img_size, self.output_img_size, 3)) * self.background_color
        for x in tqdm(range(self.ratio)):
            x0 = x * self.each_img_size
            x05 = (x + 0.5) * self.each_img_size
            for y in range(self.ratio):
                y0 = y * self.each_img_size
                y05 = (y + 0.5) * self.each_img_size
                tmp_tsne = tsne_norm - [x05, y05]
                tmp_tsne[used_imgs] = 99999  # don't use the same img twice
                tsne_dist = np.hypot(tmp_tsne[:, 0], tmp_tsne[:, 1])
                min_index = np.argmin(tsne_dist)
                used_imgs[min_index] = True
                img_path = self.image_list[min_index]
                small_img, x1, y1, dx, dy = get_image(img_path, self.each_img_size)
                if small_img is None:
                    y -= 1
                    continue
                if x < 1 and all(side < self.each_img_size for side in [x1, y1]):
                    self.each_img_size = min(x1, y1)
                    dx = int(ceil(x1 / 2))
                    dy = int(ceil(y1 / 2))
                image[x0 + dx:x0 + dx + x1, y0 + dy:y0 + dy + y1] = small_img

        return image 

Example 37

def on_button(self, event):
        # only consider events from the lines Axes
        if event.inaxes is not self.ln.axes:
            return

        # if not the left mouse button or a modifier key
        # is held down, bail
        if event.button != 1 or event.key not in (None, 'shift'):
            print('key+button: {!r}+{!r}'.format(event.key, event.button))
            return

        if event.key == 'shift':
            # compute the distance to each point *in data space*
            d = np.hypot(np.asarray(self.xdata) - event.xdata,
                         np.asarray(self.ydata) - event.ydata)
            # find the closest point
            ix = np.argmin(d)
            # remove that data point
            del self.xdata[ix]
            del self.ydata[ix]
        else:
            # get the event location in data-space
            # and add to internal data list
            self.xdata.append(event.xdata)
            self.ydata.append(event.ydata)
        # update the line
        self._update_line() 

Example 38

def point_distance(p1, p2):
    dist_diff = p1 - p2
    return np.hypot(*dist_diff) 

Example 39

def collide_line_ball(line, ball):
    displacement_to_second_point = line.line[1] - line.line[0]
    normalised_point_diff_vector = displacement_to_second_point / \
                                   np.hypot(*(displacement_to_second_point))
    perpendicular_vector = np.array(
        [-normalised_point_diff_vector[1], normalised_point_diff_vector[0]])
    ball.velocity -= 2 * np.dot(perpendicular_vector,
                                ball.velocity) * perpendicular_vector 

Example 40

def __init__(self, line):
        self.line = np.array(line)
        self.middle = (self.line[0] + self.line[1]) / 2
        self.size = np.round(np.abs(self.line[0] - self.line[1]))
        self.length = np.hypot(*self.size)
        if np.count_nonzero(self.size) != 2:
            # line is perpendicular to y or x axis
            if self.size[0] == 0:
                self.size[0] += 1
            else:
                self.size[1] += 1


# draws the yellow part of the table 

Example 41

def ball_hit(self):
        new_velocity = -(self.displacement - config.ball_radius - config.cue_safe_displacement) * \
                       config.cue_hit_power * np.array([math.sin(self.angle), math.cos(self.angle)])
        change_in_disp = np.hypot(*new_velocity) * 0.1
        while self.displacement - change_in_disp > config.ball_radius:
            self.displacement -= change_in_disp
            self.update()
            pygame.display.flip()
        self.target_ball.ball.apply_force(new_velocity)
        self.displacement = config.ball_radius
        self.visible = False 

Example 42

def update(self, *args):
        if np.hypot(*self.ball.velocity) != 0:
            # updates label circle and number offset
            perpendicular_velocity = -np.cross(self.ball.velocity, [0, 0, 1])
            # angle formula is angle=((ballspeed*2)/(pi*r*2))*2
            rotation_angle = -np.hypot(
                *(self.ball.velocity)) * 2 / (config.ball_radius * np.pi)
            transformation_matrix = physics.rotation_matrix(
                perpendicular_velocity, rotation_angle)
            self.label_offset = np.matmul(
                self.label_offset, transformation_matrix)
            if self.ball_type == BallType.Striped:
                self.ball_stripe.update_stripe(transformation_matrix)
            self.update_sprite()
            self.ball.update() 

Example 43

def check_reg(fixed_img, moved_img, scale=15, norm=True, sigma=0.8, **kwargs):
        dim = list(moved_img.shape)
        resol = list(moved_img.header['pixdim'][1:4])
        # Convert 4D image to 3D or raise error
        data = convert_to_3d(moved_img)
        # Check normalization
        if norm:
            data = apply_p2_98(data)
        # Set slice axis for mosaic grid
        slice_axis, cmap = check_sliceaxis_cmap(data, kwargs)
        cmap = 'YlOrRd'
        # Set grid shape
        data, slice_grid, size = set_mosaic_fig(data, dim, resol, slice_axis, scale)
        fig, axes = BrainPlot.mosaic(fixed_img, scale=scale, norm=norm, cmap='bone', **kwargs)
        # Applying inversion
        invert = check_invert(kwargs)
        data = apply_invert(data, *invert)
        # Plot image
        for i in range(slice_grid[1] * slice_grid[2]):
            ax = axes.flat[i]
            edge = data[:, :, i]
            edge = feature.canny(edge, sigma=sigma)  # edge detection for second image
            # edge = ndimage.gaussian_filter(edge, 3)
            mask = np.ones(edge.shape)
            sx = ndimage.sobel(edge, axis=0, mode='constant')
            sy = ndimage.sobel(edge, axis=1, mode='constant')
            sob = np.hypot(sx, sy)
            mask[sob == False] = np.nan
            m_norm = colors.Normalize(vmin=0, vmax=1.5)
            if i < slice_grid[0] and False in np.isnan(mask.flatten()):
                ax.imshow(mask.T, origin='lower', interpolation='nearest', cmap=cmap, norm=m_norm, alpha=0.8)
            else:
                ax.imshow(np.zeros((dim[0], dim[1])).T, origin='lower', interpolation='nearest', cmap='bone')
            ax.set_axis_off()
        fig.set_facecolor('black')
        if notebook_env:
            display(fig)
        return fig, axes 

Example 44

def distance(vertex1, vertex2):
        x, y = vertex1 - vertex2
        return np.hypot(x, y) 

Example 45

def angsep(lon1,lat1,lon2,lat2):
    """
    Angular separation (deg) between two sky coordinates.
    Borrowed from astropy (www.astropy.org)

    Notes
    -----
    The angular separation is calculated using the Vincenty formula [1],
    which is slighly more complex and computationally expensive than
    some alternatives, but is stable at at all distances, including the
    poles and antipodes.

    [1] http://en.wikipedia.org/wiki/Great-circle_distance
    """
    lon1,lat1 = numpy.radians([lon1,lat1])
    lon2,lat2 = numpy.radians([lon2,lat2])
    
    sdlon = numpy.sin(lon2 - lon1)
    cdlon = numpy.cos(lon2 - lon1)
    slat1 = numpy.sin(lat1)
    slat2 = numpy.sin(lat2)
    clat1 = numpy.cos(lat1)
    clat2 = numpy.cos(lat2)

    num1 = clat2 * sdlon
    num2 = clat1 * slat2 - slat1 * clat2 * cdlon
    denominator = slat1 * slat2 + clat1 * clat2 * cdlon

    return numpy.degrees(numpy.arctan2(numpy.hypot(num1,num2), denominator))

############################################################

# ADW: Reduce numpy array operations for speed 

Example 46

def generate_pattern(self, reference, size):
        """Extracts a pattern from the reference image.

        Firstly, the image is transformed to grayscale. A random square from image
        is picked. A pattern is extracted using the edge detection (Sobel's filter).

        :param reference: Reference image.
        :param int size: Size of a pattern (length of its edge).
        :returns:
            A pattern extracted from the image.
        """
        # Import image from reference and convert it to grayscale.
        img = mpimg.imread(reference)
        gray = np.mean(img, -1)

        # Normalization of data to decimal (0.0 - 1.0) representation
        if gray.max() > 1.0:
            gray /= 255.0

        # Extract a random slice with the pixel size given as parameter
        slice_center_x = random.randint(0, len(img[0]) - size - 1)
        slice_center_y = random.randint(0, len(img) - size - 1)

        slice = gray[slice_center_y: slice_center_y + size, slice_center_x: slice_center_x + size]

        # # Detects border to generate the pattern of the brush
        dx = ndimage.sobel(slice, 0)  # horizontal derivative
        dy = ndimage.sobel(slice, 1)  # vertical derivative
        pattern = np.hypot(dx, dy)    # grayscale slice with border detection

        # Normalize pattern
        if pattern.max() > 1.0:
            return pattern / pattern.max()

        return pattern



    # Test 

Example 47

def _deproj(x, y, inc, pa, polar_out=True, polar_in=True, fourier_plan=False):
    if polar_in:
        y, x = x*np.cos(y), x*np.sin(y)
    else:
        y, x = x, y
    if fourier_plan:
        X = (x*np.cos(pa) + y*np.sin(pa))*np.cos(inc)
        Y = y*np.cos(pa) - x*np.sin(pa)
    else:
        X = x*np.cos(pa) + y*np.sin(pa)
        Y = (y*np.cos(pa) - x*np.sin(pa))/np.cos(inc)
    x, y = np.hypot(Y, X), (np.arctan2(X, Y)-pa) % (2*np.pi)
    if not polar_out:
        return x*np.cos(y), x*np.sin(y)
    return x, y 

Example 48

def psf(lOverd, masperpx):
    """
    lOverd in radian
    masperpx in mas per px
    """
    nbpts = (lOverd*4/(masperpx*MAS2RAD))//2*2+1
    y, x = np.meshgrid(np.linspace(-1, 1, nbpts), np.linspace(-1, 1, nbpts))
    psf = airy(np.hypot(y, x)*2*lOverd+1e-10, 1/lOverd)**2
    psf /= psf.sum()
    return psf 

Example 49

def distance_matrix(x0, y0, x1, y1):
    '''Distance matrix for IDW calculation'''
    obs = np.vstack((x0, y0)).T
    interp = np.vstack((x1, y1)).T

    # Make a distance matrix between pairwise observations
    # Note: from <http://stackoverflow.com/questions/1871536>
    d0 = np.subtract.outer(obs[:,0], interp[:,0])
    d1 = np.subtract.outer(obs[:,1], interp[:,1])
    return np.hypot(d0, d1) 

Example 50

def length(v):
    r"""Length of an vector

    .. math::
       \|\mathbf{v}\|

    Args:
        v (numpy.ndarray): 2D vector

    Returns:
        float|numpy.ndarray: Length of the vector in [0, infty)
    """
    return np.hypot(v[..., 0], v[..., 1]) 
点赞

发表评论

电子邮件地址不会被公开。 必填项已用*标注